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
|
|---|---|---|---|---|---|---|---|
Markdown
|
UTF-8
| 4,837
| 3.203125
| 3
|
[
"MIT"
] |
permissive
|
## 스프링 REST Client
### RestTemplate
- Blocking I/O 기반의 Synchronous API
- RestTemplateAutoConfiguration
- 프로젝트에 spring-web 모듈이 있다면 RestTemplateBuilder를 빈으로 등록해 줍니다.
- [공식문서 참고](https://docs.spring.io/spring/docs/current/spring-framework-reference/integration.html#rest-client-access)
**예제 코드**
```java
@RestController
public class SampleController {
@GetMapping("/hello")
public String hello() throws InterruptedException {
Thread.sleep(5000);
return "hello";
}
@GetMapping("/world")
public String world() throws InterruptedException {
Thread.sleep(3000);
return "world";
}
}
```
```java
@Component
public class RestTemplateRunner implements ApplicationRunner {
@Autowired
RestTemplateBuilder builder;
@Override
public void run(ApplicationArguments args) throws Exception {
RestTemplate restTemplate = builder.build();
StopWatch stopWatch = new StopWatch();
stopWatch.start();
String helloResult = restTemplate.getForObject("http://localhost:8080/hello", String.class);
System.out.println(helloResult);
String worldResult = restTemplate.getForObject("http://localhost:8080/world", String.class);
System.out.println(worldResult);
stopWatch.stop();
System.out.println(stopWatch.prettyPrint());
}
}
```
예제코드가 수행되면 `Thread.sleep()`이 Synchronous하게 총 8초동안 수행되므로, stopwatch에도 약 8초정도의 시간이 걸린다.
#### RestTemplate Customizing
- RestTemplate은 기본으로 java.net.HttpURLConnection 사용.
**로컬 커스터마이징**
- build()를 수행하기 전에, 커스터마이징을 할 수 있다.
```java
public class RestTemplateRunner implements ApplicationRunner {
RestTemplate restTemplate;
public RestTemplateRunner(RestTemplateBuilder builder) {
restTemplate = builder.setConnectTimeout(Duration.ofMinutes(3)).build();
}
}
```
**글로벌 커스터마이징**
```java
@Bean
public RestTemplateCustomizer restTemplateCustomizer() {
return new RestTemplateCustomizer() {
@Override
public void customize(RestTemplate restTemplate) {
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
}
};
}
```
- 의존성에 apache http Client를 추가하고, 위의 예시처럼 커스터마이징하면 restTemplate을 HttpClient으로 사용할 수 있다.
### WebClient
- Non-Blocking I/O 기반의 Asynchronous API
- WebClientAutoConfiguration
- 프로젝트에 spring-webflux 모듈이 있다면 WebClient.Builder를 빈으로 등록해 줍니다.
- [공식문서 참고](https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#webflux-client)
**예제 코드**
```java
@RestController
public class SampleController {
//위의 예제와 동일.
}
```
```java
@Component
public class WebClientRunner implements ApplicationRunner {
@Autowired
WebClient.Builder builder;
@Override
public void run(ApplicationArguments args) throws Exception {
WebClient webClient = builder.build();
StopWatch stopWatch = new StopWatch();
stopWatch.start();
Mono<String> helloMono = webClient.get()
.uri("http://localhost:8080/hello")
.retrieve()
.bodyToMono(String.class);
helloMono.subscribe(s->{
System.out.println(s);
if(stopWatch.isRunning()) {
stopWatch.stop();
}
System.out.println(stopWatch.prettyPrint());
stopWatch.start();
});
Mono<String> worldMono = webClient.get()
.uri("http://localhost:8080/world")
.retrieve()
.bodyToMono(String.class);
worldMono.subscribe(s -> {
System.out.println(s);
if (stopWatch.isRunning()) {
stopWatch.stop();
}
System.out.println(stopWatch.prettyPrint());
stopWatch.start();
});
}
}
```
webClient는 subscribe()가 호출되었을 때, API 요청을 보내고 그 결과를 비동기적으로 받게 된다. 따라서 `/hello`에 대한 요청을 수행하고, 그 결과를 바로 받는 것이 아니라, `/world`에 대한 요청을 수행한다. `RestTemplate`을 사용했을 때에는 8초라는 시간이 걸렸지만, `WebClient`를 사용했을 때에는 5초 정도의 시간밖에 걸리지 않는다.
### WebClient Customizing
**로컬 커스터마이징**
```java
public class WebClientRunner implements ApplicationRunner {
WebClient webClient;
public WebClientRunner(WebClient.Builder builder) {
webClient = builder.baseUrl("http://localhost:8080").build();
}
}
```
**글로벌 커스터마이징**
```java
@Bean
public WebClientCustomizer webClientCustomizer() {
return new WebClientCustomizer() {
@Override
public void customize(Builder webClientBuilder) {
webClientBuilder.baseUrl("http://localhost:8080");
}
};
}
```
|
JavaScript
|
UTF-8
| 5,632
| 3.265625
| 3
|
[] |
no_license
|
import '../../globalTest';
import Set from '../../../src/data-structures/sets/Set';
const set = new Set();
describe('@Set', () => {
describe('#add', () => {
it('should be a function', () => {
assert.typeOf(set.add, 'function', 'add should be a function');
});
it('should add new element(s)', () => {
set.add(1);
set.add(2);
set.add(3);
set.add(4);
set.add(5);
console.log(cyan, 'Current Set ========> ', green, set.getItems());
// The set should have 5 elements (length)
const actualResult = set.size();
const expectedResult = 5;
assert.isTrue(expectedResult === actualResult);
});
});
describe('#delete', () => {
it('should be a function', () => {
assert.typeOf(set.delete, 'function', 'delete should be a function');
});
it('should delete an element', () => {
const actualResult = set.delete(4);
const expectedResult = true;
console.log(cyan, 'Current Set ========> ', green, set.getItems());
assert.isTrue(expectedResult === actualResult);
});
});
describe('#has', () => {
it('should be a function', () => {
assert.typeOf(set.has, 'function', 'has should be a function');
});
it('should validate if a set has an element', () => {
// Getting the first element
const actualResult = set.has(2);
const expectedResult = true;
assert.isTrue(expectedResult === actualResult);
});
});
describe('#size', () => {
it('should be a function', () => {
assert.typeOf(set.size, 'function', 'size should be a function');
});
it('should return the current size of the queue', () => {
// Getting the size of the actual list
const actualResult = set.size();
const expectedResult = 4;
assert.isTrue(expectedResult === actualResult);
});
});
describe('#values', () => {
it('should be a function', () => {
assert.typeOf(set.values, 'function', 'values should be a function');
});
it('should return the current values in array', () => {
const actualResult = set.values();
const expectedResult = [1, 2, 3, 5];
assert.deepEqual(expectedResult, actualResult, 'expectedResult should match actualResult');
});
});
describe('#clear', () => {
it('should be a function', () => {
assert.typeOf(set.clear, 'function', 'clear should be a function');
});
it('should clear the set', () => {
set.clear();
const actualResult = set.size();
const expectedResult = 0;
assert.isTrue(expectedResult === actualResult);
});
});
describe('#union', () => {
it('should be a function', () => {
assert.typeOf(set.union, 'function', 'union should be a function');
});
it('should return the union of two sets', () => {
const setA = new Set();
setA.add(1);
setA.add(2);
setA.add(3);
const setB = new Set();
setB.add(4);
setB.add(5);
setB.add(6);
const unionAB = setA.union(setB);
console.log(cyan, 'Current Set ========> ', green, unionAB.getItems());
// The union set should have [1, 2, 3, 4, 5, 6]
const actualResult = unionAB.values();
const expectedResult = [1, 2, 3, 4, 5, 6];
assert.deepEqual(expectedResult, actualResult, 'expectedResult should match actualResult');
});
});
describe('#intersection', () => {
it('should be a function', () => {
assert.typeOf(set.union, 'function', 'intersection should be a function');
});
it('should return the intersection of two sets', () => {
const setA = new Set();
setA.add(1);
setA.add(2);
setA.add(3);
const setB = new Set();
setB.add(2);
setB.add(3);
setB.add(4);
const intersectionAB = setA.intersection(setB);
console.log(cyan, 'Current Set ========> ', green, intersectionAB.getItems());
// The intersection set should have [2, 3]
const actualResult = intersectionAB.values();
const expectedResult = [2, 3];
assert.deepEqual(expectedResult, actualResult, 'expectedResult should match actualResult');
});
});
describe('#difference', () => {
it('should be a function', () => {
assert.typeOf(set.union, 'function', 'difference should be a function');
});
it('should return the difference of two sets', () => {
const setA = new Set();
setA.add(1);
setA.add(2);
setA.add(3);
const setB = new Set();
setB.add(2);
setB.add(3);
setB.add(4);
const differenceAB = setA.difference(setB);
console.log(cyan, 'Current Set ========> ', green, differenceAB.getItems());
// The difference set should have [1]
const actualResult = differenceAB.values();
const expectedResult = [1];
assert.deepEqual(expectedResult, actualResult, 'expectedResult should match actualResult');
});
});
describe('#subset', () => {
it('should be a function', () => {
assert.typeOf(set.union, 'function', 'subset should be a function');
});
it('should return the subset of two sets', () => {
const setA = new Set();
setA.add(1);
setA.add(2);
const setB = new Set();
setB.add(1);
setB.add(2);
setB.add(3);
const setC = new Set();
setB.add(2);
setB.add(3);
setB.add(4);
assert.isTrue(setA.subset(setB)); // Set A is subset of Set B (contains both values)
assert.isFalse(setA.subset(setC)); // Set A is not subset of Set C (just contains 2)
});
});
});
|
PHP
|
UTF-8
| 1,109
| 2.5625
| 3
|
[] |
no_license
|
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers:Origin, X-Requested-With, Content-Type, Accept');
//var_dump($_POST);
//获取applicatin-json的数据类型 然后解析对象 插入到数据库中使用
//获取JSON的输入流对象
// 判断Header头是 appliction-json 对象类型 才执行下面的代码
$array = getallheaders();
$conteyType = $array['Content-Type'];
// MIMEtype 类型
// echo $conteyType;
$obj = $_POST;
//将数据插入到数据库中
require "./extends/Model.class.php";
require "./extends/config.php";
$model=new Model("s_information");
$detailResult = $model->add($obj);
$returnResult=[];
if($detailResult>0){
$returnResult['code'] = 0;
$returnResult['data'] = "添加成功";
echo json_encode($returnResult);
}else{
$returnResult['code'] = 1;
$returnResult['data'] = "添加失败";
echo json_encode($returnResult);
}
|
Python
|
UTF-8
| 11,719
| 2.546875
| 3
|
[] |
no_license
|
import json, csv, sys, getopt, os, math, operator, random, scipy, nltk
import numpy as np
from nltk.tokenize import TweetTokenizer
from collections import defaultdict
from sklearn.svm import SVC
from sklearn.naive_bayes import MultinomialNB
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import AdaBoostClassifier, RandomForestClassifier, GradientBoostingClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.feature_extraction.text import TfidfTransformer, CountVectorizer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline, FeatureUnion
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
from sklearn.preprocessing import FunctionTransformer
from scipy.sparse import hstack, csr_matrix
from nltk.tokenize import word_tokenize
# reads items in json file as a list of dicts, where the entries are "article_link", "headline", "is_sarcastic"
def read_headlines(filename = 'data/headlines/Sarcasm_Headlines_Dataset.json'):
artList = []
with open(filename) as f:
for jsonObj in f:
art = json.loads(jsonObj)
artList.append(art)
return artList
# associate headlines with labels
def naive_headlines(articles=read_headlines()):
artlist = {}
for art in articles:
artlist[art["headline"]] = art["is_sarcastic"]
return artlist
# extract tweets as dict mapping tweet to sarcasm = 1, not sarcasm = 0
def read_tweets(filename = 'data/twitter/sarcasm-dataset.txt'):
tweetlist = {}
with open(filename, 'r') as fp:
for twt in fp:
tweetlist[twt[0:len(twt)-2].strip()] = twt[-2]
return tweetlist
votes_train = []
votes_test = []
# returns json file as dict
def read_reddit(filename = 'data/reddit/comments.json'):
with open(filename) as f:
for jsonObj in f:
c = json.loads(jsonObj)
return c
# associates comments with labels, also extracts votes
def read_reddit_label(filename = 'data/reddit/train-balanced.csv'):
comments = read_reddit()
with open(filename) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
lab = {}
for row in csv_reader:
line_count+=1
sp = row[0].split('|')
for i,s in enumerate(sp[1].split()):
lab[s] = int(sp[2].split()[i])
if filename == 'data/reddit/train-balanced.csv':
global votes_train
votes_train = [[abs(comments[i]['ups']),abs(comments[i]['downs'])] for i in list(lab.keys())]
else:
global votes_test
votes_test = [[abs(comments[i]['ups']),abs(comments[i]['downs'])] for i in list(lab.keys())]
print(f'Processed {line_count} lines.')
return ([comments[i]['text'] for i in list(lab.keys())], list(lab.values()))
# collects tweets and labels from csv file
def read_tweets_csv(filename = 'data/twitter/dataset_csv.csv'):
tweetlist = {}
numTweets = 0
with open(filename, 'r') as fp:
for i,twt in enumerate(fp):
numTweets = i
tweetlist[twt[0:len(twt)-2].strip()] = twt[-2]
print("num tweets (csv file): {}".format(numTweets+1))
return tweetlist
# finds length of each document in the corpus
def get_length(x):
return np.array([len(t) for t in x]).reshape(-1, 1)
posW = set()
negW = set()
# extracts positive and negative sentiment lexicons from NRC set
def buildSentiment():
with open('data/sentiment/NRC-emotion-lexicon.txt', 'r') as fp:
for line in fp:
word,emotion,value = line.split('\t')
if emotion == 'positive' and int(value) == 1:
posW.add(word)
if emotion == 'negative' and int(value) == 1:
negW.add(word)
# finds the number of positive and negative sentiment words, as well as their ratio (with correction for negative denominator).
def use_sentiment(x):
sent = []
for t in x:
words = t.split()
poscount = negcount = 0
ratio = 100
for word in words:
if word in posW:
poscount += 1
if word in negW:
negcount += 1
if negcount != 0:
ratio = float(poscount)/negcount
if poscount == 0 and negcount == 0:
ratio = 0
elif poscount == 0 and negcount != 0:
ratio = negcount
sent.append([poscount,negcount,ratio])
return np.array(sent).reshape(-1, 3)
# takes the votes on the comment into account
def use_score(x):
if len(x) == len(votes_train):
return np.array(votes_train).reshape(-1, 2)
else:
return np.array(votes_test).reshape(-1, 2)
# adds parts of speech tags to each word, appended with a /
def add_pos(x):
docs = []
for t in x:
text_tagged = nltk.pos_tag(t)
new_text = [word[0] + "/" + word[1] for word in text_tagged]
doc = ' '.join(new_text)
docs.append(doc)
return docs
# builds pipeline for the classifier, using text (character) features, document length, sentiment, POS tags, and votes
def clf(classifier = MultinomialNB()):
c = Pipeline([
('features', FeatureUnion([
('text', Pipeline([
('vectorizer', CountVectorizer(analyzer='char', ngram_range=(1, 6))),
# ('tfidf', TfidfTransformer()),
])),
('length', Pipeline([
('count', FunctionTransformer(get_length, validate=False)),
])),
('sentiment', Pipeline([
('sentcount', FunctionTransformer(use_sentiment, validate=False)),
])),
# ('POS', Pipeline([
# ('tags', FunctionTransformer(add_pos, validate=False)),
# ('vect', CountVectorizer()),
# ])),
# ('votes', Pipeline([
# ('updown', FunctionTransformer(use_score, validate=False)),
# ]))
])),
('clf', classifier)])
return c
def main():
# data = naive_headlines()
# X_train, X_test, y_train, y_test = train_test_split(list(data.keys()), list(data.values()), random_state=1)
# cv = CountVectorizer()
# X_train_cv = cv.fit_transform(X_train)
# X_test_cv = cv.transform(X_test)
# setup for SARC 2.0 dataset
comments = read_reddit()
X_train, y_train = read_reddit_label()
X_test, y_test = read_reddit_label('data/reddit/test-balanced.csv')
buildSentiment()
# cv = CountVectorizer(ngram_range=(1, 2))
cv = CountVectorizer(analyzer='char', ngram_range=(1, 6))
X_train_cv = cv.fit_transform(X_train)
X_test_cv = cv.transform(X_test)
# SVC
# svc = clf(SVC())
# svc.fit(X_train, y_train)
# predictions = svc.predict(X_test)
# print('SVC Accuracy score: ', accuracy_score(y_test, predictions))
# print('SVC Precision score: ', precision_score(y_test, predictions))
# print('SVC Recall score: ', recall_score(y_test, predictions))
# print('SVC F1 score: ', f1_score(y_test, predictions))
# Naïve Bayes
nb = clf()
nb.fit(X_train, y_train)
predictions = nb.predict(X_test)
print('NB Accuracy score: ', accuracy_score(y_test, predictions))
print('NB Precision score: ', precision_score(y_test, predictions))
print('NB Recall score: ', recall_score(y_test, predictions))
print('NB F1 score: ', f1_score(y_test, predictions))
acc_sarc = 0
acc_non = 0
count_sarc = 0
count_non = 0
for i in range(len(predictions)):
if predictions[i] == 1:
count_sarc += 1
if y_test[i] == 1:
acc_sarc += 1
if predictions[i] == 0:
count_non += 1
if y_test[i] == 0:
acc_non += 1
print(acc_sarc/count_sarc, acc_non/count_non)
# Logistic Regression
lr = clf(LogisticRegression())
lr.fit(X_train,y_train)
# print top 20 weights
# coeff = lr.named_steps['clf'].coef_[0]
# fnames = dict(lr.named_steps['features'].transformer_list).get('text').named_steps['vectorizer'].get_feature_names()
# coefs_with_fns = sorted(zip(coeff[0:len(fnames)+1], fnames))
# top = zip(coefs_with_fns[:20], coefs_with_fns[:-(20 + 1):-1])
# for (coef_1, fn_1), (coef_2, fn_2) in top:
# print ("\t%.4f\t%-15s\t\t%.4f\t%-15s" % (coef_1, fn_1, coef_2, fn_2))
predictions = lr.predict(X_test)
print('LR Accuracy score: ', accuracy_score(y_test, predictions))
print('LR Precision score: ', precision_score(y_test, predictions))
print('LR Recall score: ', recall_score(y_test, predictions))
print('LR F1 score: ', f1_score(y_test, predictions))
acc_sarc = 0
acc_non = 0
count_sarc = 0
count_non = 0
for i in range(len(predictions)):
if predictions[i] == 1:
count_sarc += 1
if y_test[i] == 1:
acc_sarc += 1
if predictions[i] == 0:
count_non += 1
if y_test[i] == 0:
acc_non += 1
print(acc_sarc/count_sarc, acc_non/count_non)
# SVC
# svc = clf(SVC())
# svc.fit(X_train, y_train)
# predictions = svc.predict(X_test)
# print('SVC Accuracy score: ', accuracy_score(y_test, predictions))
# print('SVC Precision score: ', precision_score(y_test, predictions))
# print('SVC Recall score: ', recall_score(y_test, predictions))
# print('SVC F1 score: ', f1_score(y_test, predictions))
# Adaboost Classifier
# abc = clf(AdaBoostClassifier(n_estimators=1000, learning_rate = 0.9, random_state=0))
# abc.fit(X_train, y_train)
# predictions = abc.predict(X_test)
# print('Adaboost Accuracy score: ', accuracy_score(y_test, predictions))
# print('Adaboost Precision score: ', precision_score(y_test, predictions))
# print('Adaboost Recall score: ', recall_score(y_test, predictions))
# print('Adaboost F1 score: ', f1_score(y_test, predictions))
# Random Forest
# rf = clf(RandomForestClassifier(max_depth=2, random_state=0))
# rf.fit(X_train, y_train)
# predictions = rf.predict(X_test)
# print('RandomForest Accuracy score: ', accuracy_score(y_test, predictions))
# print('RandomForest Precision score: ', precision_score(y_test, predictions))
# print('RandomForest Recall score: ', recall_score(y_test, predictions))
# print('RandomForest F1 score: ', f1_score(y_test, predictions))
# Gradient Boosting
gb = clf(GradientBoostingClassifier(loss='deviance'))
gb.fit(X_train, y_train)
predictions = gb.predict(X_test)
print('GB Accuracy score: ', accuracy_score(y_test, predictions))
print('GB Precision score: ', precision_score(y_test, predictions))
print('GB Recall score: ', recall_score(y_test, predictions))
print('GB F1 score: ', f1_score(y_test, predictions))
acc_sarc = 0
acc_non = 0
count_sarc = 0
count_non = 0
for i in range(len(predictions)):
if predictions[i] == 1:
count_sarc += 1
if y_test[i] == 1:
acc_sarc += 1
if predictions[i] == 0:
count_non += 1
if y_test[i] == 0:
acc_non += 1
print(acc_sarc/count_sarc, acc_non/count_non)
# K-neighbors
# kn = clf(KNeighborsClassifier())
# kn.fit(X_train, y_train)
# predictions = kn.predict(X_test)
# print('KN Accuracy score: ', accuracy_score(y_test, predictions))
# print('KN Precision score: ', precision_score(y_test, predictions))
# print('KN Recall score: ', recall_score(y_test, predictions))
# print('KN F1 score: ', f1_score(y_test, predictions))
if __name__ == "__main__":
main()
|
C++
|
UTF-8
| 2,181
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
#include <functional>
#include "requests/request_factory.h"
#include "requests/request.h"
#include "requests/write_logs_request.h"
#include "requests/new_logger_request.h"
#include "requests/configuration_update_request.h"
#include "requests/flags_update_request.h"
Request* RequestFactory::buildRequest(JsonPacket* jsonPacket, Credentials* credentials)
{
Request* request = nullptr;
if (!jsonPacket->hasKey(Request::kKeyType)) {
LOG(ERROR) << "Request type not received";
} else {
RequestType type = RequestTypeHelper::findRequestTypeFromJson(jsonPacket);
// Intel C++ does not yet support switch over strongly-typed enums so we use if-statements
if (type == RequestType::WriteLogs) {
request = new WriteLogsRequest(jsonPacket, credentials);
} else if (type == RequestType::NewLogger) {
request = new NewLoggerRequest(jsonPacket, credentials);
} else if (type == RequestType::ConfigurationUpdate) {
request = new ConfigurationUpdateRequest(jsonPacket, credentials);
} else if (type == RequestType::FlagsUpdate) {
request = new FlagsUpdateRequest(jsonPacket, credentials);
} else {
LOG(ERROR) << "Invalid request type received";
}
}
return request;
}
void RequestFactory::updateTarget(JsonPacket* jsonPacket, const std::string& key, const std::string& defaultVal, std::string* target, bool optionalKey)
{
updateTarget(jsonPacket, key, defaultVal, target, optionalKey, std::bind(&JsonPacket::getString, &*jsonPacket, key, defaultVal));
}
void RequestFactory::updateTarget(JsonPacket* jsonPacket, const std::string& key, int defaultVal, int* target, bool optionalKey)
{
updateTarget(jsonPacket, key, defaultVal, target, optionalKey, std::bind(&JsonPacket::getInt, &*jsonPacket, key, defaultVal));
}
template <typename T, class Func>
void RequestFactory::updateTarget(JsonPacket *jsonPacket, const std::string &key, const T& defaultVal, T* target, bool optionalKey, const Func& f)
{
if (optionalKey) {
if (!jsonPacket->hasKey(key)) {
return;
}
}
*target = f(key, defaultVal);
}
|
TypeScript
|
UTF-8
| 1,068
| 2.515625
| 3
|
[] |
no_license
|
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class SharedService {
constructor() {}
getErrorMessageFormInput(form, input: string): string | null {
console.log(form, input);
if (form.hasError('required', [input])) {
return 'You must enter a value';
}
if (form.hasError('email', [input])) {
return 'Not a valid email';
}
if (form.hasError('minlength', [input])) {
const { actualLength, requiredLength } = form.getError('minlength', [input]);
return `Min length is ${requiredLength}, you enter ${actualLength}`;
}
return null;
}
getErrorMessageInput(control): string | null {
if (control.hasError('required')) {
return 'You must enter a value';
}
if (control.hasError('email')) {
return 'Not a valid email';
}
if (control.hasError('minlength')) {
const { actualLength, requiredLength } = control.getError('minlength');
return `Min length is ${requiredLength}, you enter ${actualLength}`;
}
return null;
}
}
|
Python
|
UTF-8
| 929
| 2.765625
| 3
|
[] |
no_license
|
import logging
import boto3
import config
def obj_last_modified(myobj):
"""
Gets the last modified date of the file
:param myobj:
:return: Last Modified timestamp of file
"""
return myobj['LastModified']
def fileWithLeastTimestamp():
"""
Gets the file with the least timestamp
:return: file with the least timestamp
"""
s3client = boto3.client('s3')
try:
response = s3client.list_objects(Bucket=config.BUCKET_NAME, Prefix=config.PREFIX)
print('resonpnse is: ', response)
except Exception as e:
logging.error(e)
print(f'Unexpected error while listing the dir {config.BUCKET_NAME}:{config.PREFIX}')
if ('Contents' in response):
l = []
for key in response['Contents']:
l.append(key)
sortedObjects = sorted(l, key=obj_last_modified, reverse=False)
return sortedObjects[0]['Key']
return None
|
Go
|
UTF-8
| 1,874
| 2.765625
| 3
|
[] |
no_license
|
package api
import (
"FRSC-Project/error"
"FRSC-Project/model"
"encoding/json"
"fmt"
"log"
"net/http"
)
func setupResponse(w *http.ResponseWriter, req *http.Request) {
(*w).Header().Set("Access-Control-Allow-Origin", "*")
(*w).Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
}
func (a *api) RegisterBus(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var buses model.Motor
err := json.NewDecoder(r.Body).Decode(&buses)
setupResponse(&w, r)
if (*r).Method == "POST" {
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
err = a.service.Validate(&buses)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(error.ServiceError{Message: err.Error()})
return
}
bus, err := a.service.RegisterBus(buses)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Fatal(err)
return
}
//w.WriteHeader(model.StatusCreated)
json.NewEncoder(w).Encode(bus)
} else {
w.WriteHeader(http.StatusMethodNotAllowed)
fmt.Println("error")
json.NewEncoder(w).Encode(error.ServiceError{Message: "Method not allowed"})
}
}
func (a *api) GetBuses(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
buses, err := a.service.Buses()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Fatal(err)
return
}
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(buses)
}
func (a *api) CheckMembership(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var buses model.Motor
bus, err := a.service.CheckMembership(&buses)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Fatal(err)
return
}
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(bus)
}
|
Rust
|
UTF-8
| 4,212
| 2.953125
| 3
|
[
"MIT"
] |
permissive
|
use super::{Board};
use constants::{Rank, File, PieceType, FILE_COUNT, RANK_COUNT, BLACK, WHITE};
use util::{piece_list_to_string};
use board::{parse_fen_pieces};
use board::mailbox::{Mailbox};
pub struct PieceIter<'a> {
board: &'a Board,
current_rank: Rank,
current_file: File,
}
impl<'a> PieceIter<'a> {
pub fn new(board: &'a Board) -> Self {
PieceIter {
board: board,
current_rank: 0,
current_file: 0,
}
}
}
impl<'a> Iterator for PieceIter<'a> {
type Item = PieceType;
fn next(&mut self) -> Option<PieceType> {
let res: Option<PieceType>;
if self.current_rank >= RANK_COUNT {
res = None;
} else {
let ty: PieceType = self.board.mb.get(self.current_file, self.current_rank);
res = Some(ty);
}
if self.current_file + 1 >= FILE_COUNT {
self.current_file = 0;
self.current_rank += 1;
} else {
self.current_file += 1;
}
res
}
}
pub fn assert_boards_equal(board1: &Board, board2: &Board) {
assert!(board1.bb == board2.bb);
assert_eq!(board1.to_move, board2.to_move);
assert_eq!(board1.castling, board2.castling);
assert_eq!(board1.en_passant, board2.en_passant);
assert_eq!(board1.zhash, board2.zhash);
assert!(board1.mb.eq(&board2.mb));
}
pub fn are_boards_equal(board1: &Board, board2: &Board) -> bool {
board1.bb == board2.bb &&
board1.to_move == board2.to_move &&
board1.zhash == board2.zhash &&
board1.castling == board2.castling &&
board1.en_passant == board2.en_passant &&
board1.mb.eq(&board2.mb)
}
mod tests {
#[allow(unused_imports)]
use super::*;
use constants::*;
mod piece_iter {
#[allow(unused_imports)]
use super::*;
// #[test]
// fn from_fen_start_board() {
// let board = Board::from_fen(START_FEN);
// let subject = PieceIter::new(board);
// let pieces = subject.collect::<Vec<PieceType>>();
// assert_eq!(pieces., NO_EN_PASSANT);
// }
#[test]
fn from_fen_custom_board() {
let board = Board::from_fen("r1bqkbnr/p2ppp2/2n3p1/Pp6/2PNP2p/8/1P3PPP/RNBQKB1R w KQkq b6 7 4");
assert_eq!(board.en_passant, 1);
assert_eq!(board.castling, 0b1111);
assert_eq!(board.mb.get(3,3), W_KNIGHT);
assert_eq!(board.mb.get(7,7), B_ROOK);
assert_eq!(board.mb.get(4,3), W_PAWN);
assert_eq!(board.to_move, WHITE);
assert_eq!(board.halfmove_counter, 7);
assert_eq!(board.fullmove_counter, 3);
}
#[test]
fn test_print_board() {
let board = Board::from_fen(START_FEN);
board.print_board();
}
#[test]
fn test_get_pieces_of_color() {
let board = Board::from_fen(START_FEN);
let white_pieces = board.get_pieces_of_color(WHITE);
let black_pieces = board.get_pieces_of_color(BLACK);
assert_eq!(white_pieces.len(), 16);
assert_eq!(black_pieces.len(), 16);
board.print_board();
}
}
mod mailbox {
#[allow(unused_imports)]
use super::*;
#[test]
fn get() {
let mb: Mailbox = Mailbox([5; 128]);
for f in 0..FILE_COUNT {
for r in 0..RANK_COUNT {
assert_eq!(mb.get(f,r), 5);
}
}
}
#[test]
fn set() {
let mut mb: Mailbox = Mailbox([5; 128]);
mb.set(0,0, 10);
assert_eq!(mb.get(0,0), 10);
}
}
#[test]
fn parse_fen_pieces_default() {
let pieces = parse_fen_pieces("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR");
assert_eq!(pieces.len(), 32);
let s = piece_list_to_string(&pieces);
assert_eq!(s, "[ra8, nb8, bc8, qd8, ke8, bf8, ng8, rh8, pa7, pb7, pc7, pd7, pe7, pf7, pg7, ph7, Pa2, Pb2, Pc2, Pd2, Pe2, Pf2, Pg2, Ph2, Ra1, Nb1, Bc1, Qd1, Ke1, Bf1, Ng1, Rh1]");
}
}
|
Markdown
|
UTF-8
| 19,004
| 2.734375
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
---
layout: post
title: What I'm Playing - No. 52
author: bsinky
description: "I played through Luigi's Mansion Dark Moon, and started The Legend of Zelda: Breath of the Wild!"
date: 2019-12-30
modified: 2019-12-30
categories: [Weekly]
tags: [What I'm Playing,Weekly,Casual]
image:
feature: feature-3ds-and-switch-1.jpg
credit: Steve Johnson
creditlink: https://www.pexels.com/photo/crystal-glass-on-a-colorful-background-2179374/
thumb: feature-3ds-and-switch-1-thumb.jpg
games: ["Luigi's Mansion Dark Moon", "Super Mario Odyssey", "The Legend of Zelda Breath of the Wild"]
---
Welcome back to another weekly wrap-up of the games I've been playing over the
past week!
We've reached the final What I'm Playing post of 2019. Whether you're here for
the first time, or you've been reading since post number 1, thanks for visiting!
My Luigi's Mansion section is spoiler-free, though there's not really much to
spoil in that game. For Breath of the Wild, I've spoiled the general premise and
backstory of the plot. If you want to go in without knowing that, then skip that
section this week!
Click a title to skip to that section. Games contained within this post:
- [Luigi's Mansion Dark Moon *(3DS)*]({{ page.url }}#LuigisMansionDarkMoon)
- [Super Mario Odyssey *(Switch)*]({{ page.url }}#SuperMarioOdyssey)
- [The Legend of Zelda: Breath of the Wild *(Switch)*]({{ page.url }}#TheLegendofZelda:BreathoftheWild)
<!--more-->
### Luigi's Mansion Dark Moon *(3DS)* {#LuigisMansionDarkMoon}
[](https://i.imgur.com/vhEHKCh.png)
{: .image-right }
I played through Luigi's Mansion Dark Moon this week! For some reason, it's only
in North America that it was given this name. The rest of the world knows it as
Luigi's Mansion 2, which I think makes far more sense. Maybe Nintendo of America
was afraid of branding it as a full sequel since it does deviate from the
original in a number of ways? Whatever the case, it was a fun experience, and a
solid follow-up to the original!
In the beginning, Professor E. Gadd is researching and living with peaceful
ghosts in the Evershade Valley. The ghosts there are peaceful due to the effects
of the mysterious Dark Moon that hangs in the sky. However, when a mysterious
silhouette shatters the Dark Moon, the ghosts become mischievous and violent.
<figure class="third">
<a href="https://i.imgur.com/7DDs8JR.png"><img src="https://i.imgur.com/7DDs8JRm.png" alt="researching and living with peaceful ghosts"/></a>
<a href="https://i.imgur.com/U2DTa77.png"><img src="https://i.imgur.com/U2DTa77m.png" alt="a mysterious silhouette shatters the Dark Moon"/></a>
<a href="https://i.imgur.com/wufzmvR.png"><img src="https://i.imgur.com/wufzmvRm.png" alt="mischievous and violent"/></a>
</figure>
In response to this, E. Gadd flees to his underground bunker, and summons up his
go-to ghost-hunting lackey, Luigi against his will. He asks Luigi to seek out
the pieces of the Dark Moon so it can be made whole again. E. Gadd again brings
his inventions and knowledge of ghosts to the table to help Luigi, but the rest
is up to the lovable and fearful green Mario brother.
<figure class="third">
<a href="https://i.imgur.com/D2Bk9kz.png"><img src="https://i.imgur.com/D2Bk9kzm.png" alt="summons up"/></a>
<a href="https://i.imgur.com/gkyc8Oy.png"><img src="https://i.imgur.com/gkyc8Oym.png" alt="lovable"/></a>
<a href="https://i.imgur.com/p1RR5R3.png"><img src="https://i.imgur.com/p1RR5R3m.png" alt="fearful green Mario"/></a>
</figure>
There are a number of changes to the formula compared to the original Luigi's
Mansion, but the core of the experience is the same. You'll guide Luigi to
explore rooms, find keys, solve puzzles, and suck up ghosts with your trusty
Poltergust vacuum. The mechanics of the ghost-catching are slightly tweaked, in
that you now need to press a button to shoot a stronger flashlight pulse at
ghosts to stun them, instead of just hitting them with the normal light from
your flashlight.
<figure class="third center">
<a href="https://i.imgur.com/Voz2SXL.png"><img src="https://i.imgur.com/Voz2SXLm.png" alt="explore rooms"/></a>
<a href="https://i.imgur.com/w9KGJYR.png"><img src="https://i.imgur.com/w9KGJYRm.png" alt="find keys"/></a>
</figure>
<figure class="third center">
<a href="https://i.imgur.com/pd9LBYz.png"><img src="https://i.imgur.com/pd9LBYzm.png" alt="suck up ghosts"/></a>
<a href="https://i.imgur.com/PYZ3XFU.png"><img src="https://i.imgur.com/PYZ3XFUm.png" alt="press a button to shoot a stronger flashlight pulse"/></a>
</figure>
[](https://i.imgur.com/Dc06yHQ.png)
{: .image-right }
You also charge up a meter while pulling against them as Luigi vacuums them up,
and when the meter is charged pressing A nets you bonus damage and keeps them
from escaping the Poltergust's pull for a while longer. These tweaks to the
ghost-catching mechanics worked pretty well, although having to "shoot" the
flashlight at ghosts to stun them is a little weird in premise, but it works
well as a gameplay element.
Additionally, there's a new exploration mechanic introduced early in the game.
Certain objects are invisible due to the presence of Spirit Balls. Shining your
Dark-Light Device will reveal these objects temporarily, and flush out the
Spirit Balls that are concealing it. Vacuuming up the Spirit Balls will dispel
the illusion, making the object permanently visible and allowing you to interact
with it normally. This is used in many puzzles throughout the game, and there
are also a bunch of doors hidden this way. It was a pretty fun mechanic, and
apparently it returns in Luigi's Mansion 3 as well!
<figure class="half">
<a href="https://i.imgur.com/AlqdXex.png"><img src="https://i.imgur.com/AlqdXexm.png" alt="Spirit Balls"/></a>
<a href="https://i.imgur.com/SjoizFI.png"><img src="https://i.imgur.com/SjoizFIm.png" alt="Dark-Light Device"/></a>
</figure>
One of the biggest changes to the gameplay structure compared to the first game
is that Dark Moon is mission based. The first game was sort of structured the
same way behind the scenes, with Luigi returning to E. Gadd after collecting
certain portrait ghosts, Dark Moon takes this much further and has actual
missions/levels. I haven't played it in a long time, but I think I prefer the
structure of the original game. That said, the design of Luigi's Mansion Dark
Moon is still fun. The missions are bite-sized, likely to adapt the formula to
shorter handheld gaming sessions, and a single mission took me, on average,
about 15 minutes, with the longest ones taking around 30 minutes if I got stuck
on a puzzle for a while.
<figure class="third">
<a href="https://i.imgur.com/KFD9oqE.png"><img src="https://i.imgur.com/KFD9oqEm.png" alt="mission based"/></a>
<a href="https://i.imgur.com/VicDswN.png"><img src="https://i.imgur.com/VicDswNm.png" alt="actual missions"/></a>
<a href="https://i.imgur.com/UG8yWYN.png"><img src="https://i.imgur.com/UG8yWYNm.png" alt="15 minutes"/></a>
</figure>
Another big change is that rather than taking place in a single mansion like the
first game, Luigi's Mansion Dark Moon has you visit 5 different mansions over
the course of the game. Each mansion was fun to explore, but I did find myself
thinking back longingly to the single, large mansion of the first game from time
to time.
<figure class="third center">
<a href="https://i.imgur.com/agfQtuF.png"><img src="https://i.imgur.com/agfQtuFm.png" alt="5 different mansions"/></a>
<a href="https://i.imgur.com/44FW2yS.png"><img src="https://i.imgur.com/44FW2ySm.png" alt="Each mansion"/></a>
</figure>
Lastly, there are no portrait ghosts in this game. Portrait ghosts were the
bosses and mini-bosses of the first game, but here they're mostly replaced by
more generic ghosts. The bosses in this game are mostly "possessor" ghosts, who
all look pretty much the same, and fight you by possessing something and
attacking you. The boss battles themselves were okay, but I feel like they're
not as good as the portrait ghost boss battles of the first game. That could
just be nostalgia talking though.
<figure class="half">
<a href="https://i.imgur.com/AbNXdPf.png"><img src="https://i.imgur.com/AbNXdPfm.png" alt="possessor"/></a>
<a href="https://i.imgur.com/niOQTXq.png"><img src="https://i.imgur.com/niOQTXqm.png" alt="possessing something and attacking you"/></a>
</figure>
I could ramble on more about the differences between the first 2 Luigi's Mansion
games, but I'll leave it there for now. There are aspects of each game I prefer.
Both have a lot of charm though, and are fun games that give Luigi a moment in
the spotlight!
<figure class="half">
<a href="https://i.imgur.com/bG5ZhOR.png"><img src="https://i.imgur.com/bG5ZhORm.png" alt="a lot of charm though"/></a>
<a href="https://i.imgur.com/4FT1Y7a.png"><img src="https://i.imgur.com/4FT1Y7am.png" alt="spotlight"/></a>
</figure>
### Super Mario Odyssey *(Switch)* {#SuperMarioOdyssey}
I played a little more Odyssey this week, and collected a few more Power Moons
by just wandering around or doing some shepherding. You know, the usual!
<figure class="half">
<a href="https://i.imgur.com/UbQf4sM.jpg"><img src="https://i.imgur.com/UbQf4sMm.jpg" alt="wandering around"/></a>
<a href="https://i.imgur.com/UtXtgxf.jpg"><img src="https://i.imgur.com/UtXtgxfm.jpg" alt="doing some shepherding"/></a>
</figure>
My Power Moon total is up to 520 now, but I feel like there's still so many left
to collect! Running and jumping around to find them still hasn't gotten old
though, it's just so much fun!
<figure class="half">
<a href="https://i.imgur.com/QPlIN1b.jpg"><img src="https://i.imgur.com/QPlIN1bm.jpg" alt="520 now"/></a>
<a href="https://i.imgur.com/tY545h8.jpg"><img src="https://i.imgur.com/tY545h8m.jpg" alt="so much fun"/></a>
</figure>
### The Legend of Zelda: Breath of the Wild *(Switch)* {#TheLegendofZelda:BreathoftheWild}
I finally started Breath of the Wild this week!
<figure class="half">
<a href="https://i.imgur.com/kBrjlLa.jpg"><img src="https://i.imgur.com/kBrjlLam.jpg" alt="Breath of the Wild"/></a>
<a href="https://i.imgur.com/4bp74i4.jpg"><img src="https://i.imgur.com/4bp74i4m.jpg" alt="this week"/></a>
</figure>
I'll briefly summarize the premise as revealed in the Great Plateau during the
beginning of the game. 100 years ago, Link was gravely injured fighting against
Ganon with Princess Zelda. Link awakens, healed, in the Shrine of Resurrection
after sleeping for 100 years. He picks up the Sheikah Slate, an advanced little
tablet that can activate Sheikah relics, which causes towers and shrines across
Hyrule to re-activate. He gains several Rune powers from shrines around the
Great Plateau. Then, the spirit of the King of Hyrule explains how Ganon took
control of the Guardians and Divine Beasts, ancient weapons the Hylians intended
to use to seal Ganon away, and with them laid waste to Hyrule. The King lost his
life to the Guardians, but his daughter Zelda survived. Even now, Zelda remains
at Hyrule Castle, keeping Ganon contained there. But her power is waning. It's
up to Link to help her defeat Calamity Ganon, and end the threat to the kingdom!
<figure class="third">
<a href="https://i.imgur.com/0FZJv91.jpg"><img src="https://i.imgur.com/0FZJv91m.jpg" alt="Link awakens"/></a>
<a href="https://i.imgur.com/unLImSJ.jpg"><img src="https://i.imgur.com/unLImSJm.jpg" alt="Sheikah Slate"/></a>
<a href="https://i.imgur.com/Qghm2rC.jpg"><img src="https://i.imgur.com/Qghm2rCm.jpg" alt="King of Hyrule"/></a>
</figure>
<figure class="third">
<a href="https://i.imgur.com/Q3h11YS.jpg"><img src="https://i.imgur.com/Q3h11YSm.jpg" alt="Guardians"/></a>
<a href="https://i.imgur.com/O8qJZGk.jpg"><img src="https://i.imgur.com/O8qJZGkm.jpg" alt="laid waste to Hyrule"/></a>
<a href="https://i.imgur.com/HW0CH3L.jpg"><img src="https://i.imgur.com/HW0CH3Lm.jpg" alt="up to Link"/></a>
</figure>
With that, you are given the Paraglider, and finally have a means to safely
leave the Great Plateau. From there, you're free to explore Hyrule. You could
guide Link directly to Hyrule Castle. However, the King advises that this would
be foolish, and instead advises you to seek out Impa at Kakariko Village. So,
that's exactly what I set out to do!
<figure class="half">
<a href="https://i.imgur.com/U5OiFpO.jpg"><img src="https://i.imgur.com/U5OiFpOm.jpg" alt="given the Paraglider"/></a>
<a href="https://i.imgur.com/ZkXLwry.jpg"><img src="https://i.imgur.com/ZkXLwrym.jpg" alt="this would be foolish"/></a>
</figure>
Of course, given the open world nature of the game, I got distracted along the
way. I stumbled upon a Korok, collecting a seed from it, got the Spirit Orb from
a Shrine along the way. After discovering my first stable, I found and tamed my
first horse, who I named Scrub. It's named after a Deku Scrub. I forgot how fun
riding a horse around Hyrule in a Zelda game is. Especially in Breath of the
Wild with its expansive world! Plus, you can attack from on horseback, similar
to how you were able to in Twilight Princess but this feels more polished.
<figure class="third">
<a href="https://i.imgur.com/JtbrpfV.jpg"><img src="https://i.imgur.com/JtbrpfVm.jpg" alt="Korok"/></a>
<a href="https://i.imgur.com/2rZ6nIA.jpg"><img src="https://i.imgur.com/2rZ6nIAm.jpg" alt="Shrine along the way"/></a>
<a href="https://i.imgur.com/JZqZspQ.jpg"><img src="https://i.imgur.com/JZqZspQm.jpg" alt="Scrub"/></a>
</figure>
Riding my trusty horse Scrub, I went exploring and found Hateno Village. I found
the Dye Shop here, where you can pay to dye your current set of armor, choosing
from a wide selection of colors. I went with light blue. It doesn't have any
effect on the stats of your equipment at all from what I can tell, but I'd still
consider it money well spent. With the armor and bandana died light blue, Link
looks like he's ready to join Team Aqua from Pokémon Ruby/Sapphire.
<figure class="half">
<a href="https://i.imgur.com/phMzIUm.jpg"><img src="https://i.imgur.com/phMzIUmm.jpg" alt="Hateno Village"/></a>
<a href="https://i.imgur.com/eryPPhS.jpg"><img src="https://i.imgur.com/eryPPhSm.jpg" alt="a wide selection of colors"/></a>
</figure>
[](https://i.imgur.com/w7stoDE.jpg)
{: .image-right }
After that, I got back on track pursuing my main quest to find Impa, and finally
made it to Kakariko Village. The Sheikah have always been like Hyrule's version
of ninja's, but the Japanese-sounding music and architecture of Kakariko Village
in Breath of the Wild really solidify this idea.
Anyway, I spoke with Impa and she had another quest for me, directing me to find
a Sheikah researcher at the lab near Hateno Village. Luckily since my detour
took me to the Shrine near there earlier, I could fast travel back! I quickly
found the researcher, Purah. With her help, the final rune of the Sheikah Slate
was unlocked: the Camera.
<figure class="third">
<a href="https://i.imgur.com/nu0U5Zo.jpg"><img src="https://i.imgur.com/nu0U5Zom.jpg" alt="Impa"/></a>
<a href="https://i.imgur.com/FxUcngT.jpg"><img src="https://i.imgur.com/FxUcngTm.jpg" alt="Purah"/></a>
<a href="https://i.imgur.com/hiHiUZF.jpg"><img src="https://i.imgur.com/hiHiUZFm.jpg" alt="the Camera"/></a>
</figure>
With the Camera, Link basically has a smartphone. The applications for the
Camera in-game seem really cool though. By taking pictures of objects, they'll
be added to the Hyrule Compendium. The Compendium is *massive*, and has pages of
animals, monsters, and all sorts of things to take pictures of and fill the
Compendium. For some reason, that alone seems like a fun completion task to me,
maybe because it reminds me of the Pictograph and Figurine mechanics from Wind
Waker. But adding an item to the Compendium has a practical use as well. You can
set your Sheikah Sensor to track any object you've added to your Compendium, and
it will let you know when that item is nearby. I haven't tried this yet, but it
sounds pretty useful!
<figure class="third">
<a href="https://i.imgur.com/oR7rEIS.jpg"><img src="https://i.imgur.com/oR7rEISm.jpg" alt="taking pictures of objects"/></a>
<a href="https://i.imgur.com/c5IwvhZ.jpg"><img src="https://i.imgur.com/c5IwvhZm.jpg" alt="added to the Hyrule Compendium"/></a>
<a href="https://i.imgur.com/LkCVJ0T.jpg"><img src="https://i.imgur.com/LkCVJ0Tm.jpg" alt="monsters"/></a>
</figure>
After getting the Camera, I followed an old man in Kakariko and he pointed me to
the direction of the nearby Great Fairy Fountain, where I revived a Great Fairy
by giving her 100 rupees. They went with slightly different design for the Great
Fairies in Breath of the Wild from what I've seen in the series before. The
Great Fairy I found can enhance your equipment if you give her a few raw
materials, increasing its armor value. It was definitely worth seeking her out!
<figure class="half">
<a href="https://i.imgur.com/gfYTUgT.jpg"><img src="https://i.imgur.com/gfYTUgTm.jpg" alt="a Great Fairy"/></a>
<a href="https://i.imgur.com/EUSLyLJ.jpg"><img src="https://i.imgur.com/EUSLyLJm.jpg" alt="enhance your equipment"/></a>
</figure>
That about sums about my adventure in Hyrule so far, but there are a few final
random notes I want to share. I love that Beedle is in this game, seeing him
again is really making me feel nostalgia for The Wind Waker! With the open
world, you can really get into situations that you are vastly under prepared
for, leading to death as you get trampled by a Bokoblin on horseback. I love it!
Lastly, Blood Moons are super metal. I only saw one this week, but as it began,
the light began to turn red, and ember-like particles filled the air. At the
time, I had just started some grass on fire in Hateno Village, and I was worried
that the changes were due to it spreading into a wildfire or something. But
nope, just a Blood Moon!
<figure class="third">
<a href="https://i.imgur.com/E1tA3tV.jpg"><img src="https://i.imgur.com/E1tA3tVm.jpg" alt="Beedle"/></a>
<a href="https://i.imgur.com/mQmj4Sm.jpg"><img src="https://i.imgur.com/mQmj4Smm.jpg" alt="death"/></a>
<a href="https://i.imgur.com/tlJQAZ6.jpg"><img src="https://i.imgur.com/tlJQAZ6m.jpg" alt="Blood Moons are super metal"/></a>
</figure>
That's all I have to say about Breath of the Wild for now. There's so many
things to do in this version of Hyrule, and so many possibilities within the
gameplay and combat, it's just amazing. I'm really looking forward to playing
more!
<figure class="half">
<a href="https://i.imgur.com/8CwtzLt.jpg"><img src="https://i.imgur.com/8CwtzLtm.jpg" alt="Breath of the Wild"/></a>
<a href="https://i.imgur.com/AXdWywq.jpg"><img src="https://i.imgur.com/AXdWywqm.jpg" alt="playing more"/></a>
</figure>
|
PHP
|
UTF-8
| 881
| 2.53125
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
<?php namespace Rikki\Heroeslounge\classes\Discord;
use Rikki\Heroeslounge\classes\Discord\AuthCode;
use Log;
class Webhook
{
public static function sendMatchReschedule($message = "", $embed)
{
$url = 'https://discordapp.com/api/webhooks/' . Authcode::getCasterWebhookId() . '/' . Authcode::getCasterWebhookSecret();
$headers = [
"Content-Type: application/json",
"User-Agent: HeroesLounge (http://heroeslounge.gg, 0.1)"
];
$payload = json_encode(['content' => $message, 'embeds' => [$embed]]);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );
$output = curl_exec($ch);
curl_close($ch);
}
}
|
C#
|
UTF-8
| 2,037
| 3.28125
| 3
|
[] |
no_license
|
using CommonStuff;
using System;
namespace M6_Classes
{
public static class SetAccessorLab
{
private static void SetWithProperty()
{
ConsoleHelper ch = new ConsoleHelper();
Address address = new Address
{
Street = "Långa gatan",
StreetNumber = "13B",
City = "Sundsvall",
};
ch.WriteDark("Try to set zipcode to 111 22");
address.ZipCode = "111 22";
ch.TwoColumns("ZipCode", address.ZipCode);
Console.WriteLine();
ch.WriteDark("Try to set zipcode to 222 33");
address.ZipCode = "222 33";
ch.TwoColumns("ZipCode", address.ZipCode);
Console.WriteLine();
ch.WriteDark("Try to set zipcode to HELLO");
address.ZipCode = "HELLO";
ch.TwoColumns("ZipCode", address.ZipCode);
}
private static void SetWithMethods()
{
ConsoleHelper ch = new ConsoleHelper();
Address address = new Address
{
Street = "Långa gatan",
StreetNumber = "13B",
City = "Sundsvall",
};
ch.WriteDark("Try to set zippycode to 111 22");
address.SetZipCode("111 22");
ch.TwoColumns("ZippyCode", address.GetZipCode());
Console.WriteLine();
ch.WriteDark("Try to set zippycode to 222 33");
address.SetZipCode("222 33");
ch.TwoColumns("ZippyCode", address.GetZipCode());
Console.WriteLine();
ch.WriteDark("Try to set zippycode to HELLO");
address.SetZipCode("HELLO");
ch.TwoColumns("ZippyCode", address.GetZipCode());
}
public static void Run()
{
//SetWithMethods();
//Console.WriteLine();
//ch.Line();
//Console.WriteLine();
SetWithProperty();
}
}
}
|
Java
|
UTF-8
| 570
| 2.953125
| 3
|
[] |
no_license
|
package question4_b;
public class matrice {
public static void main(String[] args) {
// TODO Auto-generated method stub
Integer matrice[][] = new Integer[9][9];
for (int i = 0; i < matrice.length; i++) {
for (int j = 0; j <= i; j++) {
if (j == 0 || (i == j)) {
matrice[i][j] = 1;
}
else
{
matrice[i][j] = matrice[i-1][j] + matrice[i-1][j-1];
}
}
}
for (int i = 0; i < matrice.length; i++) {
for (int j = 0; j <=i; j++) {
System.out.print(matrice[i][j]+" ");
}
System.out.println();
}
}
}
|
Python
|
UTF-8
| 987
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
import dense_flow_cv as df
from pathlib import Path
import argparse
# run on specific files instead of an entire directory
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Process videos and analyze motility.")
parser.add_argument('vidlist', nargs='+', type=str,
help='video(s) to be analyzed')
args = parser.parse_args()
vidlist = args.vidlist
fix_list = []
wd = Path.cwd()
for file in vidlist:
path = wd.joinpath(file)
fix_list.append(path)
for file in fix_list:
vid = file
motility = df.optical_flow(wd, vid)
normalization_factor = df.segment_worms(wd, vid)
outfile = str(wd) + '.csv'
df.wrap_up(vid, outfile, motility, normalization_factor)
print("Video:", file, "Total motility:", motility,
"Normalization factor:", normalization_factor,
"Normalized motility:", motility / normalization_factor)
|
Python
|
UTF-8
| 2,532
| 3.234375
| 3
|
[
"MIT"
] |
permissive
|
import numpy as np
from collections import defaultdict
from enum import Enum, auto
class AlgorithmType(Enum):
MonteCarlo = auto()
Sarsa = auto()
QLearning = auto()
ExpectedSarsa = auto()
class Agent:
def __init__(self,
na=6,
algorithm_type=AlgorithmType.ExpectedSarsa,
alpha=0.6,
gamma=1,
):
""" Initialize agent.
Params
======
- nA: number of actions available to the agent
"""
self.alpha = alpha
self.gamma = gamma
self.start_epsilon = epsilon
self.nA = na
self.Q = defaultdict(lambda: np.zeros(self.nA))
self.epsilon = self.start_epsilon
self.epsilon_decay = lambda e: e*self.start_epsilon
self.episode_counter = 0
self.algorithm_type = algorithm_type
def select_action(self, state):
""" Given the state, select an action.
Params
======
- state: the current state of the environment
Returns
=======
- action: an integer, compatible with the task's action space
"""
greedy_action = np.argmax(self.Q[state])
return greedy_action if np.random.uniform() > self.epsilon else np.random.randint(0, self.nA)
def step(self, state, action, reward, next_state, done):
""" Update the agent's knowledge, using the most recently sampled tuple.
Params
======
- state: the previous state of the environment
- action: the agent's previous choice of action
- reward: last reward received
- next_state: the current state of the environment
- done: whether the episode is complete (True or False)
"""
if self.algorithm_type == AlgorithmType.QLearning:
# Q-learning
self.Q[state][action] += self.alpha * (reward + self.gamma*np.max(self.Q[next_state]) - self.Q[state][action])
elif self.algorithm_type == AlgorithmType.ExpectedSarsa:
## Expected Sarsa
pi = np.ones(self.nA) * self.epsilon / self.nA
pi[np.argmax(self.Q[state])] += 1 - self.epsilon
self.Q[state][action] += self.alpha * (reward + self.gamma * np.sum(pi * self.Q[next_state]) - self.Q[state][action])
else:
raise ValueError("Algorithm type %s is not supported" % (self.algorithm_type))
if done:
self.episode_counter += 1
self.epsilon = self.epsilon_decay(self.epsilon)
|
JavaScript
|
UTF-8
| 709
| 2.6875
| 3
|
[] |
no_license
|
import React, {useEffect, useState} from 'react';
export const ForecastContaxt = React.createContext({
forecasts: [],
setForecast: () => {},
});
export default function ForecastProvider({children}){
const [forecasts, setForecast] = useState([]);
useEffect(() => { // fetch as default TLV 5 daily forecast
fetch('http://localhost:8080/cities/Tel-aviv/forcasts')
.then(response => response.json())
.then(data => setForecast(data))
}, []);
console.log(forecasts);
return (
<ForecastContaxt.Provider value={{
forecasts,
setForecast,
}}>
{children}
</ForecastContaxt.Provider>
);
}
|
Java
|
UTF-8
| 2,997
| 2.71875
| 3
|
[] |
no_license
|
package com.cwl.generator.file;
import com.cwl.tool.util.Util;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
/**
* <li>文件名称: FileUtil.java</li>
* <li>版权所有: 陈文龙(C)2015-2020</li>
* <li>修改记录: ...</li>
* <li>内容摘要: ...</li>
* <li>其他说明: ...</li>
*
* @version 0.0.1
* @since 2015年1月23日
* @author cwl
*/
public class FileUtil {
public static final void fileReplace(String rootPath, AbstractFileNameFilter fileNameFilter, IReplace replace) {
List<String> filePaths = getFilePaths(rootPath, fileNameFilter, false);
for (String filePath : filePaths) {
fileReplace(filePath, replace);
}
}
public static final void copy(String src, String des, boolean includeDir) {
List<String> files = getFilePaths(src, new AllFileNameFileter(), includeDir);
for (String path : files) {
File file = new File(path);
String destPath = path.replace(src, des);
if (file.isDirectory()) {
new File(destPath).mkdirs();
} else {
Util.writeFileContent(destPath, Util.getFileContent(path, "utf-8"));
}
}
}
/**
* <pre>
* 读取目录下所有满足过滤条件的文件目录列表
* </pre>
*
* @param rootPath
* @param fileNameFilter
* @return
*/
public static final List<String> getFilePaths(String rootPath, AbstractFileNameFilter fileNameFilter,
boolean includeDir) {
List<String> filePaths = new ArrayList<String>();
read(new File(rootPath), fileNameFilter, filePaths, includeDir);
return filePaths;
}
/**
* <pre>
* 将文件列表中的内容合并到目标文件中
* </pre>
*
* @param srcFilePaths
* @param toFilePath
* @param encoding
* 文件内容编码
* @param delimit
* 合并文件时,文件分割内容
*/
public static final void mergerFileContent(List<String> srcFilePaths, String toFilePath, String encoding,
IFileDelimit delimit) {
StringBuilder sb = new StringBuilder(8192);
for (String srcFilePath : srcFilePaths) {
sb.append(delimit.delimit(srcFilePath));
sb.append(Util.getFileContent(srcFilePath, encoding));
}
Util.writeFileContent(toFilePath, sb.toString());
}
public static final void fileReplace(String filePath, IReplace replace) {
String str = Util.getFileContent(filePath, replace.getEncoding());
Matcher matcher = replace.getPattern().matcher(str);
String s;
while (matcher.find()) {
s = matcher.group();
str = str.replace(s, replace.to(s));
}
Util.writeFileContent(filePath, str);
}
private static final void read(File file, AbstractFileNameFilter fileNameFilter, List<String> filePaths,
boolean includeDir) {
String name = file.getPath();
if (fileNameFilter.filter(name)) {
if (file.isDirectory()) {
if (includeDir) {
filePaths.add(name);
}
for (File p : file.listFiles()) {
read(p, fileNameFilter, filePaths, includeDir);
}
} else {
filePaths.add(name);
}
}
}
}
|
C++
|
UTF-8
| 570
| 2.765625
| 3
|
[] |
no_license
|
#include<SoftwareSerial.h>
const int RX_PIN = 8;
const int TX_PIN = 9;
SoftwareSerial xbee(RX_PIN, TX_PIN);
void setup() {
Serial.begin(115200);
pinMode(RX_PIN, INPUT);
pinMode(TX_PIN, OUTPUT);
xbee.begin(9600);
}
byte buf[7];
int x, y;
void loop() {
if (xbee.available() >= 9) {
if (xbee.read() == 'H') {
for (int i = 0; i < 8; i++)
buf[i] = xbee.read();
}
}
// for (int i = 0; i < 8; i++) {
// Serial.print(buf[i]); Serial.print("\t");
// }
// Serial.println();
Serial.write('H');
Serial.write(buf, 8);
}
|
PHP
|
UTF-8
| 2,812
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
<?php
/**
* Project name: OpenNote
* Author: Jacob Liscom
* Version: 13.10.0
**/
//Notice no include here. We need this here because we want to include this without the rest of the include tree
abstract class Config{
/**
* Database details
*/
public static function dbConfig(){
if(self::$injectedCoreConfig!=null)
return self::$injectedCoreConfig;
//Un-comment desired database type
return self::mysqlConfig();
//return self::sqliteConfig();
}
/**
* sql lite
*/
private static function sqliteConfig(){
//pdo
//Path to DB. Do not put in webdirectory without protection! If you do anyone can download your database!
$dbName = "OpenNote.sqlite"; //relative path to sqllite db
// PDO cannot find database file when it's "%s\%s" on Ubuntu 14.04
return new PDO(sprintf("sqlite:%s/%s",dirname(__FILE__),$dbName));
}
/**
* mysql
*/
private static function mysqlConfig(){
//mysql
$dbUserName = "notebook";
$dbPassword = "password";
$dbServer = "127.0.0.1";
$dbName = "notebook";
return new PDO(sprintf("mysql:host=%s;dbname=%s", $dbServer, $dbName), $dbUserName, $dbPassword);
}
private static $injectedCoreConfig = null;
/**
* Setter for config
* @param $config - config object to inject
*/
public static function setInjectedCoreConfig($config){
self::$injectedCoreConfig = $config;
}
/**
* Which model to use
*/
public static function getModel(){
return new \model\pdo\Model(self::dbConfig());
}
/**
* Upload
*/
public static function getUploadEnabled(){
return true;//Default: true. Allwer users to upload files.
}
/**
* Get upload path
*/
public static function getUploadPath(){
return dirname(__FILE__)."/upload/";
}
/**
* Registration
*/
public static function getRegistrationEnabled(){
return true;//Default: true. Allow users to register.
}
/**
* Security
*/
/**
* @return - the token life in minutes
*/
public static function tokenLife(){
return 60;
}
/**
* Config
*/
/**
* @return - array to send client
*/
public static function getInitialConfig(){
return array(
"uploadEnabled" => self::getUploadEnabled(),
"registrationEnabled" => self::getRegistrationEnabled()
);
}
/**
* Get web root
*/
public static function getWebRoot(){
return str_replace("\\", "/",str_replace(realpath($_SERVER["DOCUMENT_ROOT"]),"",realpath(dirname(__FILE__))))."/";
}
}
?>
|
C#
|
UTF-8
| 1,934
| 3.1875
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppDoWhile
{
class Program
{
static void Main(string[] args)
{
int contador=0;
float promedio = 0, numero = 0, suma=0;
Console.WriteLine(" ");
Console.WriteLine(" ===================");
Console.WriteLine(" Programa Do While 2 ");
Console.WriteLine(" ===================");
Console.WriteLine(" ");
Console.WriteLine(" ");
do
{
Console.Write(" Digite Un Numero: ");
numero = float.Parse(Console.ReadLine());
if (numero == 0)
break;
contador = contador + 1;
suma = suma + numero;
Console.WriteLine(" ");
Console.WriteLine(" ");
}
while (numero != 0);
promedio = (suma / contador);
Console.WriteLine(" ");
Console.WriteLine(" ");
Console.WriteLine(" ");
Console.Write(" El Promedio De Los Numero Ingresados Fue: " + promedio);
Console.WriteLine(" ");
Console.WriteLine(" ");
Console.WriteLine(" ");
Console.WriteLine(" ");
Console.WriteLine(" Elaboro <<Ing Alvaro Carvajal>> ");
Console.Write(" Universidad Simon Bolivar - Ext. Cucuta ");
Console.ReadKey();
}
}
}
|
C#
|
UTF-8
| 4,164
| 2.78125
| 3
|
[] |
no_license
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public float movementSpeed;
//Subscribe to this in controller if you want to act based on movement/direction
public delegate void MovementUpdateHandler(Vector2 direction);
public event MovementUpdateHandler MovementUpdate;
private List<Coordinate> Path = new List<Coordinate>();
private bool moving = false;
//Variables used for path movement
private Coordinate pathNode;
private Vector2 targetPosition;
private Vector2 initialPosition;
private Vector2 interpolatedMovement;
public Coordinate Destination
{
get
{
if (Path.Count < 1)
{
return WorldGen.PixelToNodeMap(transform.position);
}
else
{
return Path[Path.Count - 1];
}
}
}
//Add waypoint to path. If overwrite is true, will clear the current path
public void AddWaypoint(Coordinate newDestination, bool overwrite = false)
{
if (Destination == newDestination)
{
return;
}
if (overwrite)
{
ClearPath();
}
var newPath = Pathfinding.GetPath(Destination, newDestination);
if (newPath.Count > 0)
{
newPath.RemoveAt(0);
Path.AddRange(newPath);
}
StartMoving();
}
//Clears the current path. Will leave one node if currently moving to it
public void ClearPath()
{
if (Path.Count > 0)
{
Path.RemoveRange(1,Path.Count - 1);
}
}
public void Update()
{
if (moving)
{
MoveAlongPath();
}
}
//Enables movement
public void StartMoving()
{
moving = true;
}
//Disables movement
public void StopMoving()
{
if(MovementUpdate != null)
{
MovementUpdate(Vector2.zero);
}
moving = false;
}
public bool IsMoving()
{
return moving;
}
//Move towards next point in current path
public void MoveAlongPath()
{
//If current path is empty, stop moving
if (Path == null || Path.Count < 1)
{
StopMoving();
//Debug.Log("Destination reached.");
return;
}
//Current node should always be the first in path.
if (pathNode != Path[0])
{
pathNode = Path[0];
//Set target/initial positions and calculate normalized vector
targetPosition = WorldGen.NodeMapToPixel(pathNode);
initialPosition = transform.position;
interpolatedMovement = (targetPosition - initialPosition).normalized;
//Debug.Log("Next node. Moving from " + initialPosition + " to " + targetPosition);
//Start movement animation in the direction of the current target node
if (MovementUpdate != null)
{
MovementUpdate(interpolatedMovement);
}
}
//Move to the next destination
//Entity.rigidbody.MovePosition(interpolatedMovement);
transform.Translate(interpolatedMovement * Time.smoothDeltaTime * movementSpeed);
/*
* This could give increased precision and no risk of just walking past the target position
Vector2 nextPosition = (Vector2)transform.position + interpolatedMovement * Time.smoothDeltaTime * movementSpeed;
//Check if next position would go past target position
if (Vector2.Dot((targetPosition - nextPosition), interpolatedMovement) < 0)
{
Path.Remove(pathNode);
}
*/
//If we've reached our current destination, remove the path node we just reached
if ((targetPosition - (Vector2)transform.position).magnitude < Time.smoothDeltaTime * movementSpeed * 2)
{
Path.Remove(pathNode);
if(Path.Count < 1)
{
StopMoving();
}
}
}
}
|
Markdown
|
UTF-8
| 3,983
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
[@hqoss/monads](../README.md) › [Globals](../globals.md) › [ResOk](resok.md)
# Interface: ResOk ‹**T, E**›
## Type parameters
▪ **T**
▪ **E**
## Hierarchy
* [Result](result.md)‹T, E›
↳ **ResOk**
## Index
### Properties
* [type](resok.md#type)
### Methods
* [andThen](resok.md#andthen)
* [err](resok.md#err)
* [isErr](resok.md#iserr)
* [isOk](resok.md#isok)
* [map](resok.md#map)
* [mapErr](resok.md#maperr)
* [match](resok.md#match)
* [ok](resok.md#ok)
* [orElse](resok.md#orelse)
* [unwrap](resok.md#unwrap)
* [unwrapErr](resok.md#unwraperr)
* [unwrapOr](resok.md#unwrapor)
## Properties
### type
• **type**: *symbol*
*Inherited from [Result](result.md).[type](result.md#type)*
Defined in lib/result/result.ts:14
## Methods
### andThen
▸ **andThen**‹**U**›(`fn`: function): *[Result](result.md)‹U, E›*
*Overrides [Result](result.md).[andThen](result.md#andthen)*
Defined in lib/result/result.ts:36
**Type parameters:**
▪ **U**
**Parameters:**
▪ **fn**: *function*
▸ (`val`: T): *[Result](result.md)‹U, E›*
**Parameters:**
Name | Type |
------ | ------ |
`val` | T |
**Returns:** *[Result](result.md)‹U, E›*
___
### err
▸ **err**(): *[Option](option.md)‹E›*
*Inherited from [Result](result.md).[err](result.md#err)*
Defined in lib/result/result.ts:18
**Returns:** *[Option](option.md)‹E›*
___
### isErr
▸ **isErr**(): *boolean*
*Inherited from [Result](result.md).[isErr](result.md#iserr)*
Defined in lib/result/result.ts:16
**Returns:** *boolean*
___
### isOk
▸ **isOk**(): *boolean*
*Inherited from [Result](result.md).[isOk](result.md#isok)*
Defined in lib/result/result.ts:15
**Returns:** *boolean*
___
### map
▸ **map**‹**U**›(`fn`: function): *[ResOk](resok.md)‹U, never›*
*Overrides [Result](result.md).[map](result.md#map)*
Defined in lib/result/result.ts:34
**Type parameters:**
▪ **U**
**Parameters:**
▪ **fn**: *function*
▸ (`val`: T): *U*
**Parameters:**
Name | Type |
------ | ------ |
`val` | T |
**Returns:** *[ResOk](resok.md)‹U, never›*
___
### mapErr
▸ **mapErr**‹**U**›(`fn`: function): *[ResOk](resok.md)‹T, never›*
*Overrides [Result](result.md).[mapErr](result.md#maperr)*
Defined in lib/result/result.ts:35
**Type parameters:**
▪ **U**
**Parameters:**
▪ **fn**: *function*
▸ (`err`: E): *U*
**Parameters:**
Name | Type |
------ | ------ |
`err` | E |
**Returns:** *[ResOk](resok.md)‹T, never›*
___
### match
▸ **match**‹**U**›(`fn`: Match‹T, never, U›): *U*
*Overrides [Result](result.md).[match](result.md#match)*
Defined in lib/result/result.ts:33
**Type parameters:**
▪ **U**
**Parameters:**
Name | Type |
------ | ------ |
`fn` | Match‹T, never, U› |
**Returns:** *U*
___
### ok
▸ **ok**(): *[Option](option.md)‹T›*
*Inherited from [Result](result.md).[ok](result.md#ok)*
Defined in lib/result/result.ts:17
**Returns:** *[Option](option.md)‹T›*
___
### orElse
▸ **orElse**‹**U**›(`fn`: function): *[Result](result.md)‹T, E›*
*Overrides [Result](result.md).[orElse](result.md#orelse)*
Defined in lib/result/result.ts:37
**Type parameters:**
▪ **U**
**Parameters:**
▪ **fn**: *function*
▸ (`err`: E): *[Result](result.md)‹U, E›*
**Parameters:**
Name | Type |
------ | ------ |
`err` | E |
**Returns:** *[Result](result.md)‹T, E›*
___
### unwrap
▸ **unwrap**(): *T*
*Overrides [Result](result.md).[unwrap](result.md#unwrap)*
Defined in lib/result/result.ts:30
**Returns:** *T*
___
### unwrapErr
▸ **unwrapErr**(): *never*
*Overrides [Result](result.md).[unwrapErr](result.md#unwraperr)*
Defined in lib/result/result.ts:32
**Returns:** *never*
___
### unwrapOr
▸ **unwrapOr**(`optb`: T): *T*
*Overrides [Result](result.md).[unwrapOr](result.md#unwrapor)*
Defined in lib/result/result.ts:31
**Parameters:**
Name | Type |
------ | ------ |
`optb` | T |
**Returns:** *T*
|
C#
|
UTF-8
| 3,451
| 2.890625
| 3
|
[] |
no_license
|
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace CITI.EVO.Tools.Collections.Lookups
{
public class LookupDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
private readonly EntityLookup<TKey, TValue> _lookup;
public LookupDictionary() : this(7, EqualityComparer<TKey>.Default)
{
}
public LookupDictionary(int capacity) : this(capacity, EqualityComparer<TKey>.Default)
{
}
public LookupDictionary(IEqualityComparer<TKey> comparer) : this(7, comparer)
{
}
public LookupDictionary(int capacity, IEqualityComparer<TKey> comparer)
{
_lookup = new EntityLookup<TKey, TValue>(comparer, capacity);
}
public LookupDictionary(IDictionary<TKey, TValue> dictionary) : this(dictionary, EqualityComparer<TKey>.Default)
{
}
public LookupDictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer)
{
_lookup = new EntityLookup<TKey, TValue>(comparer, dictionary.Count + 1);
foreach (var pair in dictionary)
_lookup.Add(pair.Key, pair.Value);
}
public int Count
{
get { return _lookup.Count; }
}
public bool IsReadOnly
{
get { return false; }
}
public TValue this[TKey key]
{
get
{
return _lookup[key];
}
set
{
_lookup[key] = value;
}
}
public ICollection<TKey> Keys
{
get
{
var items = _lookup.Select(n => n.Key);
return items.ToList();
}
}
public ICollection<TValue> Values
{
get
{
var items = _lookup.Select(n => n.Value);
return items.ToList();
}
}
public bool ContainsKey(TKey key)
{
return _lookup.Contains(key);
}
public void Add(TKey key, TValue value)
{
_lookup.Add(key, value);
}
public bool Remove(TKey key)
{
return _lookup.Remove(key);
}
public void Clear()
{
_lookup.Clear();
}
public bool TryGetValue(TKey key, out TValue value)
{
return _lookup.TryGetValue(key, out value);
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return _lookup.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void Add(KeyValuePair<TKey, TValue> item)
{
_lookup.Add(item.Key, item.Value);
}
public bool Contains(KeyValuePair<TKey, TValue> item)
{
return _lookup.Contains(item);
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
foreach (var pair in this)
{
if (arrayIndex >= array.Length)
break;
array[arrayIndex++] = pair;
}
}
public bool Remove(KeyValuePair<TKey, TValue> item)
{
return _lookup.Remove(item.Key);
}
}
}
|
Markdown
|
UTF-8
| 5,416
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
**You're viewing a file in the SMAPI mod dump, which contains a copy of every open-source SMAPI mod
for queries and analysis.**
**This is _not_ the original file, and not necessarily the latest version.**
**Source repository: https://github.com/Esca-MMC/CustomNPCExclusions**
----
# Custom NPC Exclusions
A mod for the game Stardew Valley that allows mods to exclude NPCs from certain quests and events, especially those that randomly select NPCs.
## Contents
* [Installation](#installation)
* [Exclusion Rules](#exclusion-rules)
* [Mod Examples](#mod-examples)
* [SMAPI Mods](#smapi-mods)
* [Content Patcher Mods](#content-patcher-mods)
* [Credits](#credits)
## Installation
1. **Install the latest version of [SMAPI](https://smapi.io/).**
2. **Download Custom NPC Exclusions** from [the Releases page on GitHub](https://github.com/Esca-MMC/CustomNPCExclusions/releases), Nexus Mods, or ModDrop.
3. **Unzip Custom NPC Exclusions** into the `Stardew Valley\Mods` folder.
Mods that use Custom NPC Exclusions should now work correctly. For information about creating mods, see the sections below.
Multiplayer note:
* It is recommended that **all players** install this mod for multiplayer sessions. There are no known issues directly related to this mod, but NPC mods can cause unexpected errors if mismatched.
## Exclusion Rules
This mod can apply different exclusion rules to each individual NPC, preventing them being involved in the related quests and events.
The available exclusion rules are:
Rule | Category | Description
-----|----------|------------
All | | Excludes the NPC from all content affected by this mod.
TownEvent | | Excludes the NPC from all content in the "TownEvent" category (see below).
TownQuest | | Excludes the NPC from all content in the "TownQuest" category (see below).
IslandEvent | | Excludes the NPC from all content in the "IslandEvent" category (see below).
OtherEvent | | Excludes the NPC from all content in the "OtherEvent" category (see below).
MovieInvite | TownEvent | Excludes the NPC from receiving a Movie Ticket. This will use custom text from "Strings/Characters:MovieInvite_CantInvite_**NPCName**" if available.
ShopDialog | TownEvent | Excludes the NPC from randomly discussing items that players have sold to certain shops.
WinterStar | TownEvent | Excludes the NPC from giving or receiving secret gifts at the Feast of the Winter Star festival.
Calendar | TownEvent | Excludes the NPC's birthday from being displayed on calendars.
ItemDelivery | TownQuest | Excludes the NPC from randomized "item delivery" quests on the Help Wanted board.
Socialize | TownQuest | Excludes the NPC from "socialize" quests, which currently includes the "Introductions" quest at the start of the game.
IslandVisit | IslandEvent | Excludes the NPC from random visits to the Ginger Island resort.
BeGreeted | OtherEvent | Excludes the NPC from being greeted by other NPCs while traveling.
Greet | OtherEvent | Excludes the NPC from greeting other NPCs while traveling.
PerfectFriend | OtherEvent | Excludes the NPC from Stardew's "perfection score" tracker when it checks for maximum friendship with NPCs.
## Mod Examples
This mod loads a new data asset into Stardew: `Data/CustomNPCExclusions`.
The asset is similar to other "Data" types and is a `Dictionary<string, string>` internally. Each entry should have a NPC's name as the *key*, and a set of exclusion rules for that NPC as the *value*. Exclusion rules can be separated by spaces, commas, or forward slashes.
The asset can be edited in multiple ways; see the sections below for example of specific methods.
### SMAPI Mods
SMAPI mods can edit NPC exclusion data by using the `IAssetEditor` interface. See this wiki page for an overview: [https://stardewvalleywiki.com/Modding:Modder_Guide/APIs/Content#Edit_a_game_asset](https://stardewvalleywiki.com/Modding:Modder_Guide/APIs/Content#Edit_a_game_asset)
Below is a more specific example, which adds the "WinterStar" and "ItemDelivery" rules to a custom NPC named "MyCustomNpcName":
```cs
public bool CanEdit<T>(IAssetInfo asset)
{
if (asset.AssetNameEquals("Data/CustomNPCExclusions"))
return true;
return false;
}
public void Edit<T>(IAssetData asset)
{
if (asset.AssetNameEquals("Data/CustomNPCExclusions"))
{
IDictionary<string, string> data = asset.AsDictionary<string, string>().Data;
data.Add("MyCustomNpcName", "WinterStar ItemDelivery");
}
}
```
### Content Patcher Mods
Content Patcher's content packs can edit NPC exclusion data by using `"Action": "EditData"` with `"Target": "Data/CustomNPCExclusions"`. See the Content Patcher author guide for an overview: [https://github.com/Pathoschild/StardewMods/blob/develop/ContentPatcher/docs/author-guide.md#editdata](https://github.com/Pathoschild/StardewMods/blob/develop/ContentPatcher/docs/author-guide.md#editdata)
Below is a more specific example, which adds the "WinterStar" and "ItemDelivery" rules to a custom NPC named "MyCustomNpcName":
```js
{
"Format": "1.18.0",
"Changes": [
{
"Action": "EditData",
"Target": "Data/CustomNPCExclusions",
"Entries": {
"MyCustomNpcName": "WinterStar ItemDelivery"
}
}
]
}
```
## Credits
This mod was commissioned by FlashShifter for use with [Stardew Valley Expanded](https://www.moddrop.com/stardew-valley/mods/833179-stardew-valley-expanded)’s custom NPCs.
|
Shell
|
UTF-8
| 296
| 3.375
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env sh
for dir in $(echo "$PATH" | tr ":" "\n" | grep -Fxv "$(dirname $0)"); do
if [ -x "$dir/$(basename $0)" ]; then
exec "$dir/$(basename $0)" --rcfile "${XDG_CONFIG_HOME:-$HOME/.config}/bash/bashrc" "$@"
fi
done
echo "$0: error: Wrapped command does not exist" >&2
|
Python
|
UTF-8
| 1,477
| 3.515625
| 4
|
[] |
no_license
|
#!/usr/local/bin/python3
from random import randint
class Node(object):
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def print(self):
curr = self
while curr is not None:
print(curr.data,end=" ")
curr = curr.next
print()
def count(self):
count, curr = 0, self
while curr is not None:
count += 1
curr = curr.next
return count
def insert(root,data):
if root is None:
root = Node(data)
else:
curr = root
while curr.next is not None:
curr = curr.next
curr.next = Node(data)
return root
def find(root,data):
while root is not None:
if root.data == data:
return root
root = root.next
return None
def tail(root):
if root is None:
return None
while root.next is not None:
root = root.next
return root
def palindrome(root):
count = root.count()
left = root
for i in range(int(count/2)):
right = left
for j in range(count - 2*i - 1):
right = right.next
if right.data != left.data:
return False
left = left.next
return True
root = None
x = list(range(10))
for i in x:
root = insert(root, i)
print(palindrome(root))
root = insert(root, 6)
x.reverse()
for i in x:
root = insert(root, i)
root.print()
print(palindrome(root))
|
Markdown
|
UTF-8
| 732
| 2.75
| 3
|
[] |
no_license
|
# sherl: Make Erlang talk to subprocesses like a boss
Erlang's built-in subprocess management facilities are good enough to run a
well behaved port, but aren't going to do you much good for running arbitrary
processes.
## Project goals
The goal for sherl is to be more or less on par with the capabilities of the
subprocess module for Python. This includes:
* Know the pid of the subprocess
* Get the exit status of the subprocess
* Flow control
* Take a list of arguments and escape them as appropriate, or just run
a command with the default shell
* Route input via pipes or just inherit stdin/stdout/stderr
* Send signals to subprocess
* Poll or wait for exit of subprocess
The following are non-goals:
* Windows support
|
Java
|
UTF-8
| 604
| 3.09375
| 3
|
[] |
no_license
|
package com.sample.util;
public class CaptchaUtil {
public static String generateCaptchaText(int captchaLength) {
// Characters to show in captcha A-Z & 1-9.
String saltChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";
StringBuffer captchaStrBuffer = new StringBuffer();
java.util.Random rnd = new java.util.Random();
// build a random captchaLength chars slat
while (captchaStrBuffer.length() < captchaLength) {
int index = (int) (rnd.nextFloat() * saltChars.length());
captchaStrBuffer.append(saltChars.substring(index, index + 1));
}
return captchaStrBuffer.toString();
}
}
|
C++
|
UTF-8
| 298
| 2.875
| 3
|
[] |
no_license
|
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int lt = 0, rt = nums.size();
while(lt < rt) {
int mid = lt + (rt - lt) / 2;
if(nums[mid] < target) lt = mid + 1;
else rt = mid;
}
return lt;
}
};
|
C
|
UTF-8
| 2,604
| 2.828125
| 3
|
[] |
no_license
|
#include "TTree.h"
#include "TFile.h"
#include "TH1D.h"
#include "TCanvas.h"
double background(double *x, double *par) {
return par[0] + par[1]*x[0] + par[2]*x[0]*x[0];
}
// Lorentzian Peak function
double lorentzianPeak(double *x, double *par) {
//return (0.5*par[0]*par[1]/TMath::Pi()) / TMath::Max(1.e-10, (x[0]-par[2])*(x[0]-par[2])+ .25*par[1]*par[1]);
return (0.5*par[0]*par[1]/TMath::Pi()) / TMath::Max(1.e-10, (x[0]-par[2])*(x[0]-par[2])+ .25*par[1]*par[1]);
}
double gaussian(double *x, double *par){
return (par[0] * TMath::Exp(-(x[0] - par[1])*(x[0] - par[1]) / 2 * par[2] * par[2]));
}
// Sum of background and peak function
double fitFunction(double *x, double *par) {
return background(x,par) + gaussian(x,&par[3]);
}
void problem_1(){
//Declare variable for energy
Float_t energy;
//declare a histogram for the energy
TH1D *energy_hist = new TH1D("Energy","Energy",50,100,160);
//declare the canvas to display hist
TCanvas *c1 = new TCanvas("c1","c1",10,10,900,900);
TF1 *fitFcn = new TF1("fitFcn",fitFunction,90,180,6);
//get the input file
TFile *inputFile = new TFile("data.root");
//get the correct tree from the input file
//depending on the tree name change "data"
TTree *data_tree = (TTree*)inputFile->Get("data");
//Get the branch named E1 and put it into the varialbe energy
data_tree->SetBranchAddress("E", &energy);
//Get the number of events for the for loop
int count = data_tree->GetEntries();
for (int i = 0; i < count; i++) {
//get the current event i
data_tree->GetEntry(i);
//Fill the histogram
energy_hist->Fill(energy);
}
//label the axis and draw the histogram after it's filled
energy_hist->GetXaxis()->SetTitle("E (GeV)");
energy_hist->Draw();
// first try without starting values for the parameters
// this defaults to 1 for each param.
energy_hist->Fit("fitFcn");
// this results in an ok fit for the polynomial function however
// the non-linear part (Lorentzian) does not respond well
// second try: set start values for some parameters
fitFcn->SetParameter(4,1.66); // width
fitFcn->SetParameter(5,126.5); // peak
energy_hist->Fit("fitFcn");
// improve the picture:
TF1 *backFcn = new TF1("backFcn",background,100,160,3);
backFcn->SetLineColor(1);
backFcn->SetLineStyle(3);
TF1 *signalFcn = new TF1("signalFcn",gaussian,100,160,3);
signalFcn->SetLineColor(4);
Double_t par[6];
// writes the fit results into the par array
fitFcn->GetParameters(par);
backFcn->SetParameters(par);
backFcn->Draw("same");
signalFcn->SetParameters(&par[4]);
signalFcn->Draw("same");
gStyle->SetOptFit(1111);
}
|
PHP
|
UTF-8
| 5,916
| 2.96875
| 3
|
[] |
no_license
|
<?php
/**
* System V shared memory wrapper.
*
* @link http://php.net/sem
*
* @uses sysvshm
*
* @project Anizoptera CMF
* @package system.ipc
*/
class CIpcSharedMemory
{
const MEMORY_SIZE = 524288;
const PERMISSIONS = 0777;
/**
* A numeric shared memory segment ID
*
* @var int
*/
protected $key;
/**
* The memory size. If not provided, default to the sysvshm.init_mem in the php.ini, otherwise 10000 bytes.
*
* @var int
*/
protected $memorySize;
/**
* The optional permission bits. Default to 0666.
*
* @var int
*/
protected $permissions;
/**
* A shared memory segment identifier.
*
* @var resource
*/
protected $shmId;
/**
* Cache for names hashes
*/
protected static $namesCache = array();
/**
* Initializes shared memory with file path and project identifier.
*
* @param string $file Path to an accessible file.
* @param string $proj Project identifier. This must be a one character string.
* @param int $memorySize The memory size. If not provided, default to the sysvshm.init_mem in the php.ini, otherwise 10000 bytes.
* @param int $permissions The optional permission bits.
*
* @return CIpcSharedMemory
*/
public static function instance($file, $proj = 'm', $memorySize = self::MEMORY_SIZE,
$permissions = self::PERMISSIONS
) {
$key = ftok($file, $proj);
if ($key === -1) {
throw new AzaException("Can't initialize System V shared memory with file [$file] and project [$proj]", 1);
}
return new self($key, $memorySize, $permissions);
}
/**
* Creates or open a shared memory segment
*
* @param int $key A numeric shared memory segment ID
* @param int $memorySize The memory size. If not provided, default to the sysvshm.init_mem in the php.ini, otherwise 10000 bytes.
* @param int $permissions The optional permission bits.
*/
public function __construct($key, $memorySize = self::MEMORY_SIZE, $permissions = self::PERMISSIONS)
{
if (!function_exists('shm_attach')) {
throw new AzaException('You need php compiled with --enable-sysvshm option to work with System V shared memory', 1);
}
if (!is_numeric($key)) {
$key = sprintf('%u', crc32($key));
}
$this->key = (int)$key;
$this->memorySize = $memorySize;
$this->permissions = $permissions;
}
/**
* Disconnects from shared memory segment
*/
public function __destruct()
{
$this->detach();
}
/**
* Initializes a shared memory segment
*/
protected function init()
{
if (null === $this->shmId) {
$this->shmId = shm_attach($this->key, $this->memorySize, $this->permissions);
}
}
/**
* Returns variable name key
*
* @param string $name The variable name.
*
* @return int
*/
protected function name($name)
{
if (!isset(self::$namesCache[$name])) {
self::$namesCache[$name] = sprintf('%u', crc32($name));
}
return self::$namesCache[$name];
}
/**
* Disconnects from shared memory segment
*/
public function detach()
{
if (null !== $this->shmId) {
shm_detach($this->shmId);
$this->shmId = null;
}
}
/**
* Removes shared memory from Unix systems
*
* @throws AzaException on fail
*
* @return bool Returns true on success or false on failure.
*/
public function destroy()
{
$this->init();
if (!shm_remove($this->shmId)) {
throw new AzaException("Can't destroy shared memory segment", 1);
}
$this->detach();
}
/**
* Returns a variable from shared memory
*
* @param string $name The variable name.
*
* @return mixed|null The variable with the given key or NULL if it's not set
*/
public function get($name)
{
$this->init();
return $this->_get($this->name($name));
}
/**
* Returns a variable and deletes it from shared memory
*
* @param string $name The variable name.
*
* @return mixed the variable with the given key or null if not set
*/
public function getOnce($name)
{
$this->init();
$key = $this->name($name);
$value = $this->_get($key);
$this->_delete($key);
return $value;
}
/**
* Returns whether variable is set
*
* @param string $name The variable name.
*
* @return bool
*/
public function containsKey($name)
{
$this->init();
return false !== $this->_get($this->name($name), false);
}
/**
* Inserts or updates a variable in shared memory.
*
* @throws AzaException on fail
*
* @param string $name The variable name.
* @param mixed $value The variable. All variable-types (except resources) are supported.
*/
public function set($name, $value)
{
// shm_get_var return false in case of non-existed key.
// We need a wrapper to store FALSE values
if (false === $value) {
$value = (object)array('__shmFalseWrapper' => true);
}
$this->init();
if (!shm_put_var($this->shmId, $key = $this->name($name), $value)) {
throw new AzaException("Can't set var '$key' ($name) into shared memory", 1);
}
}
/**
* Removes a variable from shared memory
*
* @throws AzaException on fail
*
* @param string $name The variable name.
*/
public function delete($name)
{
$this->init();
$this->_delete($this->name($name));
}
/**
* Returns a variable from shared memory
*
* @param int $key The variable key.
* @param bool $process Whether to process variable
*
* @return mixed|null The variable with the given key or NULL if it's not set
*/
protected function _get($key, $process = true)
{
$value = @shm_get_var($this->shmId, $key);
if ($process) {
return $value === false ? null : (isset($value->__shmFalseWrapper) ? false : $value);
}
return $value;
}
/**
* Removes a variable from shared memory
*
* @throws AzaException on fail
*
* @param int $key The variable key.
*
* @return bool
*/
protected function _delete($key)
{
if (!shm_remove_var($this->shmId, $key)) {
throw new AzaException("Can't delete var '$key' from shared memory", 2);
}
}
}
|
Markdown
|
UTF-8
| 12,157
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
# Gloss → Codable Migration Guide
Adopters of Gloss are urged to migrate to Swift's first-class JSON parsing framwork, [Codable](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types). Gloss is no longer maintainined as of September 2020, unless in support of Codable migration. For more context on this decision, see: [hkellaway.github.io/blog/2020/08/30/tale-of-third-parties](https://hkellaway.github.io/blog/2020/08/30/tale-of-third-parties)
## :rotating_light: Before Migration :rotating_light:
```
Upgrade Gloss to minimum version 3.2.0
```
Version `3.2.0` adds methods to help translate between Gloss and Codable models.
## Migration Summary
The following is a summary of steps to take when migrating any single model from using Gloss to using Codable.
### Comparable Terms
| Gloss | Codable |
|---|---|
| `JSONDecodable` | `Decodable` |
| `JSONEncodable` | `Encodable` |
| `Glossy` | `Codable` |
| `Gloss.Decoder` | `Swift.Decoder` |
| `Gloss.Encoder` | `Swift.Encoder` |
### Migration Steps
#### Step 1: Update your Gloss model to add Codable conformance
If your Gloss model conforms to `JSONDecodable`, add conformance to `Decodable`. A model that looks like this:
``` swift
import Gloss
struct MyModel: JSONDecodable {
let id: Int?
init?(json: JSON) {
self.id = "id" <~~ json
}
}
```
adds
``` swift
extension MyModel: Decodable { }
```
Alternatively, the following could be added to silence Codable errors:
``` swift
extension My Model: Decodable {
init(from decoder: Swift.Decoder) throws {
throw GlossError.decodableMigrationUnimplemented(context: "TODO")
}
}
```
Similarly, `JSONEncodable` models add conformance to `Encodable`:
``` swift
struct MyModel: Encodable { }
```
alternatively:
``` swift
extension MyModel: Encodable {
func encode(to encoder: Swift.Encoder) throws {
throw GlossError.encodableMigrationUnimplemented(context: "TODO")
}
}
```
**NOTE**: Explicit usage of `Swift.Decoder` and `Swift.Encoder` is needed not to namespace clash with `Gloss.Decoder` and `Gloss.Encoder`.
#### Step 2: Update call-sites
At call-sites where the Gloss model is used, update from using the current Gloss methods for decoding or encoding to new ones that take Codable into account.
For example, where initializing that model currently looks like:
``` swift
let myModel = MyModel(json: someJSON)
```
it becomes:
``` swift
let myModel: MyModel? = .from(decodableJSON: someJSON)
```
As for encoding, this:
``` swift
let json: JSON? = myModel.toJSON()
```
becomes:
``` swift
let json: JSON? = myModel.toEncodableJSON()
```
**NOTE**: Similar usage applies to arrays, with `from(decodableJSONArray:)` and `toEncodableJSONArray()` respectively.
#### Step 3: Update your model to use `Codable` for decoding/encoding
This means fleshing out that `init(from decoder: Swift.Decoder) throws` or `func encode(to encoder: Swift.Encoder) throws ` method. Or, better yet, removing them if Codable can synthesize your decoding/encoding for you.
Rinse and repeat this process for every Gloss model. You can leave the fallback Gloss methods in place until you're comfortable with your Codable implementation - then take the Gloss wheels off and ride into the sunset with Codable :sunrise:
### Backwards Compatibility
If you are receiving errors anytime along the way don't worry - these **changes are backwards compatible**. What the new `from(decodableJSON:)` and `toEncodableJSON()` methods do under the hood is attempt to use Codable, but fallback to Gloss if any errors occur. They're also nice enough to log errors to the console to help you figure out where your migration is going astray.
If your Codable definitions are sound, but you're still receiving errors - you may need to explicitly configure a `JSONDecoder` or `JSONEncoder` and pass them along. A common reason for this is if your JSON is in [snake_case](https://en.wikipedia.org/wiki/Snake_case), whereas Codable defaults to [camelCase](https://en.wikipedia.org/wiki/Camel_case).
``` swift
let mySharedJSONDecoder: JSONDecoder = ...
let myModel: MyModel? = .from(decodableJSON: someJSON, jsonDecoder: mySharedJSONDecoder)
```
``` swift
let mySharedJSONEncoder: JSONEncoder = ...
let json: JSON? = myModel.toEncodableJSON(jsonEncoder: mySharedJSONEncoder)
```
### :warning: One Caveat: Nested Data :warning:
**One significant caveat** is for models using [a special feature of Gloss that allows nested values to be retrieved](/README_ARCHIVE.md#retrieving-nested-model-values-without-creating-extra-models) using a period-delimited string.
Before migrating to `Codable`, it may be simpler to un-nest those values by creating the nested models you were avoiding in the first place :cold_sweat: It's what Codable encourages regardless! Alternatively, you can use Codable's [nested containers](https://www.hackingwithswift.com/articles/119/codable-cheat-sheet) syntax.
## Case Study
Let's look at how we'd migrate [one of the models found in the Demo project](https://github.com/hkellaway/Gloss/blob/3.1.1/GlossExample/GlossExample/RepoOwner.swift#L29). We start with a simple model of a GitHub Repo owner. Here's our JSON:
``` json
{
"id": 123,
"html_url": "https://github.com/someUser"
}
```
### Preparing for Migration
First, we'll add conformance to Codable and update our call-sites.
#### Decodable
Our original `RepoOwner` model looks like this:
``` swift
import Gloss
struct RepoOwner: JSONDecodable, JSONEncodable {
let ownerId: Int
let url: String?
init?(json: JSON) {
guard let ownerId: Int = "id" <~~ json else { return nil }
self.ownerId = ownerId
self.url = "html_url" <~~ json
}
// ...
}
```
To start migrating to Codable, let's add conformance to `Decodable`.
``` swift
extension RepoOwner: Decodable { }
```
At our call-sites, we currently create this model from `JSON` as such:
``` swift
let json: JSON = ...
let repoOwner = RepoOwner(json: json)
```
Let's change that to use our new Codable-friendly method:
``` swift
let json: JSON = ...
let repoOwner: RepoOwner? = .from(decodableJSON: json)
```
That's it! We're done preparing our Gloss decoding for a rewrite to Codable. For now, Gloss will attempt to use Codable but safely fallback to our Gloss decoding if there's an error.
#### Encodable
Let's look at the same steps for `Encodable`. Remember our model:
``` swift
import Gloss
struct RepoOwner: JSONDecodable, JSONEncodable {
let ownerId: Int
let url: String?
// ...
func toJSON() -> JSON? {
return jsonify([
"id" ~~> self.ownerId,
"html_url" ~~> self.url
])
}
}
```
To start migrating to Codable, let's add conformance to `Encodable`.
``` swift
extension RepoOwner: Encodable { }
```
Currently, our call-sites look like this:
``` swift
let someRepoOwner: RepoOwner = ...
let json: JSON? = someRepoOwner.toJSON()
```
Let's change it to use our new Codable-friendly method:
``` swift
let someRepoOwner: RepoOwner = ...
let json: JSON? = someRepoOwner.toEncodableJSON()
```
That's it! We're done preparing our Gloss encoding for a rewrite to Codable. For now, Gloss will attempt to use Codable but safely fallback to our Gloss encoding if there's an error.
### Codable Definitions
Now we're ready to write our actual Codable definitions. Let's update our `Decodable` extension:
``` swift
extension RepoOwner: Decodable {
fileprivate enum CodingKeys: String, CodingKey {
case id, htmlUrl
}
init(from decoder: Swift.Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let ownerId = try container.decode(Int.self, forKey: .id)
let url = try container.decodeIfPresent(String.self, forKey: .htmlUrl)
self.init(ownerId: ownerId, url: url)
}
}
```
and the `Encodable` one:
``` swift
extension RepoOnwer: Encodable {
func encode(to encoder: Swift.Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.ownerId, forKey: .id)
try container.encode(self.url, forKey: .htmlUrl)
}
}
```
Looks great! But, even though these `Decodable` and `Encodable` definitions are sound....we're still getting an error.
It turns out that Codable assumes JSON keys will be in [camelCase](https://en.wikipedia.org/wiki/Camel_case), whereas our JSON uses [snake_case](https://en.wikipedia.org/wiki/Snake_case). We simply have to create our own `JSONDecoder` and `JSONEncoder` configured as such and pass those along. The good news is they will still come in handy when we ultimately remove Gloss!
``` swift
extension JSONDecoder {
static func snakeCase() -> JSONDecoder {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
return decoder
}
}
extension JSONEncoder {
static func snakeCase() -> JSONEncoder {
let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
return encoder
}
}
```
And our call-sites now become:
``` swift
let repoOwner: RepoOwner? = .from(decodableJSON: json, jsonDecoder: .snakeCase())
```
and:
``` swift
let json: JSON = someRepoOwner.toEncodableJSON(jsonEncoder: .snakeCase())
```
There we go! Our Codable code-paths now should be executing and our Gloss defintion is defunct :sparkles:
### Embracing Codable
Could we do better? Could we get Swift-ier?
The answer is: Yes. One of the most powerful things about Codable is it it can auto-magically use property names to synthesize our JSON decoding and encoding for us. Unless we have a special need for our key names or de/encoding logic, this is what we should aim for.
Let's revisit our JSON:
``` json
{
"id": 123,
"html_url": "https://github.com/someUser"
}
```
If we match our `RepoOwner` property names to `id` and `html_url` respectively, Codable will take care of the rest. Our penultimate model defintion looks like this, with Codable doing the work but our Gloss fallback in place:
``` swift
import Gloss
struct RepoOwner: JSONDecodable, JSONEncodable {
let id: Int
let htmlUrl: String?
init?(json: JSON) {
guard let id: Int = "id" <~~ json else { return nil }
self.id = id
self.htmlUrl = "html_url" <~~ json
}
func toJSON() -> JSON? {
return jsonify([
"id" ~~> self.id,
"html_url" ~~> self.htmlUrl
])
}
}
extension RepoOwner: Codable { } // Codable covers both Decodable & Encodable
```
#### Using `Data` Instead of `JSON` to Create Models
In the places where you've come to rely on Gloss's `JSON` type, you'll eventually need to pass `Data`, as that is what Codable uses. To get a jump using `decode(:)`, one option is use the same method Gloss uses to do `Data` transformation:
``` swift
import Gloss
let mySharedSerializer: GlossJSONSErializer = ...
let json: JSON = ...
if let data: Data? = mySharedSerializer.data(from: json, options: nil) {
let myModel: MyModel? = try? myJSONDecoder.decode(MyModel.self, from : data)
...
}
```
### Finally
The last step, once we're comfortable with our Codable integration, is to strip Gloss away. At the end of the day, our beautiful model looks like this:
``` swift
struct RepoOwner: Codable {
let id: Int
let htmlUrl: String?
}
```
And our need for snake-case is defined in just one place, instead of stringly-typed in each and every model. Talk about [lightweight](https://github.com/hkellaway/Gloss/blob/main/README_ARCHIVE.md#why-gloss)!
Take the opportunity with this migration to pare your models down to the slim amount of code Codable needs to work its magic and detangle your networking code from the details of JSON serialization. Future you will be grateful! :crystal_ball:
## Errata
If you find an issue with this guide or would like to add helpful content given your own migration, please [submit a Pull Request](https://github.com/hkellaway/Gloss/pulls).
|
JavaScript
|
UTF-8
| 2,320
| 2.640625
| 3
|
[] |
no_license
|
const events = require('events');
const scheduler = require('node-schedule');
class GoogleCalendarScheduler extends events.EventEmitter {
constructor(calendar, args = {}) {
super();
this.calendar = calendar;
this.opts = {
calendarId: '',
interval: 3600,
notifyBefore: 60,
debug: false,
...args
};
this.eventIds = {};
}
start() {
setInterval(() => {
this.startDate = new Date();
this.update();
}, this.opts.interval * 1000);
this.startDate = new Date();
this.update();
}
update() {
let timeMin = this.startDate.getTime();
timeMin += this.opts.notifyBefore * 1000;
const timeMax = timeMin + this.opts.interval * 1000;
const dateMin = new Date(timeMin).toISOString();
const dateMax = new Date(timeMax).toISOString();
if (this.opts.debug) {
console.log('Load events for %s between %s and %s', this.opts.calendarId, dateMin, dateMax);
}
this.calendar.events.list(
{
calendarId: this.opts.calendarId,
orderBy: 'startTime',
singleEvents: true,
timeMin: dateMin,
timeMax: dateMax,
fields: 'items(id,summary,start,end)'
},
(err, { data }) => {
if (err) {
console.error(err);
return;
}
const { items } = data;
if (this.opts.debug) {
console.log('found %d events', items.length);
}
for (let i = 0; i < items.length; i += 1) {
this.handleEvent(items[i], timeMin);
}
}
);
}
handleEvent(ev, timeMin) {
if (!('dateTime' in ev.start)) {
return;
}
if (ev.id in this.eventIds) {
return;
}
let startTime = new Date(ev.start.dateTime).getTime();
startTime -= this.opts.notifyBefore * 1000;
if (startTime < timeMin) {
return;
}
this.eventIds[ev.id] = 1;
const startDate = new Date(startTime);
if (this.opts.debug) {
console.log('schedule event %s for %s', ev.summary, startDate);
}
scheduler.scheduleJob(startDate, () => {
delete this.eventIds[ev.id];
if (this.opts.debug) {
console.log('notify about event %s', ev.summary);
}
this.emit('event', ev);
});
}
}
module.exports = GoogleCalendarScheduler;
|
Python
|
UTF-8
| 7,582
| 3.09375
| 3
|
[] |
no_license
|
# Jackie's Universal Cartographics System Code Decoder
# Kay Johnston
# Now with added elegance. And fixed the silly muppet bug I introduced merging things. :)
# Reference
# High points, below plane
# KF-D C29, PG-D C29
# QW-F C, VX-F C
# Low points, above plane
# UI-X C28, ZJ-X C28
# AA-A C, FB-A C
# High points, below plane
# EK-C D14, TK-C D14
# WV-C D, LW-C D
# Low points, above plane
# IO-Z D13, XO-Z D13
# AA-A D, PA-A D
# Add brute force systems-near-system finder.
# v4 for EAFOTS search
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
divisor = 26
middle = divisor**2
biggest = divisor**3
# Can merge these.
masscodes = 'HGFEDCBA'
sectorlength = 1280
sidelength = 128
walllength = 128 * 128
def cubes():
short_alpha = 'HGFEDCBA'
cubeside = 1280
for letter in short_alpha:
print(letter,':',cubeside,' lightyear sides, which is',int(1280/cubeside),'subsectors.')
cubeside = int(cubeside/2)
def finder(column,row,stack):
position = 0
position += row * walllength
position += stack * sidelength
position += column
#print('column:',column,'row:',row,'stack:',stack,'gives position:',position)
number = int(position / biggest)
working = position - (number * biggest)
number_third = int(working / middle)
third = alphabet[number_third]
working = working - (number_third * middle)
number_second = int(working / divisor)
second = alphabet[number_second]
working = working - (number_second * divisor)
first = alphabet[working]
if number != 0:
text = first + second + '-' + third + ' (letter code)' + str(number) + '-(system code)'
else:
text = first + second + '-' + third + ' (letter code)(system code)'
#print(text)
return first,second,third,number
class System():
def __init__(self,first,second,third,masscode,n1,n2):
try:
self.first = first.upper()
self.second = second.upper()
self.third = third.upper()
self.masscode = masscode.upper()
self.n1 = int(n1)
self.n2 = int(n2)
except:
print('There\'s a problem with those values.')
# Could add extra error checking here.
self.name = self.first + self.second + '-' + self.third + ' ' + self.masscode
if self.n1 == 0:
self.name += str(self.n2)
else:
self.name += str(self.n1) + '-' + str(self.n2)
self.calculate()
def calculate(self):
# Change the index into decimal.
self.index = 0
self.index += alphabet.index(self.first)
self.index += alphabet.index(self.second) * 26
self.index += alphabet.index(self.third) * 26 * 26
self.index += self.n1 * 26 * 26 * 26
# Work out the position of this index in slices, rows and columns.
self.rows = int(self.index / walllength)
remainder = self.index - (self.rows * walllength)
self.slices = int(remainder / sidelength)
self.columns = remainder - (self.slices * sidelength)
# Get an approximate position given the masscode.
self.divisions = 2**(masscodes.index(self.masscode))
self.sidelength = int(sectorlength / self.divisions)
self.x = int(self.columns * self.sidelength) + int(self.sidelength/2)
self.y = int(self.rows * self.sidelength) + int(self.sidelength/2)
self.z = int(self.slices * self.sidelength) + int(self.sidelength/2)
def report(self):
print(self.name)
print('Column:',self.columns,'Row:',self.rows,'Slice:',self.slices)
print('X: ~',self.x,'Y: ~',self.y,'Z: ~',self.z)
print()
def bruteforce(target,radius):
print(target.columns,target.rows,target.slices)
print(target.x,target.y,target.z)
def getsubs(x,y,z):
# Boxel size equivalent to E mass code subsector.
subsector_list = []
# E
first,second,third,number = finder(x,y,z)
newsystem = System(first,second,third,'E',number,0)
subsector_list.append(newsystem)
# D
startx = x * 2
starty = y * 2
startz = z * 2
endx = ((x + 1) * 2)# - 1
endy = ((y + 1) * 2)# - 1
endz = ((z + 1) * 2)# - 1
for sx in range(startx,endx):
for sy in range(starty,endy):
for sz in range(startz,endz):
first,second,third,number = finder(sx,sy,sz)
newsystem = System(first,second,third,'D',number,0)
subsector_list.append(newsystem)
# C
startx = x * 4
starty = y * 4
startz = z * 4
endx = ((x + 1) * 4)# - 1
endy = ((y + 1) * 4)# - 1
endz = ((z + 1) * 4)# - 1
for sx in range(startx,endx):
for sy in range(starty,endy):
for sz in range(startz,endz):
first,second,third,number = finder(sx,sy,sz)
newsystem = System(first,second,third,'C',number,0)
subsector_list.append(newsystem)
# B
startx = x * 8
starty = y * 8
startz = z * 8
endx = ((x + 1) * 8)# - 1
endy = ((y + 1) * 8)# - 1
endz = ((z + 1) * 8)# - 1
for sx in range(startx,endx):
for sy in range(starty,endy):
for sz in range(startz,endz):
first,second,third,number = finder(sx,sy,sz)
newsystem = System(first,second,third,'B',number,0)
subsector_list.append(newsystem)
# A
startx = x * 16
starty = y * 16
startz = z * 16
endx = ((x + 1) * 16)# - 1
endy = ((y + 1) * 16)# - 1
endz = ((z + 1) * 16)# - 1
for sx in range(startx,endx):
for sy in range(starty,endy):
for sz in range(startz,endz):
first,second,third,number = finder(sx,sy,sz)
newsystem = System(first,second,third,'A',number,0)
subsector_list.append(newsystem)
# Finish
return subsector_list
def writelist(subsector_list,filename):
with open(filename,'w') as opened:
opened.write('SECTOR,FIRST,SECOND,THIRD,MASSCODE,N1,N2\n')
for thing in subsector_list:
opened.write('EAFOTS,')
opened.write(thing.first)
opened.write(',')
opened.write(thing.second)
opened.write(',')
opened.write(thing.third)
opened.write(',')
opened.write(thing.masscode)
opened.write(',')
opened.write(str(thing.n1))
opened.write(',')
opened.write(str(thing.n2))
opened.write('\n')
cubes()
print()
Alice = System('I','Q','Y','D',0,0)
Alice.report()
alice = getsubs(0,0,0)
##print('Started.')
##for x in range(0,8):
## for y in range(0,8):
## for z in range(0,8):
## alice = getsubs(x,y,z)
## filename = 'EAFOTS' + str(x) + ',' + str(y) + ',' + str(z) + '.csv'
## writelist(alice,filename)
##print('Finished')
##bruteforce(Alice,10)
##x = input('Please enter the x co-ordinate for the mass-code E boxel: ')
##y = input('Please enter the y co-ordinate for the mass-code E boxel: ')
##z = input('Please enter the z co-ordinate for the mass-code E boxel: ')
##
##filename = 'EAFOTS' + x + ',' + y + ',' + z + '.csv'
##
##alice = getsubs(int(x),int(y),int(z))
##
##writelist(alice,filename)
##finder(0,0,0)
##finder(0,1,0)
##finder(0,2,0)
##finder(0,3,0)
##finder(0,0,1)
|
Python
|
UTF-8
| 1,450
| 3.125
| 3
|
[] |
no_license
|
import errno
import socket
from typing import Tuple, Union
class Socket:
def __init__(self, HOST: str, DEFAULT_SOCKET_PORT: Tuple[int]):
self.HOST = HOST
self.DEFAULT_SOCKET_PORT = DEFAULT_SOCKET_PORT
self.PORT: Union[int, None] = None
# super().__init__()
def checkAndBindSocket(self):
"""
Check port is binding, return socket instance
"""
for socketport in range(self.DEFAULT_SOCKET_PORT[0], self.DEFAULT_SOCKET_PORT[1] + 1):
try:
# Use IPv4 , TCP Protocol socket
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.bind((self.HOST, socketport))
self.PORT = socketport
self.sock.listen()
print(f"Socket Server use Address:{self.HOST}\tPort:{self.PORT}")
self.sock.setblocking(False) # non-block socket
break
"""
or you can use this to avoid port already use
# Avoid bind() exception: OSError: [Errno 48] Address already in use
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
"""
except socket.error as e:
if e.errno == errno.EADDRINUSE:
print(f"Port {socketport} is already in use.")
else:
print(f"Other socket error exception :\n{e}")
|
Shell
|
UTF-8
| 2,881
| 2.890625
| 3
|
[] |
no_license
|
# Path to your oh-my-zsh installation
export ZSH=$HOME/.oh-my-zsh
export LANG=en_US.UTF-8
# Theme
ZSH_THEME="spaceship"
# Command auto-correction.
ENABLE_CORRECTION="false"
# Display red dots whilst waiting for completion.
COMPLETION_WAITING_DOTS="true"
# Which plugins would you like to load? (plugins can be found in ~/.oh-my-zsh/plugins/*)
# Custom plugins may be added to ~/.oh-my-zsh/custom/plugins/
# Add wisely, as too many plugins slow down shell startup
plugins=(git node brew tmux zsh-autosuggestions)
# User configuration
# Hide user@hostname if it's expected default user
DEFAULT_USER=""
prompt_context(){}
# Set default editor to nvim
export EDITOR='nvim'
# Aliases
alias cls='clear'
alias vim='nvim'
alias vi='nvim'
alias v='nvim'
alias ll='ls -1a'
alias showFiles='defaults write com.apple.finder AppleShowAllFiles YES; killall Finder /System/Library/CoreServices/Finder.app'
alias hideFiles='defaults write com.apple.finder AppleShowAllFiles NO; killall Finder /System/Library/CoreServices/Finder.app'
alias deleteDSFiles='find . -name '.DS_Store' -type f -delete'
alias npm-update='npx npm-check -u'
# Custom functions
mg () { mkdir "$@" && cd "$@" || exit; }
# fzf
fzf-history-widget-accept() {
fzf-history-widget
zle accept-line
}
zle -N fzf-history-widget-accept
bindkey '^X^R' fzf-history-widget-accept
export FZF_DEFAULT_COMMAND='fd --type f --hidden --follow --exclude .git'
export FZF_DEFAULT_OPTS='
--height 40% --layout=reverse --border --extended
--color fg:242,bg:233,hl:65,fg+:15,bg+:234,hl+:108
--color info:108,prompt:109,spinner:108,pointer:168,marker:168
'
export FZF_CTRL_R_OPTS="--preview 'echo {}' --preview-window down:3:hidden:wrap --bind '?:toggle-preview'"
is_in_git_repo() {
git rev-parse HEAD > /dev/null 2>&1
}
fzf-down() {
fzf --height 50% "$@" --border
}
gst() {
git -c color.status=always status --short |
fzf --height 50% --border --ansi --multi --ansi --nth 2..,.. \
--preview '(git diff --color=always -- {-1} | sed 1,4d; cat {-1}) | head -500' |
cut -c4- | sed 's/.* -> //'
}
glo() {
is_in_git_repo || return
git log --date=short --format="%C(green)%C(bold)%cd %C(auto)%h%d %s (%an)" --graph --color=always |
fzf-down --ansi --no-sort --reverse --multi --bind 'ctrl-s:toggle-sort' \
--header 'Press CTRL-S to toggle sort' \
--preview 'grep -o "[a-f0-9]\{7,\}" <<< {} | xargs git show --color=always | head -'$LINES |
grep -o "[a-f0-9]\{7,\}"
}
# Enabled zsh-autosuggestions
source ~/.zsh/zsh-autosuggestions/zsh-autosuggestions.zsh
source $ZSH/oh-my-zsh.sh
# Enabled true color support for terminals
export NVIM_TUI_ENABLE_TRUE_COLOR=1
# Set Spaceship as prompt
autoload -U promptinit; promptinit
prompt spaceship
SPACESHIP_CHAR_SYMBOL='𝝺 '
SPACESHIP_PACKAGE_SHOW=false
SPACESHIP_NODE_SHOW=false
SPACESHIP_GIT_STATUS_STASHED=''
SPACESHIP_EXEC_TIME_COLOR='cyan'
|
JavaScript
|
UTF-8
| 7,043
| 2.875
| 3
|
[
"MIT"
] |
permissive
|
$('.button-collapse').sideNav({
draggable: true // Choose whether you can drag to open on touch screens
}
);
var user_name = "";
var wordReadyAdd = "";
var explanation = "";
(function($){
$(function(){
$('.button-collapse').sideNav();
var token = window.location.href.split('?');
if(token.length > 1)
{
token = token[1].split('&');
user_name = token[0];
if(user_name.split('=')[0] !== "user_name") user_name ="";
if(document.getElementById("user_name"))
document.getElementById("user_name").innerText = window.location.href.split('?')[1].split('=')[1];
}
toPage(1);
}); // end of document ready
})(jQuery); // end of jQuery name space
function toPage(pageNumber)
{
var user_name = window.location.href.split('?')[1].split('=')[1];
var insertHtml = "";
var totalPage = 0;
var totalWord = 0;
$.ajax({
//type: "post",
data: "bookWordNum_req&" + user_name,
url: 'http://127.0.0.1:5426',
async:false,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "bookWordNumSuccess_jsonpCallback"
}).done(function (res)
{
if(res == "no-word")
{
insertHtml = "<ul class=\"pagination\">"+
"<li class=\"disabled\"><i class=\"material-icons\">chevron_left</i></a></li>"+
"<li class=\"disabled\"><i class=\"material-icons\">chevron_right</i></a></li>"+
"</ul>";
document.getElementById("page").innerHTML = insertHtml;
alert("现在单词本中没有单词!");
}
else
{
if(res%5==0)
totalPage = res/5;
else
totalPage = (res-res%5)/5+1;
totalWord = res;
insertHtml = "<ul class=\"pagination\">";
if(pageNumber == 1)
insertHtml += "<li class=\"disabled\"><i class=\"material-icons\">chevron_left</i></a></li>";
else
insertHtml += "<li class=\"waves-effect\"><a href=\"javascript:toPage("+(pageNumber-1)+");\"><i class=\"material-icons\">chevron_left</i></a></li>";
var i = 1;
for(i = 1; i < pageNumber; ++i)
insertHtml += "<li class=\"waves-effect\"><a href=\"javascript:toPage("+i+");\">"+i+"</a></li>";
insertHtml += "<li class=\"active\"><a href=\"javascript:toPage("+pageNumber+");\">"+pageNumber+"</a></li>";
++i;
for(; i <= totalPage; ++i)
insertHtml += "<li class=\"waves-effect\"><a href=\"javascript:toPage("+i+");\">"+i+"</a></li>";
if(pageNumber == totalPage)
insertHtml += "<li class=\"disabled\"><i class=\"material-icons\">chevron_right</i></a></li>";
else
insertHtml += "<li class=\"waves-effect\"><a href=\"javascript:toPage("+(pageNumber+1)+");\"><i class=\"material-icons\">chevron_right</i></a></li>";
document.getElementById("page").innerHTML = insertHtml;
$.ajax({
//type: "post",
data: "book_req&" + user_name + "&" + pageNumber,
url: 'http://127.0.0.1:5426',
async:false,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "bookSuccess_jsonpCallback"
}).done(function (res)
{
var response = new String(res);
var wordGot = new Array(5);
var explanationGot = new Array(5);
var wordNum = parseInt(response.substr(0));
var index = 0;
for(var i=0; i < wordNum; ++i)
{
index = response.indexOf('&', index)+1;
wordGot[i] = response.substr(index, response.indexOf('&', index)-index);
console.log(wordGot[i]);
}
for(var i=0; i < wordNum; ++i)
{
if(i != wordNum - 1)
{
index = response.indexOf('&', index)+1;
explanationGot[i] = response.substr(index, response.indexOf('&', index)-index);
console.log(explanationGot[i]);
}
else
{
index = response.indexOf('&', index)+1;
explanationGot[i] = response.substr(index, response.length-index);
console.log(explanationGot[i]);
}
}
var i=0
for(i=0; i < wordNum; ++i)
{
i++;
var word = "word-"+i.toString();
var explanation = "explanation-"+i.toString();
i--;
document.getElementById(`${word}`).innerHTML = wordGot[i];
document.getElementById(explanation).innerHTML = "<p>"+explanationGot[i]+"</p>";
}
for(; i < 5; ++i)
{
i++;
var word = "word-"+i.toString();
var explanation = "explanation-"+i.toString();
i--;
document.getElementById(`${word}`).innerText = "";
document.getElementById(explanation).innerText = "";
}
});
}
});
}
function toBookHomepage()
{
window.location.href = 'bookhomepage.html?' + user_name;
}
function toWordsReview()
{
window.location.href = 'wordsreview.html?' + user_name;
}
function toTest()
{
window.location.href = 'test.html?' + user_name;
}
function toProcess()
{
window.location.href = 'process.html?' + user_name;
}
function checkWord(word)
{
if(word.value.length!=0)
{
return true;
}
else
{
alert("请输入单词");
return false;
}
}
function searchWord(word){
if(true == checkWord(word))
{
$.ajax({
//type: "post",
data: "wordSearch_req&" + document.getElementById("word").value,
url: 'http://127.0.0.1:5426',
async:false,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "successSearch_jsonpCallback",
}).done(function (res)
{
if(res == "word_does_not_exit")
{
alert("该单词在本单词本中不存在");
}
else
{
var insertHtml = "<input type=\"submit\" id=\"login-button\" class=\"waves-effect waves-light btn\" value=\"是否将该单词加入词汇本?\" name=\"submit\" onclick=\"return addWordToBook();\"/>"
wordReadyAdd = document.getElementById("word").value;
explanation = res;
document.getElementById("explanation").innerText = res;
document.getElementById("confirmButton").innerHTML = insertHtml;
}
});
return true;
}
else
{
return false;
}
}
function addWordToBook(){
var user_name = window.location.href.split('?')[1].split('=')[1];
$.ajax({
//type: "post",
data: "addWordToBook_req&" + user_name + "&" + wordReadyAdd + "&" + explanation,
url: 'http://127.0.0.1:5426',
async:false,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "successAddToBook_jsonpCallback",
}).done(function (res)
{
if(res == "success")
{
alert("该单词已经成功加入单词本中");
window.location.href = 'userwordbook.html?user_name=' + user_name;
}
else if(res == "duplicate")
{
alert("该单词已经存在于单词本中");
window.location.href = 'userwordbook.html?user_name=' + user_name;
}
});
return true;
}
|
Java
|
UTF-8
| 560
| 3.140625
| 3
|
[] |
no_license
|
class ImitateJavaLangStringTest
{
public static void charAtIndex(String a, int b)
{
System.out.print(a.charAt(b));
}
public static void concat(String a, String b)
{
System.out.print(a.concat(b));
}
public static void replace(String a, String b, String c)
{
System.out.print(a.replace(b, c));
}
public static void toLowerCase(String a)
{
System.out.print(a.toLowerCase());
}
public static void toUpperCase(String a)
{
System.out.print(a.toUpperCase());
}
}
|
JavaScript
|
UTF-8
| 549
| 2.515625
| 3
|
[] |
no_license
|
"use strict";
var chai_1 = require("chai");
var kata_1 = require("../src/kata");
describe('kata test', function () {
it('should pass this canary test', function () {
chai_1.expect(true).to.eql(true);
});
it('should return right result', function () {
chai_1.expect(kata_1.kata("din")).to.eql("(((");
chai_1.expect(kata_1.kata("recede")).to.eql("()()()");
chai_1.expect(kata_1.kata("Success")).to.eql(")())())", "should ignore case");
chai_1.expect(kata_1.kata("(( @")).to.eql("))((");
});
});
|
C#
|
UTF-8
| 2,947
| 2.8125
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TrainStation.Model
{
public class TrainModel
{
private string name { get; set; }
private string placeDeparture { get; set; }
private string placeArrival { get; set; }
private Dictionary<string, DateTime> routeAndDate { get; set; }
private Dictionary<string, int> routeAndPrice = new Dictionary<string, int>();
private List<VanModel> vanList { get; set; }
public string Name // property
{
get { return placeDeparture + " " + placeArrival; } // get method
}
public string PlaceDeparture // property
{
get { return placeDeparture; } // get method
set { placeDeparture = value; }
}
public string PlaceArrival // property
{
get { return placeArrival; } // get method
set { placeArrival = value; }
}
public Dictionary<string, int> RouteAndPrice // property
{
get { return routeAndPrice; } // get method
}
public List<VanModel> VanList // property
{
get { return vanList; } // get method
}
public Dictionary<string, DateTime> RouteAndDate // property
{
get { return routeAndDate; } // get method
}
public TrainModel(string PlaceDeparture, string PlaceArrival, Dictionary<string, DateTime> RouteAndDate, Dictionary<string, int> RouteAndPrice, List<VanModel> VanList)
{
this.PlaceDeparture = PlaceDeparture;
this.PlaceArrival = PlaceArrival;
this.routeAndPrice = RouteAndPrice;
this.routeAndDate = RouteAndDate;
this.vanList = VanList;
}
public void AddRouteAndPrice(string city, int price)
{
routeAndPrice.Add(city, price);
}
public void AddRouteAndDate(string city, DateTime dateTime)
{
routeAndDate.Add(city, dateTime);
}
public VanModel PickVan(List<SeatModel> SeatList, string Class, int Number)
{
VanModel pickedVan = VanList.FirstOrDefault(i => i.Class == Class && i.Number == Number);
return pickedVan;
}
public void CreateVansForTrain(int countOfVans, string classOfVans)
{
int lastNumberOfVan = 0;
if (vanList.Count != 0) lastNumberOfVan = vanList[vanList.Count - 1].Number + 1;
for (int i = lastNumberOfVan; i < lastNumberOfVan + countOfVans; i++)
{
AddVan(new List<SeatModel>(), classOfVans, i);
}
}
public void AddVan(List<SeatModel> seatList, string classVan, int number)
{
VanList.Add(new VanModel(seatList, classVan, number));
}
}
}
|
Python
|
UTF-8
| 537
| 3.625
| 4
|
[] |
no_license
|
my_name = "Zed A Shaw"
my_age = 38 #not a lie
my_height = 74 #inches
my_weight = 180 #lbs
my_eyes = "Blue"
my_hair = "Blond"
my_teeth = "White"
print "Let's talk about %s." % my_name
print "He's %d inches tall." % my_height
print "He's %d pounds heavy." % my_weight
print "Actually that is not too heavy."
print "He's got %s hair and %s eyes." % (my_hair, my_eyes)
print "His teeth are usually %s depending on the coffee." % my_teeth
print "If I add %d, %d and %d I get %d" % (my_age, my_height, my_weight, my_age + my_height + my_weight)
|
C++
|
UTF-8
| 1,507
| 2.703125
| 3
|
[] |
no_license
|
/*
Problem: 797C. Minimal string
Solution: strings, stack, greedy, O(n)
Author: Dmitry Kozyrev, github: dmkz, e-mail: dmkozyrev@rambler.ru
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <string>
#include <vector>
#include <cassert>
#include <numeric>
#include <cmath>
#define ios_fast std::ios_base::sync_with_stdio(0); \
std::cin.tie(0); std::cout.tie(0); std::cerr.tie(0);
#define input(x) for (auto& it : (x)) std::cin >> it
#define all(x) (x).begin(), (x).end()
#define size(x) (int)((x).size())
#define unique(x) (x).erase(std::unique(all((x))), (x).end())
const int mod = (int)1e9+7;
typedef long long ll;
typedef std::vector<int> vi;
typedef std::vector<vi> vvi;
typedef std::vector<ll> vll;
void update(int& a, int b) {
a = std::max(a,b);
}
int main() {
ios_fast;
std::string s; std::cin >> s;
vi cnt(26,0);
for (auto& it : s) cnt[it-'a']++;
std::string stack, answer;
int pos = 0;
for (char c = 'a'; c <= 'z'; ++c) {
while (!stack.empty() && stack.back() <= c) {
answer += stack.back();
stack.pop_back();
}
while (cnt[c-'a'] > 0) {
assert(pos < size(s));
if (s[pos] != c) {
stack.push_back(s[pos]);
} else {
answer.push_back(s[pos]);
}
cnt[s[pos++]-'a']--;
}
}
while (!stack.empty()) {
answer.push_back(stack.back());
}
std::cout << answer;
return 0;
}
|
C++
|
UTF-8
| 6,224
| 2.625
| 3
|
[] |
no_license
|
/**
* @file sancu_adder.cpp
*
* @date Mar 17, 2014
* @author norethel
*
* @{
*/
#include "sancu_adder.hh"
#include <fstream>
#include <sstream>
#include <cmath>
#include <cstring>
#include <iostream>
#include <sndfile.hh>
#include <sancu_signal.hh>
#include <sancu_sample.hh>
SancuAdder::SancuAdder(const std::string& _script_file) :
script_file(_script_file)
{
parse_script_file();
}
SancuAdder::~SancuAdder()
{
std::vector<SancuSignal*>::iterator voice_sig_iter = voice_signals.begin();
std::vector<SancuSignal*>::iterator noise_sig_iter = noise_signals.begin();
for (; voice_sig_iter != voice_signals.end(); ++voice_sig_iter)
{
delete *voice_sig_iter;
}
for (; noise_sig_iter != noise_signals.end(); ++noise_sig_iter)
{
delete *noise_sig_iter;
}
}
void SancuAdder::parse_snr(std::string& _line)
{
double snr;
char* current = strtok(const_cast<char*>(_line.c_str()), ",");
while (0 != current)
{
std::stringstream converter(current);
converter >> snr;
snr_levels.push_back(snr);
current = strtok(0, ",");
}
}
void SancuAdder::parse_voice(std::ifstream& fscript)
{
std::string line;
while (std::getline(fscript, line)
&& std::string::npos == line.find("</voice>"))
{
voice_files.push_back(line);
}
}
void SancuAdder::parse_noise(std::ifstream& fscript)
{
std::string line;
while (std::getline(fscript, line)
&& std::string::npos == line.find("</noise>"))
{
noise_files.push_back(line);
}
}
void SancuAdder::parse_output_path(std::string& _line)
{
output_path = _line;
if ('/' != output_path[output_path.length() - 1])
{
output_path += '/';
}
}
void SancuAdder::parse_script_file()
{
std::ifstream fscript(script_file.c_str());
std::string line;
while (std::getline(fscript, line))
{
if (std::string::npos != line.find("<snr>"))
{
if (std::getline(fscript, line))
{
parse_snr(line);
}
}
else if (std::string::npos != line.find("<voice>"))
{
parse_voice(fscript);
}
else if (std::string::npos != line.find("<noise>"))
{
parse_noise(fscript);
}
else if (std::string::npos != line.find("<output_path>"))
{
if (std::getline(fscript, line))
{
parse_output_path(line);
}
}
else
{
std::cout << "parse warning: unknown line:" << std::endl;
std::cout << "\"" << line.c_str() << "\"" << std::endl;
}
}
fscript.close();
}
void SancuAdder::modify_path(std::string& path, size_t noise_num,
size_t snr_num)
{
std::stringstream ss;
std::string postfix;
size_t slash_pos = path.find_last_of('/');
/* long path found */
if (std::string::npos != slash_pos)
{
/* extract only filename */
path = path.substr(slash_pos + 1);
}
path.insert(0, output_path);
ss << "_" << noise_num << "_" << snr_num;
ss >> postfix;
path.insert(path.length() - 4, postfix);
}
void SancuAdder::prepare_data()
{
std::vector<double>::iterator iter = snr_levels.begin();
for (; iter != snr_levels.end(); ++iter)
{
snr_ratios.push_back(
std::pow(SNR_CONST_RATIO, (*iter / SNR_CONST_RATIO)));
}
std::vector<std::string>::iterator voice_iter = voice_files.begin();
for (; voice_iter != voice_files.end(); ++voice_iter)
{
voice_signals.push_back(new SancuSignal(*voice_iter, true));
}
std::vector<std::string>::iterator noise_iter = noise_files.begin();
for (; noise_iter != noise_files.end(); ++noise_iter)
{
noise_signals.push_back(new SancuSignal(*noise_iter, false));
}
}
void SancuAdder::recalculate_data()
{
size_t noise_num = 0;
std::vector<SancuSignal*>::iterator noise_iter = noise_signals.begin();
/* for every noise signal */
for (; noise_iter != noise_signals.end(); ++noise_iter)
{
++noise_num;
SancuSampleReader noise_reader(*noise_iter);
std::vector<SancuSignal*>::iterator voice_iter = voice_signals.begin();
/* for every voice */
for (; voice_iter != voice_signals.end(); ++voice_iter)
{
size_t num_chunks = (*voice_iter)->chunks.size();
size_t last_chunk_size = (*voice_iter)->chunks.back()->length;
/* read noise sample of the same length as current voice signal */
std::vector<TSampleChunk> chunks = noise_reader.read(num_chunks,
last_chunk_size);
size_t snr_num = 0;
std::vector<double>::iterator snr_iter = snr_ratios.begin();
/* for every snr_ratio */
for (; snr_iter != snr_ratios.end(); ++snr_iter)
{
++snr_num;
/* copy base signal */
SancuSignal* voice_sig = new SancuSignal(**voice_iter);
/* modify output signal path */
modify_path(voice_sig->path, noise_num, snr_num);
/* the constructor copies buffer data,
* and also computes the energy of the read noise sample */
SancuSample noise_sample(chunks);
/* compute SNR coefficient for current noise level adjustment */
double snr_level = std::sqrt(
voice_sig->energy
/ ((*snr_iter) * noise_sample.energy));
/* multiply noise signal by calculated coefficient */
noise_sample *= snr_level;
std::cout << "Noise energy before recalculation: "
<< noise_sample.energy << std::endl;
noise_sample.compute_mean();
noise_sample.compute_energy();
std::cout << "Noise energy after recalculation: "
<< noise_sample.energy << std::endl;
/* add noise to voice signal */
*voice_sig += noise_sample;
std::cout << "Voice energy: " << voice_sig->energy << std::endl;
double out_snr = 10
* std::log10(voice_sig->energy / noise_sample.energy);
std::cout << "output SNR: " << out_snr << "dB" << std::endl;
voice_sig->normalize();
// calculate DC offset
voice_sig->compute_mean();
// remove DC offset
*voice_sig -= voice_sig->mean;
double max = voice_sig->getAbsMax();
double snr = 1.0 / max;
*voice_sig *= snr;
/* adjust voice signal to begin from 0 */
voice_sig->fadein();
/* adjust voice signal to end at 0 */
voice_sig->fadeout();
/* write back the signal */
voice_sig->write_back();
delete voice_sig;
}
}
}
}
void SancuAdder::execute()
{
/* calculate snr_ratios, read voice and noise files;
* compute energy for voice files while reading them */
prepare_data();
recalculate_data();
}
|
JavaScript
|
UTF-8
| 1,174
| 2.671875
| 3
|
[] |
no_license
|
const fb = require("./fb.js");
const database = fb.database;
function Create(item, callback) {
let id = database.ref('items/').push().key;
// item.name = item.name.replace(/\s/g, '');
database.ref('items/' + item.name).set({
"uname": item.uname,
"category": item.category,
"currentQty": item.currQty,
"totQty": item.totQty
}, (err) => {
callback(err);
});
}
function Update(item, newData, callback){
var updates={};
updates = newData;
database.ref("/items/" + item).update(updates, (err) =>{
callback(err);
})
}
function RetrieveOne(item, callback){
database.ref("items/" + item).once('value').then(function(snapshot){
let items = snapshot.val();
console.log(items);
if(items){
items.name = item;
callback(items);
}else{
callback(null);
}
})
}
function RetrieveAll(callback){
database.ref("items/").once("value").then(function(snapshot){
console.log(snapshot.val());
callback(snapshot.val());
});
}
module.exports = {
Create,
RetrieveAll,
Update,
RetrieveOne
}
|
PHP
|
UTF-8
| 802
| 3.640625
| 4
|
[] |
no_license
|
<?php
class A {
protected $name;
public function start(){
echo 'Starting: '.$this->name.'<br/>';
}
public function setName($n){
$this->name = $n;
}
}
class B extends A {
public function end(){
echo 'Ending: '.$this->name.'<br/>';
}
}
// $b = new B;
// $b->setName('Janko');
// $b->start();
// $b->end();
class Document{
public $name;
public $size;
public $type;
}
interface iDocument {
public function GetContent();
}
class Excell extends Document implements iDocument {
public function GetContent() {
echo 'Excel'.'<br/>';
}
}
class Word extends Document implements iDocument {
public function GetContent() {
echo 'World'.'<br/>';
}
}
class PowerPoint extends Document implements iDocument {
public function GetContent() {
echo 'PowerPoint'.'<br/>';
}
}
?>
|
Java
|
UTF-8
| 184
| 3.109375
| 3
|
[] |
no_license
|
// 21. write a java program to print the reverce of digits of numbers.
class Twentyone{
public static void main(String[] k){
for(int i=5;i>=0;i--){
System.out.print(i);
}
}
}
|
C++
|
UTF-8
| 1,672
| 3.984375
| 4
|
[] |
no_license
|
#include "card.h"
//constructor that takes a card's face value (an integer) and its suit
// card face example: Ace=0, 2=1, 3=2, ... Q=11, K=12
Card::Card (int face, suit st)
{
cardFace = face;
cardSuit = st;
if (face == 0)
pointValue = 15;
if (face >= 1 && face <= 9)
pointValue = face + 1;
if (face >= 10 && face <= 12)
pointValue = 10;
}
// overload the << operator to display the card
ostream& operator << (ostream& os, const Card& cd)
{
if (cd.cardFace == 1)
os << "A";
else if (cd.cardFace == 13)
os << "K";
else if (cd.cardFace == 12)
os << "Q";
else if (cd.cardFace == 11)
os << "J";
else
os << cd.cardFace;
if (cd.cardSuit == diamonds)
os << "D";
else if (cd.cardSuit == clubs)
os << "C";
else if (cd.cardSuit == hearts)
os << "H";
else if (cd.cardSuit == spades)
os << "S";
os << "[" << cd.cardFace << "] ";
return os;
}
// compare and return true if *this has a lesser point value than cd, false otherwise
bool Card::operator <= (const Card& cd) const
{
if (cardFace <= cd.cardFace)
return true;
else
return false;
}
// compare and return true if *this has a larger point value than cd, false otherwise
bool Card::operator >= (const Card &cd) const
{
if (cardFace >= cd.cardFace)
return true;
else
return false;
}
// compare and return true if *this has the same point value as cd, false otherwise
bool Card::operator == (const Card &cd) const
{
if (cardFace == cd.cardFace)
return true;
else
return false;
}
|
JavaScript
|
UTF-8
| 366
| 4.125
| 4
|
[] |
no_license
|
//The function is supposed to return a new array made up of 'num' copies of 'arr'
// modify it using spread syntax so that is works
function copyMachine(arr, num){
let newArr = [];
// iteration
while(num >= 1) {
let spreadArg = [...arr];
newArr.push(spreadArg);
num--;
}
return newArr;
}
//console.log(copyMachine([1,3,5],3));
|
PHP
|
UTF-8
| 355
| 2.5625
| 3
|
[] |
no_license
|
<?php
namespace ProjxIO\Token;
use ProjxIO\Token\Encoder;
class Base64Encoder implements Encoder
{
/**
* @inheritDoc
*/
public function encodeToken($value)
{
return base64_encode($value);
}
/**
* @inheritDoc
*/
public function decodeToken($value)
{
return base64_decode($value);
}
}
|
C
|
UTF-8
| 1,345
| 2.84375
| 3
|
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
/*
* pcshutwindown.c : (Not so) Lua module 'pcshutwindown'
*/
#include <stdio.h>
#include <windows.h>
/* No Lua things :-) */
/*
* Initiates system shutdown.
* Returns a bool showing whether the job succeeded.
*/
static BOOL shutdown_system (void) {
HANDLE TokenHandle;
TOKEN_PRIVILEGES Privileges;
if (!OpenProcessToken(GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
&TokenHandle))
return FALSE;
Privileges.PrivilegeCount = 1;
Privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME,
&Privileges.Privileges[0].Luid);
AdjustTokenPrivileges(TokenHandle, FALSE, &Privileges,
0, NULL, NULL);
if (GetLastError() != ERROR_SUCCESS)
return FALSE;
return ExitWindowsEx(EWX_SHUTDOWN, 0);
}
/*
* The entry point.
* Here shutdown will be initiated.
*/
__declspec(dllexport) int luaopen_pcshutwindown(void *L) {
int c;
for (c = 10; c >= 1; c--) {
printf("System will be shutdown in %d second%s...\n", c,
(c == 1) ? "" : "s");
Sleep(1000);
}
if (shutdown_system()) {
printf("FAREWELL!\n");
} else {
printf("ERROR: cannot initiate shutdown\n");
}
return 0;
}
|
Python
|
UTF-8
| 138
| 3
| 3
|
[] |
no_license
|
def som(getal1, getal2, getal3):
return getal1 + getal2 + getal3
getal1 = 1
getal2 = 2
getal3 = 5
print(som(getal1, getal2, getal3))
|
C#
|
UTF-8
| 3,125
| 2.71875
| 3
|
[] |
no_license
|
using MovieWeb.Data;
using MovieWeb.Data.Entities;
using MovieWeb.Repository.IRepository;
using MovieWeb.Services.IServices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MovieWeb.Repository
{
public class MoviesApiRepository : IMoviesApiRepository
{
private readonly MovieContext _context;
private readonly IGenresService _genresService;
private readonly IPeopleService _peopleService;
public MoviesApiRepository(MovieContext context, IGenresService genresService, IPeopleService peopleService)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
_genresService = genresService ?? throw new ArgumentNullException(nameof(genresService));
_peopleService = peopleService ?? throw new ArgumentNullException(nameof(peopleService));
}
public List<MovieDTO> GetAllMoviesApi()
{
var movies = _context.Movie.ToList();
var movieDTOList = MapMovieDTOList(movies);
return movieDTOList;
}
public List<MovieDTO> GetTopMoviesApi(int number)
{
var topMovies = _context.Movie.OrderByDescending(x => x.MovieRating).Take(number).ToList();
var movieDTOList = MapMovieDTOList(topMovies);
return movieDTOList;
}
public MovieDTO GetMovieByIdApi(int id)
{
var movie = _context.Movie.Find(id);
var movieDTO = MapMovieDTO(movie);
return movieDTO;
}
public List<MovieDTO> SearchMoviesApi(string search)
{
var searchedMovies = _context.Movie.Where(s => s.MovieTitle.Contains(search)).ToList();
var movieDTOList = MapMovieDTOList(searchedMovies);
return movieDTOList;
}
#region MapMoviDTOList
private List<MovieDTO> MapMovieDTOList(List<Movie> movies)
{
var movieList = new List<MovieDTO>();
foreach (var movie in movies)
{
movieList.Add(MapMovieDTO(movie));
}
return movieList;
}
private MovieDTO MapMovieDTO(Movie movie)
{
var movieDTO = new MovieDTO
{
ID = movie.ID,
MovieTitle = movie.MovieTitle,
Summary = movie.Summary,
ReleaseDate = movie.ReleaseDate,
Runtime = movie.Runtime,
MovieRating = movie.MovieRating,
MoviePrice = movie.MoviePrice,
MoviePosterURL = movie.MoviePosterURL,
IMDBLink = movie.IMDBLink,
Genres = _genresService.GetMovieGenresNamesByMovieID(movie.ID),
Directors = _peopleService.GetMoviePersonDTOByMovieID(movie.ID, 1),
Writers = _peopleService.GetMoviePersonDTOByMovieID(movie.ID, 2),
Actors = _peopleService.GetMoviePersonDTOByMovieID(movie.ID, 3)
};
return movieDTO;
}
#endregion
}
}
|
Java
|
UTF-8
| 2,720
| 2.5
| 2
|
[] |
no_license
|
package com.jmj.common.util.store;
import java.nio.ByteBuffer;
import java.util.Deque;
import java.util.concurrent.ConcurrentLinkedDeque;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.nio.ch.DirectBuffer;
import com.jmj.common.LoggerName;
import com.jmj.common.util.store.config.MessageStoreConfig;
import com.sun.jna.NativeLong;
import com.sun.jna.Pointer;
/**
* Created by ryao on 2017/7/11.
*/
public class TransientStorePool {
private static final Logger log = LoggerFactory.getLogger(LoggerName.STORE_LOGGER_NAME);
private final int poolSize;
private final int fileSize;
private final Deque<ByteBuffer> availableBuffers;
private final MessageStoreConfig storeConfig;
public TransientStorePool(final MessageStoreConfig storeConfig) {
this.storeConfig = storeConfig;
this.poolSize = storeConfig.getTransientStorePoolSize();
this.fileSize = storeConfig.getMapedFileSizeCommitLog();
this.availableBuffers = new ConcurrentLinkedDeque<>();
}
/**
* 初始化 根据队列长度,循环申请内存,并获取所申请内存的地址,并给申请到块内存加锁
*/
public void init() {
for (int i = 0; i < poolSize; i++) {
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(fileSize);
final long address = ((DirectBuffer) byteBuffer).address(); //获取分配到的物理内存地址
Pointer pointer = new Pointer(address);
LibC.INSTANCE.mlock(pointer, new NativeLong(fileSize)); //锁住该内存
availableBuffers.offer(byteBuffer);
}
}
/**
* 为队列中所有内存解锁
*/
public void destroy() {
for (ByteBuffer byteBuffer : availableBuffers) {
final long address = ((DirectBuffer) byteBuffer).address();
Pointer pointer = new Pointer(address);
LibC.INSTANCE.munlock(pointer, new NativeLong(fileSize));
}
}
public void returnBuffer(ByteBuffer byteBuffer) {
byteBuffer.position(0);
byteBuffer.limit(fileSize);
this.availableBuffers.offerFirst(byteBuffer);
}
public ByteBuffer borrowBuffer() {
ByteBuffer buffer = availableBuffers.pollFirst();
if (availableBuffers.size() < poolSize * 0.4) {
log.warn("TransientStorePool only remain {} sheets.", availableBuffers.size());
}
return buffer;
}
/**
* 获取栈中剩余缓存数
*
* @return
*/
public int remainBufferNumbs() {
if (storeConfig.isTransientStorePoolEnable()) {
return availableBuffers.size();
}
return Integer.MAX_VALUE;
}
}
|
JavaScript
|
UTF-8
| 7,554
| 2.515625
| 3
|
[] |
no_license
|
import React, { useState } from 'react';
import { useEffect } from 'react';
import './App.css';
import Header from './components/Header/Header';
import Card from './components/Card/Card';
import axios from 'axios';
import {Route} from 'react-router-dom';
import Modal from './utils/Modal';
function App() {
const[data,setData] = useState([]);
const[data2,setData2]= useState([]);
const[validateBtn,setValidateBtn]=useState(false);
const[validateBtn2,setValidateBtn2]=useState(false);
const[validateBtn3,setValidateBtn3]=useState(false);
//--------------------------------------------------------
const [checkedNum,setCheckedNum] = useState([]);
const [twoValidate,setTwoValidate]=useState(false);
const [twoValidate2,setTwoValidate2]=useState(false);
const [twoValidate3,setTwoValidate3]=useState(false);
const [twoValidate4,setTwoValidate4]=useState(false);
const [twoValidate5,setTwoValidate5]=useState(false);
//--------------------------------------------------------
const [nextBtn,setNextBtn]=useState(false);
//------------------------------------------------------
const [selectedCard,setSelectedCard]= useState([]);
const [selectedProductCard,setSlProductCard] = useState([]);
useEffect(()=>{
axios.get('https://api.kadporastembicu.dev/v1/templates')
.then(response =>{
setData(response.data);
})
.catch(error =>{
console.log(error)
})
}, [])
useEffect(()=>{
axios.get('https://api.kadporastembicu.dev/v1/products')
.then(response =>{
setData2(response.data);
})
.catch(error =>{
console.log(error)
})
}, [])
const nextButtonHandler = (e) => {
setNextBtn(true);
}
const templatesSelectHandler=(name,description,price) => {
if(name === "e20"){
setValidateBtn(true);
setValidateBtn2(false);
setValidateBtn3(false);
}else if (name === "e200"){
setValidateBtn2(true);
setValidateBtn(false);
setValidateBtn3(false);
}else {
setValidateBtn3(true);
setValidateBtn2(false);
setValidateBtn(false);
}
setTwoValidate(false);
setTwoValidate2(false);
setTwoValidate3(false);
setTwoValidate4(false);
setTwoValidate5(false);
setCheckedNum([]);
setSelectedCard({name,description,price})
setSlProductCard([])
}
const productSelectHandler = (name,description,price)=>{
setCheckedNum((prev)=>{
return [...prev,name]
})
if(name === "CDN"){
setTwoValidate(true);
}else if (name === "DNS"){
setTwoValidate2(true)
}else if (name === "Edge Compute"){
setTwoValidate3(true)
}else if (name === "Monitoring"){
setTwoValidate4(true)
}else if (name === "WAF"){
setTwoValidate5(true)
}
setValidateBtn(false);
setValidateBtn2(false);
setValidateBtn3(false);
setSelectedCard([]);
setSlProductCard((prv)=>{
return[...prv,{name,description,price}]
})
}
const productUncheckHandler = (name) =>{
let newArr = checkedNum.filter((item)=>{
return item !== name
})
setCheckedNum(()=>newArr);
if(name === "CDN"){
setTwoValidate(false);
}else if (name === "DNS"){
setTwoValidate2(false)
}else if (name === "Edge Compute"){
setTwoValidate3(false)
}else if (name === "Monitoring"){
setTwoValidate4(false)
}else if (name === "WAF"){
setTwoValidate5(false)
}
let newArrTwo = selectedProductCard.filter((el)=>{
return el.name !==name;
})
setSlProductCard(()=>newArrTwo);
}
const dummyData =["Unlimited Sites","Unlimited SSL Ceritifcates","1TB CDN Bandwith","5M WAF requests","5 WAF Custom Rules","2M DNS Requests","1 Monitored Service","Netword Layer DDoS Protection"]
const dummyData1 = ["Unlimited Sites","Unlimited Requests","1TB/mo Bandwith","All Global PoPs Included","Free SSL Certificate per site","Network Layer DDoS Protection"];
const dummyData2 = ["Unlimited DNS Zones","Unlimited DNS Records","2M/mo DNS Queries","Global Anycast Network","Network Layer DDoS Protection"];
const dummyData3 = ["45+ PoPs around the World","Platform-wide network layer DDoS protection","Anycast IPs","Built-in CPU and RAM Monitoring"];
const dummyData4 = ["5 Monitored Services","34 Location Checks","30-day Data Retention","5-minute Check Interval"];
const dummyData5 = ["Unlimited Sites","10M Requests","5 Custom Rules","Free Private SSL Certificate","Built-in OWASP & CMS Rules"];
return (
<div className="App">
<Header checkedNum={checkedNum} />
<Route path="/vl/templates">
<div className="templates">
<Card position="e20" title="mixed" data={data} dummyData={dummyData} validateBtn={validateBtn} templates="yes" clicked={templatesSelectHandler}/>
<Card position="e200" title="mixed" data={data} dummyData={dummyData} validateBtn={validateBtn2} templates="yes"clicked={templatesSelectHandler}/>
<Card position="e2000" title="mixed" data={data} dummyData={dummyData} validateBtn={validateBtn3} templates="yes" clicked={templatesSelectHandler}/>
</div>
</Route>
<Route path="/vl/products">
<div className="products">
<Card position="CDN" data={data2} dummyData={dummyData1} colored="yes" clicked={productSelectHandler} validateBtn={twoValidate} uncheck={productUncheckHandler} />
<Card position="DNS" data={data2} dummyData={dummyData2} clicked={productSelectHandler} validateBtn={twoValidate2} uncheck={productUncheckHandler}/>
<Card position="Edge Compute" data={data2} dummyData={dummyData3} colored="yes" clicked={productSelectHandler} validateBtn={twoValidate3} uncheck={productUncheckHandler} />
<Card position="Monitoring" data={data2} dummyData={dummyData4} clicked={productSelectHandler} validateBtn={twoValidate4} uncheck={productUncheckHandler}/>
<Card position="WAF" data={data2} dummyData={dummyData5} colored="yes" clicked={productSelectHandler} validateBtn={twoValidate5} uncheck={productUncheckHandler}/>
</div>
</Route>
<div className="bottomBtns">
{validateBtn === false &&
validateBtn2 === false &&
validateBtn3 === false &&
twoValidate === false &&
twoValidate2 === false &&
twoValidate3 === false &&
twoValidate4 === false &&
twoValidate5 === false
?
<button disabled={true}>Next →</button>
:
<button onClick={nextButtonHandler}disabled={false}>Next →</button>
}
<span>or</span>
<button>Back</button>
</div>
{nextBtn === true ?
<Modal onClose={()=> setNextBtn(false)}>
{selectedCard && checkedNum.length <=0 ? <div className="selectedTemp">
<h2>Edge Delivery{selectedCard.name}</h2>
<div>{selectedCard.description}</div>
<div>{selectedCard.price}</div>
</div>: null }
{selectedProductCard.map((item)=>{
return (
<div key={item.name} className="selectedTemp">
<h2>{item.name}</h2>
<div>{item.description}</div>
<div>{item.price}</div>
</div>
)
}) }
</Modal>
: null}
</div>
);
}
export default App;
|
Markdown
|
UTF-8
| 1,371
| 2.515625
| 3
|
[] |
no_license
|
## Thumb joystick
<table border="0" width="100%"><tr><td colspan=2 width="60%">seeed studio Grove </td>
<td rowspan=9 width="40%" align="right"><img src="../../.img/thumb.jpg" width="200px" /></td></tr>
<tr><td>Voltage range</td><td><b>4.75V - 5.25V</b></td></tr>
<tr><td>Input type</td><td><b>Digital</b></td></tr>
<tr><td>Compatible</td><td><b>Arduino, Raspberry Pi, ESP8266</b></td></tr>
<tr><td>Response time</td><td><b>1s</b></td></tr>
<tr><td>Price</td><td><b>< 182 Kč</b></td></tr></table>
* [Datasheet](./datasheet.pdf)
### Circuit
<p align="center"><img src="../../.img/thumb.png" width="45%" /></p>
### MicroPython
```python
import machine
import time
x_pin = machine.Pin(4, machine.Pin.IN) # X pin D2
y_pin = machine.Pin(2, machine.Pin.IN) # Y pin D4
def read_joystick():
x_state = x_pin.value()
y_state = y_pin.value()
return x_state, y_state
while True:
x, y = read_joystick()
print("X-axis state:", x)
time.sleep(1)
print("Y-axis state:", y)
time.sleep(1)
print("------------------")
time.sleep(1)
```
### Notes
> Also found in Grove Creator Kit-
>
>https://wiki.seeedstudio.com/Grove-Creator-Kit-1/
### References
> https://wiki.seeedstudio.com/Grove-Thumb_Joystick/
>
> https://seeeddoc.github.io/Grove-Thumb_Joystick/
### Zpracováno
- Václav Sontag
- Lucas Löffler
|
PHP
|
UTF-8
| 740
| 2.546875
| 3
|
[] |
no_license
|
<?php
/*
* 精英贷数据
*/
class EliteloanDataModel extends Model{
//添加数据
public function addData($data){
$rules = array('name'=>'姓名','phone'=>'手机号码','email'=>'邮箱');
foreach($rules as $k=>$v){
if($data[$k] == ''){
$this->error = $v.'不能为空';
return false;
}
}
$data['cTime'] = time();
$res = $this->add($data);
if($res){
return true;
}else{
$this->error = '系统错误';
return false;
}
}
//数据列表
public function dataList(){
$res = $this->field('name,phone,email,ctime')->order('id DESC')->findPage(10);
}
}
?>
|
Python
|
UTF-8
| 634
| 3.890625
| 4
|
[] |
no_license
|
# coding=utf-8
# Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
# Triangle Tn=n(n+1)/2 1, 3, 6, 10, 15, ...
# Pentagonal Pn=n(3n−1)/2 1, 5, 12, 22, 35, ...
# Hexagonal Hn=n(2n−1) 1, 6, 15, 28, 45, ...
# It can be verified that T285 = P165 = H143 = 40755.
# Find the next triangle number that is also pentagonal and hexagonal.
from comm import timed
import comm
@timed
def p45():
n = 143
while True:
n+=1
x = n*(2*n-1)
y, z = comm.isPent(x)
if y:
a,b = comm.isTri(x)
return f"T{b} = P{z} = H{n} = {x}"
print(p45())
|
C++
|
UTF-8
| 370
| 2.734375
| 3
|
[] |
no_license
|
#pragma once
#include <cmath>
/// @defgroup util
/// @{
namespace ax {
namespace util {
namespace Interpole {
template <typename T> T Lineair(const T& y1, const T& y2, const T& mu)
{
return y1 + mu * (y2 - y1);
}
template <typename T> T Logarithmic(const T& y1, const T& y2, const T& mu)
{
return pow(y2, mu) * pow(y1, 1.0 - mu);
}
}
}
}
/// @}
|
C++
|
UTF-8
| 3,330
| 3.578125
| 4
|
[
"Apache-2.0"
] |
permissive
|
#include <fstream>
#include "bstree.hpp"
#include <string>
#include <iostream>
using namespace std;
using namespace BSTree;
Tree::Tree() {
root = nullptr;
}
Node* Tree::insert(int var, Node *&node) { //Фукция добавления звена в дерево
if (nullptr == node) { // Если дерева нет, то ложим семечко
node = new Node{var,nullptr,nullptr}; // память под звено дерева
}
else {
if (var < node->var) //Если нововведенный элемент var меньше чем элемент var из семечка дерева, уходим влево
node->left=insert(var, node->left);
if (var> node->var) //Если нововведенный элемент var больше чем элемент var из семечка дерева, уходим вправо
node->right=insert(var, node->right);
}
return node;
}
void Tree::remove(Node *&node) {
if (node != nullptr) {
remove(node->left); //Рекурсивная функция прохода по левому поддереву
remove(node->right); //Рекурсивная функция для прохода по правому поддереву
delete node; //Удаляем конечный элемент дерева
node = nullptr;
}
}
void Tree::insert(int var) {
insert(var, root);
}
void Tree::show(){
show(root,1);
}
void Tree::show(char choice){
switch(choice)
{
case 'a':direct_bypass(root);
cout<<endl;
break;
case 'b':symmetric_bypass(root);
cout<<endl;
break;
case 'c':back_bypass(root);
cout<<endl;
break;
}
}
void Tree::show(Node *node, int x) {
if (node != nullptr) {
if (node->right != nullptr)
show(node->right, x + 1);
for (int i = 0; i < x; i++) {
cout << " ";
}
if ((node->var) != (root->var))
cout << "--";
cout << node->var << endl;
if (node->left != nullptr)
show(node->left, x + 1 );
}
else
cout << "Tree is empty!" << endl;
}
void Tree::show(Node *node,ostream& os, int x) const{
if (node->right != nullptr)
show(node->right,os, x + 1);
for (int i = 0; i < x; i++) {
os << " ";
}
if ((node->var) != (root->var))
os << "--";
os << node->var << endl;
if (node->left != nullptr)
show(node->left,os , x + 1 );
}
void Tree::direct_bypass(Node *node){
cout<<node->var<<" ";
if(node->left!=nullptr)
direct_bypass(node->left);
if(node->right!=nullptr)
direct_bypass(node->right);
}
void Tree::symmetric_bypass(Node *node){
if(node!=nullptr){
symmetric_bypass(node->left);
cout<<node->var<<" ";
symmetric_bypass(node->right);
}
return;
}
void Tree::back_bypass(Node *node){
if(node!=nullptr){
back_bypass(node->left);
back_bypass(node->right);
cout<<node->var<<" ";
}
}
void Tree::show23(Node* root, ofstream &fout) {
if (root != nullptr) {
fout << root->var << " ";
show23(root->right,fout);
show23(root->left,fout);
}
}
void Tree::save_to_file()
{
string filename;
cout << "enter name of file" << endl;
cin >> filename;
ofstream fout(filename.c_str());
show23(root, fout);
}
namespace BSTree{
auto operator<<(ostream& os,const Tree& tree) -> ostream&{
tree.show(tree.root,os,1);
return os;
}
}
Tree::~Tree() {
remove(root);
}
|
C++
|
UTF-8
| 1,138
| 2.71875
| 3
|
[] |
no_license
|
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
string dogam1[100000];
pair<string,int> dogam2[100000];
int main(){
ios::sync_with_stdio(0);cin.tie(0);
int N,M;
string s;
cin>>N>>M;
for(int i=0;i<N;i++){
cin>>dogam1[i];
dogam2[i]={dogam1[i],i+1};
}
sort(dogam2,dogam2+N);
for(int i=0;i<M;i++){
cin>>s;
if(isdigit(s[0])){
cout<<dogam1[stoi(s)-1]<<'\n';
}else{
cout<<lower_bound(dogam2,dogam2+N,make_pair(s,0))->second<<'\n';
}
}
return 0;
}
#include <iostream>
#include <algorithm>
#include <cstring>
#include <unordered_map>
using namespace std;
string dogam1[100000];
unordered_map<string,int> dogam2;
int main(){
ios::sync_with_stdio(0);cin.tie(0);
int N,M;
string s;
cin>>N>>M;
for(int i=0;i<N;i++){
cin>>dogam1[i];
dogam2[dogam1[i]]=i+1;
}
for(int i=0;i<M;i++){
cin>>s;
if(isdigit(s[0])){
cout<<dogam1[stoi(s)-1]<<'\n';
}else{
cout<<dogam2[s]<<'\n';
}
}
return 0;
}
|
Python
|
UTF-8
| 8,149
| 2.96875
| 3
|
[] |
no_license
|
import sys
import pygame
from pygame.display import update
from time import sleep
from settings import Settings
from ships import Ship
from bullet import Bullet
from alien import Alien
from game_start import GameStats
from button import Buttom
from scoreboard import Scoreboard
class AlienInvasion:
"""管理游戏资源和行为的类"""
def __init__(self):
"""初始化游戏并创建游戏资源"""
pygame.init()
self.settings=Settings()
# 创建屏幕
# self.screen=pygame.display.set_mode((0,0),pygame.FULLSCREEN)
# self.settings.screen_height=self.screen.get_rect().height
# self.settings.screen_width=self.screen.get_rect().width
self.screen=pygame.display.set_mode(
(self.settings.screen_width,self.settings.screen_height))
pygame.display.set_caption("Alien Invasion")
# 创建储存游戏统计信息的实例,并创建计分牌
self.stats=GameStats(self)
self.sb=Scoreboard(self)
# 创建飞船子弹外星人
self.ship=Ship(self)
self.bullets=pygame.sprite.Group()
self.aliens=pygame.sprite.Group()
self._create_fleet()
# 创建play按钮
self.play_buttom=Buttom(self,"Play")
# 设置背景色
self.bg_color=self.settings.bg_color
def run_game(self):
"""开始游戏的主循环"""
while True:
self._check_events()
if self.stats.game_active:
self.ship.update()
self._update_bullets()
self._update_aliens()
self._update_screen()
def _create_fleet(self):
"""创建外星人群"""
alien=Alien(self)
alien_width,alien_height=alien.rect.size
availbale_space_x=self.settings.screen_width-(2*alien_width)
number_aliens_x=availbale_space_x//(2*alien_width)
ship_height=self.ship.rect.height
availbale_space_y=(self.settings.screen_height-
(3*alien_height)-ship_height)
number_rows=availbale_space_y//(2*ship_height)
# 创建外星人群
for row_number in range(number_rows-3):
for alien_number in range(number_aliens_x):
self._create_alien(alien_number,row_number)
def _create_alien(self, alien_number, row_number):
alien=Alien(self)
alien_width,alien_height=alien.rect.size
alien.x=alien_width+2*alien_width*alien_number
alien.rect.x=alien.x
alien.rect.y=alien_height+2*alien_height*row_number
self.aliens.add(alien)
def _check_events(self):
# 监视键盘和鼠标事件
for event in pygame.event.get():
if event.type==pygame.QUIT:
sys.exit()
elif event.type==pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type==pygame.KEYUP:
self._check_keyup_events(event)
elif event.type==pygame.MOUSEBUTTONDOWN:
mouse_pos=pygame.mouse.get_pos()
self._check_play_buttom(mouse_pos)
def _check_keydown_events(self, event):
if event.key==pygame.K_RIGHT:
self.ship.moving_right=True
if event.key==pygame.K_LEFT:
self.ship.moving_left=True
if event.key==pygame.K_SPACE:
self._fire_bullet()
if event.key==pygame.K_q:
sys.exit()
if event.key==pygame.K_p:
self._start_game()
def _check_keyup_events(self, event):
if event.key==pygame.K_RIGHT:
self.ship.moving_right=False
if event.key==pygame.K_LEFT:
self.ship.moving_left=False
def _check_play_buttom(self,mouse_pos):
"""在玩家点击play按钮时开始新游戏"""
buttom_clicked=self.play_buttom.rect.collidepoint(mouse_pos)
if buttom_clicked and not self.stats.game_active:
self._start_game()
self.sb.prep_score()
self.sb.prep_level()
self.sb.prep_ships()
def _start_game(self):
# 重置游戏统计信息
self.stats.reset_stats()
self.stats.game_active=True
# 清空余下的外星人和子弹
self.aliens.empty()
self.bullets.empty()
# 创建一群新的外星人并让飞船居中
self._create_fleet()
self.ship.center_ship()
# 隐藏光标
pygame.mouse.set_visible(False)
def _fire_bullet(self):
# 创建一个子弹,并将其加入编组bullets中
if len(self.bullets)<self.settings.bullet_allow:
new_bullet=Bullet(self)
self.bullets.add(new_bullet)
def _update_bullets(self):
# 更新子弹位置并删除消失的子弹
self.bullets.update()
for bullet in self.bullets.copy():
if bullet.rect.bottom<=0:
self.bullets.remove(bullet)
self._check_bullet_alien_collisions()
def _check_bullet_alien_collisions(self):
# 检查是否有子弹击中了外星人
# 如果是,就删除相应的子弹和外星人
collisions=pygame.sprite.groupcollide(
self.bullets,self.aliens,True,True)
if collisions:
for aliens in collisions.values():
self.stats.score+=self.settings.alien_point*len(aliens)
self.sb.prep_score()
self.sb.check_high_score()
if not self.aliens:
# 删除现有的子弹并创建一群外星人
self.bullets.empty()
self._create_fleet()
self.settings.increase_speed()
# 提高等级
self.stats.level+=1
self.sb.prep_level()
def _update_aliens(self):
"""更新外星人群中所有外星人的位置"""
self._check_fleet_edges()
self.aliens.update()
# 检查是否有外星人撞到了飞船
if pygame.sprite.spritecollideany(self.ship,self.aliens):
self._ship_hit()
# 检查是否有外星人到达了屏幕底端
self._check_aliens_bottom()
def _check_aliens_bottom(self):
"""检查是否有外星人到达了屏幕底端"""
screen_rect=self.screen.get_rect()
for alien in self.aliens.sprites():
if alien.rect.bottom>=screen_rect.bottom:
# 像飞船被撞一样处理
self._ship_hit()
break
def _ship_hit(self):
if self.stats.ship_left>0:
"""响应飞船被外星人撞到"""
self.stats.ship_left-=1
self.sb.prep_ships()
self.aliens.empty()
self.bullets.empty()
self._create_fleet()
self.ship.center_ship()
# 暂停
sleep(0.5)
else:
self.stats.game_active=False
pygame.mouse.set_visible(True)
def _check_fleet_edges(self):
"""有外星人到达边缘时采取相应的措施"""
for alien in self.aliens.sprites():
if alien.check_edges():
self._change_fleet_direction()
break
def _change_fleet_direction(self):
"""将整群外星人下移,并改变它们的方向"""
for alien in self.aliens.sprites():
alien.rect.y+=self.settings.fleet_drop_speed
self.settings.fleet_direction*=-1
def _update_screen(self):
# 每次循环时都重绘屏幕
self.screen.fill(self.bg_color)
self.ship.blitme()
for bullet in self.bullets.sprites():
bullet.draw_bullet()
self.aliens.draw(self.screen)
# 显示得分
self.sb.show_score()
# 如果游戏处于非活动状态,就绘制play按钮
if not self.stats.game_active:
self.play_buttom.draw_buttom()
# 让最近绘制的屏幕可见
pygame.display.update()
if __name__=="__main__":
# 创建游戏实例并运行游戏
ai=AlienInvasion()
screen=ai.screen.get_rect()
ai.run_game()
|
Shell
|
UTF-8
| 1,773
| 3.484375
| 3
|
[] |
no_license
|
#!/bin/bash
# https://raspberrypi.stackexchange.com/questions/60593/how-raspbian-detects-under-voltage
font_size=11500
icon_size=13000
medicon_size=15000
largeicon_size=20000
RED_SPAN="<span color=\"red\">"
NORMAL_SPAN="<span font-size=\"$font_size\">"
ICON_SPAN="<span font-size=\"$icon_size\">"
MEDICON_SPAN="<span font-size=\"$medicon_size\">"
LARGEICON_SPAN="<span font-size=\"$largeicon_size\">"
ERROR_SPAN="<span font-size=\"$font_size\" weight=\"heavy\" color=\"red\" underline=\"error\">"
WARNING_SPAN="<span font-size=\"$font_size\" weight=\"bold\" color=\"yellow\">"
BATTERY_ICON="<span font-size=\"$icon_size\">🔋</span>"
NODEVICE_SUB="No raw devices found."
MOUNT_SUB="/media/pi/s9"
OUTPUT=" $LARGEICON_SPAN📱</span>"
ERRORX_OUTPUT="$ERROR_SPAN❌</span>"
MOUNTDETECT=$(mount)
if [[ "$MOUNTDETECT" == *"$MOUNT_SUB"* ]]; then
OUTPUT+="$MEDICON_SPAN🖴</span>"
else
MTPDETECT=$(mtp-detect)
# if [[ $? ]]; then
# OUTPUT+="$ERRORX_OUTPUT"
# echo "$OUTPUT"
# exit
# else
if [[ "$MTPDETECT" != *"$NODEVICE_SUB"* ]]; then
# Determine Battery Level
SUB="Battery level"
BATTERYSTATUS=$(grep "$SUB" <<< "$MTPDETECT")
BATTERYSTATUS=${BATTERYSTATUS#*(}
BATTERYSTATUS=${BATTERYSTATUS%\%*}
if (($BATTERYSTATUS > 15 )); then
BATTERYSTATUS="$NORMAL_SPAN$BATTERYSTATUS</span>"
elif (($BATTERYSTATUS > 5 )); then
BATTERYSTATUS="$WARNING_SPAN$BATTERYSTATUS</span>"
else
BATTERYSTATUS="$ERROR_SPAN$BATTERYSTATUS</span>"
fi
OUTPUT+="$BATTERY_ICON$BATTERYSTATUS%"
else
OUTPUT+="$ERROR_SPAN❌</span>"
fi
# fi
fi
echo "$OUTPUT"
|
Java
|
UTF-8
| 1,132
| 2.296875
| 2
|
[] |
no_license
|
package com.sony.model.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
@Entity
@Table(name = "specialisation")
public class Specialisation {
@Id
@GeneratedValue(strategy=GenerationType.AUTO, generator = "specialisation_sequence")
@SequenceGenerator(name = "specialisation_sequence", sequenceName = "SPECIALISATION_ID_SEQ")
@Column(name = "specialisation_id")
private int specialisationId;
@Column(name = "specialisation_name")
private String specialisationName;
public int getSpecialisationId() {
return specialisationId;
}
public void setSpecialisationId(int specialisationId) {
this.specialisationId = specialisationId;
}
public String getSpecialisationName() {
return specialisationName;
}
public void setSpecialisationName(String specialisationName) {
this.specialisationName = specialisationName;
}
}
|
Java
|
UTF-8
| 1,776
| 2.03125
| 2
|
[] |
no_license
|
package com.fisincorporated.exercisetracker.ui.media.mediagrid;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import com.bumptech.glide.Glide;
import com.fisincorporated.exercisetracker.GlobalValues;
import com.fisincorporated.exercisetracker.R;
import com.fisincorporated.exercisetracker.ui.media.MediaDetail;
import java.util.ArrayList;
public class MediaGridFragment extends Fragment {
private ArrayList<MediaDetail> mediaDetails;
private GridView gridView;
public static MediaGridFragment newInstance() {
MediaGridFragment fragment = new MediaGridFragment();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.photo_fragment_gridview, container, false);
getReferencedViews(view);
lookForArguments(savedInstanceState);
gridView.setAdapter(new MediaGridAdapter(getContext(), Glide.with(this), mediaDetails));
return view;
}
private void getReferencedViews(View view) {
gridView = (GridView) view.findViewById(R.id.photo_fragment_gridview);
}
private void lookForArguments(Bundle savedInstanceState) {
Bundle bundle = null;
if (getArguments() != null) {
bundle = getArguments();
}
if (bundle != null) {
mediaDetails = bundle.getParcelableArrayList(GlobalValues.PHOTO_POINTS);
}
}
}
|
Markdown
|
UTF-8
| 3,278
| 3
| 3
|
[
"MIT"
] |
permissive
|
---
layout: post
title: xml 이란?
subtitle:
gh-repo:
gh-badge: [star, fork, follow]
tags: [java]
categories : [Other]
---
### xml 이란?
Extensible Markup Language
마크업 언어를 정의하기 위한 언어, 확장이 가능한 언어이다.
HTML 이 데이터를 표현하는 마크업 언어라면, XML 은 Tag를 정의할 수 있고 데이터를 기술하는 마크업 언어
* 텍스트 기반이며 간결한 데이터형
* 마크업언어(HTML)가 아니라 마크업언어를 정의하기 위한 언어.
* XML은 데이터를 기술하고 구조화시키는데 사용(데이터 교환)
* HTML은 동일한 데이터를 표시하고 꾸미는데 사용
### 주요 용어
* (유니코드) 문자
정의 상, XML 문서는 문자로 이루어진 문자열이다. 거의 모든 올바른 유니코드 문자는 XML 문서에 나타날 수 있다.
프로세서(processor)와 애플리케이션(application)
프로세서는 마크업을 분석하고 구조화된 정보를 애플리케이션에 넘긴다. 이 명세는 XML 프로세서가 무엇을 해야하고 하지 말아야 하는지 제시하지만, 애플리케이션에 대해서는 다루지 않는다. 이 프로세서(명세가 부르기를)는 흔히 XML parser라 불린다.
* 마크업(markup)과 내용(content)
XML 문서를 구성하는 문자들은 마크업과 내용으로 나뉘는데, 그 구분은 간단한 문법 규칙으로 이루어진다. 일반적으로 마크업을 구성하는 문자열은 문자 <로 시작하여 문자 >로 끝나거나, 문자 &로 시작하여 문자 ;로 끝나며, 마크업이 아닌 문자열은 내용이다. 그러나, CDATA 절에서, 구분자 <![CDATA[와 ]]>는 마크업으로 분류되고, 그들 사이의 텍스트는 내용으로 구분된다. 추가로, 가장 바깥 엘리먼트의 앞과 뒤의 공백(whitespace)은 마크업으로 분류된다.
* 태그(tag)
- <로 시작하여 >로 끝나는 마크업 구조. 태그는 세 가지 종류가 있다:
- 시작 태그(start-tag); 예: <section>
- 끝 태그(end-tag); 예: </section>
- 빈 엘리먼트(empty-element) 태그; 예: <line-break />
* 엘리먼트(element)
문서의 논리 요소로서, 시작 태그로 시작하여 짝이 되는 끝 태그로 끝나거나, 빈 엘리먼트 태그만으로 이루어진다. 시작 태그와 끝 태그 사이의 문자들은(있다면) 엘리먼트의 내용이고, 마크업을 포함할 수 있다. 이 마크업은 자식 엘리먼트(child elements)라 부르는 다른 엘리먼트들을 포함할 수도 있다. 엘리먼트의 예는 <Greeting>Hello, world.</Greeting> (see hello world). 다른 예는 <line-break />.
* 애트리뷰트(Attribute)
이름/값 짝으로 이루어진 마크업 구조로 시작 태그 또는 빈 엘리먼트 태그 속에 위치한다. 다음 예에서 엘리먼트 img는 src와 alt의 두 애트리뷰트를 갖는다:
> <img src="madonna.jpg" alt='Foligno Madonna, by Raphael'/>
다른 예로
> <step number="3">Connect A to B.</step>
에서 애트리뷰트 이름은 "number"이고 값은 "3"이다.
* XML 선언
XML 문서는 다음과 같이 자신에 대한 정보 일부를 선언하는 것으로 시작할 수 있다:
> <?xml version="1.0" encoding="UTF-8" ?>
|
JavaScript
|
UTF-8
| 2,083
| 3.984375
| 4
|
[] |
no_license
|
`
한 반에 30명인 학생, 총 7개의 반 점수가 '국어, 영어, 수학, 사회, 과학' 순서로 있는 다중 리스트를 랜덤 한 값으로 만들어주시고 아래 값을 모두 출력하세요.
1. 반 점수 모두가 담긴 전교 점수 다중 리스트를 만들어주세요.
2. 반 평균을 구하세요.
3. 반 1등 점수를 구하세요.
4. 전교 평균을 구하세요.
(출력 형식은 상관없습니다.)
`
let student_score = [];
let class_score = [];
let total_score = [];
for (let k = 0; k < 7; k++) {
class_score = [];
for (let j = 0; j < 30; j++) {
student_score = [];
for (let i = 0; i < 5; i++) {
student_score.push(Math.floor(Math.random() * 100) + 1);
}
class_score.push(student_score);
}
total_score.push(class_score);
}
const classAverageRank = total_score => {
let classAverage = []
total_score.forEach(classScore => {
let tmp = 0;
console.log(classScore)
classScore.forEach(score => {
tmp += score
})
classAverage.push(Math.floor(tmp/classScore.length))
})
return classAverage
}
const classTopRank = total_score => {
let studentTop = []
total_score.forEach(classScore => {
classScore.forEach(score => {
studentTop.push(score)
})
})
return Math.max.apply(studentTop,null)
}
// console.log(classAverageRank(total_score))
// console.log(classTopRank(total_score))
let total_average = [];
let c_average = [];
let s_average = 0;
let s_sum = 0;
let c_sum = 0;
let student_one = 0;
let 일등 = 0;
for (let c of total_score) {
// console.log(c);
for (let s of c) {
s_sum = s.reduce((a, b) => a + b);
s_average = s_sum / 5;
c_average.push(s_average);
if (일등 < s_average){
일등 = s_average;
}
}
console.log(일등);
일등 = 0;
console.log(c_average);
total_average.push(c_average.reduce((a, b) => a + b)/30);
c_average = [];
}
console.log(total_average);
console.log(total_average.reduce((a, b) => a + b)/7);
|
Java
|
UTF-8
| 7,093
| 2.171875
| 2
|
[] |
no_license
|
package com.example.gymfit.system.conf.recycleview;
import android.graphics.Canvas;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;
import com.example.gymfit.R;
public class ItemTouchHelperCallback extends ItemTouchHelper.Callback {
private final OnItemSwipeListener actionListener;
public ItemTouchHelperCallback(OnItemSwipeListener actionListener) {
this.actionListener = actionListener;
}
@Override
public boolean isLongPressDragEnabled() {
return false;
}
@Override
public boolean isItemViewSwipeEnabled() {
return true;
}
/**
* In this method we will get the movement of recycleView item when activated
*
* @param recyclerView RecycleView subject of the action
* @param viewHolder RecycleView Holder subject of the action
* @return both of swipe and drag action flag
*/
@Override
public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
final int dragFlag = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
final int swipeFlag = ItemTouchHelper.START;
return makeMovementFlags(dragFlag, swipeFlag);
}
/**
* In this method when we move our item we just get its old position and send in interface in news
*
* @param viewHolder RecycleView Holder subject of the action
* @param direction direction of action
*/
@Override
public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
actionListener.onItemSwipe(viewHolder, viewHolder.getAdapterPosition());
}
/**
* In this method we show delete button when we swipe
*
* @param c default
* @param recyclerView default
* @param viewHolder default
* @param dX default
* @param dY default
* @param actionState default
* @param isCurrentlyActive default
*/
@Override
public void onChildDraw(@NonNull Canvas c, @NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
} else {
final View foregroundView;
if (viewHolder instanceof ListGymAdapter.MyViewHolder) {
foregroundView = ((ListGymAdapter.MyViewHolder) viewHolder).cardContainer;
} else if (viewHolder instanceof ListUserSubscribedAdapter.MyViewHolder) {
foregroundView = ((ListUserSubscribedAdapter.MyViewHolder) viewHolder).cardContainer;
} else if (viewHolder instanceof ListSubscriberAdapter.MyViewHolder) {
foregroundView = ((ListSubscriberAdapter.MyViewHolder) viewHolder).cardContainer;
} else {
foregroundView = ((ListTurnPickedAdapter.MyViewHolder) viewHolder).cardContainer;
}
getDefaultUIUtil().onDraw(c, recyclerView, foregroundView, dX, dY, actionState, isCurrentlyActive);
}
}
/**
* In this method when we swipe create smooth animation
*
* @param c default
* @param recyclerView default
* @param viewHolder default
* @param dX default
* @param dY default
* @param actionState default
* @param isCurrentlyActive default
*/
@Override
public void onChildDrawOver(@NonNull Canvas c, @NonNull RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {
super.onChildDrawOver(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
} else {
final View foregroundView;
if (viewHolder instanceof ListGymAdapter.MyViewHolder) {
foregroundView = ((ListGymAdapter.MyViewHolder) viewHolder).bcContainer;
} else if (viewHolder instanceof ListUserSubscribedAdapter.MyViewHolder) {
foregroundView = ((ListUserSubscribedAdapter.MyViewHolder) viewHolder).bcContainer;
} else if (viewHolder instanceof ListSubscriberAdapter.MyViewHolder) {
foregroundView = ((ListSubscriberAdapter.MyViewHolder) viewHolder).deleteContainer;
} else {
foregroundView = ((ListTurnPickedAdapter.MyViewHolder) viewHolder).deleteContainer;
}
getDefaultUIUtil().onDrawOver(c, recyclerView, foregroundView, dX, dY, actionState, isCurrentlyActive);
}
}
/**
* In this method we clear view when swipe or drag
*
* @param recyclerView default
* @param viewHolder default
*/
@Override
public void clearView(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
final View foregroundView;
if (viewHolder instanceof ListGymAdapter.MyViewHolder) {
foregroundView = ((ListGymAdapter.MyViewHolder) viewHolder).cardContainer;
foregroundView.setBackgroundColor(ContextCompat.getColor(((ListGymAdapter.MyViewHolder) viewHolder).cardContainer.getContext(), R.color.quantum_white_100));
} else if (viewHolder instanceof ListUserSubscribedAdapter.MyViewHolder) {
foregroundView = ((ListUserSubscribedAdapter.MyViewHolder) viewHolder).cardContainer;
foregroundView.setBackgroundColor(ContextCompat.getColor(((ListUserSubscribedAdapter.MyViewHolder) viewHolder).cardContainer.getContext(), R.color.quantum_white_100));
} else if (viewHolder instanceof ListSubscriberAdapter.MyViewHolder) {
foregroundView = ((ListSubscriberAdapter.MyViewHolder) viewHolder).cardContainer;
foregroundView.setBackgroundColor(ContextCompat.getColor(((ListSubscriberAdapter.MyViewHolder) viewHolder).cardContainer.getContext(), R.color.quantum_white_100));
} else {
foregroundView = ((ListTurnPickedAdapter.MyViewHolder) viewHolder).cardContainer;
foregroundView.setBackgroundColor(ContextCompat.getColor(((ListTurnPickedAdapter.MyViewHolder) viewHolder).cardContainer.getContext(), R.color.quantum_white_100));
}
getDefaultUIUtil().clearView(foregroundView);
}
@Override
public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
return false;
}
@Override
public void onSelectedChanged(@Nullable RecyclerView.ViewHolder viewHolder, int actionState) {
super.onSelectedChanged(viewHolder, actionState);
}
@Override
public int convertToAbsoluteDirection(int flags, int layoutDirection) {
return super.convertToAbsoluteDirection(flags, layoutDirection);
}
}
|
Python
|
UTF-8
| 674
| 3.765625
| 4
|
[] |
no_license
|
"""For Want of a Nail."""
import itertools
def proverb(words, qualifier=None):
"""Return "For Want of a Nail"."""
phrases = (
"For want of a {} the {} was lost.".format(want, lost)
for want, lost in pairwise(words)
)
qualifier = "" if qualifier is None else qualifier + " "
phrases = itertools.chain(
phrases,
["And all for the want of a {}{}.".format(qualifier, words[0])])
return "\n".join(phrases)
def pairwise(iterable):
"""s -> (s[0], s[1]), (s[1], s[2]), (s[2], s[3]), ..."""
iterable1, iterable2 = itertools.tee(iterable)
next(iterable2, None)
return itertools.izip(iterable1, iterable2)
|
Java
|
UTF-8
| 286
| 1.742188
| 2
|
[] |
no_license
|
package com.blackfat.springboot.druid.dao;
import com.blackfat.springboot.druid.entity.Stock;
/**
* @author wangfeiyang
* @desc
* @create 2018/10/23-14:37
*/
public interface StockMapper {
Stock selectByPrimaryKey(Integer id);
int updateByOptimistic(Stock stock);
}
|
Markdown
|
UTF-8
| 6,551
| 2.96875
| 3
|
[
"Unlicense"
] |
permissive
|
# DLE Registration Code Generator
This program can generate registration codes for the Deluxe LORD Editor
(DLE), a 16-bit DOS program I wrote in 1995.
Since the source was lost, I have taken it upon myself to hack the
registration key algorithm and now provide keys freely to all those who
wish to have them.
Create keys for yourself at https://mikeeheler.github.io/dle-keygen/.
Read on for information about the program and the process of hacking it.
## About DLE
The Deluxe LORD Editor is a tool useful for SysOps running LORD
(Legend of the Red Dragon) on their BBS'. It's an editor and management
tool all-in-one, with several modules:
* Player data editor
* Monster data editor
* Menu/graphics ANSI editor
* Mailer
With these tools you can punish and reward your players, either by
editing their stats directly, or sending them specially-coded mail bombs
that granted them gold or whatever. The Player Editor includes an action
to "reset" a player so it was as if a day had passed and they could play
another set of turns. Very handy for a SysOp.
You could also use these to mod the game. While the core game loop could
not change, by changing the monster names and menus/screens/graphics, it
could certainly set the game in a different era or genre, or simply give
it a new flavour.
This repository is at once code, archive, blog post, and online key
generator.
## History
I was still in high school when I wrote this thing and very much wanted
someone to pay me for a program that I wrote, so I disabled certain
features unless the program was unlocked with a code.
Give me $5 and I'll send you a code. I made a grand total of about $15
from that scheme.
25 years later, the SysOp of Danger Bay BBS, who goes by Night Rider,
reached out to me to ask if I was still able to generate codes for the
program.
Yes, there is still very much a BBS scene out there in 2020, and I could
not be happier to have learned about it.
The source to DLE is long lost, but I saw a puzzle ready to be solved;
I would hack the damn thing myself.
So that's what I've done. I grabbed a debug build of DOSbox, loaded DLE
into the debugger and began stepping through, one instruction at a time.
I mapped out code segments, function calls, memory regions. I found the
region of memory where the text "Unregistered" was stored, and from
there, the code to print it, the check for whether you were registered,
and, ultimately, the registration code validation. It was glorious.
## "Encryption"
My 16-year-old self thought he was pretty clever to come up with this.
(Narrator: He wasn't.) I remember challenging a friend who said he knew
a guy that could hack anything to ask that guy to hack it.
They never took me up on it. I think they were scared. Clearly.
The registration codes are strings of hex characters that basically
map to the SysOp and BBS Name fields one-to-one. For each character
in the SysOp name, there's 2 characters in the Reg 1 code, and thusly
for BBS Name / Reg 2 as well.
The algorithm to generate a code goes like this:
* Seed the random number generator with the static value 0x1935
(6,453 decimal).
Then, for each character in the SysOp or BBS Name field:
* Pull a psuedo-random value less than 255 from the RNG.
* Add 1.
* XOR it with the input character.
* Convert that value to a 2-character hex string (i.e. 0xAA -> "AA").
That's it. Because it's effectively a XOR with some cruft around it,
decoding the code is basically the same process:
* Seed the random number generator with the static value 0x1935
(6,453 decimal).
Then for every two characters in the code:
* Convert the hex string to its numeric value (i.e. "AA" -> 0xAA).
* Pull a psuedo-random value less than 255 from the RNG.
* Add 1.
* XOR it with the number to make a byte.
* Add that byte to a string.
Once that's done, compare the resulting string to either the SysOp name
(for Reg 1) or the BBS Name (for Reg 2). If both match, ta-da! Product
is registered and all the annoyware is disabled.
The key to this whole thing, really, is the random number generator.
See [RANDOM.ASM][random-asm-source]. I don't know what algorithm
it uses, but it seems to depend somewhat on how 16-bit x86 instructions
handle math on 32-bit numbers.
I couldn't be arsed to convert the RNG into Javascript so the online
generator uses a [lookup table][lookup-table] of pre-generated RNG
values from the [GENRNG][genrng-asm-source] tool.
## "Hacking Protection"
I needed to find a way to stop hackers, and I knew that hackers used
tools like memory scanners to look for booleans that might map to an
"is_registered" variable, so I threw a wrench into the works.
Instead, I set a variable to a magic value:
* The unregistered, or "false" state of this variable is 0xE7CB.
* The registered, or "true" state of this variable is 0xE70D9.
I do not know the significance of these numbers, if any.
I was tempted to just edit the DLE.EXE binary to ensure the checksums
were always set to the _registered_ value, but as I thought about it, I
knew that I wanted to keep that exe intact. It was built on January
22nd, 1996 at 06:51:44 and there it has sat, unmodified. It didn't feel
right to change it now.
## Learnings
Going in I had only written or even debugged a minimal amount of
assembly, and everything I had written was usually just little snippets
inlined next to C or Pascal for executing a specific interrupt or
something like that.
That much was quite educational! I'd highly recommend anyone getting
into assembly to start at an earlier level of technology: code for a
16-bit 286 in real mode with 640kb of RAM.
It's one thing to step through existing code and make sense of it (with
the Intel x86 Architecture Guide in hand), and another thing entirely to
write code that executes. I'm still very much learning how to write NASM
code, and most of what I've written just looks like the machine code I
was stepping through. I'm now inspired to write some larger apps in pure
286-era assembly just to try my hand at it.
For kicks, I compiled the REGCODE program with 16-bit NASM for DOS
during development. It produced identical output using the 64-bit NASM
for Win32 but it just felt more correct to compile it in the same
context that the program would run in.
[lookup-table]: FILES/RNGTABLE.TXT
[random-asm-source]: SOURCE/COMMON/RANDOM.ASM
[genrng-asm-source]: SOURCE/GENRNG.ASM
|
Python
|
UTF-8
| 6,016
| 2.828125
| 3
|
[] |
no_license
|
class AuctionSystem(object):
def __init__(self):
self._users = []
self._items = []
def register_user(self, user_id, name):
self._users.append(User(user_id, name))
def post_item(self, item):
self._items.append(item)
for user in self._users:
if user.id == item.owner_id:
user.add_post(item.id)
return
def make_bid(self, user_id, item_id, price):
for item in self._items:
if item.id == item_id:
item.add_bid(user_id, price)
for user in self._users:
if user.id == user_id:
user.add_bid(item_id, price)
def get_items(self):
for item in self._items:
print(str(item))
def get_user(self, user_id):
for user in self._users:
if user.id == user_id:
return str(user)
def search_posts(self, user_id):
posts = []
for user in self._users:
if user.id == user_id:
posts = user.posts
for post in posts:
print(post)
def search_user_bids(self, user_id):
bids = []
for user in self._users:
if user.id == user_id:
bids = user.bids
for bid in bids:
print(bid)
def search_item_bids(self, item_id):
bids = []
for item in self._items:
if item.id == item_id:
bid = item.bid
print(bid)
class Item(object):
def __init__(self, item_id, name, description, user_id):
self._item_id = item_id
self._name = name
self._description = description
self._user_id = user_id
self._bid = Bid()
def add_bid(self, user_id, price):
self._bid.add_bid(user_id, price)
@property
def id(self):
return self._item_id
@property
def name(self):
return self._name
@property
def description(self):
return self._description
@property
def owner_id(self):
return self._user_id
@property
def bid(self):
return self._bid
def __str__(self):
string = "Item_Id: %s\nItem_Name: %s\nItem_Description: %s\nOwner_Id: %s\n"\
%(self._item_id, self._name, self._description, self._user_id)
string += str(self._bid)
return string
class Electronic(Item):
def __init__(self, item_id, name, description, user_id, voltage, brand):
Item.__init__(self, item_id, name, description, user_id)
self._voltage = voltage
self._brand = brand
def __str__(self):
string = Item.__str__(self)
string += "Voltage: %s\nBrand:%s\n"%(self._voltage, self._brand)
return string
class Furniture(Item):
def __init__(self, item_id, name, description, user_id, material, age):
Item.__init__(self, item_id, name, description, user_id)
self._age = age
self._material = material
def __str__(self):
string = Item.__str__(self)
string += "Material: %s\nAge:%s\n" % (self._material, self._age)
return string
class Book(Item):
def __init__(self, item_id, name, description, user_id, author, publish_year):
Item.__init__(self, item_id, name, description, user_id)
self._author = author
self._publish_year = publish_year
def __str__(self):
string = Item.__str__(self)
string += "Author: %s\nPublish_Year:%s\n" % (self._author, self._publish_year)
return string
class User(object):
def __init__(self, user_id, name):
self._user_id = user_id
self._name = name
self._posts = []
self._bids = []
def add_post(self, item_id):
self._posts.append(item_id)
def add_bid(self, item_id, price):
self._bids.append((item_id, price))
@property
def id(self):
return self._user_id
@property
def name(self):
return self._name
@property
def posts(self):
return self._posts
@property
def bids(self):
return self._bids
def __str__(self):
string = "User_Id: %s\nName: %s\nMy Posts:\n"%(self._user_id, self._name)
for post in self._posts:
string += (post + "\n")
string += "Bids Made:\n"
for bid in self._bids:
string += (bid[0] + " $" + str(bid[1]) + "\n")
return string
class Bid(object):
def __init__(self):
self._bids = []
def add_bid(self, user_id, price):
self._bids.append((user_id, price))
def __str__(self):
string = "All_Bids:\n"
for bid in self._bids:
string += (bid[0] + " $" + str(bid[1]) + "\n")
return string
system = AuctionSystem()
system.register_user("U001","Jack")
system.register_user("U002","Tom")
system.register_user("U003","Jason")
system.register_user("U004","David")
book = Book("I001","Agile Design","AnAgile Design Guide book", "U001", "Aarthi", "1996")
electronic = Electronic("I002","Iphone7","latest iphone", "U003","220V", "Apple")
furniture = Furniture("I003","Table","a nice table", "U003", "Wood", "5 years")
system.post_item(book)
system.post_item(electronic)
system.post_item(furniture)
system.make_bid("U002","I001", 800)
system.make_bid("U003","I001", 900)
system.make_bid("U003","I002", 200)
system.make_bid("U004","I002", 220)
system.make_bid("U001","I002", 250)
system.make_bid("U004","I002", 300)
system.make_bid("U001","I002", 350)
system.make_bid("U004","I001", 920)
system.make_bid("U004","I003", 40)
system.make_bid("U002","I003", 50)
system.make_bid("U001","I003", 60)
system.make_bid("U002","I003", 80)
system.get_users()
print("---------------------")
system.get_items()
|
Java
|
UTF-8
| 163
| 1.820313
| 2
|
[] |
no_license
|
package com.example.myapplication.db;
final class BaseDatosConstantes {
public static String BaseDatosName= "Petagram";
public static int Version=1;
}
|
Python
|
UTF-8
| 2,526
| 2.875
| 3
|
[] |
no_license
|
import influxdb as db
import talib
import zmq
from tradex.strategy.indicators import Indicator
# import time
class Strategy1:
"""This class implements the basic strategy
of SMA and MACD oscillators"""
timeframes = ['M1', 'M5', 'M15', 'H1', 'H4']
def __init__(self, other, timeframe=None):
self.market = other.database_name if other else 'EURUSD'
self.max_period = 100
# self.monitor = self.timeframes[1]
self.monitor = 'EURUSD'
self.client = db.DataFrameClient(
database=self.market)
self.init = self.client.query(
f"SELECT open,high,low,close from {self.market} \
LIMIT {self.max_period}"
).get(self.monitor).dropna()
self.ema = Indicator('ema', talib.EMA, timeperiod=20)
self.ema.update(self.init)
self.ema3 = Indicator('ema3', talib.EMA, timeperiod=50)
self.ema3.update(self.init)
self.ema4 = Indicator('ema4', talib.EMA, timeperiod=100)
self.ema4.update(self.init)
def loop_fill(self, frame):
for ind in [self.ema, self.ema3, self.ema4]:
ind.update(frame)
def loop_subscribe(self):
self.ctx = zmq.Context()
self.sub = self.ctx.socket(zmq.SUB)
self.sub.connect("tcp://localhost:45600")
self.sub.subscribe(self.market)
while True:
try:
m = self.sub.recv()
if m != b'':
if m == b'EURUSD kill':
self.kill_sockets()
break
if m == b'EURUSD':
self.init = self.client.query(
f"select open,high,low,close from\
{self.market} LIMIT \
{self.max_period}").get(
self.monitor).dropna()
self.loop_fill(self.init)
self.algo(self.init)
except zmq.error.Again:
pass
except KeyboardInterrupt:
self.kill_sockets()
break
except Exception:
self.kill_sockets()
raise Exception
def kill_sockets(self):
self.sub.close()
self.ctx.term()
def algo(self, frame):
# arr = frame
if self.ema.v1[-1] > self.ema3.v1[-1] > self.ema4.v1[-1]:
print("yay...place trade now....")
else:
print("No trade mehn....")
|
Java
|
UTF-8
| 688
| 2.578125
| 3
|
[] |
no_license
|
package com.ioc;
import org.jetbrains.annotations.Nullable;
import javax.lang.model.element.Element;
/**
* Created by sergeygolishnikov on 08/08/2017.
*/
public class ProcessorException extends RuntimeException {
@Nullable
public Element element;
public ProcessorException(String message, Object... args) {
super(String.format(message, args));
}
public ProcessorException setElement(@Nullable Element element) {
this.element = element;
return this;
}
@Override
public String toString() {
return "ProcessorException{" +
"element=" + (element != null ? element : "null") +
'}';
}
}
|
Java
|
UTF-8
| 2,050
| 2.75
| 3
|
[] |
no_license
|
package queries;
import datos.Profesor;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Daniel
*/
public class QueriePractica extends Querie{
private PreparedStatement insertNewPractica;
public QueriePractica(){
try{
Class.forName(dbclassname);
}catch(Exception e){}
try {
//Conectamos
connection =
DriverManager.getConnection(URL, USERNAME, PASSWORD);
// crea un query que inserta datos a la base de datos
insertNewPractica = connection.prepareStatement(
"INSERT INTO Practica " +
"(numeroPractica, nombrePractica, unidadPractica, fechaProgramada,"
+ " fechaR, clave_grupo)" +
"VALUES (?, ?, ?, ?, ?, ?)");
}
catch (SQLException sqlException){
sqlException.printStackTrace();
System.exit(1);
}
}//Fin del consstructor
public int añadirPractica(int numeroPractica,String nombrePractica, int unidadPractica,
String fechaProgramada, String fechaR, int clave_grupo){
int result = 0;
// set parameters, then execute insertNewPerson
try {
insertNewPractica.setInt(1, numeroPractica);
insertNewPractica.setString(2, nombrePractica);
insertNewPractica.setInt(3, unidadPractica);
insertNewPractica.setString(4, fechaProgramada);
insertNewPractica.setString(5, fechaR);
insertNewPractica.setInt(6, clave_grupo);
// insert the new entry; returns # of rows updated
result = insertNewPractica.executeUpdate();
}catch (SQLException sqlException){
sqlException.printStackTrace();
close();
}
return result;
}//Fin del método anñadirMaestro
}
|
Shell
|
UTF-8
| 183
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
#!/bin/bash
DIR="$(cd "$(dirname "$0")" && pwd)"
PARENTDIR="$(dirname "$DIR")"
export GOOS=darwin
export GOARCH=amd64
go build -o ${DIR}/dirk_${GOOS}_${GOARCH} ${PARENTDIR}/main.go
|
Markdown
|
UTF-8
| 1,389
| 3.296875
| 3
|
[
"MIT"
] |
permissive
|
---
title: UIColor.xyz - Converting HEX & RGB colours to UIColor
slug: ui-color-convert-hex-rgb
keywords: uicolor,programming,ios,objective-c,swift,convert,hex,rgb,xcode
cover: ui-color.png
date: 2015-02-15
---
Have you ever developed an iOS mobile application in Objective C or in Swift? Then I guess at some point you have "googled" convert HEX or RGB colors to UIColor or UIColor picker. Same happened with me. So while I was developing "Go Back" - an application written in Swift where you can store your location and find your way back there at any time - I had to use a color converter or a color picker for UI Color.
<!--more-->
UIcolor.xyz is a tiny Angular app, where you can either convert HEX & RGB(A) colors or you can use the color picker and it will generate the code you need to copy & paste to your iOS application.
# It's obvious that it's not that easy to convert colors without a converter
HEX: #bd3e3e
RGB: R-189 G-62 B-62
Objective C: [UIColor colorWithRed:0.74 green:0.24 blue:0.24 alpha:1.0];
Swift: UIColor(red:0.74, green:0.24, blue:0.24, alpha:1.0)
I guess after the example above it will all make sense right? The application is hosted on **GitHub Pages** and it is of course open-sourced so feel free to get involved! It's free and easy to use. You can now head to [http://www.uicolor.xyz/](http://www.uicolor.xyz/) and give it a try.
|
Swift
|
UTF-8
| 1,008
| 3.203125
| 3
|
[
"MIT"
] |
permissive
|
import VectorMath
import RaytracerLib
public struct InfinitePlane: Surface {
let anchor: Vector4
let normal: Vector4
let material: Material
public init(anchor: Vector4, normal: Vector4, material: Material) {
self.anchor = anchor
self.normal = normal.normalized()
self.material = material
}
public func intersectsRay(_ ray: Ray, min: Scalar, max: Scalar) -> Intersection? {
if ray.direction.dot(normal) ~= 0 {
return Intersection(
point: ray.point,
normal: normal,
material: material,
ray: ray,
time: ray.time
)
} else {
let t = (anchor - ray.point).dot(normal) / ray.direction.dot(normal)
if t >= min && t <= max {
return Intersection(
point: ray.point + ray.direction*t,
normal: normal * (ray.direction.dot(normal) > 0 ? -1 : 1),
material: material,
ray: ray,
time: ray.time
)
} else {
return nil
}
}
}
}
|
Java
|
UTF-8
| 1,391
| 2.09375
| 2
|
[] |
no_license
|
package aiyiqi.bwf.com.yiqizhuangxiu.fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import aiyiqi.bwf.com.yiqizhuangxiu.R;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by Yishi on 2016/11/28.
*/
public class ZiZhuXiaDan_Inner_Fragment extends BaseFragment {
private String text;
@BindView(R.id.activity_zzxd_inner_viewpager_text)
TextView activityZzxdInnerViewpagerText;
public ZiZhuXiaDan_Inner_Fragment() {
}
public ZiZhuXiaDan_Inner_Fragment(String text) {
this.text = text;
}
@Override
protected int getContentViewResID() {
return R.layout.activity_zzxd_inner_viewpager_item;
}
@Override
protected void initViews() {
if (text.equals("0")){
activityZzxdInnerViewpagerText.setText("");
}else{
activityZzxdInnerViewpagerText.setText(text);
}
}
@Override
protected void initDatas() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// TODO: inflate a fragment view
View rootView = super.onCreateView(inflater, container, savedInstanceState);
ButterKnife.bind(this, rootView);
return rootView;
}
}
|
Java
|
UTF-8
| 2,756
| 2.140625
| 2
|
[] |
no_license
|
package me.fdawei.picker.loader;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import me.fdawei.picker.R;
import me.fdawei.picker.entity.PhotoDir;
import static android.provider.BaseColumns._ID;
import static android.provider.MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME;
import static android.provider.MediaStore.Images.ImageColumns.BUCKET_ID;
import static android.provider.MediaStore.MediaColumns.DATA;
import static android.provider.MediaStore.MediaColumns.SIZE;
/**
* Created by david on 2018/2/18.
*/
public class PhotoDirLoaderCallbacks implements LoaderManager.LoaderCallbacks<Cursor> {
private Context context;
private OnPhotoDirResultListener photoDirResultListener;
public PhotoDirLoaderCallbacks(Context context, OnPhotoDirResultListener listener) {
this.context = context;
this.photoDirResultListener = listener;
}
@Override public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new PhotoDirLoader(context, false);
}
@Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (data == null) {
return;
}
Map<String, PhotoDir> photoDirMap = new HashMap<>();
PhotoDir photoDirAll = new PhotoDir();
photoDirAll.setName(context.getString(R.string.all_photo));
photoDirAll.setId("ALL");
while (data.moveToNext()) {
int imageId = data.getInt(data.getColumnIndexOrThrow(_ID));
String bucketId = data.getString(data.getColumnIndexOrThrow(BUCKET_ID));
String bucketName = data.getString(data.getColumnIndexOrThrow(BUCKET_DISPLAY_NAME));
String path = data.getString(data.getColumnIndexOrThrow(DATA));
long size = data.getInt(data.getColumnIndexOrThrow(SIZE));
if (size < 1) {
continue;
}
PhotoDir photoDir = photoDirMap.get(bucketId);
if(photoDir == null) {
photoDir = new PhotoDir();
photoDir.setId(bucketId);
photoDir.setName(bucketName);
photoDirMap.put(bucketId, photoDir);
}
photoDir.addPhoto(imageId, path,size);
photoDirAll.addPhoto(imageId, path, size);
}
List<PhotoDir> photoDirList = new ArrayList<>();
photoDirList.add(photoDirAll);
photoDirList.addAll(photoDirMap.values());
if(photoDirResultListener != null) {
photoDirResultListener.onPhotoDirResult(photoDirList);
}
}
@Override public void onLoaderReset(Loader<Cursor> loader) {
}
public interface OnPhotoDirResultListener {
void onPhotoDirResult(List<PhotoDir> photoDirList);
}
}
|
C++
|
UHC
| 2,388
| 3.421875
| 3
|
[] |
no_license
|
// https://www.acmicpc.net/problem/10451
// BFS or DFS
/*
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <string.h>
#define MAX 1001
using namespace std;
int map[MAX][MAX];
int visited[MAX];
queue<int> q;
int T, N, M, answer = 0;
void bfs(int root) {
visited[root] = 1;
q.push(root); // 1-1. ť ߰
// 3. ť Ѵ.
while (!q.empty()) {
int r = q.front();
q.pop(); // ť տ
// 2-2. ť ʷ 湮Ѵ.
for (int i = 1; i <= N; i++) {
if (map[r][i] == 1 && !visited[i]) {
visited[i] = 1; // (湮 üũ)
q.push(i); // 2-3. ť ߰
break;
}
}
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> T;
for (int t = 0; t < T; t++) {
cin >> N;
for (int n = 0; n < N; n++) {
int v;
cin >> v;
map[n + 1][v] = 1;
}
bool exist = true;
int root = 1;
while (exist) {
bfs(root);
answer++;
exist = false;
for (int i = 1; i <= N; i++) {
if (!visited[i]) { //湮 尡 ִٸ
root = i;
exist = true;
break;
}
}
}
cout << answer << "\n";
// 0 ʱȭ
answer = 0;
memset(map, 0, sizeof(map));
memset(visited, 0, sizeof(visited));
}
return 0;
}
*/
#include <iostream>
#include <string>
#include <vector>
#include <string.h>
#define MAX 1001
using namespace std;
vector<int> map[MAX];
int visited[MAX];
int T, N, M, answer = 0;
void dfs(int root) {
if (visited[root]) return;
// 1. root 湮
visited[root]=1; // 1-1. 湮 带 ǥ
// 2. root 湮
for (int i = 0; i < map[root].size(); i++) {
int next = map[root][i];
dfs(next);
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> T;
for (int t = 0; t < T; t++) {
cin >> N;
for (int n = 0; n < N; n++) {
int v;
cin >> v;
map[n + 1][v] = 1;
}
for (int i = 1; i <= N; i++) {
if (!visited[i]) { //湮 尡 ִٸ
dfs(i);
answer++;
}
}
cout << answer << "\n";
// 0 ʱȭ
answer = 0;
memset(map, 0, sizeof(map));
memset(visited, 0, sizeof(visited));
}
return 0;
}
|
Java
|
UTF-8
| 1,010
| 2.015625
| 2
|
[] |
no_license
|
package com.ateamforce.coffeenow.service.impl;
import com.ateamforce.coffeenow.model.StorePaymenttype;
import com.ateamforce.coffeenow.model.repository.StorePaymentTypeRepository;
import com.ateamforce.coffeenow.service.StorePaymentTypeService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
*
* @author Sakel
*/
@Service
public class StorePaymentTypeServiceImpl implements StorePaymentTypeService {
@Autowired
StorePaymentTypeRepository storePaymentTypeRepository;
@Override
public List<StorePaymenttype> findAllByStoreId(int storeid) {
return storePaymentTypeRepository.findByStoreid(storeid);
}
@Override
public void deleteAllByStoreId(int storeId) {
storePaymentTypeRepository.deleteAllByStoreId(storeId);
}
@Override
public void addOne(int storeId, int paymentTypeId) {
storePaymentTypeRepository.addOne(storeId, paymentTypeId);
}
}
|
Shell
|
UTF-8
| 785
| 3.65625
| 4
|
[
"Apache-2.0"
] |
permissive
|
#!/bin/bash
set -e
# Run MongoDB backup
python $WORKSPACE/utils/test/testapi/update/templates/backup_mongodb.py -o $WORKSPACE/
# Compressing the dump
now=$(date +"%m_%d_%Y_%H_%M_%S")
echo $now
file_name="testapi_mongodb_"$now".tar.gz"
echo $file_name
tar cvfz "$file_name" test_results_collection*
rm -rf test_results_collection*
artifact_dir="testapibackup"
workspace="$WORKSPACE"
set +e
/usr/local/bin/gsutil &>/dev/null
if [ $? != 0 ]; then
echo "Not possible to push results to artifact: gsutil not installed"
exit 1
else
echo "Uploading mongodump to artifact $artifact_dir"
/usr/local/bin/gsutil cp -r "$workspace"/"$file_name" gs://artifacts.opnfv.org/"$artifact_dir"/
echo "MongoDump can be found at http://artifacts.opnfv.org/$artifact_dir.html"
fi
|
Python
|
UTF-8
| 1,237
| 3.859375
| 4
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env python
# -*- coding_ utf-8 -*-
## we want to apply a discrete integral
"""
Based on the Trapezoid method to integrate defined functions:
https://www.geeksforgeeks.org/trapezoidal-rule-for-approximate-value-of-definite-integral/
"""
# area down this function
def main_function(x):
#f_de_x = (1.0 / (1.0 + x * x))
f_de_x = (9.0 * x) - 6
return f_de_x
# sumation in the second component of the trapezoid method
def sumation(n, a, h):
result = 0.0
i = 1
while i <= n-1:
#print("i: {}".format(i))
result += main_function(a + (i * h))
#print(result)
i += 1
#print(result)
return result
# main logic to integrate all the function over a and b in n slices
def integral_trapezoide(a, b, n):
# grid spacing
h = (b - a) /float(n)
#print("h: {}".format(h))
# calculating the integral
first_component = (b - a) / (2 * float(n))
f_de_a = main_function(a)
f_de_b = main_function(b)
intermediate_component = 2* sumation(n, a, h)
result = first_component*(f_de_a + intermediate_component + f_de_b)
return result
if __name__ == "__main__":
n = 6
a = 1
b = 3
r = integral_trapezoide(a,b,n)
print(r)
|
Markdown
|
UTF-8
| 2,673
| 3.625
| 4
|
[] |
no_license
|
# 享元模式
享元模式的定义与特点
----------
享元(Flyweight)模式的定义:运用共享技术来有效地支持大量细粒度对象的复用。它通过共享已经存在的对象来大幅度减少需要创建的对象数量、避免大量相似类的开销,从而提高系统资源的利用率。
享元模式的主要优点是:相同对象只要保存一份,这降低了系统中对象的数量,从而降低了系统中细粒度对象给内存带来的压力。
其主要缺点是:
1. 为了使对象可以共享,需要将一些不能共享的状态外部化,这将增加程序的复杂性。
2. 读取享元模式的外部状态会使得运行时间稍微变长。
享元模式的结构与实现
----------
享元模式中存在以下两种状态:
1. 内部状态,即不会随着环境的改变而改变的可共享部分;
2. 外部状态,指随环境改变而改变的不可以共享的部分。享元模式的实现要领就是区分应用中的这两种状态,并将外部状态外部化。下面来分析其基本结构和实现方法。
#### 1\. 模式的结构
享元模式的主要角色有如下。
1. 抽象享元角色(Flyweight):是所有的具体享元类的基类,为具体享元规范需要实现的公共接口,非享元的外部状态以参数的形式通过方法传入。
2. 具体享元(Concrete Flyweight)角色:实现抽象享元角色中所规定的接口。
3. 非享元(Unsharable Flyweight)角色:是不可以共享的外部状态,它以参数的形式注入具体享元的相关方法中。
4. 享元工厂(Flyweight Factory)角色:负责创建和管理享元角色。当客户对象请求一个享元对象时,享元工厂检査系统中是否存在符合要求的享元对象,如果存在则提供给客户;如果不存在的话,则创建一个新的享元对象。
图 1 是享元模式的结构图。图中的 UnsharedConcreteFlyweight 是非享元角色,里面包含了非共享的外部状态信息 info;而 Flyweight 是抽象享元角色,里面包含了享元方法 operation(UnsharedConcreteFlyweight state),非享元的外部状态以参数的形式通过该方法传入;ConcreteFlyweight 是具体享元角色,包含了关键字 key,它实现了抽象享元接口;FlyweightFactory 是享元工厂角色,它逝关键字 key 来管理具体享元;客户角色通过享元工厂获取具体享元,并访问具体享元的相关方法。

图1 享元模式的结构图
#### 2\. 模式的实现
享元模式的实现代码如flyweight.go所示。
|
Markdown
|
UTF-8
| 4,575
| 3.203125
| 3
|
[] |
no_license
|
# PG - Protobuf Generate
一个从protobuf定义文件自动生产代码的脚本
## 约定
* 目前默认消息ID为 Int16, 也就是2Bytes
## protobuf定义文件要求
在这里假设你的 定义文件 a.proto, b.proto 等等都位于 目录A中
* 定义文件中不要加 package, 生成的csharp会自动添加namespace
* 确保message, enum 的名字全局唯一
* message 的名字 建议是首字母大写的驼峰命名法。比如 `message PlayerAction {...}`
* 目录A中需要有 `pg` 用的配置文件 `pg.conf`, 格式参考 此repo中的 pg.conf
* 目录A中需要有 `pg` 用的给消息ID定义文件 `define.ini`.
格式为:
```
[define]
MessageOne = 1
MessageTwo = 2
```
表示每个消息所对应的消息ID
* 生成的文件位于 out/ 目录下的 各自语言的目录中。
将其拷贝到你项目中即可。
### Csharp with Mono
生成的文件:
```
out/csharp
|----ProtocolDefine.dll
|----ProtocolSerializer.dll
|----protobuf-net.dll
|----Protocol
|----Handler.cs
|
|----Implement
|----MessageOne.cs
|----MessageTwo.cs
...
```
* 在Mono环境下 用 [protobuf-net][1] 来生成对应的csharp文件,并且将其编译为一个`ProtocolDefine.dll`文件。
```
namespace: Protocol.Define
class name: 就是定义中的各种 message 的名字
```
* 用预编译 `precompile` 来避免在IOS设备上的AOT问题。产生的文件为 `ProtocolSerializer.dll`
```
namespace: Protocol
class name: Serializer
```
**NOTE: 你并不会直接使用这个类,见下面的 `ProtocolHandler` 类提供的 `Pack/Process` 方法**
* 脚本自己也生成了一个 `Protocol` 目录。里面的 `Protocol.ProtocolHandler` 类提供了非常方便的方法来 打包/解包 数据。
* `Implement`目录中的各种 `MessageName.cs` 文件, 其中的 `Process`方法 就是你要写代码的地方,该如何处理数据
#### 使用方法
比如有个 proto 文件定义如下:
```
message MyMessage {
required int32 id = 1;
required string name = 2;
}
```
然后在这个proto文件的目录中 创建 `pg.conf` 和 `define.ini`
`pg.conf` 可参考此 repo 中的 自己修改
`define.ini` 内容如下: 表示 MyMessage 这个消息的ID是10
```
[define]
MyMessage = 10
```
最后使用 命令 `pg /PATH/*.proto` 生成文件,会得到上述文件,将其拷贝至自己的项目中即可。
在自己的项目中使用
**序列化**
```csharp
// 首先实例化一个消息
var msg = new Protocol.Define.MyMessage();
// 填充数据
msg.id = 1;
msg.name = "Alex";
// 把消息ID和消息一起序列化.
var data = Protocol.ProtocolHandler.PackWithId(msg);
// 完毕。 buffer 类型是 byte[]。 你可以将其通过socket发送出去
```
**反序列化**
```csharp
Protocol.ProtocolHandler.Process(data);
// data 是待处理数据, 类型是 byte[].
```
你要自己去实现生成的 `Protocol/Implement/MyMessage.cs` 文件中的 `Process` 方法
```csharp
namespace Protocol.Implement
{
public static class MyMessage
{
public static void Process(Protocol.Define.MyMessage msg)
{
// Logic here
Console.WriteLine("id = {0}, name = {1}", msg.id, msg.name)
}
}
}
```
就是这么简单!!!
socket数据收发可以 看 我的这个项目 [YLib][2]
### Erlang
生成的文件
```
out/erlang
|---- gpb.hrl
|---- protocol.hrl
|---- protocol.erl
|---- protocol_handler.erl
|---- protocol_implement.erl
```
将其拷贝到你的项目中
#### 使用方法
首先还是和上面一样,用 `pg` 生成代码
如果你的`pg.conf` 中 没有设置 `msg_prefix` 和 `msg_suffix`, 那么 `MyMessage` 回生成一个 `#'MyMessage'{id, name}` 的 record
在代码中需要 `-include("protocol.hrl")`,
**序列化**
```erlang
Msg = #'MyMessage'{id = 1, name = <<"Tom">>},
Data = protocol_handler:pack_with_id(Msg),
%% 完毕,直接用gen_tcp:send() 将Data发送出去
```
**反序列化**
```erlang
NewState = protocol_handler:process(Data, State),
%% 完毕, 因为pg生成的代码是嵌入基于OTP设计的项目中使用的。所以这里有 State 这个参数
%% 具体处理逻辑需要到 protocol_implement.erl 中去实现。
```
[1]: https://code.google.com/p/protobuf-net/
[2]: https://github.com/yueyoum/YLib
|
C#
|
UTF-8
| 1,018
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
using Semver.Ranges;
namespace Semver.Test.TestCases
{
public class NpmRangeParsingTestCase
{
public static NpmRangeParsingTestCase Valid(
string range,
bool includeAllPrerelease,
SemVersionRange expected)
=> new NpmRangeParsingTestCase(range, includeAllPrerelease, expected);
private NpmRangeParsingTestCase(
string range,
bool includeAllPrerelease,
SemVersionRange expected)
{
Range = range;
IncludeAllPrerelease = includeAllPrerelease;
ExpectedRange = expected;
}
public string Range { get; }
public bool IncludeAllPrerelease { get; }
public bool IsValid { get; }
#region Valid Values
public SemVersionRange ExpectedRange { get; }
#endregion
public override string ToString()
=> !IncludeAllPrerelease ? $"'{Range}'" : $"'{Range}' true";
}
}
|
Java
|
UTF-8
| 340
| 1.820313
| 2
|
[] |
no_license
|
package com.hayagou.dao;
import com.hayagou.domain.UserVO;
public interface UserDAO {
public void signUp(UserVO vo);
public UserVO login(UserVO vo);
public void userUpdate(UserVO vo)throws Exception;
public void userDelete(UserVO vo)throws Exception;
// 패스워드 체크
public int passChk(UserVO vo) throws Exception;
}
|
Java
|
UTF-8
| 1,439
| 2.421875
| 2
|
[
"MIT"
] |
permissive
|
package mage.cards.v;
import mage.MageInt;
import mage.abilities.common.SimpleStaticAbility;
import mage.abilities.dynamicvalue.common.CreaturesYouControlCount;
import mage.abilities.effects.common.continuous.SetBasePowerToughnessSourceEffect;
import mage.abilities.keyword.FlyingAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.Zone;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class VertexPaladin extends CardImpl {
public VertexPaladin(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "");
this.subtype.add(SubType.ANGEL);
this.subtype.add(SubType.KNIGHT);
this.power = new MageInt(0);
this.toughness = new MageInt(0);
this.color.setWhite(true);
this.color.setBlue(true);
this.nightCard = true;
// Flying
this.addAbility(FlyingAbility.getInstance());
// Vertex Paladin's power and toughness are each equal to the number of creatures you control.
this.addAbility(new SimpleStaticAbility(Zone.ALL, new SetBasePowerToughnessSourceEffect(CreaturesYouControlCount.instance)));
}
private VertexPaladin(final VertexPaladin card) {
super(card);
}
@Override
public VertexPaladin copy() {
return new VertexPaladin(this);
}
}
|
Java
|
UTF-8
| 2,610
| 2.5
| 2
|
[] |
no_license
|
package com.besttravelproject.command;
import com.besttravelproject.command.flightCommands.*;
import com.besttravelproject.command.orderCommands.*;
import com.besttravelproject.command.userCommands.*;
import javax.servlet.http.*;
import java.util.*;
/**
* Created by А on 08.01.15.
*/
public class CommandFactory {
private static Map<String, Command> commands = new HashMap<String, Command>();
static{
commands.put("error", new ErrorCommand());
commands.put("authorization", new AuthCommand());
commands.put("logout", new LogoutCommand());
commands.put("language", new LangCommand());
commands.put("show_flights", new ShowFlightsCommand());
commands.put("find_flight", new FindFlightCommand());
commands.put("edit_flight", new EditFlightCommand());
commands.put("show_clients", new ShowClientsCommand());
commands.put("blacklist", new BlacklistCommand());
commands.put("change_cart", new CartCommand());
commands.put("make_order", new AddOrderCommand());
commands.put("show_orders", new ShowOrdersCommand());
commands.put("approve_order", new ApproveOrderCommand());
}
public static Command createCommand(HttpServletRequest request){
String command = request.getParameter("command");
if (command != null) {
switch (command) {
case "login":
return commands.get("authorization");
case "logout":
return commands.get("logout");
case "language":
return commands.get("language");
case "show_flights":
return commands.get("show_flights");
case "find_flight":
return commands.get("find_flight");
case "edit_flight":
return commands.get("edit_flight");
case "show_clients":
return commands.get("show_clients");
case "blacklist":
return commands.get("blacklist");
case "change_cart":
return commands.get("change_cart");
case "make_order":
return commands.get("make_order");
case "show_orders":
return commands.get("show_orders");
case "approve_order":
return commands.get("approve_order");
default:
return commands.get("error");
}
}
return commands.get("bad");
}
}
|
Python
|
UTF-8
| 215
| 2.78125
| 3
|
[] |
no_license
|
# load the url content
# https://stackoverflow.com/questions/17178483/how-do-you-send-an-http-get-web-request-in-python
from urllib.request import urlopen
html = urlopen("http://www.google.com/").read()
print(html)
|
PHP
|
UTF-8
| 554
| 2.671875
| 3
|
[] |
no_license
|
<?php
use Illuminate\Database\Seeder;
class CourseExerciseTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$course_ids = App\Course::all('id')->pluck('id')->toArray();
$exercise_ids = App\Exercise::all('id')->pluck('id')->toArray();
$data = [];
foreach ($course_ids as $i => $id) {
$data[] = ['exercise_id' => $exercise_ids[$i], 'course_id' => $id];
}
DB::table('course_exercise')->insert($data);
}
}
|
C++
|
UTF-8
| 6,299
| 3.3125
| 3
|
[] |
no_license
|
//Bowling game calculator
//Uses either string input or file input
//Created by Claycot, 2017-2018
#include <iostream> //User input
#include <stdio.h> //This was quicker than <iomanip> for outputting score
#include <string> //Used for manipulating string input, as a result of notation
#include <fstream> //Used for reading from files
#include <deque> //Used for scoring each frame
using namespace std;
enum Ball {
BALL_SPARE = -1,
BALL_MISS,
BALL_ONE,
BALL_TWO,
BALL_THREE,
BALL_FOUR,
BALL_FIVE,
BALL_SIX,
BALL_SEVEN,
BALL_EIGHT,
BALL_NINE,
BALL_STRIKE
};
string processInput(string rawInput, int ballsInFrame[]);
int scoreFrame(Ball gameBalls[], int strikeShift, int index);
Ball charToBall(char inputChar);
void printScore(int scoreFrames[], int totScore);
int main (int argc, char* argv[]) {
//Greet user once on program run
cout << "Enter the bowling line of the player.\n"
<< "Add a space between each frame.\n"
<< "Strikes are denoted by X and spares by /\n";
//Test cases
string testCase1 = "8- 7- 53 9/ 9/ X 8- 51 3/ 9-"; // = 122
string testCase2 = "8/ 9- 44 72 9- X X 8- 35 9/7"; // = 133
string testPerfect = "X X X X X X X X X XXX"; // = 300
string userInput = "q";
deque<string> fileInput = {};
if (argc == 2) {
//Get bowling strings from file
ifstream inputFile;
string fileName = argv[1];
inputFile.open(fileName);
string tempLine = "";
while (!inputFile.eof()) {
inputFile >> ws;
getline(inputFile, tempLine);
fileInput.push_back(tempLine);
}
inputFile.close();
}
do {
int score = 0;
int frameScore[10] = {};
int ballsInFrame[10] = {};
int indexFrame[10] = {};
Ball gameBalls[21] = {};
if (fileInput.empty()) {
//Get bowling line from the user
cout << "Enter the bowling line, or 'q' to quit.\n";
userInput = "q";
cin >> ws;
getline(cin, userInput);
}
else {
//Get bowling line from filled deque
userInput = fileInput.front();
fileInput.pop_front();
}
if (userInput != "q" && userInput != "Q"){
//Get a good input
string goodInput = processInput(userInput, ballsInFrame);
//Index frames (eg. Frame X starts at Ball Y)
int numBalls = 0;
for (int index = 0; index < 10 ; index++){
indexFrame[index] = numBalls;
numBalls += ballsInFrame[index];
}
//Turn the input string into an array of Balls
for (int index = 0; index < goodInput.length(); index++) {
gameBalls[index] = charToBall(goodInput[index]);
}
//Calculate the bowling score
for (int index = 0; index < 10; index++) {
frameScore[index] = scoreFrame(gameBalls, indexFrame[index], index);
score += frameScore[index];
}
//If a valid score was calculated, output that score
if (score > -1) {
printScore(frameScore, score);
}
}
} while (userInput != "q" && userInput != "Q");
return 0;
}
//Process the input to remove any rough edges
string processInput(string rawInput, int ballsInFrame[]) {
string matchString = "/-123456789Xx";
string newInput;
bool charMatched = false;
int prevFrameIndex = 0;
int frameNum = 0;
//Loop through each character in the input
for (int index = 0; index < rawInput.length(); index++) {
charMatched = false;
//If the character isn't a space, go forth
if (rawInput[index] != ' ') {
//Loop through acceptable characters to check validity of input
for (int strIndex = 0; strIndex < matchString.length() + 1; strIndex++) {
//If the character matches, add it to new string
if (rawInput[index] == matchString[strIndex]) {
newInput += rawInput[index];
charMatched = true;
}
}
//If the character doesn't match, output an error message
if (!charMatched) {
cout << "Bad character found... " << rawInput[index] << "\n";
newInput += '0';
}
}
//If the character was a space, the frame ended
else {
ballsInFrame[frameNum] = index - prevFrameIndex;
frameNum++;
prevFrameIndex = index + 1;
}
}
ballsInFrame[9] = rawInput.length() - prevFrameIndex;
//Make sure a good number of frames was entered
if (frameNum != 9) {
cout << "Bad number of frames entered! Use a space between frames.\n";
newInput = "---------------------";
}
return newInput;
}
//Return the score from each individual frame
int scoreFrame(Ball gameBalls[], int strikeShift, int index) {
int score = 0;
Ball ballOne = gameBalls[strikeShift];
Ball ballTwo = gameBalls[strikeShift + 1];
//Logic to score
if (ballOne != BALL_STRIKE) {
if (ballTwo != BALL_SPARE) {
score += static_cast<int>(ballOne);
score += static_cast<int>(ballTwo);
}
else if (ballTwo == BALL_SPARE) {
Ball ballThree = gameBalls[strikeShift + 2];
score += (10 + ballThree);
}
}
else if (ballOne == BALL_STRIKE) {
Ball ballThree = gameBalls[strikeShift + 2];
if (ballThree == BALL_SPARE) {
ballThree = static_cast<Ball>(10 - static_cast<int>(ballTwo));
}
score += (10 + ballTwo + ballThree);
}
//Output score for each frame?
//cout << "Frame #" << index + 1 << " score: " << score << "\n";
return score;
}
//Convert an input char to an enum Ball
Ball charToBall(char inputChar) {
string matchString = "/-123456789X";
Ball outputBall = BALL_MISS;
//Attempt to match each ball to the enumeration
for (int n = -1; n <= 10; n++){
if (matchString[n + 1] == inputChar) {
outputBall = static_cast<Ball>(n);
}
}
//Additional check in case strikes were lower-case
if (inputChar == 'x') {
outputBall = BALL_STRIKE;
}
return outputBall;
}
void printScore(int scoreFrames[], int totScore){
//Display the frame numbers
cout << "|Frame";
for (int i = 1; i <= 10; i++) {
printf("|%3d", i);
}
cout << "|TOTAL|\n";
//Divider...
//cout << "|=====|---|---|---|---|---|---|---|---|---|---|=====|\n";
cout << "|=====|===|===|===|===|===|===|===|===|===|===|=====|\n";
//Display the scores for each frame, including total
cout << "|Score";
for (int i = 1; i <= 10; i++) {
printf("|%3d", scoreFrames[i - 1]);
}
printf("| %3d |\n\n", totScore);
return;
}
|
Java
|
UTF-8
| 6,175
| 1.859375
| 2
|
[] |
no_license
|
package com.xr.happyFamily.le.adapter;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.squareup.picasso.Picasso;
import com.xr.happyFamily.R;
import com.xr.happyFamily.bao.PingLunActivity;
import com.xr.happyFamily.le.bean.ClickFriendBean;
import com.xr.happyFamily.le.pojo.UserInfo;
import com.xr.happyFamily.together.util.GlideCircleTransform;
import com.xr.happyFamily.together.util.Utils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
//快递列表适配器
public class ClockAddQinglvAdapter extends RecyclerView.Adapter<ClockAddQinglvAdapter.MyViewHolder> implements View.OnClickListener {
private Context context;
private List<ClickFriendBean> data;
private ButtonInterface buttonInterface;
private int selPosition = -1;
private int defItem = -1;
private OnItemListener onItemListener;
private int type = 0;
boolean isFirst = true;
public ClockAddQinglvAdapter(Context context, List<ClickFriendBean> list) {
this.context = context;
this.data = list;
}
public void setOnItemListener(OnItemListener onItemListener) {
this.onItemListener = onItemListener;
}
public interface OnItemListener {
void onClick(View v, int pos, String projectc);
}
public void setDefSelect(int position) {
this.defItem = position;
notifyDataSetChanged();
}
/**
* 按钮点击事件需要的方法
*/
public void buttonSetOnclick(ButtonInterface buttonInterface) {
this.buttonInterface = buttonInterface;
}
/**
* 按钮点击事件对应的接口
*/
public interface ButtonInterface {
public void onclick(View view, int position);
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
MyViewHolder holder = new MyViewHolder(LayoutInflater.from(
context).inflate(R.layout.item_clock_add_qinglv, parent,
false));
return holder;
}
public void setSelection(int position) {
this.selPosition = position;
notifyDataSetChanged();
}
@Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
if (Utils.isEmpty(data.get(position).getHeadImgUrl())) {
holder.img_touxiang.setImageResource(R.mipmap.ic_touxiang_moren);
} else
Glide.with(context).load(data.get(position).getHeadImgUrl()).transform(new GlideCircleTransform(context.getApplicationContext())).error(R.mipmap.ic_touxiang_moren).into(holder.img_touxiang);
holder.tv_name.setText(data.get(position).getUsername().toString());
// holder.tv_context.setText(data.get(position).get("context").toString());
final int[] sign = {0};
final Drawable drawable_false = context.getResources().getDrawable(R.mipmap.ic_clock_qinglv_false);
final Drawable drawable_true = context.getResources().getDrawable(R.mipmap.ic_clock_qinglv_true);
drawable_true.setBounds(0, 0, drawable_true.getMinimumWidth(), drawable_true.getMinimumHeight());
drawable_false.setBounds(0, 0, drawable_false.getMinimumWidth(), drawable_false.getMinimumHeight());
if (selPosition == position) {
holder.tv_name.setCompoundDrawables(null, null, drawable_true, null);
data.get(position).setMemSign(1);
} else {
holder.tv_name.setCompoundDrawables(null, null, drawable_false, null);
data.get(position).setMemSign(0);
}
if (isFirst) {
Log.e("qqqqqqqqqIIIII222", loveId + "????");
if (data.get(position).getUserId() == loveId) {
isFirst = false;
sign[0] = 1;
this.selPosition = position;
holder.tv_name.setCompoundDrawables(null, null, drawable_true, null);
data.get(position).setMemSign(1);
}
}
holder.tv_name.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setSelection(position);
if (sign[0] == 1) {
sign[0] = 0;
holder.tv_name.setCompoundDrawables(null, null, drawable_false, null);
} else {
sign[0] = 1;
holder.tv_name.setCompoundDrawables(null, null, drawable_true, null);
}
}
});
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv_zhuiping:
context.startActivity(new Intent(context, PingLunActivity.class));
break;
}
}
@Override
public int getItemCount() {
return data.size();
}
/**
* ViewHolder的类,用于缓存控件
*/
class MyViewHolder extends RecyclerView.ViewHolder {
ImageView img_touxiang;
TextView tv_name;
RelativeLayout rl_item;
public MyViewHolder(View view) {
super(view);
img_touxiang = (ImageView) view.findViewById(R.id.img_touxiang);
tv_name = (TextView) view.findViewById(R.id.tv_name);
}
}
public String getMember() {
String member = "0";
if (selPosition != -1) {
member = data.get(selPosition).getUserId() + "";
}
return member;
}
public int getItem() {
return selPosition;
}
private int loveId = -1;
public void setUserId(int loveId) {
this.loveId = loveId;
notifyDataSetChanged();
}
}
|
C#
|
UTF-8
| 1,488
| 2.9375
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PerformanceApp
{
public class Module
{
private String code;
private String name;
private int credits;
private List<Assessment> assessments;
public string Level { get; set; }
public string Code
{
get
{
return code;
}
set
{
code = value;
}
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public int Credits
{
get
{
return credits;
}
set
{
credits = value;
}
}
public List<Assessment> Assessments
{
get
{
if (assessments == null)
{
assessments = new List<Assessment>();
}
return assessments;
}
set
{
assessments = value;
}
}
public decimal Status
{
get
{
return Assessments.Sum(x => x.Weight * x.Mark / 100);
}
}
}
}
|
Java
|
UTF-8
| 22,794
| 1.90625
| 2
|
[] |
no_license
|
/* */ package com.google.gson.internal;
/* */
/* */ import java.io.Serializable;
/* */ import java.lang.reflect.Array;
/* */ import java.lang.reflect.GenericArrayType;
/* */ import java.lang.reflect.GenericDeclaration;
/* */ import java.lang.reflect.Modifier;
/* */ import java.lang.reflect.ParameterizedType;
/* */ import java.lang.reflect.Type;
/* */ import java.lang.reflect.TypeVariable;
/* */ import java.lang.reflect.WildcardType;
/* */ import java.util.Arrays;
/* */ import java.util.Collection;
/* */ import java.util.Map;
/* */ import java.util.NoSuchElementException;
/* */ import java.util.Properties;
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public final class $Gson$Types
/* */ {
/* 44 */ static final Type[] EMPTY_TYPE_ARRAY = new Type[0];
/* */
/* */ private $Gson$Types() {
/* 47 */ throw new UnsupportedOperationException();
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public static ParameterizedType newParameterizedTypeWithOwner(Type ownerType, Type rawType, Type... typeArguments) {
/* 58 */ return new ParameterizedTypeImpl(ownerType, rawType, typeArguments);
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public static GenericArrayType arrayOf(Type componentType) {
/* 68 */ return new GenericArrayTypeImpl(componentType);
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public static WildcardType subtypeOf(Type bound) {
/* 78 */ return new WildcardTypeImpl(new Type[] { bound }, EMPTY_TYPE_ARRAY);
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public static WildcardType supertypeOf(Type bound) {
/* 87 */ return new WildcardTypeImpl(new Type[] { Object.class }, new Type[] { bound });
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public static Type canonicalize(Type type) {
/* 96 */ if (type instanceof Class) {
/* 97 */ Class<?> c = (Class)type;
/* 98 */ return c.isArray() ? new GenericArrayTypeImpl(canonicalize(c.getComponentType())) : c;
/* */ }
/* 100 */ if (type instanceof ParameterizedType) {
/* 101 */ ParameterizedType p = (ParameterizedType)type;
/* 102 */ return new ParameterizedTypeImpl(p.getOwnerType(), p
/* 103 */ .getRawType(), p.getActualTypeArguments());
/* */ }
/* 105 */ if (type instanceof GenericArrayType) {
/* 106 */ GenericArrayType g = (GenericArrayType)type;
/* 107 */ return new GenericArrayTypeImpl(g.getGenericComponentType());
/* */ }
/* 109 */ if (type instanceof WildcardType) {
/* 110 */ WildcardType w = (WildcardType)type;
/* 111 */ return new WildcardTypeImpl(w.getUpperBounds(), w.getLowerBounds());
/* */ }
/* */
/* */
/* 115 */ return type;
/* */ }
/* */
/* */
/* */ public static Class<?> getRawType(Type type) {
/* 120 */ if (type instanceof Class)
/* */ {
/* 122 */ return (Class)type;
/* */ }
/* 124 */ if (type instanceof ParameterizedType) {
/* 125 */ ParameterizedType parameterizedType = (ParameterizedType)type;
/* */
/* */
/* */
/* */
/* 130 */ Type rawType = parameterizedType.getRawType();
/* 131 */ $Gson$Preconditions.checkArgument(rawType instanceof Class);
/* 132 */ return (Class)rawType;
/* */ }
/* 134 */ if (type instanceof GenericArrayType) {
/* 135 */ Type componentType = ((GenericArrayType)type).getGenericComponentType();
/* 136 */ return Array.newInstance(getRawType(componentType), 0).getClass();
/* */ }
/* 138 */ if (type instanceof TypeVariable)
/* */ {
/* */
/* 141 */ return Object.class;
/* */ }
/* 143 */ if (type instanceof WildcardType) {
/* 144 */ return getRawType(((WildcardType)type).getUpperBounds()[0]);
/* */ }
/* */
/* 147 */ String className = (type == null) ? "null" : type.getClass().getName();
/* 148 */ throw new IllegalArgumentException("Expected a Class, ParameterizedType, or GenericArrayType, but <" + type + "> is of type " + className);
/* */ }
/* */
/* */
/* */
/* */ static boolean equal(Object a, Object b) {
/* 154 */ return (a == b || (a != null && a.equals(b)));
/* */ }
/* */
/* */
/* */
/* */
/* */ public static boolean equals(Type a, Type b) {
/* 161 */ if (a == b)
/* */ {
/* 163 */ return true;
/* */ }
/* 165 */ if (a instanceof Class)
/* */ {
/* 167 */ return a.equals(b);
/* */ }
/* 169 */ if (a instanceof ParameterizedType) {
/* 170 */ if (!(b instanceof ParameterizedType)) {
/* 171 */ return false;
/* */ }
/* */
/* */
/* 175 */ ParameterizedType pa = (ParameterizedType)a;
/* 176 */ ParameterizedType pb = (ParameterizedType)b;
/* 177 */ return (equal(pa.getOwnerType(), pb.getOwnerType()) && pa
/* 178 */ .getRawType().equals(pb.getRawType()) &&
/* 179 */ Arrays.equals((Object[])pa.getActualTypeArguments(), (Object[])pb.getActualTypeArguments()));
/* */ }
/* 181 */ if (a instanceof GenericArrayType) {
/* 182 */ if (!(b instanceof GenericArrayType)) {
/* 183 */ return false;
/* */ }
/* */
/* 186 */ GenericArrayType ga = (GenericArrayType)a;
/* 187 */ GenericArrayType gb = (GenericArrayType)b;
/* 188 */ return equals(ga.getGenericComponentType(), gb.getGenericComponentType());
/* */ }
/* 190 */ if (a instanceof WildcardType) {
/* 191 */ if (!(b instanceof WildcardType)) {
/* 192 */ return false;
/* */ }
/* */
/* 195 */ WildcardType wa = (WildcardType)a;
/* 196 */ WildcardType wb = (WildcardType)b;
/* 197 */ return (Arrays.equals((Object[])wa.getUpperBounds(), (Object[])wb.getUpperBounds()) &&
/* 198 */ Arrays.equals((Object[])wa.getLowerBounds(), (Object[])wb.getLowerBounds()));
/* */ }
/* 200 */ if (a instanceof TypeVariable) {
/* 201 */ if (!(b instanceof TypeVariable)) {
/* 202 */ return false;
/* */ }
/* 204 */ TypeVariable<?> va = (TypeVariable)a;
/* 205 */ TypeVariable<?> vb = (TypeVariable)b;
/* 206 */ return (va.getGenericDeclaration() == vb.getGenericDeclaration() && va
/* 207 */ .getName().equals(vb.getName()));
/* */ }
/* */
/* */
/* 211 */ return false;
/* */ }
/* */
/* */
/* */ static int hashCodeOrZero(Object o) {
/* 216 */ return (o != null) ? o.hashCode() : 0;
/* */ }
/* */
/* */ public static String typeToString(Type type) {
/* 220 */ return (type instanceof Class) ? ((Class)type).getName() : type.toString();
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */ static Type getGenericSupertype(Type context, Class<?> rawType, Class<?> toResolve) {
/* 229 */ if (toResolve == rawType) {
/* 230 */ return context;
/* */ }
/* */
/* */
/* 234 */ if (toResolve.isInterface()) {
/* 235 */ Class<?>[] interfaces = rawType.getInterfaces();
/* 236 */ for (int i = 0, length = interfaces.length; i < length; i++) {
/* 237 */ if (interfaces[i] == toResolve)
/* 238 */ return rawType.getGenericInterfaces()[i];
/* 239 */ if (toResolve.isAssignableFrom(interfaces[i])) {
/* 240 */ return getGenericSupertype(rawType.getGenericInterfaces()[i], interfaces[i], toResolve);
/* */ }
/* */ }
/* */ }
/* */
/* */
/* 246 */ if (!rawType.isInterface()) {
/* 247 */ while (rawType != Object.class) {
/* 248 */ Class<?> rawSupertype = rawType.getSuperclass();
/* 249 */ if (rawSupertype == toResolve)
/* 250 */ return rawType.getGenericSuperclass();
/* 251 */ if (toResolve.isAssignableFrom(rawSupertype)) {
/* 252 */ return getGenericSupertype(rawType.getGenericSuperclass(), rawSupertype, toResolve);
/* */ }
/* 254 */ rawType = rawSupertype;
/* */ }
/* */ }
/* */
/* */
/* 259 */ return toResolve;
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ static Type getSupertype(Type context, Class<?> contextRawType, Class<?> supertype) {
/* 270 */ $Gson$Preconditions.checkArgument(supertype.isAssignableFrom(contextRawType));
/* 271 */ return resolve(context, contextRawType,
/* 272 */ getGenericSupertype(context, contextRawType, supertype));
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */ public static Type getArrayComponentType(Type array) {
/* 280 */ return (array instanceof GenericArrayType) ? ((GenericArrayType)array)
/* 281 */ .getGenericComponentType() : ((Class)array)
/* 282 */ .getComponentType();
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */ public static Type getCollectionElementType(Type context, Class<?> contextRawType) {
/* 290 */ Type collectionType = getSupertype(context, contextRawType, Collection.class);
/* */
/* 292 */ if (collectionType instanceof WildcardType) {
/* 293 */ collectionType = ((WildcardType)collectionType).getUpperBounds()[0];
/* */ }
/* 295 */ if (collectionType instanceof ParameterizedType) {
/* 296 */ return ((ParameterizedType)collectionType).getActualTypeArguments()[0];
/* */ }
/* 298 */ return Object.class;
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public static Type[] getMapKeyAndValueTypes(Type context, Class<?> contextRawType) {
/* 311 */ if (context == Properties.class) {
/* 312 */ return new Type[] { String.class, String.class };
/* */ }
/* */
/* 315 */ Type mapType = getSupertype(context, contextRawType, Map.class);
/* */
/* 317 */ if (mapType instanceof ParameterizedType) {
/* 318 */ ParameterizedType mapParameterizedType = (ParameterizedType)mapType;
/* 319 */ return mapParameterizedType.getActualTypeArguments();
/* */ }
/* 321 */ return new Type[] { Object.class, Object.class };
/* */ }
/* */
/* */
/* */
/* */ public static Type resolve(Type context, Class<?> contextRawType, Type toResolve) {
/* 327 */ while (toResolve instanceof TypeVariable) {
/* 328 */ TypeVariable<?> typeVariable = (TypeVariable)toResolve;
/* 329 */ toResolve = resolveTypeVariable(context, contextRawType, typeVariable);
/* 330 */ if (toResolve == typeVariable) {
/* 331 */ return toResolve;
/* */ }
/* */ }
/* 334 */ if (toResolve instanceof Class && ((Class)toResolve).isArray()) {
/* 335 */ Class<?> original = (Class)toResolve;
/* 336 */ Type<?> componentType = original.getComponentType();
/* 337 */ Type newComponentType = resolve(context, contextRawType, componentType);
/* 338 */ return (componentType == newComponentType) ? original :
/* */
/* 340 */ arrayOf(newComponentType);
/* */ }
/* 342 */ if (toResolve instanceof GenericArrayType) {
/* 343 */ GenericArrayType original = (GenericArrayType)toResolve;
/* 344 */ Type componentType = original.getGenericComponentType();
/* 345 */ Type newComponentType = resolve(context, contextRawType, componentType);
/* 346 */ return (componentType == newComponentType) ? original :
/* */
/* 348 */ arrayOf(newComponentType);
/* */ }
/* 350 */ if (toResolve instanceof ParameterizedType) {
/* 351 */ ParameterizedType original = (ParameterizedType)toResolve;
/* 352 */ Type ownerType = original.getOwnerType();
/* 353 */ Type newOwnerType = resolve(context, contextRawType, ownerType);
/* 354 */ boolean changed = (newOwnerType != ownerType);
/* */
/* 356 */ Type[] args = original.getActualTypeArguments();
/* 357 */ for (int t = 0, length = args.length; t < length; t++) {
/* 358 */ Type resolvedTypeArgument = resolve(context, contextRawType, args[t]);
/* 359 */ if (resolvedTypeArgument != args[t]) {
/* 360 */ if (!changed) {
/* 361 */ args = (Type[])args.clone();
/* 362 */ changed = true;
/* */ }
/* 364 */ args[t] = resolvedTypeArgument;
/* */ }
/* */ }
/* */
/* 368 */ return changed ?
/* 369 */ newParameterizedTypeWithOwner(newOwnerType, original.getRawType(), args) : original;
/* */ }
/* */
/* 372 */ if (toResolve instanceof WildcardType) {
/* 373 */ WildcardType original = (WildcardType)toResolve;
/* 374 */ Type[] originalLowerBound = original.getLowerBounds();
/* 375 */ Type[] originalUpperBound = original.getUpperBounds();
/* */
/* 377 */ if (originalLowerBound.length == 1) {
/* 378 */ Type lowerBound = resolve(context, contextRawType, originalLowerBound[0]);
/* 379 */ if (lowerBound != originalLowerBound[0]) {
/* 380 */ return supertypeOf(lowerBound);
/* */ }
/* 382 */ } else if (originalUpperBound.length == 1) {
/* 383 */ Type upperBound = resolve(context, contextRawType, originalUpperBound[0]);
/* 384 */ if (upperBound != originalUpperBound[0]) {
/* 385 */ return subtypeOf(upperBound);
/* */ }
/* */ }
/* 388 */ return original;
/* */ }
/* */
/* 391 */ return toResolve;
/* */ }
/* */
/* */
/* */
/* */ static Type resolveTypeVariable(Type context, Class<?> contextRawType, TypeVariable<?> unknown) {
/* 397 */ Class<?> declaredByRaw = declaringClassOf(unknown);
/* */
/* */
/* 400 */ if (declaredByRaw == null) {
/* 401 */ return unknown;
/* */ }
/* */
/* 404 */ Type declaredBy = getGenericSupertype(context, contextRawType, declaredByRaw);
/* 405 */ if (declaredBy instanceof ParameterizedType) {
/* 406 */ int index = indexOf((Object[])declaredByRaw.getTypeParameters(), unknown);
/* 407 */ return ((ParameterizedType)declaredBy).getActualTypeArguments()[index];
/* */ }
/* */
/* 410 */ return unknown;
/* */ }
/* */
/* */ private static int indexOf(Object[] array, Object toFind) {
/* 414 */ for (int i = 0; i < array.length; i++) {
/* 415 */ if (toFind.equals(array[i])) {
/* 416 */ return i;
/* */ }
/* */ }
/* 419 */ throw new NoSuchElementException();
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */ private static Class<?> declaringClassOf(TypeVariable<?> typeVariable) {
/* 427 */ GenericDeclaration genericDeclaration = (GenericDeclaration)typeVariable.getGenericDeclaration();
/* 428 */ return (genericDeclaration instanceof Class) ? (Class)genericDeclaration : null;
/* */ }
/* */
/* */
/* */
/* */ static void checkNotPrimitive(Type type) {
/* 434 */ $Gson$Preconditions.checkArgument((!(type instanceof Class) || !((Class)type).isPrimitive()));
/* */ }
/* */
/* */ private static final class ParameterizedTypeImpl implements ParameterizedType, Serializable {
/* */ private final Type ownerType;
/* */ private final Type rawType;
/* */ private final Type[] typeArguments;
/* */ private static final long serialVersionUID = 0L;
/* */
/* */ public ParameterizedTypeImpl(Type ownerType, Type rawType, Type... typeArguments) {
/* 444 */ if (rawType instanceof Class) {
/* 445 */ Class<?> rawTypeAsClass = (Class)rawType;
/* */
/* 447 */ boolean isStaticOrTopLevelClass = (Modifier.isStatic(rawTypeAsClass.getModifiers()) || rawTypeAsClass.getEnclosingClass() == null);
/* 448 */ $Gson$Preconditions.checkArgument((ownerType != null || isStaticOrTopLevelClass));
/* */ }
/* */
/* 451 */ this.ownerType = (ownerType == null) ? null : $Gson$Types.canonicalize(ownerType);
/* 452 */ this.rawType = $Gson$Types.canonicalize(rawType);
/* 453 */ this.typeArguments = (Type[])typeArguments.clone();
/* 454 */ for (int t = 0; t < this.typeArguments.length; t++) {
/* 455 */ $Gson$Preconditions.checkNotNull(this.typeArguments[t]);
/* 456 */ $Gson$Types.checkNotPrimitive(this.typeArguments[t]);
/* 457 */ this.typeArguments[t] = $Gson$Types.canonicalize(this.typeArguments[t]);
/* */ }
/* */ }
/* */
/* */ public Type[] getActualTypeArguments() {
/* 462 */ return (Type[])this.typeArguments.clone();
/* */ }
/* */
/* */ public Type getRawType() {
/* 466 */ return this.rawType;
/* */ }
/* */
/* */ public Type getOwnerType() {
/* 470 */ return this.ownerType;
/* */ }
/* */
/* */ public boolean equals(Object other) {
/* 474 */ return (other instanceof ParameterizedType &&
/* 475 */ $Gson$Types.equals(this, (ParameterizedType)other));
/* */ }
/* */
/* */ public int hashCode() {
/* 479 */ return Arrays.hashCode((Object[])this.typeArguments) ^ this.rawType
/* 480 */ .hashCode() ^
/* 481 */ $Gson$Types.hashCodeOrZero(this.ownerType);
/* */ }
/* */
/* */ public String toString() {
/* 485 */ StringBuilder stringBuilder = new StringBuilder(30 * (this.typeArguments.length + 1));
/* 486 */ stringBuilder.append($Gson$Types.typeToString(this.rawType));
/* */
/* 488 */ if (this.typeArguments.length == 0) {
/* 489 */ return stringBuilder.toString();
/* */ }
/* */
/* 492 */ stringBuilder.append("<").append($Gson$Types.typeToString(this.typeArguments[0]));
/* 493 */ for (int i = 1; i < this.typeArguments.length; i++) {
/* 494 */ stringBuilder.append(", ").append($Gson$Types.typeToString(this.typeArguments[i]));
/* */ }
/* 496 */ return stringBuilder.append(">").toString();
/* */ }
/* */ }
/* */
/* */ private static final class GenericArrayTypeImpl
/* */ implements GenericArrayType, Serializable {
/* */ private final Type componentType;
/* */ private static final long serialVersionUID = 0L;
/* */
/* */ public GenericArrayTypeImpl(Type componentType) {
/* 506 */ this.componentType = $Gson$Types.canonicalize(componentType);
/* */ }
/* */
/* */ public Type getGenericComponentType() {
/* 510 */ return this.componentType;
/* */ }
/* */
/* */ public boolean equals(Object o) {
/* 514 */ return (o instanceof GenericArrayType &&
/* 515 */ $Gson$Types.equals(this, (GenericArrayType)o));
/* */ }
/* */
/* */ public int hashCode() {
/* 519 */ return this.componentType.hashCode();
/* */ }
/* */
/* */ public String toString() {
/* 523 */ return $Gson$Types.typeToString(this.componentType) + "[]";
/* */ }
/* */ }
/* */
/* */
/* */ private static final class WildcardTypeImpl
/* */ implements WildcardType, Serializable
/* */ {
/* */ private final Type upperBound;
/* */
/* */ private final Type lowerBound;
/* */
/* */ private static final long serialVersionUID = 0L;
/* */
/* */
/* */ public WildcardTypeImpl(Type[] upperBounds, Type[] lowerBounds) {
/* 539 */ $Gson$Preconditions.checkArgument((lowerBounds.length <= 1));
/* 540 */ $Gson$Preconditions.checkArgument((upperBounds.length == 1));
/* */
/* 542 */ if (lowerBounds.length == 1) {
/* 543 */ $Gson$Preconditions.checkNotNull(lowerBounds[0]);
/* 544 */ $Gson$Types.checkNotPrimitive(lowerBounds[0]);
/* 545 */ $Gson$Preconditions.checkArgument((upperBounds[0] == Object.class));
/* 546 */ this.lowerBound = $Gson$Types.canonicalize(lowerBounds[0]);
/* 547 */ this.upperBound = Object.class;
/* */ } else {
/* */
/* 550 */ $Gson$Preconditions.checkNotNull(upperBounds[0]);
/* 551 */ $Gson$Types.checkNotPrimitive(upperBounds[0]);
/* 552 */ this.lowerBound = null;
/* 553 */ this.upperBound = $Gson$Types.canonicalize(upperBounds[0]);
/* */ }
/* */ }
/* */
/* */ public Type[] getUpperBounds() {
/* 558 */ return new Type[] { this.upperBound };
/* */ }
/* */
/* */ public Type[] getLowerBounds() {
/* 562 */ (new Type[1])[0] = this.lowerBound; return (this.lowerBound != null) ? new Type[1] : $Gson$Types.EMPTY_TYPE_ARRAY;
/* */ }
/* */
/* */ public boolean equals(Object other) {
/* 566 */ return (other instanceof WildcardType &&
/* 567 */ $Gson$Types.equals(this, (WildcardType)other));
/* */ }
/* */
/* */
/* */ public int hashCode() {
/* 572 */ return ((this.lowerBound != null) ? (31 + this.lowerBound.hashCode()) : 1) ^ 31 + this.upperBound
/* 573 */ .hashCode();
/* */ }
/* */
/* */ public String toString() {
/* 577 */ if (this.lowerBound != null)
/* 578 */ return "? super " + $Gson$Types.typeToString(this.lowerBound);
/* 579 */ if (this.upperBound == Object.class) {
/* 580 */ return "?";
/* */ }
/* 582 */ return "? extends " + $Gson$Types.typeToString(this.upperBound);
/* */ }
/* */ }
/* */ }
/* Location: C:\Users\Josep\Downloads\Decompile Minecraft\tuinity-1.16.3.jar!\com\google\gson\internal\$Gson$Types.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
PHP
|
UTF-8
| 257
| 2.84375
| 3
|
[] |
no_license
|
<?php
/*
* Request class.
*/
namespace Request;
class Request
{
/**
* @method handle
* @return pointer to array();
*/
function &handle()
{
$this->_request = &$_REQUEST;
return $this->_request;
}
}
|
Markdown
|
UTF-8
| 3,493
| 3.09375
| 3
|
[
"MIT"
] |
permissive
|
# N5 Web Application
N5 is a web application that displays the next five races that can be bet on, sorted by the closing date.
When a race is closed, you can no longer bet or view that race.
To view the details of the race, click on the race number and a new page will load displaying the race type, time, competitors and other details.
## Getting Started
Before running the N5 Application make sure you have installed the correct dependencies, programs and have correctly set up the database connection. If this is not done, erroneous results may occur.
##### You have been warned /s.
### Prerequisites
The main programs required to run this project are
- A Golang IDE (Goland is my fave)
- Docker
- A database visualiser tool (not necessary but makes life so much better)
- Some sort of command line tool (is it possible to not have one?)
- PostgreSQL
### Installing
Follow this guide to install and run the project.
1. Install IDE of choice
2. Set GOPATH and GOROOT variables
3. To install all required packages and dependencies that you do not have, on your command line tool navigate to the N5 Web App and run ``` go get -d ./... ```
4. Install Docker
5. Run docker and either ``` docker pull postgres ``` or open up your command line tool, navigate to the project and then run ``` docker-compose -f stacker.yml up ```
6. Once database container is running, open up database visualiser tool and connect
7. In your IDE of choice, make sure you have set up your database to postgreSQL and you connect to the IP and Port shown by the docker container
8. Start the database connection in your IDE
9. Open tables.sql in the sql folder of the project and run the database creation statements within
10. Check your database visualisation tool or run SQL commands to make sure the tables have been created correctly
11. Run main.go in your IDE
12. Open up a web browser and navigate to ```127.0.0.1:8080``` or ```localhost:8080```
### And there you have it! You are now successfully running the application.
## Navigating the web page information
### Main Page
On the main page that is loaded on ```127.0.0.1:8080``` or ```localhost:8080``` you will find the next five races with the smallest time remaining til closing in comparison to your current time.
It displays the race number, the race type, the race location, it's closing time, and the time remaining (in seconds) until the race is closed.
### Race Details Page
To view the details of each race, click on the race number and a new page will load displaying the race information.
The race details page displays the race location, race type, the competitors names, their starting positions, the closing time, and the time remaining until the race is closed (in seconds).
## Built With
* [Goland](https://www.jetbrains.com/go/) - Golang IDE used
* [Docker](https://www.docker.com/) - The software containerization platform
* [PostgreSQL](https://www.postgresql.org/) - Database used
* [SQLBoiler](https://github.com/volatiletech/sqlboiler) - Database ORM tool
* [Gin Gonic](https://github.com/gin-gonic/gin) - Web framework
## Authors
* **Sir Professor Lord David Gray** - *Only the best* - [Subrising](https://github.com/subrising)
## License
This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details
## Acknowledgments
* Me for being awesome
* StackOverflow for helping me remember things I've forgotten
* LadBrokes for giving me this opportunity
* Google for obvious reasons
|
C
|
UTF-8
| 2,431
| 2.515625
| 3
|
[] |
no_license
|
#include "xparameters.h"
#include "xgpio.h"
#include "RLC_decoder_IP.h"
/**************************** user definitions ********************************/
#define CHANNEL 1
//RLC coder base address redefinition
#define RLC_DECODER_IP_BASE_ADDR XPAR_RLC_DECODER_IP_0_S00_AXI_BASEADDR
//RLC coder registers' offset redefinition
#define CONTROL_REG_OFFSET RLC_DECODER_IP_S00_AXI_SLV_REG0_OFFSET
#define CODED_DATA_REG_OFFSET RLC_DECODER_IP_S00_AXI_SLV_REG1_OFFSET
#define STATUS_REG_OFFSET RLC_DECODER_IP_S00_AXI_SLV_REG2_OFFSET
#define DECODED_DATA_REG_OFFSET RLC_DECODER_IP_S00_AXI_SLV_REG3_OFFSET
/***************************** Main function *********************************/
int main() {
int status;
XGpio codedDataGpio, decodedDataGpio;
u32 inputData, outputData;
/* Initialize driver for the input data GPIO */
status = XGpio_Initialize(&codedDataGpio, XPAR_AXI_GPIO_CODED_DATA_DEVICE_ID);
if (status != XST_SUCCESS) {
goto FAILURE;
}
XGpio_SetDataDirection(&codedDataGpio, CHANNEL, 0xFFFFFFFF);
/* Initialize driver for the output coded data GPIO */
status = XGpio_Initialize(&decodedDataGpio, XPAR_AXI_GPIO_DECODED_DATA_DEVICE_ID);
if (status != XST_SUCCESS) {
goto FAILURE;
}
XGpio_SetDataDirection(&decodedDataGpio, CHANNEL, 0x00000000);
// copy input data from the input GPIO
inputData = XGpio_DiscreteRead(&codedDataGpio, CHANNEL);
// insert input data into register
RLC_DECODER_IP_mWriteReg(RLC_DECODER_IP_BASE_ADDR, CODED_DATA_REG_OFFSET, inputData);
int finish = 0;
while ( finish == 0 ) {
//Start RLC coder processor - pulse start bit in control register
RLC_DECODER_IP_mWriteReg(RLC_DECODER_IP_BASE_ADDR, CONTROL_REG_OFFSET, 0x1); // set "start" to 1
RLC_DECODER_IP_mWriteReg(RLC_DECODER_IP_BASE_ADDR, CONTROL_REG_OFFSET, 0x0); // set "start" to 0
//Wait for ready bit in status register
while( (RLC_DECODER_IP_mReadReg(RLC_DECODER_IP_BASE_ADDR, STATUS_REG_OFFSET) & 0x1) == 0 ); // wait for "result_ready"
finish = (RLC_DECODER_IP_mReadReg(RLC_DECODER_IP_BASE_ADDR, STATUS_REG_OFFSET) & 0x2);
//Get results
outputData = RLC_DECODER_IP_mReadReg(RLC_DECODER_IP_BASE_ADDR, DECODED_DATA_REG_OFFSET);
RLC_DECODER_IP_mWriteReg(RLC_DECODER_IP_BASE_ADDR, CONTROL_REG_OFFSET, 0x2); // set "read_success" to 1
//Send to GPIO
XGpio_DiscreteWrite(&decodedDataGpio, CHANNEL, outputData);
}
/* Failure or end trap */
FAILURE:
while(1);
}
|
Java
|
UTF-8
| 283
| 2.265625
| 2
|
[] |
no_license
|
package leetcode.leetcode23xx.leetcode2357;
import java.util.HashSet;
public class Solution {
public int minimumOperations(int[] nums) {
HashSet<Integer> set = new HashSet<>();
for (int num : nums) if (num != 0) set.add(num);
return set.size();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.