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
Python
UTF-8
86
3.140625
3
[]
no_license
#!/usr/bin/python #range function listofevennum=range(0,400,2) print listofevennum
Python
UTF-8
2,882
3.265625
3
[]
no_license
import random """ # randomContractions.py Implementation of Karger's algorithm. http://en.wikipedia.org/wiki/Karger's_algorithm """ def importGraph(filename = 'kargerAdj.txt'): """Imports pairs of endpoints into an adjancey list graph representation. Keep track of both edges and vertices.""" f = open(filename) adjEdges = [] adjVertix = [] for line in f: points = line.split() v = Vertix(points.pop(0)) for item in points: e = Edge(v.n, item) adjEdges.append(e) v.addEdge(e) adjVertix.append(v) # remove redundancies: n = len(adjEdges) adjEdges.sort(key=lambda x: x.ends[1]) adjEdges.sort(key=lambda x: x.ends[0]) i = 0 while i < n - 1: if adjEdges[i].ends == adjEdges[i+1].ends: adjEdges.pop(i+1) n = len(adjEdges) else: i += 1 return (adjEdges, adjVertix) class Vertix: def __init__(self, n): self.n = int(n) self.edges = [] def addEdge(self, v): self.edges.append(v) class Edge: def __init__(self, end1, end2): end1 = int(end1) end2 = int(end2) if end1 < end2: self.ends = [end1, end2] else: # end1 > end2: self.ends = [end2, end1] def hasEndPoint(self, endTest): if endTest in self.ends: return True else: return False def isSelfLoop(self): if self.ends[0] == self.ends[1]: return True else: return False def replaceEndPoint(self, find, replace): for i in range(len(self.ends)): if self.ends[i] == find: self.ends[i] = replace def findmincut(adj): (adje, adjv) = adj while len(adjv) > 2: # pick a remaining edge randomly r = random.randint(0, len(adje) - 1) # contract u and v to a single vertex contractEdge = adje[r] for i in range(len(adjv)): if adjv[i].n == contractEdge.ends[0]: headIndex = i if adjv[i].n == contractEdge.ends[1]: tailIndex = i find = adjv[headIndex].n replace = adjv[tailIndex].n adjv[tailIndex].edges = adjv[tailIndex].edges + adjv[headIndex].edges adjv.pop(headIndex) # replace vertix values in edge list for i in range(len(adje)): adje[i].replaceEndPoint(find, replace) # remove self-loops new_adje = [] for e in adje: if not e.isSelfLoop(): new_adje.append(e) adje = new_adje # return cut return len(adje) if __name__ == '__main__': adj = importGraph() print findmincut(adj)
Markdown
UTF-8
541
2.609375
3
[]
no_license
# Text-Mining-Analytics-Using-R **Data used for this project:** News group data comes along with the 'tm' Package. **Create Document Term matrix:** Create a Corpus dataset by grouping all the data which you want to classify. **Data Preprocessing:** Clean the data by removing punctuations or any extra characters. **Split Document Term matrix:** Into Train and Test Dataset. **Create Tags:** To Classify Data **Classify text:** Using KNN() function from the Library(Class) **Display the Results:** Percentage of TRUE classification
Java
UTF-8
10,909
2.28125
2
[]
no_license
package ufm.universalfinancemanager.addeditbudget; import android.support.annotation.Nullable; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.inject.Inject; import ufm.universalfinancemanager.db.TransactionDataSource; import ufm.universalfinancemanager.db.UserDataSource; import ufm.universalfinancemanager.db.UserRepository; import ufm.universalfinancemanager.db.entity.Category; import ufm.universalfinancemanager.db.entity.Transaction; import ufm.universalfinancemanager.support.Flow; import ufm.universalfinancemanager.support.atomic.Budget; import ufm.universalfinancemanager.support.atomic.User; import ufm.universalfinancemanager.util.EspressoIdlingResource; /** * Created by Areeba on 2/23/2018. */ public class AddEditBudgetPresenter implements AddEditBudgetContract.Presenter{ private User mUser; @Nullable private AddEditBudgetContract.View mAddEditBudgetview = null; private final UserRepository mUserRepository; private Category category1; private String cat; //private Date d1; //private Date d2; final List<Category> expense = new ArrayList<>(); final List<Transaction> transactions = new ArrayList<>(); //private final String mBudgetId; private String budgetName; @Inject AddEditBudgetPresenter(User user, UserRepository transactionRepository){//, @Nullable String id) { mUser = user; mUserRepository = transactionRepository; //mBudgetId = id; } @Override public void saveBudget(String name, String category, double amount, Date startdate, Date enddate) { this.cat = category; for(Budget b : mUser.getBudgets()) { expense.add(b.getCategory()); } loadTransactions(startdate, enddate, category); double sum = 0.0; for (Transaction t : this.transactions) { sum += t.getAmount(); } Budget budget = new Budget(name, category, amount, sum, startdate, enddate); mUser.addBudget(budget); if (mAddEditBudgetview != null) { mAddEditBudgetview.showMessage("Budget successfully saved."); mAddEditBudgetview.showLastActivity(true); } //}catch(RuntimeException e) { // } //} if (mAddEditBudgetview != null) mAddEditBudgetview.showLastActivity(true); } @Override public void loadTransactions(final Date startdate, final Date enddate, final String category) { //Performing database/network call, forbid ui test activity until it's done EspressoIdlingResource.increment(); long currentDate = startdate.getTime(); long pastDate = enddate.getTime(); mUserRepository.getTransactionsInDateRange(currentDate, pastDate, new UserDataSource.LoadTransactionsCallback() { @Override public void onTransactionsLoaded(List<Transaction> transactions) { // This callback may be called twice, once for the cache and once for loading // the data from the server API, so we check before decrementing, otherwise // it throws "Counter has been corrupted!" exception. if (!EspressoIdlingResource.getIdlingResource().isIdleNow()) { EspressoIdlingResource.decrement(); // Set app as idle. } processTransactions(transactions); // processCategory(category); } @Override public void onDataNotAvailable() { //display loading transactions error message } }); /*mTransactionRepository.getTransactions(currentDate, pastDate, new TransactionDataSource.LoadTransactionsCallback() { @Override public void onTransactionsLoaded(List<Transaction> transactions) { // This callback may be called twice, once for the cache and once for loading // the data from the server API, so we check before decrementing, otherwise // it throws "Counter has been corrupted!" exception. if (!EspressoIdlingResource.getIdlingResource().isIdleNow()) { EspressoIdlingResource.decrement(); // Set app as idle. } processTransactions(transactions, name, category,amount,startdate, enddate); } @Override public void onDataNotAvailable() { //display loading transactions error message } });*/ } private void processTransactions(List<Transaction> transactions) { for(Transaction t: transactions) { if(t.getCategory().compareTo(this.cat) == 0 && t.getFlow().compareTo(Flow.OUTCOME) == 0) { this.transactions.add(t); } } } private void processCategory(String category1) { mUserRepository.getCategory(category1, new UserDataSource.GetCategoryCallback() { @Override public void onCategoryLoaded(Category category) { saveCategory(category); } @Override public void onDataNotAvailable() { } }); } private void saveCategory(Category category) { this.category1 = category; } @Override public void getUpdatedCategories(Flow flow) { // mAddEditBudgetview.updateCategories(mUser.getIncomeCategories()); } public void processTransactions(List<Transaction> transactions, String name, Category categoryName, double amount, Date startdate, Date enddate) { List<Transaction> budgetTransactionList = new ArrayList<>(); double sum = 0.0; if(isNewBudget()) { if (name.length() > 25) { if (mAddEditBudgetview != null) mAddEditBudgetview.showMessage("Budget name too long!"); } else { try { for (Transaction t : transactions) { if ((t.getCategory() == categoryName.toString()) && t.getFlow() == (Flow.OUTCOME)) { // or its greater or close to the end date { budgetTransactionList.add(t); sum = sum + t.getAmount(); } } Budget budget = new Budget(name, categoryName, amount, sum, startdate, enddate); mUser.addBudget(budget); if (mAddEditBudgetview != null) { mAddEditBudgetview.showMessage("Budget successfully saved."); mAddEditBudgetview.showLastActivity(true); } } catch (RuntimeException e) { if (mAddEditBudgetview != null) mAddEditBudgetview.showMessage("Error saving budget, Budget with that name already exists!"); return; } if (mAddEditBudgetview != null) mAddEditBudgetview.showLastActivity(true); } } else { if (name.length() > 25) { if (mAddEditBudgetview != null) mAddEditBudgetview.showMessage("Budget name too long!"); } else { try { for (Transaction t : transactions) { if ((t.getCategory() == categoryName.toString()) && t.getFlow() == (Flow.OUTCOME)) { // or its greater or close to the end date { budgetTransactionList.add(t); sum = sum + t.getAmount(); } } Budget budget = new Budget(name, categoryName, amount, sum, startdate, enddate); mUser.addBudget(budget); if (mAddEditBudgetview != null) { mAddEditBudgetview.showMessage("Budget successfully saved."); mAddEditBudgetview.showLastActivity(true); // mAddEditBudgetview.populateExistingFields(budget.getName(), budget.getCategory(), budget.getAmount(), budget.getCurrentValue(), budget.getStartDate(), budget.getEndDate()); } } catch (RuntimeException e) { if (mAddEditBudgetview != null) mAddEditBudgetview.showMessage("Error saving budget, Budget with that name already exists!"); return; } if (mAddEditBudgetview != null) mAddEditBudgetview.showLastActivity(true); } } } /* @Override public void saveBudget(String name, Category category, double amount) { if(name.length() > 25) { if (mAddEditBudgetview != null) mAddEditBudgetview.showMessage("Budget name too long!"); } else { try{ mUser.addBudget(new Budget(name, category, amount)); if(mAddEditBudgetview != null) mAddEditBudgetview.showMessage("Budget successfully saved."); } catch(RuntimeException e){ if(mAddEditBudgetview != null) mAddEditBudgetview.showMessage("Error saving budget, Budget with that name already exists!"); return; } if(mAddEditBudgetview != null) mAddEditBudgetview.showLastActivity(true); } }*/ @Override public void deleteBudget() { mUser.deleteBudget(budgetName); } @Override public void takeView(AddEditBudgetContract.View view) { mAddEditBudgetview = view; mAddEditBudgetview.updateCategories(mUser.getExpenseCategories()); /* mUserRepository.getCategories(new UserDataSource.LoadCategoriesCallback() { @Override public void onCategoriesLoaded(List<Category> categories) { for(Category c: categories) { if(c.getFlow() == Flow.INCOME); expense.add(c); } } @Override public void onDataNotAvailable() { } }); */ //mAddEditBudgetview.updateCategories(expense); if(view == null) return; if(isNewBudget()) { mAddEditBudgetview.setupFragmentContent(false); } else{ mAddEditBudgetview.setupFragmentContent(true); } } @Override public void dropView() { mAddEditBudgetview = null; } public boolean isNewBudget() { // return mBudgetId == null; return true; } }
C++
UTF-8
417
2.5625
3
[]
no_license
#include "../include/movop.h" #include "iostream" void MovOp::Apply(Memory &mem) { // mem.SetReg(mem.registers[op1_], op2_->Get(mem)); op1_->Set(mem, op2_->Get(mem)); mem.Push(op2_->Get(mem)); } MovOp::~MovOp() { std::cout << "delete - op1_ " << op1_ << std::endl; delete op1_; delete op2_; std::cout << "~MovOp" << std::endl; } // нужно так? // Memory& mem; // mutablevalue.Set(mem, value);
PHP
UTF-8
9,394
2.828125
3
[]
no_license
<?php namespace DkanTools\Command; use DkanTools\Util\Util; /** * This is project's console commands configuration for Robo task runner. * * @see http://robo.li/ */ class RestoreCommands extends \Robo\Tasks { /** * Restore files and database. * * A command that creates a DKAN site from a db dump and files. The restore * command supports files compressed in zip, .gz and .tar.gz formats, and * will accept URLs using the http, https or s3 protocols. * * For files, dktl expects that the archive contain a files/ dir either in * the root of the archive or under a dir with the same basename as the * archive. (For instance, files in mysite.tar.gz could be located either in * /mysite/files/ or just /files/). * * If your site uses private files, a second dir called private/ may be * included at the same level as files/. These files will be copied to a * new "/private" dir created in your project root. * * It is recommended that you set the options for this in command in * dktl.yml (see README for more information). * * @todo Give feedback when no options provided. * * @param array $opts * @option $db_url * The database archive URL. sql and sql.gz files are supported. * @option $files_url * A url to the site files archive. zip, gz, and tar.gz files are supported. */ public function restore($opts = ['db_url' => null, 'files_url' => null]) { if ($opts['db_url']) { $this->restoreDb($opts['db_url']); } if ($opts['files_url']) { $this->restoreFiles($opts['files_url']); } } /** * Restore the database from a backup. * * @param string $file * URL to remote backup or a filename that lives in the /backups directory. */ public function restoreDb($file = null) { // If no file argument provided, check out the backups dir. if (!$file) { $filepath = $this->getDbBackupPath(); } elseif (filter_var($file, FILTER_VALIDATE_URL)) { // If provided a URL, get it with getFile(). $filepath = $this->getFile($file); $tempNeedsCleanup = true; } elseif (!file_exists('backups') || !file_exists("backups/{$file}")) { // If not a URL check for existence of file in /backups. throw new \Exception("{$file} backup could not be found."); } else { $filepath = realpath("backups/$file"); } $info = pathinfo($filepath); $s = $this->taskExecStack()->stopOnFail()->dir(Util::getProjectDocroot()); $s->exec('drush -y sql-drop'); if ($info['extension'] == "gz") { $s->exec("zcat $filepath | drush sqlc"); } else { $s->exec("drush sqlc < $filepath"); } $result = $s->run(); if ($result->getExitCode() == 0) { $this->io()->success('Database restored.'); } else { $this->io()->error('Issues restoring the database.'); } Util::cleanupTmp(); return $result; } /** * Ask for which backup to use from the project /backups dir */ private function getDbBackupPath() { if (file_exists('backups')) { $backups = array_values(array_diff(scandir('backups'), ['.', '..'])); if (empty($backups)) { throw new \Exception('No backup files available.'); } elseif (count($backups) === 1) { $filename = current($backups); $this->io()->note("No filename provided; using $filename."); } if (!empty($backups)) { $filename = $this->io()->choice('Choose backup file', $backups); } return realpath("backups/$filename"); } else { throw new \Exception("No backup files available."); } } /** * Restore a files archive to appropriate site directories. * * @param string $files_url Files URL to restore. * @see self::dkanRestore() For full documentation on URL params. */ public function restoreFiles(string $files_url) { Util::prepareTmp(); $filePath = $this->getFile($files_url); $projectDirectory = Util::getProjectDirectory(); $parentDir = $this->restoreFilesExtract($filePath); if (is_dir("{$parentDir}/files")) { $this->restoreFilesCopy("{$parentDir}/files", "{$projectDirectory}/src/site/files"); $this->_exec("chmod -R 777 {$projectDirectory}/src/site/files"); } if (is_dir("{$parentDir}/private")) { $this->restoreFilesCopy("{$parentDir}/private", "{$projectDirectory}/private"); } if (!is_dir("{$parentDir}/files") && !is_dir("{$parentDir}/private")) { $this->io->warning('No files found'); return false; } Util::cleanupTmp(); } /** * Extract a zip or tar.gz archive in the tmp dir. * * @param string $filePath The path to the archive. * * @return string The directory to which the archive was extracted. */ private function restoreFilesExtract(string $filePath) { $tmpPath = Util::TMP_DIR; $info = pathinfo($filePath); $extension = $info['extension']; if ($extension == "zip") { $taskUnzip = $this->taskExec("unzip $filePath -d {$tmpPath}"); $parentDir = substr($filePath, 0, -4); } elseif ($extension == "gz") { if (substr_count($filePath, ".tar") > 0) { $taskUnzip = $this->taskExec("tar -xvzf {$filePath}")->dir($tmpPath); $parentDir = substr($filePath, 0, -7); } else { $taskUnzip = $this->taskExec("gunzip {$filePath}"); $parentDir = substr($filePath, 0, -3); } } else { throw new \Exception('Could not extract file.'); } $result = $taskUnzip->run(); if (!is_dir($parentDir)) { $parentDir = dirname($parentDir); } if (is_dir($parentDir) && $result->getExitCode() == 0) { return $parentDir; } throw new \Exception('Extraction failed.'); } private function restoreFilesCopy(string $source, string $destination) { if (is_dir($source)) { $this->say('Copying files'); $result = $this->taskCopyDir([$source => $destination])->run(); if ($result->getExitCode() == 0) { $this->io()->success("Files restored to $destination."); } else { throw new \Exception("Failed restoring files to $destination."); } return $result; } throw new \Exception("Source dir $source not found."); } private function getFile($url) { $tmp_dir_path = Util::TMP_DIR; if (substr_count($url, "http://") > 0 || substr_count($url, "https://")) { $info = pathinfo($url); $filename = $info['basename']; $approach = "wget -O {$tmp_dir_path}/{$filename} {$url}"; } elseif (substr_count($url, "s3://")) { $parser = new \Aws\S3\S3UriParser(); $info = $parser->parse($url); $filename = $info['key']; $approach = "aws s3 cp {$url} {$tmp_dir_path}/"; } else { $this->io()->error("Unsupported file protocol."); return; } $result = $this->taskExec($approach)->run(); if ($result->getExitCode() == 0) { $this->io()->success("Got the file from {$url}."); return "$tmp_dir_path/$filename"; } else { $this->io()->error("Issues getting the file from {$url}."); throw new \Exception("Error retrieving file."); } } /** * Create a database dump excluding devel and datastore tables. * * Run drush command on $alias to create a database dump excluding tables * related to devel and datastore. * * @param String $alias Drush alias of the site we want the db from. */ public function restoreGrabDatabase($alias) { // Tables for which we want the structure and not the data. $structure_tables_common = array( 'accesslog', 'batch', 'cache', 'cache_*', '*_cache', 'ctools_views_cache', 'ctools_object_cache', 'flood', 'history', 'queue', 'search_*', 'semaphore', 'sessions', 'watchdog' ); $structure_tables_devel = array('devel_queries', 'devel_times'); $structure_tables_webform = array('webform_submitted_data'); $structure_tables = array_merge( $structure_tables_common, $structure_tables_devel, $structure_tables_webform ); $structure_tables_list = implode(', ', $structure_tables); // Tables to be completely skipped. $skip_tables = array('dkan_datastore_*'); $skip_tables_list = implode(', ', $skip_tables); return $this->taskExec("drush $alias sql-dump") ->option('structure-tables-list', $structure_tables_list) ->option('skip-tables-list', $skip_tables_list) ->rawArg('> excluded_tables.sql') ->run(); } }
PHP
UTF-8
9,755
2.578125
3
[ "Apache-2.0" ]
permissive
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * This class controls acount registration on the system. * * @author Al Zziwa <azziwa@gmail.com> * @version 1.1.0 * @copyright TMIS * @created 01/08/2015 */ class Register extends CI_Controller { # Constructor to set some default values at class load function __construct() { parent::__construct(); $this->load->model('_person'); } #The first step form for the registration process function step_one() { $data = filter_forwarded_data($this); # Are you just editing the step for preview? if(!empty($data['action']) && $data['action'] == 'edit_preview') { $this->native_session->set('just_preview_1', 'Y'); } else if(!empty($data['action']) && $data['action'] == 'prefill') { $this->load->model('_teacher'); $this->_teacher->populate_session($this->native_session->get('__user_id')); } # The user posted the form if(!empty($_POST)) { #Pass these details to the person object to handle with XSS filter turned on $data['result'] = $this->_person->add_profile($this->input->post(NULL, TRUE)); $data['msg'] = $data['result']['boolean'] && empty($data['result']['msg'])? "Please check your email for a confirmation code to proceed.": $data['result']['msg']; } # Prepare appropriate message and view to load if(!empty($data['result']['boolean']) && $data['result']['boolean']) { if($this->input->post('justpreview')) { $data['msg'] = "Your application had been saved. Click Submit to finish."; $this->native_session->delete('just_preview_1'); $viewToLoad = 'register/step_four'; } else { $viewToLoad = 'register/step_two'; } } else { $viewToLoad = 'register/step_one'; } $this->load->view($viewToLoad, $data); } #The second step form for the registration process function step_two() { $data = filter_forwarded_data($this); # Are you just editing the step for preview? if(!empty($data['action']) && $data['action'] == 'edit_preview') { $this->native_session->set('just_preview_2', 'Y'); } # The user posted the form if(!empty($_POST)) { if($this->native_session->get('person_id')) { #Pass these details to the person object to handle with XSS filter turned on $data['result'] = $this->_person->add_id_and_contacts($this->native_session->get('person_id'), $this->input->post(NULL, TRUE)); $data['msg'] = $data['result']['boolean'] && empty($data['result']['msg'])? "Please enter your education and qualifications to proceed.": $data['result']['msg']; } else { $data['msg'] = "ERROR: We could not verify your data. Your session may have expired. If this problem persists, please contact us."; } } # Prepare appropriate message and view to load if(!empty($data['result']['boolean']) && $data['result']['boolean']) { if($this->input->post('justpreview')) { $data['msg'] = "Your application had been saved. Click Submit to finish."; $this->native_session->delete('just_preview_2'); $viewToLoad = 'register/step_four'; } else if($this->input->post('justsaving')) { $data['msg'] = "Your application had been saved. <br>You will need to login using the details sent to your email to proceed with your application."; $viewToLoad = 'account/login'; } else { $viewToLoad = 'register/step_three'; } } else { $viewToLoad = 'register/step_two'; } $this->load->view($viewToLoad, $data); } # The third step form for the registration process function step_three() { $data = filter_forwarded_data($this); # Are you just editing the step for preview? if(!empty($data['action']) && $data['action'] == 'edit_preview') { $this->native_session->set('just_preview_3', 'Y'); } # The user posted the form if(!empty($_POST)) { if($this->native_session->get('person_id')) { # a) Are they adding an education? if(!empty($data['action']) && $data['action'] == 'add_education') { $data['response'] = $this->_person->add_education($this->native_session->get('person_id'), $this->input->post(NULL, TRUE)); $data['area'] = "education_list"; $viewToLoad = "addons/basic_addons"; } # b) Are they adding a subject? else if(!empty($data['action']) && $data['action'] == 'add_subject') { $data['response'] = $this->_person->add_subject_taught($this->native_session->get('person_id'), $this->input->post(NULL, TRUE)); $data['area'] = "subject_list"; $viewToLoad = "addons/basic_addons"; } # c) Are they adding a document? else if(!empty($data['action']) && $data['action'] == 'add_document') { # Process the document addition if one has been successfully uploaded if(!empty($_FILES['documenturl__fileurl']) && file_exists($_FILES['documenturl__fileurl']['tmp_name'])) { $this->load->model('_document'); $upload = $this->_document->upload($_FILES['documenturl__fileurl'], array('type'=>'document')); $_POST['documenturl__fileurl'] = $upload['file']; } $data['response'] = $this->_person->add_document($this->native_session->get('person_id'), $this->input->post(NULL, TRUE)); $data['area'] = "document_list"; $viewToLoad = "addons/basic_addons"; } # d) Are they submitting the entire form to save the data? else if($this->native_session->get('education_list') && $this->native_session->get('subject_list')) { #Pass these details to the person object to handle with XSS filter turned on $data['result'] = $this->_person->add_education_and_qualifications($this->native_session->get('person_id'), $this->input->post(NULL, TRUE)); $data['msg'] = $data['result']['boolean'] && empty($data['result']['msg'])? "Please review your details and submit.": $data['result']['msg']; } # d) Has the user submitted an incomplete form? else { $data['result']['boolean'] = false; $data['msg'] = "WARNING: You need to provide both the education and subjects studied to continue."; } } else { $data['msg'] = "ERROR: We could not verify your data. Your session may have expired. If this problem persists, please contact us."; } } if(!empty($data['result']['boolean']) && $data['result']['boolean']) { if($this->input->post('justpreview')) { $data['msg'] = "Your application has been saved. Click Submit to finish."; $this->native_session->delete('just_preview_3'); $viewToLoad = 'register/step_four'; } else if($this->input->post('justsaving')) { $data['msg'] = "Your application had been saved. <br>You will need to login using the details sent to your email to proceed with your application."; $viewToLoad = 'account/login'; } else { $viewToLoad = 'register/step_four'; } } $viewToLoad = !empty($viewToLoad)? $viewToLoad: 'register/step_three'; $this->load->view($viewToLoad, $data); } # Function to edit a registration list item function edit_list_item() { $data = filter_forwarded_data($this); # Populate the edit form if the necessary data is available if(!empty($data['type']) && !empty($data['item_id']) && $this->native_session->get($data['type'].'_list')) { $this->native_session->set('edit_step_3_'.$data['type'], 'Y'); $data['details'] = get_row_from_list($this->native_session->get($data['type'].'_list'), $data['type'].'_id', $data['item_id']); $data['details']['item_id'] = $data['item_id']; } # Prepare appropriate message $data['msg'] = empty($data['details'])? "ERROR: We could not resolve the item you are attempting to edit.": ""; $data['area'] = !empty($data['type'])? $data['type']."_form": "basic_msg"; $this->load->view('addons/basic_addons', $data); } # Function to delete a registration list item function delete_list_item() { $data = filter_forwarded_data($this); if(!empty($data['type']) && !empty($data['item_id'])) { $result = $this->_person->remove_list_item($data['type'], $data['item_id']); } $data['response']['msg'] = (!empty($result) && $result)? "The ".$data['type']." has been deleted.": "ERROR: There was a problem deleting the ".$data['type']."."; $data['area'] = !empty($data['type'])? $data['type']."_list": "basic_msg"; $this->load->view('addons/basic_addons', $data); } #The third step form for the registration process function step_four() { $data = filter_forwarded_data($this); # The user posted the form if(!empty($_POST)) { $result = $this->_person->submit_application($this->native_session->get('person_id'), array('user_id'=>($this->native_session->get('__user_id')? $this->native_session->get('__user_id'): $this->native_session->get('user_id')), 'emailaddress'=>$this->native_session->get('emailaddress'), 'first_name'=>$this->native_session->get('firstname'), 'last_name'=>$this->native_session->get('lastname'))); if($result['boolean']) { $data['msg'] = !empty($result['msg'])? $result['msg']: "Your application has been submitted. You will be notified using your registered email when it is approved.<br><br>Please check your email spam folder if you can not find your confirmation email."; $viewToLoad = 'account/login'; } else { $data['msg'] = !empty($result['msg'])? $result['msg']: "ERROR: There was a problem submitting your application. Please try again or contact us if the problem persists."; $viewToLoad = 'register/step_four'; } } $viewToLoad = !empty($viewToLoad)? $viewToLoad: 'register/step_four'; $this->load->view($viewToLoad, $data); } } /* End of controller file */
Shell
UTF-8
610
2.921875
3
[]
no_license
#!/bin/bash #set -e sudo -k # Just because, clearing some variables that are shared between other scripts. unset account_password unset git_fullname unset git_email . init/banner.sh . init/check.sh . init/input.sh # Initializing apt-get sudo apt update sudo apt upgrade -y # Installing various applications... sudo apt install git -y sudo apt install vim -y sudo apt install nmap -y sudo apt install moreutils -y sudo apt install curl -y sudo apt install ctags -y sudo apt clean sudo apt autoclean # Initializing scripts... . init/git.sh . init/vim.sh . init/bash.sh # For sanity sake sudo -k exit 0
C++
UTF-8
1,109
3.640625
4
[]
no_license
// Copyright (c) 2020 Ryan Walsh All rights reserved // // Created by Ryan Walsh // Created on December 9 2020 // this program tells you if the year entered is a leap year #include <iostream> #include <string> int main() { // this program tells you if the year entered is a leap year std::string year_string; int year; // input std::cout << "Enter a year please:"; std::cin >> year_string; std::cout << "" << std::endl; // process and output try { year = std::stoi(year_string); if (year % 4 == 0) { if (year % 100 == 0) { if (year % 400 == 0) { std::cout << year << " is a leap year." << std::endl; } else { std::cout << year << " is a common year." << std::endl; } } else { std::cout << year << " is a leap year." << std::endl; } } else { std::cout << year << " is a common year." << std::endl; } }catch (std::invalid_argument) { std::cout << "That was not a year. Try again."; } }
Java
UTF-8
646
2.1875
2
[]
no_license
package br.com.letscode.Request; import br.com.letscode.entities.Aluno; import br.com.letscode.entities.Curso; import br.com.letscode.repository.CursoRepository; import lombok.Getter; import java.sql.Date; import java.util.Optional; @Getter public class AlunoRequest { private Long ra; private String nome; private String sobrenome; private Date datanascimento; private Long codigocurso; public Aluno converter(CursoRepository cursoRepository){ Optional<Curso> curso = cursoRepository.findById(codigocurso); return new Aluno(ra,nome,sobrenome,datanascimento,curso.get().getCodigoCurso()); } }
PHP
UTF-8
1,415
2.75
3
[]
no_license
<?php require_once("library.php"); function sendMessage($message) { if(strlen($message) > 1000) { $message = substr($message, 0, 2000) . "-"; } if(!checkSession()) { return array("success" => false, "message" => "Session not created"); } $g_id = $_SESSION["group_id"]; $u_id = $_SESSION["user_id"]; if(strpos($message, "<script")) { logSecurityMessage("WARNING: User " . $u_id . " probably tried to put executable Javascript into a message."); } // Preventing XSS attacks // Stops user messages from becoming arbitrarily executable JS $message = str_replace("&", "&amp", $message); $message = str_replace("<", "&lt", $message); $message = str_replace(">", "&gt", $message); // Not sure how this is possible, but whatever $message = str_replace("\n", " ", $message); if(!file_exists(getChatsPath() . $g_id . ".txt")) { return array("success" => false, "message" => "Could not find group chat file for group id " . $g_id, "attempted" => getChatsPath() . $g_id . ".txt"); } $fp = fopen(getChatsPath() . $g_id . ".txt", "a"); $dat = array(); $dat["user_id"] = $u_id; $dat["message"] = $message; fwrite($fp, json_encode($dat) . "\n"); fclose($fp); return array("success" => true, "message" => "Sent message"); } ?>
C
UTF-8
205
2.859375
3
[]
no_license
#include<stdio.h> main() { int a,i,max=0; scanf("%d",&a); int ar[a]; for(i=0;i<a;i++){ scanf("%d",&ar[i]); if(i==0){ max=ar[i];} if(ar[i]<max) { max=ar[i]; } } printf("%d",max); }
PHP
UTF-8
986
3.34375
3
[ "MIT" ]
permissive
<?php namespace Userv\Connection; use Userv\Server; /** * This class represent a connection with a unique client */ class Connection implements ConnectionInterface { public $connection; public $server; /** * {@inheritdoc} */ public function setServer(Server $server) { $this->server = $server; } /** * {@inheritdoc} */ public function setSocketConnection($connection) { if (! is_resource($connection)) { throw new \InvalidArgumentException('Connection must be a resource'); } $this->connection = $connection; } /** * {@inheritdoc} */ public function read() { return trim(fgets($this->connection)); } /** * {@inheritdoc} */ public function write($msg) { fwrite($this->connection, $msg); } /** * {@inheritdoc} */ public function close() { fclose($this->connection); } }
C++
UTF-8
862
2.921875
3
[]
no_license
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <climits> #include <iterator> using namespace std; using ivec = vector<long long int>; ivec read_array() { auto n = 0ul; cin >> n; auto arr = ivec(n); for (auto i = 0; i < n; ++i) { cin >> arr[i]; } return arr; } int main() { auto arr = read_array(); sort(arr.begin(), arr.end()); auto min = UINT_MAX; auto mins = vector<int>(); for (auto pair1 = 0, pair2 = 1; pair2 < arr.size(); ++pair1, ++pair2) { auto diff = abs(arr[pair1] - arr[pair2]); if (diff < min) { min = diff; mins.clear(); mins.push_back(arr[pair1]); mins.push_back(arr[pair2]); } else if (diff == min) { mins.push_back(arr[pair1]); mins.push_back(arr[pair2]); } } copy(mins.begin(), mins.end(), ostream_iterator<int>(cout, " ")); return 0; }
C++
UTF-8
1,222
3.078125
3
[ "MIT" ]
permissive
#include<stdio.h> #include<limits.h> #include<list> using namespace std; int V; list<int> *adj; int *color, *tf, time; list<int> sortedlist; void dfsvisit(int u) { color[u] = 1; time = time + 1; list<int>::iterator i; for(i = adj[u].begin(); i != adj[u].end(); i++) { int v = *i; if(color[v] == 0) { dfsvisit(v); } } color[u] = 2; time = time + 1; tf[u] = time; sortedlist.push_front(u); } void topologicalsort() { color = new int[V]; tf = new int[V]; for(int u = 0; u < V; u++) { color[u] = 0; } time = 0; for(int u = 0; u < V; u++) { if(color[u] == 0) { dfsvisit(u); } } list<int>::iterator i; for(i = sortedlist.begin(); i != sortedlist.end(); i++) { printf("%d ", *i); } printf("\n"); } int main() { int e, u, v; FILE* f = fopen("3 topologicalsort.txt", "r"); fscanf(f, "%d %d", &V, &e); adj = new list<int>[V]; for(int i = 0; i < e; i++) { fscanf(f, "%d %d", &u, &v); adj[u].push_back(v); } topologicalsort(); fclose(f); delete[] adj; delete[] color; delete[] tf; return 0; }
Java
WINDOWS-1250
8,419
2.296875
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * DoctorWindow.java * * Created on 2012-01-05, 13:55:38 */ package gui; import sildent.Config; import utilities.User; import javax.swing.border.BevelBorder; import javax.swing.border.LineBorder; import java.awt.Color; import javax.swing.border.EtchedBorder; /** * * @author Aleks */ public class LoginWindow extends javax.swing.JFrame { /** Creates new form DoctorWindow */ public LoginWindow() { initComponents(); setLocationRelativeTo(null); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); loginField = new javax.swing.JTextField(); passwordField = new javax.swing.JPasswordField(); jPanel4 = new javax.swing.JPanel(); loginButton = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Logowanie"); setResizable(false); jPanel2.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null)); jPanel2.setToolTipText("dane personalne"); jPanel2.setName("test"); // NOI18N jLabel1.setText("Login:"); jLabel2.setText("Haso:"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(passwordField, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(loginField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 119, Short.MAX_VALUE))) .addContainerGap(13, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(loginField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(passwordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); loginButton.setText("zaloguj"); loginButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { login(evt); } }); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addGap(31, 31, 31) .addComponent(loginButton, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(33, Short.MAX_VALUE)) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(loginButton) .addContainerGap()) ); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); jPanel2.getAccessibleContext().setAccessibleName("test"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void login(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_save if( loginField.getText().equalsIgnoreCase("test") && new String(passwordField.getPassword()).equals("test") ){ Config.isAdmin = true; this.dispose(); } }//GEN-LAST:event_save /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new LoginWindow().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel4; private javax.swing.JButton loginButton; private javax.swing.JTextField loginField; private javax.swing.JPasswordField passwordField; // End of variables declaration//GEN-END:variables }
Shell
UTF-8
263
2.640625
3
[]
no_license
#!/usr/bin/env bash ### List of passed in variables # $1 - Path name to working directory # $2 - Base name of fit. # $3 - Photometry file. # $4 - Calcsfh parameter file. echo "Passed in quantities ${1}, ${2}, ${3}, and ${4}" ./scripts/ProcessDAv.py $1 $2 $3 $4
PHP
UTF-8
608
2.8125
3
[]
no_license
<?php /* 路径生成器 提供文件或文件夹的存储路径 更新记录: 2016-04-12 创建 */ class PathBuilder { function __construct() { } /* 返回上传路径: 示例:D:\wamp\www\HttpUploader6.1\upload\ */ function getRoot() { $path = getcwd();// D:\wamp\www\HttpUploader6.1 $path = realpath($path);//规范化路径 up6.1/upload/ $path = PathTool::combin($path, "upload"); if(!is_dir($path) ) mkdir($path);//创建目录 return realpath($path);//与操作系统保持一致 } function genFolder($uid,&$fd){} function genFile($uid,$md5,$nameLoc){} } ?>
C++
UTF-8
959
4.0625
4
[]
no_license
/* * Implement an algorithm to find the nth to last element of a singly linked list. */ #include <iostream> using namespace std; typedef struct node { int data; struct node *next; }LinkList; LinkList* createLinkList(int a[], int n) { LinkList *head, *p, *q; for(int i = 0; i < n; ++i){ q = new LinkList; q->data = a[i]; if(i==0){ p = q; head = p; continue; } p->next = q; p = q; } return head; } LinkList* findNthToLast(LinkList *head, int n) { LinkList *fast = head, *slow = head; for (int i = 0; i < n; ++i) fast = fast->next; while (fast) { slow = slow->next; fast = fast->next; } return slow; } int main(int argc, char const *argv[]) { int a[] = {1, 2, 4, 5, 4, 4, 9}; int length = 7; LinkList *head = createLinkList(a, length); int n = 4; LinkList *nthToLast = findNthToLast(head, n); cout << nthToLast->data << endl; return 0; }
C++
UTF-8
820
3.015625
3
[]
no_license
#include "Elevator.h" #include <iostream> #include <cstdlib> //srand, rand #include <chrono> #include <vector> #include <cmath> #include <string> #include <random> using namespace std; //Elevator::Elevator(){ // //}; // num_elevators = times this program is being run? // 3 variables // access * 2 // travel-time = abs(final_floor - initial floor) * 2 (up and back down), could go from 4 to 3, but only up and down to floor for now // travel-time to guest (one-way) // we are calculating the average travel time to get guest to their destination (basically the average of 2-7 to ground) // and delivering the guest (when more than one elevator can pick up a guest on the way down // i.e. 4 going down CAN get 3, but a elevator is on 3, so it picks them up instead, reducing travel time
C++
UTF-8
19,071
2.96875
3
[]
no_license
// Agent.cc #include <iostream> #include <fstream> #include <list> #include <string> #include <string.h> #include "Agent.h" using namespace std; Agent::Agent () { } // end Agent constructor Agent::~Agent () { ofstream outputFile; //cout << "X: " << curLoc.X << " Y: " << curLoc.Y << endl; if (normalExit == 0) { //cout << "normalExit is zero, lastPercept = " << lastPercept << "\n"; if (lastPercept == 1) { //cout << "lastPercept is 1\n"; //cout << "pit at this location" << endl; pitList.push_back (curLoc); searchEngine.RemoveSafeLocation(curLoc.X,curLoc.Y); } // end if else if (lastPercept == 2) { //cout << "lastPercept is 2\n"; //cout << "wumpus at this location" << endl; wumpusLoc = curLoc; searchEngine.RemoveSafeLocation(curLoc.X,curLoc.Y); } // end else } // end if not normalExit outputFile.open ("saved.txt", ios::out); fileCount++; fileCount %= 10; // reset every ten iterations outputFile << fileCount << "\n"; //cout << "fileCount: " << fileCount << endl; outputFile << goldLoc.X << "," << goldLoc.Y << "\n"; outputFile << wumpusLoc.X << "," << wumpusLoc.Y << "\n"; for (list<Location>::iterator it = pitList.begin (); it != pitList.end (); it++) { outputFile << it->X << "," << it->Y << "\n"; } // end output all known pit locations outputFile << "safe\n"; for (list<Location>::iterator it = searchEngine.safeLocations.begin (); it != searchEngine.safeLocations.end (); it++) { outputFile << it->X << "," << it->Y << "\n"; } // end output all known pit locations outputFile << "possible\n"; for (list<Location>::iterator it = possibleMoveList.begin (); it != possibleMoveList.end (); it++) { outputFile << it->X << "," << it->Y << "\n"; } // end output all known pit locations outputFile << "EOF\n"; outputFile.close (); } // end Agent deconstructor void Agent::Initialize () { ifstream inputFile; string line; list <Action> actionList2; int x, y; int a = 1, b = 1; /* // initialize all locations as safe locations: for (y = 1; y <= 4; y++) { for (x = 1; x <= 4; x++) { searchEngine.AddSafeLocation(x,y); } // end inner for loop } // end outer for loop */ /* inputFile.open ("saved.txt", ios::in); if (inputFile.is_open()) { readFile (inputFile); } // if inputFile exists, read it inputFile.close (); */ // initialize what we know about locations: curLoc.X = 1; curLoc.Y = 1; prevLoc.X = 0; prevLoc.Y = 0; curDir = 0; wumpusLoc.X = 0; wumpusLoc.Y = 0; goldLoc.X = 0; goldLoc.Y = 0; lastPercept = 0; fileCount = 0; //cout << "calling readfile:\n"; fileCount = readFile (); //cout << "finished readfile\n"; //cout << "Safe locations List: \n"; for (list<Location>::iterator it = searchEngine.safeLocations.begin (); it != searchEngine.safeLocations.end (); it++) { //cout << it->X << "," << it->Y << "\n"; } // end output all known pit locations agentHasGold = false; actionList.clear(); } Action Agent::Process (Percept& percept) { Action action; // vector list of Actions list<Action> actionList2; Location theGoto; // Flag variable to test if an element exists in a list int exists = 0; int safeFlag = 1; // variables to store possible moves: Location p_up, p_down, p_left, p_right, possibleMove; /*****************************BEGIN****************************/ // if we are here, this is a safe location // if it has not been added to safeLocations, add it: // flag will be set to 1 if the location is in the safeLocations list for (list<Location>::iterator it = searchEngine.safeLocations.begin (); it != searchEngine.safeLocations.end (); it++) { if (curLoc == *it) { exists = 1; //cout << curLoc.X << "," << curLoc.Y << " already exists\n"; } // end if location is already in safe list, set exists flag so we don't re-add it } // end iterate through safelist to test if location is already in safeLocations if (exists == 0) { searchEngine.AddSafeLocation(curLoc.X, curLoc.Y); //cout << "Added: " << curLoc.X << "," << curLoc.Y << endl; removePotentialPit (potentialPit, curLoc); } // end if location isn't already in safeLocations, add it /*** *** *** *** *** END Add safe location *** *** *** *** ***/ /*****************************BEGIN****************************/ // if we are at home position with the gold, exit the game: (c) if (agentHasGold && curLoc.X == 1 && curLoc.Y == 1 && (curDir == 2 || curDir == 3)) { action = CLIMB; normalExit = 1; return action; } // end if home with gold, climb /*** *** *** *** *** END if home with gold, exit *** *** *** *** ***/ /***************************BEGIN******************************/ // if we have found the gold, pick it up and set the agentHasGold flag: (b) if (!agentHasGold && percept.Glitter == 1) { //cout << "Glitter\n"; action = GRAB; agentHasGold = 1; goldLoc.X = curLoc.X; goldLoc.Y = curLoc.Y; return action; } // if glitter, grab /*** *** *** *** *** END if Glitter, Grab *** *** *** *** ***/ /*****************************BEGIN****************************/ if (actionList.empty()) { //cout << "actionList is empty\n"; /*** Begin convoluted move evaluations ***/ /*****************************BEGIN****************************/ // If we know the location of the gold, get to it, get it, get back, get out (d) if (goldLoc.X != 0) { //cout << "Gold location is known\n"; //cout << goldLoc.X << "," << goldLoc.Y << endl; if (!agentHasGold) { //cout << "Plot path to gold\n"; actionList2 = searchEngine.FindPath (Location(curLoc.X,curLoc.Y), (Orientation) curDir, Location(goldLoc.X,goldLoc.Y), (Orientation) curDir); actionList.splice (actionList.end(), actionList2); actionList.push_back(GRAB); agentHasGold = 1; } // end if we don't yet have the gold, get to it and get it else { //cout << "plot the return trip\n"; actionList2 = searchEngine.FindPath (Location(curLoc.X,curLoc.Y), (Orientation) curDir, Location(1,1), LEFT); actionList.splice (actionList.end(), actionList2); actionList.push_back(CLIMB); } // if we do already have the gold, get back and get out: } // end findPath to gold /*** *** *** *** *** END *** *** *** *** ***/ /* end if we know the location of the gold, go to it, get it, get back, get out */ /*****************************BEGIN****************************/ // get a list of possible moves: // evaluate up if (curLoc.Y < 4 && curLoc.Y > 0) // between 1 and 3 { possibleMove.X = (curLoc.X); possibleMove.Y = (curLoc.Y + 1); // check if location contains a wumpus: if (possibleMove.X == wumpusLoc.X && possibleMove.Y == wumpusLoc.Y) { safeFlag = 0; } // end check if location contains a wumpus // check if location contains a pit: for (list<Location>::iterator it = pitList.begin (); it != pitList.end (); it++) { if (it->X == possibleMove.X and it->Y == possibleMove.Y) { safeFlag = 0; } // end if location is a pit, set safeFlag to zero } // end iterate through pit list to check if move location is a pit if (safeFlag == 1) { // only add if it's not already in the list: int alreadyFlag = 0; for (list <Location>::iterator it = possibleMoveList.begin (); it != possibleMoveList.end (); it++) { if (possibleMove.X == it->X && possibleMove.Y == it->Y) { alreadyFlag = 1; } // end if already in list, set flag } // end iterate through list to check if postion is already in it if (alreadyFlag == 0) { possibleMoveList.push_back (possibleMove); } // end only add if not already in list //cout << "added: " << possibleMove.X << "," << possibleMove.Y << endl; } // end if move is not a pit or wumpus, add to list of possible moves } // end evaluate up // evaluate down if (curLoc.Y > 1 && curLoc.Y < 5) { possibleMove.X = (curLoc.X); possibleMove.Y = (curLoc.Y - 1); // check if location contains a wumpus: if (possibleMove.X == wumpusLoc.X && possibleMove.Y == wumpusLoc.Y) { safeFlag = 0; } // end check if location contains a wumpus // check if location contains a pit: for (list<Location>::iterator it = pitList.begin (); it != pitList.end (); it++) { if (it->X == possibleMove.X and it->Y == possibleMove.Y) { safeFlag = 0; } // end if location is a pit, set safeFlag to zero } // end iterate through pit list to check if move location is a pit if (safeFlag == 1) { // only add if it's not already in the list: int alreadyFlag = 0; for (list <Location>::iterator it = possibleMoveList.begin (); it != possibleMoveList.end (); it++) { if (possibleMove.X == it->X && possibleMove.Y == it->Y) { alreadyFlag = 1; } // end if already in list, set flag } // end iterate through list to check if postion is already in it if (alreadyFlag == 0) { possibleMoveList.push_back (possibleMove); } // end only add if not already in list //cout << "added: " << possibleMove.X << "," << possibleMove.Y << endl; } // end if move is not a pit or wumpus, add to list of possible moves } // end evaluate down // evaluate left if (curLoc.X > 1 && curLoc.X < 5) { possibleMove.X = (curLoc.X - 1); possibleMove.Y = (curLoc.Y); // check if location contains a wumpus: if (possibleMove.X == wumpusLoc.X && possibleMove.Y == wumpusLoc.Y) { safeFlag = 0; } // end check if location contains a wumpus // check if location contains a pit: for (list<Location>::iterator it = pitList.begin (); it != pitList.end (); it++) { if (it->X == possibleMove.X and it->Y == possibleMove.Y) { safeFlag = 0; } // end if location is a pit, set safeFlag to zero } // end iterate through pit list to check if move location is a pit if (safeFlag == 1) { // only add if it's not already in the list: int alreadyFlag = 0; for (list <Location>::iterator it = possibleMoveList.begin (); it != possibleMoveList.end (); it++) { if (possibleMove.X == it->X && possibleMove.Y == it->Y) { alreadyFlag = 1; } // end if already in list, set flag } // end iterate through list to check if postion is already in it if (alreadyFlag == 0) { possibleMoveList.push_back (possibleMove); } // end only add if not already in list //cout << "added: " << possibleMove.X << "," << possibleMove.Y << endl; } // end if move is not a pit or wumpus, add to list of possible moves } // end evaluate left // evaluate right safeFlag = 1; if (curLoc.X < 4 && curLoc.X > 0) { possibleMove.X = (curLoc.X + 1); possibleMove.Y = (curLoc.Y); //cout << "evaluating: " << possibleMove.X << "," << possibleMove.Y << endl; // check if location contains a wumpus: if (possibleMove.X == wumpusLoc.X && possibleMove.Y == wumpusLoc.Y) { safeFlag = 0; } // end check if location contains a wumpus // check if location contains a pit: for (list<Location>::iterator it = pitList.begin (); it != pitList.end (); it++) { if (it->X == possibleMove.X and it->Y == possibleMove.Y) { safeFlag = 0; } // end if location is a pit, set safeFlag to zero } // end iterate through pit list to check if move location is a pit if (safeFlag == 1) { // only add if it's not already in the list: int alreadyFlag = 0; for (list <Location>::iterator it = possibleMoveList.begin (); it != possibleMoveList.end (); it++) { if (possibleMove.X == it->X && possibleMove.Y == it->Y) { alreadyFlag = 1; } // end if already in list, set flag } // end iterate through list to check if postion is already in it if (alreadyFlag == 0) { possibleMoveList.push_back (possibleMove); } // end only add if not already in list //cout << "added: " << possibleMove.X << "," << possibleMove.Y << endl; } // end if move is not a pit or wumpus, add to list of possible moves } // end evaluate right /*** *** *** *** *** END add to list of possible moves *** *** *** *** ***/ for (list <Location>::iterator it = possibleMoveList.begin (); it != possibleMoveList.end (); it++) { //cout << "possible: " << it->X << "," << it->Y << endl; } // we now have a list of potential moves, search list for latest unexplored loation and go to it int visited = 0; Location nextLocation, nextUnexploredLocation; nextLocation.X = 0; nextLocation.Y = 0; nextUnexploredLocation.X = 0; nextUnexploredLocation.Y = 0; for (list <Location>::iterator it = possibleMoveList.begin (); it != possibleMoveList.end (); it++) { for (list <Location>::iterator it2 = searchEngine.safeLocations.begin (); it2 != searchEngine.safeLocations.end (); it2++) { if (*it == *it2) { visited = 1; } // end if location is in safe list, it has been visited } // end iterate through safe list looking for location if (visited == 1) { nextLocation.X = it->X; nextLocation.Y = it->Y; } // if the location has been visited, add as nextLocation else { nextUnexploredLocation.X = it->X; nextUnexploredLocation.Y = it->Y; //cout << "next unexplored: " << it->X << "," << it->Y << endl; } // if the location has not been visited, add as nextUnexploredLocation visited = 0; } // end check each location in possible list for visited/unexplored // favor unexplored locations over explored: if (nextUnexploredLocation.X != 0) { nextLocation.X = nextUnexploredLocation.X; nextLocation.Y = nextUnexploredLocation.Y; } // end if there is an unexplored location, set it to nextLocation // we need to remove the location we're going to from the possible Move list // but we have to handle the last element differently than not-last elements list <Location>::iterator it = possibleMoveList.end (); if (it->X == nextLocation.X && it->Y == nextLocation.Y) { possibleMoveList.pop_back (); } // end if it's at the end, do pop_back else { for (list <Location>::iterator it = possibleMoveList.begin (); it != possibleMoveList.end (); it++) { if (it->X == nextLocation.X && it->Y == nextLocation.Y) { possibleMoveList.erase (it); // once we delete our record, no reason to continue iterating through list, get out break; } // end if it's at the end, do erase } // end iterate through list to find element to erase } // end else, iterate to location and erase //cout << "Goto: " << nextLocation.X << "," << nextLocation.Y << endl; searchEngine.AddSafeLocation (nextLocation.X, nextLocation.Y); actionList2 = searchEngine.FindPath (Location(curLoc.X,curLoc.Y), (Orientation) curDir, Location(nextLocation.X,nextLocation.Y), (Orientation) curDir); actionList.splice (actionList.end(), actionList2); if (goldLoc.X == 0 && percept.Stench == 1) lastPercept = 2; if (goldLoc.X == 0 && percept.Breeze == 1) lastPercept = 1; if (goldLoc.X == 0 && percept.Breeze == 0 && percept.Stench == 0) lastPercept = 0; } // end if action list is empty action = actionList.front(); actionList.pop_front(); if (goldLoc.X == 0 && percept.Stench == 1) lastPercept = 2; if (goldLoc.X == 0 && percept.Breeze == 1) lastPercept = 1; if (goldLoc.X == 0 && percept.Breeze == 0 && percept.Stench == 0) lastPercept = 0; // adjust curLoc appropriately: if (action == GOFORWARD) { if (curDir == 0) { if (curLoc.X < 4) { curLoc.X++; } } if (curDir == 1) { if (curLoc.Y < 4) { curLoc.Y++; } } if (curDir == 2) { if (curLoc.X > 1) { curLoc.X--; } } if (curDir == 3) { if (curLoc.Y > 1) { curLoc.Y--; } } } // end if action == GOFORWARD else if (action == TURNLEFT) { curDir++; curDir = curDir % 4; } else if (action == TURNRIGHT) { curDir--; if (curDir == -1) { curDir = 3; } } for (list<Location>::iterator it = searchEngine.safeLocations.begin (); it != searchEngine.safeLocations.end (); it++) { //cout << it->X << "," << it->Y << "\n"; } // end output all known pit locations return action; } // end Process function void Agent::GameOver (int score) { } // readFile function int Agent::readFile () { string line; Location loc; // initialize fileCount to 0 fileCount = 0; ifstream inputFile; inputFile.open ("saved.txt", ios::in); if (inputFile.is_open()) { // first line is count: // if the file has been used 10 times, disregard it getline (inputFile, line); fileCount = int (line[0] - 48); if (fileCount < 9) { // second line is the gold location: getline (inputFile, line); goldLoc.X = int (line[0] - 48); goldLoc.Y = int (line[2] - 48); //cout << "Gold\n"; // second line is the wumpus location: getline (inputFile, line); wumpusLoc.X = int (line[0] - 48); wumpusLoc.Y = int (line[2] - 48); //cout << "wumpus\n"; // remaining locations until "Safe" are pit locations int flag = 0; while (flag == 0) { getline (inputFile, line); if (line[0] == 's') { flag = 1; getline (inputFile, line); } // end if we encounter the letter s, stop reading else { loc.X = int (line[0] - 48); loc.Y = int (line[2] - 48); //cout << "pit\n"; pitList.push_back (loc); } // if not "safe" keyword, add to pit list } // end add known pit locations to pitList // locations until "possible" are known safe locations flag = 0; while (flag == 0) { if (line[0] == 'p') { flag = 1; } // end if possible found if (flag == 0) { loc.X = int (line[0] - 48); loc.Y = int (line[2] - 48); //cout << "safe\n"; searchEngine.safeLocations.push_back (loc); } // end if not possible flag getline (inputFile, line); } // end add known safe locations // locations until "EOF" are possible locations flag = 0; while (flag == 0) { if (line[0] == 'E') { flag = 1; } // end if EOF found if (flag == 0) { loc.X = int (line[0] - 48); loc.Y = int (line[2] - 48); //cout << "possible\n"; possibleMoveList.push_back (loc); } // end if not EOF flag getline (inputFile, line); } // end add known safe locations } // end only read the rest of the file if count is less than 9 } // end if there is a save file, read from it: inputFile.close (); return fileCount; } // end function readFile // Remove given location from safeLocations list void Agent::removePotentialPit (list <Location> potentialPit, Location location) { //for (list<Location>::iterator it = searchEngine.safeLocations.begin (); it != searchEngine.safeLocations.end (); it++) list<Location>::iterator itr = findLocation (potentialPit.begin(), potentialPit.end(), location); if (itr != potentialPit.end()) { potentialPit.erase(itr); ////cout << "Removed safe location (" << x << "," << y << ")\n"; } }
Python
UTF-8
4,941
3.1875
3
[]
no_license
import pygame import imgui from Framework.Vector import vec2 from GameObject import GameObject from Tilemap import TileTypes class PlayerTilemapFree(GameObject): def __init__(self, tilePosition, sprite, animationFrames, tilemap): super().__init__( vec2( 0, 0 ), sprite, animationFrames[0] ) self.animationFrames = animationFrames self.tilemap = tilemap self.currentAnimation = 1 # Moving down. self.currentFrame = 0 self.animationTimer = 0.2 self.position = self.tilemap.getWorldPositionForTilePosition( tilePosition ) def onEvent(self, event): super().onEvent( event ) # Inputs will set the direction the player is moving. if event.type == pygame.KEYDOWN: if event.key == pygame.K_w: self.direction.y += 1 if event.key == pygame.K_s: self.direction.y += -1 if event.key == pygame.K_a: self.direction.x += -1 if event.key == pygame.K_d: self.direction.x += 1 if event.type == pygame.KEYUP: if event.key == pygame.K_w: self.direction.y -= 1 if event.key == pygame.K_s: self.direction.y -= -1 if event.key == pygame.K_a: self.direction.x -= -1 if event.key == pygame.K_d: self.direction.x -= 1 def doesPositionFitOnTilemap(self, position, size): # Check if the player's new X position is valid on this tilemap. tileTypeBL = self.tilemap.getTileTypeForWorldPosition( vec2( position.x, position.y ) ) tileTypeBR = self.tilemap.getTileTypeForWorldPosition( vec2( position.x + size.x, position.y ) ) tileTypeTL = self.tilemap.getTileTypeForWorldPosition( vec2( position.x, position.y + size.y ) ) tileTypeTR = self.tilemap.getTileTypeForWorldPosition( vec2( position.x + size.x, position.y + size.y ) ) # If it fits, set the new X position. if tileTypeBL == TileTypes.Empty and tileTypeBR == TileTypes.Empty and tileTypeTL == TileTypes.Empty and tileTypeTR == TileTypes.Empty: return True return False def update(self, deltaTime): # GameObject update will do the actual player movement. # super().update( deltaTime ) collisionOffset = vec2( 0.15, 0.05 ) playerSize = vec2( self.tilemap.tileSize.x * 0.7, self.tilemap.tileSize.y * 0.45 ) newPosition = vec2( self.position.x + self.direction.x * self.speed * deltaTime, self.position.y + self.direction.y * self.speed * deltaTime ) # Check if the player's new X position is valid on this tilemap. If it fits, set it. newPositionOnXAxis = vec2( newPosition.x + collisionOffset.x, self.position.y + collisionOffset.y ) if self.doesPositionFitOnTilemap( newPositionOnXAxis, playerSize ): self.position.x = newPosition.x # Check if the player's new Y position is valid on this tilemap. If it fits, set it. newPositionOnYAxis = vec2( self.position.x + collisionOffset.x, newPosition.y + collisionOffset.y ) if self.doesPositionFitOnTilemap( newPositionOnYAxis, playerSize ): self.position.y = newPosition.y # Set the correct animation based on the direction we're going. # Animations are in this order: Up, Down, Left, Right # Each animation is 3 frames long. if self.direction.y > 0: self.currentAnimation = 0 # Moving up. if self.direction.y < 0: self.currentAnimation = 1 # Moving down. if self.direction.x < 0: self.currentAnimation = 2 # Moving left. if self.direction.x > 0: self.currentAnimation = 3 # Moving right. # Update the timer and switch frames on the animation. self.animationTimer -= deltaTime if self.animationTimer < 0: self.animationTimer = 0.2 self.currentFrame += 1 if self.currentFrame > 2: self.currentFrame = 0 # If the player isn't moving, just force the first frame of the animation. if self.direction.x == 0 and self.direction.y == 0: self.currentFrame = 0 # Set the player's current texture. self.texture = self.animationFrames[self.currentAnimation * 3 + self.currentFrame] # Debug info displayed using imgui. imgui.begin( "Player", True ) changed, newvalue = imgui.slider_float2( "Position", self.position.x, self.position.y, 0, 20 ) self.position.x = newvalue[0] self.position.y = newvalue[1] tiletype = self.tilemap.getTileTypeForWorldPosition( self.position + collisionOffset ) imgui.text( "Tile Type: " + str(tiletype) ) imgui.end() def draw(self): super().draw()
SQL
UTF-8
184
3.265625
3
[ "Apache-2.0", "PostgreSQL", "BSD-3-Clause", "MIT" ]
permissive
select sum(cnt1), sum(sum2) from ( select o_orderdate, count(distinct o_orderpriority), count(distinct o_orderkey) cnt1, sum(o_totalprice) sum2 from orders group by o_orderdate ) a
Python
UTF-8
341
3.484375
3
[ "MIT" ]
permissive
list_a = [ 5 , 4 , 2 , 1 , 3 ] length = len(list_a) for i in range(length -1 ): smallest = i for j in range(i+ 1 , length): if list_a[j] < list_a[smallest]: smallest = j tmp = list_a[smallest] list_a[smallest] = list_a[i] list_a[i] = tmp print(list_a)
Java
UTF-8
2,132
2.0625
2
[]
no_license
package com.eagle.qa.testcases; import org.openqa.selenium.By; import org.openqa.selenium.support.ui.Select; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.EagleconM.qa.pages.LoginPage; import com.EagleconM.qa.pages.Payment_and_Billing_Page; import com.eagle.qa.base.Testbase; import com.eagle.qa.util.Testutil; public class Payment_test extends Testbase { String sheetName = "Payment12"; LoginPage login; Payment_and_Billing_Page payment; public Payment_test() { super(); } @BeforeMethod public void Setup() { initiolization(); login = new LoginPage(); payment = new Payment_and_Billing_Page(); login.login(pro.getProperty("username"), pro.getProperty("password")); } /* * @DataProvider public Object[][] getdatafromExcel(){ Object * data[][]=Testutil.getTestData(sheetName); return data; } * * @Test(dataProvider="getdatafromExcel") public void paymet(String * InvoiceNumber, String Total_Bill_Amount,String Name,String * Telephone,String Email,String Address,String City,String State,String * Zip){ payment.Payment(InvoiceNumber, Total_Bill_Amount, Name, Telephone, * Email, Address, City, State, Zip); * * } */ @Test public void payment_page() throws Exception { /* * Select drpo = new Select(driver.findElement(By.xpath( * "//*[@id='billing_form']/div/div[2]/div[9]/div/div/span"))); * drpo.selectByValue("India"); */ Thread.sleep(500); payment.Payment("123", "25", "Devaraj Gunjali", "9902938769", "raj@gmail.com", "ITpl", "Banglore", "Ka", "2019"); String url = driver.getCurrentUrl(); System.out.println(url); String text = driver .findElement( By.xpath("//*[@id='page-home']/div[1]/table[2]/tbody/tr/td/div[3]/table/tbody/tr[1]/th[2]")) .getText(); System.out.println(text); Assert.assertEquals(text, ": Eagle Conferencing Pvt Ltd"); } @AfterMethod public void teardown() { driver.quit(); } }
Python
UTF-8
126
3.046875
3
[]
no_license
n=[3,2,3,4,5,6] s=0 d=1 for i in range(len(n)): f=i+n[i] if f%3==0: s=s+(n[i]**2) print(n[i]) print(s)
PHP
UTF-8
1,662
2.53125
3
[]
no_license
<?php session_start(); $con = mysqli_connect('localhost', 'root', 'nitrr2020mca'); mysqli_select_db($con, 'studentsdb'); $email=$_POST['email_login']; $pass=$_POST['pass_login']; $password="#@nit"; for ($i = 0; $i < strlen($pass); $i++){ $password=$password.ord($pass[$i]); } $password=$password."@#"; $sql = "SELECT * FROM student_record WHERE (Email='$email' AND Password='$password')" ; $result = mysqli_query( $con, $sql ) ; if( mysqli_num_rows( $result ) > 0 ) { while($row = $result->fetch_assoc()) { $fname=$row['First_Name']; $mname=$row['Middle_Name']; $lname=$row['Last_Name']; $fatherName=$row['Father_Name']; $motherName=$row['Mother_Name']; $gender=$row['Gender']; $adhar=$row['Adhar']; $dob=$row['DOB']; $email=$row['Email']; $mobile=$row['Phone']; $country=$row['Country']; $state=$row['State']; $city=$row['City']; $pass=$row['Password']; if($mname==""){ $_SESSION['username'] = $fname." ".$lname; }else{ $_SESSION['username'] = $fname." ".$mname." ".$lname; } $_SESSION['email'] = $email; $record = array($fname,$mname,$lname,$fatherName,$motherName,$gender,$adhar,$dob,$email,$mobile,$country,$state,$city); $_SESSION['student_data']= $record; $_SESSION['pass']=$pass; } header('location:student_login_page.php'); exit; }else{ echo "oops.. something went wrong" ; } ?>
TypeScript
UTF-8
1,547
2.890625
3
[]
no_license
import * as fs from "fs"; import * as os from "os"; import { assert } from "chai"; import { isArray, isString } from "util"; import { IActualResult } from "./actual-result"; import { IExpectedResult, linesMatch } from "./expected-result"; export class ExpectedSuccess implements IExpectedResult { public lines(): string[] { return this.stdout; } public readonly stdout?: string[]; constructor(expectation?: string | string[]) { if (typeof (expectation) === 'string') this.stdout = fs.readFileSync(expectation, 'utf8').split(os.EOL); else this.stdout = expectation; } assertActual(actual: IActualResult): boolean { if (!actual) return false; if (actual.exit !== 0) { return assert.fail( "npm-make failed with output\n " + " " + actual.stderr.join("\n ") + "\n" + "Expected successful completion" + ((!!this.stdout) ? (": \n " + this.stdout.join("\n ")) : "") ); } if (this.stdout != undefined) { if (!linesMatch(this.stdout, actual.stdout)) { return assert.fail( "Succeeded as expected, but output didn't match.\n" + "EXPECTED\n " + this.stdout.join("\n ") + "\nACTUAL\n " + actual.stdout.join("\n ") ); } } } }
PHP
UTF-8
4,076
2.640625
3
[ "MIT" ]
permissive
<?php use App\Models\Kriteria; class Helper { public static function applyClass($user) { return "call from helper to " . $user; } public static function bobotTransform($data) { $listBobot = array(); foreach ($data as $d){ array_push($listBobot, $d->pivot->bobot); } $sum = array_sum($listBobot); $listBobotPersen = array(); foreach ($listBobot as $x){ array_push($listBobotPersen, number_format((float)$x/$sum, 3, '.', '')); } return $listBobotPersen; } public static function minmaxTransform($data) { $count = count($data[0]->bobot); $list = array(); for ($x = 0; $x < $count; $x++) { $bobot = null; foreach ($data as $d){ if ($d->bobot[$x]->type == 'cost'){ if ($bobot == null){ $bobot = $d->bobot[$x]->pivot->bobot; } else if ($bobot > $d->bobot[$x]->pivot->bobot) { $bobot = $d->bobot[$x]->pivot->bobot; } } else { if ($bobot == null){ $bobot = $d->bobot[$x]->pivot->bobot; } else if ($bobot < $d->bobot[$x]->pivot->bobot) { $bobot = $d->bobot[$x]->pivot->bobot; } } } array_push($list, $bobot); } return $list; } public static function colspan(){ $kriteria = Kriteria::all(); $count = count($kriteria); return $count+1; } public static function normalisasiTransform($data){ $getMinMax = self::minmaxTransform($data); $count = count($data[0]->bobot); $listfull = array(); foreach ($data as $d){ $list = array(); array_push($list, $d->name); for ($x = 0; $x < $count; $x++) { if ($d->bobot[$x]->type == 'cost'){ $normalisasi = $getMinMax[$x] / $d->bobot[$x]->pivot->bobot; } else { $normalisasi = $d->bobot[$x]->pivot->bobot / $getMinMax[$x]; } array_push($list, number_format((float)$normalisasi, 3, '.', '')); } array_push($listfull, $list); } return $listfull; } public static function hasilTransform($bobot,$data){ $getBobot = self::bobotTransform($bobot); $getNormalisasi = self::normalisasiTransform($data); $listhasilfull = array(); $count = count($getNormalisasi[0]); foreach ($getNormalisasi as $n){ $listhasil = array(); for ($x = 0; $x < $count; $x++) { if ($x > 0){ $hasil = number_format((float)$n[$x]*$getBobot[$x-1], 3, '.', ''); } else { $hasil = $n[$x]; } array_push($listhasil, $hasil); } array_push($listhasilfull, $listhasil); } return $listhasilfull; } public static function rankTransform($bobot,$data){ $getHasil = self::hasilTransform($bobot, $data); $listrankfull = array(); $count = count($getHasil[0]); foreach ($getHasil as $h){ $ranklist = array(); $hasiljumlah = 0; for ($x = 0; $x < $count; $x++) { if ($x == 0){ $name = $h[$x]; array_push($ranklist, $name); } else { $hasiljumlah += $h[$x]; } } array_push($ranklist, $hasiljumlah); array_push($listrankfull, $ranklist); } // $col = array_column( $listrankfull,1); // array_multisort( $col, SORT_DESC, $listrankfull ); // print_r($col); array_multisort( array_column($listrankfull, 1), SORT_DESC, $listrankfull ); return $listrankfull; } }
C#
UTF-8
611
3.15625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab1OOP { abstract class Shape { //абстрактный класс protected int width, height; //инкапсуляция - можем изменять данные в дочерник классах public Shape(int a, int b) { width = a; height = b; } public abstract int area(); //не нужно реализовать этот метод в базовом абстрактном классе } }
Java
UTF-8
1,248
3.734375
4
[]
no_license
package com.sparta.jm.sorters; public class Quicksort implements Sorter { @Override public int[] getSortedArray(int[] array1) { return quickSort(array1,0,array1.length-1); } public int[] quickSort(int[] array1, int low_index, int high_index) { int i = low_index; int j = high_index; //choose middle element as pivot int pivot = array1[low_index + (high_index - low_index) / 2]; // Divide into two arrays while (i <= j) { while (array1[i] < pivot) { i++; } while (array1[j] > pivot) { j--; } if (i <= j) { //if element on the left side is smallers than the element on the rightside int temp = array1[i]; array1[i] = array1[j]; array1[j] = temp; i++; //left j--; //right } } if (low_index < j) { //if array1 = quickSort(array1, low_index, j); } if (i < high_index) { array1 = quickSort(array1, i, high_index); } return array1; } @Override public String toString(){ return "Quick Sorter"; } }
Shell
UTF-8
2,214
2.96875
3
[ "BSD-2-Clause", "MIT", "GPL-2.0-or-later", "GPL-1.0-or-later", "GPL-2.0-only", "GPL-3.0-only", "FSFAP", "GPL-3.0-or-later", "Autoconf-exception-3.0", "LicenseRef-scancode-other-copyleft" ]
permissive
#! /bin/sh # Copyright (C) 2003-2013 Free Software Foundation, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Make sure we allow Libtool's -dlopen/-dlpreopen # Also check basic support for AM_LIBTOOLFLAGS/LIBTOOLFLAGS required='cc libtoolize' . test-init.sh cat >> configure.ac << 'END' AC_PROG_CC AM_PROG_AR AC_LIBTOOL_DLOPEN AM_PROG_LIBTOOL AC_OUTPUT END cat > Makefile.am << 'END' AUTOMAKE_OPTIONS = subdir-objects AM_LIBTOOLFLAGS = --silent lib_LTLIBRARIES = libmod1.la mod2.la libmod1_la_SOURCES = sub/mod1.c libmod1_la_LDFLAGS = -module libmod1_la_LIBADD = -dlopen mod2.la mod2_la_SOURCES = mod2.c mod2_la_LDFLAGS = -module mod2_la_LIBTOOLFLAGS = bin_PROGRAMS = prg prg_SOURCES = prg.c prg_LDADD = -dlopen libmod1.la -dlpreopen mod2.la .PHONY: print print: @echo 1BEG: $(prg_DEPENDENCIES) :END1 @echo 2BEG: $(libmod1_la_DEPENDENCIES) :END2 @echo 3BEG: $(LTCOMPILE) :END3 END mkdir sub liba cat > sub/mod1.c << 'END' int mod1 (void) { return 1; } END cat > mod2.c << 'END' int mod2 (void) { return 2; } END cat > prg.c << 'END' int main (void) { return 0; } END libtoolize --force --copy $ACLOCAL $AUTOCONF $AUTOMAKE --add-missing --copy ./configure "--prefix=$(pwd)/_inst" run_make -M print LIBTOOLFLAGS=--silent grep '1BEG: libmod1.la mod2.la :END1' output grep '2BEG: mod2.la :END2' output grep '3BEG: .*silent.*silent.* :END3' output test 2 -le $(grep mod2_la_LIBTOOLFLAGS Makefile | wc -l) $MAKE run_make -M install LIBTOOLFLAGS=--silent grep 'silent.*silent.*prg' output grep 'silent.*silent.*libmod1' output run_make -M uninstall LIBTOOLFLAGS=--silent grep 'silent.*silent.*libmod1' output :
Java
UTF-8
423
3.03125
3
[]
no_license
package sortowanie; import tablice.TabHelper; public class InsertSort { public static void sort(int[] tab) { for (int i = 1; i < tab.length; i++) { int j = i; // fragment [0, ..., i - 1] jest już posortowany int temp = tab[j]; while (j > 0 && tab[j - 1] > temp) { TabHelper.swap(tab, j, j - 1); j--; } } } }
C++
UTF-8
2,018
3.65625
4
[ "Apache-2.0" ]
permissive
#include "ArrayUtil/RView.hpp" #include <array> #include <cstdint> #include <iostream> using namespace ArrayUtil; static constexpr size_t testSize = 3; template <typename T, typename Owner> bool RunTests(std::string const& testName, T& view, Owner& owner) { // check data if (!(owner[0] == *view.begin() && owner[1] == *(view.begin()+1) && owner[2] == *(view.begin()+2))) { std::cout << "!!! FAIL !!!" << std::endl; std::cout << "In test '" << testName.c_str() << "':" << std::endl; std::cout << "Viewed data incorrect" << std::endl; return false; } // begin & end, const // Range-based for loop (just check if it compiles) for (auto const& el : view) {} return true; } int main() { bool success = true; std::array<uint32_t, testSize> testArrayMut{1,2,3}; // Compile time size + initialize from pointer + mutable { RView<uint32_t> view(testArrayMut.data(), testArrayMut.size()); success &= RunTests("Compile time size + initialize from pointer + mutable", view, testArrayMut); } // Compile time size + initialize from object + mutable { RView<uint32_t> view(testArrayMut); success &= RunTests("Compile time size + initialize from object + mutable", view, testArrayMut); } std::array<uint32_t, testSize> const testArrayConst{1,2,3}; // Compile time size + initialize from pointer + const { RView<uint32_t const> view(testArrayConst.data(), testArrayConst.size()); success &= RunTests("Compile time size + initialize from pointer + const", view, testArrayConst); } // Compile time size + initialize from object + const { RView<uint32_t const> view(testArrayConst); success &= RunTests("Compile time size + initialize from object + const", view, testArrayConst); } if (success) std::cout << "Everything works!" << std::endl; else std::cout << "Some tests failed!" << std::endl; return 0; }
Shell
UTF-8
1,801
3.75
4
[]
no_license
#!/bin/bash # description: Tools for React.js / Node.js - docker, docker-compose sysadmin (MERM stack) # Environment settings INSTALL_DIR=`echo $0 | sed 's/tools\.sh//g'` DOCKERCOMPOSE_BIN=`which docker-compose` ; DOCKER_BIN=`which docker` ; #SH_BIN =`which sh` ; set -x removeAllFromDocker() { echo "Stop all containers.." $DOCKER_BIN stop `docker ps -qa` echo "Remove all containers.." $DOCKER_BIN rm `docker ps -qa` echo "Remove all images.." $DOCKER_BIN rmi -f `docker images -qa ` $DOCKER_BIN volume rm $(docker volume ls -qf dangling=true) echo "Containes left.." $DOCKER_BIN ps -a } rebuildEnvironment() { $DOCKERCOMPOSE_BIN --file ./docker-compose.yml stop echo "Build images.." $DOCKERCOMPOSE_BIN --file ./docker-compose.yml build echo "Check images.." $DOCKER_BIN image ls --no-trunc echo "Up containers.." $DOCKERCOMPOSE_BIN --file ./docker-compose.yml up -d $DOCKER_BIN ps } deployCode() { $DOCKER_BIN exec -it frontend rm -rf /usr/src/build $DOCKER_BIN exec -i frontend mkdir /usr/src/build $DOCKER_BIN exec -i frontend ls -lasht /usr/src/build $DOCKERCOMPOSE_BIN --file ./docker-compose.yml stop $DOCKERCOMPOSE_BIN --file ./docker-compose.yml rm $DOCKERCOMPOSE_BIN --file ./docker-compose.yml build $DOCKERCOMPOSE_BIN --file ./docker-compose.yml up -d } case "$1" in removeAllFromDocker) removeAllFromDocker echo "Remove All From Docker complete.." ;; rebuildEnvironment) rebuildEnvironment echo "Rebuild Environment complete.." ;; *) echo " SYNOPSIS sh bin/tools.sh sh bin/tools.sh [-- [OPTIONS...]] [-- [ENVIRONMENT...]] OPTIONS rebuildEnvironment Re-build environment removeAllFromDocker Remove all docker and start from scratch " >&2 exit 1 ;; esac
Python
UTF-8
414
3.765625
4
[]
no_license
def append_length(lst=[]): lst.append(len(lst)) return lst print(append_length([1, 2])) # [1, 2, 2] print(append_length()) # [0] print(append_length()) # [0, 1] def fact(x, cache={0: 1}): print(f" fact({x})") if x not in cache: cache[x] = x * fact(x - 1) return cache[x] print(f"fact(5) = {fact(5)}") print(f"fact(5) = {fact(5)}") print(f"fact.__defaults__ = {fact.__defaults__}")
Python
UTF-8
3,997
2.578125
3
[ "MIT" ]
permissive
import logging import torch import pandas as pd from torch.utils.data import DataLoader, Dataset import torch from functools import partial logging.basicConfig(level=logging.INFO) # BAD: this should not be global # tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased") def get_dataloader(tokenizer, data_path, batch_size, max_seq_len): dataset = TextDataset(tokenizer=tokenizer, data_path=data_path) dataloader = DataLoader( dataset, batch_size=batch_size, # 20, drop_last=True, shuffle=True, num_workers=1, collate_fn=partial(TextDataset.collate_pad, cutoff=max_seq_len), ) while True: for batch in dataloader: yield batch class TextDataset(Dataset): def __init__( self, tokenizer, data_path: str, has_labels: bool = False ) -> None: super().__init__() self.data_path = data_path self.tokenizer = tokenizer self.read_data() if has_labels: self.read_labels() def read_data(self): logging.info("Reading data from {}".format(self.data_path)) data = pd.read_csv(self.data_path, sep="\t", header=None) # read text file logging.info(f"Tokenizing {len(data)} sentences") self.text = data[0].apply(lambda x: x.strip()).tolist() # encoded_input = self.tokenizer(self.questions, self.paragraphs) # check if tokenizer has a method 'encode_batch' if hasattr(self.tokenizer, 'encode_batch'): encoded_input = self.tokenizer.encode_batch(self.text) self.input_ids = [x.ids for x in encoded_input] else: encoded_input = self.tokenizer(self.text) self.input_ids = encoded_input["input_ids"] def read_labels(self): self.labels = pd.read_csv(self.data_path, sep="\t", header=None)[1].tolist() # check if labels are already numerical self.labels = [str(x) for x in self.labels] if isinstance(self.labels[0], int): return # if not, convert to numerical all_labels = sorted(list(set(self.labels))) self.label_to_idx = {label: i for i, label in enumerate(all_labels)} self.idx_to_label = {i: label for i, label in self.label_to_idx.items()} self.labels = [self.label_to_idx[label] for label in self.labels] def __len__(self) -> int: return len(self.text) def __getitem__(self, i): out_dict = { "input_ids": self.input_ids[i], # "attention_mask": [1] * len(self.input_ids[i]), } if hasattr(self, "labels"): out_dict["label"] = self.labels[i] return out_dict @staticmethod def collate_pad(batch, cutoff: int): max_token_len = 0 num_elems = len(batch) # batch[0] -> __getitem__[0] --> returns a tuple (embeddings, out_dict) for i in range(num_elems): max_token_len = max(max_token_len, len(batch[i]["input_ids"])) max_token_len = min(cutoff, max_token_len) tokens = torch.zeros(num_elems, max_token_len).long() tokens_mask = torch.zeros(num_elems, max_token_len).long() has_labels = False if "label" in batch[0]: labels = torch.zeros(num_elems).long() has_labels = True for i in range(num_elems): toks = batch[i]["input_ids"] length = len(toks) tokens[i, :length] = torch.LongTensor(toks) tokens_mask[i, :length] = 1 if has_labels: labels[i] = batch[i]["label"] # TODO: the first return None is just for backward compatibility -- can be removed if has_labels: return None, {"input_ids": tokens, "attention_mask": tokens_mask, "labels": labels} else: return None, {"input_ids": tokens, "attention_mask": tokens_mask}
TypeScript
UTF-8
2,458
2.515625
3
[ "BSD-3-Clause" ]
permissive
/* Language: YAML Author: Stefan Wienert <stwienert@gmail.com> Requires: ruby.js Description: YAML (Yet Another Markdown Language) Category: config */ import { LanguageDef } from '../types'; import { BACKSLASH_ESCAPE, UNDERSCORE_IDENT_RE, HASH_COMMENT_MODE, C_NUMBER_MODE } from '../common'; const LITERALS = 'true false yes no null'; const keyPrefix = '^[ \\-]*'; const keyName = '[a-zA-Z_][\\w\\-]*'; const KEY = { className: 'attr', variants: [ { begin: keyPrefix + keyName + ":" }, { begin: keyPrefix + '"' + keyName + '"' + ":" }, { begin: keyPrefix + "'" + keyName + "'" + ":" } ] }; const TEMPLATE_VARIABLES = { className: 'template-variable', variants: [ { begin: '\{\{', end: '\}\}' }, // jinja templates Ansible { begin: '%\{', end: '\}' } // Ruby i18n ] }; const STRING = { className: 'string', relevance: 0, variants: [ { begin: /'/, end: /'/ }, { begin: /"/, end: /"/ }, { begin: /\S+/ } ], contains: [ BACKSLASH_ESCAPE, TEMPLATE_VARIABLES ] }; export const YAML: LanguageDef = { name: 'yaml', case_insensitive: true, aliases: ['yml', 'YAML', 'yaml'], contains: [ KEY, { className: 'meta', begin: '^---\s*$', relevance: 10 }, { // multi line string className: 'string', begin: '[\\|>] *$', returnEnd: true, contains: STRING.contains, // very simple termination: next hash key end: KEY.variants[0].begin }, { // Ruby/Rails erb begin: '<%[%=-]?', end: '[%-]?%>', subLanguage: 'ruby', excludeBegin: true, excludeEnd: true, relevance: 0 }, { // data type className: 'type', begin: '!!' + UNDERSCORE_IDENT_RE, }, { // fragment id &ref className: 'meta', begin: '&' + UNDERSCORE_IDENT_RE + '$', }, { // fragment reference *ref className: 'meta', begin: '\\*' + UNDERSCORE_IDENT_RE + '$' }, { // array listing className: 'bullet', begin: '^ *-', relevance: 0 }, HASH_COMMENT_MODE, { beginKeywords: LITERALS, keywords: { literal: LITERALS } }, C_NUMBER_MODE, STRING ] };
Markdown
UTF-8
7,256
3.015625
3
[]
no_license
# So you want to delete your old tweets Great! The setup process may seem like a lot of steps, but it's not that hard and should only take you 15-20 minutes. Unfortunately, that's the trade-off of doing things yourself instead of letting a service to do it for you. It's mostly just filling out forms and clicking buttons, though, so don't worry. If you look at the left you'll see a list of files. Most of them are the code necessary to make this app work – you can ignore those (unless you're interested!). You'll also see `README.md` highlighted. That's the instructions file that you're looking at right now, and the highlight means it's open. Sometimes these instructions will link out to a page for you to go and do things. I recommend you open all links in a new tab so you always have the instructions open. If you forget, though, you can always use the back button in your browser, or go to <a href="https://glitch.com" target="_blank">glitch.com</a> and click the "Resume Coding" button in the top right. That will bring you back here again. If you have any issues or questions, feel free to reach out to me on Twitter <a href="https://twitter.com/ryangiglio" target="_blank">@ryangiglio</a> and I'll help you out. ## Setup ### (Optional) Sign up for Glitch You _can_ setup and run this app without signing up for Glitch, but if there's an issue and you need to come back later and resume deleting, making an account will make sure your stuff is saved and that it picks up from where it left off. Up to you! 1. Click Sign In at the top of this page 2. Log in with Facebook or Github. If you don't have either one, it's very quick to sign up for Github on the Free plan. _If your Twitter is anonymous, don't worry, your login account won't be linked to it in any way._ ### Register with Twitter as a developer _If you're already registered as a developer, skip to the next section._ 1. Go to the <a href="https://developer.twitter.com" target="_blank">Twitter developer portal</a> 2. Click "Apply" in the top right, and then the "Apply For A Developer Account" button _You need to have a developer account in order to access Twitter's API, which is how this app deletes your tweets._ 3. If you don't have a verified phone number on your account, Twitter will ask you to add one. _Twitter requires developers to have a verified phone number to have a point of contact in case of abuse. If you're not comfortable giving them your real phone number, there are a number of services that let you generate temporary phone numbers, although I can't vouch for any of them and it seems risky to permanently tie your account to a burner number. Your best bet is probably to add your real phone number and then if you want, remove it from your account when you're done using this app._ 4. Click "Continue" to associate your current username. 5. Select "I am requesting access for my own personal use." Fill in your Twitter username and select your country. Click "Continue". 6. Select "Other" as your use case. In the "Describe in your own words what you're building" box, feel free to enter your own explanations or erase the pre-filled numbers and copy/paste this text that already meets their minimum text requirement. These are true answers to the four questions they ask you: ``` 1. I'm using Twitter's API to programmatically delete my own Twitter archive. 2. I do not plan to analyze Tweets, Twitter users, or their content. 3. I will not be Tweeting, Retweeting, or liking content. 4. I will not be displaying any data, I'm just using the API for programmatic access to my own tweets. ``` Choose "No" for the question about information being available to government entities. 7. Scroll through and accept the terms and conditions. If you feel like reading them, they're actually pretty plain English. 8. Twitter will now send you a verification email to complete your application. When you recieve it, click the "Confirm your email" button. ### Create an app and add the credentials to this project 1. Go to Twitter's <a href="https://developer.twitter.com/en/apps/create" target="_blank">create an app</a> page _The values you enter for steps 2, 3, and 4 don't actually matter for the functionality of this app, you're just naming a few things._ 2. Enter `(your username here) archive deleter` as the App name 3. Enter `Glitch Twitter archive deleter credentials` as the Application description 4. Enter `https://twitter.com` as the website URL 5. Scroll to the bottom of the page and copy/paste this text in the "Tell us how this app will be used" field ``` This app will be used to generate credentials that let me use the Twitter API on behalf of my own account. ``` 6. Press Create, and then press Create again on the popup 7. Click on the "Keys and tokens" tab at the top. Under the "Access token & access token secret" section, click the Create button 8. Open your `.env` file from the list on the left (it's the one with the little key). Copy your Consumer API Key, Consumer API Secret Key, Access Token, and Access Token Secret from the Twitter app page and paste them into the `.env` file after each `=`. It should look like this, with your values filled in: ``` TWITTER_CONSUMER_API_KEY=Pqhe6a6rSFb4vfCun7sYyDWOA TWITTER_CONSUMER_API_SECRET_KEY=HfTfQc0lFm33T3Ixfv4cCmRj0k6daT9iSa6DF2n3H6qwZ4lWai TWITTER_ACCESS_TOKEN=12345678-AzNwMwPGtNehMvf86ChlhYuowX95Bw7BBbpmFm2qw TWITTER_ACCESS_TOKEN_SECRET=ym62oXokuSH5f7jqw18Mr7LuwCaifQHaFIQUtcoeC8QZL ``` ### Download your Twitter archive 1. Go to your <a href="https://twitter.com/settings/account" target="_blank">Twitter account settings</a> 2. Scroll down to "Your Tweet archive" and click the "Request your archive" button 3. Wait to get an email from Twitter. It takes longer if you have a lot of tweets, but in my experience not usually more than an hour 4. Follow the link in your email and download your archive from the page 5. Unzip the archive (it'll have a long name of letters and numbers) and open the folder 6. Drag and drop the `tweets.csv` file into this window. You'll see a bunch of numbers and symbols – that's the content of the csv. You'll also see tweets.csv show up in the sidebar to the left. ### (Optional) Specify any tweets you don't want deleted If you have some Tweets you just can't bear to part with, you can add them as exceptions so they don't get deleted along with the rest. 1. Go to the tweet on <a href="https://twitter.com" target="_blank">twitter.com</a> and click on it. 2. In the URL bar at the top of your browser, you should see `https://twitter.com/username/status/#####`. Copy all of those numbers at the end - this is the Tweet ID. 3. Open the file `config/default.js` in the list of files on the left. 4. Inside the `[ ]` brackets, add a new line with the Tweet ID in single quotes followed by a comma at the end, the same as `'1234567890',`. 5. Repeat for as many Tweets as you want to save. The final file should look like this: ``` module.exports = { savedTweets: [ '1234567890', '###########', '###########', '###########', ], } ``` ### You're done with setup! Hopefully that wasn't too hard! Once you're done with setup, click the `Show` button at the top of this page next to the cool sunglasses to move on to the last step.
Java
UTF-8
7,950
2.3125
2
[]
no_license
/******************************************************************************* * Copyright (c) 2009, 2017 Mountainminds GmbH & Co. KG and Contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marc R. Hoffmann - initial API and implementation * *******************************************************************************/ package org.jacoco.core.internal.flow; import org.objectweb.asm.Label; /** * Data container that is attached to {@link Label#info} objects to store flow * and instrumentation specific information. The information is only valid * locally in specific contexts. */ public final class LabelInfo { /** * Reserved ID for "no probe". */ public static final int NO_PROBE = -1; private boolean target = false; private boolean multiTarget = false; private boolean successor = false; private boolean methodInvocationLine = false; private boolean done = false; private int probeid = NO_PROBE; private Label intermediate = null; private Instruction instruction = null; // instances are only created within this class private LabelInfo() { } /** * Defines that the given label is a jump target. * * @param label * label to define */ public static void setTarget(final Label label) { final LabelInfo info = create(label); if (info.target || info.successor) { info.multiTarget = true; } else { info.target = true; } } /** * Defines that the given label is the possible successor of the previous * instruction in the method. * * @param label * label to define */ public static void setSuccessor(final Label label) { final LabelInfo info = create(label); info.successor = true; if (info.target) { info.multiTarget = true; } } /** * Checks whether multiple control paths lead to a label. Control flow path * to a certain label are: jump targets, exception handlers and normal * control flow from its predecessor instruction (unless this is an * unconditional jump or method exit). * * @param label * label to check * @return <code>true</code> if the given multiple control paths lead to the * given label */ public static boolean isMultiTarget(final Label label) { final LabelInfo info = get(label); return info == null ? false : info.multiTarget; } /** * Checks whether this label is the possible successor of the previous * instruction in the method. This is the case if the predecessor isn't a * unconditional jump or method exit instruction. * 判断该label是否是一个指令的后任者 *如果是goto之类的无状态jump和函数exit指令就是true,这里是为了防止不知上述指令的情况 * @param label * label to check * @return <code>true</code> if the label is a possible instruction * successor */ public static boolean isSuccessor(final Label label) { final LabelInfo info = get(label); return info == null ? false : info.successor; } /** * Mark a given label as the beginning of a line with method invocations. * * @param label * label to mark */ public static void setMethodInvocationLine(final Label label) { create(label).methodInvocationLine = true; } /** * Checks whether the a given label has been marked as a line with method * invocations. * * @param label * label to check * @return <code>true</code> if the label represents a line with method * invocations */ public static boolean isMethodInvocationLine(final Label label) { final LabelInfo info = get(label); return info == null ? false : info.methodInvocationLine; } /** * Determines whether the given label needs a probe to be inserted before. * * @param label * label to test * @return <code>true</code> if a probe should be inserted before */ public static boolean needsProbe(final Label label) { final LabelInfo info = get(label); return info != null && info.successor && (info.multiTarget || info.methodInvocationLine); } /** * Mark a given label as done. * * @param label * label to mark */ public static void setDone(final Label label) { create(label).done = true; } /** * Resets the "done" status of a given label. * * @param label * label to reset */ public static void resetDone(final Label label) { //即:LabelInfo info=label.info final LabelInfo info = get(label); if (info != null) { //设置label.info的done属性为false info.done = false; } } /** * Resets the "done" status of all given labels. * * @param labels * labels to reset */ public static void resetDone(final Label[] labels) { for (final Label label : labels) { resetDone(label); } } /** * Checks whether this label is marked as done. * * @param label * label to check * @return <code>true</code> if this label is marked as done */ public static boolean isDone(final Label label) { final LabelInfo info = get(label); return info == null ? false : info.done; } /** * Sets the given probe id to the given label. * * @param label * label to assign a probe to * @param id * id of the probe */ public static void setProbeId(final Label label, final int id) { create(label).probeid = id; } /** * Returns the assigned probe id. * * @param label * label to check * @return probe id or {@link #NO_PROBE} if no probe is assigned to the * label */ //返回该label的probeID,如果没有 public static int getProbeId(final Label label) { final LabelInfo info = get(label); return info == null ? NO_PROBE : info.probeid; } /** * Defines an intermediate label for the given label. Such intermediate * labels are required during instrumentation to add probes to jump targets. * * @param label * label to define for * @param intermediate * intermediate label */ public static void setIntermediateLabel(final Label label, final Label intermediate) { create(label).intermediate = intermediate; } /** * Returns the intermediate label for the given label if one has been * defined. * * @param label * label to look for * @return intermediate label or <code>null</code> */ public static Label getIntermediateLabel(final Label label) { final LabelInfo info = get(label); return info == null ? null : info.intermediate; } /** * Sets the instruction corresponding to this label. * * @param label * label to set the instruction for * @param instruction * corresponding instruction */ public static void setInstruction(final Label label, final Instruction instruction) { create(label).instruction = instruction; } /** * Returns the corresponding instruction for the given label if one has been * defined. * * @param label * label to look for * @return corresponding instruction or <code>null</code> */ public static Instruction getInstruction(final Label label) { final LabelInfo info = get(label); return info == null ? null : info.instruction; } //判断label合法?合法输出label.info private static LabelInfo get(final Label label) { final Object info = label.info; //a?b:c //a为真,输出b;a为假,输出c //a instanceof b //若a是b的实例,输出true;a不是b的实例,输出false return info instanceof LabelInfo ? (LabelInfo) info : null; } private static LabelInfo create(final Label label) { LabelInfo info = get(label); if (info == null) { info = new LabelInfo(); label.info = info; } return info; } }
Ruby
UTF-8
4,726
3.375
3
[ "MIT" ]
permissive
require 'json' require 'erubis' module Jaspion module Kilza # Represents an program language module Language # Array with all Class classes attr_accessor :classes # Name used to represent the first generated class attr_accessor :base_name # JSON that will be used to generate objects attr_accessor :json_string # Words that will receive an undescore before property name attr_accessor :reserved_words # Array with all properties that will be used to compare other objects attr_accessor :equal_keys # Hash table with all language types mapped to target language attr_accessor :types # Initializes the language # If json_string is not a Hash {}, it will surroud the json with # { "base_name"} = json_string # # @param json_string [String] JSON String # def initialize(json_string) @json_string = json_string @classes = [] @types = {} @reserved_words = [] @equal_keys = [] end # Returns all available classes # # @param base_name [String] First class name # # @return [Array] All available classes def classes(base_name) @classes = [] hash = JSON.parse(json_string) hash = { base_name + 'Object' => hash } if hash.is_a?(Array) parse_hash(base_name, hash) @classes end protected # Creates a new Class object and checks for valid name # # @param name [String] name of the class to be created # # @return [Kilza::Class] new class def clazz(name) # cl_name = self.class.name.split('::').last # cl = Jaspion::Kilza.const_get("#{cl_name}::Class") # return cl.new(name) unless cl.nil? # Class.new(name) end # Creates a new Property object and checks for valid name # # @param name [String] name of the property to be created # @param type [String] type of the property based on class name # @param array [Boolean] indicates if this property represents an array # @param key [Boolean] indicates if this property can be used to compare # objects # # @return [Kilza::Property] new property def property(name, type, array, key) original_name = name prop = Property.new(name , type, array, key) prop.original_name = original_name prop end # Searches for a Kilza::Class inside @classes # and creates a new one if it could not be found # # @param name [String] class name to find # # @return [Kilza::Class] class with the specified name def find(name) name = Jaspion::Kilza::Class::normalize(name) @classes.each { |cl| return cl if cl.name == name } @classes.push(clazz(name)) @classes.last end # Parses an element value an verify if it should create a new Classs # inside @classes # # @param class_name [String] Name of the class the element is inside # @param name [String] The element name # @param value [Any] The element value # @param array [Boolean] Indicates the element is inside an Array def parse_el(class_name, name, value, array = false) type = value.class.name.split('::').last.downcase return parse_array(class_name, name, value) if type == 'array' cur_class = find(class_name) key = @equal_keys.index(name).nil? ? false : true cur_class.push(property(name, type, array, key)) # if value is nil, consider it as an Object find(name) if type == 'nilclass' parse_hash(name, value) if type == 'hash' end # Parses an hash calling parse_el for each element # # @param class_name [String] Name of the class the hash is inside # @param hash [Hash] The hash value def parse_hash(class_name, hash) hash.each do |property_name, value| parse_el(class_name, property_name, value) end end # Parses an element that represents an array calling parse_el # for each element. # If the array is empty, it creates a new class to represent # each array's element. # # @param class_name [String] Name of the class the array is inside # @param name [String] The element name # @param value [Any] The element value def parse_array(class_name, name, value) if value.length == 0 parse_el(class_name, name, nil, true) else value.each do |val| parse_el(class_name, name, val, true) end end end end end end
Java
UTF-8
1,141
2.109375
2
[ "Apache-2.0" ]
permissive
package com.springsource.insight.plugin.webflow; import static org.junit.Assert.assertNotNull; import org.junit.Test; import com.springsource.insight.collection.OperationCollectionAspectSupport; import com.springsource.insight.collection.OperationCollectionAspectTestSupport; import com.springsource.insight.intercept.operation.Operation; import com.springsource.insight.plugin.webflow.ActionOperationCollectionAspect; public class ActionOperationCollectionAspectTest extends OperationCollectionAspectTestSupport { @Test public void test1() { // Step 1: Execute test WebFlowExecutionTest webFlow=new WebFlowExecutionTest(); webFlow.testAction(); // Step 2: Get the Operation that was just created by our aspect Operation op = getLastEntered(); // Step 3: Validate assertNotNull(op); assert op.getType().getName().equals("wf-action"); assertNotNull(op.get("action")); assert "flowScope.person=personDao.findPersonById(id)".equals(op.get("action")); } @Override public OperationCollectionAspectSupport getAspect() { return ActionOperationCollectionAspect.aspectOf(); } }
C#
UTF-8
2,305
3.484375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace snake { struct Position { public int X; public int Y; public Position(int x,int y) { this.X = x; this.Y = y; } } class Program { static void Main(string[] args) { Position[] directions = new Position[] { new Position(0,1), new Position(0,-1), new Position(1,0), new Position(-1,0), }; int direction = 0; Queue<Position>Elements=new Queue<Position>(); for (int i = 0; i < 5; i++) { Elements.Enqueue(new Position(0, i)); } foreach (var Position in Elements) { Console.SetCursorPosition(Position.Y, Position.X); Console.WriteLine("0"); } while (true) { ConsoleKeyInfo userInput = Console.ReadKey(); if (userInput.Key==ConsoleKey.LeftArrow) { direction = 1; } if (userInput.Key == ConsoleKey.RightArrow) { direction = 0; } if (userInput.Key == ConsoleKey.UpArrow) { direction = 3; } if (userInput.Key == ConsoleKey.DownArrow) { direction = 2; } Position head = Elements.Last(); Elements.Dequeue(); Position newDirection=directions[direction]; Position newHead = new Position(head.X + newDirection.X,head.Y+newDirection.Y); Elements.Enqueue(newHead); Console.Clear(); foreach (var Position in Elements) { Console.SetCursorPosition(Position.Y, Position.X); Console.WriteLine("0"); } } } } }
PHP
UTF-8
4,727
2.859375
3
[]
no_license
<?php use \Psr\Http\Message\ServerRequestInterface as Request; use \Psr\Http\Message\ResponseInterface as Response; require 'vendor/autoload.php'; $app = new \Slim\App; //$app = new \Slim\App(['settings' => ['displayErrorDetails' => true]]); function getDB() { $dbhost = "pajaros.com"; $dbname = "pajaros"; $dbuser = "pajaros"; $dbpass = "root"; //Resolviendo problema de codificacion utf-8 $options = array( PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8', ); $mysql_conn_string = "mysql:host=$dbhost;dbname=$dbname"; $dbConnection = new PDO($mysql_conn_string,$dbuser,$dbpass,$options); $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $dbConnection; } $app->get('/', function (Request $request, Response $response) { $response->write('Bienvenido'); return $response; }); /* Return all pajaros */ $app->get('/all', function (Request $request, Response $response) { try{ $db = getDB(); $sth = $db->prepare("SELECT id, titulo, pajaro, veces FROM avistamientos"); $sth->execute(); $pajaros = $sth->fetchAll(PDO::FETCH_ASSOC); if($pajaros) { $response = $response->withJson($pajaros); $db = null; //cerramos la conexion con la BD }else{ return $response->withJson(['message'=>'Not results found','code'=>'404']); } }catch(PDOException $e) { $response->withJson(['error'=>['texto'=>$e->getMessage()]]); } return $response; }); /* Return one pajaro by id */ $app->get('/one/{id}', function (Request $request, Response $response, $args) { try{ $db = getDB(); $sth = $db->prepare("SELECT * FROM avistamientos WHERE id = :id"); $sth->bindParam(":id", $args['id'], PDO::PARAM_INT); $sth->execute(); $pajaros = $sth->fetchAll(PDO::FETCH_ASSOC); if($pajaros) { $response = $response->withJson(['data'=>$pajaros]); $db = null; //cerramos la conexion con la BD }else{ return $response->withJson(['message'=>'Not results found','code'=>'404']); } }catch(PDOException $e) { $response->withJson(['error'=>['texto'=>$e->getMessage()]]); } return $response; }); /* Update pajaro with put */ $app->put('/updateVeces', function ($request, $response) { try{ $data = $request->getParams(); $db = getDB(); $sth = $db->prepare("UPDATE avistamientos SET veces=?, lastview=? WHERE id=?"); $sth->execute(array($data['veces'], $data['lastview'], $data['id'])); $response = $response->withJson(['message'=>'Update success','code'=>'200']); }catch(PDOException $e) { $response->withJson(['error'=>['texto'=>$e->getMessage()]]); } return $response; }); /* Update pajaro with put */ $app->put('/update', function ($request, $response) { try{ $data = $request->getParams(); $db = getDB(); $sth = $db->prepare("UPDATE avistamientos SET titulo=?, pajaro=? WHERE id=?"); $sth->execute(array($data['titulo'], $data['pajaro'], $data['id'])); $response = $response->withJson(['message'=>'Update success','code'=>'200']); }catch(PDOException $e) { $response->withJson(['error'=>['texto'=>$e->getMessage()]]); } return $response; }); /* Create new pajaro */ $app->post('/update', function ($request, $response) { try{ $data = $request->getParams(); $db = getDB(); $sth = $db->prepare("INSERT INTO avistamientos (titulo, pajaro, lastview, veces, latitud, longitud) VALUES(?,?,?,?,?,?)"); $sth->execute(array($data['titulo'], $data['pajaro'], $data['lastview'], $data['veces'],$data['latitud'],$data['longitud'])); $response = $response->withJson(['message'=>'Update success','code'=>'200']); }catch(PDOException $e) { $response->withJson(['error'=>['texto'=>$e->getMessage()]]); } return $response; }); /* Kill pajaro x_x */ $app->delete('/delete/{id}', function ($request, $response, $args) { try{ $db = getDB(); $sth = $db->prepare("DELETE FROM avistamientos WHERE id=:id"); $sth->bindParam(":id", $args['id'], PDO::PARAM_INT); $sth->execute(); $response = $response->withJson(['message'=>'Delete success','code'=>'200']); }catch(PDOException $e) { $response->withJson(['error'=>['texto'=>$e->getMessage()]]); } return $response; }); $app->run();
Markdown
UTF-8
7,074
3.109375
3
[ "Apache-2.0", "MIT" ]
permissive
<div style="text-align:center"><img src="https://raw.githubusercontent.com/sopra-fs21-group-4/client/master/src/image/logo/doyouevenmeme.png"/></div> [toc] # Project-Description In this game players submit titles for images and gifs that are collected from a specified Subreddit. A normal game flow looks something like this. 1. A user creates a game and enters a Subreddit. 2. With the Reddit API the game master can define what type of memes are taken. For example these are the last 25 currently best posts of subreddit r/memes: https://www.reddit.com/r/memes/top.json 3. Because Reddit gives the possibility to filter the posts for specific parameters like time or upvotes we can give the users the possibility to set those. (hot/rising/new/etc.) 4. Other players join the game 5. The game begins, and a meme is shown to all users. Those users have to enter a title that they find funny and fitting 6. As soon as the time is up all players vote on which is the best title for the meme. Then the players receive points according to the votes recieved. Steps 5 and 6 get repeated until the total number of rounds are played. # Technologies The client is written in JavaScript using React. To establish a connection between the front- and backend REST is used. # High-Level Components ## GameList The [GameList](https://github.com/sopra-fs21-group-4/client/blob/master/src/components/lobby/GameList.js) and [GameInfoItem](https://github.com/sopra-fs21-group-4/client/blob/master/src/components/lobby/GameInfoItem.js) display all currently open lobbies. To implement this we used REST-Requests to update the list. When a User clicks on a open lobby the user then gets forwarded to the game. Where they then either have to enter the lobby password or if no password was set they just enter the lobby. ## GameRound The [GameRunning](https://github.com/sopra-fs21-group-4/client/blob/master/src/components/game/GameRunnning.js) class implements what the user will see during the a round of the game. The class can advance between four states: * **STARTING**: in this state the players see the Meme but can't input anything yet. * **SUGGEST**: during this state every player can input their title * **VOTE**: while voting the players, can vote for a title (but not their own) * **AFTERMATH**: here the results will be displayed and the corresponding points are displayed. ## GameRoundSummary The [GameRoundSummary](https://github.com/sopra-fs21-group-4/client/blob/master/src/components/game/GameRoundSummary.js) is displayed when the game is over. It gets the data from the SSE-Emitter and then displays every round with the corresponding data. # Launch and Development * `npm run dev` Runs the app in the development mode.<br /> Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits.<br /> You will also see any lint errors in the console. * `npm run build` Builds the app for production to the `build` folder.<br /> It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified, and the filenames include the hashes.<br /> Your app is ready to be deployed! See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. # Screenshots ## Lobby creation Below you can see how a lobby can be set up and then will be displayed on the Dashboard. <div><img src="https://marock.li/cloud-storage/sopra.gif" width="250" allign="center"/></div> ## Login When visiting our project the user is prompted with a login/registration screen. ![login](https://marock.li/cloud-storage/login.png) ## Dashboard After the login the user is prompted with the dashboard. Where the user sees the currently open games and can create his own new game. ![login](https://marock.li/cloud-storage/dashboard.png) ## Lobby When in game and waiting for players the Entity master sees the below screen. Here he can edit the settings, chat with the other players, set their own status to ready or not ready and ban Players that he doesnt want in his game. The game then can only start, when at least 3 Players and at most the maximum amount of Players are in the Lobby. If this condidition is met every player needs to be ready then the game will automatically start. ![login](https://marock.li/cloud-storage/lobby.png) ## In Entity During the game there are three different phases to the game. 1. The suggestion phase where every Player is prompted with the same meme. They then have a certain amount of time to think of a title and enter/submit it. If a player does not submit a title they will get points deducted for not entering a title. ![login](https://marock.li/cloud-storage/submitting.png) 2. After the time has run out all players can then vote for the titles that were submitted. A player can never vote for their own title. If a player does not vote or can not vote for a other title the player will also get point deducted. ![login](https://marock.li/cloud-storage/voting.png) 3. When the time has run out the points given will be calculated and displayed. After the time has run out the next round will start or if the last round just happened the Entity Summary will be displayed. ![login](https://marock.li/cloud-storage/results.png) # Roadmap 1. extend the resources where memes could be collected for the game 2. making sure that no meme is displayed to a player twice # Authors and Acknowledgments ## Authors The authors of this project are: [Florian Herzog](https://github.com/Stud-FH), [Aljoscha Schnider](https://github.com/plexinio), [Max-Zurbriggen](https://github.com/Max-Zurbriggen), [Cyrill Hidber](https://github.com/Aece96), [Philipp Marock](https://github.com/Sahibabdul) ## Acknowledgments We would like to thank our tutors for providing us with a starting point and continued support. Further we would like to thank our friends for testing our game and providing us with ideas for improvement. # License MIT License Copyright (c) [2021] [SoPra Group 04] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
JavaScript
UTF-8
286
2.609375
3
[ "MIT" ]
permissive
export function formatAmount(value) { Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(value) return value } export function formatDate(date) { const splittedDate = date.split("-") return `${splittedDate[2]}/${splittedDate[1]}/${splittedDate[0]}` }
C
UTF-8
2,246
3.09375
3
[ "MIT" ]
permissive
#define NADA 0 #define NUMERO 1 #define INCORRECTO 2 #define FIN 3 #define CONTEO 0 #define ALMACEN 1 typedef struct entrada { int cont, max, acc, size; char estado, op; } VEC_IN; void eval_est(VEC_IN *v, char c, int *in_min) { switch (v->estado) { case NADA: if (c >= '0' && c <= '9') { v->estado = NUMERO; if (v->op == ALMACEN) v->acc = c - '0'; break; } if (c == ' ') { v->estado = NADA; break; } if (c == 0) { v->estado = FIN; break; } v->estado = INCORRECTO; break; case NUMERO: if (c >= '0' && c <= '9') { v->estado = NUMERO; if (v->op == ALMACEN) v->acc = v->acc * 10 + c - '0'; break; } if (c == ' ') { v->estado = NADA; if (v->op == ALMACEN) { in_min[v->cont] = v->acc; if (v->acc > v->max) v->max = v->acc; } v->cont++; break; } if (c == 0) { v->estado = FIN; if (v->op == ALMACEN) { in_min[v->cont] = v->acc; if (v->acc > v->max) v->max = v->acc; } v->cont++; break; } v->estado = INCORRECTO; break; default: break; } } int *scanint(VEC_IN *v, char *in_str) { int i, j; int *in_min; in_min = 0; i = 0; v->cont = 0; v->max = 0; v->estado = NADA; v->op = CONTEO; v->size = 0; while (v->estado != FIN && v->estado != INCORRECTO) { eval_est(v, in_str[i], in_min); i++; } if (v->estado != INCORRECTO && v->cont > 0) { in_min = malloc(v->cont * sizeof(int)); v->op = ALMACEN; v->estado = NADA; i = 0; v->cont = 0; while (v->estado != FIN) { eval_est(v, in_str[i], in_min); i++; } if (v->cont > 0) { i = 0x0001; for (j = 0; j <= 15; j++) { if (i & v->max) v->size = j; i = i << 1; } v->size++; } else v->size = 0; } return in_min; }
C++
UTF-8
3,099
2.578125
3
[]
no_license
// // Created by sttony on 5/16/23. // #include <QVBoxLayout> #include <QFileDialog> #include "MainWindow.h" #include "CNoteBook.h" void MainWindow::contextMenuEvent(QContextMenuEvent *event) { QMainWindow::contextMenuEvent(event); } MainWindow::MainWindow() { auto *widget = new QWidget; setCentralWidget(widget); auto *centralWidget = new QWidget(this); this->setCentralWidget(centralWidget); // Create a horizontal layout auto* layout = new QHBoxLayout; m_treeWidget = new QTreeWidget; auto *item1 = new QTreeWidgetItem(m_treeWidget, QStringList("Item 1")); auto *item2 = new QTreeWidgetItem(m_treeWidget, QStringList("Item 2")); auto *item3 = new QTreeWidgetItem(item2, QStringList("Item 3")); m_treeWidget->setColumnCount(1); m_treeWidget->setHeaderLabels(QStringList("Tree Widget")); auto* label = new QLabel("Label"); layout->addWidget(m_treeWidget, 3); layout->addWidget(label, 7); centralWidget->setLayout(layout); createActions(); createMenus(); // QString message = tr("A context menu is available by right-clicking"); // statusBar()->showMessage(message); // setWindowTitle(tr("Menus")); // setMinimumSize(160, 160); resize(800, 600); } void MainWindow::newFile() { } void MainWindow::open() { QString filePath = QFileDialog::getExistingDirectory(nullptr, "Open Directory", ""); // Check if a file was selected if (filePath.isEmpty()) { } CNoteBook::Open(filePath.toStdString()); this->updateOnNewNotebook(); } void MainWindow::save() { } void MainWindow::createActions() { newAct = new QAction(tr("&New"), this); newAct->setShortcuts(QKeySequence::New); newAct->setStatusTip(tr("Create a new file")); connect(newAct, &QAction::triggered, this, &MainWindow::newFile); openAct = new QAction(tr("&Open"), this); openAct->setShortcuts(QKeySequence::Open); openAct->setStatusTip(tr("Open a existing file")); connect(openAct, &QAction::triggered, this, &MainWindow::open); } void MainWindow::createMenus() { fileMenu = menuBar()->addMenu(tr("&File")); fileMenu->addAction(newAct); fileMenu->addAction(openAct); // fileMenu->addAction(saveAct); // fileMenu->addAction(printAct); fileMenu->addSeparator(); // fileMenu->addAction(exitAct); } void MainWindow::undo() { } void MainWindow::print() { } void MainWindow::bold() { } void MainWindow::copy() { } void MainWindow::setParagraphSpacing() { } void MainWindow::aboutQt() { } void MainWindow::setLineSpacing() { } void MainWindow::rightAlign() { } void MainWindow::about() { } void MainWindow::center() { } void MainWindow::justify() { } void MainWindow::leftAlign() { } void MainWindow::italic() { } void MainWindow::paste() { } void MainWindow::redo() { } void MainWindow::cut() { } void MainWindow::updateOnNewNotebook() { m_NoteBook = CNoteBook::getCurrentInstance(); this->setWindowTitle(m_NoteBook->GetFileName().c_str()); m_treeWidget->setHeaderLabels(QStringList(m_NoteBook->GetName().c_str())); }
PHP
UTF-8
1,313
3
3
[ "MIT" ]
permissive
<?php namespace HMorm; class Log { private static $path = ''; public function __construct($setPath = "") { self::$path = self::$path ? self::$path : ($setPath ? $setPath : "./runtime/log/"); } public static function setLogPath($path) { self::$path = $path; } public function write($message, $fileSalt) { $date = new \DateTime(); $log = self::$path ."/". $date->format('Y-m-d') . "-" . md5($date->format('Y-m-d') . $fileSalt) . ".txt"; if (is_dir(self::$path)) { if (!file_exists($log)) { $fh = fopen($log, 'a+') or die("Fatal Error !"); $logcontent = "Time : " . $date->format('H:i:s') . "\r\n" . $message . "\r\n"; fwrite($fh, $logcontent); fclose($fh); } else { $this->edit($log, $date, $message); } } else { if (mkdir(self::$path, 0777, true) === true) { $this->write($message, $fileSalt); } } } private function edit($log, $date, $message) { $logcontent = "Time : " . $date->format('H:i:s') . "\r\n" . $message . "\r\n\r\n"; $logcontent = $logcontent . file_get_contents($log); file_put_contents($log, $logcontent); } }
C++
UTF-8
876
3.1875
3
[ "MIT" ]
permissive
// // Created by 정현민 on 2021/03/31. // #include "string_handler.h" std::vector<std::string> StringHandler::SplitString(const std::string &original_string, char delimiter) { std::vector<std::string> sub_strings; std::stringstream string_stream(original_string); std::string temp; while (getline(string_stream, temp, delimiter)) { if (!temp.empty()) { sub_strings.push_back(temp); } } return sub_strings; } int StringHandler::StringToInteger(const std::string &original_string) { for (int i = 0; i < original_string.size(); ++i) { if (!std::isdigit(original_string[i])) return -1; } return std::stoi(original_string); } std::string StringHandler::IntegerToString(const int &original_int) { return std::to_string(original_int); } StringHandler::StringHandler() = default;
SQL
UTF-8
3,936
3.203125
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 5.0.3 -- https://www.phpmyadmin.net/ -- -- Máy chủ: localhost -- Thời gian đã tạo: Th10 30, 2020 lúc 07:35 AM -- Phiên bản máy phục vụ: 10.4.14-MariaDB -- Phiên bản PHP: 7.2.34 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; 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 */; -- -- Cơ sở dữ liệu: `account` -- -- -------------------------------------------------------- -- -- Cấu trúc bảng cho bảng `account` -- CREATE TABLE `account` ( `idA` int(255) NOT NULL, `username` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `name` varchar(255) NOT NULL, `age` varchar(255) NOT NULL, `email` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Đang đổ dữ liệu cho bảng `account` -- INSERT INTO `account` (`idA`, `username`, `password`, `name`, `age`, `email`) VALUES (1, 'thanh@abc.com', 'thanh', 'thanh', '18', 'thanh@abc.com'); -- -------------------------------------------------------- -- -- Cấu trúc bảng cho bảng `account_bank_detail` -- CREATE TABLE `account_bank_detail` ( `idB` int(255) NOT NULL, `idA` int(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -------------------------------------------------------- -- -- Cấu trúc bảng cho bảng `account_role_detail` -- CREATE TABLE `account_role_detail` ( `idA` int(255) NOT NULL, `idRole` int(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -------------------------------------------------------- -- -- Cấu trúc bảng cho bảng `bank` -- CREATE TABLE `bank` ( `idB` int(255) NOT NULL, `name` int(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -------------------------------------------------------- -- -- Cấu trúc bảng cho bảng `role` -- CREATE TABLE `role` ( `IdRole` int(255) NOT NULL, `name` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Chỉ mục cho các bảng đã đổ -- -- -- Chỉ mục cho bảng `account` -- ALTER TABLE `account` ADD PRIMARY KEY (`idA`); -- -- Chỉ mục cho bảng `account_bank_detail` -- ALTER TABLE `account_bank_detail` ADD PRIMARY KEY (`idB`,`idA`), ADD KEY `Account_FK` (`idA`); -- -- Chỉ mục cho bảng `account_role_detail` -- ALTER TABLE `account_role_detail` ADD PRIMARY KEY (`idA`,`idRole`), ADD KEY `Role_FK` (`idRole`); -- -- Chỉ mục cho bảng `bank` -- ALTER TABLE `bank` ADD PRIMARY KEY (`idB`); -- -- Chỉ mục cho bảng `role` -- ALTER TABLE `role` ADD PRIMARY KEY (`IdRole`); -- -- AUTO_INCREMENT cho các bảng đã đổ -- -- -- AUTO_INCREMENT cho bảng `account` -- ALTER TABLE `account` MODIFY `idA` int(255) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT cho bảng `bank` -- ALTER TABLE `bank` MODIFY `idB` int(255) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT cho bảng `role` -- ALTER TABLE `role` MODIFY `IdRole` int(255) NOT NULL AUTO_INCREMENT; -- -- Các ràng buộc cho các bảng đã đổ -- -- -- Các ràng buộc cho bảng `account_bank_detail` -- ALTER TABLE `account_bank_detail` ADD CONSTRAINT `Account_FK` FOREIGN KEY (`idA`) REFERENCES `account` (`idA`), ADD CONSTRAINT `Bank_FK` FOREIGN KEY (`idB`) REFERENCES `bank` (`idB`); -- -- Các ràng buộc cho bảng `account_role_detail` -- ALTER TABLE `account_role_detail` ADD CONSTRAINT `Account_FK2` FOREIGN KEY (`idA`) REFERENCES `account` (`idA`), ADD CONSTRAINT `Role_FK` FOREIGN KEY (`idRole`) REFERENCES `role` (`IdRole`); 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 */;
Markdown
UTF-8
1,060
2.515625
3
[ "MIT" ]
permissive
<p align="center"><img src="https://raw.githubusercontent.com/Gamecrafter/PocketMine-Plugins/master/SkinTools/images/icon.png?raw=true"/></p> #SkinTools Skins have never been this fun to mess around with! ###Commands: Main command: **skintools**, **st** |Sub-command|Description| |-----------|-----------| |**file**|Saves the specified player's skin as a data file| |**help**|Shows all SkinTools commands| |**image**|Saves the specified player's skin as an image| |**morph**|Sets user's skin to that of the specified player's| |**restore**|Restores user's skin to the skin they joined with| |**swap**|Swaps skins with the specified player| |**touch**|Toggles touch mode| ###Permissions: |Node|Default| |----|:-------:| |skintools.command.skintools|op| ###Releases: |Version|Release Date|Download| |:-------:|------------|:--------:| |1.0.0|August 13, 2015|[available](http://forums.pocketmine.net/plugins/skintools.1364/download?version=2607)| |1.1.0|December 25, 2015|[available](http://forums.pocketmine.net/plugins/skintools.1364/download?version=2984)|
Markdown
UTF-8
1,382
2.84375
3
[]
no_license
# Article 38 I. - Pour l'application des articles 33 à 37 : 1° Les fonctions qui ne sont pas exercées à temps plein sont prises en compte à concurrence des services réellement effectués ; 2° Une même période ne peut donner lieu à prise en compte qu'une seule fois ; 3° Les demandes de classement en application du présent décret sont présentées dans un délai d'un an à compter de la nomination des intéressés dans l'un des corps mentionnés à l'article 1er. Le classement s'effectue à la date de nomination ou, le cas échéant, à la date de nomination en qualité de stagiaire. II. - Les personnes nommées dans l'un des corps mentionnés à l'article 1er peuvent bénéficier cumulativement des dispositions des articles 33 à 37 sous réserve que les services ne l'aient pas déjà été lors de l'accès initial à un corps de fonctionnaire. III. - Lorsque la période de préparation du doctorat, du doctorat d'Etat, du doctorat de troisième cycle, du diplôme de docteur ingénieur ou de diplômes universitaires, qualifications et titres français ou étrangers de niveau jugé équivalent, n'a pas été accomplie sous contrat de travail et qu'elle n'a pas été prise en compte en application des dispositions du présent décret, elle ouvre droit à une bonification d'ancienneté de deux ans pour l'accès au corps des maîtres-assistants.
C++
UTF-8
22,972
2.53125
3
[ "MIT" ]
permissive
#include "Context.hpp" #include <iostream> #include <stdexcept> #include "UtilsOpenCL.hpp" #include "../pch.hpp" bool print_info = false; /** * _kernels uses pointers, which makes the wrapper more lightweight. * As soon as vector that holds original instances is reloacted * the pointers are obsolete. */ const size_t max_resources_per_type = 128; namespace opencl { // // RawMemoryHandle // RawMemoryHandle::RawMemoryHandle() : handle(nullptr), released(false) {} void RawMemoryHandle::release() { if (!released && handle) { clReleaseMemObject(handle); // auto ciErr1 = clReleaseMemObject(handle); // TODO check error // check_error(ciErr1, "Error in RawMemoryHandle::release"); } released = true; } // // Context // // init/core functions Context::Context() : initialized(false) {} Context::~Context() { this->_cleanup(); } void Context::init(bool profile) { // TODO ad ability to select platform & device cl_int ciErr1; _profiling = profile; // Get an OpenCL platform cl_platform_id platform_id; ciErr1 = clGetPlatformIDs(1, &platform_id, nullptr); check_error(ciErr1, "Error in clGetPlatformID"); platform_info(platform_id, this->_platform); std::cout << "PLATFORM: " << _platform << std::endl; // Get the devices ciErr1 = clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_GPU, 1, &_device.device_id, nullptr); check_error(ciErr1, "Error in clGetDeviceIDs"); device_info(_device.device_id, this->_device); std::cout << "DEVICE:" << _device << std::endl; // Create the context _clcontext = clCreateContext(0, 1, &_device.device_id, nullptr, nullptr, &ciErr1); check_error(ciErr1, "Error in clCreateContext"); // Create a command-queue _clcommand_queue = clCreateCommandQueue(_clcontext, _device.device_id, _profiling ? CL_QUEUE_PROFILING_ENABLE : 0, &ciErr1); check_error(ciErr1, "Error in clCreateCommandQueue"); _kernels.reserve(max_resources_per_type); _allocations.reserve(max_resources_per_type); initialized = true; } void Context::_cleanup() { // can be called only once if (!initialized) return; initialized = false; this->block(); // kernels for (auto kernel = begin(_kernels); kernel != end(_kernels); ++kernel) { // we are done with the kernel, print it's execution time sum if (_profiling) { auto timer = kernel->get_total_execution_time(); auto timer_in_s = timer / 1000000000.0; std::cout << "Kernel " << kernel->get_human_identifier() << " total execution time: " << timer << "ns = " << timer_in_s << "s" << std::endl; } kernel->cleanup(); } // memory for (auto alloc = begin(_allocations); alloc != end(_allocations); ++alloc) { alloc->release(); } // other if (_clcommand_queue) clReleaseCommandQueue(_clcommand_queue); if (_clcontext) clReleaseContext(_clcontext); } void Context::check_error(cl_int errCode, char const* msg) { // std::cout << "CHECK: " << errCode << ": " << msg << std::endl; if (errCode != CL_SUCCESS) { std::cout << "[OPENCL ERROR] " << utils::get_opencl_error_str(errCode) << "(" << errCode << ") : " << msg << std::endl; this->_cleanup(); throw std::runtime_error(msg); } } void Context::check_error(bool check, char const* msg) { this->check_error(check ? CL_SUCCESS : -100, msg); } RawMemoryHandle* Context::raw_memory(MemoryHandle handle) { check_error(handle < _allocations.size(), "Invalid memory handle." "Could not get RawMemoryHandle object"); return &_allocations[handle]; } void Context::print_app_memory_usage() { size_t image_memory = 0, buffer_memory = 0; for (const RawMemoryHandle& mem : _allocations) { if (!mem.is_usable()) continue; if (mem.is_image()) { image_memory += mem.size; } else { buffer_memory += mem.size; } } const size_t unit = 1024 * 1024; std::cout << "Memory usage: " << (image_memory + buffer_memory) / unit // << "/" << _device.global_mem_size / unit << " MB (" // << (image_memory + buffer_memory) * 100.0 / _device.global_mem_size << "%), " << buffer_memory / unit // << "MB of raw buffers and " << image_memory / unit << "MB for images" << std::endl; } // core: execution related void Context::block() { if (cnn_sr::warn_about_blocking_operation) std::cout << "BLOCK explicit Context::block()" << std::endl; cl_int ciErr1; ciErr1 = clFlush(_clcommand_queue); check_error(ciErr1, "Error during command queue flush during Context::block()"); ciErr1 = clFinish(_clcommand_queue); check_error(ciErr1, "Error during clFinish during Context::block()"); } MemoryHandle Context::allocate(cl_mem_flags flags, size_t size) { check_error(initialized, "Context was not initialized"); cl_int ciErr1; _allocations.push_back(RawMemoryHandle()); MemoryHandle idx = _allocations.size() - 1; auto mem_handle = &_allocations[idx]; mem_handle->handle = clCreateBuffer(_clcontext, flags, size, nullptr, &ciErr1); mem_handle->size = size; check_error(ciErr1, "Error in clCreateBuffer"); return idx; } Kernel* Context::create_kernel(char const* file_path, char const* cmp_opt, char const* main_f) { check_error(initialized, "Context was not initialized"); check_error( _kernels.size() < max_resources_per_type, "Kernel limit reached, increase max_resources_per_type in Context.cpp"); if (print_info) std::cout << "Reading kernel function from '" << file_path << "' with args: '" << (cmp_opt ? cmp_opt : "") << "'" << std::endl; cl_int ciErr1; _kernels.push_back(Kernel()); auto kernel_ptr = &_kernels[_kernels.size() - 1]; // TODO better manage the resources: kernel_source, program_id, kernel_id // (if code crashes there is going to be a leak!) // Read the OpenCL kernel from source file size_t kernel_len = 0; char* kernel_source = utils::load_file(file_path, "", &kernel_len); if (print_info) std::cout << "Kernel length: " << kernel_len << std::endl; check_error(kernel_len > 0, "Could not read file"); // create program cl_program program_id = clCreateProgramWithSource( _clcontext, 1, (const char**)&kernel_source, &kernel_len, &ciErr1); check_error(ciErr1, "Error in clCreateProgramWithSource"); free(kernel_source); // build program ciErr1 = clBuildProgram(program_id, 1, &_device.device_id, cmp_opt, nullptr, nullptr); if (ciErr1 == CL_BUILD_PROGRAM_FAILURE) { char buffer[2048]; clGetProgramBuildInfo(program_id, _device.device_id, CL_PROGRAM_BUILD_LOG, sizeof(buffer), buffer, nullptr); std::cout << "******************************************" << std::endl << " --- Build log ---" << std::endl << std::endl << buffer << std::endl << "******************************************" << std::endl; } check_error(ciErr1, "Error in clBuildProgram"); // Create the kernel cl_kernel kernel_id = clCreateKernel(program_id, main_f, &ciErr1); check_error(ciErr1, "Error in clCreateKernel"); kernel_ptr->init(this, kernel_id, program_id, file_path, cmp_opt); return kernel_ptr; } /// /// Buffers: read/write/copy /// cl_event Context::read_buffer(MemoryHandle gpu_buffer_handle, size_t offset, size_t size, void* dst, bool block, cl_event* events_to_wait_for, int events_to_wait_for_count) { if (cnn_sr::warn_about_blocking_operation && block) std::cout << "BLOCK: read_buffer" << std::endl; check_error(initialized, "Context was not initialized"); auto gpu_buffer = raw_memory(gpu_buffer_handle); check_error(size <= gpu_buffer->size, "Tried to read more then is allocated"); cl_event finish_token; cl_bool clblock = block ? CL_TRUE : CL_FALSE; cl_mem gpu_memory_pointer = gpu_buffer->handle; cl_int ciErr1 = clEnqueueReadBuffer( _clcommand_queue, gpu_memory_pointer, // what and where to execute clblock, // block or not offset, size, dst, // read params: offset, size and target events_to_wait_for_count, events_to_wait_for, // sync events &finish_token); check_error(ciErr1, "Error in read buffer"); return finish_token; } cl_event Context::read_buffer(MemoryHandle gpu_buffer_handle, void* dst, bool block, cl_event* events_to_wait_for, int events_to_wait_for_count) { auto gpu_buffer = raw_memory(gpu_buffer_handle); return this->read_buffer(gpu_buffer_handle, 0, gpu_buffer->size, dst, block, events_to_wait_for, events_to_wait_for_count); } cl_event Context::write_buffer(MemoryHandle gpu_buffer_handle, size_t offset, size_t size, void* src, bool block, cl_event* events_to_wait_for, int events_to_wait_for_count) { if (cnn_sr::warn_about_blocking_operation && block) std::cout << "BLOCK: write_buffer" << std::endl; check_error(initialized, "Context was not initialized"); auto gpu_buffer = raw_memory(gpu_buffer_handle); check_error(size <= gpu_buffer->size, "Tried to write more then is allocated"); cl_event finish_token; cl_bool clblock = block ? CL_TRUE : CL_FALSE; cl_mem gpu_memory_pointer = gpu_buffer->handle; cl_int ciErr1 = clEnqueueWriteBuffer( _clcommand_queue, gpu_memory_pointer, // what and where to execute clblock, // block or not offset, size, src, // read params: offset, size and target events_to_wait_for_count, events_to_wait_for, // sync events &finish_token); check_error(ciErr1, "Error in write buffer"); return finish_token; } cl_event Context::write_buffer(MemoryHandle gpu_buffer_handle, void* src, bool block, cl_event* events_to_wait_for, int events_to_wait_for_count) { auto gpu_buffer = raw_memory(gpu_buffer_handle); return this->write_buffer(gpu_buffer_handle, 0, gpu_buffer->size, src, block, events_to_wait_for, events_to_wait_for_count); } cl_event Context::zeros_float(MemoryHandle gpu_buffer_handle, bool block, cl_event* es, int event_count) { return fill_float(gpu_buffer_handle, 0.0f, block, es, event_count); } cl_event Context::fill_float(MemoryHandle gpu_buffer_handle, float val, bool block, cl_event* es, int event_count) { auto gpu_buffer = raw_memory(gpu_buffer_handle); size_t len = gpu_buffer->size / sizeof(float); std::vector<float> v(len); for (size_t i = 0; i < len; i++) { v[i] = val; } return this->write_buffer(gpu_buffer_handle, &v[0], block, es, event_count); } cl_event Context::copy_buffer(MemoryHandle src_buffer, MemoryHandle dst_buffer, cl_event* events_to_wait_for, int events_to_wait_for_count) { auto gpu_src = raw_memory(src_buffer); auto gpu_dst = raw_memory(dst_buffer); check_error( gpu_src->size == gpu_dst->size, "When performing buffer copy, both buffers should have equal length"); return copy_buffer(src_buffer, dst_buffer, 0, events_to_wait_for, events_to_wait_for_count); } cl_event Context::copy_buffer(MemoryHandle src_buffer, MemoryHandle dst_buffer, size_t dst_offset, cl_event* events_to_wait_for, int events_to_wait_for_count) { check_error(initialized, "Context was not initialized"); auto gpu_src = raw_memory(src_buffer); auto gpu_dst = raw_memory(dst_buffer); check_error(gpu_src->size + dst_offset <= gpu_dst->size, "When performing buffer copy, would write after dst end"); cl_event finish_token; cl_int ciErr1 = clEnqueueCopyBuffer(_clcommand_queue, // gpu_src->handle, // gpu_dst->handle, // 0, dst_offset, gpu_src->size, // events_to_wait_for_count, events_to_wait_for, &finish_token); check_error(ciErr1, "Error in copy buffer"); return finish_token; } /// /// Images /// size_t Context::channels_count(cl_channel_order o, cl_channel_type t) { // 'x' means not all bits will be used f.e. CL_UNORM_SHORT_555 switch (o) { case CL_R: case CL_A: case CL_Rx: return 1; case CL_INTENSITY: case CL_LUMINANCE: check_error(t == CL_UNORM_INT8 || t == CL_UNORM_INT16 || t == CL_SNORM_INT8 || t == CL_SNORM_INT16 || t == CL_HALF_FLOAT || t == CL_FLOAT, "Use CL_INTENSITY/CL_LUMINANCE only with CL_UNORM_INT8, " "CL_UNORM_INT16, " "CL_SNORM_INT8, CL_SNORM_INT16, CL_HALF_FLOAT, or CL_FLOAT"); return 1; case CL_RG: case CL_RA: case CL_RGx: return 2; case CL_RGB: case CL_RGBx: check_error(t == CL_UNORM_SHORT_565 || t == CL_UNORM_SHORT_555 || t == CL_UNORM_INT_101010, "Use CL_RGB/CL_RGBx only with CL_UNORM_SHORT_565, " "CL_UNORM_SHORT_555 or CL_UNORM_INT_101010"); return 3; case CL_RGBA: return 4; case CL_BGRA: case CL_ARGB: check_error(t == CL_UNORM_INT8 || t == CL_SNORM_INT8 || t == CL_SIGNED_INT8 || t == CL_UNSIGNED_INT8, "Use CL_ARGB/CL_BGRA only with CL_UNORM_INT8, CL_SNORM_INT8, " "CL_SIGNED_INT8 or CL_UNSIGNED_INT8"); return 4; } check_error(false, "Unrecognised cl_channel_order"); return 0; } size_t Context::per_pixel_bytes(cl_channel_order o, cl_channel_type t) { auto ch_count = channels_count(o, t); switch (t) { case CL_SNORM_INT8: case CL_UNORM_INT8: case CL_SIGNED_INT8: case CL_UNSIGNED_INT8: return ch_count; case CL_SNORM_INT16: case CL_UNORM_INT16: case CL_SIGNED_INT16: case CL_UNSIGNED_INT16: return 2 * ch_count; case CL_SIGNED_INT32: case CL_UNSIGNED_INT32: return 4 * ch_count; case CL_UNORM_SHORT_565: check_error(o == CL_RGB || o == CL_RGB, "Use CL_UNORM_SHORT_565 only with CL_RGB/CL_RGBx"); return sizeof(cl_short); case CL_UNORM_SHORT_555: check_error(o == CL_RGB || o == CL_RGB, "Use CL_UNORM_SHORT_555 only with CL_RGB/CL_RGBx"); return sizeof(cl_short); case CL_UNORM_INT_101010: check_error(o == CL_RGB || o == CL_RGB, "Use CL_UNORM_INT_101010 only with CL_RGB/CL_RGBx"); return sizeof(cl_int); case CL_HALF_FLOAT: return sizeof(cl_float) * ch_count / 2; case CL_FLOAT: return sizeof(cl_float) * ch_count; } check_error(false, "Unrecognised cl_channel_type"); return 0; } MemoryHandle Context::create_image(cl_mem_flags flags, cl_channel_order image_channel_order, cl_channel_type image_channel_data_type, size_t w, size_t h) { check_error(initialized, "Context was not initialized"); auto bpp = per_pixel_bytes(image_channel_order, image_channel_data_type); cl_image_format image_format; image_format.image_channel_order = image_channel_order; image_format.image_channel_data_type = image_channel_data_type; cl_int ciErr1; _allocations.push_back(RawMemoryHandle()); auto mem_idx = _allocations.size() - 1; auto mem_handle = &_allocations[mem_idx]; mem_handle->handle = clCreateImage2D(_clcontext, flags, &image_format, w, h, 0, nullptr, &ciErr1); mem_handle->size = w * h * bpp; mem_handle->bpp = bpp; check_error(ciErr1, "Error in clCreateImage2D"); return mem_idx; } cl_event Context::write_image(MemoryHandle gpu_buffer_handle, utils::ImageData& data, bool block, cl_event* events_to_wait_for, int events_to_wait_for_count) { check_error(initialized, "Context was not initialized"); auto gpu_image = raw_memory(gpu_buffer_handle); cl_event finish_token; cl_bool clblock = block ? CL_TRUE : CL_FALSE; cl_mem gpu_memory_pointer = gpu_image->handle; size_t origin[3] = {0, 0, 0}; size_t region[3] = {(size_t)data.w, (size_t)data.h, 1}; cl_int ciErr1 = clEnqueueWriteImage( _clcommand_queue, gpu_memory_pointer, // what and where to execute clblock, // block or not origin, region, // corners: left-top, right-down data.w * gpu_image->bpp, // length of each row in bytes 0, (void*)data.data, // events_to_wait_for_count, events_to_wait_for, // sync events &finish_token); check_error(ciErr1, "Error in write_image"); return finish_token; } /// /// info /// void Context::display_opencl_info() { cl_int ciErr1; cl_uint platform_count = 0; ciErr1 = clGetPlatformIDs(0, nullptr, &platform_count); check_error(ciErr1, "Could not get platform count"); std::cout << "platforms:" << std::endl; // prepare platform ids vector std::vector<cl_platform_id> platform_ids; platform_ids.reserve(platform_count); for (size_t i = 0; i < platform_count; i++) { platform_ids.push_back(nullptr); } ciErr1 = clGetPlatformIDs(platform_count, &platform_ids[0], nullptr); check_error(ciErr1, "Could not get platform ids"); PlatformInfo platform_info; std::vector<DeviceInfo> devices; for (auto i = begin(platform_ids); i != end(platform_ids); ++i) { devices.clear(); this->platform_info(*i, platform_info, &devices); std::cout << " " << platform_info << std::endl; std::cout << " devices:" << std::endl; // devices for (auto j = begin(devices); j != end(devices); ++j) { std::cout << " " << (*j) << std::endl; } } std::cout << "found " << platform_count << " opencl platforms" << std::endl; } void Context::platform_info(cl_platform_id platform_id, PlatformInfo& platform_info, std::vector<DeviceInfo>* devices) { size_t value_size = 0; cl_int ciErr1; /* clang-format off */ ciErr1 = clGetPlatformInfo(platform_id, CL_PLATFORM_NAME, sizeof(platform_info.name), &platform_info.name, &value_size); platform_info.name[value_size] = '\0'; ciErr1 |= clGetPlatformInfo(platform_id, CL_PLATFORM_VENDOR, sizeof(platform_info.vendor), &platform_info.vendor, &value_size); platform_info.vendor[value_size] = '\0'; ciErr1 |= clGetPlatformInfo(platform_id, CL_PLATFORM_VERSION, sizeof(platform_info.version), &platform_info.version, &value_size); platform_info.version[value_size] = '\0'; /* clang-format on */ check_error(ciErr1, "Could not get platform details"); if (!devices) { // no reason to read device data return; } // get device count cl_uint device_count = 0; ciErr1 = clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_ALL, // 0, nullptr, &device_count); check_error(ciErr1, "Could not get platform devices"); // std::cout << " found " << device_count << " devices" << std::endl; // device ids std::vector<cl_device_id> device_ids; device_ids.reserve(device_count); for (size_t i = 0; i < device_count; i++) { device_ids.push_back(0); } ciErr1 = clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_ALL, // device_count, &device_ids[0], nullptr); check_error(ciErr1, "Could not get device ids"); for (auto i = begin(device_ids); i != end(device_ids); ++i) { DeviceInfo d; this->device_info(*i, d); devices->push_back(d); } } void Context::device_info(cl_device_id device_id, DeviceInfo& info) { cl_int ciErr1; size_t value_size = 0; /* clang-format off */ ciErr1 = clGetDeviceInfo(device_id, CL_DEVICE_GLOBAL_MEM_SIZE, 1024, &info.global_mem_size, nullptr); ciErr1 |= clGetDeviceInfo(device_id, CL_DEVICE_IMAGE_SUPPORT, 1024, &info.image_support, nullptr); ciErr1 |= clGetDeviceInfo(device_id, CL_DEVICE_MAX_WORK_GROUP_SIZE, 1024, &info.max_work_group_size, nullptr); ciErr1 |= clGetDeviceInfo(device_id, CL_DEVICE_ADDRESS_BITS, 1024, &info.address_bits, nullptr); ciErr1 |= clGetDeviceInfo(device_id, CL_DEVICE_MAX_WORK_ITEM_SIZES, 1024, &info.work_items_for_dims, nullptr); ciErr1 |= clGetDeviceInfo(device_id, CL_DEVICE_TYPE, 1024, &info.type, nullptr); ciErr1 |= clGetDeviceInfo(device_id, CL_DEVICE_LOCAL_MEM_SIZE, 1024, &info.local_mem_size, nullptr); ciErr1 |= clGetDeviceInfo(device_id, CL_DEVICE_LOCAL_MEM_TYPE, 1024, &info.local_mem_type, nullptr); ciErr1 |= clGetDeviceInfo(device_id, CL_DEVICE_MAX_COMPUTE_UNITS, 1024, &info.compute_units, nullptr); ciErr1 |= clGetDeviceInfo(device_id, CL_DEVICE_NAME, sizeof(info.name), &info.name, &value_size); info.name[value_size] = '\0'; /* clang-format on */ check_error(ciErr1, "Could not get device data"); } } std::ostream& operator<<(std::ostream& os, const opencl::PlatformInfo& platform_info) { os << platform_info.vendor << "::" << platform_info.name // << ", version " << platform_info.version; return os; } std::ostream& operator<<(std::ostream& os, const opencl::DeviceInfo& device) { auto wifd = device.work_items_for_dims; /* clang-format off */ os << opencl::utils::device_type_str[device.type] << "::" << device.name << ", compute units: " << device.compute_units << ", global memory: " << (device.global_mem_size / 1024 / 1024) << "MB" << ", max local memory: " << (device.local_mem_size / 1024) << "KB, local memory type: " << (device.local_mem_type == CL_LOCAL ? "local" : "global") << ", address bits: " << device.address_bits << ", max work group size: " << device.max_work_group_size << ", work items: [" << wifd[0] << ", " << wifd[1] << ", " << wifd[2] << "], image support: " << (device.image_support == CL_TRUE ? "YES" : "NO"); /* clang-format on */ return os; } /* int main(int argc, char **argv) { opencl::Context context(argc, argv); context.display_opencl_info(); } */
C
UTF-8
524
2.953125
3
[]
no_license
#include<stdio.h> #include<stdlib.h> #include<fcntl.h> #include<unistd.h> int main(){ int fd=open("a.txt",O_RDONLY); if(fd==-1) perror("opena"),exit(-1); int fd1=open("b.txt",O_CREAT|O_RDWR|O_TRUNC,0666);//新建文件时有权限屏蔽 if(fd1==-1) perror("openb"),exit(-1); char buf[4096]={}; while(1){ int ret=read(fd,buf,sizeof(buf)); if(ret==-1) perror("read"),exit(-1); if(!ret) break; write(fd1,buf,sizeof(buf)); } close(fd); close(fd1); }
C
UTF-8
1,350
2.765625
3
[]
no_license
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <time.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include "func.h" #ifdef DEBUG #define BYTES #endif #define SERVER_SOCKET_IP "192.168.40.185" #define SERVER_SOCKET_PORT 9090 int main (int argc, char **argv) { char txDgramBuffer[512]="Hello World"; //DATA struct sockaddr_in rxAddress; memset(&rxAddress, 0, sizeof(rxAddress)); rxAddress.sin_family = AF_INET; // Receiving Socket Family rxAddress.sin_addr.s_addr = inet_addr(SERVER_SOCKET_IP);// Receiving Socket IP Address if (argc >= 2) rxAddress.sin_addr.s_addr = inet_addr(argv[1]); rxAddress.sin_port = htons(SERVER_SOCKET_PORT); // Receiving Socket Port Number if (argc >= 3) rxAddress.sin_port = htons(atoi(argv[2])); //Establish a socket connection int txSocket = -1; txSocket = socket(AF_INET,SOCK_DGRAM,0); int test = -1; //TX Socket, TX Data, TX Data Size, flags, RX Socket Info (DOMAIN, IP and PORT), size of RX Address Struct) test=sendto(txSocket, txDgramBuffer, strlen(txDgramBuffer),\ 0, (struct sockaddr *) &rxAddress, sizeof(rxAddress) ); if ( test < 0) printf("Failed to send\n"); #ifdef BYTES printBytes( (unsigned char *) &rxAddress, 16); #endif return 0; }
Java
UTF-8
2,528
2.515625
3
[ "MIT" ]
permissive
package net.dumbcode.test; import net.dumbcode.hwkengine.display.DisplayManager; import net.dumbcode.hwkengine.entities.Camera; import net.dumbcode.hwkengine.entities.Entity; import net.dumbcode.hwkengine.entities.Light; import net.dumbcode.hwkengine.model.RawModel; import net.dumbcode.hwkengine.model.TexturedModel; import net.dumbcode.hwkengine.model.loader.ModelLoader; import net.dumbcode.hwkengine.model.loader.OBJLoader; import net.dumbcode.hwkengine.render.ModelRenderer; import net.dumbcode.hwkengine.shaders.StaticShader; import net.dumbcode.hwkengine.textures.ModelTexture; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.GL11; import org.lwjgl.util.vector.Vector3f; import java.io.File; public class HwkEngine { private static DisplayManager displayManager; private static ModelLoader modelLoader = new ModelLoader(); private static ModelRenderer renderer; private static RawModel model; private static StaticShader staticShader; private static ModelTexture texture; private static TexturedModel texturedModel; private static Entity entity; private static Light light; private static Camera camera = new Camera(); public static void main(String[] args) { displayManager = DisplayManager.INSTANCE; displayManager.createDisplay("Test Game", 1280, 720); model = OBJLoader.loadObBJModel(new File("src/test/resources/models/stall.obj"), modelLoader); staticShader = new StaticShader(); renderer = new ModelRenderer(staticShader); texture = new ModelTexture(modelLoader.loadTexture("stall")); texture.setDamper(10f); texture.setReflectivity(1f); texturedModel = new TexturedModel(model, texture); entity = new Entity(texturedModel, new Vector3f(0, 0, -50), 0, 0, 0, 1); light = new Light(new Vector3f(0, 0, -20), new Vector3f(1, 1, 1)); loop(); } private static void loop() { while(!Display.isCloseRequested()) { GL11.glClearColor(0, 0, 1, 0); entity.increaseRotation(0, 1, 0); camera.move(); renderer.prepare(); staticShader.start(); staticShader.loadLight(light); staticShader.loadViewMatrix(camera); renderer.render(entity, staticShader); staticShader.stop(); displayManager.updateDisplay(60); } staticShader.clean(); modelLoader.clean(); displayManager.destroyDisplay(); } }
Python
UTF-8
8,521
3.15625
3
[]
no_license
import pygame import tweepy import random #user:TrumpPong #password:FUPgdpp100t auth = tweepy.OAuthHandler("VOrDwufgnBfc9Pg7MU0NNJnhg", "U34un9TLQjiC0vSZT5ACkYIG8anlNibZSsEq5QCjZP4fsIk4SR") auth.set_access_token("747244855550582784-NY7T1r6SfVQ8lEMtUPXfsr8IBtysolN","9h8fYzJEWMVnvpCAyJzLs8du17X7H170lAc1PdywnX3II") api = tweepy.API(auth) # -- Global constants # Colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) BLUE = (50, 50, 255) GREEN = (0, 255, 0) # Screen dimensions SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 class Player(pygame.sprite.Sprite): """ This class represents the bar at the bottom that the player controls. """ # Constructor function def __init__(self, x, y): # Call the parent's constructor super().__init__() # Set height, width self.image = pygame.Surface([15, 100]) self.image.fill(BLACK) # Make our top-left corner the passed-in location. self.rect = self.image.get_rect() self.rect.y = y self.rect.x = x # Set speed vector self.change_x = 0 self.change_y = 0 self.walls = None self.score = 0 def changespeed(self, x, y): """ Change the speed of the player. """ self.change_x += x self.change_y += y def update(self): """ Update the player position. """ # Move left/right self.rect.x += self.change_x # Did this update cause us to hit a wall? block_hit_list = pygame.sprite.spritecollide(self, self.walls, False) for block in block_hit_list: # If we are moving right, set our right side to the left side of # the item we hit if self.change_x > 0: self.rect.right = block.rect.left else: # Otherwise if we are moving left, do the opposite. self.rect.left = block.rect.right # Move up/down self.rect.y += self.change_y # Check and see if we hit anything block_hit_list = pygame.sprite.spritecollide(self, self.walls, False) for block in block_hit_list: # Reset our position based on the top/bottom of the object. if self.change_y > 0: self.rect.bottom = block.rect.top else: self.rect.top = block.rect.bottom class Wall(pygame.sprite.Sprite): """ Wall the player can run into. """ def __init__(self, x, y, width, height): """ Constructor for the wall that the player can run into. """ # Call the parent's constructor super().__init__() # Make a blue wall, of the size specified in the parameters self.image = pygame.Surface([width, height]) self.image.fill(BLUE) # Make our top-left corner the passed-in location. self.rect = self.image.get_rect() self.rect.y = y self.rect.x = x class Ball(pygame.sprite.Sprite): """ Wall the player can run into. """ def __init__(self, x, y, width, height): """ Constructor for the wall that the player can run into. """ # Call the parent's constructor super().__init__() # Make a blue wall, of the size specified in the parameters self.image = pygame.Surface([width, height]) self.image.fill(GREEN) # Make our top-left corner the passed-in location. self.rect = self.image.get_rect() self.rect.y = y self.rect.x = x self.hit = None self.change_x = 0 self.change_y = 0 self.trump = None def update(self): """ Update the player position. """ # Move left/right self.rect.x += self.change_x # Did this update cause us to hit a wall? block_hit_list = pygame.sprite.spritecollide(self, self.hit, False) for block in block_hit_list: # If we are moving right, set our right side to the left side of # the item we hit if self.change_x > 0: self.rect.right = block.rect.left else: # Otherwise if we are moving left, do the opposite. self.rect.left = block.rect.right self.change_x = -1*(self.change_x+random.randrange(-2, 3)) self.change_y += random.randrange(-2, 3) # Move up/down self.rect.y += self.change_y # Check and see if we hit anything block_hit_list = pygame.sprite.spritecollide(self, self.hit, False) for block in block_hit_list: if self.change_y > 0: self.rect.bottom = block.rect.top else: self.rect.top = block.rect.bottom self.change_y = -1*(self.change_y+random.randrange(-2, 3)) self.change_x += random.randrange(-2, 3) class Trump(pygame.sprite.Sprite): """ Wall the player can run into. """ def __init__(self): """ Constructor for the wall that the player can run into. """ # Call the parent's constructor super().__init__() self.string = "" x = random.randrange(0,3) if x == 0: self.string = "trump1.jpg" elif x == 1: self.string = "trump2.jpg" else: self.string = "trump3.png" # Make a blue wall, of the size specified in the parameters self.image = pygame.image.load(self.string).convert() # Make our top-left corner the passed-in location. self.rect = self.image.get_rect() self.rect.y = random.randrange(10,500) self.rect.x = random.randrange(10,700) self.hit = None # Call this function so the Pygame library can initialize itself pygame.init() # Create an 800x600 sized screen screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT]) # Set the title of the window pygame.display.set_caption('Test') # List to hold all the sprites all_sprite_list = pygame.sprite.Group() # Make the walls. (x_pos, y_pos, width, height) wall_list = pygame.sprite.Group() hit_list = pygame.sprite.Group() trump_list = pygame.sprite.Group() wall = Wall(0, 0, 800, 10) wall_list.add(wall) hit_list.add(wall) all_sprite_list.add(wall) wall = Wall(0, 590, 800, 10) wall_list.add(wall) hit_list.add(wall) all_sprite_list.add(wall) wall = Wall(790, 0, 10, 270) wall_list.add(wall) hit_list.add(wall) all_sprite_list.add(wall) wall = Wall(790, 330, 10, 270) wall_list.add(wall) hit_list.add(wall) all_sprite_list.add(wall) trumpeter = Trump() trump_list.add(trumpeter) # Create the player paddle object player = Player(50, 50) player.walls = wall_list hit_list.add(player) ball = Ball(300,400,20,20) ball.change_x = -6 ball.change_y = 6 ball.hit = hit_list ball.trump = trump_list all_sprite_list.add(player) all_sprite_list.add(ball) all_sprite_list.add(trumpeter) clock = pygame.time.Clock() done = False while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True elif event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: player.changespeed(0, -8) elif event.key == pygame.K_DOWN: player.changespeed(0, 8) elif event.type == pygame.KEYUP: if event.key == pygame.K_UP: player.changespeed(0, 8) elif event.key == pygame.K_DOWN: player.changespeed(0, -8) all_sprite_list.update() trump_hit_list = pygame.sprite.spritecollide(ball, ball.trump, True) for block in trump_hit_list: player.score += 1 trumpeter = Trump() ball.trump.add(trumpeter) all_sprite_list.add(trumpeter) if ball.rect.x > 810: api.update_status("@realDonaldTrump " + input("what is your name?")+ " scored " + str(player.score) + " in Trump Pong.") done = True if ball.rect.x < 0: player.score = 0 ball.rect.x = 400 ball.rect.y = 300 ball.change_x = -6 ball.change_y = 6 screen.fill(WHITE) # Select the font to use, size, bold, italics font = pygame.font.SysFont('Calibri', 25, True, False) # Render the text. "True" means anti-aliased text. # Black is the color. The variable BLACK was defined # above as a list of [0, 0, 0] # Note: This line creates an image of the letters, # but does not put it on the screen yet. text = font.render(str(player.score), True, BLACK) # Put the image of the text on the screen at 250x250 screen.blit(text, [350, 50]) all_sprite_list.draw(screen) pygame.display.flip() clock.tick(60) pygame.quit()
PHP
UTF-8
360
2.578125
3
[]
no_license
<?php namespace App; use Illuminate\Database\Eloquent\Model; class DriverLocation extends Model { public function driver() { return $this->hasOne('App\Driver','driver_id'); } // Once Relationship defined I can access $ride = DriverLocation::fine(1)->ride(); // The above line will return A ride related to driverlocation id 1 }
PHP
UTF-8
1,271
2.65625
3
[]
no_license
<?php require_once "includes/config.php"; require_once "lib/password.php"; ?> <form method='post'> <input type="text" name="username" placeholder="username"> <br /> <input type="password" name="password" placeholder="password"> <br /> <input type="submit" value="login" name="submit"> </form> <div id="help"> <a href="#">Forgot your password?</a><br /> <a href="register.php" class="register">Don't have an account?</a> </div> <?php if(isset($_POST['submit'])) { $uname = $_POST['username']; $uname = clean($conn, $uname); $pword = $_POST['password']; $query = mysqli_query($conn, "SELECT username FROM user WHERE username = '$uname' ") or die(mysqli_error($conn)); if (mysqli_num_rows($query) == true) { $query = mysqli_query($conn, "SELECT user_id, username, password FROM user WHERE username = '$uname'"); $row = mysqli_fetch_array($query); $hash = $row['password']; $user_id = $row['user_id']; if (password_verify($pword, $hash) == true) { $_SESSION['user'] = $user_id; header("location: index.php"); } else { ?> <script> window.alert("Wrong username/password"); </script> <?php } } else { ?> <script> window.alert("Wrong username/password"); </script> <?php } }
C++
UTF-8
5,844
2.609375
3
[]
no_license
#ifndef __CUDA_DRAW__ #define __CUDA_DRAW__ #include <glog/logging.h> #include <opencv2/opencv.hpp> namespace cudraw { // Utilities // Support U8C3 images only uint8_t* allocateImage(size_t width, size_t height); uint8_t* uploadImage(size_t width, size_t height, uint8_t* img); void uploadImage(size_t width, size_t height, uint8_t* img, uint8_t* d_img); void downloadImage(size_t width, size_t height, uint8_t* d_img, uint8_t* img); void copyImage(uint8_t* d_dst, uint8_t* d_src, size_t size); void freeImage(uint8_t* d_img); // API struct Color { Color() = default; __device__ __host__ Color( unsigned char rr, unsigned char gg, unsigned char bb) { r = rr; g = gg; b = bb; } __device__ __host__ Color(unsigned int hex) { // TODO: This logic has something to do with the Endianess of the machine. // Check back later - to debug this r = hex & 0x000000ff; hex >>= 8; g = hex & 0x000000ff; hex >>= 8; b = hex & 0x000000ff; } __device__ __host__ void overlay(const Color& other, float alpha) { if (alpha < 0) { alpha = 0; } if (alpha > 1) { alpha = 1; } r = (float)r * (1.f - alpha) + (float)other.r * alpha; g = (float)g * (1.f - alpha) + (float)other.g * alpha; b = (float)b * (1.f - alpha) + (float)other.b * alpha; } unsigned char r = 0; unsigned char g = 0; unsigned char b = 0; }; struct AABB { AABB() = default; __device__ __host__ AABB(int x_0, int y_0, int x_1, int y_1) { x0 = x_0; y0 = y_0; x1 = x_1; y1 = y_1; } __device__ __host__ void inflate(int i) { x0 -= i; x1 += i; y0 -= i; y1 += i; } __device__ __host__ bool inside(int x, int y) { return x >= x0 && x <= x1 && y >= y0 && y <= y1; } int x0 = 0; int y0 = 0; int x1 = 0; int y1 = 0; }; struct Shape { Shape() = default; __device__ virtual Color checkPixel(int x, int y, Color color) = 0; __device__ __host__ virtual AABB getAABB() const = 0; }; struct Line : public Shape { Line() = default; __device__ __host__ Line(int x_0, int y_0, int x_1, int y_1, float w) { x0 = x_0; y0 = y_0; x1 = x_1; y1 = y_1; width = w; } __device__ Color checkPixel(int x, int y, Color prev_color) override; __device__ __host__ AABB getAABB() const override; int x0 = 0; int y0 = 0; int x1 = 0; int y1 = 0; float width = 1; Color color; }; struct String : public Shape { String() = default; __device__ __host__ String(int x_in, int y_in, const char *str, int l) { #ifdef __CUDA_ARCH__ x = x_in; y = y_in; length = l; cudaMalloc(&d_buffer, length); cudaMemcpy(d_buffer, str, length, cudaMemcpyDeviceToDevice); #else CHECK(str); CHECK(l >= 0); x = x_in; y = y_in; length = l; buffer = new char[length]; memcpy(buffer, str, length); cudaMalloc(&d_buffer, length); cudaMemcpy(d_buffer, str, length, cudaMemcpyHostToDevice); #endif } __device__ __host__ String(const String& other) { #ifdef __CUDA_ARCH__ x = other.x; y = other.y; length = other.length; color = other.color; font_size = other.font_size; if (d_buffer) { cudaFree(d_buffer); } cudaMalloc(&d_buffer, length); cudaMemcpy(d_buffer, other.d_buffer, length, cudaMemcpyDeviceToDevice); #else CHECK(other.buffer); CHECK(other.length >= 0); x = other.x; y = other.y; length = other.length; color = other.color; font_size = other.font_size; if (buffer) { delete[] buffer; } buffer = new char[length]; memcpy(buffer, other.buffer, length); if (d_buffer) { cudaFree(d_buffer); } cudaMalloc(&d_buffer, length); cudaMemcpy(d_buffer, other.d_buffer, length, cudaMemcpyHostToDevice); #endif } __device__ __host__ String& operator=(const String& other) { #ifdef __CUDA_ARCH__ x = other.x; y = other.y; length = other.length; color = other.color; font_size = other.font_size; if (d_buffer) { cudaFree(d_buffer); } cudaMalloc(&d_buffer, length); cudaMemcpy(d_buffer, other.d_buffer, length, cudaMemcpyDeviceToDevice); return *this; #else CHECK(other.buffer); CHECK(other.length >= 0); x = other.x; y = other.y; length = other.length; color = other.color; font_size = other.font_size; if (buffer) { delete[] buffer; } buffer = new char[length]; memcpy(buffer, other.buffer, length); if (d_buffer) { cudaFree(d_buffer); } cudaMalloc(&d_buffer, length); cudaMemcpy(d_buffer, other.d_buffer, length, cudaMemcpyHostToDevice); return *this; #endif } __device__ __host__ ~String() { #ifdef __CUDA_ARCH__ if (d_buffer) { cudaFree(d_buffer); } #else if (buffer) { delete[] buffer; } if (d_buffer) { cudaFree(d_buffer); } #endif } __device__ Color checkPixel(int in_x, int in_y, Color prev_color) override; __device__ __host__ AABB getAABB() const override; int x = 0; int y = 0; char* buffer = nullptr; char* d_buffer = nullptr; int length = 0; float font_size = 8; Color color; }; struct Rect : public Shape { Rect() = default; __device__ __host__ Rect(int x_0, int y_0, int x_1, int y_1, float w) { x0 = x_0; y0 = y_0; x1 = x_1; y1 = y_1; width = w; } __device__ Color checkPixel(int x, int y, Color prev_color) override; __device__ __host__ AABB getAABB() const override; int x0 = 0; int y0 = 0; int x1 = 0; int y1 = 0; float width = 1; float fill_alpha = 1; bool fill = false; Color color; Color fill_color; }; template<class T> void scanPixel(size_t width, size_t height, uint8_t* d_img, const T& shape); } #endif
C#
UTF-8
743
2.875
3
[]
no_license
using SettlersOfValgard.resource; namespace SettlersOfValgard.command { public static class StockPileCommands { public static void StockPile(Command command) { if (command.Args.Count == 0) { var isEmpty = true; foreach ((Resource resource, int amount) in Settlement.Get().StockPile.Contents) { if (amount > 0) { isEmpty = false; Console.WriteLine(resource + " x" + amount); } } if(isEmpty) Console.WriteLine("Your stockpile is empty."); } } } }
Python
UTF-8
2,227
3.15625
3
[]
no_license
import requests import re from bs4 import BeautifulSoup class Parser: """ URLにアクセスして、パソコンの情報を含んだデータをかえす(仮) """ URL = "http://www.lenovo.com/jp/ja/notebooks/thinkpad/e-series/E495/p/22TP2TEE495" @staticmethod def _getSoupFromURL(url: int): """ urlのリンク先のsoupを返す parameter ----- url : str 読み込みたいページのurl return ----- soup : Beautifulsoup.soup 読み込んだページのsoupオブジェクト? """ UA = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0" headers = {"User-Agent": UA} # スクレイピング対象の URL にリクエストを送り HTML を取得する res = requests.get(Parser.URL, headers=headers) # レスポンスの HTML から BeautifulSoup オブジェクトを作る soup = BeautifulSoup(res.text, 'html.parser') return soup @staticmethod def main(): page = Parser._getSoupFromURL(Parser.URL) result = [] # データを取得する items = page.find_all("div", {"class": "tabbedBrowse-productListing"}) for item in items: not_striped_name = item.find( "h3", {"class": "tabbedBrowse-productListing-title"}).text.strip() name = re.sub("<.*>", "", not_striped_name) price = item.find( "dd", {"class": "saleprice pricingSummary-details-final-price"}).text processor = item.find("div", { "class": "expandableContent tabbedBrowse-productListing-expandableContent-features expandableContent-is-collapsed"}).find_all("dd")[0].text memory = item.find("div", { "class": "expandableContent tabbedBrowse-productListing-expandableContent-features expandableContent-is-collapsed"}).find_all("dd")[2].text # データを加工する dic = {"name": name, "price": price, "processor": processor, "memory": memory} result.append(dic) return result
C++
UTF-8
1,460
2.765625
3
[]
no_license
/* Edmonds-Karp O(VE^2) time O(E) memory */ #include<bits/stdc++.h> using namespace std; const int maxN=1e3+10; int n,st,fn,m; bool mark[maxN]; int cap[maxN][maxN],parent[maxN]; vector<int> g[maxN],path; #define PB push_back void input() { cin>>n>>m; cin>>st>>fn; for(int i=1;i<=m;i++) { int k1,k2,val; cin>>k1>>k2>>val; g[k1].push_back(k2); g[k2].push_back(k1); cap[k1][k2]=val; } } bool BFS(int v) { queue<int> q; q.push(v); mark[v]=true; parent[v]=v; while(q.size()>0) { v=q.front(); q.pop(); if(v==fn)//found break; for(auto u :g[v]) if(!mark[u] && cap[v][u]>0) { mark[u]=true; parent[u]=v; q.push(u); } } if(mark[fn]==false) return false; v=fn; while(parent[v]!=v) {path.PB(v); v=parent[v];} path.PB(v); reverse(path.begin(),path.end()); return true; } int Edmonds_Karp() { int MaxFlow=0; while(BFS(st)) { int minCap=INT_MAX; for(int i=1;i<path.size();i++) minCap=min(minCap,cap[path[i-1]][path[i]]); for(int i=1;i<path.size();i++) { cap[path[i-1]][path[i]]-=minCap; cap[path[i]][path[i-1]]+=minCap; } MaxFlow+=minCap; path.clear(); memset(mark,0,sizeof(mark)); } return MaxFlow; } int main() { input(); int ans=Edmonds_Karp(); cout<<ans<<endl; return 0; }
JavaScript
UTF-8
1,921
3.671875
4
[]
no_license
/* Created By: Kris Kuchinka * Start Date: 2016.02.26 * Submission Date: * Document Purpose: This is an external JavaScript file * written for the "JavaPic" assignment at PDX Code Guild. */ function externalJs() { console.log("Your external JS is connected properly."); } // End of start funtion // Create function that changes images every 10 seconds. // There are 59 images to cycle through (#42 is missing) function changeImage() { // Set variable changing_image to id; grab a hold of it var changing_image = document.getElementById("jumbotron"); // The numbers are written with a 0 before single digit // numbers. To avert this the first step is for images // 1-9 to add an exra zero to the file path. if (image_number <= 9) { // Change the styling of the variables background // image changing_image.style.backgroundImage = "url('images/pdxcg_0" + image_number + ".jpg')"; // Increment image number image_number += 1; // Let the console know where you are "located" in // if statement console.log("You are <= 9"); // If the image_number is 10 or greater.... } else if (image_number >= 10 && image_number <= 60) { // Let the console know where you are "located" in // if statement console.log("You are now >= 10"); // Image number 42 is missing from folder--> skip it if (image_number == 42) { image_number = 43; }; // End of if image_number is 42 // Change background image, in this set no need to // add a zero. changing_image.style.backgroundImage = "url('images/pdxcg_" + image_number + ".jpg')"; image_number += 1; // If the number is greater than 60 } else if (image_number >= 61) { image_number = 1; }; // End of if, else if, else if statement block } // End of changeImage function externalJs(); // Create global variable for "image_number" var image_number = 1; // Set a 10 second interval to change the picture window.setInterval(changeImage, 10000);
PHP
UTF-8
636
3.484375
3
[]
no_license
<html> <head> <title>AoC 2018 DAY02</title> </head> <body> <?php $input = file("input\day02.txt"); $two = 0; $three = 0; foreach($input as $element) { $lul = str_split($element); sort($lul); for($i = 0; $i < (count($lul) - 2); $i++) { if($lul[$i] == $lul[$i+1] && $lul[$i] != $lul[$i+2]) { $two++; break;} } for($i = 0; $i < (count($lul) - 3); $i++) { if($lul[$i] == $lul[$i+1] && $lul[$i] == $lul[$i+2] && $lul[$i] != $lul[$i+3]) { $three++; break; } } } $checksum = $three * $two; echo "<p>" . $checksum . "</p>"; ?> </body> </html>
JavaScript
UTF-8
7,435
2.71875
3
[]
no_license
function Llanta(){ var material = new THREE.MeshStandardMaterial( { color: 0x000000, metalness: 0.5, roughness: 0.2 }); var material2 = new THREE.MeshStandardMaterial( { color: 0x7A7A7A, metalness: 0.5, roughness: 0.2 } ); var geoLlanta = new THREE.CylinderGeometry( 2, 2, 2, 32 ); var Llanta = new THREE.Mesh( geoLlanta, material ); var RotacionLlanta = new THREE.Euler(0,0,Math.PI/2, 'XYZ'); Llanta.setRotationFromEuler(RotacionLlanta); var geoLlantaInt = new THREE.CylinderGeometry( 1.5, 1.5, 1.5, 32 ); var LLantaInt = new THREE.Mesh( geoLlantaInt, material2 ); LLantaInt.setRotationFromEuler(RotacionLlanta); var geoLlantaInt = new THREE.CylinderGeometry( 1.5, 1.5, 2.5, 32 ); var LLantaIntCorte = new THREE.Mesh( geoLlantaInt, material2 ); LLantaIntCorte.setRotationFromEuler(RotacionLlanta); var LLantaIntCorteCSG = THREE.CSG.fromMesh( LLantaIntCorte ); var LlantaCSG = THREE.CSG.fromMesh( Llanta); var resultado = LlantaCSG.subtract( LLantaIntCorteCSG); Llanta = THREE.CSG.toMesh( resultado ); Llanta.material = material; //scene.add(Llanta); var Grabadoline = []; Grabadoline[3] = new THREE.Vector2( 0, 0 ); Grabadoline[2] = new THREE.Vector2( 1, .55 ); Grabadoline[1] = new THREE.Vector2( 0, 1 ); Grabadoline[0] = new THREE.Vector2( -1, .55); var FormaGrabado = new THREE.Shape(); FormaGrabado .splineThru( Grabadoline); var material = new THREE.LineBasicMaterial( { color : 0xff0000 } ); var resolution = 30; var points = FormaGrabado .getPoints( resolution ); var geometry = new THREE.BufferGeometry().setFromPoints( points ); var curveGrabado = new THREE.Line( geometry, material ); var extrudeSettings = { steps: 5, amount: 3, bevelEnabled: false }; var geometriaGrabado = new THREE.ExtrudeGeometry( FormaGrabado, extrudeSettings ); var materialGrabado = new THREE.MeshStandardMaterial( { color: 0xFF7000, metalness: 0.5, roughness: 0.1, opacity: 0.75, transparent: true } ); var material = new THREE.MeshStandardMaterial( { color: 0xFDAD00, metalness: 0.5, roughness: 0.2 }); var Grabado = new THREE.Mesh( geometriaGrabado, material) ; Grabado.applyMatrix(new THREE.Matrix4().makeTranslation(-1.5,0.45,0)); var RotacionGrabado = new THREE.Euler(0,Math.PI/2,0, 'XYZ'); Grabado.setRotationFromEuler(RotacionGrabado); var Grabado2 = new THREE.Mesh( geometriaGrabado, material) ; Grabado2.applyMatrix(new THREE.Matrix4().makeTranslation(-1.5,-0.23,0.4)); var RotacionGrabado2 = new THREE.Euler(2.15,Math.PI/2,0, 'XYZ'); Grabado2.setRotationFromEuler(RotacionGrabado2); //scene.add(Grabado2); var Grabado3 = new THREE.Mesh( geometriaGrabado, material) ; Grabado3.applyMatrix(new THREE.Matrix4().makeTranslation(-1.5,-0.23,-0.4)); var RotacionGrabado3 = new THREE.Euler(-2.15,Math.PI/2,0, 'XYZ'); Grabado3.setRotationFromEuler(RotacionGrabado3); //scene.add(Grabado3); var GrabadoCirculosline = []; GrabadoCirculosline[3] = new THREE.Vector2( 0, 0); GrabadoCirculosline[2] = new THREE.Vector2( 0.25, .5 ); GrabadoCirculosline[1] = new THREE.Vector2( 0, 1 ); GrabadoCirculosline[0] = new THREE.Vector2( -0.25, .5); var FormaGrabadoCirculos = new THREE.Shape(); FormaGrabadoCirculos .splineThru( GrabadoCirculosline); var pointsCirculos = FormaGrabadoCirculos .getPoints( resolution ); var geometryCirculos = new THREE.BufferGeometry().setFromPoints( pointsCirculos ); var curveGrabadoCirculos = new THREE.Line( geometryCirculos, material ); var geometriaGrabadoCirculo = new THREE.ExtrudeGeometry( FormaGrabadoCirculos, extrudeSettings ); var GrabadoCirculo = new THREE.Mesh( geometriaGrabadoCirculo, material) ; GrabadoCirculo.applyMatrix(new THREE.Matrix4().makeTranslation(-1.625,0.725,1.25)); var RotacionGrabadoCirculo = new THREE.Euler(-2.15,Math.PI/2,0, 'XYZ'); GrabadoCirculo.setRotationFromEuler(RotacionGrabadoCirculo); //scene.add(GrabadoCirculo); var GrabadoCirculo2 = new THREE.Mesh( geometriaGrabadoCirculo, material) ; GrabadoCirculo2.applyMatrix(new THREE.Matrix4().makeTranslation(-1.625,0.725,-1.25)); var RotacionGrabadoCirculo2 = new THREE.Euler(2.15,Math.PI/2,0, 'XYZ'); GrabadoCirculo2.setRotationFromEuler(RotacionGrabadoCirculo2); //scene.add(GrabadoCirculo2); var GrabadoCirculo3 = new THREE.Mesh( geometriaGrabadoCirculo, material) ; GrabadoCirculo3.applyMatrix(new THREE.Matrix4().makeTranslation(-1.625,-1.4,0)); var RotacionGrabadoCirculo3 = new THREE.Euler(0,Math.PI/2,0, 'XYZ'); GrabadoCirculo3.setRotationFromEuler(RotacionGrabadoCirculo3); //scene.add(GrabadoCirculo3); var geoCilindroExt = new THREE.CylinderGeometry( 0.35, 0.35, 1, 32 ); var geoCilindroInt = new THREE.CylinderGeometry( 0.3, 0.3, 1, 32 ); var geoCilindroGrande = new THREE.CylinderGeometry( 0.2, 0.2, 1, 32 ); var cilindroExt = new THREE.Mesh( geoCilindroExt, material ); var cilindroInt = new THREE.Mesh( geoCilindroInt, material2 ); var cilindroGrande = new THREE.Mesh( geoCilindroGrande, material2 ); var RotacionCilindro = new THREE.Euler(0,0,Math.PI/2, 'XYZ'); cilindroExt.applyMatrix(new THREE.Matrix4().makeTranslation(1.2,0,0)); cilindroInt.applyMatrix(new THREE.Matrix4().makeTranslation(1.2,0,0)); cilindroGrande.applyMatrix(new THREE.Matrix4().makeTranslation(1.2,0,0)); cilindroExt.setRotationFromEuler(RotacionCilindro); cilindroInt.setRotationFromEuler(RotacionCilindro); cilindroGrande.setRotationFromEuler(RotacionCilindro); var CilindroExtCSG = THREE.CSG.fromMesh( cilindroExt ); var CilindroIntCSG = THREE.CSG.fromMesh( cilindroInt ); var resultadoCilindro = CilindroExtCSG.subtract(CilindroIntCSG); cilindroExt = THREE.CSG.toMesh( resultadoCilindro ); cilindroExt.material = material2; CilindroExtCSG = THREE.CSG.fromMesh( cilindroExt ); var CilindroGrandeCSG = THREE.CSG.fromMesh( cilindroGrande ); var GrabadoCSG = THREE.CSG.fromMesh( Grabado ); var Grabado2CSG = THREE.CSG.fromMesh( Grabado2 ); var Grabado3CSG = THREE.CSG.fromMesh( Grabado3 ); var GrabadoCirculoCSG = THREE.CSG.fromMesh( GrabadoCirculo ); var GrabadoCirculo2CSG = THREE.CSG.fromMesh( GrabadoCirculo2 ); var GrabadoCirculo3CSG = THREE.CSG.fromMesh( GrabadoCirculo3 ); var LlantaIntCSG = THREE.CSG.fromMesh( LLantaInt); var resultado = LlantaIntCSG.subtract( GrabadoCSG).subtract( Grabado2CSG).subtract(Grabado3CSG ).subtract( GrabadoCirculoCSG).subtract(GrabadoCirculo2CSG ).subtract(GrabadoCirculo3CSG).subtract(CilindroExtCSG).subtract(CilindroGrandeCSG); LLantaInt = THREE.CSG.toMesh( resultado ); LLantaInt.material = material2; //scene.add(LLantaInt); var geoPunto = new THREE.Geometry(); geoPunto.vertices.push(new THREE.Vector3(0,0,0)); var matPunto = new THREE.PointsMaterial( { color: 0x000000, size: 0.1 } ); var centro = new THREE.Points(geoPunto,matPunto); centro.add( LLantaInt); centro.add(Llanta); var s = 0.35; var MatrizS = new THREE.Matrix4(); MatrizS.set( s, 0, 0, 0, 0, s, 0, 0, 0, 0, s, 0, 0, 0, 0, 1); centro.applyMatrix(MatrizS); centro.elementsNeedUpdate = true; return centro; }
C
UTF-8
3,519
3.421875
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* rot_min.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: rhohls <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/07/19 08:03:53 by rhohls #+# #+# */ /* Updated: 2018/07/19 08:04:05 by rhohls ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/push_swap.h" int min_stack (t_stack *stack_x, int *ind_min_x) { int min; int i; t_list *node; int curr_num; i = 0; min = INT_MAX; node = stack_x->start; while (node) { curr_num = *(int *)node->content; if (curr_num < min) { min = curr_num; *ind_min_x = i; } i++; node = node->next; } return (min); } t_list *rot_min_a( t_list *instruction, t_stack *stack_a, t_stack *stack_b) { int min_a; int ind_min_a; int min_direction_a; min_a = min_stack(stack_a, &ind_min_a); min_direction_a = (ind_min_a > (int)stack_a->length / 2) ? 0 : 1; // printf("direction a: %d ind_a %d\n", min_direction_a, ind_min_a); if (min_direction_a) { while (ind_min_a != 0) { do_instruction(instruction, "ra\n", stack_a, stack_b); // printf("doing - ra\n"); ind_min_a--; } } else { while (ind_min_a != (int)stack_a->length) { do_instruction(instruction, "rra\n", stack_a, stack_b); // printf("doing - rra\n"); ind_min_a++; } } return (instruction); } t_list *rot_min(t_list *instruction, t_stack *stack_a, t_stack *stack_b) { int min_a; int ind_min_b; int min_direction_b; min_a = min_stack(stack_a, &ind_min_b); min_stack(stack_b, &ind_min_b); min_direction_b = (ind_min_b > (int)stack_b->length / 2) ? 0 : 1; // printf("min a %i\n",min_a); // printf("ind min b %i length/2 b %i\n", ind_min_b, (int)stack_b->length / 2); // printf("min direction --%i-- \n", min_direction_b); if (min_direction_b) { while (ind_min_b != 0) { do_instruction(instruction, "rr\n", stack_a, stack_b); ind_min_b--; } } else { while (ind_min_b != (int)stack_b->length) { do_instruction(instruction, "rrr\n", stack_a, stack_b); ind_min_b++; } } // printf("\nStacks before min a\n"); // print_stacks(stack_a, stack_b); rot_min_a(instruction, stack_a, stack_b); // printf("\nStacks before after a\n"); // print_stacks(stack_a, stack_b); return (instruction); } t_list *rot_max_b(t_list *instruction, t_stack *stack_a, t_stack *stack_b) { int min_b; int ind_min_b; int min_direction_b; min_b = min_stack(stack_b, &ind_min_b); min_direction_b = (ind_min_b > (int)stack_b->length / 2) ? 0 : 1; printf("direction b: %d ind_b %d\n", min_direction_b, ind_min_b); if (min_direction_b) { while (ind_min_b != 0) { do_instruction(instruction, "rrb\n", stack_a, stack_b); printf("doing - rb\n"); ind_min_b--; } } else { while (ind_min_b != (int)stack_b->length) { do_instruction(instruction, "rb\n", stack_a, stack_b); printf("doing - rra\n"); ind_min_b++; } } return (instruction); }
Java
UTF-8
1,569
1.625
2
[]
no_license
package androidx.preference; import android.os.Bundle; import android.view.View; import android.widget.EditText; import androidx.annotation.NonNull; @Deprecated /* renamed from: androidx.preference.c reason: case insensitive filesystem */ public class C0149c extends n { private EditText i; private CharSequence j; private EditTextPreference b() { return (EditTextPreference) a(); } /* access modifiers changed from: protected */ public void a(View view) { super.a(view); this.i = (EditText) view.findViewById(16908291); this.i.requestFocus(); EditText editText = this.i; if (editText != null) { editText.setText(this.j); EditText editText2 = this.i; editText2.setSelection(editText2.getText().length()); return; } throw new IllegalStateException("Dialog view must contain an EditText with id @android:id/edit"); } @Deprecated public void a(boolean z) { if (z) { String obj = this.i.getText().toString(); if (b().callChangeListener(obj)) { b().a(obj); } } } public void onCreate(Bundle bundle) { super.onCreate(bundle); this.j = bundle == null ? b().g() : bundle.getCharSequence("EditTextPreferenceDialogFragment.text"); } public void onSaveInstanceState(@NonNull Bundle bundle) { super.onSaveInstanceState(bundle); bundle.putCharSequence("EditTextPreferenceDialogFragment.text", this.j); } }
Python
UTF-8
360
2.609375
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Sun Dec 8 10:50:58 2019 @author: Divy Pandya """ import numpy as np # Moore-Penrose Pseudoinverse def MPP(A): u, s, vh = np.linalg.svd(A) sinv = 1./s Dinv = np.diag(sinv) Dinv = np.concatenate((Dinv, np.zeros((A.shape[1], A.shape[0] - s.shape[0]))), axis = 1) U_T, V = u.T, vh.T return V@Dinv@U_T
Markdown
UTF-8
814
2.65625
3
[]
no_license
# Article 4 Peuvent se présenter à la consultation prévue à l'article 1er du présent arrêté les organisations syndicales de fonctionnaires mentionnées au quatrième alinéa de l'article 14 de la loi du 11 janvier 1984 susvisée. Si aucune de ces organisations syndicales ne présente de candidature ou si le nombre de votants, constaté par les émargements portés sur la liste électorale, est inférieur à la moitié des personnels appelés à voter, il est organisé un second scrutin auquel toute organisation syndicale de fonctionnaires peut participer. Ce second scrutin a lieu, le cas échéant, à une date fixée par arrêté du ministre des affaires étrangères et européennes, dans le respect du délai prévu au troisième alinéa de l'article 11 bis du décret du 28 mai 1982 susvisé.
Python
UTF-8
2,004
2.890625
3
[]
no_license
import torch from torch.utils.checkpoint import checkpoint from torch import nn #from my_checkpoint import MyCheckpointFunction, mycheckpoint from clean_checkpoint import MyCheckpointFunction, mycheckpoint class Test1(nn.Module): def __init__(self): super(Test1, self).__init__() def bottleneck(self, inp): out = torch.sum(torch.sqrt(inp)) return out def bottleneck2(self, inp): out = inp**2 + inp**3 - 2*inp return out def forward(self, inp): out = self.bottleneck(inp) #out = self.bottleneck2(out) return out class Test2(nn.Module): def __init__(self): super(Test2, self).__init__() def bottleneck(self, inp): out = torch.sum(torch.sqrt(inp)) return out def bottleneck2(self, inp): out = inp**2 + inp**3 - 2*inp return out def forward(self, inp, idx): out = mycheckpoint(self.bottleneck, inp, idx) # Only difference: use checkpoint here! #out = self.bottleneck(inp) #out = mycheckpoint(self.bottleneck2, out, idx) # Only difference: use checkpoint here! return out def grad_hess(x,y): y.backward(create_graph=True) gradient = x.grad.clone().flatten() hess = [] for g in gradient: x.grad.zero_() g.backward(create_graph=True) hess.append(x.grad.clone()) hessian = torch.stack(hess) return gradient, hessian def weird_hess(x,y): y.backward(create_graph=True) hess_row = x.grad.clone().flatten() x.grad.zero_() return hess_row x1 = torch.tensor([1.0, 2.0], requires_grad=True) model1 = Test1() y1 = model1(x1) g1,h1 = grad_hess(x1,y1) print(g1) print(h1) x2 = torch.tensor([1.0, 2.0], requires_grad=True) model2 = Test2() y2 = model2(x2, torch.tensor(0)) h2_0 = weird_hess(x2,y2) y2 = model2(x2, torch.tensor(1)) h2_1 = weird_hess(x2,y2) h2 = torch.stack((h2_0,h2_1)) print("Same value: ",torch.allclose(y1,y2)) print("Same hessian: ",torch.allclose(h1,h2))
Java
UTF-8
1,771
2.171875
2
[]
no_license
package cn.dogoo.club.pojo; import java.util.Date; import java.util.List; /** * 学生参加活动 * * @author Dogoo * */ public class ClubActUser { private String cauUid; private String caUid; private String userId; private String userUid; private String userName; private Integer cauScore;// 参加活动获得的基础分数 private Integer cauExscore;// 参加互动获得额外分数 private Integer caScore;// 对活动的评分 private Date cauTime;// 时间 private String cauMsg; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getCauMsg() { return cauMsg; } public void setCauMsg(String cauMsg) { this.cauMsg = cauMsg; } public String getUserUid() { return userUid; } public void setUserUid(String userUid) { this.userUid = userUid; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getCauUid() { return cauUid; } public void setCauUid(String cauUid) { this.cauUid = cauUid; } public String getCaUid() { return caUid; } public void setCaUid(String caUid) { this.caUid = caUid; } public Integer getCauScore() { return cauScore; } public void setCauScore(Integer cauScore) { this.cauScore = cauScore; } public Integer getCauExscore() { return cauExscore; } public void setCauExscore(Integer cauExscore) { this.cauExscore = cauExscore; } public Integer getCaScore() { return caScore; } public void setCaScore(Integer caScore) { this.caScore = caScore; } public Date getCauTime() { return cauTime; } public void setCauTime(Date cauTime) { this.cauTime = cauTime; } }
Java
UTF-8
2,585
2.140625
2
[]
no_license
package com.retail.biocare.adapter; import android.app.Dialog; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import androidx.recyclerview.widget.RecyclerView; import com.retail.biocare.R; import com.retail.biocare.model.PaymentHistoryModel; import com.retail.biocare.model.PendingWithdrawModel; import java.util.List; public class PaymentHistoryAdapter extends RecyclerView.Adapter<PaymentHistoryAdapter.DataObjectHolder> { Context context; List<PaymentHistoryModel> mData; String name; public PaymentHistoryAdapter(Context context, List<PaymentHistoryModel> mData, String name) { this.context = context; this.mData = mData; this.name = name; } public static class DataObjectHolder extends RecyclerView.ViewHolder{ TextView txtUsername,txtFullname,txtDate,txtMessage,txtAmt,txtUserid; public DataObjectHolder(View itemView) { super(itemView); txtUsername=(TextView)itemView.findViewById(R.id.txt_useerame); txtFullname=(TextView)itemView.findViewById(R.id.txt_compeltename); txtDate=(TextView)itemView.findViewById(R.id.txt_date); txtMessage=(TextView)itemView.findViewById(R.id.txt_sttaus); txtAmt=(TextView)itemView.findViewById(R.id.txtprice); txtUserid=(TextView)itemView.findViewById(R.id.txtFundId); } } @Override public DataObjectHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_payment_history, parent, false); DataObjectHolder dataObjectHolder = new DataObjectHolder(view); return dataObjectHolder; } @Override public void onBindViewHolder(final DataObjectHolder holder, final int position) { holder.txtUsername.setText(mData.get(position).getUsername()); holder.txtFullname.setText(mData.get(position).getFullname()); holder.txtAmt.setText(mData.get(position).getAmount()); holder.txtDate.setText(mData.get(position).getDate()); holder.txtMessage.setText(mData.get(position).getMessage()); holder.txtUserid.setText(name); } @Override public int getItemCount() { return mData.size(); } }
Swift
UTF-8
1,656
2.859375
3
[]
no_license
// // NewsTableViewController.swift // NewsRxSwift // // Created by Ivan Ivanov on 5/9/21. // import UIKit import RxCocoa import RxSwift class NewsTableViewController: UITableViewController { let disposeBag = DisposeBag() private var articles = [Article]() override func viewDidLoad() { super.viewDidLoad() configureNavigationBar(largeTitleColor: .white, backgoundColor: #colorLiteral(red: 0.2039215686, green: 0.5960784314, blue: 0.8588235294, alpha: 1), tintColor: .white, title: "Good News", preferredLargeTitle: true) populateNews() } private func populateNews() { URLRequest.load(resource: ArticlesList.all).subscribe(onNext: { [weak self] result in if let result = result { self?.articles = result.articles DispatchQueue.main.async { self?.tableView.reloadData() } } }).disposed(by: disposeBag) } } extension NewsTableViewController { override func numberOfSections(in tableView: UITableView) -> Int { 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return articles.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell cell.title.text = articles[indexPath.row].title cell.desciptionTitle.text = articles[indexPath.row].description return cell } }
Python
UTF-8
7,627
3.15625
3
[ "MIT" ]
permissive
import csv import pdb from sklearn.metrics import accuracy_score, precision_score, recall_score, classification_report, confusion_matrix import numpy as np class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count class Logger(object): def __init__(self, path, header): self.log_file = open(path, 'w') self.logger = csv.writer(self.log_file, delimiter='\t') self.logger.writerow(header) self.header = header def __del(self): self.log_file.close() def log(self, values): write_values = [] for col in self.header: assert col in values write_values.append(values[col]) self.logger.writerow(write_values) self.log_file.flush() class Queue: #Constructor creates a list def __init__(self, max_size, n_classes): self.queue = list(np.zeros((max_size, n_classes),dtype = float).tolist()) self.max_size = max_size self.median = None self.ma = None self.ewma = None #Adding elements to queue def enqueue(self,data): self.queue.insert(0,data) self.median = self._median() self.ma = self._ma() self.ewma = self._ewma() return True #Removing the last element from the queue def dequeue(self): if len(self.queue)>0: return self.queue.pop() return ("Queue Empty!") #Getting the size of the queue def size(self): return len(self.queue) #printing the elements of the queue def printQueue(self): return self.queue #Average def _ma(self): return np.array(self.queue[:self.max_size]).mean(axis = 0) #Median def _median(self): return np.median(np.array(self.queue[:self.max_size]), axis = 0) #Exponential average def _ewma(self): weights = np.exp(np.linspace(-1., 0., self.max_size)) weights /= weights.sum() average = weights.reshape(1,self.max_size).dot( np.array(self.queue[:self.max_size])) return average.reshape(average.shape[1],) # def LevenshteinDistance(a,b): # # This is a straightforward implementation of a well-known algorithm, and thus # # probably shouldn't be covered by copyright to begin with. But in case it is, # # the author (Magnus Lie Hetland) has, to the extent possible under law, # # dedicated all copyright and related and neighboring rights to this software # # to the public domain worldwide, by distributing it under the CC0 license, # # version 1.0. This software is distributed without any warranty. For more # # information, see <http://creativecommons.org/publicdomain/zero/1.0> # "Calculates the Levenshtein distance between a and b." # n, m = len(a), len(b) # if n > m: # # Make sure n <= m, to use O(min(n,m)) space # a,b = b,a # n,m = m,n # current = range(n+1) # for i in range(1,m+1): # previous, current = current, [i]+[0]*n # for j in range(1,n+1): # add, delete = previous[j]+1, current[j-1]+1 # change = previous[j-1] # if a[j-1] != b[i-1]: # change = change + 1 # current[j] = min(add, delete, change) # return current[n] def load_value_file(file_path): with open(file_path, 'r') as input_file: value = float(input_file.read().rstrip('\n\r')) return value def calculate_accuracy(outputs, targets): batch_size = targets.size(0) _, pred = outputs.topk(1, 1, True) pred = pred.t() correct = pred.eq(targets.view(1, -1)) n_correct_elems = correct.float().sum().item() return n_correct_elems / batch_size def calculate_precision(outputs, targets): batch_size = targets.size(0) _, pred = outputs.topk(1, 1, True) pred = pred.t() return precision_score(targets.cpu().view(-1), pred.cpu().view(-1), average = 'macro') def calculate_recall(outputs, targets): batch_size = targets.size(0) _, pred = outputs.topk(1, 1, True) pred = pred.t() return recall_score(targets.cpu().view(-1), pred.cpu().view(-1), average = 'macro') ############################################# ######## For Levenshtein Accuracy calculation def LevenshteinDistance(r, h): edit_distance_matrix = editDistance(r=r, h=h) step_list = getStepList(r=r, h=h, d=edit_distance_matrix) min_distance = float(edit_distance_matrix[len(r)][len(h)]) num_del = float(np.sum([s == "d" for s in step_list])) num_ins = float(np.sum([s == "i" for s in step_list])) num_sub = float(np.sum([s == "s" for s in step_list])) word_error_rate = round((min_distance / len(r) * 100), 4) del_rate = round((num_del / len(r) * 100), 4) ins_rate = round((num_ins / len(r) * 100), 4) sub_rate = round((num_sub / len(r) * 100), 4) # return {"wer": word_error_rate, "del": del_rate, "ins": ins_rate, "sub": sub_rate} return min_distance, num_del, num_ins, num_sub def editDistance(r, h): """ Original Code from https://github.com/zszyellow/WER-in-python/blob/master/wer.py This function is to calculate the edit distance of reference sentence and the hypothesis sentence. Main algorithm used is dynamic programming. Attributes: r -> the list of words produced by splitting reference sentence. h -> the list of words produced by splitting hypothesis sentence. """ d = np.zeros((len(r) + 1) * (len(h) + 1), dtype=np.uint8).reshape( (len(r) + 1, len(h) + 1) ) for i in range(len(r) + 1): for j in range(len(h) + 1): if i == 0: d[0][j] = j elif j == 0: d[i][0] = i for i in range(1, len(r) + 1): for j in range(1, len(h) + 1): if r[i - 1] == h[j - 1]: d[i][j] = d[i - 1][j - 1] else: substitute = d[i - 1][j - 1] + 1 insert = d[i][j - 1] + 1 delete = d[i - 1][j] + 1 d[i][j] = min(substitute, insert, delete) return d def getStepList(r, h, d): """ Original Code from https://github.com/zszyellow/WER-in-python/blob/master/wer.py This function is to get the list of steps in the process of dynamic programming. Attributes: r -> the list of words produced by splitting reference sentence. h -> the list of words produced by splitting hypothesis sentence. d -> the matrix built when calulating the editting distance of h and r. """ x = len(r) y = len(h) max_len = 3 * (x + y) list = [] while True: if (x <= 0 and y <= 0) or (len(list) > max_len): break elif x >= 1 and y >= 1 and d[x][y] == d[x - 1][y - 1] and r[x - 1] == h[y - 1]: list.append("e") x = max(x - 1, 0) y = max(y - 1, 0) elif y >= 1 and d[x][y] == d[x][y - 1] + 1: list.append("i") x = max(x, 0) y = max(y - 1, 0) elif x >= 1 and y >= 1 and d[x][y] == d[x - 1][y - 1] + 1: list.append("s") x = max(x - 1, 0) y = max(y - 1, 0) else: list.append("d") x = max(x - 1, 0) y = max(y, 0) return list[::-1]
Markdown
UTF-8
455
2.765625
3
[]
no_license
# ExifData Extracting exif data from .JPG file outputting creation date and GPS Information using Python3 # Usage : ./Exifdata.py <imageName.jpg> optional ouput Exif data file # Output Checks for Exif data in JPEG file and outputs Exif data to file: <imageName>_ExifData.txt Extracts GPS Coordinates and translates them from DMS (degree, minutes, seconds to DD (decimal) and outputs GPS data to file: <imageName>_GPSData.txt Prints out created date;
C#
UTF-8
8,053
2.515625
3
[]
no_license
using System; using System.Drawing; using ch = ConsoleHelper.Console; namespace ConsoleHelper { public class Demo { public static void Run() { var dx = ch.GetUniqueRandoms(3, 77, 345, 788, 432); dx = ch.GetUniqueRandoms(3, 77, 345, 788, 432); dx = ch.GetUniqueRandoms(3, 77, 345, 788, 432); dx = ch.GetUniqueRandoms(3, 77, 345, 788, 432); ConsoleHelper.Console.FullScreen(); startTest("DrawRectangle", (fl) => { ch.ClearScreen(); for (int i = 0; i < 10; i++) { int left, width, top, height; ch.GetRandomLeftWidth(out left, out width); ch.GetRandomTopHeight(out top, out height); ch.SetRandomFgBg(); ConsoleHelper.Console.DrawRectangle(left, top, width, height, fl); } }); //kruhy startTest("DrawCircle", (fl) => { int left, width, top, height; ConsoleHelper.Console.GetRandomLeftWidth(out left, out width); ConsoleHelper.Console.GetRandomTopHeight(out top, out height); ConsoleHelper.Console.DrawCircle( left + width / 2, top + height / 2, height / 2, 0, 360, fl); }); //ciary startTest("DrawLine", (fl) => { var x1 = ConsoleHelper.Console.GetRandomWidth(5); var y1 = ConsoleHelper.Console.GetRandomHeight(2); var x2 = ConsoleHelper.Console.GetRandomWidth(5); var y2 = ConsoleHelper.Console.GetRandomHeight(2); ConsoleHelper.Console.DrawLine(x1, y1, x2, y2); }); //elipsy startTest("DrawEllipse", (fl) => { int left, width, top, height; ConsoleHelper.Console.GetRandomLeftWidth(out left, out width); ConsoleHelper.Console.GetRandomTopHeight(out top, out height); ConsoleHelper.Console.DrawEllipse( left + width / 2, top + height / 2, width / 2, height / 2, 0, 360, fl); }); // trianglatka startTest("DrawTriangle", (fl) => { Point p1, p2, p3; p1 = new Point(ConsoleHelper.Console.GetRandomWidth(5), ConsoleHelper.Console.GetRandomHeight(2)); p2 = new Point(ConsoleHelper.Console.GetRandomWidth(5), ConsoleHelper.Console.GetRandomHeight(2)); p3 = new Point(ConsoleHelper.Console.GetRandomWidth(5), ConsoleHelper.Console.GetRandomHeight(2)); ConsoleHelper.Console.DrawTriangle(p1, p2, p3, fl); }); bounce(); } private static void bounce() { resetHeads("MoveRectangle"); var head1 = new Head(); //var head2 = new Head(); bool stop = false; bool wait = true; while (true) { while (!System.Console.KeyAvailable) { head1.move(wait); //head2.move(wait); } var kch = System.Console.ReadKey().KeyChar; switch (kch) { case 'c': resetHeads("MoveRectangle"); head1 = new Head(); //head2 = new Head(); break; case 'w': wait = !wait; break; default: stop = true; break; } if (stop) { break; } } } private static void startTest(string msg, Action<bool> act) { bool fill = false; bool wait = true; ch.ResetColor(); while (true) { reset(msg); while (!System.Console.KeyAvailable) { ConsoleHelper.Console.SetRandomForeground(); act(fill); if (wait) ConsoleHelper.Console.Wait(300); } var ky = System.Console.ReadKey().KeyChar; var stop = false; switch (ky) { case 'f': fill = !fill; break; case 'w': wait = !wait; break; case 'c': reset(msg); break; default: stop = true; break; } if (stop) { break; } } } private static void reset(string msg) { System.Console.ResetColor(); System.Console.Clear(); System.Console.WriteLine($"{msg}, f - toggle fill, c - clear, w - toggle wait, other - continue"); } private static void resetHeads(string msg) { System.Console.ResetColor(); System.Console.Clear(); System.Console.WriteLine($"{msg}, c - new, w - toggle wait, other - continue"); } } public class Head { int moveByX = 0; int moveByY = 0; Rectangle rect; int border = 0; int maxMove = 5; public Head() { int l = 0, t = 0, r = 0; r = ch.Rand.Next(10, 15); while (l <= border + r + 1) l = ch.Rand.Next(5, 100); while (t <= border + r + 1) t = ch.Rand.Next(5, 20); rect = new Rectangle(l - r, t - ch.ZoomIntNumber(r, 0.5), r * 2 + 1, r + 1); ch.SetRandomForeground(); ch.DrawCircle(l, t, r, 0, 360, true); ch.SetRandomForeground(); ch.DrawCircle(l - 4, t - 2, 2, 0, 180, true); ch.SetRandomForeground(); ch.DrawCircle(l + 4, t - 2, 2, 0, 180, false); ch.SetRandomForeground(); ch.DrawCircle(l, t + 4, 4, 180, 180, false); while (moveByX == 0) moveByX = ch.Rand.Next(-maxMove, maxMove); while (moveByY == 0) moveByY = ch.Rand.Next(-maxMove, maxMove); ch.ResetColor(); } internal void move(bool wait) { rect = ConsoleHelper.Console.MoveRectangle(rect, moveByX, moveByY); var beep = false; if (rect.Left <= border - moveByX) { moveByX = ch.Rand.Next(1, maxMove); beep = true; } else if (rect.Left + rect.Width >= System.Console.WindowWidth - border - moveByX) { moveByX = ch.Rand.Next(-maxMove, -1); beep = true; } if (rect.Top <= border - moveByY) { moveByY = ch.Rand.Next(1, maxMove); beep = true; } else if (rect.Top + rect.Height >= System.Console.WindowHeight - border - moveByY) { moveByY = ch.Rand.Next(-maxMove, -1); beep = true; } if (beep) ch.Beep(); if (wait) ch.Wait(50); } } }
Java
UTF-8
2,155
2.765625
3
[]
no_license
package zedly.zenchantments.enchantments; import org.bukkit.entity.Entity; import org.bukkit.entity.MushroomCow; import org.bukkit.entity.Player; import org.bukkit.entity.Sheep; import org.bukkit.event.player.PlayerEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerShearEntityEvent; import zedly.zenchantments.CustomEnchantment; import zedly.zenchantments.enums.Hand; import zedly.zenchantments.enums.Tool; import static org.bukkit.event.block.Action.RIGHT_CLICK_AIR; import static org.bukkit.event.block.Action.RIGHT_CLICK_BLOCK; import static zedly.zenchantments.enums.Tool.SHEAR; public class Mow extends CustomEnchantment { public static final int ID = 37; @Override public Builder<Mow> defaults() { return new Builder<>(Mow::new, ID) .maxLevel(3) .loreName("Mow") .probability(0) .enchantable(new Tool[]{SHEAR}) .conflicting(new Class[]{}) .description("Shears all nearby sheep") .cooldown(0) .power(1.0) .handUse(Hand.RIGHT); } private boolean shear(PlayerEvent evt, int level, boolean usedHand) { boolean shearedEntity = false; int radius = (int) Math.round(level * power + 2); Player player = evt.getPlayer(); for (Entity ent : evt.getPlayer().getNearbyEntities(radius, radius, radius)) { if (ent instanceof Sheep) { Sheep sheep = (Sheep) ent; if (sheep.isAdult()) { ADAPTER.shearEntityNMS(sheep, player, usedHand); shearedEntity = true; } } else if (ent instanceof MushroomCow) { MushroomCow mCow = (MushroomCow) ent; if (mCow.isAdult()) { ADAPTER.shearEntityNMS(mCow, player, usedHand); shearedEntity = true; } } } return shearedEntity; } @Override public boolean onBlockInteract(PlayerInteractEvent evt, int level, boolean usedHand) { if (evt.getAction() == RIGHT_CLICK_AIR || evt.getAction() == RIGHT_CLICK_BLOCK) { return shear(evt, level, usedHand); } return false; } @Override public boolean onShear(PlayerShearEntityEvent evt, int level, boolean usedHand) { return shear(evt, level, usedHand); } }
JavaScript
UTF-8
957
2.953125
3
[]
no_license
import React from "react"; class ExerciseOneInput extends React.Component { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); this.handleCheckboxChange = this.handleCheckboxChange.bind(this); } handleCheckboxChange(ev) { let divisor; if (ev.target.checked === true) { divisor = 2; } else { divisor = 1; } this.props.handleCheckboxChange(divisor); } handleChange(ev) { const inputValue = ev.target.value; this.props.handleInputChange(inputValue); } render() { return ( <> <input type="number" name="number" onChange={this.handleChange} /> <label htmlFor="even">Mostrar solo los pares</label> <input type="checkbox" name="even" onChange={this.handleCheckboxChange} id="even" /> </> ); } } export default ExerciseOneInput;
Markdown
UTF-8
2,692
2.5625
3
[]
no_license
--- author: cyoasu date: 2015-10-01 11:58:09+00:00 draft: false title: 'JACKA THE MUSICAL: The AFUO encourages you to come and witness this production' type: post url: /culture/jacka-the-musical-the-afuo-encourages-you-to-come-and-witness-this-production/ categories: - Culture --- ![Australian Federation of Ukrainian Organisations](http://www.ozeukes.com/wp-content/uploads/2014/10/image001.png) **JACKA THE MUSICAL** **The AFUO encourages you to come and witness this production** As many of you may be aware  Prof Michael Lawriwsky wrote a book about Albert Jacka and his role in WWI. Jacka received Australia's first Victoria Cross of the war. _“He was one of the first people among 300,000 plus Australians to volunteer,"._ _"It was just that adventurous spirit he had."_ _A private in the 14th Battalion, Jacka landed at Anzac Cove late in the day on April 25 and was soon on his way to the frontline._ _In Jacka's case this turned out to be Courtney's Post, about a kilometre inland from the beach and one of the most dangerous spots on the peninsula_. noted Jacka's biographer Michael Lawriwsky _He thought if you got a VC you had to stick with the men. You couldn't just rest on your laurels and go away. You had to stick it out and take the same chances as everybody else._ Michael Lawriwsky, biographer **The Jacka VC Musical is now just over 1 week away at the ** **DAREBIN ARTS AND ENTERTAINMENT CENTRE** **Friday 9 October 8pm** **Saturday 10 October 2pm and 8pm** Tickets $38 / $34 Concession, Veterans, RSL members Web: [http://www.darebinartscentre.com.au](http://www.darebinartscentre.com.au) Phone: (03) 8470 8282 **CAPITAL THEATRE BENDIGO** **17 October 2015 8pm** Tickets $38 / $34 Concession, Veterans, RSL members Web: [http://www.thecapital.com.au](http://www.thecapital.com.au) Phone: (03) 5434 6100 For further information please visit [www.jackavc.com.au](http://www.jackavc.com.au) or email [promotion@jackavc.com.au](mailto:promotion@jackavc.com.au) Australia has never seen anything like it before. An incredible roller-coaster ride of emotions, it depicts the drama and tragedy of key battles at Gallipoli and the Western Front, a number of Aussie larrikin comedy routines including a football-rugby stand-off, a casino/bar room brawl in Cairo, a song about ‘two-up’, and a love story set in Scotland. With costumes, innovative sets, pyro-technics and the backing of a 25 piece orchestra, it will leave the audience enthralled. Here is more information https://www.youtube.com/watch?v=XHDrQtIYNyM https://www.youtube.com/watch?v=cGHwqPtBwZE&feature;=youtu.be Next Monday 5 October at 1:20pm Michael  will be interviewed by Richard Stubbs on 3LO. The AFUO congratulates Michael on his efforts. Book now!
Java
UTF-8
1,078
2.90625
3
[ "MIT" ]
permissive
package <missing>; public class GlobalMembers { public static void Main() { int n; int i; int j = 0; int k = 0; int l; String tempVar = ConsoleInput.scanfRead(); if (tempVar != null) { n = Integer.parseInt(tempVar); } //C++ TO JAVA CONVERTER TODO TASK: Java does not allow declaring types within methods: // struct p // { // char id[10]; // int age; // } // a[n],b[n],c[n],d; for (i = 0;i < n;i++) { String tempVar2 = ConsoleInput.scanfRead(); if (tempVar2 != null) { a[i].id = tempVar2; } String tempVar3 = ConsoleInput.scanfRead(" "); if (tempVar3 != null) { a[i].age = tempVar3; } if (a[i].age >= 60) { b[j] = a[i]; j++; } else { c[k] = a[i]; k++; } } for (i = 0;i < j - 1;i++) { for (l = 0;l < j - 1 - i;l++) { if (b[l].age < b[l + 1].age) { d = b[l]; b[l] = b[l + 1]; b[l + 1] = d; } } } for (i = 0;i < j;i++) { System.out.printf("%s\n",b[i].id); } for (i = 0;i < k;i++) { System.out.printf("%s\n",c[i].id); } } }
Java
UTF-8
805
2.140625
2
[]
no_license
package hu.myprojects.flighttracker.controller; import hu.myprojects.flighttracker.dao.FlightRepository; import hu.myprojects.flighttracker.domain.Flight; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import java.util.List; @Controller public class HomeController { @Autowired private FlightRepository repository; @RequestMapping(value = "/", method = RequestMethod.GET) public String listFlight(Model model) { List<Flight> flights = repository.findAll(); model.addAttribute("flights", flights); return "listFlight.html"; } }
Java
UTF-8
2,000
2.53125
3
[]
no_license
package base; import org.openqa.selenium.WebDriver; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Map; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; public class Base { public static final String USERNAME = "speianudana1"; public static final String AUTOMATE_KEY = "yHotttDFUPdR1pLRmqYS"; public static final String URL = "https://" + USERNAME + ":" + AUTOMATE_KEY + "@hub-cloud.browserstack.com/wd/hub"; DesiredCapabilities caps = new DesiredCapabilities(); protected WebDriver driver; public Base() { caps.setCapability("os", "Windows"); caps.setCapability("os_version", "10"); caps.setCapability("browser", "Chrome"); caps.setCapability("browser_version", "80"); caps.setCapability("name", "speianudana1's First Test"); ChromeOptions options = new ChromeOptions(); Map < String, Object > prefs = new HashMap < String, Object > (); Map < String, Object > profile = new HashMap < String, Object > (); Map < String, Object > contentSettings = new HashMap < String, Object > (); // SET CHROME OPTIONS // 0 - Default, 1 - Allow, 2 - Block contentSettings.put("geolocation", 1); profile.put("managed_default_content_settings", contentSettings); prefs.put("profile", profile); options.setExperimentalOption("prefs", prefs); // SET CAPABILITY caps.setCapability(ChromeOptions.CAPABILITY, options); try { driver = new RemoteWebDriver(new URL(URL), options); } catch (MalformedURLException e) { e.printStackTrace(); } driver.manage().window().maximize(); } public void tearDown() { driver.close(); driver.quit(); driver = null; System.out.println("Working Driver was closed."); } }
Python
UTF-8
444
3.875
4
[]
no_license
walk_in_min = int(input()) count_walk_in_day = int(input()) calories_per_day = int(input()) calories_burn = count_walk_in_day * walk_in_min * 5 total_calories = calories_per_day - calories_burn if calories_burn >= total_calories / 2: print(f"Yes, the walk for your cat is enough. Burned calories per day: {calories_burn}.") else: print(f"No, the walk for your cat is not enough. Burned calories per day: {calories_burn}.")
TypeScript
UTF-8
964
3.0625
3
[ "MIT" ]
permissive
import Message from "../../interfaces/Message"; import State from "../../interfaces/State"; import { CREATE_MESSAGE, GET_MESSAGES_FOR_CHANNEL, SET_FETCHING_MSGS } from "../types"; const initState: State["message"] = { messages: [], loading: true, }; type Actions = | { type: typeof CREATE_MESSAGE; } | { type: typeof GET_MESSAGES_FOR_CHANNEL; messages: Message[]; } | { type: typeof SET_FETCHING_MSGS; loading: boolean; }; export default function messageReducer(state = initState, action: Actions): State["message"] { switch (action.type) { case "CREATE_MESSAGE": { return { ...state, }; } case "GET_MESSAGES_FOR_CHANNEL": { return { ...state, messages: action.messages, }; } case "SET_FETCHING_MSGS": { return { ...state, loading: action.loading, }; } default: { return { ...state }; } } }
Python
UTF-8
1,224
3.328125
3
[ "MIT" ]
permissive
from . import constants from .decorators import DebugDecorator class Utilities: @staticmethod @DebugDecorator() def get_shift_by_direction(direction_index): """ Function return shift depending on direction. Args: direction_index(int): index specified direction Returns: (int, int): shift by columns and rows """ shift_x = constants.all_shifts[direction_index]['x'] shift_y = constants.all_shifts[direction_index]['y'] return shift_x, shift_y @staticmethod @DebugDecorator() def get_new_coordinates(direction_index, x, y): """ Function returns new coordinates of player shifted in specified direction Args: direction_index(int): index presenting direction x(int): coordinate by columns of current player position y(int): coordinate by rows of current player position Returns: (int, int): new player's coordinates """ shift_x, shift_y = Utilities.get_shift_by_direction(direction_index) new_x, new_y = shift_x + x, shift_y + y return new_x, new_y
Python
UTF-8
2,960
3.9375
4
[]
no_license
""" 文件操作 打开 open(文件名,打开方式) 默认以只读形式打开文件 f 只读,默认值 w 只写,若文件存在,覆盖原文件,若文件不存在,自动创建 a 追加 r+ 读写,若文件不存在,抛出异常 w+ 读写,若文件存在,覆盖原文件,若文件不存在,自动创建 a+ 读写,若文件存在,在文件指针指向末尾追加,若不存在,自动创建 注意:频繁移动文件指针会影响文件读写效率,所以一般使用无+号的三个参数 读 read() 分行读 readline() 写 write() 关闭 close() 文件指针 在使用open()打开文件后,文件指针指向文件开头 使用read()后,文件指针指向文件结尾,默认读取文件所有内容 再次调用read(),就没有任何数据可以获取了 import os 文件/文件夹操作的包 """ import os # 文件/文件夹操作的包 """打开文件""" file = open("readme.txt") # 会在当前目录下寻找 """读取文件""" text = file.read() print(text) print("*" * 34) text2 = file.read() print(text2) # 没有内容输出 # file.write("try to write") # 文件是以只读的形式打开的,不能进行写的操作:io.UnsupportedOperation: not writable """关闭文件""" file.close() """以追加方式写入文件""" file = open("readme.txt", "a") file.write("phone:10086") file.close() """分行读取""" file = open("readme.txt") while True: text3 = file.readline() if not text3: break print(text3) file.close() """小文件的复制,可以一次读取,一次写入""" # file1 = open("readme.txt") # file2 = open("readme[copy].txt","w") # 只写,文件不存在会自动创建,创建在当前文件夹下 # # text = file1.read() # file2.write(text) # # file1.close() # file2.close() """大文件的复制,分行读写""" # file1 = open("readme.txt") # file2 = open("readme[copy].txt","w") # 只写,文件不存在会自动创建,创建在当前文件夹下 # # while True: # text = file1.readline() # if not text: # break # file2.write(text) # # file1.close() # file2.close() """ 文件/文件夹的相关操作 要导入os包 """ """重命名文件""" # os.rename("readme[copy].txt","README[COPY].txt") """删除文件""" # os.remove("README[COPY].txt") """查看目录下的内容""" # dir_list = os.listdir(".") # print(dir_list) """判断是否是文件夹""" # print(os.path.isdir("ibbie_45_发布模块")) # True # print(os.path.isdir("HelloPython.py")) # False """创建与删除目录""" # os.mkdir("test") # 若文件夹已存在:FileExistsError: [WinError 183] 当文件已存在时,无法创建该文件。: 'test' # os.rmdir("test") # 若文件夹不存在:FileNotFoundError: [WinError 2] 系统找不到指定的文件。: 'test' """获取当前目录""" dir_curr = os.getcwd() print(dir_curr)
TypeScript
UTF-8
273
2.546875
3
[]
no_license
import {EventRequestTypes} from '../request.types.enum'; export function getCommandTypeFromText(text: string): EventRequestTypes { if (!text) { console.log('No body'); return; } return (text.toLowerCase().slice(0, text.indexOf(' '))) as EventRequestTypes; }
JavaScript
UTF-8
390
3.90625
4
[]
no_license
const triple_steps = (n) => { if (n == 0 || n == 1) return 1 if (n < 0) return 0 let res = new Array(n + 1).fill(-1) res[0] = 1 res[1] = 1 res[2] = 2 for (let i = 3; i <= n; i++) { res[i] = res[i - 1] + res[i - 2] + res[i - 3] } return res[res.length - 1] } console.log(triple_steps(5)) console.log(triple_steps(1)) console.log(triple_steps(0))
PHP
UTF-8
2,906
2.515625
3
[]
no_license
<?php namespace app\controllers; use app\models\forms\CopyForm; use app\services\ClientLetterSearch; use Yii; use yii\data\ArrayDataProvider; use yii\filters\AccessControl; use yii\web\Controller; use yii\web\Response; use yii\filters\VerbFilter; use app\models\LoginForm; use app\models\ContactForm; class SiteController extends Controller { /** * {@inheritdoc} */ public function actions() { return [ 'error' => [ 'class' => 'yii\web\ErrorAction', ], ]; } /** * Displays homepage. * * @return string */ public function actionCopy(): string { $copyForm = new CopyForm(); if ($copyForm->load(Yii::$app->request->post())) { if ($copyForm->runService()) { foreach ($copyForm->report as $item) { Yii::$app->session->addFlash('success', $item); } } else { foreach ($copyForm->errors as $error) { Yii::$app->session->addFlash('error', $error); } } } $search = new ClientLetterSearch(); $allModels = $search->getLastPrevLetterList(); $arrayDataProvider = new ArrayDataProvider([ 'allModels' => $allModels, ]); if ($search->hasErrors()) { Yii::$app->session->addFlash('error', $search->errors); } return $this->render('copy', [ 'copyForm' => $copyForm, 'dataProvider' => $arrayDataProvider, ]); } /** * @return string|Response */ public function actionOpenFile() { $prepareFileToOpen = ''; $post = Yii::$app->request->post(); if (\array_key_exists('file', $post) && null !== $post['file'] && '' !== $post['file']) { $prepareFileToOpen = Yii::$app->request->post('file'); } if (file_exists($prepareFileToOpen)) { if (0 === strncasecmp(PHP_OS, 'win', 3)) { $prepareFileToOpen = '"' . $prepareFileToOpen . '"'; } $config = [ 0 => ['pipe', 'r'], // stdin - канал, из которого дочерний процесс будет читать 1 => ['pipe', 'w'], // stdout - канал, в который дочерний процесс будет записывать 2 => ['file', sys_get_temp_dir() . '/error-output.txt', 'a'] // stderr - файл для записи ]; $process = proc_open($prepareFileToOpen, $config, $pipes, null, null, ['bypass_shell']); return '<script>window.close()</script>'; } Yii::$app->session->addFlash('error', 'Указанный файл не существует: ' . $prepareFileToOpen); return $this->redirect(['site/copy']); } }
Python
UTF-8
2,740
4.09375
4
[]
no_license
# --- Day 1: Report Repair --- # After saving Christmas five years in a row, you've decided to take a # vacation at a nice resort on a tropical island. Surely, Christmas will go on # without you. # The tropical island has its own currency and is entirely cash-only. The gold # coins used there have a little picture of a starfish; the locals just call # them stars. None of the currency exchanges seem to have heard of them, but # somehow, you'll need to find fifty of these coins by the time you arrive so # you can pay the deposit on your room. # To save your vacation, you need to get all fifty stars by December 25th. # Collect stars by solving puzzles. Two puzzles will be made available on each # day in the Advent calendar; the second puzzle is unlocked when you complete # the first. Each puzzle grants one star. Good luck! # Before you leave, the Elves in accounting just need you to fix your expense # report (your puzzle input); apparently, something isn't quite adding up. # Specifically, they need you to find the two entries that sum to 2020 and # then multiply those two numbers together. # For example, suppose your expense report contained the following: # 1721 # 979 # 366 # 299 # 675 # 1456 # In this list, the two entries that sum to 2020 are 1721 and 299. Multiplying # them together produces 1721 * 299 = 514579, so the correct answer is 514579. # Of course, your expense report is much larger. Find the two entries that sum # to 2020; what do you get if you multiply them together? # To begin, get your puzzle input. # Answer: # Your puzzle answer was 1010884. # --- Part Two --- # The Elves in accounting are thankful for your help; one of them even offers # you a starfish coin they had left over from a past vacation. They offer you # a second one if you can find three numbers in your expense report that meet # the same criteria. # Using the above example again, the three entries that sum to 2020 are 979, # 366, and 675. Multiplying them together produces the answer, 241861950. # In your expense report, what is the product of the three entries that sum to # 2020? # Your puzzle answer was 253928438. # values = [1721, 979, 366, 299, 675, 1456] # Expect 514579 # Read data with open("01.data") as f: values = f.read().splitlines() values = [int(v) for v in values] def sum_to_2020(a: int, b: int, c: int = 0): if a + b + c == 2020: return True else: return False # Part 1 # for a in values: # for b in values: # if sum_to_2020(a, b): # print(f"{a=} * {b=} = {a*b}") # Part 2 for a in values: for b in values: for c in values: if sum_to_2020(a, b, c): print(f"{a=} * {b=} * {c=} = {a*b*c}")
Ruby
UTF-8
559
3.28125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Hash def keys_of(*args) map {|key, value| args.include?(value) ? key : nil }.compact end end class Hash def keys_of(*arguments) array = [] self.each do |key, value| arguments.each do |i| if i == value array.push(key) end end end return array end end class Hash def keys_of(*arguments) arr = [] arguments.each do |arg| self.each do |key, val| if arg == val arr.push(key) end end end arr end end
Java
UTF-8
2,245
3.65625
4
[]
no_license
public class TraitsInJava { public interface Coffee { // getter for val basePrice double basePrice(); // implementation of Coffee.price to be used for calls to super.price in mixin static double price$(Coffee c) { return c.basePrice(); } // default implementation of method price for Coffee default double price() { return price$(this); } } public interface Sugar extends Coffee { // Sugar's super.price to be determined during mixin double Sugar$$super$price(); // implementation of Sugar.price to be used for calls to super.price in mixin static double price$(Sugar s) { return s.Sugar$$super$price() + 0.5; } // default implementation of method price for Sweetened default double price() { return price$(this); } } public interface Milk extends Coffee { // Milk's super.price to be determined during mixin double Milk$$super$price(); // implementation of Milk.price to be used for calls to super.price in mixin static double price$(Milk m) { return m.Milk$$super$price() + 0.5; } // default implementation of method price for Milky default double price() { return price$(this); } } /* Scala: * class CoffeeWithSugarMilk extends Coffee with Sugar with Milk { * val basePrice = 1.0 * } */ public static class CoffeeWithSugarMilk implements Sugar, Milk { // val basePrice = 1.0 final double basePrice = 1.0; // implementation of getter method for val basePrice public double basePrice() { return basePrice; } // Milk's super.price is resolved to Sweetened.price public double Milk$$super$price() { return Sugar.price$(this); } // Sugar's super.price is resolved to Coffee.price public double Sugar$$super$price() { return Coffee.price$(this); } // Milky is last trait that is mixed in, so inherit its implementation of price. public double price() { return Milk.price$(this); } } public static void main(String[] args) { Coffee c = new CoffeeWithSugarMilk(); System.out.println("A coffee with sugar and milk costs $" + c.price()); } }
JavaScript
UTF-8
2,302
2.6875
3
[]
no_license
import DCast from 'dcast' import randomWords from 'random-words' import chalk from 'chalk' const FULL_USAGE = ` The cast command is a general-purpose tool for sending data over the dWeb according to a secret passphrase. You choose a phrase (try to make it hard-ish to guess!) and then share the phrase with your recipient. The phrase is only good for 30-60 minutes. On the sending device: cat hello.txt | dweb cast "for Satoshi" On the receiving device: dweb cast "for Satoshi" > ./hello.txt This can be really useful for sharing dweb keys between devices. For instance: > dweb sync ./my-folder Creating new dDrive... Source: my-folder/ Target: dweb://f7145e1bbc0d17705861e996b47422e0ca50a80db9441249bd721ff426b79f2a/ Begin sync? [y/N] y Syncing... Synced > echo "dweb://f7145e1bbc0d17705861e996b47422e0ca50a80db9441249bd721ff426b79f2a/" \\ | dweb cast "nobody can guess" ` export default { name: 'cast', description: 'Send a stream of data over the dWeb.', usage: { simple: '[passphrase]', full: FULL_USAGE }, command: async function (args) { var phrase = args._[0] ? args._.join(' ') : randomWords(3).join(' ') const cast = new DCast(phrase) if (!args._[0]) { console.error('[dcast] Generated passphrase:') console.error('') console.error(' ', chalk.bold(phrase)) console.error('') } cast.on('remote-address', function ({ host, port }) { if (!host) console.error('[dcast] Could not detect remote address') else console.error('[dcast] Joined the dWeb DHT - remote address is ' + host + ':' + port) if (port) console.error('[dcast] Network is holepunchable \\o/') }) cast.on('connected', function () { console.error('[dcast] Success! Encrypted tunnel established to remote peer') }) cast.on('end', () => cast.end()) process.stdin.pipe(cast).pipe(process.stdout) process.stdin.unref() process.once('SIGINT', () => { if (!cast.connected) closeASAP() else cast.end() }) function closeASAP () { console.error('[dcast] Shutting down cast...') const timeout = setTimeout(() => process.exit(1), 2000) cast.destroy() cast.on('close', function () { clearTimeout(timeout) }) } } }
Java
UTF-8
1,193
2.328125
2
[]
no_license
package ru.yaal.project.hhapi.loader.cache; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; public class MemoryStorageTest { @Test public void testSave() throws Exception { int lifeTimeMin = 10; ICache storage = new MemoryCache(lifeTimeMin); String name = "http://nasa.com?curiosity=good"; assertNull(storage.search(name)); String expContent = "{gangnamStyle:PSY}"; storage.save(name, expContent); String actContent = storage.search(name); assertEquals(expContent, actContent); storage.delete(name); assertNull(storage.search(name)); storage.save(name, expContent); storage.clear(); assertNull(storage.search(name)); } @Test public void outdated() throws Exception { int lifeTimeMin = 0; ICache storage = new MemoryCache(lifeTimeMin); String name = "http://danceja.com"; String content = "{Dancehall:'Vybz Kartel'}"; storage.save(name, content); Thread.sleep(100); String actContent = storage.search(name); assertNull(actContent); } }
Python
UTF-8
1,068
3.03125
3
[]
no_license
class Subsir: def __init__(self, index, subsir, lungime): self.index = index self.subsir = subsir self.lungime = lungime ### CITIRE DATE ### lungime_sir = int(raw_input()) sir = [float(x) for x in raw_input().split()] ### PRELUCRARE DATE ### if all(sir[i] < 0 for i in range(len(sir))): ### Daca toate valorile sirului sunt negative: se printeaza "-1 0" print("-1" + "\n" + "0") else: lista = [] tmp_subsir = [] tmp_index = 0 for i in range(lungime_sir): if sir[i] >= 0: tmp_subsir.append(sir[i]) if sir[i-1] < 0 and i != 0: tmp_index = i else: tmp_subsir = [] if len(tmp_subsir) != 0: lista.append( Subsir(tmp_index, tmp_subsir, len(tmp_subsir)) ) index = 0 max_lungime = -1 for i in range(len(lista)): if lista[i].lungime > max_lungime: index = i max_lungime = lista[i].lungime print(str(lista[index].index) + '\n' + str(lista[index].lungime))
JavaScript
UTF-8
593
2.5625
3
[ "MIT" ]
permissive
import { ACTION_TYPE_MON_AN } from "../actions/monAn"; const list = { listMonAn : [] } const monAn = (state = list, action) => { switch(action.type){ case ACTION_TYPE_MON_AN.FETCH_ALL_MON_AN : return { ...state , listMonAn : [...action.payload] } // case ACTION_TYPE_MON_AN.CREATE_MON_AN : // return { // ...state , // listMonAn : [...state.listMonAn,...action.payload] // } default : return state ; } } export default monAn;
SQL
UTF-8
1,491
2.9375
3
[]
no_license
PROMPT ===================================================================================== PROMPT *** Run *** ========== Scripts /Sql/BARS/View/CHECK_42A.sql =========*** Run *** ==== PROMPT ===================================================================================== PROMPT *** Create view CHECK_42A *** CREATE OR REPLACE FORCE VIEW BARS.CHECK_42A ("VDATE", "RNK", "NMK", "OST") AS select a.fdat, c.rnk, c.nmk, SUM(gl.p_icurval( a.kv, a.ost, a.fdat)) from sal a, cust_acc ca, customer c, kl_f3_29 kl where ca.acc=a.acc and ca.rnk=c.rnk and kl.kf='42' and a.nbs=kl.r020 and a.ost<>0 group by a.fdat, c.rnk, c.nmk; PROMPT *** Create grants CHECK_42A *** grant SELECT on CHECK_42A to BARSREADER_ROLE; grant SELECT on CHECK_42A to BARS_ACCESS_DEFROLE; grant SELECT on CHECK_42A to START1; grant SELECT on CHECK_42A to UPLD; PROMPT ===================================================================================== PROMPT *** End *** ========== Scripts /Sql/BARS/View/CHECK_42A.sql =========*** End *** ==== PROMPT =====================================================================================
Go
UTF-8
2,648
3.328125
3
[]
no_license
package model import ( "encoding/json" "fmt" "github.com/zxccl0518/go_study/chatroom/common/message" "github.com/garyburd/redigo/redis" ) // 我们在服务器启动后,就初始化一个userDao的实例, // 把它做成全局的,在需要和redis操作时,就直接使用即可 var ( MyUserDao *UserDao ) // 定义一个结构体,完成对User 结构体的各种操作 type UserDao struct { pool *redis.Pool } // 使用工厂模式,创建一个UserDao的实例。 func NewUserDao(pool *redis.Pool) (userDao *UserDao) { userDao = &UserDao{ pool: pool, } return } // 思考一下,UserDao 应该提供哪些方法 // 1.根据用户id 返回一个User实例+err func (this *UserDao) getUserByID(conn redis.Conn, userID int) (user *User, err error) { // 通过给定的id 去redis查询用户, res, err := redis.String(conn.Do("HGET", "users", userID)) if err != nil { // 表示在user哈希中,没有找到对应的id if err == redis.ErrNil { err = ERROR_USER_NOT_EXISTS } return } fmt.Println("UserDao.go === > res = ", res) user = &User{} // 我们需要把 res反序列化成user实例。 err = json.Unmarshal([]byte(res), user) if err != nil { fmt.Println("user 反序列化失败。") } return } // 完成登录的一个校验 // 1.Login() 完成对用户的验证, // 2.如果用户的id 密码都正确,返回一个user实例。 // 3.如果用户的id 或者密码不正确。返回一个错误的信息。 func (this *UserDao) Login(userID int, userPwd string) (user *User, err error) { // 先从 userDao连接池中,取出一个连接。 conn := this.pool.Get() defer conn.Close() user, err = this.getUserByID(conn, userID) if err != nil { return } // 到了这步,证明用户是获取到了,但是不知道密码是否正确。 if user.UserPwd != userPwd { err = ERROR_USER_PWD return } return } func (this *UserDao) Rigister(user *message.RigisterMes) (err error) { conn := this.pool.Get() defer conn.Close() _, err = this.getUserByID(conn, user.User.UserID) if err == nil { fmt.Println("此时 用户已经存在。") return } // 测试说明id在redis中还没有,则允许完成注册 data, err := json.Marshal(user.User) if err != nil { fmt.Println("Rigister 序列化 用户注册信息 失败。") return } // 向 数据库中写入注册信息 fmt.Println("注册成功,想数据库写入数据之前 查看数据 data = ", string(data)) _, err = conn.Do("HSET", "users", user.User.UserID, string(data)) if err != nil { fmt.Println("register 向redis写入数据失败。 err = ", err) return } return }