language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
Java
|
UTF-8
| 1,165 | 2.3125 | 2 |
[
"Apache-2.0"
] |
permissive
|
package drakonli.jcomponents.file;
import drakonli.jcomponents.file.impl.BufferedCharsetLineEndingIncludedFileReaderFactory;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.internal.matchers.apachecommons.ReflectionEquals;
import java.io.*;
import java.nio.charset.Charset;
public class BufferedCharsetLineEndingIncludedFileReaderFactoryTest
{
@Test
@Ignore("Skipping test. Can not find a way to test equality of resulting readers")
public void createFileReader() throws IOException
{
File file = new File("someName.txt");
Charset charset = java.nio.charset.StandardCharsets.UTF_16LE;
BufferedReader expectedReader =
new BufferedReader(
new InputStreamReader(
new FileInputStream(file),
charset
)
);
BufferedReader actualReader = (new BufferedCharsetLineEndingIncludedFileReaderFactory(charset))
.createFileReader(file);
Assert.assertThat(expectedReader, new ReflectionEquals(actualReader));
}
}
|
Java
|
UTF-8
| 367 | 1.710938 | 2 |
[] |
no_license
|
package edu.wpi.cs3733.d19.teamO;
import com.google.common.eventbus.EventBus;
import com.google.inject.AbstractModule;
public class ProjectModule extends AbstractModule {
@Override
protected void configure() {
bind(EventBus.class).asEagerSingleton();
bind(AppPreferences.class).asEagerSingleton();
bind(GlobalState.class).asEagerSingleton();
}
}
|
Markdown
|
UTF-8
| 1,190 | 2.9375 | 3 |
[] |
no_license
|
# spring-boot-camel
This application is developed on Spring Boot Framework. It receives address parameter in HTTP GET request via a REST interface, forwards it to an integration layer written on Apache Camel.
The integration layer then sends this request to Google Geocoding API as an HTTP request, receives the response in XML format, maps the response to a Pojo object, and sends it back to the REST layer.
The REST layer converts this object into JSON and sends the response back to the client.
XML -> Pojo transformation is done by using JAXB library, and Pojo -> JSON transformation is done by Jsonpath
# How to call the service
Open a browser and send a GET request to the following URL
http://localhost:8080/location?address=Jacob Bontiusplaats 91018 LL, Amsterdam The Netherlands
The response will be
```
{"status":"OK","lat":"52.3714238","lng":"4.9269278","address":"Jacob Bontiusplaats, 1018 Amsterdam, Netherlands"}
```
# Building and running the service
Execute the command below:
```
mvn spring-boot:run
```
# Testing the service
There are 2 test cases, one is for the Camel component, the other is for the REST Component. Both tests can be run by typing:
```
mvn test
```
|
Python
|
UTF-8
| 253 | 3.765625 | 4 |
[] |
no_license
|
n1 = float(input('Diga quantos KM tem a sua viagem: '))
if n1 <= 200:
print('O preço da sua passagem ficara R${}' .format(n1 * 0.50))
else:
print('O preço da sua passagem ficara R${}' .format(n1 * 0.45))
print('Tenha uma boa viagem!! ;D')
|
C#
|
UTF-8
| 6,039 | 2.703125 | 3 |
[] |
no_license
|
using Oracle.ManagedDataAccess.Client;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Web;
namespace MultiBank.DAL
{
public class OracleHelper
{
protected OracleConnection Connection;
private string connectionString;
public OracleHelper()
{
string connStr;
connStr = System.Configuration.ConfigurationManager.ConnectionStrings["OraConnection"].ToString();
connectionString = connStr;
Connection = new OracleConnection(connectionString);
}
public OracleHelper(string ConnString)
{
string connStr;
connStr = System.Configuration.ConfigurationManager.ConnectionStrings[ConnString].ToString();
Connection = new OracleConnection(connStr);
}
public void OpenConn()
{
if (this.Connection.State != ConnectionState.Open)
this.Connection.Open();
}
public void CloseConn()
{
if (Connection.State == ConnectionState.Open)
Connection.Close();
}
/// <summary>
/// 执行查询语句
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public DataTable ExecuteQuery(string sql)
{
DataTable dt = new DataTable();
OpenConn();
OracleDataAdapter OraDA = new OracleDataAdapter(sql, Connection);
OraDA.Fill(dt);
CloseConn();
return dt;
}
/// <summary>
/// 分页返回dataset
/// </summary>
/// <param name="sql"></param>
/// <param name="PageSize"></param>
/// <param name="CurrPageIndex"></param>
/// <param name="DataSetName"></param>
/// <returns></returns>
public DataSet ReturnDataSet(string sql, int PageSize, int CurrPageIndex, string DataSetName)
{
DataSet dataSet = new DataSet();
OpenConn();
OracleDataAdapter OraDA = new OracleDataAdapter(sql, Connection);
OraDA.Fill(dataSet, PageSize * (CurrPageIndex - 1), PageSize, DataSetName);
CloseConn();
return dataSet;
}
/// <summary>
/// 返回记录总条数
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public int GetRecordCount(string sql)
{
int recordCount = 0;
OpenConn();
OracleCommand command = new OracleCommand(sql, Connection);
OracleDataReader dataReader = command.ExecuteReader();
while (dataReader.Read())
{
recordCount++;
}
dataReader.Close();
CloseConn();
return recordCount;
}
/// <summary>
/// 返回受影响行数
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public int ExecuteSQL(string sql)
{
int Cmd = 0;
OpenConn();
OracleCommand command = new OracleCommand(sql, Connection);
try
{
Cmd = command.ExecuteNonQuery();
}
catch
{
}
finally
{
CloseConn();
}
return Cmd;
}
/// <summary>
/// 批量事物化执行SQL
/// </summary>
/// <param name="SqlList"></param>
/// <returns></returns>
public bool ExecuteSqlTran(ArrayList SqlList)
{
using (Connection)
{
OpenConn();
OracleTransaction MyTran = Connection.BeginTransaction();
OracleCommand MyComm = Connection.CreateCommand();
try
{
MyComm.CommandTimeout = 60;
MyComm.Transaction = MyTran;
foreach (string Sql in SqlList)
{
MyComm.CommandText = Sql;
MyComm.ExecuteNonQuery();
}
MyTran.Commit();
return true;
}
catch (Exception ex)
{
MyTran.Rollback();
throw ex;
}
finally
{
Connection.Close();
MyComm.Dispose();
}
}
}
/// <summary>
/// 反射返回list集合
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="table"></param>
/// <returns></returns>
public IList<T> DataTableToList<T>(DataTable table)
{
IList<T> list = new List<T>();
T t = default(T);
PropertyInfo[] propertypes = null;
string tempName = string.Empty;
foreach (DataRow row in table.Rows)
{
t = Activator.CreateInstance<T>();
propertypes = t.GetType().GetProperties();
foreach (PropertyInfo pro in propertypes)
{
tempName = pro.Name;
if (table.Columns.Contains(tempName))
{
object value = IsNullOrDBNull(row[tempName]) ? null : row[tempName];
pro.SetValue(t, value, null);
}
}
list.Add(t);
}
return list;
}
static bool IsNullOrDBNull(object data)
{
if (data == null)
{
return true;
}
if (data == System.DBNull.Value)
{
return true;
}
return false;
}
}
}
|
C++
|
UTF-8
| 624 | 2.734375 | 3 |
[] |
no_license
|
#ifndef RAMMODULE_HPP
#define RAMMODULE_HPP
#include "Info.hpp"
#include "Item.hpp"
class Info;
class RamModule: public Info {
public:
RamModule(std::string title);
~RamModule(void);
/**
* Methods
*/
void refresh(void);
void addItem(Item *item);
std::vector<Item*> *items;
std::string title;
private:
RamModule &operator=(RamModule &ref);
RamModule(RamModule const &ref);
Item *freeCount;
Item *activeCount;
Item *inactiveCount;
Item *wiredCount;
};
#endif
|
Python
|
UTF-8
| 1,261 | 2.609375 | 3 |
[] |
no_license
|
import os, sys
parent_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(parent_dir)
sys.path.append(os.path.dirname(parent_dir))
from helpers import train_and_evaluate, display_predictions, display_classification_evaluation
from svm_classification_model import SupportVectorMachinesBankLeavingPredictionModel
from random_forest_classification_model import RandomForestBankLeavingPredictionModel
from neural_network_classification_model import NeuralNetworkBankLeavingPredictionModel
from neural_network_v2_classification_model import NeuralNetworkV2BankLeavingPredictionModel
title = 'Training bank leaving prediction models'
print(title + ': Start')
models = {
'SVM Model': SupportVectorMachinesBankLeavingPredictionModel(),
'Random Forest Model': RandomForestBankLeavingPredictionModel(),
'Neural Network Model': NeuralNetworkBankLeavingPredictionModel(),
'Neural Network V2 Model': NeuralNetworkV2BankLeavingPredictionModel()
}
evaluation = train_and_evaluate(models)
print(title + ': End')
display_classification_evaluation(evaluation)
display_predictions(models, [[502, 'France', 'Female', 42, 8, 159660.8, 3, 1, 0, 113931.57]])
print('\nSaving models')
for key in models:
models[key].save()
|
C++
|
UTF-8
| 1,824 | 2.703125 | 3 |
[] |
no_license
|
//pins
int v24a = 2;
int v24b = 3;
int v24c = 4;
int v24s = 5;
int v5a = 8;
int v5b = 9;
int v5c = 10;
int v5d = 11;
int i;
void setup() {
pinMode(v24a, OUTPUT);
pinMode(v24b, OUTPUT);
pinMode(v24c, OUTPUT);
pinMode(v24s, OUTPUT);
pinMode(v5a, OUTPUT);
pinMode(v5b, OUTPUT);
pinMode(v5c, OUTPUT);
pinMode(v5d, OUTPUT);
}
void loop()
{
poff();
p24a();
p5loop(200);
p24b();
p5loop(200);
p24c();
p5loop(200);
p24d();
p5loop(200);
digitalWrite(v24s, HIGH);
p24a();
p5loop(200);
p24b();
p5loop(200);
p24c();
p5loop(200);
p24d();
p5loop(200);
}
void poff()
{
digitalWrite(v24a, LOW);
digitalWrite(v24b, LOW);
digitalWrite(v24c, LOW);
digitalWrite(v24s, LOW);
digitalWrite(v5a, LOW);
digitalWrite(v5b, LOW);
digitalWrite(v5c, LOW);
digitalWrite(v5d, LOW);
}
void p24a()
{
digitalWrite(v24a, LOW);
digitalWrite(v24b, LOW);
digitalWrite(v24c, LOW);
}
void p24b()
{
digitalWrite(v24a, LOW);
digitalWrite(v24b, LOW);
digitalWrite(v24c, HIGH);
}
void p24c()
{
digitalWrite(v24a, HIGH);
digitalWrite(v24b, LOW);
digitalWrite(v24c, LOW);
}
void p24d()
{
digitalWrite(v24a, HIGH);
digitalWrite(v24b, HIGH);
digitalWrite(v24c, LOW);
}
void p5a()
{
digitalWrite(v5a, HIGH);
digitalWrite(v5b, LOW);
digitalWrite(v5c, LOW);
digitalWrite(v5d, LOW);
}
void p5b()
{
digitalWrite(v5a, LOW);
digitalWrite(v5b, HIGH);
digitalWrite(v5c, LOW);
digitalWrite(v5d, LOW);
}
void p5c()
{
digitalWrite(v5a, LOW);
digitalWrite(v5b, LOW);
digitalWrite(v5c, HIGH);
digitalWrite(v5d, LOW);
}
void p5d()
{
digitalWrite(v5a, LOW);
digitalWrite(v5b, LOW);
digitalWrite(v5c, LOW);
digitalWrite(v5d, HIGH);
}
void p5loop(int dtime)
{
p5a();
delay(dtime);
p5b();
delay(dtime);
p5c();
delay(dtime);
p5d();
delay(dtime);
}
|
C#
|
UTF-8
| 2,259 | 3.515625 | 4 |
[] |
no_license
|
using System;
namespace OtherMembers
{
// It is OK to define the following types:
//internal sealed class AType { }
//internal sealed class AType<T> { }
//internal sealed class AType<T1, T2> { }
//// Error: conflicts with AType<T> that has no constraints
//internal sealed class AType<T> where T : IComparable<T> { }
//// Error: conflicts with AType<T1, T2>
//internal sealed class AType<T3, T4> { }
//internal sealed class AnotherType
//{
// // It is OK to define the following methods:
// private static void M() { }
// private static void M<T>() { }
// private static void M<T1, T2>() { }
// // Error: conflicts with M<T> that has no constraints
// private static void M<T>() where T : IComparable<T> { }
// // Error: conflicts with M<T1, T2>
// private static void M<T3, T4>() { }
//}
//internal class Base
//{
// public virtual void M<T1, T2>()
// where T1 : struct
// where T2 : class
// {
// }
//}
//internal sealed class Derived : Base
//{
// public override void M<T3, T4>()
// where T3 : EventArgs // Error
// where T4 : class // Error.................... Why??
// { }
//}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(MethodTakingAnyType("5"));
}
private static Boolean MethodTakingAnyType<T>(T o)
{
T temp = o;
Console.WriteLine(o.ToString());
Boolean b = temp.Equals(o);
return b;
}
// Will drop compile error
//private static T Min<T>(T o1, T o2)
//{
// if (o1.CompareTo(o2) < 0)
// {
// return o1;
// }
// return o2;
//}
public static T Min<T>(T o1, T o2) where T : IComparable<T>
{
if (o1.CompareTo(o2) < 0) return o1;
return o2;
}
//private static void CallMin()
//{
// Object o1 = "Jeff", o2 = "Richter";
// Object oMin = Min<Object>(o1, o2); // Error CS0311, System.Object doesn't implement IComparable<T>
//}
}
}
|
Markdown
|
UTF-8
| 2,649 | 2.703125 | 3 |
[] |
no_license
|
# clip-preprocess
This repository holds scripts for pre-processing of clip data.
This is not in a usable state for others!
This repository is not intended to be useful to others at the moment, as file paths are hardcoded, it is not generalized, ect.
First, the fastq files were split by barcode:
$ python src/split_by_barcode.py <fastq>
Several steps are done to get to uncollapsed bed files.
The script split_fastq_to_bed.py will move barcodes to read names, remove linkers, map and take the best map for each read, and finally create bams and beds from the sam output by STAR.
The sequence of folders is:
input dir -> temp_adapter_in_name/ -> temp_fastq/ -> temp_clipped/ -> sams/
-> temp_sam_collapse_multi_map/ -> sams/ -> bed_uncollapsed/
bed_collapsed is the only output needed for everything else.
This is run by:
$ python split_fastq_to_bed.py -i input_dir
That script does the following:
The barcodes were moved to the read header:
$ python move_barcode_to_name_in_fastq.py <fastq directory/>
The three prime linker was removed:
$ python clip_adapter.py -t -i <in_dir> -o <out_dir>
The RT primer was removed:
$ python clip_adapter.py -r -i <in_dir> -o <out_dir>
Reads were mapped to the genome:
$ python map_with_star.py -i <in_dir>
WARNING: this version of STAR will output all loci for a multimapped read, and has no option to do otherwise, except to reject all multimapped reads.
Collapse multimapping reads to one:
$ python collapse_multimapping_reads_to_one_sam.py <file or folder of sams>
This will output to the folder sam_collapse_multi_map/ by default.
TO DO: compare with the published STAR parameters from that comparison paper.
This outputs both bams to bams/ and beds to bed_uncollapsed/.
Commands to run the duplicates-removal script from the Zhang lab were printed with a call to:
$ python write_commands_for_collapsing.py
The commands output by this script were then run, outputing to bed_collapsed/.
Bedgraphs were made and normalized with:
$ python bed_to_wig.py -b bed_collapsed/ -o bedgraph_norm/ -u bedgraph_unnorm/
Bedgraphs can be normalized separately with:
$ python normalize_bedgraph.py -b bed_folder -i bedgraph_folder -o output_bedgraph_folder
So to summarize the essential chain of commands:
$ python split_fastq_to_bed.py -i input_dir
$ python write_commands_for_collapsing.py
$ python bed_to_wig.py -b bed_collapsed/ -o bedgraph_norm/ -u bedgraph_unnorm/
Peaks are called by importing peaks-by-permutations and running:
$ generate_config_file.py . # Edit output as needed.
$ find_peaks_by_permutations.py -x -c auto.ini
Peak calling is covered elsewhere.
|
Markdown
|
UTF-8
| 439 | 2.765625 | 3 |
[] |
no_license
|
What happens to the layout when you resize the screen to less than 550 px. How do you think that works?
The webpage's layout rearrages itself so that all the elements are in the middle of the page. This is because Skeleton media queries are mobile first, so any screen smaller than 550px makes the page adopt the layout created for mobile phones. Which is described in the first block of the CSS code, before all the other media queries.
|
PHP
|
UTF-8
| 1,170 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
<?php
/**
* This file is part of CaptainHook
*
* (c) Sebastian Feldmann <sf@sebastian-feldmann.info>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CaptainHook\App;
use SebastianFeldmann\Git\Operator\Info;
use SebastianFeldmann\Git\Repository;
/**
* Class to more closely mimic the repo behaviour
*
* Only the operators ar supposed to be replaced by mocks
*/
class RepoMock extends Repository
{
/**
* Info Operator Mock
*
* @var \SebastianFeldmann\Git\Operator\Info
*/
private Info $infoOperator;
/**
* Overwrite the original constructor to not do any validation at all
*/
public function __construct()
{
}
/**
* Set info operator mock
*
* @param \SebastianFeldmann\Git\Operator\Info $op
* @return void
*/
public function setInfoOperator(Info $op): void
{
$this->infoOperator = $op;
}
/**
* Return the operator mock
*
* @return \SebastianFeldmann\Git\Operator\Info
*/
public function getInfoOperator(): Info
{
return $this->infoOperator;
}
}
|
Java
|
UTF-8
| 678 | 2.234375 | 2 |
[] |
no_license
|
/*
* License information at https://github.com/Caltech-IPAC/firefly/blob/master/License.txt
*/
package edu.caltech.ipac.visualize.plot;
import java.util.EventListener;
/**
* A listener that is called when a PlotView status has a changed
* @author Trey Roby
*/
public interface PlotViewStatusListener extends EventListener {
/**
* Called when a plot is added to this plot view
* @param ev the event
*/
public abstract void plotAdded(PlotViewStatusEvent ev);
/**
* Called when a plot is added to this plot view
* @param ev the event
*/
public abstract void plotRemoved(PlotViewStatusEvent ev);
}
|
PHP
|
UTF-8
| 882 | 2.734375 | 3 |
[] |
no_license
|
<?php
/**
* Author: avsudnichnikov (alsdew@ya.ru)
* Date: 17.04.2019
* Time: 18:21
*/
class DataRecordModel
{
private $data;
private $guid;
public function __construct()
{
$this->data = new JsonObjDataModel(strtolower(static::class));
}
public function myself()
{
$this->data->newQuery()->byGuid($this->guid);
return $this->data;
}
public function create()
{
$this->data->add($this);
$this->myself();
}
public function getGuid()
{
return $this->guid;
}
public function data()
{
return $this->data;
}
public function commit()
{
$this->data->save();
}
public function findFirst($param, $value, $findLike = false)
{
$this->data->newQuery()->find($param, $value, $findLike)->first();
return $this->data;
}
}
|
JavaScript
|
UTF-8
| 1,414 | 2.5625 | 3 |
[] |
no_license
|
const jwt = require("jsonwebtoken");
const store = require("./store");
const crypto = require("crypto");
const getUser = (data) => {
return new Promise(async (resolve, reject) => {
const loginDB = await store.singIn(data);
if (!loginDB.length > 0) {
reject({message: "Ingrese usuario y contraseña válidos", status:400});
return false;
}
const contraseña = crypto.createHmac('sha256', process.env.SEED)
.update(data.contraseña)
.digest('hex');
if (contraseña != loginDB[0].contraseña) {
reject({message: "Ingrese usuario y contraseña válidos", status:400});
return false;
}
let token = jwt.sign(
{
login: loginDB[0],
},
process.env.SEED,
{ expiresIn: process.env.CADUCIDAD_TOKEN }
);
resolve({
user: loginDB[0],
token,
});
});
};
const checkToken = async (token) => {
return new Promise(async (resolve, reject) => {
let user = null;
jwt.verify(token, process.env.SEED, (err, decoded) => {
if (err) {
return reject(err);
}
user = decoded;
});
let Today = Math.round(new Date().getTime() / 1000);
const { exp } = user;
if (Today < exp) {
let getUser = await store.singIn({usuario:user.login.usuario});
resolve(getUser[0]);
}
reject("token expirado.");
});
};
module.exports = {
getUser,
checkToken,
};
|
Swift
|
UTF-8
| 2,839 | 2.828125 | 3 |
[] |
no_license
|
//
// Singleton.swift
// Template
//
// Created by Pulkit Rohilla on 21/06/17.
// Copyright © 2017 PulkitRohilla. All rights reserved.
//
import UIKit
class Singleton : NSObject, NSCoding{
static let shared = Singleton()
var userName : String = ""
var endpointARN : String = ""
var devicePinCode : Int = 0
var isDemoUser: Bool = false
var hasLoggedIn : Bool = false
var hasConfigured : Bool = false
func saveUserSelection(withKey key : String){
let encodedData = NSKeyedArchiver.archivedData(withRootObject: self)
UserDefaults.standard.set(encodedData, forKey: key)
}
func loadUserSelection(forKey key : String){
if let data = UserDefaults.standard.data(forKey: key),
let userSelection = NSKeyedUnarchiver.unarchiveObject(with: data) as? Singleton {
userName = userSelection.userName
endpointARN = userSelection.endpointARN
devicePinCode = userSelection.devicePinCode
isDemoUser = userSelection.isDemoUser
hasLoggedIn = userSelection.hasLoggedIn
hasConfigured = userSelection.hasConfigured
} else {
// print("Unable to retrieve selection")
}
}
func clearData() {
devicePinCode = 0
isDemoUser = false
hasConfigured = false
hasLoggedIn = false
}
override init(){
}
//MARK: NSCoding
func encode(with coder: NSCoder) {
//Encode properties, other class variables, etc
coder.encode(userName, forKey: SingletonConstants().KVUserName)
coder.encode(endpointARN, forKey: SingletonConstants().KVEndpointARN)
coder.encode(devicePinCode, forKey: SingletonConstants().KVDevicePinCode)
coder.encode(isDemoUser, forKey: SingletonConstants().KVDemoUser)
coder.encode(hasLoggedIn, forKey: SingletonConstants().KVLoggedIn)
coder.encode(hasConfigured, forKey: SingletonConstants().KVConfigured)
}
required init?(coder decoder: NSCoder) {
if let user = decoder.decodeObject(forKey: SingletonConstants().KVUserName) as? String{
userName = user
}
if let ARN = decoder.decodeObject(forKey: SingletonConstants().KVEndpointARN) as? String{
endpointARN = ARN
}
devicePinCode = decoder.decodeInteger(forKey: SingletonConstants().KVDevicePinCode)
isDemoUser = decoder.decodeBool(forKey: SingletonConstants().KVDemoUser)
hasLoggedIn = decoder.decodeBool(forKey: SingletonConstants().KVLoggedIn)
hasConfigured = decoder.decodeBool(forKey: SingletonConstants().KVConfigured)
}
}
|
C#
|
UTF-8
| 4,351 | 2.640625 | 3 |
[] |
no_license
|
using Core.Abstract;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace Core.Concrete
{
public class EFBaseRepository<TEntity> : IRepository<TEntity>
where TEntity : class, IVeri, new()
{
protected DbContext context;
public EFBaseRepository(DbContext _context)
{
context = _context;
}
public ResultMessage<TEntity> Add(TEntity data)
{
try
{
var addedData = context.Entry(data);
addedData.State = EntityState.Added;
return new ResultMessage<TEntity> { BasariliMi = true, Data = data, Mesaj = "Kayıt eklenmeye hazır." };
}
catch (Exception ex)
{
return new ResultMessage<TEntity> { BasariliMi = false, Data = null, Mesaj = ex.Message };
}
}
public ResultMessage<TEntity> Delete(int id)
{
try
{
var data = context.Set<TEntity>().Find(id);
var deletedData = context.Entry(data);
deletedData.State = EntityState.Deleted;
return new ResultMessage<TEntity> { BasariliMi = true, Data = data, Mesaj = "Kayıt silinmeye hazır." };
}
catch (Exception ex)
{
return new ResultMessage<TEntity> { BasariliMi = false, Data = null, Mesaj = ex.Message };
}
}
public ResultMessage<TEntity> Get(Expression<Func<TEntity, bool>> filter)
{
try
{
TEntity data = context.Set<TEntity>().Where(filter).FirstOrDefault();
return data == null ? new ResultMessage<TEntity> { BasariliMi = false, Mesaj = "Aranan kriterlere uygun kayıt bulunamadı." } : new ResultMessage<TEntity> { BasariliMi = true, Mesaj = "Kayıt getirildi.", Data = data };
}
catch (Exception ex)
{
return new ResultMessage<TEntity> { BasariliMi = false, Mesaj = ex.Message };
}
}
public ResultMessage<ICollection<TEntity>> GetAll(Expression<Func<TEntity, bool>> filter = null)
{
try
{
ICollection<TEntity> dataList;
if (filter == null)
{
dataList = context.Set<TEntity>().AsNoTracking().Where(x => x.IsActive == 0).ToList();
}
else
{
dataList = context.Set<TEntity>().AsNoTracking().Where(filter).ToList();
}
return new ResultMessage<ICollection<TEntity>> { BasariliMi = true, Data = dataList, Mesaj = "Veriler listelendi." };
}
catch (Exception ex)
{
return new ResultMessage<ICollection<TEntity>> { BasariliMi = false, Mesaj = ex.Message };
}
}
public ResultMessage<TEntity> SoftDelete(int id)
{
try
{
var data = context.Set<TEntity>().Find(id);
var softDeletedData = context.Entry(data);
data.IsActive = 1;
softDeletedData.State = EntityState.Modified;
return new ResultMessage<TEntity> { BasariliMi = true, Data = data, Mesaj = "Kayıt silinmeye hazır." };
}
catch (Exception ex)
{
return new ResultMessage<TEntity> { BasariliMi = false, Data = null, Mesaj = ex.Message };
}
}
public ResultMessage<TEntity> Update(TEntity data)
{
try
{
var updatedData = context.Entry(data);
updatedData.State = EntityState.Modified;
return new ResultMessage<TEntity> { BasariliMi = true, Data = data, Mesaj = "Kayıt güncellenmeye hazır." };
}
catch (Exception ex)
{
return new ResultMessage<TEntity> { BasariliMi = false, Data = null, Mesaj = ex.Message };
}
}
}
}
|
C#
|
UTF-8
| 651 | 3.46875 | 3 |
[] |
no_license
|
using System;
using System.Text;
using System.Threading.Tasks;
namespace IfStatement2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(GetMax(10,20,30));
}
static int GetMax(int num1,int num2,int num3)
{
int result;
if(num1>=num2 && num1>=num3)
{
result=num1;
}
else if(num2>=num1 && num2>=num3)
{
result=num2;
}
else{
result=num3;
}
return result;
}
}
}
|
C++
|
UTF-8
| 3,607 | 3.6875 | 4 |
[] |
no_license
|
#include <iostream>
#include <vector>
int main(int argc, char const *argv[])
{
char choix(0);
std::vector<int> list;
do
{
std::cout << "\n---------------------------" << std::endl;
std::cout << "P - Print numbers (Afficher)" << std::endl;
std::cout << "A - Ajouter un nombre" << std::endl;
std::cout << "M - Afficher la Moyenne des nombre" << std::endl;
std::cout << "S - Afficher the smallest number (plus petit)" << std::endl;
std::cout << "G - Afficher le plus grand nombre" << std::endl;
std::cout << "Q - Quitter" << std::endl;
std::cout << "Faites un choix: ";
std::cin >> choix;
int num(0);
switch (choix)
{
case 'p':
case 'P':
if (list.size() == 0) {
std::cout << "[] - La liste est vide" << std::endl;
}
else{
std::cout << "[";
for(int i = 0; i < list.size(); ++i){
std::cout << list[i] << " ";
}
std::cout << "]";
}
break;
case 'a':
case 'A':
std::cout << "Entrer un nombre: ";
std::cin >> num;
list.push_back(num);
std::cout << num << "est Ajoute" << std::endl;
break;
case 'm':
case 'M':
if (list.size() == 0) {
std::cout << "Impossible de calculer la moyenne - List vide" << std::endl;
}
else{
double moyenne(0);
for(int i = 0; i < list.size(); ++i){
moyenne += list[i];
}
std::cout << "La Moyenne est egale a :" << moyenne / list.size() << std::endl;
}
break;
case 's':
case 'S':
if (list.size() == 0){
std::cout << "Impossible de determiner la plus petite valeur - liste vide\n";
}
else{
int min = list[0];
for (int i = 0; i < list.size(); ++i){
if (min > list[i]){
min = list[i];
}
}
std::cout << "Le plus petit nombre est :" << min << std::endl;
}
break;
case 'g':
case 'G':
if (list.size() == 0){
std::cout << "Impossible de determiner le grand nombre - liste vide\n";
}
else {
int max = list[0];
for (int i = 0; i < list.size(); ++i){
if (max < list[i]){
max = list[i];
}
}
std::cout << "Le plus grand nombre est :" << max << std::endl;
}
break;
case 'q':
case 'Q':
std::cout << "Goodbye..." << std::endl;
break;
default:
std::cout << "Choix Inconnue - Reessayer Encore" << std::endl;
break;
}
} while (choix != 'q' && choix != 'Q');
return 0;
}
|
Java
|
UTF-8
| 260 | 2.015625 | 2 |
[] |
no_license
|
package com.labus.transportation.hash;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
public interface Hash {
public String getHash(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException;
}
|
Markdown
|
UTF-8
| 1,900 | 3.75 | 4 |
[] |
no_license
|
# Operating Systems: Three Easy Pieces
> Operating Systems: Three Easy Pieces
>
> Remzi H. Arpaci-Dusseau and Andrea C. Arpaci-Dusseau
>
> Arpaci-Dusseau Books
>
> March, 2015 (Version 0.90)
Read online: http://pages.cs.wisc.edu/~remzi/OSTEP/
## Preface
The three easy pieces in the title refer to **virtualization**, **concurrency**, and **persistence**.
## Chapter 2 - Introduction to Operating Systems
### Virtualizing the CPU
### Virtualizing Memory
This example was particularly interesting. We create a program that performs the following:
1. Dynamically allocate memory for an integer
1. Print the address of the newly allocated memory
1. Initialize the memory to 0
1. while(true) {
1. Print the process ID and contents of the memory
1. Increment the contents of the memory
1. }
``` c
int main(int argc, char* argv[]) {
int* p = malloc(sizeof(int));
printf("[%d] memory address of p: %08\n");
*p = 0;
while(1) {
Spin(1);
*p = *p + 1;
printf("[%d] p: %d\n", getpid(), *p);
}
return 0;
}
```
Running the program once prints `0x00200000` and then 1, 2, 3, ... as expected.
We then run multiple instances of the same program simultaneously and each one prints `0x00200000` while maintaining a independent count. How can all of the programs be pointing to the same address, but maintaining independent counts?
```
[1234] memory address of p: 00200000
[1235] memory address of p: 00200000
[1234] p: 1
[1235] p: 1
[1234] p: 2
[1235] p: 2
[1234] p: 3
[1235] p: 3
...
```
The explanation is that the memory is virtualized. The address printed isn't in the global address space. Instead, the address is in the virtual address space, which is specific to the process and mapped into the global address space by the operating system. So process 1234's address `0x00200000` could map to the global address `0xCAFEBABE` and process 1235's address `0x00200000` could map to the global address `0xCAFED00D`.
|
Java
|
UTF-8
| 1,083 | 2.703125 | 3 |
[] |
no_license
|
package elf_crawler.crawler;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class KBTagManager {
private Map<String, Tag> tagMap;
private List<Tag> tags;
private static final Type LIST_STRING_TYPE =
new TypeToken<List<Tag>>(){}.getType();
public KBTagManager(String filename) throws FileNotFoundException {
JsonReader reader = new JsonReader(new FileReader(filename));
Gson gson = new Gson();
tags = gson.fromJson(reader, LIST_STRING_TYPE);
this.tagMap = new HashMap<>(tags.size());
for (Tag tag : tags)
this.tagMap.put(tag.getTagName(), tag);
}
public boolean hasTag(String tagName)
{
return this.tagMap.containsKey(tagName);
}
public List<Tag> getAllTags()
{
return this.tags;
}
}
|
PHP
|
UTF-8
| 3,542 | 3.4375 | 3 |
[] |
no_license
|
<?php
/**
* Developed by : Muhammad Elgendi
* Date : 14/12/2018
*
* || Notes ||
* This class implemented to comply Fluent interface pattern
* You can build the tree of Shannon Fano from a message or predefined table
*/
// build code book from a predefined table (letters with frequencies)
// $table = ['B'=> 3,'L'=> 2,'E'=> 2,'I'=>1,'A'=>1,'T'=>1,'S'=>1,'N'=>1];
// $shannon = (new ShannonFano())->setTable($table);
// // build code book from a message
// $shannon =(new ShannonFano())->setMessage('BBBLLEEIATSN');
// $shannon->buildCodeBook()->encodeMessage();
// // print code book
// print_r($shannon->getCodeBook());
// // print encoded message
// echo $shannon->getCompressedCode()."\n";
class ShannonFano{
private $table;
private $codeBook;
private $message;
private $compressedCode;
// Build the table from an assiochative array
public function setTable($table){
arsort($table);
$this->table = $table;
$this->codeBook = array_fill_keys(array_keys($this->table), '');
return $this;
}
// Build the table from a message
public function setMessage($msg){
$this->message = $msg;
$chars = array_unique(str_split($msg));
$frequency = count_chars($msg,1);
$table = array_fill_keys(array_values($chars), 0);
$keys = array_keys($frequency);
$values = array_values($frequency);
for($i=0;$i<count($frequency);$i++){
$key = chr($keys[$i]);
$table[$key] = $values[$i];
}
arsort($table);
$this->table = $table;
$this->codeBook = array_fill_keys(array_keys($this->table), '');
return $this;
}
public function buildCodeBook(){
foreach($this->table as $key => $value){
$tempTable =$this->table;
while( count($tempTable) > 1){
$tempFrequency =array_values($tempTable);
$point = $this->getSeprationPoint($tempFrequency);
$leftBranch = array_slice($tempTable,0, $point+1, true);
$rightBranch = array_slice($tempTable,$point+1,(count($tempTable)-($point+1)),true);
if(in_array($key,array_keys($leftBranch))){
$this->codeBook[$key] .= '0';
$tempTable = $leftBranch;
}
else{
$this->codeBook[$key] .= '1';
$tempTable = $rightBranch;
}
}
}
return $this;
}
public function encodeMessage(){
$this->compressedCode = "";
$array = str_split($this->message);
foreach($array as $letter){
$this->compressedCode .= $this->codeBook[$letter];
}
return $this;
}
public function getCodeBook(){
return $this->codeBook;
}
public function getCompressedCode(){
return $this->compressedCode;
}
private function getSeprationPoint($frequency){
$result = [];
for($i =0;$i<count($frequency);$i++){
$upperHalf = $this->sum($frequency,0,$i);
$lowerHalf = $this->sum($frequency,$i+1,count($frequency)-1);
$result[$i] = abs($upperHalf -$lowerHalf);
}
return array_search(min($result),$result);
}
private function sum($array,$start,$end){
$sum =0;
for($i=$start;$i<=$end;$i++){
$sum+=$array[$i];
}
return $sum;
}
}
|
TypeScript
|
UTF-8
| 2,921 | 2.5625 | 3 |
[
"Apache-2.0"
] |
permissive
|
import { IMPORTS } from "../../internalImports";
import { packageNameToVariable } from "../../packageNameToVariable";
import { staticOrProvider } from "./staticOrProvider";
import { urlParser } from "./standardConfigurationProperties";
import {
ConfigurationPropertyDefinition,
ConfigurationDefinition
} from "@aws-sdk/build-types";
import { ServiceMetadata } from "@aws-sdk/types";
/**
* @internal
*/
export function endpointConfigurationProperties(
metadata: ServiceMetadata
): ConfigurationDefinition {
return {
urlParser,
endpointProvider: endpointProviderProperty(metadata),
endpoint
};
}
const typesPackage = packageNameToVariable("@aws-sdk/types");
const endpointType = `string|${staticOrProvider(
`${typesPackage}.HttpEndpoint`
)}`;
const resolvedEndpointType = `${typesPackage}.Provider<${typesPackage}.HttpEndpoint>`;
/**
* @internal
*/
export const endpoint: ConfigurationPropertyDefinition = {
type: "unified",
inputType: endpointType,
resolvedType: resolvedEndpointType,
imports: [IMPORTS.types],
documentation:
"The fully qualified endpoint of the webservice. This is only required when using a custom endpoint (for example, when using a local version of S3).",
required: false,
default: {
type: "provider",
expression: `(
configuration: {
sslEnabled: boolean,
endpointProvider: any,
region: ${typesPackage}.Provider<string>,
}
) => {
const promisified = configuration.region()
.then(region => configuration.endpointProvider(
configuration.sslEnabled,
region
));
return () => promisified;
}`
},
normalize: `(
value: ${endpointType}|undefined,
configuration: {
urlParser?: ${typesPackage}.UrlParser,
}
): ${resolvedEndpointType} => {
if (typeof value === 'string') {
const promisified = Promise.resolve(configuration.urlParser!(value));
return () => promisified;
} else if (typeof value === 'object') {
const promisified = Promise.resolve(value);
return () => promisified;
}
// Users are not required to supply an endpoint, so \`value\`
// could be undefined. This function, however, will only be
// invoked if \`value\` is defined, so the return will never
// be undefined.
return value!;
}`
};
/**
* @internal
*/
function endpointProviderProperty(
metadata: ServiceMetadata
): ConfigurationPropertyDefinition {
return {
type: "unified",
inputType: "any", // TODO change this,
imports: [IMPORTS.types],
documentation: "The endpoint provider to call if no endpoint is provided",
required: false,
default: {
type: "value",
expression: `(
sslEnabled: boolean,
region: string,
) => ({
protocol: sslEnabled ? 'https:' : 'http:',
path: '/',
hostname: \`${metadata.endpointPrefix}.\${region}.amazonaws.com\`
})`
}
};
}
|
PHP
|
UTF-8
| 1,769 | 2.65625 | 3 |
[] |
no_license
|
<?php
namespace App\Services;
use App\Models\Invoice;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;
use Illuminate\Http\RedirectResponse;
class PaymentGateway
{
public Invoice $invoice;
/**
* Constructor
*
* @param \App\Models\Invoice $invoice
*/
public function __construct(Invoice $invoice)
{
$this->invoice = $invoice;
}
/**
* Create self instance statically
*
* @param \App\Models\Invoice $invoice
* @return self
*/
public static function create(Invoice $invoice): self
{
return new PaymentGateway($invoice);
}
/**
* Generate URL to redirect to payment gateway
*
* @return string
*/
public function generatePaymentUrl(): string
{
return external_url(config('settings.payments.url'), [
'public-key' => config('settings.payments.key'),
'currency' => $this->invoice->currency->code,
'amount-in-cents' => number_format($this->invoice->total, 2, '', ''),
'reference' => $this->invoice->number,
'redirect-url' => route(config('settings.payments.redirect'), ['number' => $this->invoice->number])
]);
}
/**
* Return redirect to payment gateway
*
* @return \Illuminate\Http\RedirectResponse
*/
public function redirect(): RedirectResponse
{
return redirect()->away($this->generatePaymentUrl());
}
/**
* Get transaction status data to check payment
*
* @param string $id
* @return \Illuminate\Http\Client\Response
*/
public static function confirm(string $id): Response
{
return Http::get(config('settings.payments.confirm') . $id);
}
}
|
Markdown
|
UTF-8
| 8,063 | 3.0625 | 3 |
[] |
no_license
|
# CS253 HW3: Options!
## Description
For this assignment, you will improve upon your previous work, adding command-line options, and changing a few things.
## Arguments
The first argument is no longer a keyword file. Instead, the first command-line arguments should be options:
#### -k keywordfile
Specify the keyword file. The keyword file contains a list of valid keywords, one per line.
#### -n
Display lines with Name keys. That is, keys that are exactly the string Name.
#### -l
Display lines with Link… keys. These are the string Link, followed by an arbitrary alphanumeric string of at least one character, e.g., LinkDog, Link1902689, Linkqq42sv, etc.
#### -o
Display lines with other keys. That is, keys that aren’t Name or Link… keys.
If any of -n, -o, or -l are given, then display only lines with those keys. If not, then display all keys.
Any remaining arguments are files containing lists of enemies. If no remaining arguments are given, read enemies from standard input, as in the previous assignment.
## Input Format
Same as previous assignment, except that a Name key is mandatory, and keys can now be alphanumeric.
As you may have realized, there is no need for an explicit check for alphabetic keys, since the -k keyfile controls which keys are valid.
## Output Format
Same as previous assignment, except that within a given enemy, keys & values are displayed in this order:
Name
anything but Name and Link…
Link…
Multiple Link… lines are displayed in the input order.
Except as specified above, the output order is the same as the input order.
## Sample Runs
Here are sample runs, where % is my prompt.
% cat keys
Name
Linkage
LinkIs
bonehead
motivation
RealName
Motif
% cat in1
RealName Victor Von Doom
Linkage College Acquaintance
Name Doctor Doom
motivation Rule the world!
Name Silver Surfer
Motif Really into
the whole
silver thing
% cat in2
Name Super-Skrull
LinkIs Just wants to kill the FF
RealName Kl'rt
% cat in3
Name
Annihilus
ActualName unknown
Origin Negative Zone
% cmake .
… cmake output appears here …
% make
… make output appears here …
% ./hw3 -k keys in1 in2
Name Doctor Doom
RealName Victor Von Doom
motivation Rule the world!
Linkage College Acquaintance
Name Silver Surfer
Motif Really into the whole silver thing
Name Super-Skrull
RealName Kl'rt
LinkIs Just wants to kill the FF
% ./hw3 -k keys <in3
./hw3: key “ActualName” not in keyfile
% ./hw3 -n -k keys in1 in2
Name Doctor Doom
Name Silver Surfer
Name Super-Skrull
% ./hw3 -k keys -ln in1 in2
Name Doctor Doom
Linkage College Acquaintance
Name Silver Surfer
Name Super-Skrull
LinkIs Just wants to kill the FF
% ./hw3 -lkkeys in1 in2
Linkage College Acquaintance
LinkIs Just wants to kill the FF
%
## Debugging
If you encounter “STACK FRAME LINK OVERFLOW”, then try this:
export STACK_FRAME_LINK_OVERRIDE=0861-f88a75ffe0801823a715cf078a1a6901
## Requirements
Error messages:
go to standard error.
include the program name, no matter how it was compiled.
include the offending data, if applicable
Produce an error message and stop the program if:
not enough arguments are given
an options is bad
a file cannot be opened
a key in an enemies file is not in the keys file
the key or value is missing
duplicate keys are encountered in an enemy
a Name key is missing from an enemy
If more than one problem exists, you don’t have to report them all. Produce one error message and stop.
-k keyfile option must occur exactly once.
It doesn’t have to be first.
The first thing after -k (after optional whitespace) will be the keys file.
Options must precede filenames. ./hw3 -k keys foo -n will attempt to process the file -n, which would probably fail.
Bundling of options must work:
./hw3 -ok mykeys data is the same as ./hw3 -o -k mykeys data
./hw3 -knewkeys -on data is the same as ./hw3 -k newkeys -o -n data
./hw3 -n -lkmykeys data1 dataApN is the same as ./hw3 -n -l -k mykeys data1 dataApN
./hw3 -o-k mykeys data is invalid.
The -n, -o, and -l options may be specified multiple times, with no additional effect.
The output must end with a newline.
Newlines do not separate lines—newlines terminate lines.
Creativity is a wonderful thing, but your output format is not the place for it. Your non-error output should look exactly like the output shown above. You have more leeway in error cases.
UPPERCASE/lowercase matters.
Spaces matter.
Blank lines matter.
Extra output matters.
You may not use any external programs via system(), fork(), popen(), exec*(), etc.
You may not use C-style <stdio.h> or <cstdio> facilities, such as printf(), scanf(), fopen(), and getchar().
Instead, use C++ facilities such as cout, cerr, and ifstream.
You may not use dynamic memory via new, delete, malloc(), calloc(), realloc(), free(), strdup(), etc.
It’s ok to implicitly use dynamic memory via containers such as string or vector.
You may not use the istream::eof() method.
No global variables.
Except for an optional single global string containing argv[0].
For readability, don’t use ASCII int constants (65) instead of char constants ('A') for printable characters.
We will compile your program like this: cmake .; make
If that generates warnings, you will lose a point.
If that generates errors, you will lose all points.
There is no automated testing/pre-grading/re-grading.
Test your code yourself. It’s your job.
Even if you only change it a little bit.
Even if all you do is add a comment.
If you have any questions about the requirements, ask. In the real world, your programming tasks will almost always be vague and incompletely specified. Same here.
## Hint
Use getopt. Seriously, use it. Don’t do this yourself.
## Tar file
For each assignment this semester, you will create a tar file, and turn it in.
The tar file for this assignment must be called: hw3.tar
It must contain:
source files (*.cc)
header files (*.h) (if any)
CMakeLists.txt
These commands must produce the program hw3 (note the dot):
cmake .
make
At least -Wall must be used every time g++ runs.
## How to submit your homework:
Use web checkin, or Linux checkin:
~cs253/bin/checkin HW3 hw3.tar
## How to receive negative points:
Turn in someone else’s work.
|
Markdown
|
UTF-8
| 2,052 | 3.859375 | 4 |
[] |
no_license
|
# 如何在 Java 中创建文件
> 原文: [https://beginnersbook.com/2014/01/how-to-create-a-file-in-java/](https://beginnersbook.com/2014/01/how-to-create-a-file-in-java/)
在本教程中,我们将了解如何使用`createNewFile()`方法在 Java 中创建文件。如果文件在指定位置不存在并且返回 true,则此方法创建一个空文件。如果文件已存在,则此方法返回 false。它抛出:
[`IOException`](https://docs.oracle.com/javase/7/docs/api/java/io/IOException.html "class in java.io") - 如果在创建文件期间发生输入/输出错误。
[`SecurityException`](https://docs.oracle.com/javase/7/docs/api/java/lang/SecurityException.html "class in java.lang") - 如果存在安全管理器且其 [`SecurityManager.checkWrite(java.lang.String)`](https://docs.oracle.com/javase/7/docs/api/java/lang/SecurityManager.html#checkWrite(java.lang.String)) 方法拒绝对该文件的写访问。
**完整代码:**
下面的代码将在 C 盘中创建一个名为“newfile.txt”的 txt 文件。您可以更改以下代码中的路径,以便在不同目录或不同驱动器中创建文件。
```java
package beginnersbook.com;
import java.io.File;
import java.io.IOException;
public class CreateFileDemo
{
public static void main( String[] args )
{
try {
File file = new File("C:\\newfile.txt");
/*If file gets created then the createNewFile()
* method would return true or if the file is
* already present it would return false
*/
boolean fvar = file.createNewFile();
if (fvar){
System.out.println("File has been created successfully");
}
else{
System.out.println("File already present at the specified location");
}
} catch (IOException e) {
System.out.println("Exception Occurred:");
e.printStackTrace();
}
}
}
```
#### 参考:
[Javadoc:createNewFile()](https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createNewFile() "createNewFile() method")
|
C
|
UTF-8
| 48,768 | 2.703125 | 3 |
[] |
no_license
|
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include "Game.h"
#define DEFAULT_DISCIPLINES { STUDENT_BQN, STUDENT_MMONEY, STUDENT_MJ, \
STUDENT_MMONEY, STUDENT_MJ, STUDENT_BPS, STUDENT_MTV, \
STUDENT_MTV, STUDENT_BPS,STUDENT_MTV, STUDENT_BQN, \
STUDENT_MJ, STUDENT_BQN, STUDENT_THD, STUDENT_MJ, \
STUDENT_MMONEY, STUDENT_MTV, STUDENT_BQN, STUDENT_BPS }
#define DEFAULT_DICE {9,10,8,12,6,5,3,11,3,11,4,6,4,7,9,2,8,10,5}
#define REGION_0 0
#define REGION_1 1
#define REGION_2 2
#define REGION_3 3
#define REGION_4 4
#define REGION_5 5
#define REGION_6 6
#define REGION_7 7
#define REGION_8 8
#define REGION_9 9
#define REGION_10 10
#define REGION_11 11
#define REGION_12 12
#define REGION_13 13
#define REGION_14 14
#define REGION_15 15
#define REGION_16 16
#define REGION_17 17
#define REGION_18 18
void testDisposeGame (void);
void testGetDiscipline (void);
void testGetTurnNumber (void);
void testIsLegalAction (void);
void testGetCampuses (void);
void testMakeAction (void);
void testGetMostARCs (void);
void testGetCampus (void);
void testGetARCs (void);
void testGetPublications (void);
void testThrowDice (void);
void testGetMostPublications (void);
void testGetARC (void);
void testGetGO8s (void);
void testGetStudents (void);
void testGetDiceValue (void);
void testGetWhoseTurn (void);
void testGetKPIpoints (void);
void testGetIPs (void);
int rollDice (int no7);
void failedExternalTests(void);
void externalTest001(void);
void externalTest002(void);
void failedExternalTestSimon(void);
void failedExternalTestMeghana(void);
int main (int argc, char *argv[]) {
testDisposeGame ();
testGetDiscipline ();
testGetTurnNumber ();
testIsLegalAction ();
testGetCampuses ();
testMakeAction ();
testGetMostARCs ();
testGetCampus ();
testGetARCs ();
testGetPublications ();
testGetCampuses ();
testThrowDice ();
testGetMostPublications ();
testGetARC ();
testGetGO8s ();
testGetStudents ();
testGetDiceValue ();
testGetWhoseTurn ();
testGetKPIpoints ();
externalTest001();
failedExternalTests ();
failedExternalTestSimon ();
failedExternalTestMeghana();
failedExternalTests ();
externalTest002();
printf ("All tests passed. You are awesome!\n");
return EXIT_SUCCESS;
}
void testThrowDice (void) {
printf ("Testing throwDice\n");
int disciplines[] = DEFAULT_DISCIPLINES;
int diceScores[] = DEFAULT_DICE;
//Create a new game to test on
Game testGame = newGame (disciplines, diceScores);
//Throw the dice to advance the turn
throwDice (testGame, 1);
//Check that the turn is Terra Nullis
assert (getTurnNumber (testGame) == 0);
//Check that the turn advances again
throwDice (testGame, 1);
assert (getTurnNumber (testGame) == 1);
//And Once more for luck
throwDice (testGame, 1);
assert (getTurnNumber (testGame) == 2);
int turnNum = 3;
while (turnNum < 9000) {
throwDice (testGame, 2);
assert (getTurnNumber (testGame) == turnNum);
turnNum ++;
}
printf ("throwDice works - You are Awesome!\n\n");
}
void testGetMostPublications (void) {
//Initialize Variables
printf ("Testing getMostPublications\n");
int playersTurn = 0;
int newPlayersTurn = 0;
int disciplines[] = DEFAULT_DISCIPLINES;
int diceScores[] = DEFAULT_DICE;
//Create a new game to test on
Game testGame = newGame (disciplines, diceScores);
//Check that the most publications is currently NO_ONE
assert (getMostPublications (testGame) == NO_ONE);
//Make an action to obtain publication
action testAction;
testAction.actionCode = OBTAIN_PUBLICATION;
//Throw the dice to progress to a turn
throwDice (testGame, 1);
//Get whose turn it is now
playersTurn = getWhoseTurn (testGame);
//Obtain a publication for them
makeAction (testGame, testAction);
//Check that they now have the most publications
assert (getMostPublications (testGame) == playersTurn);
//Need to check proper tie behaviour
newPlayersTurn = getWhoseTurn (testGame);
//Obtain a publication for them
makeAction (testGame, testAction);
//Check behaviour in a tie
assert (getMostPublications (testGame) == playersTurn);
printf ("getMostPublications works - You are Awesome!\n\n");
}
void testGetARC (void){
printf ("Testing getARC\n");
//Initialize varible
int playersTurn = 0;
int disciplines[] = DEFAULT_DISCIPLINES;
int diceScores[] = DEFAULT_DICE;
//Create a new game to test on
Game testGame = newGame (disciplines, diceScores);
//Check that a whole bunch of them are vacant
assert (getARC (testGame, "L") == VACANT_ARC);
assert (getARC (testGame, "R") == VACANT_ARC);
assert (getARC (testGame, "LR") == VACANT_ARC);
assert (getARC (testGame, "RL") == VACANT_ARC);
// assert (getARC (testGame, "LLR") == VACANT_ARC);
assert (getARC (testGame, "RRL") == VACANT_ARC);
// assert (getARC (testGame, "RRR") == VACANT_ARC);
// assert (getARC (testGame, "LLL") == VACANT_ARC);
// assert (getARC (testGame, "LLLR") == VACANT_ARC);
// assert (getARC (testGame, "RRRL") == VACANT_ARC);
assert (getARC (testGame, "RRLL") == VACANT_ARC);
// assert (getARC (testGame, "LLRR") == VACANT_ARC);
assert (getARC (testGame, "LRRR") == VACANT_ARC);
assert (getARC (testGame, "RLLL") == VACANT_ARC);
// assert (getARC (testGame, "LLLL") == VACANT_ARC);
// assert (getARC (testGame, "RRRR") == VACANT_ARC);
// assert (getARC (testGame, "LLLLR") == VACANT_ARC);
// assert (getARC (testGame, "RRRRL") == VACANT_ARC);
// assert (getARC (testGame, "RRRLL") == VACANT_ARC);
// assert (getARC (testGame, "LLLRR") == VACANT_ARC);
//Advance turn from Terra Nullis
throwDice (testGame, 1);
//Get whose turn it is now
playersTurn = getWhoseTurn (testGame);
//Setup the action
action testAction;
testAction.actionCode = OBTAIN_ARC;
strcpy (testAction.destination, "L");
//Make the action
makeAction (testGame, testAction);
assert (getARC (testGame, "L") == playersTurn);
//Advance turn from Previous
throwDice (testGame, 1);
//Get whose turn it is now
playersTurn = getWhoseTurn (testGame);
//Setup the action
testAction.actionCode = OBTAIN_ARC;
strcpy (testAction.destination, "LR");
//Make the action
makeAction (testGame, testAction);
assert (getARC (testGame, "LR") == playersTurn);
//Advance turn from Previous
throwDice (testGame, 1);
//Get whose turn it is now
playersTurn = getWhoseTurn (testGame);
//Setup the action
testAction.actionCode = OBTAIN_ARC;
strcpy (testAction.destination, "RR");
//Make the action
makeAction (testGame, testAction);
assert (getARC (testGame, "RR") == playersTurn);
printf ("getARCs works - You are Awesome!\n\n");
}
void testGetGO8s (void){
printf ("Testing getGO8s\n");
//Initialize varible
int player = 0;
int disciplines[] = DEFAULT_DISCIPLINES;
int diceScores[] = DEFAULT_DICE;
//Create a new game to test on
Game testGame = newGame (disciplines, diceScores);
//Test that everyone starts with none during Terra Nullis
assert (getGO8s (testGame, UNI_A) == 0);
assert (getGO8s (testGame, UNI_B) == 0);
assert (getGO8s (testGame, UNI_C) == 0);
//Advance turn from Terra Nullis
throwDice (testGame, 1);
//Get whose turn it is now
player = getWhoseTurn (testGame);
//Setup the action
action testAction;
testAction.actionCode = BUILD_GO8;
strcpy (testAction.destination, "LR");
makeAction (testGame, testAction);
assert (getGO8s (testGame, player) == 1);
//Give him another one
testAction.actionCode = BUILD_GO8;
strcpy (testAction.destination, "LRR");
makeAction (testGame, testAction);
assert (getGO8s (testGame, player) == 2);
//Change the player
throwDice (testGame, 1);
//Get whose turn it is now
player = getWhoseTurn (testGame);
//Give them a GO8
testAction.actionCode = BUILD_GO8;
strcpy (testAction.destination, "LRR");
makeAction (testGame, testAction);
assert (getGO8s (testGame, player) == 1);
printf ("getGO8s works - You are Awesome!\n\n");
}
// STILL NEED TO FIGURE OUT HOW TO ASSIGN PEOPLE STUDENTS###############
void testGetStudents (void) {
//Initialize varible
//int player = 0;
printf ("Testing getStudents\n");
//Eh, setup another test game
int disciplines[] = DEFAULT_DISCIPLINES;
int diceScores[] = DEFAULT_DICE;
//Create a new game to test on
Game testGame = newGame (disciplines, diceScores);
//Check everyone has zero to start off with
assert (getStudents (testGame, UNI_A, STUDENT_THD) == 0);
assert (getStudents (testGame, UNI_A, STUDENT_BPS) == 3);
assert (getStudents (testGame, UNI_A, STUDENT_BQN) == 3);
assert (getStudents (testGame, UNI_A, STUDENT_MJ) == 1);
assert (getStudents (testGame, UNI_A, STUDENT_MTV) == 1);
assert (getStudents (testGame, UNI_A, STUDENT_MMONEY) == 1);
assert (getStudents (testGame, UNI_B, STUDENT_THD) == 0);
assert (getStudents (testGame, UNI_B, STUDENT_BPS) == 3);
assert (getStudents (testGame, UNI_B, STUDENT_BQN) == 3);
assert (getStudents (testGame, UNI_B, STUDENT_MJ) == 1);
assert (getStudents (testGame, UNI_B, STUDENT_MTV) == 1);
assert (getStudents (testGame, UNI_B, STUDENT_MMONEY) == 1);
assert (getStudents (testGame, UNI_C, STUDENT_THD) == 0);
assert (getStudents (testGame, UNI_C, STUDENT_BPS) == 3);
assert (getStudents (testGame, UNI_C, STUDENT_BQN) == 3);
assert (getStudents (testGame, UNI_C, STUDENT_MJ) == 1);
assert (getStudents (testGame, UNI_C, STUDENT_MTV) == 1);
assert (getStudents (testGame, UNI_C, STUDENT_MMONEY) == 1);
//Advance turn from Terra Nullis
throwDice (testGame, 11);
assert (getStudents (testGame, UNI_A, STUDENT_MTV) == 2);
throwDice (testGame, 8);
assert (getStudents (testGame, UNI_C, STUDENT_MTV) == 2);
assert (getStudents (testGame, UNI_C, STUDENT_MJ) == 2);
throwDice (testGame, 8);
assert (getStudents (testGame, UNI_C, STUDENT_MTV) == 3);
assert (getStudents (testGame, UNI_C, STUDENT_MJ) == 3);
throwDice (testGame, 11);
assert (getStudents (testGame, UNI_A, STUDENT_MTV) == 3);
throwDice (testGame, 9);
assert (getStudents (testGame, UNI_B, STUDENT_BQN) == 4);
throwDice (testGame, 6);
//assert (getStudents (testGame, UNI_B, STUDENT_MJ) == 1);
printf ("getStudents works - You are Awesome!\n\n");
}
void testMakeAction (void) {
printf ("Testing makeAction\n");
// test BUILD_CAMPUS and BUILD_GO8 and PASS
testGetCampus ();
// test OBTAIN_ARC
testGetARCs ();
// test START_SPINOFF and OBTAIN_PUBLICATION
testGetPublications ();
// test RETRAIN_STUDENTS
testGetStudents ();
// test OBTAIN_IP_PATENT
testGetIPs ();
printf ("makeAction works - You are Awesome!\n\n");
}
void testGetMostARCs (void) {
printf ("Testing getMostARCs\n");
// Create a game
int disciplines [] = DEFAULT_DISCIPLINES;
int dice[] = DEFAULT_DICE;
Game testGame = newGame (disciplines, dice);
// Check all players start with 0 arcs
assert (getMostARCs (testGame) == NO_ONE);
// Go to next turn (A)
throwDice (testGame, 3);
// Create and execute action that creates an arc
action testAction;
testAction.actionCode = OBTAIN_ARC;
strcpy (testAction.destination, "LBL");
makeAction (testGame, testAction);
// Check first player has most arcs
assert (getMostARCs (testGame) == UNI_A);
// Go to next player (B)
throwDice (testGame, 5);
// Create 2 arcs
strcpy (testAction.destination, "RRL");
makeAction (testGame, testAction);
assert (getMostARCs (testGame) == UNI_A);
strcpy (testAction.destination, "RRLLL");
makeAction (testGame, testAction);
// Check player 2 has the most arcs
assert (getMostARCs (testGame) == UNI_B);
// Go to next player (C) and pass
throwDice (testGame, 5);
testAction.actionCode = PASS;
makeAction (testGame, testAction);
// Check player 2 has the most arcs
assert (getMostARCs (testGame) == UNI_B);
// Go to next player (A)
throwDice (testGame, 2);
assert (getMostARCs (testGame) == UNI_B);
// Pass and check player B still has the most arcs
makeAction (testGame, testAction);
assert (getMostARCs (testGame) == UNI_B);
// Go to next player (B)
throwDice (testGame, 4);
// Create an arc
testAction.actionCode = OBTAIN_ARC;
strcpy (testAction.destination, "LRLRL");
makeAction (testGame, testAction);
// Check player 2 still has most arcs
assert (getMostARCs (testGame) == UNI_B);
// Go to next player (C)
throwDice (testGame, 9);
strcpy (testAction.destination, "LRRLRLRLRLRBRL");
makeAction (testGame, testAction);
assert (getMostARCs (testGame) == UNI_B);
strcpy (testAction.destination, "LRR");
makeAction (testGame, testAction);
assert (getMostARCs (testGame) == UNI_B);
strcpy (testAction.destination, "LRLRRBR");
makeAction (testGame, testAction);
assert (getMostARCs (testGame) == UNI_B);
strcpy (testAction.destination, "LRL");
makeAction (testGame, testAction);
assert (getMostARCs (testGame) == UNI_C);
disposeGame (testGame);
printf ("getMostARCs works - You are Awesome!\n\n");
}
void testGetCampus (void) {
// Create a game
printf ("Testing getCampus\n");
int disciplines [] = DEFAULT_DISCIPLINES;
int dice[] = DEFAULT_DICE;
Game testGame = newGame (disciplines, dice);
// Check random vertices are vacant
assert (getCampus (testGame, "LRLR") == VACANT_VERTEX);
assert (getCampus (testGame, "RRLRLLRLLRBR") == VACANT_VERTEX);
// Check starting campuses exist
assert (getCampus (testGame, "") == CAMPUS_A);
assert (getCampus (testGame, "LRLRLRRLRLRRLRL") == CAMPUS_A);
assert (getCampus (testGame, "RRLRL") == CAMPUS_B);
assert (getCampus (testGame, "LRLRLRRLRL") == CAMPUS_B);
assert (getCampus (testGame, "LRLRL") == CAMPUS_C);
assert (getCampus (testGame, "RRLRLLRLRL") == CAMPUS_C);
// Go to next turn (A)
throwDice (testGame, 3);
// Create and execute action that creates a campus
action testAction;
testAction.actionCode = BUILD_CAMPUS;
strcpy (testAction.destination, "LRR");
makeAction (testGame, testAction);
// Check campus is built and other vertices are the same
assert (getCampus (testGame, "LRLBR") == VACANT_VERTEX);
assert (getCampus (testGame, "LRR") == CAMPUS_A);
assert (getCampus (testGame, "LR") == VACANT_VERTEX);
assert (getCampus (testGame, "LBLLRR") == VACANT_VERTEX);
// Create a GO8 campus
testAction.actionCode = BUILD_GO8;
strcpy (testAction.destination, "");
makeAction (testGame, testAction);
// Check campus is built and other vertices are correct
assert (getCampus (testGame, "") == GO8_A);
assert (getCampus (testGame, "LRR") == CAMPUS_A);
assert (getCampus (testGame, "RLLRRLLRLR") == CAMPUS_B);
assert (getCampus (testGame, "RLLRRLLRL") == VACANT_VERTEX);
// Go to next player (B)
throwDice (testGame, 5);
// Create a campus
testAction.actionCode = BUILD_CAMPUS;
strcpy (testAction.destination, "RLLRRLLRLR");
makeAction (testGame, testAction);
// Check campus is built and other vertices are correct
assert (getCampus (testGame, "LRLBR") == VACANT_VERTEX);
assert (getCampus (testGame, "LRR") == CAMPUS_A);
assert (getCampus (testGame, "") == GO8_A);
assert (getCampus (testGame, "RLLRRLLRLR") == CAMPUS_B);
// Build another campus
testAction.actionCode = BUILD_CAMPUS;
strcpy (testAction.destination, "RLLRRLLRLRRRBB");
makeAction (testGame, testAction);
// Check campus is built and other vertices are correct
assert (getCampus (testGame, "LRLBR") == VACANT_VERTEX);
assert (getCampus (testGame, "") == GO8_A);
assert (getCampus (testGame, "RLLRRLLRLR") == CAMPUS_B);
assert (getCampus (testGame, "RLLRRLLRLRRRBB") == CAMPUS_B);
// Go to next player (C)
throwDice (testGame, 5);
// Create a campus
testAction.actionCode = BUILD_CAMPUS;
strcpy (testAction.destination, "LRRRLRLRL");
makeAction (testGame, testAction);
// Check campus is built and other vertices are correct
assert (getCampus (testGame, "LRLBRLB") == VACANT_VERTEX);
assert (getCampus (testGame, "RLLRRLLRLR") == CAMPUS_B);
assert (getCampus (testGame, "RLLRRLLRLRRRBB") == CAMPUS_B);
assert (getCampus (testGame, "") == GO8_A);
assert (getCampus (testGame, "LRRRLRLRL") == CAMPUS_C);
// Go to next player (A)
throwDice (testGame, 5);
// Pass player
testAction.actionCode = PASS;
makeAction (testGame, testAction);
// Check vertices are still correct
assert (getCampus (testGame, "LRR") == CAMPUS_A);
assert (getCampus (testGame, "RLLRRLLRLR") == CAMPUS_B);
assert (getCampus (testGame, "LRLRLRRLRL") == CAMPUS_B);
assert (getCampus (testGame, "") == GO8_A);
assert (getCampus (testGame, "LRRRLRLRL") == CAMPUS_C);
// Go to next turn (B)
throwDice (testGame, 3);
// Create a campus
testAction.actionCode = BUILD_GO8;
strcpy (testAction.destination, "RRLRL");
makeAction (testGame, testAction);
// Check campus is built and other vertices are still empty
assert (getCampus (testGame, "LRLBR") == VACANT_VERTEX);
assert (getCampus (testGame, "LRR") == CAMPUS_A);
assert (getCampus (testGame, "RLLRRLLRLR") == CAMPUS_B);
assert (getCampus (testGame, "RLLRRLLRLRRRBB") == CAMPUS_B);
assert (getCampus (testGame, "RRLRL") == GO8_B);
assert (getCampus (testGame, "") == GO8_A);
assert (getCampus (testGame, "LRRRLRLRL") == CAMPUS_C);
disposeGame (testGame);
printf ("getCampus works - You are Awesome!\n\n");
}
// test GetArcs function
void testGetARCs (void) {
printf ("Testing getARCs\n");
// Create a game
int disciplines [] = DEFAULT_DISCIPLINES;
int dice[] = DEFAULT_DICE;
Game testGame = newGame (disciplines, dice);
// Check all players start with 0 arcs
assert (getARCs (testGame, UNI_A) == 0);
assert (getARCs (testGame, UNI_B) == 0);
assert (getARCs (testGame, UNI_C) == 0);
// Go to next turn (A)
throwDice (testGame, 3);
// Create and execute action that creates an arc
action testAction;
testAction.actionCode = OBTAIN_ARC;
strcpy (testAction.destination, "LBL");
makeAction (testGame, testAction);
// Check first player has 1 arc, others still have none
assert (getARCs (testGame, UNI_A) == 1);
assert (getARCs (testGame, UNI_B) == 0);
assert (getARCs (testGame, UNI_C) == 0);
// Go to next player (B)
throwDice (testGame, 5);
// Create 2 arcs
strcpy (testAction.destination, "RRLRL");
makeAction (testGame, testAction);
strcpy (testAction.destination, "RLLRRLL");
makeAction (testGame, testAction);
// Check each player has the right number of arcs
assert (getARCs (testGame, UNI_A) == 1);
assert (getARCs (testGame, UNI_B) == 2);
assert (getARCs (testGame, UNI_C) == 0);
// Go to next player (C)
throwDice (testGame, 5);
// Pass player
testAction.actionCode = PASS;
makeAction (testGame, testAction);
// Check each player has the right number of arcs
assert (getARCs (testGame, UNI_A) == 1);
assert (getARCs (testGame, UNI_B) == 2);
assert (getARCs (testGame, UNI_C) == 0);
// Go to next player (A)
throwDice (testGame, 2);
// Check each player has the right number of arcs
assert (getARCs (testGame, UNI_A) == 1);
assert (getARCs (testGame, UNI_B) == 2);
assert (getARCs (testGame, UNI_C) == 0);
// Pass player
testAction.actionCode = PASS;
makeAction (testGame, testAction);
// Go to next player (B)
throwDice (testGame, 5);
// Pass player
testAction.actionCode = PASS;
makeAction (testGame, testAction);
// Check each player has the right number of arcs
assert (getARCs (testGame, UNI_A) == 1);
assert (getARCs (testGame, UNI_B) == 2);
assert (getARCs (testGame, UNI_C) == 0);
// Go to next player (C)
throwDice (testGame, 5);
// Create an arc
testAction.actionCode = OBTAIN_ARC;
strcpy (testAction.destination, "RLLRRLLRLRR");
makeAction (testGame, testAction);
// Check each player has the right number of arcs
assert (getARCs (testGame, UNI_A) == 1);
assert (getARCs (testGame, UNI_B) == 2);
assert (getARCs (testGame, UNI_C) == 1);
disposeGame (testGame);
printf ("getARCs works - You are Awesome!\n\n");
}
void testGetPublications (void) {
printf ("Testing getPublications\n");
// Create a game
int disciplines [] = DEFAULT_DISCIPLINES;
int dice[] = DEFAULT_DICE;
Game testGame = newGame (disciplines, dice);
// Check all players start with 0 publications
assert (getPublications (testGame, UNI_A) == 0);
assert (getPublications (testGame, UNI_B) == 0);
assert (getPublications (testGame, UNI_C) == 0);
// Go to next turn (A)
throwDice (testGame, 3);
// Create and execute action that creates a publication
action testAction;
testAction.actionCode = OBTAIN_PUBLICATION;
makeAction (testGame, testAction);
// Check first player has 1 publication, others still have none
assert (getPublications (testGame, UNI_A) == 1);
assert (getPublications (testGame, UNI_B) == 0);
assert (getPublications (testGame, UNI_C) == 0);
// Go to next player (B)
throwDice (testGame, 5);
// Create 2 publications
makeAction (testGame, testAction);
makeAction (testGame, testAction);
// Check B has 2 publications and other players are also correct
assert (getPublications (testGame, UNI_A) == 1);
assert (getPublications (testGame, UNI_B) == 2);
assert (getPublications (testGame, UNI_C) == 0);
// Go to next player (C)
throwDice (testGame, 5);
// Pass player
testAction.actionCode = PASS;
makeAction (testGame, testAction);
// Check number of publications is correct
assert (getPublications (testGame, UNI_A) == 1);
assert (getPublications (testGame, UNI_B) == 2);
assert (getPublications (testGame, UNI_C) == 0);
// Go to next player (A)
throwDice (testGame, 2);
assert (getPublications (testGame, UNI_A) == 1);
assert (getPublications (testGame, UNI_B) == 2);
assert (getPublications (testGame, UNI_C) == 0);
// Pass player
testAction.actionCode = PASS;
makeAction (testGame, testAction);
// Check number of publications is correct
assert (getPublications (testGame, UNI_A) == 1);
assert (getPublications (testGame, UNI_B) == 2);
assert (getPublications (testGame, UNI_C) == 0);
// Go to next player (B)
throwDice (testGame, 5);
// Create a publications
testAction.actionCode = OBTAIN_PUBLICATION;
makeAction (testGame, testAction);
// Check number of publications is correct
assert (getPublications (testGame, UNI_A) == 1);
assert (getPublications (testGame, UNI_B) == 3);
assert (getPublications (testGame, UNI_C) == 0);
// Go to next player (C)
throwDice (testGame, 5);
// Create a publications
makeAction (testGame, testAction);
// Check number of publications is correct
assert (getPublications (testGame, UNI_A) == 1);
assert (getPublications (testGame, UNI_B) == 3);
assert (getPublications (testGame, UNI_C) == 1);
disposeGame (testGame);
printf ("getPublications Works - You are Awesome!\n\n");
}
void testGetDiceValue (void) {
printf ("Testing getDiceValue\n");
int disciplines[] = DEFAULT_DISCIPLINES;
int diceScores[] = DEFAULT_DICE;
int dice[] = DEFAULT_DICE;
//Create a new game to test on
Game testGame = newGame (disciplines, diceScores);
printf ("here!");
assert (getDiceValue (testGame, REGION_0) == dice[0]);
assert (getDiceValue (testGame, REGION_1) == dice[1]);
assert (getDiceValue (testGame, REGION_2) == dice[2]);
assert (getDiceValue (testGame, REGION_3) == dice[3]);
assert (getDiceValue (testGame, REGION_4) == dice[4]);
assert (getDiceValue (testGame, REGION_5) == dice[5]);
assert (getDiceValue (testGame, REGION_6) == dice[6]);
assert (getDiceValue (testGame, REGION_7) == dice[7]);
assert (getDiceValue (testGame, REGION_8) == dice[8]);
assert (getDiceValue (testGame, REGION_9) == dice[9]);
assert (getDiceValue (testGame, REGION_10) == dice[10]);
assert (getDiceValue (testGame, REGION_11) == dice[11]);
assert (getDiceValue (testGame, REGION_12) == dice[12]);
assert (getDiceValue (testGame, REGION_13) == dice[13]);
assert (getDiceValue (testGame, REGION_14) == dice[14]);
assert (getDiceValue (testGame, REGION_15) == dice[15]);
assert (getDiceValue (testGame, REGION_16) == dice[16]);
assert (getDiceValue (testGame, REGION_17) == dice[17]);
assert (getDiceValue (testGame, REGION_18) == dice[18]);
printf ("getDiceValue works - You are Awesome!\n\n");
}
// needs value of turn count which will be stored in the game struct
// determines which unis turn it is by using modulus 3
// if turn count is -1, it's no ones turn. Uni A always goes first.
void testGetWhoseTurn (void) {
printf ("Testing getWhoseTurn\n");
int turnCounter = 0;
int turn2 = 1;
int disciplines[] = DEFAULT_DISCIPLINES;
int diceScores[] = DEFAULT_DICE;
//Create a new game to test on
Game testGame = newGame (disciplines, diceScores);
// test first 4 turns throw by throw
assert (getWhoseTurn (testGame) == NO_ONE);
throwDice (testGame, 2);
assert (getWhoseTurn (testGame) == UNI_A);
throwDice (testGame, 4);
assert (getWhoseTurn (testGame) == UNI_B);
throwDice (testGame, 6);
assert (getWhoseTurn (testGame) == UNI_C);
throwDice (testGame, 3);
//test next heaps of turns so see if it breaks later on.
while (turnCounter < 9000) {
while (turn2 <= 3) {
assert (getWhoseTurn (testGame) == turn2);
throwDice (testGame, 3);
turn2 ++;
}
turn2 = 1;
turnCounter ++;
}
printf ("getWhoseTurn works - You are Awesome!\n\n");
}
void testGetKPIpoints (void) {
printf("Testing getKPIpoints\n");
int disciplines[] = DEFAULT_DISCIPLINES;
int diceScores[] = DEFAULT_DICE;
//Create a new game to test on
Game testGame = newGame (disciplines, diceScores);
// assert initial KPIs are 2*no of campus points == 20
assert (getKPIpoints (testGame, UNI_A) == 20);
assert (getKPIpoints (testGame, UNI_B) == 20);
assert (getKPIpoints (testGame, UNI_C) == 20);
//advance turn to UNI_A, build campus, check +10 KPI points
throwDice (testGame, 4);
action testAction;
testAction.actionCode = BUILD_CAMPUS;
strcpy (testAction.destination, "LRRLRLRLRLRBRL");
makeAction (testGame, testAction);
assert (getKPIpoints (testGame, UNI_A) == 30);
assert (getKPIpoints (testGame, UNI_B) == 20);
assert (getKPIpoints (testGame, UNI_C) == 20);
//advance to UNI_B build arc, check +2 for arc and +10 for most arcs
throwDice (testGame ,6);
testAction.actionCode = OBTAIN_ARC;
strcpy (testAction.destination, "RRLLL");
makeAction (testGame, testAction);
assert (getKPIpoints (testGame, UNI_A) == 30);
assert (getKPIpoints (testGame, UNI_B) == 32);
assert (getKPIpoints (testGame, UNI_C) == 20);
//advance to UNI_C get publication, check for most publications
throwDice (testGame, 4);
testAction.actionCode = OBTAIN_PUBLICATION;
makeAction (testGame, testAction);
assert (getKPIpoints (testGame, UNI_A) == 30);
assert (getKPIpoints (testGame, UNI_B) == 32);
assert (getKPIpoints (testGame, UNI_C) == 30);
//advance to UNI_A get publication and get GO8, check only +10
// as not first uni to reach most publications
throwDice (testGame, 4);
testAction.actionCode = BUILD_GO8;
strcpy (testAction.destination, "LBL");
makeAction (testGame, testAction);
assert (getKPIpoints (testGame, UNI_A) == 40);
assert (getKPIpoints (testGame, UNI_B) == 32);
assert (getKPIpoints (testGame, UNI_C) == 30);
//obtain arc, test is now most arcs
testAction.actionCode = OBTAIN_ARC;
strcpy (testAction.destination, "LRR");
makeAction (testGame, testAction);
strcpy (testAction.destination, "LRRL");
makeAction (testGame, testAction);
assert (getKPIpoints (testGame, UNI_A) == 54);
assert (getKPIpoints (testGame, UNI_B) == 22);
assert (getKPIpoints (testGame, UNI_C) == 30);
//advance to UNI_B obtain IP
throwDice (testGame, 4);
testAction.actionCode = OBTAIN_IP_PATENT;
makeAction (testGame, testAction);
assert (getKPIpoints (testGame, UNI_A) == 54);
assert (getKPIpoints (testGame, UNI_B) == 32);
assert (getKPIpoints (testGame, UNI_C) == 30);
printf ("getKPIpoints works - You are Awesome!\n\n");
}
void testGetIPs (void) {
printf("Testing getIPs\n");
// initialise testGame test all start at 0
int disciplines[] = DEFAULT_DISCIPLINES;
int diceScores[] = DEFAULT_DICE;
//Create a new game to test on
Game testGame = newGame (disciplines, diceScores);
assert (getIPs (testGame, UNI_A) == 0);
assert (getIPs (testGame, UNI_B) == 0);
assert (getIPs (testGame, UNI_C) == 0);
//advance turn to UNI_A obtain patent
throwDice (testGame, 4);
action testAction;
testAction.actionCode = OBTAIN_IP_PATENT;
makeAction (testGame, testAction);
assert (getIPs (testGame, UNI_A) == 1);
assert (getIPs (testGame, UNI_B) == 0);
assert (getIPs (testGame, UNI_C) == 0);
//advance turn to UNI_C obtain patent
throwDice (testGame, 3);
throwDice (testGame, 2);
makeAction (testGame, testAction);
assert (getIPs (testGame, UNI_A) == 1);
assert (getIPs (testGame, UNI_B) == 0);
assert (getIPs (testGame, UNI_C) == 1);
//advance turn to UNI_B obtain patent
throwDice (testGame, 6);
throwDice (testGame, 8);
makeAction (testGame, testAction);
assert (getIPs (testGame, UNI_A) == 1);
assert (getIPs (testGame, UNI_B) == 1);
assert (getIPs (testGame, UNI_C) == 1);
throwDice (testGame, 8);
makeAction (testGame, testAction);
makeAction (testGame, testAction);
assert (getIPs (testGame, UNI_A) == 1);
assert (getIPs (testGame, UNI_B) == 1);
assert (getIPs (testGame, UNI_C) == 3);
printf ("getIPs works - You are Awesome!\n\n");
}
// testing: void disposeGame (Game g);
// free all the memory malloced for the game
void testDisposeGame (void) {
printf ("Testing disposeGame\n");
// create a test game
int disciplines[] = DEFAULT_DISCIPLINES;
int dice[] = DEFAULT_DICE;
Game testGame = newGame (disciplines, dice);
// just run the function
// may be need to check if game is not pointing to anything meaningful anymore
// i.e. pointer is cleared
disposeGame (testGame);
printf ("disposeGame works - You are Awesome!\n\n");
}
// testing: int getDiscipline (Game g, int regionID);
// what type of students are produced by the specified region?
void testGetDiscipline (void) {
printf ("Testing getDiscipline\n");
// create a test game
int disciplines[] = DEFAULT_DISCIPLINES;
int dice[] = DEFAULT_DICE;
Game testGame = newGame (disciplines, dice);
// assert if the discipline in the region 1 is as defined in the DEFAULT_DISCIPLINES
assert (getDiscipline (testGame, 1) == STUDENT_MMONEY);
// assert if the discipline in the region 0 is as defined in the DEFAULT_DISCIPLINES
assert (getDiscipline (testGame, 0) == STUDENT_BQN);
// assert if the discipline in the region 18 (last) is as defined in the DEFAULT_DISCIPLINES
assert (getDiscipline (testGame, 18) == STUDENT_BPS);
printf ("getDiscipline works - You are Awesome!\n\n");
}
// testing: int getTurnNumber (Game g);
// return the current turn number of the game -1,0,1, ..
void testGetTurnNumber (void) {
printf ("Testing getTurnNumber\n");
// create a test game
int disciplines[] = DEFAULT_DISCIPLINES;
int dice[] = DEFAULT_DICE;
Game testGame = newGame (disciplines, dice);
// use throwDice to make a turn
throwDice (testGame, 1);
// assert if the turn number has increased
assert (getTurnNumber (testGame) == 0);
// use throwDice to make a turn
throwDice (testGame, 2);
assert (getTurnNumber (testGame) == 1);
printf ("getTurnNumber works - You are Awesome!\n\n");
}
// testing: int isLegalAction (Game g, action a);
// returns TRUE if it is legal for the current
// player to make the specified action, FALSE otherwise.
//
// "legal" means everything is legal:
// * that the action code is a valid action code which is legal to
// be made at this time
// * that any path is well formed and legal ie consisting only of
// the legal direction characters and of a legal length,
// and which does not leave the island into the sea at any stage.
// * that disciplines mentioned in any retraining actions are valid
// discipline numbers, and that the university has sufficient
// students of the correct type to perform the retraining
//
// eg when placing a campus consider such things as:
// * is the path a well formed legal path
// * does it lead to a vacent vertex?
// * under the rules of the game are they allowed to place a
// campus at that vertex? (eg is it adjacent to one of their ARCs?)
// * does the player have the 4 specific students required to pay for
// that campus?
// It is not legal to make any action during Terra Nullis ie
// before the game has started.
// It is not legal for a player to make the moves OBTAIN_PUBLICATION
// or OBTAIN_IP_PATENT (they can make the move START_SPINOFF)
// you can assume that any pths passed in are NULL terminated strings.
//
// ACTIONS:
// #define PASS 0
// #define BUILD_CAMPUS 1
// #define BUILD_GO8 2
// #define OBTAIN_ARC 3
// #define START_SPINOFF 4
// #define OBTAIN_PUBLICATION 5
// #define OBTAIN_IP_PATENT 6
// #define RETRAIN_STUDENTS 7
//
// DISCIPLINES:
// #define STUDENT_THD 0
// #define STUDENT_BPS 1
// #define STUDENT_BQN 2
// #define STUDENT_MJ 3
// #define STUDENT_MTV 4
// #define STUDENT_MMONEY 5
//
// LATER: this test will grow significantly to test all possible loopholes and exploits
// later: for all disciplines check valid/invalid situations depending on the rules
// later: obtain_pub/obtain_patent for player - not sure yet
// later: check amount of students for the campus placing
void testIsLegalAction (void) {
printf ("Testing isLegalAction\n");
// (2,0) is the starting point
// create a test game
int disciplines[] = DEFAULT_DISCIPLINES;
int dice[] = DEFAULT_DICE;
int player = 0;
Game testGame = newGame (disciplines, dice);
// create a test action
action testAction;
// it is not legal to make any action during Terra Nullis ie before the game started
testAction.actionCode = PASS;
assert (isLegalAction (testGame, testAction) == FALSE);
// do a bunch of throw dice to give resources
int turn = 0;
while (turn < 50) {
throwDice (testGame, rollDice (TRUE));
turn++;
}
// now is it legal? - should be
assert (isLegalAction (testGame, testAction) == TRUE);
// next turn (Player C)
throwDice (testGame, 4);
// test action codes
testAction.actionCode = PASS;
assert (isLegalAction (testGame, testAction) == TRUE);
while (player != UNI_A) {
throwDice (testGame, rollDice (TRUE));
player = getWhoseTurn (testGame);
}
// when the player starts it's supposed to have resources to build the arc
testAction.actionCode = OBTAIN_ARC;
strcpy (testAction.destination, "R");
assert (isLegalAction (testGame, testAction) == TRUE);
testAction.actionCode = BUILD_CAMPUS;
strcpy (testAction.destination, "RRL");
assert (isLegalAction (testGame, testAction) == FALSE);
strcpy (testAction.destination, "RRRRRR");
testAction.actionCode = BUILD_GO8;
assert (isLegalAction (testGame, testAction) == FALSE);
testAction.actionCode = OBTAIN_ARC;
strcpy (testAction.destination, "RRRRRR");
assert (isLegalAction (testGame, testAction) == FALSE);
testAction.actionCode = START_SPINOFF;
assert (isLegalAction (testGame, testAction) == FALSE);
testAction.actionCode = OBTAIN_PUBLICATION;
//assert (isLegalAction (testGame, testAction) == TRUE);
testAction.actionCode = OBTAIN_IP_PATENT;
//assert (isLegalAction (testGame, testAction) == TRUE);
testAction.actionCode = RETRAIN_STUDENTS;
testAction.disciplineFrom = STUDENT_BPS;
testAction.disciplineTo = STUDENT_BQN;
assert (isLegalAction (testGame, testAction) == TRUE);
testAction.actionCode = 21; // invalid code
assert (isLegalAction (testGame, testAction) == FALSE);
action makeCampuses;
makeCampuses.actionCode = BUILD_CAMPUS;
strcpy (makeCampuses.destination, "RRL");
makeAction (testGame, makeCampuses);
makeCampuses.actionCode = BUILD_CAMPUS;
strcpy (makeCampuses.destination, "LRL");
makeAction (testGame, makeCampuses);
strcpy (makeCampuses.destination, "RLRLR");
makeAction (testGame, makeCampuses);
/*testAction.actionCode = BUILD_CAMPUS;
strcpy (testAction.destination, "R");
assert (isLegalAction (testGame, testAction) == FALSE);
testAction.actionCode = BUILD_GO8;
strcpy (testAction.destination, "LRLRL");
assert (isLegalAction (testGame, testAction) == TRUE);
testAction.actionCode = OBTAIN_ARC;
strcpy (testAction.destination, "LRLRL");
assert (isLegalAction (testGame, testAction) == TRUE);
testAction.actionCode = OBTAIN_ARC;
strcpy (testAction.destination, "R");
assert (isLegalAction (testGame, testAction) == FALSE);
strcpy (testAction.destination, "L");
assert (isLegalAction (testGame, testAction) == FALSE);
testAction.actionCode = START_SPINOFF;
assert (isLegalAction (testGame, testAction) == TRUE);
testAction.actionCode = OBTAIN_PUBLICATION;
assert (isLegalAction (testGame, testAction) == FALSE);
testAction.actionCode = OBTAIN_IP_PATENT;
assert (isLegalAction (testGame, testAction) == FALSE);
testAction.actionCode = RETRAIN_STUDENTS;
testAction.disciplineFrom = STUDENT_BPS;
testAction.disciplineTo = STUDENT_BQN;
assert (isLegalAction (testGame, testAction) == TRUE);
testAction.actionCode = RETRAIN_STUDENTS;
testAction.disciplineFrom = STUDENT_THD;
testAction.disciplineTo = STUDENT_BQN;
assert (isLegalAction (testGame, testAction) == FALSE);
testAction.actionCode = 21; // invalid code
assert (isLegalAction (testGame, testAction) == FALSE);
testAction.actionCode = 8; // invalid code
assert (isLegalAction (testGame, testAction) == FALSE);*/
// check paths
testAction.actionCode = OBTAIN_ARC;
// normal path not next to another path/campus
strcpy (testAction.destination, "LR");
assert (isLegalAction (testGame, testAction) == FALSE);
// normal path next to another path/campus
//strcpy (testAction.destination, "LRLRLR");
//assert (isLegalAction (testGame, testAction) == TRUE);
// invalid character path
strcpy (testAction.destination, "LXX");
assert (isLegalAction (testGame, testAction) == FALSE);
// path too long
strcpy (testAction.destination, "LLLLLLLLLLLLLLLLRRRRRRRRRRRRRRLL");
assert (isLegalAction (testGame, testAction) == FALSE);
// path leading to nowhere (sea)
strcpy (testAction.destination, "LLLL");
assert (isLegalAction (testGame, testAction) == FALSE);
// do a bunch of throw dice to give resources
turn = 0;
while (turn < 50) {
throwDice (testGame, rollDice (TRUE));
turn++;
}
// check disciplines for the retraining
testAction.actionCode = RETRAIN_STUDENTS;
// from THD
testAction.disciplineFrom = STUDENT_THD;
testAction.disciplineTo = STUDENT_THD;
assert (isLegalAction (testGame, testAction) == FALSE);
testAction.disciplineFrom = STUDENT_THD;
testAction.disciplineTo = STUDENT_BQN;
assert (isLegalAction (testGame, testAction) == FALSE);
// from THD
testAction.disciplineFrom = STUDENT_THD;
testAction.disciplineTo = STUDENT_THD;
assert (isLegalAction (testGame, testAction) == FALSE);
// normal retraining
testAction.disciplineFrom = STUDENT_BQN;
testAction.disciplineTo = STUDENT_MJ;
assert (isLegalAction (testGame, testAction) == TRUE);
// normal retraining
testAction.disciplineFrom = STUDENT_MTV;
testAction.disciplineTo = STUDENT_MMONEY;
assert (isLegalAction (testGame, testAction) == TRUE);
}
// Testing: int getCampuses (Game g, int player);
// return the number of normal Campuses the specified player currently has
void testGetCampuses (void) {
printf ("Testing getCampuses\n");
int player = 0;
int anotherPlayer = 0;
// create a test game
int disciplines[] = DEFAULT_DISCIPLINES;
int dice[] = DEFAULT_DICE;
Game testGame = newGame (disciplines, dice);
// check that there are 2 campuses per uni
assert (getCampuses (testGame, UNI_A) == 2);
assert (getCampuses (testGame, UNI_B) == 2);
assert (getCampuses (testGame, UNI_C) == 2);
// make a turn
throwDice (testGame, 1);
// assert that the vertex at the path is vacant
assert (getCampus (testGame, "LRRRL") == VACANT_VERTEX);
// get player ID
player = getWhoseTurn (testGame);
// create a test action to make a campus
action testAction;
testAction.actionCode = BUILD_CAMPUS;
strcpy (testAction.destination, "LRRRL");
// build the campus
makeAction (testGame, testAction);
// check that the campus amount is 3 now
assert (getCampuses (testGame, player) == 3);
// one more campus
// assert that the vertex at the path is vacant
assert (getCampus (testGame, "LRRRLL") == VACANT_VERTEX);
strcpy (testAction.destination, "LRRRLL");
// build the campus
makeAction (testGame, testAction);
// check that the campus amount is 4 now
assert (getCampuses (testGame, player) == 4);
// one campus for another player
// make turns
// get player ID that is different from player
anotherPlayer = player;
while (anotherPlayer == player) {
throwDice (testGame, 3);
anotherPlayer = getWhoseTurn (testGame);
}
assert (getCampus (testGame, "LRR") == VACANT_VERTEX);
// create a test action to make a campus
testAction.actionCode = BUILD_CAMPUS;
strcpy (testAction.destination, "LRR");
// build the campus
makeAction (testGame, testAction);
// check that the campus amount is 3 now
assert (getCampuses (testGame, anotherPlayer) == 3);
printf ("getCampuses works - You are Awesome!\n\n");
}
// roll the dice randomly
int rollDice (int no7) {
printf ("Rolling dice...\n");
int dice1 = 0;
int dice2 = 0;
int diceScore = 7;
while (!no7 || (no7 && diceScore == 7)) {
// random int between 0 and 6
dice1 = rand () % 6 + 1;
dice2 = rand () % 6 + 1;
diceScore = dice1 + dice2;
}
printf ("Score is: %d\n", diceScore);
return diceScore;
}
void failedExternalTests(void){
printf("Testing EXT1\n");
action a;
int disciplines[] = {2,5,3,5,3,1,4,4,1,4,2,3,2,0,3,5,4,2,1};
int dice[] = {9,10,8,12,6,5,3,11,3,11,4,6,4,7,9,2,8,10,5};
Game g = newGame(disciplines, dice);
throwDice(g, 11);
throwDice(g, 11);
throwDice(g, 11);
throwDice(g, 11);
a.actionCode = OBTAIN_ARC;
strncpy(a.destination, "\0", PATH_LIMIT - 1);
a.destination[PATH_LIMIT - 1] = 0;
a.disciplineFrom = 0, a.disciplineTo = 0;
assert (isLegalAction(g, a) == FALSE);
}
// this is a wrong test from others
// they assume we start with 24 points
// whereas the rules say we start with just 2 campuses
// online game version has 2 ARCs but it's not our spec
void externalTest001(void) {
printf("External Test 001 start\n");
//action a;
int disciplines[] = {2,5,3,5,3,1,4,4,1,4,2,3,2,0,3,5,4,2,1};
int dice[] = {9,10,8,12,6,5,3,11,3,11,4,6,4,7,9,2,8,10,5};
Game g = newGame(disciplines, dice);
//assert(getKPIpoints(g, 1) != 24); that's what they tested
assert(getKPIpoints(g, 1) == 20); // that's what it should be
printf("External Test 001 end\n");
}
// Test for simon.shield
void failedExternalTestSimon(void){
int player = 1;
int disciplines[] = {2,5,3,5,3,1,4,4,1,4,2,3,2,0,3,5,4,2,1};
int dice[] = {9,10,8,12,6,5,3,11,3,11,4,6,4,7,9,2,8,10,5};
Game g = newGame(disciplines, dice);
assert(getExchangeRate(g, player, 1, 2) == 3);
}
void failedExternalTestMeghana(void){
action a;
int disciplines[] = {2,5,3,5,3,1,4,4,1,4,2,3,2,0,3,5,4,2,1};
int dice[] = {9,10,8,12,6,5,3,11,3,11,4,6,4,7,9,2,8,10,5};
Game g = newGame(disciplines, dice);
throwDice(g, 2);
a.actionCode = OBTAIN_ARC;
strncpy(a.destination, "", PATH_LIMIT - 1);
a.destination[PATH_LIMIT - 1] = 0;
a.disciplineFrom = 134542712, a.disciplineTo = -1076558664;
assert(isLegalAction(g, a) == FALSE);
}
// Authors: vidler
// Testing make
// Author code style is kept!
// testing if we have 0 students left after trading
// by the looks of it it's an invalid setup
void externalTest002(void) {
printf("External Test 002 start\n");
action a;
int disciplines[] = {2,5,3,5,3,1,4,4,1,4,2,3,2,0,3,5,4,2,1};
int dice[] = {9,10,8,12,6,5,3,11,3,11,4,6,4,7,9,2,8,10,5};
Game g = newGame(disciplines, dice);
printf("PLayer 3 had %d student in 0\n", getStudents(g, 3, 0));
printf("PLayer 3 had %d student in 1\n", getStudents(g, 3, 1));
printf("PLayer 3 had %d student in 2\n", getStudents(g, 3, 2));
printf("PLayer 3 had %d student in 3\n", getStudents(g, 3, 3));
printf("PLayer 3 had %d student in 4\n", getStudents(g, 3, 4));
printf("PLayer 3 had %d student in 5\n", getStudents(g, 3, 5));
printf("Throwing the dice three times\n");
throwDice(g, 8);
throwDice(g, 8);
throwDice(g, 8);
printf("PLayer 3 had %d student in 0\n", getStudents(g, 3, 0));
printf("PLayer 3 had %d student in 1\n", getStudents(g, 3, 1));
printf("PLayer 3 had %d student in 2\n", getStudents(g, 3, 2));
printf("PLayer 3 had %d student in 3\n", getStudents(g, 3, 3));
printf("PLayer 3 had %d student in 4\n", getStudents(g, 3, 4));
printf("PLayer 3 had %d student in 5\n", getStudents(g, 3, 5));
assert(getStudents(g, 3, 1) == 3);
a.actionCode = RETRAIN_STUDENTS;
strncpy(a.destination, "RRL", PATH_LIMIT - 1);
a.disciplineFrom = 3, a.disciplineTo = 5;
makeAction(g, a);
printf("Make the Trade\n");
printf("PLayer 3 had %d student in 0\n", getStudents(g, 3, 0));
printf("PLayer 3 had %d student in 1\n", getStudents(g, 3, 1));
printf("PLayer 3 had %d student in 2\n", getStudents(g, 3, 2));
printf("PLayer 3 had %d student in 3\n", getStudents(g, 3, 3));
printf("PLayer 3 had %d student in 4\n", getStudents(g, 3, 4));
printf("PLayer 3 had %d student in 5\n", getStudents(g, 3, 5));
assert(getStudents(g, 3, 5) == 2);
printf("PLayer 3 had %d student in 1\n", getStudents(g, 3, 1));
assert(getStudents(g, 3, 1) == 3);
printf("External Test 002 end\n");
}
|
Ruby
|
UTF-8
| 425 | 3.96875 | 4 |
[] |
no_license
|
puts "How many pizzas would you like?"
pizza = gets.chomp!.to_i
while pizza == 0
puts "quit messing around here, give me a number!"
pizza = gets.chomp!.to_i
end
puts "How many toppings on each pizza would you like?"
toppings = gets.chomp!.to_i
while toppings == 0
puts "quit messing around here, give me a number!"
toppings = gets.chomp!.to_i
end
puts "You have ordered #{pizza} pizza with #{toppings} toppings."
|
Swift
|
UTF-8
| 3,215 | 2.75 | 3 |
[] |
no_license
|
//
// TableViewCell.swift
// Peretz
//
// Created by Асельдер on 24.08.2020.
// Copyright © 2020 Асельдер. All rights reserved.
//
import UIKit
import SDWebImage
//MARK: - Protocol delegate
protocol BasketDelegate {
func getPrice(dishItem: DishModel) -> Int
func minusButtonAction(_ sender: Any)
func plusButtonAction(_ sender: Any)
var allBasketPrice: Int { get set }
}
//MARK: - Class code
class TableViewCell: UITableViewCell {
//Outlet
@IBOutlet weak var dishNameLabel: UILabel!
@IBOutlet weak var dishDescriptionLabel: UILabel!
@IBOutlet weak var priceDishLabel: UILabel!
@IBOutlet weak var countDishLabel: UILabel!
@IBOutlet weak var minusButton: UIButton!
@IBOutlet weak var plusButton: UIButton!
@IBOutlet weak var dishImage: UIImageView!
private var currentItem: DishModel?
func setData(dishItem: DishModel) {
//Проверка
if DishUserDefaults.shared.checkCount(productId: dishItem.id) >= 1 {
countDishLabel.isHidden = false
minusButton.isHidden = false
countDishLabel.text = String(DishUserDefaults.shared.checkCount(productId: dishItem.id))
} else {
countDishLabel.isHidden = true
minusButton.isHidden = true
}
//собираем объекты
currentItem = dishItem
//спарсинговые объекты передаем в подготовленные на вью их места
if let image = dishItem.image {
dishImage.sd_setImage(with: URL(string: image), completed: nil)
}
dishNameLabel.text = dishItem.name.capitalized
dishDescriptionLabel.text = dishItem.description.capitalized
priceDishLabel.text = String(dishItem.price ) + " ₽"
}
//MARK: - Method
@IBAction func minusButtonAction(_ sender: Any) {
// Изменение basketPrice
DishUserDefaults.shared.basketPrice -= currentItem?.price ?? 0
if (Int(countDishLabel.text ?? "0")! >= 2) {
DishUserDefaults.shared.removeCount(productId: currentItem!.id)
countDishLabel.text = String(DishUserDefaults.shared.checkCount(productId: currentItem!.id))
} else if (Int(countDishLabel.text ?? "0")! <= 1) {
DishUserDefaults.shared.removeCount(productId: currentItem!.id)
minusButton.isHidden = true
countDishLabel.isHidden = true
}
// Синхронизируем изменения в баскет прайс
DishUserDefaults.shared.synchronizeBasket()
}
@IBAction func plusButtonAction(_ sender: Any) {
DishUserDefaults.shared.basketPrice += currentItem?.price ?? 0
DishUserDefaults.shared.plusCount(productId: currentItem!.id)
countDishLabel.text = String(DishUserDefaults.shared.checkCount(productId: currentItem!.id))
if Int(countDishLabel.text ?? "0")! >= 1 {
countDishLabel.isHidden = false
minusButton.isHidden = false
}
DishUserDefaults.shared.synchronizeBasket()
}
}
|
Java
|
UTF-8
| 1,932 | 2.796875 | 3 |
[
"Apache-2.0"
] |
permissive
|
package com.main.plugins.date.helpers;
import com.main.model.dto.MealDayDto;
import com.main.plugins.date.Day;
import com.main.plugins.date.Week;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
/**
* Created by sadra on 1/31/15.
*/
@Component()
public class MealWeek {
public List<MealDayDto> getMealDayDtos() {
Calendar now = Calendar.getInstance();
int weekNumber = now.get(Calendar.WEEK_OF_YEAR);
Week week = new Week (weekNumber);
List <MealDayDto> mealDayDtoList = new ArrayList<MealDayDto>();
SimpleDateFormat monthFormatter = new SimpleDateFormat("MMMM");
SimpleDateFormat dayFormatter = new SimpleDateFormat("EEEE");
SimpleDateFormat dayNumberFormatter = new SimpleDateFormat("dd");
List<Day> weekList = week.getWeekList();
for (Day day : weekList) {
String monthName = monthFormatter.format(day.getDate());
String dayName = dayFormatter.format(day.getDate());
String dayNumber = dayNumberFormatter.format(day.getDate());
MealDayDto mealDayDto = new MealDayDto();
mealDayDto.setMonth(monthName)
.setDay(dayName)
.setDate(day.getDate())
.setDayNumber(dayNumber)
.setSelected(false)
.setQuantity(0);
if (isAvailable(dayName))
mealDayDto.setAvailable(false);
else
mealDayDto.setAvailable(true);
mealDayDtoList.add(mealDayDto);
}
return mealDayDtoList;
}
private boolean isAvailable(String dayName) {
return dayName.equalsIgnoreCase("Sunday") ||
dayName.equalsIgnoreCase("Monday") ||
dayName.equalsIgnoreCase("Saturday");
}
}
|
C
|
UTF-8
| 606 | 2.640625 | 3 |
[] |
no_license
|
#include <stdlib.h>
#include "stm32f4xx.h"
#include "board.h"
#include "FreeRTOS.h"
#include "task.h"
TaskHandle_t xTaskLedHandle1 = NULL;
void vTask_Led_handler_1(void *params);
int main(void)
{
/* Hardware board init */
board_hardware_init();
/* Create task */
xTaskCreate(vTask_Led_handler_1, "Task-1", 500, NULL, 1, &xTaskLedHandle1);
/* Start scheduler */
vTaskStartScheduler();
while(1)
{
/* Never go here */
}
return 0;
}
void vTask_Led_handler_1(void *params)
{
while(1)
{
toggle_led();
vTaskDelay(pdMS_TO_TICKS(1000));
}
}
|
PHP
|
UTF-8
| 9,802 | 2.90625 | 3 |
[] |
no_license
|
<?php
function statsPrintTableSingle($stationID, $type){
include "dbConnect.php";
//query to get Stats
$query = "SELECT * FROM stats WHERE gasStationID = ? AND MONTH(timestamp) = ? AND DAY(timestamp) = ? AND YEAR(timestamp) = ? ORDER BY timestamp ASC;";
$query1 = "SELECT MIN($type) AS MINI FROM stats WHERE gasStationID = ? AND MONTH(timestamp) = ? AND DAY(timestamp) = ? AND YEAR(timestamp) = ?";
if ($stmt = $mysqli->prepare($query)) { //prepare statement to get stats
$stmt->bind_param("dddd", $stationID, $month, $day, $year); //bind parameters
$day = date("d", strtotime("last Monday")); //day from last monday
$month = date("m", strtotime("last Monday")); //month from last monday
$year = date("Y", strtotime("last Monday")); //year from last monday
$stmt->execute(); //execute statement
$result = $stmt->get_result(); //save result
while($data = $result->fetch_array()){
if(empty($data[$type]) || $data[$type] == "null"){return;}
}
?>
<h3>Preis pro Liter <?=ucfirst($type)?></h3>
<table id="stats" style="undefined;table-layout: fixed; width: 100%">
<colgroup>
<col style="width: 15%">
<?php for($i = 0; $i < 24; $i++){ ?>
<col style="width: 10%">
<?php } ?>
</colgroup>
<tr>
<th id="tg-yw4l">\</th> <!-- hours -->
<?php for($i = 0; $i < 24; $i++){ ?>
<th id="tg-yw4l"><?= $i ?></th>
<?php } ?>
</tr>
<?php
if ($stmt = $mysqli->prepare($query)) { //prepare statement to get stats
if ($stmt1 = $mysqli->prepare($query1)) { //prepare statement to get stats
for($i = 0; $i < 7; $i++){
switch ($i) {
case 0: $name = "Monday";
$nameGer = "Montag";
break;
case 1: $name = "Tuesday";
$nameGer = "Dienstag";
break;
case 2: $name = "Wednesday";
$nameGer = "Mittwoch";
break;
case 3: $name = "Thursday";
$nameGer = "Donnerstag";
break;
case 4: $name = "Friday";
$nameGer = "Freitag";
break;
case 5: $name = "Saturday";
$nameGer = "Samstag";
break;
case 6: $name = "Sunday";
$nameGer = "Sonntag";
break;
}
$stmt->bind_param("dsss", $stationID, $month, $day, $year); //bind parameters
$day = date("d", strtotime("last ${name}")); //day from last monday
$month = date("m", strtotime("last ${name}")); //month from last monday
$year = date("Y", strtotime("last ${name}")); //year from last monday
$stmt->execute(); //execute statement
$result = $stmt->get_result(); //save result
$stmt1->bind_param("dddd", $stationID, $month, $day, $year); //bind parameters
$stmt1->execute(); //execute statement
$result1 = $stmt1->get_result(); //save result
while($data = $result1->fetch_array()){
$lowest = $data["MINI"];
}
?>
<tr>
<th><?= $nameGer ?></th>
<?php while($data = $result->fetch_array()){ ?>
<?php if($data[$type] == $lowest){ ?>
<td id="low"><?= $data[$type]; ?></td>
<?php }else{ ?>
<td id="tg-yw4l"><?= $data[$type]; ?></td>
<?php }}?>
</tr>
<?php }}} echo "</table>"; }} ?>
<?php
function statsPrintTableAll($type){
include "dbConnect.php";
//query to get Stats
$query = "SELECT * FROM avgPriceDaily WHERE MONTH(timestamp) = ? AND DAY(timestamp) = ? AND YEAR(timestamp) = ? AND type = ? ORDER BY timestamp ASC";
$query1 = "SELECT MIN(avgPrice) AS MINI FROM avgPriceDaily WHERE type = ? AND MONTH(timestamp) = ? AND DAY(timestamp) = ? AND YEAR(timestamp) = ?";
if ($stmt = $mysqli->prepare($query)) { //prepare statement to get stats
$stmt->bind_param("ssss", $month, $day, $year, $type); //bind parameters
$day = date("d", strtotime("last Monday")); //day from last monday
$month = date("m", strtotime("last Monday")); //month from last monday
$year = date("Y", strtotime("last Monday")); //year from last monday
$stmt->execute(); //execute statement
$result = $stmt->get_result(); //save result
while($data = $result->fetch_array()){
if(empty($data['avgPrice']) || $data['avgPrice'] == "null"){return;}} ?>
<h3>Preis pro Liter <?=ucfirst($type)?><h3>
<table id="stats" style="undefined;table-layout: fixed; width: 100%">
<colgroup>
<col style="width: 15%">
<?php for($i = 0; $i < 24; $i++){ ?>
<col style="width: 10%">
<?php } ?>
</colgroup>
<tr>
<th id="tg-yw4l">\</th> <!-- hours -->
<?php for($i = 0; $i < 24; $i++){ ?>
<th id="tg-yw4l"><?= $i ?></th>
<?php } ?>
</tr>
<?php
if ($stmt = $mysqli->prepare($query)) { //prepare statement to get stats
if ($stmt1 = $mysqli->prepare($query1)) { //prepare statement to get stats
for($i = 0; $i < 7; $i++){
switch ($i) {
case 0: $name = "Monday";
$nameGer = "Montag";
break;
case 1: $name = "Tuesday";
$nameGer = "Dienstag";
break;
case 2: $name = "Wednesday";
$nameGer = "Mittwoch";
break;
case 3: $name = "Thursday";
$nameGer = "Donnerstag";
break;
case 4: $name = "Friday";
$nameGer = "Freitag";
break;
case 5: $name = "Saturday";
$nameGer = "Samstag";
break;
case 6: $name = "Sunday";
$nameGer = "Sonntag";
break;
}
$stmt->bind_param("ddds", $month, $day, $year, $type); //bind parameters
$day = date("d", strtotime("last ${name}")); //day from last monday
$month = date("m", strtotime("last ${name}")); //month from last monday
$year = date("Y", strtotime("last ${name}")); //year from last monday
$stmt->execute(); //execute statement
$result = $stmt->get_result(); //save result
$stmt1->bind_param("sddd", $type, $month, $day, $year); //bind parameters
$stmt1->execute(); //execute statement
$result1 = $stmt1->get_result(); //save result
while($data = $result1->fetch_array()){
$lowest = $data["MINI"];
}
?>
<tr>
<th><?= $nameGer ?></th>
<?php while($data = $result->fetch_array()){ ?>
<?php if($data['avgPrice'] <= $lowest){ ?>
<td id="low"><?= $data['avgPrice']; ?></td>
<?php }else{ ?>
<td id="tg-yw4l"><?= $data['avgPrice']; ?></td>
<?php }}}?>
</tr>
</table>
<?php }}}$mysqli->close();} ?>
<?php
function generateBarChart(&$values, $height=400, $type, $css_prefix='')
{
$max = -1;
$low = 10000;
$out = "<div id='griddiv-table' class='white'><h3>Preis pro Liter " . ucfirst($type) . "<h3><table class='chart'>";
foreach($values as $key=>$value) {
if (abs($value) > $max) {
$max = abs($value);
}
}
foreach($values as $key=>$value) {
if (abs($value) < $low) {
$low = abs($value);
}
}
if ($max != 0) {
$kf = $height / $max;
} else {
$kf = 0;
}
$out .= "<tr class='{$css_prefix}barvrow'>";
foreach($values as $key=>$value) {
$bar_height = abs(round((substr($value, 2) / 100)*$kf));
if($value == $max){
$out .= "<td style='border-bottom-width: {$bar_height}px; border-bottom-color: red'>{$value}</td>";
}elseif($value == $low){
$out .= "<td style='border-bottom-width: {$bar_height}px; border-bottom-color: green'>{$value}</td>";
}
else{
$out .= "<td style='border-bottom-width: {$bar_height}px; border-bottom-color: orange'>{$value}</td>";
}
}
$out .= '</tr>';
$out .= "<tr class='{$css_prefix}bartrow'>";
foreach($values as $key=>$value) {
$out .= "<td>{$key}</td>";
}
$out .= "</tr>";
$out .= "</table></div>";
return $out;
}
function getStatsSingle($type, $day, $month, $year, $stationID)
{
include "dbConnect.php";
$check = true;
$query = "SELECT * FROM `stats` WHERE Day(timestamp) = ? AND Month(timestamp) = ? AND YEAR(timestamp) = ? AND gasstationID = ?";
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param("dddd", $day, $month, $year, $stationID);
$stmt->execute();
$first = 0;
$result = $stmt->get_result();
while($data = $result->fetch_array()){
$date = date("H", strtotime($data['timestamp']));
$value = $data[$type];
if(empty($value)){
$check = false;
}
if($first != 1 && $check){
$stats = array($date=>$value);
}
elseif($check){
$stats_save = $stats;
$stats = array($date=>$value);
$stats = $stats_save + $stats;
}
elseif(!$check){
$stats = false;
}
$first = 1;
}
!isset($stats) ? $error = true : $error = false;
!isset($stats) ? $stats = "empty" : $stats = $stats;
return array($error, $stats);
}
$mysqli->close();
}
function getStatsAll($type, $day, $month, $year)
{
include "dbConnect.php";
$check = true;
$query = "SELECT timestamp, ROUND(avgPrice, 3) AS avgPrice FROM `avgPriceDaily` WHERE Day(timestamp) = ? AND Month(timestamp) = ? AND YEAR(timestamp) = ? AND type = ?";
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param("ddds", $day, $month, $year, $type);
$stmt->execute();
$first = 0;
$result = $stmt->get_result();
while($data = $result->fetch_array()){
$date = date("H", strtotime($data['timestamp']));
$value = $data['avgPrice'];
if(empty($value)){
$check = false;
}
if($first != 1 && $check){
$value = number_format($value, 3, '.', '');
$stats = array($date=>$value);
}
elseif($check){
$stats_save = $stats;
$value = number_format($value, 3, '.', '');
$stats = array($date=>$value);
$stats = $stats_save + $stats;
}
elseif(!$check){
$stats = false;
}
$first = 1;
}
!isset($stats) ? $error = true : $error = false;
!isset($stats) ? $stats = "empty" : $stats = $stats;
return array($error, $stats);
}
$mysqli->close();
}
|
Java
|
UTF-8
| 4,758 | 2.5 | 2 |
[] |
no_license
|
package rest;
import retrofit.RestAdapter;
import retrofit.client.Response;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
/**
* Created by vasiliy on 12.12.15.
*/
//https://en.wikipedia.org/w/api.php?action=query&prop=pageimages&titles=Far_Eastern_Party&pithumbsize=500&format=xml -возвращет ссылку на картинку соответсвуещего размера к статье
//размер можно задать
//https://en.wikipedia.org/w/api.php?action=query&prop=images&titles=Far_Eastern_Party&format=xml сылки на все картинки картинки
//https://en.wikipedia.org/w/api.php?action=query&prop=extlinks&titles=Far_Eastern_Party возвращает все внешние ссылки
//https://en.wikipedia.org/w/api.php?action=query&titles=Far_Eastern_Party&prop=revisions&rvprop=content&format=json
//https://en.wikipedia.org/w/api.php?action=query&titles=Far_Eastern_Party&prop=revisions&rvprop=content&format=xml
//https://ru.wikipedia.org/w/api.php?action=opensearch&search=%EC%E0%F1%F2%E5%F0%20%E8%20%EC%E0%F0%E3%E0%F0%E8%F2%E0&prop=info&format=xml&inprop=url
public class MediaWikiCommunicatorImpl implements MediaWikiCommunicator {
private MediaWikiApi service;
private RestAdapter retrofit;
public MediaWikiCommunicatorImpl(){
retrofit = new RestAdapter.Builder().setEndpoint("https://ru.wikipedia.org/w/api.php").build();
//retrofit = new RestAdapter.Builder().setEndpoint("https://upload.wikimedia.org").build();
service = retrofit.create(MediaWikiApi.class);
}
//метод возвращает xml в котором есть тело вики-текста сайта
@Override
public String getArticleByTitle(String title) {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("action", "query");
parameters.put("titles", title);
parameters.put("prop", "revisions");
parameters.put("rvprop", "content");
parameters.put("format", "json");
Response tmp = service.getArticleByTitle(parameters);
String result = stringFromResponse(tmp);
return result;
}
//https://en.wikipedia.org/w/api.php?action=query&list=search&srwhat=text&srsearch=zorge&format=jsonfm&srlimit=50
// метод возвращает заголовки страниц с кратким оисанием удволетворяющих поисковому запросу, 10 результатов,
// также там можно найти заголовки по которым можно получить страницу используя метод getArticleByTitle
@Override
public String getListOfArticle(String searchWords, Integer limit) {
Map<String, String> parameters = new HashMap<String, String>();
if ((limit <= 0) || (limit >= 51))
limit = 10;
parameters.put("action", "query");
parameters.put("list", "search");
parameters.put("srwhat", "text");
parameters.put("format", "json");
parameters.put("srsearch", searchWords);
parameters.put("srlimit", limit.toString());
Response tmp = service.getListOfArticle(parameters);
String result = stringFromResponse(tmp);
return result;
}
//https://en.wikipedia.org/w/api.php?action=query&prop=pageimages&titles=Far_Eastern_Party&pithumbsize=500&format=xml
@Override
public String getRawLinkImageTitle(String title, Integer size) throws IOException {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("action", "query");
parameters.put("prop","pageimages");
parameters.put("titles", title);
parameters.put("pithumbsize", size.toString());
parameters.put("format", "json");
Response tmp = service.getRawLinkImageTitle(parameters);
String result = stringFromResponse(tmp);
return result;
}
protected String stringFromResponse(Response response){
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(
response.getBody().in()));
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
String result = sb.toString();
return result;
}
}
|
C#
|
UTF-8
| 3,674 | 2.546875 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DAL;
using OnlineEventBooking.ViewModel;
using System.IO;
using System.Data.Entity;
namespace OnlineEventBooking.Controllers
{
public class VenuedataController : Controller
{
// GET: Venuedata
[HttpGet]
public ActionResult SaveVenue()
{
return View("Venue");
}
[HttpPost]
public ActionResult SaveVenue(VenueViewModel vvm)
{
if (ModelState.IsValid) //This is check all validation of Data Annotation
{
if (vvm.imageFile !=null)
{
vvm.imageFile.SaveAs(Server.MapPath("~/UploadImage/" + vvm.imageFile.FileName));
}
Venue v = new Venue();
v.VenueCost = vvm.VenueCost;
v.VenueFilename = vvm.imageFile.FileName.ToString();
v.VenueName = vvm.VenueName;
using (EventDBEntities db = new EventDBEntities())
{
db.Venues.Add(v);
db.SaveChanges();
}
}
return RedirectToAction("List");
}
public ActionResult List()
{
using (EventDBEntities db= new EventDBEntities())
{
var vanues = (from x in db.Venues select x).ToList();
return View(vanues);
}
}
public ActionResult Edit(int Id)
{
using (EventDBEntities db = new EventDBEntities())
{
var v = (from x in db.Venues where x.VenueID == Id select new { x.VenueCost, x.VenueFilename, x.VenueID, x.VenueName,x.VenueFilePath }).FirstOrDefault();
VenueViewModel vvm = new VenueViewModel();
vvm.VenueCost = v.VenueCost;
vvm.VenueFilename = v.VenueFilename;
vvm.VenueName = v.VenueName;
vvm.VenueFilePath = "~/UploadImage/" + v.VenueFilePath;
vvm.VenueID = v.VenueID;
return View("Edit", vvm);
}
}
public ActionResult UpdateData(VenueViewModel vvm)
{
using (EventDBEntities db= new EventDBEntities())
{
if (vvm.imageFile != null)
{
vvm.imageFile.SaveAs(Server.MapPath("~/UploadImage/" + vvm.imageFile.FileName));
}
Venue v = new Venue();
v.VenueCost = vvm.VenueCost;
v.VenueID = vvm.VenueID ;
v.VenueName = vvm.VenueName;
if (vvm.imageFile!=null)
{
v.VenueFilePath = vvm.imageFile.FileName.ToString();
v.VenueFilename = vvm.VenueFilename;
db.Entry(v).State = EntityState.Modified;
}
else
{
db.Venues.Attach(v); // No Need to Add during Update ..this is only used when we want update specific propery
db.Entry(v).Property(x => x.VenueCost).IsModified = true; //this is only used when we want update specific propery
db.Entry(v).Property(x => x.VenueName).IsModified = true;
}
//db.Venues.Attach(v);// No Need to Add during Update
db.SaveChanges();
return RedirectToAction("List");
}
}
}
}
|
Java
|
UTF-8
| 4,528 | 2.203125 | 2 |
[
"CC0-1.0"
] |
permissive
|
package controllers;
import akka.http.scaladsl.Http$;
import akka.stream.impl.QueueSource;
import com.fasterxml.jackson.databind.JsonNode;
import context.NormalExecutionContext;
import play.libs.Json;
import play.libs.concurrent.HttpExecution;
import play.mvc.Http;
import play.mvc.Result;
import services.QandAService;
import skeletons.request.AnswerRequest;
import skeletons.request.QuestionRequest;
import skeletons.response.ExceptionResponse;
import skeletons.response.SuccessResponse;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.Executor;
import static play.mvc.Results.ok;
@Singleton
public class QandAController {
private QandAService qandAService;
private NormalExecutionContext normalExecutionContext;
@Inject
public QandAController(QandAService qandAService,
NormalExecutionContext normalExecutionContext) {
this.qandAService = qandAService;
this.normalExecutionContext = normalExecutionContext;
}
/**
* EndPoint to insert an new Question into the system
* @param httpRequest
* @return
*/
public CompletionStage<Result> insertQuestion(Http.Request httpRequest) {
CompletionStage<Result> result;
Executor executor = HttpExecution.fromThread((Executor) normalExecutionContext);
result = CompletableFuture.supplyAsync(()->{
JsonNode response;
JsonNode jsonNode = httpRequest.body().asJson();
QuestionRequest questionRequest = QuestionRequest.build(jsonNode);
if(QuestionRequest.validate(questionRequest)) {
try {
response = Json.toJson(new SuccessResponse(qandAService.addQuestion(questionRequest)));
} catch (Exception ex) {
response = Json.toJson(new ExceptionResponse(500,"Processing Eroor",ex.getLocalizedMessage()));
}
}
else {
response = Json.toJson(new ExceptionResponse(500,"Invalid Request",QuestionRequest.validationError));
}
return ok(response);
},executor);
return result;
}
/**
* End Point to Insert a new Answer to the Question into the system
* @param httpRequest
* @return
*/
public CompletionStage<Result> answerQuestion(Http.Request httpRequest) {
CompletionStage<Result> result;
Executor executor = HttpExecution.fromThread((Executor) normalExecutionContext);
result = CompletableFuture.supplyAsync(()-> {
JsonNode response;
JsonNode jsonNode = httpRequest.body().asJson();
AnswerRequest answerRequest = AnswerRequest.build(jsonNode);
if(AnswerRequest.validate(answerRequest)){
try {
response = Json.toJson(new SuccessResponse(qandAService.addAnswer(answerRequest)));
} catch (Exception ex) {
response = Json.toJson(new ExceptionResponse(500,"Processing Error",ex.getLocalizedMessage()));
}
}else {
response = Json.toJson(new ExceptionResponse(500,"Invalid Request",AnswerRequest.validationError));
}
return ok(Json.toJson(new SuccessResponse(true)));
},executor);
return result;
}
//:TODO
//Implement "From"
public CompletionStage<Result> getRecentlyAddedQuestions() {
CompletionStage<Result> result;
Executor executor = HttpExecution.fromThread((Executor) normalExecutionContext);
result = CompletableFuture.supplyAsync(()->{
try {
return ok(Json.toJson((new SuccessResponse(qandAService.getRecentQuestion()))));
}
catch (Exception ex) {
return ok(Json.toJson(new ExceptionResponse(500,"Processing Error",ex.getLocalizedMessage())));
}
},executor);
return result;
}
//:TODO
//Implement "From" and "to"
public CompletionStage<Result> getRecentQandA() {
CompletionStage<Result> result;
Executor executor = HttpExecution.fromThread((Executor)normalExecutionContext);
result = CompletableFuture.supplyAsync(()-> {
try {
return ok(Json.toJson(new SuccessResponse(qandAService.getRecentQandA())));
} catch (Exception ex) {
return ok(Json.toJson(new ExceptionResponse(500,"Processing Error",ex.getLocalizedMessage())));
}
},executor);
return result;
}
}
|
Java
|
UTF-8
| 26,035 | 3.34375 | 3 |
[] |
no_license
|
package algorithms.maze3D;
import algorithms.search.AState;
import algorithms.search.ISearchable;
import java.util.ArrayList;
public class SearchableMaze3D implements ISearchable {
private Maze3D maze;
private Maze3DState startState;
private Maze3DState goalState;
private boolean [][][] visit; //visit is the 3D array of visited cells.
public SearchableMaze3D (Maze3D maze) throws Exception {
if (maze==null)
throw new Exception("the maze is null");
this.maze=maze;
startState=new Maze3DState(maze.getStartPosition(),null);
goalState=new Maze3DState(maze.getGoalPosition(),null);
visit=new boolean[maze.getRow()][maze.getCol()][maze.getDepth()];
for (int i = 0; i < maze.getDepth(); i++) {
for (int j = 0; j < maze.getRow(); j++) {
for (int k = 0; k < maze.getCol(); k++) {
visit[j][k][i]=false;
}
}
}
}
/**
* @return the start state where the maze begin
*/
@Override
public AState getStartState() {
return startState;
}
/**
* @return the goal state where the maze ends
*/
@Override
public AState getGoalState() {
return goalState;
}
/**
* @param stateA is a state from the maze
* @return arrayList that contains the all possible neighbors states that can move from stateA to them
*/
@Override
public ArrayList<AState> getAllSuccessors(AState stateA) throws Exception {
if (stateA == null)
throw new Exception("The state is null");
Maze3DState state = (Maze3DState) stateA;
int[][][] m = this.maze.getMap();
ArrayList<AState> possibleStates = new ArrayList<>();
if (state.getX() == 0 && state.getY() == 0 && state.getZ() == 0) {
if (m[state.getX() + 1][state.getY()][state.getZ()] == 0 && visit[state.getX() + 1][state.getY()][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX() + 1, state.getY()), state));
visit[state.getX() + 1][state.getY()][state.getZ()] = true;
}
if (m[state.getX()][state.getY() + 1][state.getZ()] == 0 && visit[state.getX()][state.getY() + 1][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX(), state.getY() + 1), state));
visit[state.getX()][state.getY() + 1][state.getZ()] = true;
}
if (m[state.getX()][state.getY()][state.getZ() + 1] == 0 && visit[state.getX()][state.getY()][state.getZ() + 1] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ() + 1,state.getX(), state.getY() ), state));
visit[state.getX()][state.getY()][state.getZ() + 1] = true;
}
}
else if (state.getX() == maze.getRow() - 1 && state.getY() == maze.getCol() - 1 && state.getZ() == 0) {
if (m[state.getX()][state.getY()][state.getZ() + 1] == 0 && visit[state.getX()][state.getY()][state.getZ() + 1] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ() + 1,state.getX(), state.getY() ), state));
visit[state.getX()][state.getY()][state.getZ() + 1] = true;
}
if (m[state.getX() - 1][state.getY()][state.getZ()] == 0 && visit[state.getX() - 1][state.getY()][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX() - 1, state.getY()), state));
visit[state.getX() - 1][state.getY()][state.getZ()] = true;
}
if (m[state.getX()][state.getY() - 1][state.getZ()] == 0 && visit[state.getX()][state.getY() - 1][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX(), state.getY() - 1), state));
visit[state.getX()][state.getY() - 1][state.getZ()] = true;
}
}
else if (state.getX() == 0 && state.getY() == maze.getCol() - 1 && state.getZ() == 0) {
if (m[state.getX()][state.getY()][state.getZ() + 1] == 0 && visit[state.getX()][state.getY()][state.getZ() + 1] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ() + 1,state.getX(), state.getY() ), state));
visit[state.getX()][state.getY()][state.getZ() + 1] = true;
}
if (m[state.getX() + 1][state.getY()][state.getZ()] == 0 && visit[state.getX() + 1][state.getY()][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX() + 1, state.getY()), state));
visit[state.getX() + 1][state.getY()][state.getZ()] = true;
}
if (m[state.getX()][state.getY() - 1][state.getZ()] == 0 && visit[state.getX()][state.getY() - 1][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX(), state.getY() - 1), state));
visit[state.getX()][state.getY() - 1][state.getZ()] = true;
}
}
else if (state.getX() == maze.getRow() - 1 && state.getY() == 0 && state.getZ() == 0) {
if (m[state.getX()][state.getY()][state.getZ() + 1] == 0 && visit[state.getX()][state.getY()][state.getZ() + 1] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ() + 1,state.getX(), state.getY()), state));
visit[state.getX()][state.getY()][state.getZ() + 1] = true;
}
if (m[state.getX() - 1][state.getY()][state.getZ()] == 0 && visit[state.getX() - 1][state.getY()][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX() - 1, state.getY()), state));
visit[state.getX() - 1][state.getY()][state.getZ()] = true;
}
if (m[state.getX()][state.getY() + 1][state.getZ()] == 0 && visit[state.getX()][state.getY() + 1][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX(), state.getY() + 1), state));
visit[state.getX()][state.getY() + 1][state.getZ()] = true;
}
}
else if (state.getX() == 0 && state.getY() == 0 && state.getZ() == maze.getDepth() - 1) {
if (m[state.getX() + 1][state.getY()][state.getZ()] == 0 && visit[state.getX() + 1][state.getY()][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX() + 1, state.getY()), state));
visit[state.getX() + 1][state.getY()][state.getZ()] = true;
}
if (m[state.getX()][state.getY() + 1][state.getZ()] == 0 && visit[state.getX()][state.getY() + 1][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX(), state.getY() + 1), state));
visit[state.getX()][state.getY() + 1][state.getZ()] = true;
}
if (m[state.getX()][state.getY()][state.getZ() - 1] == 0 && visit[state.getX()][state.getY()][state.getZ() - 1] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ() - 1,state.getX(), state.getY()), state));
visit[state.getX()][state.getY()][state.getZ() - 1] = true;
}
}
else if (state.getX() == maze.getRow() - 1 && state.getY() == maze.getCol() - 1 && state.getZ() == maze.getDepth() - 1) {
if (m[state.getX()][state.getY()][state.getZ() - 1] == 0 && visit[state.getX()][state.getY()][state.getZ() - 1] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ() - 1,state.getX(), state.getY()), state));
visit[state.getX()][state.getY()][state.getZ() - 1] = true;
}
if (m[state.getX() - 1][state.getY()][state.getZ()] == 0 && visit[state.getX() - 1][state.getY()][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX() - 1, state.getY()), state));
visit[state.getX() - 1][state.getY()][state.getZ()] = true;
}
if (m[state.getX()][state.getY() - 1][state.getZ()] == 0 && visit[state.getX()][state.getY() - 1][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX(), state.getY() - 1), state));
visit[state.getX()][state.getY() - 1][state.getZ()] = true;
}
}
else if (state.getX() == 0 && state.getY() == maze.getCol() - 1 && state.getZ() == maze.getDepth() - 1) {
if (m[state.getX()][state.getY()][state.getZ() - 1] == 0 && visit[state.getX()][state.getY()][state.getZ() - 1] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ() - 1,state.getX(), state.getY()), state));
visit[state.getX()][state.getY()][state.getZ() - 1] = true;
}
if (m[state.getX() + 1][state.getY()][state.getZ()] == 0 && visit[state.getX() + 1][state.getY()][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX() + 1, state.getY()), state));
visit[state.getX() + 1][state.getY()][state.getZ()] = true;
}
if (m[state.getX()][state.getY() - 1][state.getZ()] == 0 && visit[state.getX()][state.getY() - 1][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX(), state.getY() - 1), state));
visit[state.getX()][state.getY() - 1][state.getZ()] = true;
}
}
else if (state.getX() == maze.getRow() - 1 && state.getY() == 0 && state.getZ() == maze.getDepth() - 1) {
if (m[state.getX()][state.getY()][state.getZ() - 1] == 0 && visit[state.getX()][state.getY()][state.getZ() - 1] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ() - 1,state.getX(), state.getY()), state));
visit[state.getX()][state.getY()][state.getZ() - 1] = true;
}
if (m[state.getX() - 1][state.getY()][state.getZ()] == 0 && visit[state.getX() - 1][state.getY()][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX() - 1, state.getY()), state));
visit[state.getX() - 1][state.getY()][state.getZ()] = true;
}
if (m[state.getX()][state.getY() + 1][state.getZ()] == 0 && visit[state.getX()][state.getY() + 1][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX(), state.getY() + 1), state));
visit[state.getX()][state.getY() + 1][state.getZ()] = true;
}
}
else if (state.getX() == 0) {
if (state.getZ() > 0 && m[state.getX()][state.getY()][state.getZ() - 1] == 0 && visit[state.getX()][state.getY()][state.getZ() - 1] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ() - 1,state.getX(), state.getY()), state));
visit[state.getX()][state.getY()][state.getZ() - 1] = true;
}
if (state.getZ() < maze.getDepth() - 1 && m[state.getX()][state.getY()][state.getZ() + 1] == 0 && visit[state.getX()][state.getY()][state.getZ() + 1] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ() + 1,state.getX(), state.getY()), state));
visit[state.getX()][state.getY()][state.getZ() + 1] = true;
}
if (m[state.getX() + 1][state.getY()][state.getZ()] == 0 && visit[state.getX() + 1][state.getY()][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX() + 1, state.getY()), state));
visit[state.getX() + 1][state.getY()][state.getZ()] = true;
}
if (state.getY()>0 &&m[state.getX()][state.getY() - 1][state.getZ()] == 0 && visit[state.getX()][state.getY() - 1][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX(), state.getY() - 1), state));
visit[state.getX()][state.getY() - 1][state.getZ()] = true;
}
if (state.getY()<maze.getCol()-1 &&m[state.getX()][state.getY() + 1][state.getZ()] == 0 && visit[state.getX()][state.getY() + 1][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX(), state.getY() + 1), state));
visit[state.getX()][state.getY() + 1][state.getZ()] = true;
}
}
else if (state.getX() == maze.getRow() - 1) {
if (state.getZ() > 0 && m[state.getX()][state.getY()][state.getZ() - 1] == 0 && visit[state.getX()][state.getY()][state.getZ() - 1] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ() - 1,state.getX(), state.getY()), state));
visit[state.getX()][state.getY()][state.getZ() - 1] = true;
}
if (state.getZ() < maze.getDepth() - 1 && m[state.getX()][state.getY()][state.getZ() + 1] == 0 && visit[state.getX()][state.getY()][state.getZ() + 1] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ() + 1,state.getX(), state.getY()), state));
visit[state.getX()][state.getY()][state.getZ() + 1] = true;
}
if (m[state.getX() - 1][state.getY()][state.getZ()] == 0 && visit[state.getX() - 1][state.getY()][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX() - 1, state.getY()), state));
visit[state.getX() - 1][state.getY()][state.getZ()] = true;
}
if (state.getY()>0 &&m[state.getX()][state.getY() - 1][state.getZ()] == 0 && visit[state.getX()][state.getY() - 1][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX(), state.getY() - 1), state));
visit[state.getX()][state.getY() - 1][state.getZ()] = true;
}
if (state.getY()<maze.getCol()-1&&m[state.getX()][state.getY() + 1][state.getZ()] == 0 && visit[state.getX()][state.getY() + 1][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX(), state.getY() + 1), state));
visit[state.getX()][state.getY() + 1][state.getZ()] = true;
}
}
else if (state.getY() == 0) {
if (state.getZ() > 0 && m[state.getX()][state.getY()][state.getZ() - 1] == 0 && visit[state.getX()][state.getY()][state.getZ() - 1] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ() - 1,state.getX(), state.getY()), state));
visit[state.getX()][state.getY()][state.getZ() - 1] = true;
}
if (state.getZ() < maze.getDepth() - 1 && m[state.getX()][state.getY()][state.getZ() + 1] == 0 && visit[state.getX()][state.getY()][state.getZ() + 1] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ() + 1,state.getX(), state.getY()), state));
visit[state.getX()][state.getY()][state.getZ() + 1] = true;
}
if (state.getX()>0&&m[state.getX() - 1][state.getY()][state.getZ()] == 0 && visit[state.getX() - 1][state.getY()][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX() - 1, state.getY()), state));
visit[state.getX() - 1][state.getY()][state.getZ()] = true;
}
if (state.getX()<maze.getRow()-1&&m[state.getX() + 1][state.getY()][state.getZ()] == 0 && visit[state.getX() + 1][state.getY()][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX() + 1, state.getY()), state));
visit[state.getX() + 1][state.getY()][state.getZ()] = true;
}
if (m[state.getX()][state.getY() + 1][state.getZ()] == 0 && visit[state.getX()][state.getY() + 1][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX(), state.getY() + 1), state));
visit[state.getX()][state.getY() + 1][state.getZ()] = true;
}
}
else if (state.getY() == maze.getCol() - 1) {
if (state.getZ() > 0 && m[state.getX()][state.getY()][state.getZ() - 1] == 0 && visit[state.getX()][state.getY()][state.getZ() - 1] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ() - 1,state.getX(), state.getY()), state));
visit[state.getX()][state.getY()][state.getZ() - 1] = true;
}
if (state.getZ() < maze.getDepth() - 1 && m[state.getX()][state.getY()][state.getZ() + 1] == 0 && visit[state.getX()][state.getY()][state.getZ() + 1] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ() + 1,state.getX(), state.getY()), state));
visit[state.getX()][state.getY()][state.getZ() + 1] = true;
}
if (state.getX()>0&&m[state.getX() - 1][state.getY()][state.getZ()] == 0 && visit[state.getX() - 1][state.getY()][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX() - 1, state.getY()), state));
visit[state.getX() - 1][state.getY()][state.getZ()] = true;
}
if (m[state.getX()][state.getY() - 1][state.getZ()] == 0 && visit[state.getX()][state.getY() - 1][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX(), state.getY() - 1), state));
visit[state.getX()][state.getY() - 1][state.getZ()] = true;
}
if (state.getX()<maze.getRow()-1&&m[state.getX() + 1][state.getY()][state.getZ()] == 0 && visit[state.getX() + 1][state.getY()][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX() + 1, state.getY()), state));
visit[state.getX() + 1][state.getY()][state.getZ()] = true;
}
}
else if (state.getZ() == 0) {
if (m[state.getX()][state.getY()][state.getZ() + 1] == 0 && visit[state.getX()][state.getY()][state.getZ() + 1] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ() + 1,state.getX(), state.getY()), state));
visit[state.getX()][state.getY()][state.getZ() + 1] = true;
}
if (state.getY()<maze.getCol()-1&&m[state.getX()][state.getY() + 1][state.getZ()] == 0 && visit[state.getX()][state.getY() + 1][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX(), state.getY() + 1), state));
visit[state.getX()][state.getY() + 1][state.getZ()] = true;
}
if (state.getX()>0&&m[state.getX() - 1][state.getY()][state.getZ()] == 0 && visit[state.getX() - 1][state.getY()][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX() - 1, state.getY()), state));
visit[state.getX() - 1][state.getY()][state.getZ()] = true;
}
if (state.getY()>0&&m[state.getX()][state.getY() - 1][state.getZ()] == 0 && visit[state.getX()][state.getY() - 1][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX(), state.getY() - 1), state));
visit[state.getX()][state.getY() - 1][state.getZ()] = true;
}
if (state.getX()<maze.getRow()-1&&m[state.getX() + 1][state.getY()][state.getZ()] == 0 && visit[state.getX() + 1][state.getY()][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX() + 1, state.getY()), state));
visit[state.getX() + 1][state.getY()][state.getZ()] = true;
}
}
else if (state.getZ() == maze.getDepth() - 1) {
if (m[state.getX()][state.getY()][state.getZ() - 1] == 0 && visit[state.getX()][state.getY()][state.getZ() - 1] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ() - 1,state.getX(), state.getY()), state));
visit[state.getX()][state.getY()][state.getZ() - 1] = true;
}
if (state.getY()<maze.getCol()-1&&m[state.getX()][state.getY() + 1][state.getZ()] == 0 && visit[state.getX()][state.getY() + 1][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX(), state.getY() + 1), state));
visit[state.getX()][state.getY() + 1][state.getZ()] = true;
}
if (state.getX()>0&&m[state.getX() - 1][state.getY()][state.getZ()] == 0 && visit[state.getX() - 1][state.getY()][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX() - 1, state.getY()), state));
visit[state.getX() - 1][state.getY()][state.getZ()] = true;
}
if (state.getY()>0&&m[state.getX()][state.getY() - 1][state.getZ()] == 0 && visit[state.getX()][state.getY() - 1][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX(), state.getY() - 1), state));
visit[state.getX()][state.getY() - 1][state.getZ()] = true;
}
if (state.getX()<maze.getRow()-1&&m[state.getX() + 1][state.getY()][state.getZ()] == 0 && visit[state.getX() + 1][state.getY()][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX() + 1, state.getY() ), state));
visit[state.getX() + 1][state.getY()][state.getZ()] = true;
}
}
else {
if (m[state.getX()][state.getY()][state.getZ() - 1] == 0 && visit[state.getX()][state.getY()][state.getZ() - 1] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ() - 1,state.getX(), state.getY()), state));
visit[state.getX()][state.getY()][state.getZ() - 1] = true;
}
if (m[state.getX()][state.getY()][state.getZ() + 1] == 0 && visit[state.getX()][state.getY()][state.getZ() + 1] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ() + 1,state.getX(), state.getY()), state));
visit[state.getX()][state.getY()][state.getZ() + 1] = true;
}
if (m[state.getX()][state.getY() + 1][state.getZ()] == 0 && visit[state.getX()][state.getY() + 1][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX(), state.getY() + 1), state));
visit[state.getX()][state.getY() + 1][state.getZ()] = true;
}
if (m[state.getX() - 1][state.getY()][state.getZ()] == 0 && visit[state.getX() - 1][state.getY()][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX() - 1, state.getY()), state));
visit[state.getX() - 1][state.getY()][state.getZ()] = true;
}
if (m[state.getX()][state.getY() - 1][state.getZ()] == 0 && visit[state.getX()][state.getY() - 1][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D( state.getZ(),state.getX(), state.getY() - 1), state));
visit[state.getX()][state.getY() - 1][state.getZ()] = true;
}
if (m[state.getX() + 1][state.getY()][state.getZ()] == 0 && visit[state.getX() + 1][state.getY()][state.getZ()] == false) {
possibleStates.add(new Maze3DState(new Position3D(state.getZ(),state.getX() + 1, state.getY()), state));
visit[state.getX() + 1][state.getY()][state.getZ()] = true;
}
}
return possibleStates;
}
/**
* the function change the value of all the cells in array to false in order to search again the maze
*/
@Override
public void clearVisit() {
for (int i = 0; i < maze.getDepth(); i++) {
for (int j = 0; j < maze.getRow(); j++) {
for (int k = 0; k < maze.getCol(); k++) {
visit[j][k][i]=false;
}
}
}
}
}
|
JavaScript
|
UTF-8
| 675 | 2.625 | 3 |
[] |
no_license
|
function showRestaurants() {
var latestitems = document.getElementById("latest");
var dbRef = firebase.database().ref().child("Restaurants").child('1').child('Items');
window.alert('lol');
dbRef.on('value', function(datasnapshot) {
datasnapshot.forEach(function(childSnapshot) {
var childData = childSnapshot.val();
window.alert(childData.Name);
});
});
}
function getCartCountAndDisplay() {
var userid = 1;
var cartcount = document.getElementById("cartcount");
var cartRef = firebase.database().ref("Users/"+userid).child("Cart");
cartRef.on("value", function (snapShot) {
cartcount.innerHTML = snapShot.numChildren();
});
}
|
Java
|
UTF-8
| 283 | 1.90625 | 2 |
[
"Apache-2.0"
] |
permissive
|
package org.apache.thriftstudy.transport;
import java.nio.channels.Selector;
/**
* @author Yaochao
* @version 1.0
* @date 2017/8/17
*/
public abstract class TNonblockingServerTransport extends TServerTransport {
public abstract void registerSelector(Selector selector);
}
|
Java
|
MacCentralEurope
| 2,294 | 1.898438 | 2 |
[] |
no_license
|
package org.example.asteroides;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.IBinder;
import android.provider.MediaStore.Audio;
import android.widget.Toast;
public class ServicioMusica extends Service {
MediaPlayer reproductor;
private NotificationManager nm;
private static final int ID_NOTIFICACION_CREAR = 1;
@Override
public void onCreate() {
Toast.makeText(this, "Servicio creado", Toast.LENGTH_SHORT).show();
reproductor = MediaPlayer.create(this, R.raw.audio);
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
@Override
public int onStartCommand(Intent intenc, int flags, int idArranque) {
Toast.makeText(this, "Servicio arrancado " + idArranque,
Toast.LENGTH_SHORT).show();
reproductor.start();
Notification notificacion = new Notification(R.drawable.ic_launcher,
"Creando Servicio de Msica", System.currentTimeMillis());
PendingIntent intencionPendiente = PendingIntent.getActivity(this, 0,
new Intent(this, Asteroides.class), 0);
notificacion.setLatestEventInfo(this, "Reproduciendo msica",
"informacin adicional", intencionPendiente);
// Activar sonido a la notificacin
notificacion.defaults |= Notification.DEFAULT_SOUND;
// notificacion.sound = Uri.parse("file:///sdcard/carpeta/tono.mp3");
// notificacion.sound = Uri.withAppendedPath(
// Audio.Media.INTERNAL_CONTENT_URI, "6");
// Vibracin
// notificacion.defaults |= Notification.DEFAULT_VIBRATE;
long[] vibrate = { 0, 100, 200, 300 };
notificacion.vibrate = vibrate;
// Parpadeo de LED
//notificacion.defaults |= Notification.DEFAULT_LIGHTS;
notificacion.ledARGB = 0xff00ff00;
notificacion.ledOnMS = 300;
notificacion.ledOffMS = 1000;
notificacion.flags |= Notification.FLAG_SHOW_LIGHTS;
nm.notify(ID_NOTIFICACION_CREAR, notificacion);
return START_STICKY;
}
@Override
public void onDestroy() {
Toast.makeText(this, "Servicio detenido", Toast.LENGTH_SHORT).show();
reproductor.stop();
nm.cancel(ID_NOTIFICACION_CREAR);
}
@Override
public IBinder onBind(Intent intencion) {
return null;
}
}
|
Markdown
|
UTF-8
| 3,350 | 2.8125 | 3 |
[] |
no_license
|
###### Capital in the 14th century
# New research suggests that secular stagnation is centuries old
##### Central bankers’ biggest problem may be ancient—and getting worse

> Jan 9th 2020
HOW LOW can interest rates go? It is a question that worries central bankers everywhere. Since the global financial crisis of 2007-08 rates have been pushed down to unprecedented levels in order to prop up growth. With central banks’ interest rates near or below zero across much of the world, room for further cuts to combat the next downturn is limited. If America’s Federal Reserve can manage to keep nominal rates at 2% or higher over the long term, it should be able to cope with the help of policies such as quantitative easing, mused Ben Bernanke, a former Fed chairman, at the conference of the American Economic Association (AEA) on January 4th. Alas, a working paper* published by the Bank of England the previous day suggests that rates could have further to fall.
Most research on long-term trends in interest rates relies on data from the past century. But Paul Schmelzing of the Yale School of Management has gathered information on real interest rates (that is, corrected for inflation) covering 78% of advanced-economy GDP going back to the early 14th century, when capitalism and free markets began to emerge. He found that real rates have declined by 0.006-0.016 percentage points a year since the late Middle Ages (see chart). That may not seem much, but it means real interest rates have fallen from an average of around 10% in the 15th century to just 0.4% in 2018.

That conclusion undermines the claim that “secular stagnation” is a recent economic malaise. The concept gained prominence after Larry Summers of Harvard University used it in 2013 to describe the falling rates of return on investment and economic growth in the American economy since the 1970s. Mr Schmelzing’s data instead suggest that secular stagnation, insofar as it means falling interest rates, has been a feature of capitalism since its birth. Rates falling since the early 1980s may be less the result of acute problems, such as an ageing population, than markets simply snapping back to a centuries-old trend.
The data also challenge some of the arguments of Thomas Piketty’s “Capital in the Twenty-First Century”, one of the best-selling economics books of all time. These rely on the claim that the return on capital has stayed constant and been consistently higher than economic growth. Under such conditions capitalism produces ever-greater income inequality, Mr Piketty claims, since there are no forces acting against the steady concentration of wealth. If real interest rates—and hence, returns on capital—have been falling for centuries, however, there may well be such a force.
Mr Schmelzing’s conclusions pose an even starker challenge to central bankers. If the historical trend continues, by the late 2020s global short-term real rates will have reached permanently negative territory. By the late 21st century, long-term rates will have joined them. Even unconventional monetary policies, which rely on driving down long-term rates, would then lose traction. Any hopes for nominal rates of 2% or more, in the long term, may prove to be a pipe dream. ■
|
TypeScript
|
UTF-8
| 229 | 2.78125 | 3 |
[] |
no_license
|
import genId from "../utils/genId";
export default class Todo {
id!: number;
text!: string;
completed!: boolean;
constructor(text: string) {
this.id = genId();
this.text = text;
this.completed = false;
}
}
|
Markdown
|
UTF-8
| 2,148 | 4.21875 | 4 |
[] |
no_license
|
# Variables / Expressions / Statements
## Q1.a
```python
number1 = 13
number2 = 5
# Printing numbers in separate lines
print(number1)
print(number2)
# Printing numbers in a single line
print(number1, number2)
```
## Q1.b
```python
number1 = int(input())
number2 = int(input())
print(number1)
print(number2)
```
## Q1.c
```python
a = int(input())
b = int(input())
print(a + b, a - b, a * b, a ** b, a % b)
```
## Q2.a
```python
number = 5
my_float = 9.8
my_str = "Helloo"
print(type(number))
print(type(my_float))
print(type(my_str))
```
<br>
## Q2.b
```python
number = int(input("Enter an integer: "))
my_float = float(input("Enter a float "))
my_str = input("Please enter third number: ")
print(number, my_float, my_str)
# Same print with + operator (concatenation of strings))
print(str(number) + " " + str(my_float) + " " + my_str)
```
<br>
## Q3
```python
number1 = int(input("First number: "))
number2 = int(input("Second number: "))
number3 = int(input("Third number: "))
sum = number1 + number2 + number3
print(sum)
print(sum / 3)
print(number1 * number2 * number3)
```
<br>
## Q4
```python
A = int(input("Enter principal amount: "))
i = int(input("Enter interest rate: "))
n = int(input("Enter duration: "))
S = A * (1 + i/100) ** n
print("{:.2f}".format(S))
```
<br>
## Q5
```python
r1 = int(input("First resistance: "))
r2 = int(input("Second resistance: "))
v = int(input("Voltage: "))
print(int(v / r1), int(v / r2))
```
<br>
## Q6
```python
y = int(input("Year: "))
m = int(input("Month: "))
d = int(input("Days: "))
h = int(input("Hours: "))
min = int(input("Minutes: "))
y = y * 365 * 24 * 60 * 60
m = m * 30 * 24 * 60 * 60
d = d * 24 * 60 * 60
h = h * 60 * 60
min = min * 60
sum = y + m + d + h + min
print(sum)
```
Alternative:
```python
y = int(input("Year: "))
m = int(input("Month: "))
d = int(input("Days: "))
h = int(input("Hours: "))
min = int(input("Minutes: "))
sum = (((y * 365 + m * 30 + d) * 24 + h) * 60 + min) * 60
print(sum)
```
<br>
|
C#
|
UTF-8
| 1,147 | 2.921875 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using DUIP.UI.Graphics;
namespace DUIP.UI
{
/// <summary>
/// Content that displays a text block to allow the user to create objects based on written code.
/// </summary>
public class EditorContent : Content
{
public EditorContent()
{
}
public override Disposable<Block> CreateBlock(Theme Theme)
{
SystemTypeface typeface = SystemTypeface.Create("Courier New", false, false);
SystemFont font = typeface.GetFont(0.05, Color.Black);
TextStyle normal = new TextStyle(font, Color.White);
TextStyle selected = new TextStyle(font, Color.Black);
TextBlock textblock =
new TextBlock(((TextSection)"Look, it's a list:\n\t* With\n\t* Three\n\t* Items").Style(normal, selected),
new TextBlockStyle(new Point(0.04, 0.05), Alignment.Center, Alignment.Center, 4, 0.5, new Border(0.003, Color.Black)));
return textblock.WithMargin(0.1).WithBackground(Theme.NodeBackground).WithBorder(Theme.NodeBorder);
}
}
}
|
C++
|
UTF-8
| 878 | 3.4375 | 3 |
[] |
no_license
|
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
#include "View.h"
void View::mainMenu(int& selection)
{
int numOptions = 1;
selection = -1;
cout << endl;
cout << "(1) Add student" << endl;
cout << "(0) Exit" << endl;
while (selection < 0 || selection > numOptions) {
cout << "Enter your selection: ";
cin >> selection;
}
}
void View::readStuId(int& id)
{
cout << "student id: ";
cin >> id;
}
bool View::readCourse(int& code, int& grade, int& term, string& instructor)
{
cout << "course code <0 to end>: ";
cin >> code;
if(code == 0){
return false;
}
cout << "grade: ";
cin >> grade;
cout << "term: ";
cin >> term;
cout << "instructor: ";
cin >> instructor;
return true;
}
void View::printStorage(Storage& sto)
{
sto.print();
}
|
C++
|
UTF-8
| 713 | 3.34375 | 3 |
[] |
no_license
|
// https://www.geeksforgeeks.org/largest-rectangle-under-histogram/
int Solution::largestRectangleArea(vector<int> &A) {
stack<int> st;
int maxArea = -1, i = 0;
while(i < A.size()) {
if(st.empty() || A[st.top()] <= A[i])
st.push(i++);
else {
int currMax = st.top();
st.pop();
int area = A[currMax] * (st.empty() ? i : i - st.top() - 1);
maxArea = max(maxArea, area);
}
}
while(!st.empty()) {
int curr = st.top();
st.pop();
int area = A[curr] * (st.empty() ? i : i - st.top() - 1);
maxArea = max(maxArea, area);
}
return maxArea;
}
|
Python
|
UTF-8
| 1,764 | 2.515625 | 3 |
[] |
no_license
|
#You must have Chocolatey installed here for this to work
##Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
#You must have Selenium Installed for this to work
##Pip command to install: pip install -U selenium
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.support.ui import Select
from time import sleep
from selenium.webdriver.common.keys import Keys
from selenium.webdriver import ActionChains
from random import randrange
import base64
from getpass import getpass
# email = input("Enter your id:\n")
# password = getpass('Password:\n')
courseNumber = input("What is the CSC CRN of the course you are targeting?:\n")
#This is the driver for the browser of your choosing (Chrome) INSTALLING THE DRIVER IS NECESSARY TO AUTOMATE
driver = webdriver.Chrome()
#This line heads to the page you want to automate things on. Launches google chrome and heads to desired page
driver.get('https://dssapex.gsu.edu/pls/apex/f?p=114:184:::NO::P_RPT_FORMAT_184,P_LEVEL_184,P_COLG_184,P_DEPT_184,P_PREFIX_184,P_CRSNBR_184,P_TERM_184:C,%25,,,CSC,4330,202008')
sleep(3)
#Select Course Number Drop Down
driver.find_element_by_xpath('/html/body/form/div/div/div/div[5]/div/div/div[1]/div[2]/section/div[2]/div[2]/div[6]/div/div/select').click()
sleep(3)
#Select Course Number from Drop Down
select = Select(driver.find_element_by_id('P_CRSNBR_184'))
select.select_by_visible_text(courseNumber)
sleep(3)
#Screenshot Page
driver.save_screenshot('ssn.png')
sleep(2)
|
SQL
|
UTF-8
| 312 | 2.84375 | 3 |
[] |
no_license
|
CREATE TABLE IF NOT EXISTS `cps_admin_user` (
`id` SMALLINT NOT NULL AUTO_INCREMENT,
`email` VARCHAR(50) NOT NULL,
`status` TINYINT NOT NULL DEFAULT 0,
`last_login_time` INT NOT NULL,
PRIMARY KEY (`id`)
);
ALTER TABLE cps_admin_user
ADD UNIQUE (email);
|
Markdown
|
UTF-8
| 29,225 | 2.96875 | 3 |
[
"MIT"
] |
permissive
|
# Beginner tutorial
I'm using the data from the [dplyr tutorial](https://cran.r-project.org/web/packages/dplyr/vignettes/dplyr.html). The data is in the test folder of this package.
I created it with the following R code:
```R
library(nycflights13)
setwd("C:/Users/hp/.julia/dev/LightQuery/test")
write.csv(airports, "airports.csv", na = "", row.names = FALSE)
write.csv(flights, "flights.csv", na = "", row.names = FALSE)
write.csv(weathers, "weather.csv", na = "", row.names = FALSE)
```
First, import some tools we will need and change the working directory.
```jldoctest flights
julia> using LightQuery
julia> import Compat: Iterators
julia> using Dates: Date, DateTime, Hour
julia> using Base.Iterators: flatten
julia> using Tables: columntable
julia> using TimeZones: Class, Local, TimeZone, ZonedDateTime
julia> using Unitful: °, °F, ft, hr, inch, mbar, mi, minute
julia> cd(joinpath(pkgdir(LightQuery), "test"));
```
## Airports cleaning
The first step in cleaning up this data is to create a dataset about airports. The airports data crucially contains timezone information which we will need to adjust flight times.
Use [`CSV.File`](http://juliadata.github.io/CSV.jl/stable/#CSV.File) to import the airports data.
```jldoctest flights
julia> using CSV: File
julia> airports_file = File("airports.csv", missingstrings = ["", "\\N"]);
```
You can use `Tables.columntable` to get the columns of the file. Then, immediately use [`Rows`](@ref) to iterate over the rows of the file. `columntable` is a key entry-point to LightQuery, because so many packages implement the Tables interace.
```jldoctest flights
julia> airports_file = Rows(; columntable(airports_file)...);
```
Let's read in the first row and try to process it.
```jldoctest flights
julia> airport = first(airports_file)
(faa = "04G", name = "Lansdowne Airport", lat = 41.1304722, lon = -80.6195833, alt = 1044, tz = -5, dst = "A", tzone = "America/New_York")
```
Next, [`rename`](@ref) the variables to be human readable.
```jldoctest flights
julia> airport = rename(airport,
airport_code = name"faa",
altitude = name"alt",
daylight_savings = name"dst",
latitude = name"lat",
longitude = name"lon",
time_zone = name"tzone",
time_zone_offset = name"tz"
)
(name = "Lansdowne Airport", airport_code = "04G", altitude = 1044, daylight_savings = "A", latitude = 41.1304722, longitude = -80.6195833, time_zone = "America/New_York", time_zone_offset = -5)
```
Next, [`remove`](@ref) redundant data. This data is associated with timezones, not flights.
```jldoctest flights
julia> airport = remove(airport,
name"daylight_savings",
name"time_zone_offset"
)
(name = "Lansdowne Airport", airport_code = "04G", altitude = 1044, latitude = 41.1304722, longitude = -80.6195833, time_zone = "America/New_York")
```
Next, add units to some of our variables using [`transform`](@ref).
```jldoctest flights
julia> airport = transform(airport,
altitude = airport.altitude * ft,
latitude = airport.latitude * °,
longitude = airport.longitude * °
)
(name = "Lansdowne Airport", airport_code = "04G", time_zone = "America/New_York", altitude = 1044 ft, latitude = 41.1304722°, longitude = -80.6195833°)
```
Next, we will write a function for getting a true timezone. This will be useful because the departure and arrival times are in various timezones. Use [`@if_known`](@ref) to handle `missing` data. Note the data contains some `LEGACY` timezones.
```jldoctest flights
julia> get_time_zone(time_zone) = TimeZone(
(@if_known time_zone),
Class(:STANDARD) | Class(:LEGACY)
);
julia> get_time_zone(airport.time_zone)
America/New_York (UTC-5/UTC-4)
```
Next, put all of our row processing steps together into one function. You can use the all-purpose chaining macro [`@>`](@ref) provided in this package to chain all of these steps together.
```jldoctest flights
julia> function get_airport(row)
@> row |>
rename(_,
airport_code = name"faa",
altitude = name"alt",
daylight_savings = name"dst",
latitude = name"lat",
longitude = name"lon",
time_zone = name"tzone",
time_zone_offset = name"tz"
) |>
remove(_,
name"daylight_savings",
name"time_zone_offset",
) |>
transform(_,
altitude = _.altitude * ft,
latitude = _.latitude * °,
longitude = _.longitude * °,
time_zone = get_time_zone(_.time_zone)
)
end;
julia> get_airport(first(airports_file))
(name = "Lansdowne Airport", airport_code = "04G", altitude = 1044 ft, latitude = 41.1304722°, longitude = -80.6195833°, time_zone = tz"America/New_York")
```
Use `Iterators.map` to lazily map this function over each row of the airports file.
```jldoctest flights
julia> airports = Iterators.map(get_airport, airports_file);
```
I will repeat the following sequence of operations many times in this tutorial. Call [`make_columns`](@ref) to store the data as columns. Then, because it is useful to view the data as rows, use [`Rows`](@ref) to lazily view the data row-wise. You can use [`Peek`](@ref) to look at the first few rows of data.
```jldoctest flights
julia> airports = Rows(; make_columns(airports)...);
```
You can use [`index`](@ref) to be able to quickly retrieve airports by code. This will be helpful later. This is very similar to making a `Dict`.
```jldoctest flights
julia> const indexed_airports = index(airports, name"airport_code");
```
## Flights cleaning
Now that we have built our airports dataset, we can start working on the flights data. We're following basically the same steps as we did above.
```jldoctest flights
julia> flights_file =
@> File("flights.csv") |>
columntable |>
Rows(; _...);
```
Again, we will build a function to clean up a row of data. We will again use the first row to build and test our function. I will skip over several steps that we already used in the airports data: get the first flight, [`rename`](@ref), [`remove`](@ref), and [`transform`](@ref) to add units.
```jldoctest flights
julia> flight =
@> flights_file |>
first |>
rename(_,
arrival_delay = name"arr_delay",
arrival_time = name"arr_time",
departure_delay = name"dep_delay",
departure_time = name"dep_time",
destination = name"dest",
scheduled_arrival_time = name"sched_arr_time",
scheduled_departure_time = name"sched_dep_time",
tail_number = name"tailnum"
) |>
remove(_,
name"arrival_time",
name"departure_time",
name"hour",
name"minute",
name"time_hour"
) |>
transform(_,
air_time = _.air_time * minute,
arrival_delay = _.arrival_delay * minute,
departure_delay = _.departure_delay * minute,
distance = _.distance * mi
)
(year = 2013, month = 1, day = 1, carrier = "UA", flight = 1545, origin = "EWR", destination = "IAH", scheduled_arrival_time = 819, scheduled_departure_time = 515, tail_number = "N14228", air_time = 227 minute, arrival_delay = 11 minute, departure_delay = 2 minute, distance = 1400 mi)
```
Let's find the `time_zone` of the `airport` the `flight` departed from. Use [`@if_known`](@ref) to handle `missing` data.
```jldoctest flights
julia> airport = @if_known get(indexed_airports, flight.origin, missing)
(name = "Newark Liberty Intl", airport_code = "EWR", altitude = 18 ft, latitude = 40.6925°, longitude = -74.168667°, time_zone = tz"America/New_York")
julia> time_zone = @if_known airport.time_zone
America/New_York (UTC-5/UTC-4)
```
Now process the departure time. We are given times as hours and minutes concatenated together. Use `divrem(_, 100)` to split the `scheduled_departure_time`.
```jldoctest flights
julia> divrem(flight.scheduled_departure_time, 100)
(5, 15)
```
Let's build a `ZonedDateTime` for the departure time.
```jldoctest flights
julia> ZonedDateTime(
flight.year,
flight.month,
flight.day,
divrem(flight.scheduled_departure_time, 100)...,
time_zone
)
2013-01-01T05:15:00-05:00
```
We can combine the steps for creating a ZonedDateTime into one function. Then we can use it for both the departure and the arrival times.
```jldoctest flights
julia> get_time(indexed_airports, flight, airport, time) =
ZonedDateTime(
flight.year,
flight.month,
flight.day,
divrem(time, 100)...,
@if_known (@if_known get(indexed_airports, airport, missing)).time_zone
);
julia> get_time(
indexed_airports,
flight,
flight.origin,
flight.scheduled_departure_time
)
2013-01-01T05:15:00-05:00
```
We also used this function to build the `scheduled_arrival_time`.
```jldoctest flights
julia> arrival = get_time(
indexed_airports,
flight,
flight.destination,
flight.scheduled_arrival_time
)
2013-01-01T08:19:00-06:00
```
Let's combine all of the flights row processing steps into one function.
```jldoctest flights
julia> function get_flight(indexed_airports, row)
@> row |>
rename(_,
arrival_delay = name"arr_delay",
arrival_time = name"arr_time",
departure_delay = name"dep_delay",
departure_time = name"dep_time",
destination = name"dest",
scheduled_arrival_time = name"sched_arr_time",
scheduled_departure_time = name"sched_dep_time",
tail_number = name"tailnum"
) |>
remove(_,
name"arrival_time",
name"departure_time",
name"hour",
name"minute",
name"time_hour"
) |>
transform(_,
air_time = _.air_time * minute,
distance = _.distance * mi,
departure_delay = _.departure_delay * minute,
arrival_delay = _.arrival_delay * minute,
scheduled_departure_time =
get_time(indexed_airports, _, _.origin, _.scheduled_departure_time),
scheduled_arrival_time =
get_time(indexed_airports, _, _.destination, _.scheduled_arrival_time)
) |>
remove(_,
name"year",
name"month",
name"day"
)
end;
julia> get_flight(indexed_airports, first(flights_file))
(carrier = "UA", flight = 1545, origin = "EWR", destination = "IAH", tail_number = "N14228", air_time = 227 minute, distance = 1400 mi, departure_delay = 2 minute, arrival_delay = 11 minute, scheduled_departure_time = ZonedDateTime(2013, 1, 1, 5, 15, tz"America/New_York"), scheduled_arrival_time = ZonedDateTime(2013, 1, 1, 8, 19, tz"America/Chicago"))
```
Again, use `Iterators.map` to lazily map this function over each row. Here we are using the [`@_`](@ref) macro to create an anonymous function as tersely as possible. Finally, we will again use [`make_columns`](@ref) and [`Rows`](@ref) to store the data column-wise and view it row-wise. Again use [`Peek`](@ref) to view the first few rows.
```jldoctest flights
julia> flights =
@> flights_file |>
Iterators.map((@_ get_flight(indexed_airports, _)), _);
```
## Grouping and validating flights
Now that we have cleaned the data, what should we do with? One simple question we might want to answer is whether the distances between two airports is always the same. If this is not the case, there is an inconsistency in the data. Answering this question will also allow me to show off the grouping features of the package. For both joining and grouping, LightQuery requires your data to be pre-sorted. This is greatly improves performance. Consider keeping your data pre-sorted to begin with!
Thus, first, we will need to [`order`](@ref) flights by `origin`, `destination`, and `distance`. Note that we are using a tuple of [`Name`](@ref)s as a selector function to pass to `order`. Once the data is in order, we can [`Group`](@ref) [`By`](@ref) the same variables. [`By`](@ref) is necessary before grouping and joining to tell LightQuery how your data is ordered. All flights with the same origin, destination, and distance will be put into one group.
```jldoctest flights
julia> paths_grouped =
@> flights |>
order(_, (name"origin", name"destination", name"distance")) |>
Group(By(_, (name"origin", name"destination", name"distance")));
```
Each [`Group`](@ref) contains a [`key`](@ref) and [`value`](@ref). The [`key`](@ref) is what we use to group the rows, and the [`value`](@ref) is a group of rows which all have the same key. We can look at the first few rows in a group using [`Peek`](@ref).
```jldoctest flights
julia> path = first(paths_grouped);
julia> key(path)
(origin = "EWR", destination = "ALB", distance = 143 mi)
julia> value(path) |> Peek
Showing 4 of 439 rows
| carrier | flight | origin | destination | tail_number | air_time | distance | departure_delay | arrival_delay | scheduled_departure_time | scheduled_arrival_time |
| -------:| ------:| ------:| -----------:| -----------:| ---------:| --------:| ---------------:| -------------:| -------------------------:| -------------------------:|
| EV | 4112 | EWR | ALB | N13538 | 33 minute | 143 mi | -2 minute | -10 minute | 2013-01-01T13:17:00-05:00 | 2013-01-01T14:23:00-05:00 |
| EV | 3260 | EWR | ALB | N19554 | 36 minute | 143 mi | 34 minute | 40 minute | 2013-01-01T16:21:00-05:00 | 2013-01-01T17:24:00-05:00 |
| EV | 4170 | EWR | ALB | N12540 | 31 minute | 143 mi | 52 minute | 44 minute | 2013-01-01T20:04:00-05:00 | 2013-01-01T21:12:00-05:00 |
| EV | 4316 | EWR | ALB | N14153 | 33 minute | 143 mi | 5 minute | -14 minute | 2013-01-02T13:27:00-05:00 | 2013-01-02T14:33:00-05:00 |
```
For the purposes of our analysis, all we need is the `key`. As always, store the data as columns using [`make_columns`](@ref), lazily view it as rows using [`Rows`](@ref), and use [`Peek`](@ref) to view the first few rows.
```jldoctest flights
julia> paths =
@> paths_grouped |>
Iterators.map(key, _) |>
make_columns |>
Rows(; _ ...);
julia> Peek(paths)
Showing 4 of 226 rows
| origin | destination | distance |
| ------:| -----------:| --------:|
| EWR | ALB | 143 mi |
| EWR | ANC | 3370 mi |
| EWR | ATL | 746 mi |
| EWR | AUS | 1504 mi |
```
Let's run our data through a second round of grouping. This time, we will group data only by origin and destination. Theoretically, each group should only be one row long, because the distance between an origin and destination airport should always be the same. Our data is already sorted, so we do not need to sort it again before grouping. Again, use [`Group`](@ref) and [`By`](@ref) to group the rows. Again, we can pass a tuple of [`Name`](@ref)s as a selector function. Then, for each group, we can find the number of rows it contains.
```jldoctest flights
julia> path_groups =
@> paths |>
Group(By(_, (name"origin", name"destination")));
```
Let's create a function to add the number of distinct distances to the `key`.
```jldoctest flights
julia> first_path_group = first(path_groups);
julia> key(first_path_group)
(origin = "EWR", destination = "ALB")
julia> Peek(value(first_path_group))
| origin | destination | distance |
| ------:| -----------:| --------:|
| EWR | ALB | 143 mi |
julia> function with_number((key, value))
transform(key, number = length(value))
end;
julia> with_number(first_path_group)
(origin = "EWR", destination = "ALB", number = 1)
```
We can take a [`Peek`](@ref) at the first few results.
```jldoctest flights
julia> distinct_distances =
@> path_groups |>
Iterators.map(with_number, _);
julia> Peek(distinct_distances)
Showing at most 4 rows
| origin | destination | number |
| ------:| -----------:| ------:|
| EWR | ALB | 1 |
| EWR | ANC | 1 |
| EWR | ATL | 1 |
| EWR | AUS | 1 |
```
Let's see when there are multiple distances for the same path using `Iterators.filter`. Again, use [`@_`](@ref) to create an anonymous function to pass to `Iterators.filter`.
```jldoctest flights
julia> @> distinct_distances |>
Iterators.filter((@_ _.number != 1), _) |>
Peek
Showing at most 4 rows
| origin | destination | number |
| ------:| -----------:| ------:|
| EWR | EGE | 2 |
| JFK | EGE | 2 |
```
It looks like there is a consistency with flights which arrive at at the `EGE` airport. Let's take a [`Peek`](@ref) at flights going to `"EGE"` using `Iterators.filter`. Again, use [`@_`](@ref) to create an anonymous function to pass to `Iterators.filter`.
```jldoctest flights
julia> @> flights |>
Iterators.filter((@_ _.destination == "EGE"), _) |>
Peek
Showing at most 4 rows
| carrier | flight | origin | destination | tail_number | air_time | distance | departure_delay | arrival_delay | scheduled_departure_time | scheduled_arrival_time |
| -------:| ------:| ------:| -----------:| -----------:| ----------:| --------:| ---------------:| -------------:| -------------------------:| -------------------------:|
| UA | 1597 | EWR | EGE | N27733 | 287 minute | 1726 mi | -2 minute | 13 minute | 2013-01-01T09:28:00-05:00 | 2013-01-01T12:20:00-07:00 |
| AA | 575 | JFK | EGE | N5DRAA | 280 minute | 1747 mi | -5 minute | 3 minute | 2013-01-01T17:00:00-05:00 | 2013-01-01T19:50:00-07:00 |
| UA | 1597 | EWR | EGE | N24702 | 261 minute | 1726 mi | 1 minute | 3 minute | 2013-01-02T09:28:00-05:00 | 2013-01-02T12:20:00-07:00 |
| AA | 575 | JFK | EGE | N631AA | 260 minute | 1747 mi | 5 minute | 16 minute | 2013-01-02T17:00:00-05:00 | 2013-01-02T19:50:00-07:00 |
```
You can see just in these rows that there is an inconsistency in the data. The distance for the first two rows should be the same as the distance for the second two rows.
## Weather cleaning
Perhaps I want to know weather influences the departure delay. To do this, I will need to join weather data into the flights data. Start by cleaning the weather data using basically the same steps as above. Get the first row, [`rename`](@ref), [`remove`](@ref), and [`transform`](@ref) to add units.
```jldoctest flights
julia> weathers_file =
@> File("weather.csv") |>
columntable |>
Rows(; _...);
julia> function get_weather(indexed_airports, row)
@> row |>
rename(_,
airport_code = name"origin",
dew_point = name"dewp",
humidity = name"humid",
precipitation = name"precip",
temperature = name"temp",
visibility = name"visib",
wind_direction = name"wind_dir"
) |>
transform(_,
dew_point = _.dew_point * °F,
humidity = _.humidity / 100,
precipitation = _.precipitation * inch,
pressure = _.pressure * mbar,
temperature = _.temperature * °F,
visibility = _.visibility * mi,
wind_direction = _.wind_direction * °,
wind_gust = _.wind_gust * mi / hr,
wind_speed = _.wind_speed * mi / hr,
date_time = ZonedDateTime(
_.year,
_.month,
_.day,
_.hour,
indexed_airports[_.airport_code].time_zone,
1
)
) |>
remove(_,
name"year",
name"month",
name"day",
name"hour"
)
end;
julia> weathers =
@> weathers_file |>
Iterators.map((@_ get_weather(indexed_airports, _)), _);
julia> Peek(weathers)
Showing 4 of 26115 rows
| time_hour | airport_code | dew_point | humidity | precipitation | pressure | temperature | visibility | wind_direction | wind_gust | wind_speed | date_time |
| -------------------:| ------------:| ---------:| ------------------:| -------------:| -----------:| -----------:| ----------:| --------------:| ---------:| -----------------:| -------------------------:|
| 2013-01-01 01:00:00 | EWR | 26.06 °F | 0.5937 | 0.0 inch | 1012.0 mbar | 39.02 °F | 10.0 mi | 270° | missing | 10.35702 mi hr^-1 | 2013-01-01T01:00:00-05:00 |
| 2013-01-01 02:00:00 | EWR | 26.96 °F | 0.6163000000000001 | 0.0 inch | 1012.3 mbar | 39.02 °F | 10.0 mi | 250° | missing | 8.05546 mi hr^-1 | 2013-01-01T02:00:00-05:00 |
| 2013-01-01 03:00:00 | EWR | 28.04 °F | 0.6443000000000001 | 0.0 inch | 1012.5 mbar | 39.02 °F | 10.0 mi | 240° | missing | 11.5078 mi hr^-1 | 2013-01-01T03:00:00-05:00 |
| 2013-01-01 04:00:00 | EWR | 28.04 °F | 0.6221 | 0.0 inch | 1012.2 mbar | 39.92 °F | 10.0 mi | 250° | missing | 12.65858 mi hr^-1 | 2013-01-01T04:00:00-05:00 |
```
## Joining flights and weather
I happen to know that the weather data is already sorted by `airport_code` and `hour`. However, we will need to presort and group the flights before we can join in the weather file. Joining in LightQuery is never many-to-one; you always need to explicitly group first. This is slightly less convenient but allows some extra flexibility.
[`order`](@ref) and [`Group`](@ref) `flights` [`By`](@ref) matching variables. We will join the flights to the weather data by rounding down the scheduled departure time of the flight to the nearest hour. Only use data when the `departure_delay` is present.
```jldoctest flights
julia> grouped_flights =
@> flights |>
Iterators.filter((@_ _.departure_delay !== missing), _) |>
order(_, (name"origin", name"scheduled_departure_time")) |>
Group(By(_, @_ (_.origin, floor(_.scheduled_departure_time, Hour))));
julia> key(first(grouped_flights))
("EWR", ZonedDateTime(2013, 1, 1, 5, tz"America/New_York"))
```
An inner join will find pairs rows with matching [`key`](@ref)s. Groups of flights are already sorted by [`key`](@ref).
```jldoctest flights
julia> weathers_to_flights = @> InnerJoin(
By(weathers, @_ (_.airport_code, _.date_time)),
By(grouped_flights, key)
);
```
Let's look at the first match. This will contain weather data, and a group of flights.
```jldoctest flights
julia> a_match = first(weathers_to_flights);
julia> weather, (flights_key, flights_value) = a_match;
julia> weather
(time_hour = "2013-01-01 05:00:00", airport_code = "EWR", dew_point = 28.04 °F, humidity = 0.6443000000000001, precipitation = 0.0 inch, pressure = 1011.9 mbar, temperature = 39.02 °F, visibility = 10.0 mi, wind_direction = 260°, wind_gust = missing, wind_speed = 12.65858 mi hr^-1, date_time = ZonedDateTime(2013, 1, 1, 5, tz"America/New_York"))
julia> flights_key
("EWR", ZonedDateTime(2013, 1, 1, 5, tz"America/New_York"))
julia> Peek(flights_value)
| carrier | flight | origin | destination | tail_number | air_time | distance | departure_delay | arrival_delay | scheduled_departure_time | scheduled_arrival_time |
| -------:| ------:| ------:| -----------:| -----------:| ----------:| --------:| ---------------:| -------------:| -------------------------:| -------------------------:|
| UA | 1545 | EWR | IAH | N14228 | 227 minute | 1400 mi | 2 minute | 11 minute | 2013-01-01T05:15:00-05:00 | 2013-01-01T08:19:00-06:00 |
| UA | 1696 | EWR | ORD | N39463 | 150 minute | 719 mi | -4 minute | 12 minute | 2013-01-01T05:58:00-05:00 | 2013-01-01T07:28:00-06:00 |
```
We're interested in `visibility` and `departure_delay`. We have one row of weather data on the left but multiple flights on the right. Thus, for each flight, we will need to add in the weather data we are interested in.
```jldoctest flights
julia> visibility = weather.visibility;
julia> Iterators.map((@_ (
visibility = visibility,
departure_delay = _.departure_delay
)), flights_value) |>
Peek
| visibility | departure_delay |
| ----------:| ---------------:|
| 10.0 mi | 2 minute |
| 10.0 mi | -4 minute |
```
We will need to conduct these steps for each match. So put them together into a function.
```jldoctest flights
julia> function interested_in(a_match)
weather, (flights_key, flights_value) = a_match
visibility = weather.visibility
Iterators.map((@_ (
visibility = visibility,
departure_delay = _.departure_delay
)), flights_value)
end;
julia> Peek(interested_in(a_match))
| visibility | departure_delay |
| ----------:| ---------------:|
| 10.0 mi | 2 minute |
| 10.0 mi | -4 minute |
```
For each match, we are returning several rows. Use `Base.Iterators.flatten` to unnest data and get a single iterator of rows. Collect the result.
```jldoctest flights
julia> data =
@> weathers_to_flights |>
Iterators.map(interested_in, _) |>
flatten |>
make_columns |>
Rows(; _...);
julia> Peek(data)
Showing 4 of 326993 rows
| visibility | departure_delay |
| ----------:| ---------------:|
| 10.0 mi | 2 minute |
| 10.0 mi | -4 minute |
| 10.0 mi | -5 minute |
| 10.0 mi | -2 minute |
```
## Visibility vs. departure delay
Now we can finally answer the question we are interested in. How does visibility affect `departure_delay`? First, let's group by visibility.
```jldoctest flights
julia> by_visibility =
@> data |>
order(_, name"visibility") |>
Group(By(_, name"visibility"));
julia> visibility_group = first(by_visibility);
julia> key(visibility_group)
0.0 mi
julia> value(visibility_group) |> Peek
Showing 4 of 87 rows
| visibility | departure_delay |
| ----------:| ---------------:|
| 0.0 mi | -5 minute |
| 0.0 mi | -1 minute |
| 0.0 mi | -8 minute |
| 0.0 mi | -7 minute |
```
For each group, we can calculate the mean `departure_delay`.
```jldoctest flights
julia> using Statistics: mean
julia> @> visibility_group |>
value |>
Iterators.map(name"departure_delay", _) |>
mean
32.252873563218394 minute
```
Now run it for all the groups.
```jldoctest flights
julia> get_mean_departure_delay(visibility_group) = (
visibility = key(visibility_group),
mean_departure_delay =
(@> visibility_group |>
value |>
Iterators.map(name"departure_delay", _) |>
mean),
count = length(value(visibility_group))
);
julia> @> by_visibility |>
Iterators.map(get_mean_departure_delay, _) |>
Peek(_, 20)
Showing at most 20 rows
| visibility | mean_departure_delay | count |
| ----------:| -------------------------:| ------:|
| 0.0 mi | 32.252873563218394 minute | 87 |
| 0.06 mi | 22.2 minute | 85 |
| 0.12 mi | 50.69975186104218 minute | 403 |
| 0.25 mi | 20.481110254433307 minute | 1297 |
| 0.5 mi | 32.5890826383624 minute | 1319 |
| 0.75 mi | 30.06759906759907 minute | 429 |
| 1.0 mi | 32.24348473566642 minute | 1343 |
| 1.25 mi | 53.187845303867405 minute | 181 |
| 1.5 mi | 25.90661478599222 minute | 1542 |
| 1.75 mi | 43.333333333333336 minute | 132 |
| 2.0 mi | 22.701923076923077 minute | 2912 |
| 2.5 mi | 21.18074398249453 minute | 2285 |
| 3.0 mi | 21.2113218731476 minute | 3374 |
| 4.0 mi | 19.48311444652908 minute | 2132 |
| 5.0 mi | 21.10387902695595 minute | 4563 |
| 6.0 mi | 19.807032301480483 minute | 5944 |
| 7.0 mi | 19.208963745361118 minute | 7006 |
| 8.0 mi | 19.98660103910309 minute | 7314 |
| 9.0 mi | 18.762949476558944 minute | 10985 |
| 10.0 mi | 10.951549367828692 minute | 273660 |
```
This data suggests that low visibility levels lead to larger departure delays, on average.
|
PHP
|
UTF-8
| 613 | 2.8125 | 3 |
[
"MIT"
] |
permissive
|
<?php namespace nyx\notify\transports\slack\interfaces;
// Internal dependencies
use nyx\notify\transports\slack;
/**
* Slackable Interface
*
* Represents an object that can be cast to a Slack Message.
*
* @package Nyx\Notify
* @version 0.1.0
* @author Michal Chojnacki <m.chojnacki@muyo.io>
* @copyright 2012-2017 Nyx Dev Team
* @link https://github.com/unyx/nyx
*/
interface Slackable
{
/**
* Returns a slack\Message representation of the object.
*
* @param mixed $context
* @return slack\Message
*/
public function toSlack($context) : slack\Message;
}
|
C#
|
UTF-8
| 3,465 | 2.890625 | 3 |
[
"MIT"
] |
permissive
|
using System.Drawing;
namespace Ada.Framework.UI.WinForms.Diagram.Entities
{
public class Triangulo : Forma
{
public override Point StartPoint
{
get
{
Point punto = new Point();
punto.X = PuntoA.X;
punto.Y = PuntoA.Y;
if (punto.X > PuntoB.X) punto.X = PuntoB.X;
if (punto.X > PuntoC.X) punto.X = PuntoC.X;
if (punto.Y > PuntoB.Y) punto.Y = PuntoB.Y;
if (punto.Y > PuntoC.Y) punto.Y = PuntoC.Y;
return punto;
}
set
{
int diffX = PuntoA.X - StartPoint.X;
int diffY = PuntoA.Y - StartPoint.Y;
PuntoA = new Point() { X = value.X + diffX, Y = value.Y + diffY };
diffX = PuntoB.X - StartPoint.X;
diffY = PuntoB.Y - StartPoint.Y;
PuntoB = new Point() { X = value.X + diffX, Y = value.Y + diffY };
diffX = PuntoC.X - StartPoint.X;
diffY = PuntoC.Y - StartPoint.Y;
PuntoC = new Point() { X = value.X + diffX, Y = value.Y + diffY };
}
}
public override Point EndPoint
{
get
{
Point punto = new Point();
punto.X = PuntoA.X;
punto.Y = PuntoA.Y;
if (punto.X < PuntoB.X) punto.X = PuntoB.X;
if (punto.X < PuntoC.X) punto.X = PuntoC.X;
if (punto.Y < PuntoB.Y) punto.Y = PuntoB.Y;
if (punto.Y < PuntoC.Y) punto.Y = PuntoC.Y;
return punto;
}
set
{
int diffX = EndPoint.X - PuntoA.X;
int diffY = EndPoint.Y - PuntoA.Y;
PuntoA = new Point() { X = value.X - diffX, Y = value.Y - diffY };
diffX = EndPoint.X - PuntoB.X;
diffY = EndPoint.Y - PuntoB.Y;
PuntoB = new Point() { X = value.X - diffX, Y = value.Y - diffY };
diffX = EndPoint.X - PuntoC.X;
diffY = EndPoint.Y - PuntoC.Y;
PuntoC = new Point() { X = value.X - diffX, Y = value.Y - diffY };
}
}
public Point PuntoA { get; set; }
public Point PuntoB { get; set; }
public Point PuntoC { get; set; }
public Triangulo(Point puntoA, Point puntoB, Point puntoC) : base()
{
PuntoA = puntoA;
PuntoB = puntoB;
PuntoC = puntoC;
}
public Triangulo(int puntoAX, int puntoAY, int puntoBX, int puntoBY, int puntoCX, int puntoCY)
{
PuntoA = new Point()
{
X = puntoAX,
Y = puntoAY
};
PuntoB = new Point()
{
X = puntoBX,
Y = puntoBY
};
PuntoC = new Point()
{
X = puntoCX,
Y = puntoCY
};
}
public override void Dibujar(Graphics graphics)
{
Point[] puntos = new Point[3] { PuntoA, PuntoB, PuntoC };
graphics.DrawPolygon(new Pen(ForeColor), puntos);
graphics.FillPolygon(BackColor, puntos);
}
}
}
|
Markdown
|
UTF-8
| 4,946 | 2.640625 | 3 |
[] |
no_license
|
贷款方:中国___银行___分(支)行(或信用社);
法定代表人: _______职务:________
地址:_______邮码:_______电话:________
借款方:_______________(单位或个人);
法定代表人:_______________职务:____________
地址:___________邮码:___________电话:____________
保证方:________________
法定代表人:___________职务:________
地址:___________邮码:___电话:____
借款方为进行生产(或经营活动),向贷款方申请借款,并由作为保证人,贷款方业已审查批准,经三方协商,特订立本合同,以期共同遵守。
第一条 贷款种类
第二条 借款用途
第三条 借款金额人民币(大写)元整。
第四条 借款利率为月息千分之,利随本清,如遇国家调整利率,按新规定计算。
第五条 借款和还款期限
1.借款时间共年零个月。自年月日起,至年月日止。
2.借款分期如下:
贷款期限
贷款时间
贷款金额
第一期
___年___月___底前
元
第二期
___年___月___底前
元
第三期
___年___月___底前
元
3.还款分期如下:
归还期限
归还时间
还款金额
还款时间利率
第一期
年 月底前
元
第二期
年 月底前
元
第三期
年 月底前
元
第六条 还款资金来源及还款方式
1.还款资金来源:_________________
2.还款方式:_________________
第七条 保证条款
1.借款方用______做抵押,到期不能归还贷款方的贷款,贷款方有权处理抵押品。借款方到期如数归还贷款的,抵押品由贷款方退还借款方。
2.借款方必须按照
借款合同
规定的用途使用借款,不得挪作他用,不得用借款进行违法活动。
3.借款方必须按合同规定的期限还本付息。
4.借款方有义务接受贷款方检查、监督贷款的使用情况,了解借款方的计划执行、经营管理、财务活动、物资库存等情况。借款方应提供有关的计划、统计、财务会计报表及资料。
5.有保证人担保,保证人履行连带责任后,有向借款方追偿的权利,借款方有义务对保证人进行偿还。
第八条 约定条款
由于经营管理不善而关闭、破产,确实无法履行合同的,在处理财产时,除了按国家规定用于人员工资和必要的维护费用外,应优先偿还贷载。由于上级主管部门决定关、停、并转或撤销工程建设等措施,或者由于不可抗力的意外事故致使合同无法履行时,经向贷款方申请,可以变更或解除合同,并免除承担违约责任。
第九条 违约责任
一。借款方的违约责任
1.借款方不按合同规定的用途使用借款,贷款方有权收回部分或全部贷款,对违约使用的部分,按银行规定的利率加收罚息。
2.借款方如逾期不还借款,贷款方有权追回借款,并按银行规定加收罚息。借款方提前还款的,应按规定减收利息。
3.借款方使用借款造成损失浪费或利用借款合同进行违法活动的,贷款方应追回贷款本息,有关单位对直接责任人应追究行政和经济责任。情节严重的,由司法机关追究刑事责任。
二、贷款方的违约责任
1.贷款方未按期提供贷款,应按违约数额和延期天数,付给借款方违约金。违约金数额的计算应与加收借款方的罚息计算相同。
2.银行工作人员,因失职行为造成贷款损失浪费或利用借款合同进行违法活动的,应追究行政和经济责任。情节严重的,应由司法机关追究刑事责任。
第十条 合同变更或解除。
1.本合同非因《中华人民共和国
合同法
》规定允许变更或解除合同的情况发生,任何一方当事人不得擅自变更或解除合同。
2.当事人一方依照《中华人民共和国合同法》要求变更或解除本借款合同时,应及时采用书面形式通知其他当事人,并达成书面协议。本合同变更或解除后,借款方已占用的借款和应付的利息,仍应按本合同的规定偿付。
本合同如有未尽事宜。须经合同各方当事人共同协商,作出补充规定。补充规定与本合同具有同等效力。
第十一条 本合同正本一式三份,贷款方、借款方、保证方各执一份;合同副本一式______份,报送等有关单位(如经公证或鉴证,应送公证或鉴证机关)各留存一份。
贷款方:_____________(公章)
代表人:______________
日期:______________
借款方:_____________(公章)
代表人:______________
日期:______________
银行帐户:______________
保证方:_____________(公章)
代表人:______________
日期:______________
银行帐户:
|
JavaScript
|
UTF-8
| 3,079 | 2.84375 | 3 |
[
"Unlicense"
] |
permissive
|
const types = {
AUTO_ID: {
name: "AUTO_ID",
class: "INTEGER",
typeCheck: val => Number.isInteger(val),
decorators: [
"PRIMARY KEY",
"AUTOINCREMENT"
],
},
UTC_DATE: {
name: "UTC_DATE",
class: "INTEGER",
typeCheck: val => !isNaN(new Date(val).getTime()),
in: val => new Date(val).getTime(),
out: storedVal => new Date(storedVal).toISOString(),
},
ISO_DATE: {
name: "ISO_DATE",
class: "INTEGER",
typeCheck: val => !isNaN(new Date(val).getTime()),
in: val => new Date(val).getTime(),
out: storedVal => new Date(storedVal).toISOString(),
},
TEXT:{
name: "TEXT",
class: "TEXT",
typeCheck: val => typeof val == "string",
},
INTEGER: {
name: "INTEGER",
class: "INTEGER",
in: val => Number.parseInt(val),
typeCheck: val => !isNaN(Number.parseInt(val)),
},
REAL: {
name: "REAL",
class: "REAL",
in: val => Number.parseFloat(val),
typeCheck: val => !isNaN(Number.parseFloat(val)),
},
/**
* @typedef ArrayRestrictionArgs Set of limiting factors for the array type
* @property {Array<any>} predefined List of allowable array elements.
*/
/**
* @param {ArrayRestrictionArgs} args Restriction arguments.
*/
ARRAY: args => {
return {
name: (args && args.predefined) ? "FLAGS" : "ARRAY",
class: "TEXT",
args: args,
in: val => {
let inbound = !val ? "[]" : JSON.stringify(val)
return inbound;
},
out: storedVal => {
let outbound = !storedVal ? [] : JSON.parse(storedVal)
return outbound;
},
typeCheck: val => {
if (!Array.isArray(val)) {
// console.log("NOT AN ARRAY");
return false
}
else if (!args)
return true;
else {
if (args.predefined) {
for (let element of val) {
if (!args.predefined.includes(element)) {
// console.log("ILLEGAL ELEMENT:", element, "NOT IN", args.predefined)
return false
}
}
return true;
}
return true
}
}
}
},
BOOL : {
name: "BOOL",
class: "INTEGER",
in: val => val ? 1 : 0,
out: storedVal => storedVal == 1,
typeCheck: val => typeof val == "boolean"
},
REFACTOR: (operation) => {
return {
name: "TEXT",
class: "VIRTUAL",
out: obj => operation(obj),
readonly: true,
}
},
}
types.ENUM = {...types.TEXT, name: "ENUM"}
module.exports = types;
|
Ruby
|
UTF-8
| 1,277 | 2.59375 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
require './zip_cloud'
RSpec.describe ZipCloud do
describe '#get' do
subject {ZipCloud.get zipcode: zipcode}
context 'address is not found' do
let(:zipcode){'5368421'}
res = {}
it {is_expected.to match res}
end
context 'with argument 7830060' do
let(:zipcode){'7830060'}
res = {:address1=>"高知県", :address2=>"南国市", :address3=>"蛍が丘", :kana1=>"コウチケン", :kana2=>"ナンコクシ", :kana3=>"ホタルガオカ", :prefcode=>"39", :zipcode=>"7830060"}
it {is_expected.to match res}
end
context 'when argument is nothing' do
let(:zipcode){''}
res = {:message=>"必須パラメータが指定されていません。"}
it {is_expected.to match res}
end
context 'when argument is illegal' do
let(:zipcode){'illegal'}
res = {:message=>"パラメータ「郵便番号」に数字以外の文字が指定されています。"}
it {is_expected.to match res}
end
context 'when zipcode is wrong figure length' do
let(:zipcode){'53684'}
res = {:message=>"パラメータ「郵便番号」の桁数が不正です。"}
it {is_expected.to match res}
end
end
end
|
Java
|
UTF-8
| 3,285 | 2.4375 | 2 |
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.sanjose.model;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
*
* @author pol
*/
@Entity
@Table(name="centrocosto")
@NamedQueries({
@NamedQuery(name="CentroCosto.getCentroCostoPorNombre", query="SELECT b FROM CentroCosto b WHERE b.nombre = ?1"),
@NamedQuery(name="CentroCosto.getCentroCostoPorCodigo", query="SELECT b FROM CentroCosto b WHERE b.codigo = ?1")
})
public class CentroCosto implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private Boolean isLeaf = true;
private String nombre = "";
private String descripcion = "" ;
private String codigo = "" ;
private Integer level = new Integer(0);
@ManyToOne
private CentroCosto categoriaCentroCosto;
// we need two types of grouping - one centroCosto general for all of the accounts
// and second specific for each account
// (rubros presupuestales segun lo que define cada proyecto)
@ManyToOne
private Cuenta cuentaCentroCosto;
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public Cuenta getCuentaCentroCosto() {
return cuentaCentroCosto;
}
public void setCuentaCentroCosto(Cuenta cuentaCentroCosto) {
this.cuentaCentroCosto = cuentaCentroCosto;
}
public Integer getLevel() {
return level;
}
public void setLevel(Integer level) {
this.level = level;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public Boolean getIsLeaf() {
return isLeaf;
}
public void setIsLeaf(Boolean isLeaf) {
this.isLeaf = isLeaf;
}
public CentroCosto getCategoriaCentroCosto() {
return categoriaCentroCosto;
}
public void setCategoriaCentroCosto(CentroCosto categoriaCentroCosto) {
this.categoriaCentroCosto = categoriaCentroCosto;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are
// not set
if (!(object instanceof CentroCosto)) {
return false;
}
CentroCosto other = (CentroCosto) object;
if ((this.id == null && other.id != null)
|| (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "CentroCosto [id=" + id + ", isLeaf=" + isLeaf + ", codigo "+codigo+ ", nombre="
+ nombre + ", descripcion=" + descripcion
+ ", categoriaCentroCosto=" + categoriaCentroCosto +", cuenta "+cuentaCentroCosto+ "]";
}
}
|
Markdown
|
UTF-8
| 8,623 | 3.640625 | 4 |
[] |
no_license
|
# Lists and pattern matching
## Lists informally
Составные типы данных (compound data type).
Список — упорядоченная последовательность элементов (0 или больше). Могут содержать другие списки.
Списки придумали в Лиспе.
Лист — рекурсивный тип данных, определяется в терминах самого себя. Лист — это пустой лист (nil, null) или элемент за которым следует еще один список.
Из Racket: list is recursively defined: it is either the constant null, or it is a pair whose second value is a list.
Похоже, в Озе по-другому, чем в Липе. В лиспе все — пары, в Озе — последовательность.
```oz
declare
L = [1 2 3] % declaring list
{Browse L}
declare
M={Append L L} % append list L to L
{Browse M}
declare
N=nil % empty list
{Browse N}
```
Списки — значения. Они, как и простые типы в Oz, — значения и не могут быть изменены.
**В Oz списки могут содержать значения разных типов.** Это норма:
```oz
declare
L = [[1] 2 'a'] % ok
```
## Defining lists with grammar rules
Список — рекурсивный тип данных. То есть он определяется в своих же терминах (defined in terms of itself):
Список представляет собой либо пустой список (`nil`), либо пару элементов
определенного типа, за которой следует другой список. [Wiki](https://ru.wikipedia.org/wiki/Список_(информатика))
Рекурсия, помимо вычислений (в функциях), используется и в данных (определение типов данных).
Для обхода данных рекурсивных типов используются рекурсивные функции.
Синтаксическое представление списков в нотации [EBNF](https://ru.wikipedia.org/wiki/Расширенная_форма_Бэкуса_—_Наура):
```
<List T> ::= nil | T '|' <List T>
```
`|` — палка без скобок — это OR.
`'|'` — палка в скобках — это часть синтаксиса. То есть в Oz синтаксис для определения списка такой:
``` oz
declare
L = 1|2|3|nil % список из трех элементов
M = [1 2 3] % то же самое, синтаксический сахар, менее формально
{Browse L == M} % true
```
> And just like sugar is not usually good for you if you eat too much, too much syntactic sugar is not good for the clarity. But a little bit is good.
`1|2|3|nil` is equivalent to `1|(2|(3|nil))`. В Oz можно использовать скобки в списках для группировки.
Представление списка `[10 11 12]`:
```
nil
10 | nil
10 | 11 | nil
10 | 11 | 12 | nil
```
## Useful representations for lists
Можно представить список целых чисел (`<List <int>>`) вот так:
```
10 | <List <int>> # 10 и список
10 | 11 | <List <int>> # 10, 11 и список
10 | 11 | 12 | <List <int>> # 10, 11, 12 и список
10 | 11 | 12 | nil # в конце `<List <int>>` станет `nil`
```
Список — частный случай дерева. Графическое представление:
<img src="list_graph_example.png" width="300">
## Операции со списками
``` oz
X1 = [1 2 3]
{Browse X1.1} % 1, Head / car
{Browse X1.2} % [2 3], Tail / cdr
```
Рекурсивные функции хорошо работают с рекурсивными типами данных. Например, сумма элементов списка:
```
declare
fun {Sum L}
if L == nil then 0
else L.1 + {Sum L.2} end
end
{Browse {Sum [1 2 3]}}
```
Т. к. список — рекурсивная структура, то мы не можем напрямую взять N-й элемент.
## Calculating with lists
### Tail recursion for lists
Поэтапное создание списка:
``` oz
declare X1 X2 in
X1 = 6|X2
{Browse X1}
declare X3 in
X2 = 7|X3
X3 = nil
{Browse X1}
% Built in functions for lists
{Browse X1.1} % 6, head/car of list
{Browse X1.2} % [7|nil], tail/cdr of list
{Browse X1.2.1} % 7
```
Список — рекурсивная структура данных. Для работы с ним используются рекурсивные функции:
``` oz
% Recursive funciton on list
% Sum of elements
declare
fun {Sum L}
if L == nil then 0
else L.1 + {Sum L.2} end
end
{Browse {Sum X1}}
% Tail-recursive sum
declare
fun {SumT L Acc}
if L == nil then Acc
else {SumT L.2 Acc + L.1} end
end
{Browse {SumT X1 0}}
```
Получить N-й элемент списка напрямую нельзя, т. к. список — это значение, за которым следует еще один список. Нужно использовать рекурсию:
``` oz
% Nth element of a list
declare
fun {Nth L N}
if L == nil then 'Index is too big'
elseif N == 1 then L.1
else {Nth L.2 N - 1} end
end
declare
List = [4 1 8 9 5 7 3]
{Browse {Nth List 30}}
```
## Задача Fact
См. `fact.oz`.
Some of your friends may have already ask you to give the result of 5!. In this exercise, we will solve this problem: we will ask you to provide a list of factorial numbers, once for all! A factorial number x! is defined by: x! = x*(x-1)*(x-2)*...*1
This exercise is focused on the use of lists. Lists can be represented in several forms. For instance:
[a b c] == a|b|c|nil == '|'(1:a 2:'|'(1:b 2:'|'(1:c 2:nil)))
In this exercise, you are asked to produce a list containing the n first factorial number, starting with {Fact 1}. For instance, {Fact 4} has to return [1 2 6 24].
## Pattern Matching
``` oz
% Not tail recursive
declare
fun {Sum L}
case L
of H|T then H + {Sum T}
[] nil then 0
end
end
{Browse {Sum [5 6 7]}}
% Tail recursive
declare
fun {Sum2 L Acc}
case L
of H|T then {Sum2 T Acc + H}
[] nil then Acc
end
end
{Browse {Sum2 [5 6 7] 0}}
% Pattern engineering
% Make less recursive calls
declare
fun {Sum3 L Acc}
case L
% Здесь первый и второй паттерны пересекаются
% Нельзя их поменять местами, первый включается во второй
% В идеале все паттерны должны быть сами по себе
of H1|H2|T then {Sum3 T H1+H2+Acc} % хапаем по 2 элемента сразу
[] H|T then {Sum3 T Acc + H} % если двух не осталось, то берем один
[] nil then Acc
end
end
{Browse {Sum3 [5 6 7] 0}}
```
## List functions and the kernel language
Kernel languare — способ описать пардигму программирования. Так, любая программа, написанная в функциональном стиле может быть представлена в виде общих понятий kernel language.
Kernel languare для Oz (почти полный):
```
<s> ::= skip
| <s>1 <s>2
| local <x> in <s> end
| <x>1=<x>2
| <x>=<v>
| if <x> then <s>1 else <s>2 end
| proc {<x> <x>1 ... <x>n} <s> end | {<x> <y>1 ... <y>n}
| case <x> of <p> then <s>1 else <s>2 end
<v> ::= <number> | <list> | ...
<number> ::= <int> | <float>
<list>, <p> ::= nil | <x> | <x> ‘|’ <list>
```
## Append
``` oz
declare
fun {Append L1 L2}
case L1
of nil then L2
[] H|T then H|{Append T L2} end
end
{Browse {Append [1 2] [3 3 3]}}
```
Эта же функция на kernel language:
``` oz
declare
proc {Append L1 L2 L3}
case L1 of nil then L3=L2
else case L1 of H|T then
local T3 in % Unbound variable
L3=H|T3
{Append T L2 T3}
end
end
end
end
local R in {Append [1 2 5] [8 7 6] R}
{Browse R}
end
```
Благодаря тому, что изначально `T3` не определена функция `Append` является хвостовой рекурсией.
|
Java
|
UTF-8
| 4,913 | 1.90625 | 2 |
[] |
no_license
|
package com.oax.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.oax.common.AccessLimit;
import com.oax.common.AssertHelper;
import com.oax.common.ResultResponse;
import com.oax.context.HttpContext;
import com.oax.entity.front.vo.SnatchCoinVo;
import com.oax.entity.front.vo.SnatchConfigTypeVo;
import com.oax.entity.front.vo.SnatchDetailAggregateVo;
import com.oax.entity.front.vo.SnatchDetailVo;
import com.oax.form.SnatchAggregateForm;
import com.oax.service.activity.SnatchActivityService;
import com.oax.service.activity.SnatchConfigService;
import com.oax.service.activity.SnatchDetailService;
import com.oax.vo.SnatchActivityHomeVo;
import com.oax.vo.SnatchBetNumberVo;
import com.oax.vo.SnatchDetailPageVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
/**
* @Auther: hyp
* @Date: 2019/1/17 17:22
* @Description: 一元夺宝
*/
@RestController
@RequestMapping("/activity/snatch")
@Api(tags = { "Activity API" }, description = "活动相关的API")
public class SnatchActivityController {
@Autowired
private SnatchActivityService snatchActivityService;
@Autowired
private SnatchConfigService snatchConfigService;
@Autowired
private SnatchDetailService snatchDetailService;
//获取可参与抽奖的币种,相关说明
@GetMapping("/index/anon")
@ApiOperation("获取一元夺宝游戏首页相关数据")
public ResultResponse index(Integer coinId){
Integer userId = HttpContext.getUserId();
SnatchActivityHomeVo homeVo = snatchActivityService.index(coinId, userId);
return new ResultResponse(homeVo);
}
@PostMapping("/bet")
@ApiOperation("投注")
@AccessLimit(limit = 10, sec = 10)
public ResultResponse bet(Integer id, BigDecimal betQty){
AssertHelper.notEmpty(id, "id不能为空");
AssertHelper.notEmpty(betQty, "投注金额不能为空");
Integer userId = HttpContext.getUserId();
Map<String, Object> data = snatchActivityService.bet(id, userId, betQty, false);
return new ResultResponse(true, "投注成功", data);
}
@GetMapping("/lotteryMsg/anon")
@ApiOperation("获取开奖播报数据")
public ResultResponse listNewlyLottery(){
List<String> data = snatchActivityService.listNewlyLottery();
return new ResultResponse(true, data);
}
@GetMapping("/detailPage")
@ApiOperation("进入投注详情的页面")
public ResultResponse detailPage(){
Integer userId = HttpContext.getUserId();
SnatchDetailPageVo data = snatchActivityService.detailPage(userId);
return new ResultResponse(data);
}
@GetMapping("/listAllCoin")
@ApiOperation("获取所有币种列表")
public ResultResponse listAllCoin(){
List<SnatchCoinVo> list = snatchConfigService.listAllConfigCoin();
return new ResultResponse(list);
}
@GetMapping("/listConfigType")
@ApiOperation("获取某种币种的所有奖池数据")
public ResultResponse listConfigType(Integer coinId){
AssertHelper.notEmpty(coinId, "币种id不能为空");
List<SnatchConfigTypeVo> list = snatchConfigService.listConfigTypeByCoinId(coinId);
return new ResultResponse(list);
}
@GetMapping("/listAggregate")
@ApiOperation("获取投注聚合统计数据列表")
public ResultResponse listAggregate(SnatchAggregateForm form){
AssertHelper.notEmpty(form.getConfigId(), "奖池类别不能为空");
Integer userId = HttpContext.getUserId();
Page<SnatchDetailAggregateVo> pageData = snatchDetailService.listAggregateVoByUserIdAndConfigId(userId, form);
return new ResultResponse(pageData);
}
@GetMapping("/listMyDetail")
@ApiOperation("获取我的某期投注记录")
public ResultResponse listMyDetail(Integer activityId){
AssertHelper.notEmpty(activityId, "奖池期号");
Integer userId = HttpContext.getUserId();
SnatchBetNumberVo data = snatchActivityService.listMyDetail(userId, activityId);
return new ResultResponse(data);
}
@GetMapping("/listWin")
@ApiOperation("获取某期的开奖编号记录")
public ResultResponse listWin(Integer activityId){
AssertHelper.notEmpty(activityId, "奖池期号");
Integer userId = HttpContext.getUserId();
List<SnatchDetailVo> list = snatchDetailService.listWinVo(userId, activityId);
return new ResultResponse(list);
}
}
|
JavaScript
|
UTF-8
| 1,187 | 3.578125 | 4 |
[
"MIT"
] |
permissive
|
/**
* Created by Vladi on 23-Oct-16.
*/
function reducers(input) {
console.log(`Sum = ${input.reduce((a,b) => a+b)}`)
}
function commands(input) {
let commandProcessor = (function() {
let string =''
return {
append: function (str) {
string+=str
},
removeStart: function (index) {
string = string.substring(index, string.length)
},
removeEnd: function (index) {
string = string.substring(0,string.length-index)
},
print: function () {
console.log(string)
}
}
})()
for(let line of input){
let [first, second] = line.split(' ')
if(first=='append'){
commandProcessor.append(second)
}
else if(first=='removeStart'){
commandProcessor.removeStart(Number(second))
}
else if(first=='removeEnd'){
commandProcessor.removeEnd(Number(second))
}
else if (first=='print'){
commandProcessor.print()
}
}
}
function maxElement(arr) {
return Math.max.apply(null, arr);
}
|
Java
|
UTF-8
| 3,170 | 3.078125 | 3 |
[] |
no_license
|
package tda;
public class Lista<T> {
private Nodo<T> primerNodo;
private Nodo<T> ultimoNodo;
private int cantidadElementos;
public Lista() {
this.primerNodo = this.ultimoNodo = null;
this.cantidadElementos = 0;
}
protected boolean pushBack(T obj) {
Nodo<T> nuevoNodo = new Nodo<T>(obj, null);
if (this.cantidadElementos == 0) {
this.primerNodo = nuevoNodo;
} else {
this.ultimoNodo.setSig(nuevoNodo);
}
this.ultimoNodo = nuevoNodo;
this.cantidadElementos++;
return true;
}
protected boolean pushFront(T obj) {
Nodo<T> nuevoNodo = new Nodo<T>(obj, this.primerNodo);
if (this.cantidadElementos == 0) {
this.ultimoNodo = nuevoNodo;
}
this.primerNodo = nuevoNodo;
this.cantidadElementos++;
return true;
}
protected T popBack() {
if (this.cantidadElementos == 0)
return null;
Nodo<T> lectura = this.primerNodo;
while (lectura.getSig() != this.ultimoNodo) {
// ESTOY RECORRIENDO LOS NODOS
lectura.setSig(lectura.getSig());
}
if (this.cantidadElementos == 1) {
this.primerNodo = this.ultimoNodo = null;
this.cantidadElementos--;
return lectura.getInfo();
} else {
T auxiliar = lectura.getSig().getInfo();
lectura.setSig(null);
this.ultimoNodo = lectura;
this.cantidadElementos--;
return auxiliar;
}
}
protected T popFront() {
if (cantidadElementos == 0)
return null;
T auxiliar = this.primerNodo.getInfo();
this.primerNodo = this.primerNodo.getSig();
if (this.cantidadElementos == 1)
this.ultimoNodo = this.primerNodo;
this.cantidadElementos--;
return auxiliar;
}
protected T erase(int posicion) {
if (this.cantidadElementos <= posicion || posicion < 0)
return null;
T auxiliar;
if (posicion == 0) {
auxiliar = this.primerNodo.getInfo();
this.primerNodo = this.primerNodo.getSig();
} else {
Nodo<T> lectura = this.primerNodo;
for (int i = 0; i < posicion - 1; i++) {
lectura = lectura.getSig();
}
auxiliar = lectura.getSig().getInfo();
lectura.setSig(lectura.getSig().getSig());
if (this.cantidadElementos - 1 == posicion) {
this.ultimoNodo = lectura;
}
}
this.cantidadElementos--;
return auxiliar;
}
protected T buscar(T dato) {
Nodo<T> lectura = this.primerNodo;
while (lectura != null && !lectura.compararInformacion(dato))
lectura = lectura.getSig();
return lectura == null ? null : lectura.getInfo();
}
protected T buscar(int posicion) {
if (this.cantidadElementos <= posicion || posicion < 0) {
return null;
}
Nodo<T> auxiliar = this.primerNodo;
for (int i = 0; i < posicion; i++) {
auxiliar = auxiliar.getSig();
}
return auxiliar.getInfo();
}
public void vaciar() {
this.primerNodo = this.ultimoNodo = null;
this.cantidadElementos = 0;
}
// vacia
public boolean empty() {
return this.cantidadElementos == 0;
}
protected void reverse() {
Nodo<T> lectura = this.primerNodo;
while (lectura != null && lectura.getSig() != null) {
Nodo<T> aux = lectura.getSig();
lectura.setSig(aux.getSig());
aux.setSig(this.primerNodo);
this.primerNodo = aux;
}
}
protected int getCantidadElementos(){
return this.cantidadElementos;
}
}
|
Python
|
UTF-8
| 2,638 | 2.703125 | 3 |
[
"Apache-2.0"
] |
permissive
|
# Copyright (c) 2021. Alexander Hermes
import logging
import uuid
from collections import deque
from Changeset import Changeset
from Release import Release
logger = logging.getLogger(__name__)
class PQScheduler:
"""
Scheduler with a single queue but where queued requests can progress
in parallel with the front of the queue (but ot exit the queue).
That is, requests are serviced in parallel but only released on at a time
"""
def __init__(self):
self.active_q: deque[Release] = deque() # represents FIFO queue
self.done_q: list[Release] = list()
self.tick: int = 0 # Simulation tick
def accept_changeset(self, cs: Changeset):
# This scheduler runs changesets in parallel, but only releases from the front
# This means that new changesets must contain all of the changes contained
# in changesets that are already queued. Therefore, we need to compile the
# union of all the changed modules
# However, we don't need to union the tests modules as we only need to validate the
# new changes (previous changes were validated by previous changesets).
mod_cs = Changeset(
changed_modules=set.union(cs.changed_modules, *(r.changeset.changed_modules for r in self.active_q)),
modules_to_test=cs.modules_to_test
)
logger.debug("Incoming changeset: %s, queued changeset: %s", cs, mod_cs)
r = Release(name=f"R-{uuid.uuid4().hex}", changeset=mod_cs, queued_time=self.tick)
self.active_q.append(r)
def process_tick(self, new_tick: int):
self.tick = new_tick
if len(self.active_q) <= 0:
logger.debug("Processing requested, but queue empty, nothing to do")
return
# All of the releases in the queue get to progress
for r in self.active_q:
r.process_tick(new_tick)
# But only the front of the queue gets to release
current = self.active_q[0]
if current.is_done():
logger.info("Release %s complete, moving to done list", current)
current.mark_released(new_tick)
self.done_q.append(self.active_q.popleft())
logger.debug("Processed tick %s. Remaining active requests: %s, Done: %s",
new_tick, len(self.active_q), len(self.done_q))
def idle(self):
"""
Whether or not this scheduler is doing anything
:return: true if scheduler is idle (no active requests), false otherwise
"""
return len(self.active_q) == 0
def get_results(self) -> list[Release]:
return self.done_q
|
Markdown
|
UTF-8
| 2,151 | 3.21875 | 3 |
[
"Apache-2.0"
] |
permissive
|
---
id: api-react-components-results-per-page
slug: /search-ui/api/react/components/results-per-page
title: ResultsPerPage
date: 2022-02-27
tags: ["demo"]
---
Shows a dropdown for selecting the number of results to show per page.
Uses [20, 40, 60] as default options. You can use `options` prop to pass custom options.
**Note:** When passing custom options make sure one of the option values match
the current `resultsPerPageProp` value, which is 20 by default.
To override `resultsPerPage` default value, use the <DocLink id="api-react-search-provider" section="initial-state" text="initial state" /> property.
### Example
```jsx
import { ResultsPerPage } from "@elastic/react-search-ui";
...
<ResultsPerPage />
```
### Example using custom options
```jsx
import { SearchProvider, ResultsPerPage } from "@elastic/react-search-ui";
<SearchProvider
config={
...
initialState: {
resultsPerPage: 5
}
}
>
<ResultsPerPage options={[5, 10, 15]} />
</SearchProvider>
```
### Properties
| Name | Description |
| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| className | |
| options | Dropdown options to select the number of results to show per page. |
| view | Used to override the default view for this Component. See <DocLink id="guides-customizing-styles-and-html" section="customizing-html" text="Customization: Component views and HTML" /> for more information. |
|
Java
|
UTF-8
| 1,317 | 2.5625 | 3 |
[] |
no_license
|
package org.springproject.db;
import java.io.Serializable;
import java.util.ArrayList;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Posts implements Serializable{
@Id
private int id;
private String name;
private int price;
private int vehicle_fk;
private String descrption;
private String picture;
public Posts() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getVehicle_fk() {
return vehicle_fk;
}
public void setVehicle_fk(int vehicle_fk) {
this.vehicle_fk = vehicle_fk;
}
public String getDescrption() {
return descrption;
}
public void setDescrption(String descrption) {
this.descrption = descrption;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
@Override
public String toString() {
return "Posts [id=" + id + ", name=" + name + ", price=" + price + ", vehicle_fk=" + vehicle_fk
+ ", descrption=" + descrption + ", picture=" + picture + "]";
}
}
|
PHP
|
UTF-8
| 754 | 2.59375 | 3 |
[] |
no_license
|
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
protected $table = 'usuario';
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'id','email', 'password','id_perfil'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
// Relación uno a uno
public function perfil() {
return $this->hasOne('App\Perfil', 'idPerfil'); // Le indicamos que se va relacionar con la tabla perfil y su atributo idPerfil
}
}
|
Java
|
UTF-8
| 885 | 2.3125 | 2 |
[] |
no_license
|
package uk.co.datadisk.ddflix.entities.user;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import uk.co.datadisk.ddflix.entities.AbstractDomainClass;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.HashSet;
import java.util.Set;
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(exclude = {"addresses", "country"}, callSuper = false)
@Entity
@Table(name = "cities")
public class City extends AbstractDomainClass {
@NotNull
@Column(name = "city")
private String city;
@ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinColumn(name = "country_id")
private Country country;
@OneToMany(mappedBy = "city")
private Set<Address> addresses = new HashSet<>();
@Override
public String toString(){
return city;
}
}
|
Markdown
|
UTF-8
| 2,834 | 3.3125 | 3 |
[] |
no_license
|
# jsPsych Template
jsPsych is a framework for web-based experiments that is particularly useful for vision science.
The following jsPsych template is built for the DML and also includes a framework for a web server for testing purposes, separate source and public trees, and standard html for an intro and outro.
# How To Install
1. Branch this repository and download the branch onto your computer.
2. If you don't already have Node.js on your computer, install it from: [Download link](https://nodejs.org/en/download/)
3. In terminal, navigate to the new repository and run the command:
```
npm install
```
# How To Run Experiments
Follow the next step to create a local HTTPS server. **You must complete installation to perform these steps.**
1. In terminal, navigate to the folder you have been coding in (default name jsPsychTemplate) and run the following command:
```
npm run experiment
```
**The server will close if you close the tab in which you ran the previous command. You will have to repeat step 1 each time you want to run the experiment.**
2. In the browser, navigate to this URL:
[Localhost](http://localhost:8000/)
3. You may need to select the public folder from there. Once you've done that, you'll be at the index.html file and at the start of the program :)
# How To Update Your Experiment
This folder has two trees; the source tree (the src file) and the public tree (the public file). The code run by your participants is in the public folder. You will work in the src folder (i.e. you will edit all of your js files in the src folder) and then use a program to transfer these changes to the public folder.
1. When you make any changes, run the following command in terminal:
```
npm run build
```
After you've run this command, you will have rebuilt the public tree including any new changes, and these changes will be reflected in the local server.
# How To Code in Development Mode (Auto-Updating As You Go)
The benefit of having a separate source and public tree is the ability to check your work during the building of the public tree. The Babel system that does the building looks for typos and other types of logical and syntactical errors along the way. The system will alert you if it finds these erorrs and "fail" to build. Essentially, the program finds problems for you and points out exactly what and where they are.
While you are editing your code in the source folder, run the following command:
```
npm run dev
```
This command will start a program to re-run the build command every time a file in the source tree is re-saved. In other words, every time you save your work in the source tree (any file!), this program will try to build the public tree again and will alert you of any potential errors. Use this while you work to both save time and generate better code!
|
Java
|
UTF-8
| 7,429 | 2.125 | 2 |
[] |
no_license
|
package com.hp.cc.util;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.KeyManagementException;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMReader;
import org.bouncycastle.openssl.PasswordFinder;
import com.hp.cc.msg.mqtt.MyTrustManager;
public class SslUtil {
// options.setSocketFactory(SslUtil.getSocketFactory("/UserProfile/ca/ca.crt",
// "/UserProfile/ca/client.crt", "/UserProfile/ca/client.key", "123456"));
public static SSLSocketFactory getSocketFactory(final String caCrtFile, final String crtFile, final String keyFile,
final String password) throws Exception {
Security.addProvider(new BouncyCastleProvider());
// load CA certificate
PEMReader reader = new PEMReader(
new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(caCrtFile)))));
X509Certificate caCert = (X509Certificate) reader.readObject();
reader.close();
// load client certificate
reader = new PEMReader(new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(crtFile)))));
X509Certificate cert = (X509Certificate) reader.readObject();
reader.close();
// load client private key
reader = new PEMReader(new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(keyFile)))),
new PasswordFinder() {
@Override
public char[] getPassword() {
return password.toCharArray();
}
});
KeyPair key = (KeyPair) reader.readObject();
reader.close();
// CA certificate is used to authenticate server
KeyStore caKs = KeyStore.getInstance(KeyStore.getDefaultType());
caKs.load(null, null);
caKs.setCertificateEntry("ca-certificate", caCert);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(caKs);
// client key and certificates are sent to server so it can authenticate us
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null, null);
ks.setCertificateEntry("certificate", cert);
ks.setKeyEntry("private-key", key.getPrivate(), password.toCharArray(),
new java.security.cert.Certificate[] { cert });
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, password.toCharArray());
// finally, create SSL socket factory
// SSLContext context = SSLContext.getInstance("TLSv1");
SSLContext context = SSLContext.getInstance("TLSv1.2");
context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
return context.getSocketFactory();
}
public static SSLSocketFactory getSocketFactory(final String caCrtFile) throws Exception {
Security.addProvider(new BouncyCastleProvider());
// load CA certificate
PEMReader reader = new PEMReader(
new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(caCrtFile)))));
X509Certificate caCert = (X509Certificate) reader.readObject();
reader.close();
// CA certificate is used to authenticate server
KeyStore caKs = KeyStore.getInstance(KeyStore.getDefaultType());
caKs.load(null, null);
caKs.setCertificateEntry("ca-certificate", caCert);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(caKs);
// finally, create SSL socket factory
SSLContext context = SSLContext.getInstance("TLSv1.2");
context.init(null, tmf.getTrustManagers(), null);
return context.getSocketFactory();
}
/**
* 信任服务端任何证书
* @return
* @throws KeyManagementException
* @throws NoSuchAlgorithmException
*/
public static SSLSocketFactory getSocketFactory() throws KeyManagementException, NoSuchAlgorithmException {
TrustManager[] trustManagers = new TrustManager[1];
TrustManager tm = new MyTrustManager();
trustManagers[0] = tm;
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, trustManagers, null);
return sslContext.getSocketFactory();
}
// getSSLSocktet("F:/ssl/ca.crt","F:/ssl/client.crt","F:/ssl/client.pem","brt123");
public static SSLSocketFactory getSocketFactory2(String caPath, String crtPath, String keyPath, String password)
throws Exception {
// CA certificate is used to authenticate server
CertificateFactory cAf = CertificateFactory.getInstance("X.509");
FileInputStream caIn = new FileInputStream(caPath);
X509Certificate ca = (X509Certificate) cAf.generateCertificate(caIn);
KeyStore caKs = KeyStore.getInstance("JKS");
caKs.load(null, null);
caKs.setCertificateEntry("ca-certificate", ca);
TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
tmf.init(caKs);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
FileInputStream crtIn = new FileInputStream(crtPath);
X509Certificate caCert = (X509Certificate) cf.generateCertificate(crtIn);
crtIn.close();
// client key and certificates are sent to server so it can authenticate
// us
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
// ks.load(caIn,password.toCharArray());
ks.load(null, null);
ks.setCertificateEntry("certificate", caCert);
ks.setKeyEntry("private-key", getPrivateKey(keyPath), password.toCharArray(),
new java.security.cert.Certificate[] { caCert });
KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX");
kmf.init(ks, password.toCharArray());
// keyIn.close();
// finally, create SSL socket factory
SSLContext context = SSLContext.getInstance("TLSv1");
context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
return context.getSocketFactory();
}
public static PrivateKey getPrivateKey(String path) throws Exception {
Base64 base64 = new Base64();
byte[] buffer = base64.decode(getPem(path));
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
}
private static String getPem(String path) throws Exception {
FileInputStream fin = new FileInputStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(fin));
String readLine = null;
StringBuilder sb = new StringBuilder();
while ((readLine = br.readLine()) != null) {
if (readLine.charAt(0) == '-') {
continue;
} else {
sb.append(readLine);
sb.append('\r');
}
}
fin.close();
return sb.toString();
}
}
|
JavaScript
|
UTF-8
| 540 | 2.640625 | 3 |
[] |
no_license
|
var getmac = require('getmac');
var fs = require('fs');
function getMacAddr(callback) {
var getmacCallback = function (err, macAddr) {
if (err) {
errlog.error(err);
setTimeout(() => {
getmac.getMac(getmacCallback);
},5000);
return;
}
if(macAddr){
// 소문자로 변환
// '-'를 ':'로 변환
macAddr = macAddr.toLowerCase().replace(/-/g, ':');
if (typeof callback === 'function') {
callback(macAddr);
}
}
};
getmac.getMac(getmacCallback);
}
module.exports = getMacAddr;
|
C#
|
UTF-8
| 7,717 | 2.984375 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
/*Name : Gursharan Singh
*Student Id : 300931676
* Date : 10th August,2017
* Description : This is the BMI calculator for calculating body mass index
* Version : 1.8 Refactored the BMI calculator class
*/
namespace Comp123_Assignmnet5
{
public partial class BMICalculator : Form
{
//Private Instance Variables
private double _height;
private double _weight;
private double _bmi;
//Public Properties
public double Height
{
get
{
return this._height;
}
set
{
this._height = value;
}
}
public double Weight
{
get
{
return this._weight;
}
set
{
this._weight = value;
}
}
public double Bmi
{
get
{
return this._bmi;
}
set
{
this._bmi = value;
}
}
public BMICalculator()
{
InitializeComponent();
}
private void ImperialRadioButton_CheckedChanged(object sender, EventArgs e)
{
RadioButton imperialButton = sender as RadioButton;
if (imperialButton.Checked)
{
MyHeightTextBox.Text = "Inches";
MyWeightTextBox.Text = "Pounds";
}
else
{
MyHeightTextBox.Text = "Metres";
MyWeightTextBox.Text = "kilograms";
}
}
private void BMIButton_Click(object sender, EventArgs e)
{
Button button = sender as Button;
this.Height = _convert(MyHeightTextBox.Text);
this.Weight = _convert(MyHeightTextBox.Text);
if (ImperialRadioButton.Checked)
{
this.Bmi = Math.Round(((this.Weight * 703) / Math.Pow(this.Height, 2)), 1);
}
else if (MetricRadioButton.Checked)
{
this.Bmi = Math.Round(((this.Weight) / (this.Height * this.Height)), 1);
}
textBox.Text = Bmi.ToString();
_scale();
}
private void _scale()
{
BMITextBox.Text = "You are : ";
if (this.Bmi <= 18.5)
{
BMITextBox.Text += "Underweight";
BMITextBox.BackColor = Color.Red;
}
else if (this.Bmi > 18.5 && this.Bmi <= 24.9)
{
BMITextBox.Text += "Normal";
BMITextBox.BackColor = Color.Green;
}
else if (this.Bmi >= 25 && this.Bmi <= 29.9)
{
BMITextBox.Text += "Overweight";
BMITextBox.BackColor = Color.Orange;
}
else
{
BMITextBox.Text += "Obese";
BMITextBox.BackColor = Color.OrangeRed;
}
}
/// <summary>
/// This method converts input text of string datatype to decimal
/// </summary>
/// <param name="inputText"></param>
/// <returns></returns>
private double _convert(string inputText)
{
try
{
return Convert.ToDouble(inputText);
}
catch (Exception exception)
{
Debug.WriteLine("An Error Occurred");
Debug.WriteLine(exception.Message);
}
return 0;
}
/// <summary>
/// This is the event handler for closing the form
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BMICalculator_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
}
/// <summary>
/// This is refrenced from stacxkoverflow
/// It Handle the appropriate keyboard events to prevent anything
/// but numeric input.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MyHeightTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.'))
{
e.Handled = true;
}
// only allow one decimal point
if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
{
e.Handled = true;
}
}
private void MyWeightTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.'))
{
e.Handled = true;
}
// only allow one decimal point
if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
{
e.Handled = true;
}
}
/// <summary>
/// This is the reset button method that resets the form
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ResetButton_Click(object sender, EventArgs e)
{
MyWeightTextBox.Text = "";
MyWeightTextBox.Text = "";
textBox.Text = "";
BMITextBox.Text = "";
BMITextBox.BackColor = Color.White;
}
/// <summary>
/// This method acts as a placeholder
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MyHeightTextBox_Enter(object sender, EventArgs e)
{
{
MyHeightTextBox.Text = "";
}
}
private void MyHeightTextBox_Leave(object sender, EventArgs e)
{
if (ImperialRadioButton.Checked)
{
if (MyHeightTextBox.Text == "")
{
MyHeightTextBox.Text = "Inches";
}
else
{
return;
}
}
else if (MetricRadioButton.Checked)
{
if (MyHeightTextBox.Text == "")
{
MyHeightTextBox.Text = "Meters";
}
else
{
return;
}
}
}
private void MyWeightTextBox_Enter(object sender, EventArgs e)
{
MyWeightTextBox.Text = "";
}
private void MyWeightTextBox_Leave(object sender, EventArgs e)
{
if (ImperialRadioButton.Checked)
{
if (MyWeightTextBox.Text == "")
{
MyWeightTextBox.Text = "Pounds";
}
else
{
return;
}
}
else if(MetricRadioButton.Checked)
{
if (MyWeightTextBox.Text == "")
{
MyWeightTextBox.Text = "Kilograms";
}
else
{
return;
}
}
}
}
}
|
Markdown
|
UTF-8
| 1,374 | 2.546875 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
<img src="https://atsign.dev/assets/img/@developersmall.png?sanitize=true">
### Now for some internet optimism.
# at_contacts_flutter
A flutter plugin project for CRUD operations on contacts.
## Getting Started
This plugin can be added to the project as git dependency in pubspec.yaml
```
dependencies:
at_contacts_flutter: ^1.0.0
```
### Plugin description
This plugin provides two screens:
#### Contacts
This lists the contacts. From this screen a new contact can be added. Also, an existing contact can be blocked or deleted.
#### Blocked Contacts
This screen lists the blocked contacts. It also gives the option to unblock a contact in it.
### Sample usage
It is expected that the app will first create an AtClientService instance and authenticate an atsign.
The contacts service needs to be initialised with the `atClient` from the `AtClientService`, current atsign and the root server.
```
initializeContactsService(
clientSdkService.atClientServiceInstance.atClient, currentAtSign,
rootDomain: MixedConstants.ROOT_DOMAIN);
```
Navigating to the contacts or blocked contacts is done simply by using:
```
Navigator.of(context).push(MaterialPageRoute(
builder: (BuildContext context) => ContactsScreen(),
));
```
or
```
Navigator.of(context).push(MaterialPageRoute(
builder: (BuildContext context) => BlockedScreen(),
));
```
|
C
|
UTF-8
| 2,678 | 3.015625 | 3 |
[] |
no_license
|
#include "pokemon.h"
#include <stdio.h>
#include <string.h>
void loadPokemonList(char* pokemon_list[], unsigned int pokemon_type[]) {
FILE *pokemon_list_p;
if(( pokemon_list_p=fopen("pokemon_list", "r") )==NULL) {
printf("pokemon_list 파일이 없습니다.\n");
exit(1);
}
fscanf(pokemon_list_p, "%*[^\n]\n");
unsigned int i;
for(i=0; i<POKELIST_MAX; i++) {
pokemon_list[i]=malloc(sizeof(char *));
fscanf(pokemon_list_p, "%u|%s\n", &pokemon_type[i], pokemon_list[i]);
}
fclose(pokemon_list_p);
}
void saveData(User* user) {
FILE *save_data;
unsigned int i;
if((save_data=fopen("save_data", "w"))==NULL) {
printf("save_data 파일이 없습니다.\n");
exit(1);
}
encrypt(user->name);
fprintf(save_data, "%s\n", user->name);
fprintf(save_data, "%2d\n", user->numOfPokemon^KEY);
for(i=0; i < user->numOfPokemon; i++) {
encrypt(user->my_pokemon[i]->name);
encrypt(user->my_pokemon[i]->nickName);
fprintf(save_data, "%s %s %2d %4d %4d %3d %3d\n",
user->my_pokemon[i]->name, user->my_pokemon[i]->nickName,
user->my_pokemon[i]->type^KEY,
user->my_pokemon[i]->cur_hp^KEY, user->my_pokemon[i]->default_hp^KEY,
user->my_pokemon[i]->cur_atk^KEY, user->my_pokemon[i]->default_atk^KEY);
}
decrypt(user->name);
for(i=0; i < user->numOfPokemon; i++) {
decrypt(user->my_pokemon[i]->name);
decrypt(user->my_pokemon[i]->nickName);
}
fclose(save_data);
}
void loadData(User* user) {
FILE *save_data;
unsigned int i;
if((save_data=fopen("save_data", "r"))==NULL) {
printf("save_data 파일이 없습니다.\n");
exit(1);
}
fscanf(save_data, "%s\n", user->name);
decrypt(user->name);
fscanf(save_data, "%2d\n", &user->numOfPokemon);
user->numOfPokemon^=KEY;
for(i=0; i<user->numOfPokemon; i++)
user->my_pokemon[i]=(Pokemon *)malloc(sizeof(Pokemon));
// Pokedex Load
for(i=0 ; i<user->numOfPokemon ; i++) {
fscanf(save_data, "%s %s %2d %4d %4d %3d %3d\n",
user->my_pokemon[i]->name, user->my_pokemon[i]->nickName,
&user->my_pokemon[i]->type,
&user->my_pokemon[i]->cur_hp, &user->my_pokemon[i]->default_hp,
&user->my_pokemon[i]->cur_atk, &user->my_pokemon[i]->default_atk);
decrypt(user->my_pokemon[i]->name);
decrypt(user->my_pokemon[i]->nickName);
user->my_pokemon[i]->type^=KEY;
user->my_pokemon[i]->cur_hp^=KEY;
user->my_pokemon[i]->default_hp^=KEY;
user->my_pokemon[i]->cur_atk^=KEY;
user->my_pokemon[i]->default_atk^=KEY;
}
fclose(save_data);
}
void encrypt(char *str) {
unsigned int len = strlen(str);
unsigned int i;
for(i=0 ; i<len; i++) str[i]^=KEY;
}
void decrypt(char *enc_str) {
unsigned int len = strlen(enc_str);
unsigned int i;
for(i=0 ; i<len; i++) enc_str[i]^=KEY;
}
|
Python
|
UTF-8
| 2,406 | 2.734375 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
"""
marker dialog
"""
import tkinter as tk
from tkinter import ttk
from typing import TYPE_CHECKING
from core.gui.dialogs.colorpicker import ColorPickerDialog
from core.gui.dialogs.dialog import Dialog
from core.gui.graph import tags
if TYPE_CHECKING:
from core.gui.app import Application
MARKER_THICKNESS = [3, 5, 8, 10]
class MarkerDialog(Dialog):
def __init__(self, app: "Application", initcolor: str = "#000000"):
super().__init__(app, "Marker Tool", modal=False)
self.color = initcolor
self.radius = MARKER_THICKNESS[0]
self.marker_thickness = tk.IntVar(value=MARKER_THICKNESS[0])
self.draw()
def draw(self):
button = ttk.Button(self.top, text="clear", command=self.clear_marker)
button.grid(row=0, column=0, sticky="nsew")
frame = ttk.Frame(self.top)
frame.columnconfigure(0, weight=1)
frame.columnconfigure(1, weight=4)
frame.grid(row=1, column=0, sticky="nsew")
label = ttk.Label(frame, text="Thickness: ")
label.grid(row=0, column=0, sticky="nsew")
combobox = ttk.Combobox(
frame,
textvariable=self.marker_thickness,
values=MARKER_THICKNESS,
state="readonly",
)
combobox.grid(row=0, column=1, sticky="nsew")
combobox.bind("<<ComboboxSelected>>", self.change_thickness)
frame = ttk.Frame(self.top)
frame.columnconfigure(0, weight=1)
frame.columnconfigure(1, weight=4)
frame.grid(row=2, column=0, sticky="nsew")
label = ttk.Label(frame, text="Color: ")
label.grid(row=0, column=0, sticky="nsew")
label = ttk.Label(frame, background=self.color)
label.grid(row=0, column=1, sticky="nsew")
label.bind("<Button-1>", self.change_color)
def clear_marker(self):
canvas = self.app.canvas
canvas.delete(tags.MARKER)
def change_color(self, event: tk.Event):
color_picker = ColorPickerDialog(self, self.app, self.color)
color = color_picker.askcolor()
event.widget.configure(background=color)
self.color = color
def change_thickness(self, event: tk.Event):
self.radius = self.marker_thickness.get()
def show(self):
super().show()
self.geometry(
f"+{self.app.canvas.winfo_rootx()}+{self.app.canvas.master.winfo_rooty()}"
)
|
JavaScript
|
UTF-8
| 2,376 | 2.796875 | 3 |
[] |
no_license
|
//Require Express and Use it.
var express = require('express');
var app = express();
//Require BodyParser.
var bodyParser = require("body-parser");
//Require Morgan to show logger.
var logger = require("morgan");
//Require Mongoose to build MongoDB schema.
var mongoose = require("mongoose");
//Require My Model.
var News = require("./models/News.js");
// Sets an initial port. I'll use this later in my listener
var PORT = process.env.PORT || 3000;
//Require socket.io and http for it.
var http = require('http').Server(app);
var io = require('socket.io')(http);
//Using morgan.
app.use(logger("dev"));
//Using bodyParser and express.
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.text());
app.use(bodyParser.json({ type: "application/vnd.api+json" }));
app.use(express.static("public"));
//Initiate mongodb and use it.
mongoose.connect("mongodb://heroku_nxlnjpth:g97du67pdnjfbauk74cmpu4cd7@ds117913.mlab.com:17913/heroku_nxlnjpth");
var db = mongoose.connection;
db.on("error", function(err) {
console.log("Mongoose Error: ", err);
});
db.once("open", function() {
console.log("Mongoose connection successful.");
});
//Initiate socket.io.
io.on('connection', function(socket) {
console.log('a user connected');
});
//HTML Route
app.get("/", function(req, res) {
res.sendFile(__dirname + "/public/index.html");
});
//---------------------------------API Routes------------------------------//
app.get("/api/saved", function(req, res) {
News.find({})
.exec(function(err, doc) {
if (err) {
console.log(err);
} else {
res.json(doc);
}
});
});
app.post("/api/saved", function(req, res) {
console.log("req.body.data");
var dataTosave = new News(req.body.data);
dataTosave.save(function(err) {
if (err) return handleError(err);
console.log("Saved!!");
});
});
app.delete("/api/saved/:head", function(req, res) {
var newsTodelete = req.params;
console.log(req.params.head);
News.remove({ head: newsTodelete.head }, function(err) {
if (err) return handleError(err);
console.log("// removed!!!");
});
});
//-------------------------End of API Routes-----------------------------------//
//Port Listening.
http.listen(PORT, function() {
console.log("App listening on PORT " + PORT);
});
|
C
|
UTF-8
| 2,798 | 4.15625 | 4 |
[] |
no_license
|
#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>
void print_array(int size, int array[size]);
bool check_arrays_equal(int size, int array_a[size], int array_b[size]);
void swap(int array[], int i, int j);
void quick_sort(int array[], int left, int right);
int partition(int array[], int left, int right);
int main(int argc, char* argv[argc+1]) {
if (argc == 1) {
// use simple array if there are no arguments
int array[] = {1, 5, 3, 9, 2, -2, 6};
int array_size = sizeof(array) / sizeof(array[0]);
print_array(array_size, array);
// sort the array
quick_sort(array, 0, array_size-1);
print_array(array_size, array);
// compare the sorted result to the correct solution
int sorted_array[] = {-2, 1, 2, 3, 5, 6, 9};
if (check_arrays_equal(array_size, array, sorted_array)) {
printf("Success!\n");
} else {
printf("Failed!\n");
}
} else {
int array_size = argc - 1;
int array[array_size];
// get array from arguments
for (int i = 0; i < array_size; ++i) {
array[i] = atoi(argv[i+1]);
}
print_array(array_size, array);
// sort the array
quick_sort(array, 0, array_size-1);
print_array(array_size, array);
}
return EXIT_SUCCESS;
}
void quick_sort(int array[], int left, int right) {
if (left < right) {
// pick a pivot and put it in the right place
int pivot_i = partition(array, left, right);
// quick sort each side of the pivot
quick_sort(array, left, pivot_i-1);
quick_sort(array, pivot_i+1, right);
}
}
int partition(int array[], int left, int right) {
// pick the pivot to be the last element
int pivot_i = right;
int pivot = array[pivot_i];
int smaller_i = left-1; // index of element directly smaller than pivot
// move elements smaller than the pivot the left
for (int i = left; i < right; ++i) {
if (array[i] < pivot) {
smaller_i++;
swap(array, smaller_i, i);
}
}
// swap the pivot with the element after the smaller elements
swap(array, pivot_i, smaller_i+1);
// print_array(7, array);
return smaller_i+1;
}
void swap(int array[], int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
void print_array(int size, int array[size]) {
for (int i = 0; i < size-1; ++i) {
printf("%d, ", array[i]);
}
printf("%d\n", array[size-1]);
}
bool check_arrays_equal(int size, int array_a[size], int array_b[size]) {
for (int i = 0; i < size; ++i) {
if (array_a[i] != array_b[i]) {
return false;
}
}
return true;
}
|
Java
|
UTF-8
| 1,534 | 3.3125 | 3 |
[] |
no_license
|
package com.JavaCode.nd.nd2.nd2_tankas;
public class Tank {
private int positionA;
private int positionB;
private int shotsFired;
private String face;
public Tank(int positionA, int positionB, int shotsFired, String face) {
this.positionA = positionA;
this.positionB = positionB;
this.shotsFired = shotsFired;
this.face = face;
}
public void moveForward(){
this.positionA++;
this.face = "North";
}
public void moveBackwards(){
this.positionA--;
this.face = "South";
}
public void moveLeft(){
this.positionB--;
this.face = "West";
}
public void moveRight(){
this.positionB++;
this.face = "East";
}
public void restart(){
this.positionA = 0;
this.positionB = 0;
}
public String fire(){
this.shotsFired++;
switch (this.face){
case "North":
return "Shot to North";
case "South":
return "Shot to South";
case"West":
return "Shot to West";
case "East":
return "Shot to East";
default:
return "You have not moved yet";
}
}
public int getPositionA() {
return positionA;
}
public int getPositionB() {
return positionB;
}
public int getShotsFired() {
return shotsFired;
}
public String getFace() {
return face;
}
}
|
C++
|
SHIFT_JIS
| 2,962 | 2.8125 | 3 |
[] |
no_license
|
/* wb_t@C */
#include "OptionWaitOwnCrashState.h"
#include "BaseOption.h"
#include "BasePlayer.h"
//-------------------------------------------------------------
//!
//! @brief RlNgEH[Y
//! @brief RlNgEH[Y֘A̖O
//!
//-------------------------------------------------------------
namespace ConnectWars
{
/*************************************************************//**
*
* @brief RXgN^
* @param Ȃ
*
****************************************************************/
C_OptionWaitOwnCrashState::C_OptionWaitOwnCrashState()
{
}
/*************************************************************//**
*
* @brief fXgN^
* @param Ȃ
*
****************************************************************/
C_OptionWaitOwnCrashState::~C_OptionWaitOwnCrashState()
{
}
/*************************************************************//**
*
* @brief Jns
* @param IvV
* @return Ȃ
*
****************************************************************/
void C_OptionWaitOwnCrashState::Enter(C_BaseOption* pOption)
{
// GtOݒ
pOption->SetInvincibleFlag(true);
// ʂZbg
pOption->ResetEffect();
// AĂꍇ͘AĂIvV̐1炷
if (pOption->IsOnceConnectFlag() == true)
{
assert(pOption->GetPlayer());
pOption->GetPlayer()->AddConnectOptionCount(-1);
}
}
/*************************************************************//**
*
* @brief ss
* @param IvV
* @return Ȃ
*
****************************************************************/
void C_OptionWaitOwnCrashState::Execute(C_BaseOption* pOption)
{
pOption->ResetConnect();
}
/*************************************************************//**
*
* @brief Is
* @param IvV
* @return Ȃ
*
****************************************************************/
void C_OptionWaitOwnCrashState::Exit(C_BaseOption* pOption)
{
}
/*************************************************************//**
*
* @brief bZ[Ws
* @param IvV
* @param eO
* @return IFtrue
* @return ُIFfalse
*
****************************************************************/
bool C_OptionWaitOwnCrashState::MessageProcess(C_BaseOption* pOption, const Telegram& rTelegram)
{
if (rTelegram.message_ == Message::s_pOWN_CRASH)
{
pOption->OwnCrash();
}
return true;
}
}
|
Java
|
UTF-8
| 11,677 | 1.765625 | 2 |
[] |
no_license
|
package com.arcsoft.arcfacedemo.activity;
import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import com.arcsoft.arcfacedemo.R;
import com.arcsoft.arcfacedemo.faceserver.SignalingClient;
import com.arcsoft.arcfacedemo.util.utils.LogUtils;
import com.arcsoft.arcfacedemo.widget.PeerConnectionAdapter;
import com.arcsoft.arcfacedemo.widget.SdpAdapter;
import org.json.JSONException;
import org.json.JSONObject;
import org.webrtc.AudioSource;
import org.webrtc.AudioTrack;
import org.webrtc.Camera1Enumerator;
import org.webrtc.Camera2Enumerator;
import org.webrtc.CameraEnumerator;
import org.webrtc.DefaultVideoDecoderFactory;
import org.webrtc.DefaultVideoEncoderFactory;
import org.webrtc.EglBase;
import org.webrtc.IceCandidate;
import org.webrtc.MediaConstraints;
import org.webrtc.MediaStream;
import org.webrtc.PeerConnection;
import org.webrtc.PeerConnectionFactory;
import org.webrtc.SessionDescription;
import org.webrtc.SurfaceTextureHelper;
import org.webrtc.SurfaceViewRenderer;
import org.webrtc.VideoCapturer;
import org.webrtc.VideoSource;
import org.webrtc.VideoTrack;
import java.util.ArrayList;
import java.util.List;
public class WebRTCActivity extends AppCompatActivity implements SignalingClient.Callback {
private String TAG = "WebRTCActivity";
private MediaStream mediaStreamRemote;
private PeerConnectionFactory mPeerConnectionFactory;
private SurfaceViewRenderer remoteSurfaceView;
private SurfaceViewRenderer localSurfaceView;
PeerConnection peerConnectionLocal;
private MediaConstraints audioConstarints;
private AudioManager audioManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_rtc);
//打开扬声器
audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
audioManager.setMicrophoneMute(false);
audioManager.setSpeakerphoneOn(true);
audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL),
AudioManager.STREAM_VOICE_CALL);
audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
initWebRTC();
}
private void initWebRTC() {
EglBase.Context eglBaseContext = EglBase.create().getEglBaseContext();
//PeerConnectionFactory初始化
PeerConnectionFactory.InitializationOptions initializationOptions =
PeerConnectionFactory.InitializationOptions
.builder(this)
.createInitializationOptions();
PeerConnectionFactory.initialize(initializationOptions);
PeerConnectionFactory.Options options = new PeerConnectionFactory.Options();
DefaultVideoEncoderFactory defaultVideoEncoderFactory =
new DefaultVideoEncoderFactory(eglBaseContext, true, true);
DefaultVideoDecoderFactory defaultVideoDecoderFactory =
new DefaultVideoDecoderFactory(eglBaseContext);
//获取mPeerConnectionFactory对象
mPeerConnectionFactory = PeerConnectionFactory.builder()
.setOptions(options)
.setVideoEncoderFactory(defaultVideoEncoderFactory)//添加编码器
.setVideoDecoderFactory(defaultVideoDecoderFactory)//添加解码器
.createPeerConnectionFactory();
SurfaceTextureHelper surfaceTextureHelper = SurfaceTextureHelper.create("CaptureThread", eglBaseContext);
//获取VideoCapturer
VideoCapturer videoCapturer = createVideoCapturer();
//获取数据源VideoSource
VideoSource videoSource = mPeerConnectionFactory.createVideoSource(videoCapturer.isScreencast());
// VideoCapture 与 VideoSource 关联
videoCapturer.initialize(surfaceTextureHelper, getApplicationContext(), videoSource.getCapturerObserver());
//打开摄像头开始工作
videoCapturer.startCapture(480, 640, 30);
//获取显示本地视频的view
localSurfaceView = findViewById(R.id.LocalSurfaceView);
localSurfaceView.setMirror(true);
localSurfaceView.init(eglBaseContext, null);
VideoTrack videoTrack = mPeerConnectionFactory.createVideoTrack("101", videoSource);
// display in localView
videoTrack.addSink(localSurfaceView);
//获取数据源AudioSource
audioConstarints = new MediaConstraints();
//回声消除
audioConstarints.mandatory.add(new MediaConstraints.KeyValuePair("googEchoCancellation", "true"));
//自动增益
audioConstarints.mandatory.add(new MediaConstraints.KeyValuePair("googAutoGainControl", "true"));
//高音过滤
audioConstarints.mandatory.add(new MediaConstraints.KeyValuePair("googHighpassFilter", "true"));
//噪音处理
audioConstarints.mandatory.add(new MediaConstraints.KeyValuePair("googNoiseSuppression", "true"));
AudioSource audioSource = mPeerConnectionFactory.createAudioSource(audioConstarints);
AudioTrack audioTrack = mPeerConnectionFactory.createAudioTrack("102", audioSource);
//获取显示远端视频的view
remoteSurfaceView = findViewById(R.id.RemoteSurfaceView);
remoteSurfaceView.setMirror(false);
remoteSurfaceView.init(eglBaseContext, null);
mediaStreamRemote = mPeerConnectionFactory.createLocalMediaStream("mediaStreamRemote");
mediaStreamRemote.addTrack(videoTrack);
mediaStreamRemote.addTrack(audioTrack);
SignalingClient.get().setCallback(this);
call();
}
public void jumpTojion(View view) {
SignalingClient.get().call();
}
private void call() {
List<PeerConnection.IceServer> iceServers = new ArrayList<>();
// iceServers.add(PeerConnection.IceServer.builder("stun:stun.l.google.com:19302").createIceServer());//穿透服务器
peerConnectionLocal = mPeerConnectionFactory.createPeerConnection(iceServers, new PeerConnectionAdapter("localconnection") {
@Override
public void onIceCandidate(IceCandidate iceCandidate) {
super.onIceCandidate(iceCandidate);
LogUtils.a("onIceCandidatexxxxxxx");
SignalingClient.get().sendIceCandidate(iceCandidate);
}
@Override
public void onAddStream(MediaStream mediaStream) {
LogUtils.a("onAddStream");
super.onAddStream(mediaStream);
VideoTrack remoteVideoTrack = mediaStream.videoTracks.get(0);
// AudioTrack audioTrack = mediaStream.audioTracks.get(0);
runOnUiThread(() -> {
remoteVideoTrack.addSink(remoteSurfaceView);
});
}
});
peerConnectionLocal.addStream(mediaStreamRemote);
}
private VideoCapturer createVideoCapturer() {
if (Camera2Enumerator.isSupported(this)) {
return createCameraCapturer(new Camera2Enumerator(this));
} else {
return createCameraCapturer(new Camera1Enumerator(true));
}
}
private VideoCapturer createCameraCapturer(CameraEnumerator enumerator) {
final String[] deviceNames = enumerator.getDeviceNames();
// First, try to find front facing camera
// LogUtils.a(TAG, "Looking for front facing cameras.");
for (String deviceName : deviceNames) {
if (enumerator.isFrontFacing(deviceName)) {
// LogUtils.a(TAG, "Creating front facing camera capturer.");
VideoCapturer videoCapturer = enumerator.createCapturer(deviceName, null);
if (videoCapturer != null) {
return videoCapturer;
}
}
}
// Front facing camera not found, try something else
LogUtils.a(TAG, "Looking for other cameras.");
for (String deviceName : deviceNames) {
if (!enumerator.isFrontFacing(deviceName)) {
LogUtils.a(TAG, "Creating other camera capturer.");
VideoCapturer videoCapturer = enumerator.createCapturer(deviceName, null);
if (videoCapturer != null) {
return videoCapturer;
}
}
}
return null;
}
@Override
public void onCreateRoom() {
}
@Override
public void onPeerJoined() {
}
@Override
public void onSelfJoined() {
LogUtils.a("onSelfJoined");
peerConnectionLocal.createOffer(new SdpAdapter("local offer sdp") {
@Override
public void onCreateSuccess(SessionDescription sessionDescription) {
LogUtils.a("sdp" + "onCreateSuccess");
super.onCreateSuccess(sessionDescription);
peerConnectionLocal.setLocalDescription(new SdpAdapter("local set local"), sessionDescription);
SignalingClient.get().sendOfferSDP(sessionDescription);
}
@Override
public void onCreateFailure(String s) {
super.onCreateFailure(s);
LogUtils.a("sdp" + "onCreateFailure" + s);
}
}, audioConstarints);
}
@Override
public void onPeerLeave(String msg) {
this.finish();
}
@Override
public void onOfferReceived(JSONObject data) {
LogUtils.a("onOfferReceived");
runOnUiThread(() -> {
try {
peerConnectionLocal.setRemoteDescription(new SdpAdapter("localSetRemote"),
new SessionDescription(SessionDescription.Type.OFFER, data.getString("sdp")));
} catch (JSONException e) {
e.printStackTrace();
}
peerConnectionLocal.createAnswer(new SdpAdapter("localAnswerSdp") {
@Override
public void onCreateSuccess(SessionDescription sdp) {
super.onCreateSuccess(sdp);
LogUtils.a("sdp" + "onCreateSuccess");
peerConnectionLocal.setLocalDescription(new SdpAdapter("localSetLocal"), sdp);
SignalingClient.get().sendSessionDescription(sdp);
}
@Override
public void onCreateFailure(String s) {
super.onCreateFailure(s);
LogUtils.a("sdp" + "onCreateFailure" + s);
}
}, new MediaConstraints());
});
}
@Override
public void onAnswerReceived(JSONObject data) {
LogUtils.a("onAnswerReceived");
try {
peerConnectionLocal.setRemoteDescription(new SdpAdapter("localSetRemote"),
new SessionDescription(SessionDescription.Type.ANSWER, data.getString("sdp")));
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onIceCandidateReceived(JSONObject data) {
LogUtils.a("onIceCandidateReceived" + data);
try {
peerConnectionLocal.addIceCandidate(new IceCandidate(
data.getString("sdpMid"),
data.getInt("sdpMLineIndex"),
data.getString("candidate")
));
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
SignalingClient.get().destroy();
}
}
|
C++
|
UTF-8
| 1,775 | 2.9375 | 3 |
[] |
no_license
|
#include<stdio.h>
#include<string.h>
char alp[]="abcdefghijklmnopqrstuvwxyz";
char str[200];
char ch[50];
int value[50],total[50];
int space()
{
int i,k=0;
for(i=0;str[i];i++)
if(str[i]!=' ')
str[k++]=str[i];
str[k]=NULL;
return 0;
}
int main()
{
int i,c,j,k,sum,tc;
char dup[150];
while(gets(str))
{
sum=c=tc=0;
strcpy(dup,str);
space();
for(i=0;str[i];i++)
if(str[i]!='+')
if(str[i]!='-')
tc++;
for(i=0;alp[i];i++)
{
for(j=0;str[j];j++)
{
if(alp[i]==str[j])
{
c++;
ch[c]=alp[i];
if(str[j-1]=='+'&&str[j-2]=='+')
{
value[c]=i+2;
total[i]=i+2;
str[j-1]=str[j-2]='0';
}
else if(str[j+1]=='+' && str[j+2]=='+')
{
value[c]=i+2;
total[i]=i+1;
str[j+1]=str[j+2]='0';
}
else if(str[j-1]=='+'&&str[j-2]=='+')
{
value[c]=i+2;
total[i]=i+2;
str[j+1]=str[j+2]='0';
}
else if(str[j-1]=='-'&&str[j-2]=='-')
{
value[c]=i;
total[i]=i;
str[j-1]=str[j-2]='0';
}
else if(str[j+1]=='-'&&str[j+2]=='-')
{
value[c]=i;
total[i]=i+1;
str[j+1]=str[j+2]='0';
}
else
{
value[c]=i+1;
total[i]=i+1;
}
}
}
if(c==tc) break;
}
k=0;
for(i=0;str[i];i++)
if(str[i]!='0')
str[k++]=str[i];
str[k]=NULL;
k=0;
for(i=0;str[i];i++)
{
for(j=0;alp[j];j++)
{
if(str[i]==alp[j])
{
k++;
if(str[i-1]=='-')
sum-=total[j];
else
sum+=total[j];
}
}
if(k==tc) break;
}
printf("Expression: %s\n",dup);
printf(" value = %d\n",sum);
for(i=1;i<=c;i++)
printf(" %c = %d\n",ch[i],value[i]);
}
return 0;
}
|
Markdown
|
UTF-8
| 878 | 2.875 | 3 |
[] |
no_license
|
# HM-5
Homework #5 - Work Day Scheduler
## Use moment().format(); for time and date
* display time and date in the header
## Build Timeblocks
### Each timeblock needs the hour, an input for memos, and a save button
### Memos need to save and be retrieved upon opening the scheduler
* memo data stored to and pulled from local storage
* display saved memos immediately
### Compare time id of timeblock to current time for color coding
* for loop to go through each timeblock individually
* put both (timeblock id and current) times into arrays using .split
* used if statements to compare times and set color conditions
* change textarea color as needed using .css
** Green = Future hour | Red = Current hour | Grey = Passed hour
** Updates every millisecond

|
Python
|
UTF-8
| 774 | 3.65625 | 4 |
[] |
no_license
|
class Canvas:
def __init__(self, width,height):
self.width = width
self.height = height
self.screen = [['' for i in range(height)] for j in range(width)]
self.clearCanvas()
def clearCanvas(self):
for y in range (0,self.height):
for x in range (0,self.width):
self.screen[x][y] = ' '
def drawSymbolCanvas(self, x, y, symbol):
self.screen[x][y] = symbol
def outputCanvasTerminal(self):
for y in range (0,self.height):
for x in range (0,self.width):
print(self.screen[x][y],end = " ")
print()
print()
def getWidth(self):
return self.width
def getHeight(self):
return self.height
|
Shell
|
UTF-8
| 151 | 2.625 | 3 |
[] |
no_license
|
#!/usr/bin/env zsh
if [ "$INSIDE_EMACS" = 'vterm' ]; then
. "$HOME/.config/zsh/vterm.zsh"
find_file "$@"
else
emacsclient -t -nw "$@"
fi
|
C#
|
UTF-8
| 1,285 | 2.53125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
namespace PNI.Entities
{
public class Unit
{
public Unit()
{
BuyersID = 0;
UnitPurchased = "";
LoanAmount = 0;
Terms = 24;
LoanDate = DateTime.Now;
PaymentStart = DateTime.Now.AddDays(30);
InterestRate = decimal.Parse("7.5");
}
public int ID { get; set; }
[Required]
public int BuyersID { get; set; }
[Required]
public string UnitPurchased { get; set; }
[Required]
[Range(0, 9999999999999999.99)]
public decimal LoanAmount { get; set; }
[Required]
public int Terms { get; set; }
[Required]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime LoanDate { get; set; }
[Required]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime PaymentStart { get; set; }
[Required]
public decimal InterestRate { get; set; }
}
}
|
C++
|
UTF-8
| 7,468 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
#pragma once
#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
#else
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#endif
#ifndef INPORT_ANY
#define INPORT_ANY 0
#endif
#include <cstring>
#include <array>
#include <string>
#include <vector>
class UDPsocket
{
public:
typedef struct sockaddr_in sockaddr_in_t;
typedef struct sockaddr sockaddr_t;
typedef std::vector<uint8_t> msg_t;
public:
struct IPv4;
enum class Status : int
{
OK = 0,
SocketError = -1,
OpenError = SocketError,
CloseError = -2,
ShutdownError = -3,
BindError = -4,
ConnectError = BindError,
SetSockOptError = -5,
GetSockNameError = -6,
SendError = -7,
RecvError = -8,
// AddressError = -66,
};
private:
int sock{ -1 };
sockaddr_in_t self_addr{};
socklen_t self_addr_len = sizeof(self_addr);
sockaddr_in_t peer_addr{};
socklen_t peer_addr_len = sizeof(peer_addr);
public:
UDPsocket()
{
#ifdef _WIN32
WSAInit();
#endif
self_addr = IPv4{};
peer_addr = IPv4{};
}
~UDPsocket()
{
this->close();
}
public:
int open()
{
this->close();
sock = (int)::socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (this->is_closed()) {
return (int)Status::SocketError;
}
return (int)Status::OK;
}
int close()
{
if (!this->is_closed()) {
#ifdef _WIN32
int ret = ::shutdown(sock, SD_BOTH);
#else
int ret = ::shutdown(sock, SHUT_RDWR);
#endif
if (ret < 0) {
return (int)Status::ShutdownError;
}
#ifdef _WIN32
ret = ::closesocket(sock);
#else
ret = ::close(sock);
#endif
if (ret < 0) {
return (int)Status::CloseError;
}
sock = -1;
}
return (int)Status::OK;
}
bool is_closed() const { return sock < 0; }
public:
int bind(const IPv4& ipaddr)
{
self_addr = ipaddr;
self_addr_len = sizeof(self_addr);
int opt = 1;
int ret = ::setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(opt));
if (ret < 0) {
return (int)Status::SetSockOptError;
}
ret = ::bind(sock, (sockaddr_t*)&self_addr, self_addr_len);
if (ret < 0) {
return (int)Status::BindError;
}
ret = ::getsockname(sock, (sockaddr_t*)&self_addr, &self_addr_len);
if (ret < 0) {
return (int)Status::GetSockNameError;
}
return (int)Status::OK;
}
int bind(uint16_t portno)
{
auto ipaddr = IPv4::Any(portno);
return this->bind(ipaddr);
}
int bind_any()
{
return this->bind(INPORT_ANY);
}
int bind_any(uint16_t& portno)
{
int ret = this->bind(INPORT_ANY);
if (ret < 0) {
return ret;
}
portno = IPv4{ self_addr }.port;
return (int)Status::OK;
}
public:
int connect(const IPv4& ipaddr)
{
peer_addr = ipaddr;
peer_addr_len = sizeof(peer_addr);
int ret = ::connect(sock, (sockaddr_t*)&peer_addr, peer_addr_len);
if (ret < 0) {
return (int)Status::ConnectError;
}
return (int)Status::OK;
}
int connect(uint16_t portno)
{
auto ipaddr = IPv4::Loopback(portno);
return this->connect(ipaddr);
}
public:
IPv4 get_self_ip() const
{
return self_addr;
}
IPv4 get_peer_ip() const
{
return peer_addr;
}
public:
template <typename T, typename = typename
std::enable_if<sizeof(typename T::value_type) == sizeof(uint8_t)>::type>
int send(const T& message, const IPv4& ipaddr) const
{
// // UPnP
// std::string msg = "M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:1900\r\nMAN: ssockp:discover\r\nST: ssockp:all\r\nMX: 1\r\n\r\n";
sockaddr_in_t addr_in = ipaddr;
socklen_t addr_in_len = sizeof(addr_in);
int ret = ::sendto(sock,
(const char*)message.data(), message.size(), 0,
(sockaddr_t*)&addr_in, addr_in_len);
if (ret < 0) {
return (int)Status::SendError;
}
return ret;
}
template <typename T, typename = typename
std::enable_if<sizeof(typename T::value_type) == sizeof(uint8_t)>::type>
int recv(T& message, IPv4& ipaddr) const
{
sockaddr_in_t addr_in;
socklen_t addr_in_len = sizeof(addr_in);
typename T::value_type buffer[10 * 1024];
int ret = ::recvfrom(sock,
(char*)buffer, sizeof(buffer), 0,
(sockaddr_t*)&addr_in, &addr_in_len);
if (ret < 0) {
return (int)Status::RecvError;
}
ipaddr = addr_in;
message = { std::begin(buffer), std::begin(buffer) + ret };
return ret;
}
public:
int broadcast(int opt) const
{
int ret = ::setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (const char*)&opt, sizeof(opt));
if (ret < 0) {
return (int)Status::SetSockOptError;
}
return (int)Status::OK;
}
int interrupt() const
{
uint16_t portno = IPv4{ self_addr }.port;
auto ipaddr = IPv4::Loopback(portno);
return this->send(msg_t{}, ipaddr);
}
public:
struct IPv4
{
std::array<uint8_t, 4> octets{};
uint16_t port{};
public:
IPv4()
{
}
IPv4(const std::string& ipaddr, uint16_t portno)
{
int ret = ::inet_pton(AF_INET, ipaddr.c_str(), (uint32_t*)octets.data());
if (ret > 0) {
port = portno;
} else {
// throw std::runtime_error(Status::AddressError)
}
}
IPv4(uint8_t a, uint8_t b, uint8_t c, uint8_t d, uint16_t portno)
{
octets[0] = a;
octets[1] = b;
octets[2] = c;
octets[3] = d;
port = portno;
}
IPv4(const sockaddr_in_t& addr_in)
{
*(uint32_t*)octets.data() = addr_in.sin_addr.s_addr;
port = ntohs(addr_in.sin_port);
}
operator sockaddr_in_t() const
{
sockaddr_in_t addr_in;
std::memset(&addr_in, 0, sizeof(addr_in));
addr_in.sin_family = AF_INET;
addr_in.sin_addr.s_addr = *(uint32_t*)octets.data();
addr_in.sin_port = htons(port);
return addr_in;
}
private:
IPv4(uint32_t ipaddr, uint16_t portno)
{
*(uint32_t*)octets.data() = htonl(ipaddr);
port = portno;
}
public:
static IPv4 Any(uint16_t portno) { return IPv4{ INADDR_ANY, portno }; }
static IPv4 Loopback(uint16_t portno) { return IPv4{ INADDR_LOOPBACK, portno }; }
static IPv4 Broadcast(uint16_t portno) { return IPv4{ INADDR_BROADCAST, portno }; }
public:
const uint8_t& operator[](size_t octet) const { return octets[octet]; }
uint8_t& operator[](size_t octet) { return octets[octet]; }
public:
bool operator==(const IPv4& other) const {
return this->octets == other.octets && this->port == other.port;
}
bool operator!=(const IPv4& other) const {
return !(*this == other);
}
public:
std::string addr_string() const {
return std::to_string(octets[0]) +
'.' + std::to_string(octets[1]) +
'.' + std::to_string(octets[2]) +
'.' + std::to_string(octets[3]);
}
std::string port_string() const {
return std::to_string(port);
}
std::string to_string() const {
return this->addr_string() + ':' + this->port_string();
}
operator std::string() const { return this->to_string(); }
};
#ifdef _WIN32
public:
static WSADATA* WSAInit()
{
static WSADATA wsa;
static struct WSAContext {
WSAContext(WSADATA* wsa) {
WSAStartup(0x0202, wsa);
}
~WSAContext() {
WSACleanup();
}
} context{ &wsa };
return &wsa;
}
#endif
};
namespace std
{
template<> struct hash<UDPsocket::IPv4>
{
typedef UDPsocket::IPv4 argument_type;
typedef size_t result_type;
result_type operator()(argument_type const& ipaddr) const noexcept
{
result_type const h1{ std::hash<uint32_t>{}(*(uint32_t*)ipaddr.octets.data()) };
result_type const h2{ std::hash<uint16_t>{}(ipaddr.port) };
return h1 ^ (h2 << 1);
}
};
}
|
Python
|
UTF-8
| 336 | 2.734375 | 3 |
[] |
no_license
|
digs = [4275710637398865385, 4275710637398865381, 4275710637398865399, 4275710637398865405, 4275710637398865383, 4275710637398865400, 4275710637398865386][::-1]
expected = "easyctf"[::-1]
x = digs[0] - ord(expected[0])
out = ""
for letter in digs:
out = chr(letter - x) + out
assert out == "easyctf"
print x
# 4275710637398865284
|
Python
|
UTF-8
| 1,035 | 3.4375 | 3 |
[
"MIT"
] |
permissive
|
from rit_lib import *
def createBST():
return BinaryTree(None)
class BinaryTree(struct):
_slots = (BSTNode, 'root')
class BSTNode(struct):
_slots = ((('BSTNode',NoneType),'left'), (object, 'value'),(('BSTNode', NoneType), 'right'))
def add(self, value):
if self.root == None:
self.root = BSTNode(None, value, None)
else:
current = self.root
while True:
if value < current.value and current.left != None:
current = current.left
elif value < current.value:
current.left = BSTNode(None, value, None)
break
elif value >= current.value and current.right != None:
current = current.right
else:
current.right = BSTNode(None,value, None)
break
def search(self):
pass
def main():
myTree = createBST()
myTree.add(7)
print(myTree)
|
JavaScript
|
UTF-8
| 1,574 | 3.53125 | 4 |
[
"MIT"
] |
permissive
|
RunOnEnter();
let ArrayOfPrimeNumbers =[];
let ArrayOfAllTheNumbers =[];
function FindPrime() {
document.getElementById("PrimeNumberOutput").innerHTML = "";
ArrayOfPrimeNumbers=[];
ArrayOfAllTheNumbers=[];
let i;
let j;
let NumberOfMultiples = 0;
let range = document.getElementById("myInput").value;
for(let AllNumbers=1; AllNumbers<=range;++AllNumbers){
ArrayOfAllTheNumbers.push(AllNumbers);
}
for (i = 2; i <= range; i++) {
for (j = 2; j <= i; j++) {
if (i % j === 0) {
NumberOfMultiples++;
}
}
if (NumberOfMultiples === 1)
ArrayOfPrimeNumbers.push(i);
NumberOfMultiples = 0;
}
printPrime();
}
function printPrime(){
for(let i=0;i<ArrayOfAllTheNumbers.length;i++) {
let numberid = i+1;
let line ="";
line +="<div id='"+numberid+"' class='EachPrimeNumberOutputID'>"+ArrayOfAllTheNumbers[i]+" </div>";
document.getElementById("PrimeNumberOutput").innerHTML += line;
MakePrimeNumbersGreen();
}
}
function MakePrimeNumbersGreen() {
for (let PrimeLength = 0; PrimeLength < ArrayOfPrimeNumbers.length; PrimeLength++) {
let primenos = $("#"+ArrayOfPrimeNumbers[PrimeLength]);
primenos.attr('id', 'primeID');// the style attributes of an ID can over ride the attributes of a class
}
}
function RunOnEnter() {
let elem = document.getElementById("myInput");
elem.onkeyup = function(e){
if(e.keyCode == 13){
FindPrime();
}
}
}
|
JavaScript
|
UTF-8
| 1,761 | 3.3125 | 3 |
[] |
no_license
|
var content = document.getElementById('content'),
button = document.getElementById('button'),
ul = document.createElement('ul'),
messages = document.getElementById('message');
var nombreDeMessage = 1;
content.appendChild(ul);
ul.setAttribute('id', 'ulListDom');
var storage = localStorage.getItem("arrayList");
for(var i = 0; i < storage.length; i++) {
console.log(storage[i]);
}
// declaration de l'heure
var myDate = new Date(),
hours = myDate.getHours(),
minutes = myDate.getMinutes(),
inputValue = document.getElementById('input').value;
var arrayList = [];
// start function
button.onclick = function (){
var li = document.createElement('li'),
p = document.createElement('p'),
span = document.createElement('span'),
i = document.createElement('i'),
img = document.createElement('img');
img.setAttribute('src', 'double-tick.png');
if(hours < 10) {
hours = '0' + hours;
};
if(minutes < 10) {
minutes = '0' + minutes;
};
if(inputValue == '' || inputValue == ' ' || inputValue == ' ' || inputValue == ' ') {
} else {
ul.appendChild(li).appendChild(p);
li.appendChild(span);
span.appendChild(img);
span.appendChild(i);
i.textContent = hours + ':' + minutes;
p.textContent = inputValue;
content.scrollTop = content.scrollHeight;
messages.textContent = nombreDeMessage ++;
arrayList.push(p.textContent);
localStorage.setItem("arrayList", arrayList);
}
for(var i = 0; i < arrayList.length; i++) {
console.log(arrayList[i]);
}
}
|
Ruby
|
UTF-8
| 748 | 2.734375 | 3 |
[
"MIT"
] |
permissive
|
require 'singleton'
module Codesake
class Kernel
include Singleton
attr_reader :engine
NONE = 0
TEXT = 1
JSP = 2
UNKNOWN = -1
def choose_engine(filename, options)
engine = nil
case detect(filename)
when TEXT
engine = Codesake::Engine::Text.new(filename)
when NONE
engine = Codesake::Engine::Generic.new(filename)
when JSP
engine = Codesake::Engine::Jsp.new(filename, options)
end
engine
end
def detect(filename)
return NONE if filename.nil? or filename.empty?
return TEXT if Codesake::Engine::Text.is_txt?(filename)
return JSP if (File.extname(filename) == ".jsp")
return UNKNOWN
end
end
end
|
Python
|
UTF-8
| 424 | 2.671875 | 3 |
[] |
no_license
|
import sys
import subprocess
types = ['md5', 'sha1', 'sha256']
keys = [4*'a', 16*'a', 32*'a']
fs = sys.argv[1:]
for fname in fs:
for t in types:
for k in keys:
cmd = 'openssl dgst -{type} -hmac "{key}" {fname}'.format(type=t, key=k, fname=fname)
output = subprocess.check_output(cmd, shell=True).decode()
print(cmd)
print(output)
print()
print()
|
Python
|
UTF-8
| 1,301 | 3.15625 | 3 |
[] |
no_license
|
import A3
"""Please do not edit any part of this code!"""
def score():
score = 0
test1 = ([[5,0], [6,0], [7,1,0], [8,1,0], [9,1]], 5, 9)
ans1 = 3
test2 = ([[5, 0], [6, 0], [7, 0], [8, 0]], 5, 0)
ans2 = 1
test3 = ([[5, 3, 1, 0], [6, 2, 1, 0], [7, 3, 2, 1], [8, 3, 2, 0]], 5, 7)
ans3 = 2
test4 = ([[5, 0], [6, 1, 0], [7, 2, 1], [8, 2]], 5, 8)
ans4 = 4
test5 = ([[5, 0], [6, 1], [7, 1], [8, 1]], 7, 5)
ans5 = -1
tests = [(test1, ans1),(test2, ans2),(test3, ans3),(test4, ans4),(test5, ans5)]
test_num = len(tests)
s = A3.Solution
PASS = True
# print("Before the test loop started")
for n in range(test_num):
routes, source, target = tests[n][0]
s_a = s.leastNumBus(s.leastNumBus, routes, source, target)
# print(s_a, tests[n][1])
if s_a == tests[n][1]:
print("find one equal")
score += 100 / test_num
else:
print("You have passed " + str(n) + " out of " + str(test_num) + " test.")
print("Your current score is " + str(score))
PASS = False
break
if PASS:
print("You have passed " + str(test_num) + " tests")
print("Your score is 100. Congratulation! (This is not your final score) ")
|
Java
|
UTF-8
| 1,360 | 2.203125 | 2 |
[] |
no_license
|
package com.zry.demo.dao.teacher;
import java.util.List;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import com.zry.demo.dao.BaseDao;
import com.zry.demo.model.Teacher;
@Repository
public class TeacherDaoImpl extends BaseDao{
//测试事务是否起作用
private JdbcTemplate jdbcTemplate;
@Autowired
public void setDataSource(DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
}
public Teacher selectTeacher(int id) {
return teacherMap.selectTeacher(id);
}
public List<Teacher> selectAllTeacher() {
return teacherMap.selectAllTeacher();
}
public List<Teacher> selectTeachers(Teacher teacher) {
return teacherMap.selectTeachers(teacher);
}
public void deleteTeacher(int id) {
teacherMap.deleteTeacher(id);
}
public void addTeacher(Teacher teacher) {
teacherMap.addTeacher(teacher);
// jdbcTemplate.execute("insert into teacher values(1234,'name','nan','23')");
}
public void updateTeacher(Teacher teacher) {
teacherMap.updateTeacher(teacher);
}
@Resource
public void setTeacherMapper(TeacherMapper teacherMapper) {
this.teacherMap = teacherMapper;
}
}
|
Java
|
UTF-8
| 12,636 | 2.484375 | 2 |
[] |
no_license
|
package com.maliang.core.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.bson.types.ObjectId;
public class DBData {
public final static Map<String,Object> ObjectMetadataMap = new HashMap<String,Object>();
public final static Map<String,Object> DBDataMap = new HashMap<String,Object>();
static {
initMetadata();
initBrands();
initProductType();
initProduct();
initUserGrade();
initUser();
initUserAddress();
//System.out.println(DBDataMap.get("Product"));
}
public static void main(String[] args) {
Random r = new Random();
for(int i = 0; i < 10;i++){
System.out.println(r.nextInt(10));
}
}
/**
*
* Product:[{name:滋阴乳液125ml,product_type:面霜/乳液,brand:雪花秀,price:368.00,picture:pic,description:aa},"
+ "{name:弹力面霜75ml,product_type:面霜/乳液,brand:雪花秀,price:520.00,picture:pic,description:aa},"
+ "{name:天气丹华泫平衡化妆水150ml,product_type:保湿水,brand:Whoo,price:478.00,picture:pic,description:aa}]
* **/
private static void initProduct(){
String ps = "Product:[{name:滋阴乳液125ml,product_type:面霜/乳液,brand:雪花秀,price:368.00,picture:pic,description:aa},"
+ "{name:弹力面霜75ml,product_type:面霜/乳液,brand:雪花秀,price:520.00,picture:pic,description:aa},"
+ "{name:天气丹华泫平衡化妆水150ml,product_type:保湿水,brand:Whoo,price:478.00,picture:pic,description:aa}]";
DBDataMap.putAll(MapHelper.curlyToMap(ps));
rightFieldValue("Product");
}
public static List<Map<String,Object>> list(String coll){
return (List<Map<String,Object>>)DBData.DBDataMap.get(coll);
}
public static Map<String,Object> getRandom(String collSymbol){
List<Map<String,Object>> products = (List<Map<String,Object>>)DBDataMap.get(collSymbol);
if(products == null || products.size() == 0){
return null;
}
return products.get(new Random().nextInt(products.size()));
}
private static void innerObject(Map<String,Object> obj,String fieldName,String collName){
innerObject(obj,fieldName,collName,"name");
}
private static void innerObject(Map<String,Object> obj,String fieldName,String collName,String columnName){
Object value = obj.get(fieldName);
value = get(collName,columnName,value);
obj.put(fieldName, value);
}
public static Map<String,Object> get(String collection,String key,Object value){
List<Map<String,Object>> list = (List<Map<String,Object>>)DBDataMap.get(collection);
for(Map<String,Object> obj:list){
if(value.equals(obj.get(key))){
return obj;
}
}
return null;
}
private static void initBrands(){
String[] bnames = new String[]{"海蓝之谜","sisley","雪花秀","黛珂","Whoo","pola","科莱丽"};
List<Map<String,Object>> brands = new ArrayList<Map<String,Object>>();
DBDataMap.put("Brand", brands);
for(int i = 0; i < bnames.length; i++){
ObjectId id = new ObjectId();
Map<String,Object> brand = new HashMap<String,Object>();
brand.put("id", id);
brand.put("name", bnames[i]);
brands.add(brand);
}
}
private static void initProductType(){
String[] tnames = new String[]{"洁面","卸妆","爽肤水","保湿水","精华","面霜/乳液","眼霜","面膜","去角质产品"};
List<Map<String,Object>> types = new ArrayList<Map<String,Object>>();
DBDataMap.put("ProductType", types);
for(int i = 0; i < tnames.length; i++){
ObjectId id = new ObjectId();
Map<String,Object> type = new HashMap<String,Object>();
type.put("id", id);
type.put("name", tnames[i]);
types.add(type);
}
}
private static void initUserGrade(){
String us = "UserGrade:[{name:普通会员,discount:90.00},"
+ "{name:黄金会员,discount:85.00},"
+ "{name:白金会员,discount:80.00},"
+ "{name:钻石会员,discount:75.00}]";
DBDataMap.putAll(MapHelper.curlyToMap(us));
rightFieldValue("UserGrade");
}
private static void rightFieldValue(String coll){
List<Map<String,Object>> dataList = (List<Map<String,Object>>)DBDataMap.get(coll);
List<Map<String,Object>> fields = (List<Map<String,Object>>)MapHelper.readValue(ObjectMetadataMap, coll+".fields");
for(Map<String,Object> data:dataList){
data.put("id", new ObjectId());
for(Map<String,Object> field : fields){
Object type = field.get("type");
String fieldName = (String)field.get("name");
Object value = data.get(fieldName);
if("double".equals(type)){
try {
data.put(fieldName, new Double(value.toString()));
}catch(Exception e){}
}else if("int".equals(type)){
try {
data.put(fieldName, new Integer(value.toString()));
}catch(Exception e){}
}else if("object".equals(type)){
String related = (String)field.get("related");
innerObject(data,fieldName,related);
}
}
}
}
public static Map<String,Object> getMetadata(String coll){
return (Map<String,Object>)ObjectMetadataMap.get(coll);
}
private static void initUser(){
String us = "User:[{user_name:wangmx,password:111111,real_name:王美霞,mobile:13456789776,email:wmx@tm.com,user_grade:黄金会员},"
+ "{user_name:wangfan,password:111111,real_name:王凡,mobile:13298790987,email:wf@tm.com,user_grade:普通会员},"
+ "{user_name:wangzq,password:111111,real_name:王梓青,mobile:13876598708,email:wzq@tm.com,user_grade:钻石会员},"
+ "{user_name:wangyn,password:111111,real_name:王易楠,mobile:13609873451,email:wyn@tm.com,user_grade:白金会员},"
+ "{user_name:wangml,password:111111,real_name:王美良,mobile:13876789034,email:wml@tm.com,user_grade:普通会员},"
+ "{user_name:zhanghui,password:111111,real_name:张惠,mobile:13543456765,email:zh@tm.com,user_grade:黄金会员},"
+ "{user_name:zhaoms,password:111111,real_name:赵默笙,mobile:13456789776,email:zms@tm.com,user_grade:白金会员}]";
DBDataMap.putAll(MapHelper.curlyToMap(us));
rightFieldValue("User");
}
private static void initUserAddress(){
String us = "UserAddress:[{address:南京市鼓楼区龙江小区蓝天园26号402室内,consignee:王美霞,mobile:13456789776,default:1,user:wangmx},"
+ "{address:东阳市商城5号楼12号毛线摊,consignee:王振华,mobile:18957951177,default:0,user:wangmx},"
+ "{address:上海市浦东区张杨路1348号305室,consignee:王凡,mobile:13761136601,default:0,user:wangmx}]";
Map<String,Object> data = MapHelper.curlyToMap(us);
DBDataMap.putAll(data);
List<Map<String,Object>> addresses = (List<Map<String,Object>>)data.get("UserAddress");
for(Map<String,Object> address:addresses){
address.put("id", new ObjectId());
innerObject(address,"user","User","user_name");
}
}
/**
* Product {
* _id:objectId,
* name:'Product',
* fields:[{name:name,type:string,label:名称,unique:{scope:brand}},
* {name:product_type,type:object,related:ProductType,label:分类,edit:{type:select}},
* {name:brand,type:object,related:Brand,label:品牌},
* {name:price,type:double,label:价格},
* {name:production_date,type:date,label:生产日期},
* {name:expiry_date,type:date,label:有效期},
* {name:picture,type:string,label:图片,edit:{type:file}},
* {name:description,type:string,label:描述,edit:{type:html}}
* ]
* }
*
*
* User {
* _id:objectId,
* name:User,
* fields:[{name:user_name,type:string,label:用户名},
* {name:password,type:string,label:密码},
* {name:real_name,type:string,label:真实姓名},
* {name:birthday,type:date,label:真实姓名},
* {name:mobile,type:string,label:手机号码},
* {name:email,type:string,label:email},
* {name:user_grade,type:object,related:UserGrade,label:会员等级}]
* }
*
* UserGrade {
* _id:objectId,
* name:'UserGrade',
* fields:[{name:'name',type:'string',label:'等级 名称'},
* {name:'discount',type:'double',label:'商品折扣'}]
* }
*
* UserAddress {
* _id:objectId,
* name:UserAddress,
* fields:[{name:address,type:string,label:详细地址},
* {name:consignee,type:string,label:收货人},
* {name:mobile,type:string,label:手机号码},
* {name:default,type:int,label:是否默认},
* {name:user,type:object,related:User,label:所属会员}]
* }
*
*
* Order {sn,totalPrice,user,status,pay_status,totalNum,
* address:{address,consignee,mobile}
* items:{product,num,price,status}}
*
*
* Order {
* _id:objectId,
* name:Order,
* fields:[{name:sn,type:string,label:订单编号},
* {name:total_price,type:double,label:总价},
* {name:user,type:object,related:User,label:会员},
* {name:status,type:int,label:状态},
* {name:pay_statys,type:int,label:支付状态},
* {name:total_num,type:int,label:总数量},
* {name:address,type:object,related:inner,label:收货地址},
* {name:items,type:list,related:inner,label:订单明细}],
* address:{
* fields:[{name:address,type:string,label:详细地址},
* {name:consignee,type:string,label:收货人},
* {name:mobile,type:string,label:手机号码}]},
* items:{
* fields:[{name:product,type:object,related:Product,label:商品},
* {name:num,type:int,label:订购数量},
* {name:price,type:double,label:订购价格},
* {name:status,type:int,label:状态}]}
* }
* **/
private static void initMetadata(){
String product = "{_id:objectId,name:Product,"
+ "fields:[{name:name,type:string,label:名称,unique:{scope:brand}},"
+ "{name:product_type,type:object,related:ProductType,label:分类,edit:{type:select}},"
+ "{name:brand,type:object,related:Brand,label:品牌,edit:{type:select}},"
+ "{name:price,type:double,label:价格},"
+ "{name:production_date,type:date,label:生产日期},"
+ "{name:expiry_date,type:date,label:有效期},"
+ "{name:picture,type:string,label:图片,edit:{type:file}},"
+ "{name:description,type:string,label:描述,edit:{type:html}}]}";
ObjectMetadataMap.put("Product", MapHelper.curlyToMap(product));
String brand = "{_id:objectId,name:Brand,fields:[{name:name,type:string,label:名称}]}";
ObjectMetadataMap.put("Brand", MapHelper.curlyToMap(brand));
String productType =" {_id:objectId,name:ProductType,fields:[{name:name,type:string,label:名称}]}";
ObjectMetadataMap.put("ProductType", MapHelper.curlyToMap(productType));
String user = "{_id:objectId,name:User,"
+ "fields:[{name:user_name,type:string,label:用户名},"
+ "{name:password,type:string,label:密码},"
+ "{name:real_name,type:string,label:真实姓名},"
+ "{name:birthday,type:date,label:生日},"
+ "{name:mobile,type:string,label:手机号码},"
+ "{name:email,type:string,label:email},"
+ "{name:user_grade,type:object,related:UserGrade,label:会员等级}]}";
ObjectMetadataMap.put("User", MapHelper.curlyToMap(user));
String userGrade = "{_id:objectId,name:UserGrade,"
+ "fields:[{name:name,type:string,label:等级名称},"
+ "{name:discount,type:double,label:商品折扣}]}";
ObjectMetadataMap.put("UserGrade", MapHelper.curlyToMap(userGrade));
String order = "{_id:objectId,name:Order,"
+ "fields:[{name:sn,type:string,label:订单编号},"
+ "{name:total_price,type:double,label:总价},"
+ "{name:user,type:object,related:User,label:会员},"
+ "{name:status,type:int,label:状态},"
+ "{name:pay_statys,type:int,label:支付状态},"
+ "{name:total_num,type:int,label:总数量},"
+ "{name:address,type:object,related:inner,label:收货地址},"
+ "{name:items,type:list,related:inner,label:订单明细}],"
+ "address:{"
+ "fields:[{name:address,type:string,label:详细地址},"
+ "{name:consignee,type:string,label:收货人},"
+ "{name:mobile,type:string,label:手机号码}]},"
+ "items:{"
+ "fields:[{name:product,type:object,related:Product,label:商品},"
+ "{name:num,type:int,label:订购数量},"
+ "{name:price,type:double,label:订购价格},"
+ "{name:status,type:int,label:状态}]}}";
ObjectMetadataMap.put("Order", MapHelper.curlyToMap(order));
}
}
|
Java
|
UTF-8
| 2,610 | 2.46875 | 2 |
[] |
no_license
|
package org.launchcode.controllers;
import org.launchcode.models.Task;
import org.launchcode.models.data.TaskDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.validation.Valid;
/**
* Created by jeannie on 5/2/17.
*/
@Controller
@RequestMapping(value = "todo")
public class TodoController {
@Autowired
private TaskDao taskDao;
@RequestMapping(value = "", method = RequestMethod.GET)
public String index(Model model) {
model.addAttribute("title","Current Tasks");
model.addAttribute("tasks", taskDao.findAll());
return "todo/index";
}
@RequestMapping(value = "", method = RequestMethod.POST, params={"taskIds", "constant"})
public String index(@RequestParam int[] taskIds, @RequestParam String constant, Model model) {
for (int taskId : taskIds) {
taskDao.delete(taskId);
}
model.addAttribute("title","Current Tasks");
model.addAttribute("tasks",taskDao.findAll());
return "todo/index";
}
//Overload index POST method to rerender template with error if no task selected
@RequestMapping(value = "", method = RequestMethod.POST, params={"constant"})
public String index(@RequestParam String constant, Model model) {
model.addAttribute("title","Current Tasks");
model.addAttribute("tasks",taskDao.findAll());
model.addAttribute("error", "You must select a task to remove.");
return "todo/index";
}
@RequestMapping(value = "add", method = RequestMethod.GET)
public String add(Model model) {
model.addAttribute("title", "Add Task");
model.addAttribute("task", new Task());
return "todo/add";
}
@RequestMapping(value = "add", method = RequestMethod.POST)
public String add(@ModelAttribute @Valid Task task, Errors errors, Model model) {
if(errors.hasErrors()) {
model.addAttribute("title","Add Task");
return "todo/add";
}
taskDao.save(task);
return "redirect:";
}
@RequestMapping(value = "about")
public String about(Model model) {
model.addAttribute("title", "About");
return "todo/about";
}
}
|
JavaScript
|
UTF-8
| 309 | 2.765625 | 3 |
[] |
no_license
|
// let id = 0
// class Comment{
//
// constructor(obj,content){
// this.book_id = obj.id
// this.content = content
// this.id = ++id
// }
//
//
// render() {
// let html = `
// <div class="card">
// <p>${content}</p>
// </div>
// `
// return html
// }
// }
|
Java
|
UTF-8
| 5,883 | 3 | 3 |
[] |
no_license
|
package com.example.edd;
import java.io.IOException;
/**
*
* @author ozmarescobar
*/
public class TablaHash
{
public ListaDoble[] tabla;
public int MAX_TABLA;
public TablaHash()
{
int i, j;
for (i = 996 + 1;; i++)
{
for (j = 2; j < i; j++)
{
if (i % j == 0)
{
break;
}
}
if (j == i)
{
MAX_TABLA = i;
break;
}
}
tabla = new ListaDoble[MAX_TABLA];
for (int k = 0; k < MAX_TABLA; k++)
{
tabla[k] = new ListaDoble();
}
}
public TablaHash(int tamanyo)
{
int i, j;
for (i = tamanyo + 1;; i++)
{
for (j = 2; j < i; j++)
{
if (i % j == 0)
{
break;
}
}
if (j == i)
{
MAX_TABLA = i;
break;
}
}
tabla = new ListaDoble[MAX_TABLA];
for (int k = 0; k < MAX_TABLA; k++)
{
tabla[k] = new ListaDoble();
}
}
public int Insertar(String k, Estudiante t)//k es un nombre, el metodo es plegamiento
{
String k_en_string = "";
for (int i = 0; i < k.length(); i++)
{
k_en_string += Integer.toString((int) k.charAt(i));
}
int tamanyo_K = k_en_string.length();
int tamanyo_Grupo = ContarDigitos(MAX_TABLA);
int sumaTotal = 0;
int i;
for (i = 0; i < k_en_string.length(); i += tamanyo_Grupo)
{
if (i + tamanyo_Grupo <= k_en_string.length())
{
String string_grupo = k_en_string.substring(i, i + tamanyo_Grupo);
sumaTotal += Integer.parseInt(string_grupo);
}
}
if (tamanyo_K % tamanyo_Grupo != 0)
{
String remanente = k_en_string.substring(i - tamanyo_Grupo, k_en_string.length());
sumaTotal += Integer.parseInt(remanente);
}
int pos = sumaTotal % MAX_TABLA;
tabla[pos].InsertarAlFinal(t);
return pos;
}
public Estudiante Buscar(String k, Estudiante t)//k es un nombre, el metodo es plegamiento
{
String k_en_string = "";
for (int i = 0; i < k.length(); i++)
{
k_en_string += Integer.toString((int) k.charAt(i));
}
int tamanyo_K = k_en_string.length();
int tamanyo_Grupo = ContarDigitos(MAX_TABLA);
int sumaTotal = 0;
int i;
for (i = 0; i < k_en_string.length(); i += tamanyo_Grupo)
{
if (i + tamanyo_Grupo <= k_en_string.length())
{
String string_grupo = k_en_string.substring(i, i + tamanyo_Grupo);
sumaTotal += Integer.parseInt(string_grupo);
}
}
if (tamanyo_K % tamanyo_Grupo != 0)
{
String remanente = k_en_string.substring(i - tamanyo_Grupo, k_en_string.length());
sumaTotal += Integer.parseInt(remanente);
}
int pos = sumaTotal % MAX_TABLA;
if(tabla[pos].primero != null)
{
return (Estudiante) tabla[pos].Buscar_Estudiante(t.Carnet);
}
return null;
}
public String Graficar(String ruta) throws IOException
{
String texto = "digraph G { dpi = 100; size = 30; rankdir = TB; node[shape=box]; \n\n ";
for(int i = 0; i < tabla.length; i++)
{
if(i != tabla.length - 1)
{
texto += "\"" + i + "\"->";
}
else
{
texto += "\"" + i + "\";\n";
}
}
for(int i = 0; i < tabla.length; i++)
{
NodoLista pivote = tabla[i].primero;
while(pivote != null)
{
Estudiante estudiante = (Estudiante) pivote.data;
texto += "\"" + estudiante.hashCode() + "\"[label = \""
+ "Carnet: " + estudiante.Carnet + "\\n"
+ "DPI: " + estudiante.DPI + "\\n"
+ "Nombre: " + estudiante.Nombre + "\\n"
+ "Apellido: " + estudiante.Apellido + "\\n"
+ "Email: " + estudiante.Email + "\\n"
+ "Token: " + estudiante.Token + "\\n"
+ "Password: " + estudiante.Password + "\\n"
+ "Creditos: " + estudiante.Creditos
+ "\"];\n";
pivote = pivote.siguiente;
}
pivote = tabla[i].primero;
if(pivote != null)
{
texto += "subgraph \"G" + i + "\"{\n";
texto += "rank = \"same\";\n";
texto += "\"" + i + "\"->";
while(pivote != null)
{
Estudiante estudiante = (Estudiante) pivote.data;
if(pivote.siguiente != null)
{
texto += "\"" + estudiante.hashCode() + "\"->";
}
else
{
texto += "\"" + estudiante.hashCode() + "\";\n";
}
pivote = pivote.siguiente;
}
texto += "}\n";
}
}
texto += "} ";
Esencial esencial = new Esencial();
esencial.Generar_Archivo(texto, ruta);
Runtime.getRuntime().exec("dot -Tpng " + ruta + " -O");
return ruta + ".png";
}
private int ContarDigitos(int n)
{
if (n > 9)
{
return 1 + ContarDigitos(n / 10);
}
return 1;
}
}
|
Python
|
UTF-8
| 224 | 3.46875 | 3 |
[] |
no_license
|
name=input("write your first name :").lower().strip()
key_name= "clark"
if name==key_name:
print(f"hello,{key_name.capitalize()}! The password is : @12")
else:
print (f"Hello, {name.capitalize()}! See you later.")
|
Go
|
UTF-8
| 3,135 | 3.109375 | 3 |
[] |
no_license
|
package main
import (
"math/rand"
)
func avg(counts []int) float64 {
n := float64(len(counts))
avg := float64(0)
for _, count := range counts {
avg += float64(count) / n
}
return avg
}
func simulateOne() int {
var gaps [10][2]float64
count := 0
gapCount := 1
gaps[0][0] = 0
gaps[0][1] = 1
const minGap = 0.1
for {
y := rand.Float64()
count++
for i := 0; i < gapCount; i++ {
if y < gaps[i][0] || y > gaps[i][1] {
continue
}
if y < gaps[i][0]+minGap {
if y > gaps[i][1]-minGap {
gapCount--
if gapCount <= 0 {
return count
}
copy(gaps[i:gapCount], gaps[i+1:gapCount+1])
} else {
gaps[i][0] = y
}
} else if y > gaps[i][1]-minGap {
gaps[i][1] = y
} else {
gaps[gapCount][0] = y
gaps[gapCount][1] = gaps[i][1]
gaps[i][1] = y
gapCount++
}
break
}
}
}
func simulate(n int) {
counts := make([]int, n)
for i := 0; i < n; i++ {
counts[i] = simulateOne()
}
println(n, avg(counts))
}
func main() {
simulate(10)
simulate(100)
simulate(1000)
simulate(10000)
simulate(100000)
simulate(1000000)
simulate(10000000)
extraCredit(10)
extraCredit(100)
extraCredit(1000)
extraCredit(10000)
extraCredit(100000)
extraCredit(1000000)
}
type ecHold struct {
x, y float64
reachableFromBottom, reachableFromTop bool
canReach []int
}
func (hold *ecHold) climbableAfterPropogateReachable(fromBottom, fromTop bool, holds []ecHold) bool {
if (fromBottom || hold.reachableFromBottom) && (fromTop || hold.reachableFromTop) {
return true
}
if (fromBottom == hold.reachableFromBottom) && (fromTop == hold.reachableFromTop) {
return false
}
if fromBottom && !hold.reachableFromBottom {
hold.reachableFromBottom = true
for _, i := range hold.canReach {
if holds[i].climbableAfterPropogateReachable(fromBottom, fromTop, holds) {
return true
}
}
}
if fromTop && !hold.reachableFromTop {
hold.reachableFromTop = true
for _, i := range hold.canReach {
if holds[i].climbableAfterPropogateReachable(fromBottom, fromTop, holds) {
return true
}
}
}
return false
}
func extraCreditOne() int {
holds := make([]ecHold, 0, 200)
count := 0
const minDist = 0.1
const minDist2 = minDist * minDist
for {
x := rand.Float64()
y := rand.Float64()
reachableFromBottom := y < minDist
reachableFromTop := y > 1.0-minDist
canReach := []int{}
for i := range holds {
dx := x - holds[i].x
dy := y - holds[i].y
if dx*dx+dy*dy < minDist2 {
canReach = append(canReach, i)
if holds[i].reachableFromBottom {
reachableFromBottom = true
}
if holds[i].reachableFromTop {
reachableFromTop = true
}
holds[i].canReach = append(holds[i].canReach, count)
}
}
holds = append(holds, ecHold{x, y, false, false, canReach})
if holds[count].climbableAfterPropogateReachable(reachableFromBottom, reachableFromTop, holds) {
return count + 1
}
count++
}
}
func extraCredit(n int) {
counts := make([]int, n)
for i := 0; i < n; i++ {
counts[i] = extraCreditOne()
}
println(n, avg(counts))
}
|
Python
|
UTF-8
| 968 | 2.609375 | 3 |
[] |
no_license
|
#-*- coding: utf-8 -*-
#
#
#
#
# Author:
#
# Copyright (c) SomeCorp.
from marshmallow import Schema, fields, ValidationError, post_load
from sqlalchemy_model import Person
import sys
def name_valid(data):
if not data:
raise ValidationError("No name provided")
def length_conforms_to_iso_country_standard(data):
if not data or not len(data) in [2,4]:
raise ValidationError("Data does not conform to specification (iso country with optional region)")
class PersonSchema(Schema):
id = fields.Int(dump_only = True)
name = fields.Str(validate = name_valid)
iso_country = fields.Str(validate = length_conforms_to_iso_country_standard)
#This decorator inflates an sqlalchemy Person after a .load({blah})
@post_load
def make_person(self, data):
print ('post_load in make_person, data: {}'.format(data), file=sys.stderr)
return Person(**data) if data else Person()
|
C#
|
UTF-8
| 3,615 | 3 | 3 |
[] |
no_license
|
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace Apress.VisualCSharpRecipes.Chapter08
{
public partial class Recipe08_02 : Form
{
// Define the shapes used on this form.
private GraphicsPath path;
private Rectangle rectangle;
// Define the flags that track where the mouse pointer is.
private bool inPath = false;
private bool inRectangle = false;
// Define the brushes used for painting the shapes.
Brush highlightBrush = Brushes.HotPink;
Brush defaultBrush = Brushes.LightBlue;
public Recipe08_02()
{
InitializeComponent();
}
private void Recipe08_02_Load(object sender, EventArgs e)
{
// Create the shapes that will be displayed.
path = new GraphicsPath();
path.AddEllipse(10, 10, 100, 60);
path.AddCurve(new Point[] {new Point(50, 50),
new Point(10,33), new Point(80,43)});
path.AddLine(50, 120, 250, 80);
path.AddLine(120, 40, 110, 50);
path.CloseFigure();
rectangle = new Rectangle(100, 170, 220, 120);
}
private void Recipe08_02_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
// Paint the shapes according to the current selection.
if (inPath)
{
g.FillPath(highlightBrush, path);
g.FillRectangle(defaultBrush, rectangle);
}
else if (inRectangle)
{
g.FillRectangle(highlightBrush, rectangle);
g.FillPath(defaultBrush, path);
}
else
{
g.FillPath(defaultBrush, path);
g.FillRectangle(defaultBrush, rectangle);
}
g.DrawPath(Pens.Black, path);
g.DrawRectangle(Pens.Black, rectangle);
}
private void Recipe08_02_MouseMove(object sender, MouseEventArgs e)
{
using (Graphics g = this.CreateGraphics())
{
// Perform hit testing with rectangle.
if (rectangle.Contains(e.X, e.Y))
{
if (!inRectangle)
{
inRectangle = true;
// Highlight the rectangle.
g.FillRectangle(highlightBrush, rectangle);
g.DrawRectangle(Pens.Black, rectangle);
}
}
else if (inRectangle)
{
inRectangle = false;
// Restore the unhighlighted rectangle.
g.FillRectangle(defaultBrush, rectangle);
g.DrawRectangle(Pens.Black, rectangle);
}
// Perform hit testing with path.
if (path.IsVisible(e.X, e.Y))
{
if (!inPath)
{
inPath = true;
// Highlight the path.
g.FillPath(highlightBrush, path);
g.DrawPath(Pens.Black, path);
}
}
else if (inPath)
{
inPath = false;
// Restore the unhighlighted path.
g.FillPath(defaultBrush, path);
g.DrawPath(Pens.Black, path);
}
}
}
}
}
|
Java
|
UTF-8
| 1,832 | 3.375 | 3 |
[] |
no_license
|
package leetcode.pickone;
public class PallindromeLinkedList {
public static boolean isPallindrome(ListNode node) {
if (node == null) return false;
if (node.next == null) return true;
boolean flag = false;
LinkedListUtility llu = new LinkedListUtility();
int size = llu.size(node);
ListNode reversePointer = node;
ListNode secondHead = null;
int counter = 0;
int count = size / 2;
if (size % 2 != 0) {
while (counter < count - 1) {
reversePointer = reversePointer.next;
counter++;
}
secondHead = reversePointer.next.next;
reversePointer.next = null;
ListNode firstHead = llu.reverse(node);
while (firstHead != null && secondHead != null) {
if (firstHead.val == secondHead.val) {
flag = true;
firstHead = firstHead.next;
secondHead = secondHead.next;
} else {
flag = false;
break;
}
}
} else {
while (counter < count - 1) {
reversePointer = reversePointer.next;
counter++;
}
secondHead = reversePointer.next;
reversePointer.next = null;
ListNode firstHead = llu.reverse(node);
while (firstHead != null && secondHead != null) {
if (firstHead.val == secondHead.val) {
flag = true;
firstHead = firstHead.next;
secondHead = secondHead.next;
} else {
flag = false;
break;
}
}
}
return flag;
}
}
|
C#
|
UTF-8
| 1,655 | 2.640625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Interactivity;
namespace WpfPitchTuner.Helper
{
/// <summary>
/// Detach EventTrigger from element on Unload event
/// </summary>
class EventTriggerBehavior : Behavior<DependencyObject>
{
public static readonly DependencyProperty AttacherProperty =
DependencyProperty.RegisterAttached(
"Attacher",
typeof(FrameworkElement),
typeof(EventTriggerBehavior),
new FrameworkPropertyMetadata(OnAttacherChanged)
);
public static FrameworkElement GetAttacher(DependencyObject dp)
{
return (FrameworkElement)dp.GetValue(AttacherProperty);
}
public static void SetAttacher(DependencyObject dp, FrameworkElement value)
{
dp.SetValue(AttacherProperty, value);
}
private static void OnAttacherChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
FrameworkElement fe = (FrameworkElement)e.NewValue;
System.Windows.Interactivity.EventTrigger eve = (System.Windows.Interactivity.EventTrigger)((EventTriggerBehavior)obj).AssociatedObject;
fe.Unloaded += (sender, re) => { eve.Detach(); };
}
public EventTriggerBehavior()
{
}
protected override void OnAttached()
{
base.OnAttached();
}
protected override void OnDetaching()
{
base.OnDetaching();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.