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
|
|---|---|---|---|---|---|---|---|
C#
|
UTF-8
| 1,183
| 2.921875
| 3
|
[
"MIT"
] |
permissive
|
using Mike.Utilities.Desktop;
namespace Model.Entidades
{
public class Categoria
{
private int _id;
public int ID
{
get { return _id; }
set
{
if (int.MaxValue == value)
{
MyErro.MyCustomException("Categoria Excedeu o número máximo de cadastro, contate o Administrador");
}
else
{
_id = value;
}
}
}
private string _nome;
public string Nome
{
get { return _nome; }
set
{
if (value.Length == 0)
{
MyErro.MyCustomException("Categoria não pode ser vazio.");
}
else if (value.Length > 20)
{
MyErro.MyCustomException("Categoria não pode cpnter mais de 20 letras ou numeros.");
}
else
{
_nome = value;
}
}
}
}
}
|
Python
|
UTF-8
| 805
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
import os.path
import sys
from .loader import Loader, I18nFileLoadError
class PythonLoader(Loader):
"""class to load python files"""
def __init__(self):
super(PythonLoader, self).__init__()
def load_file(self, filename):
path, name = os.path.split(filename)
module_name, ext = os.path.splitext(name)
if path not in sys.path:
sys.path.append(path)
try:
return __import__(module_name)
except ImportError:
raise I18nFileLoadError("error loading file {0}".format(filename))
def parse_file(self, file_content):
return file_content
def check_data(self, data, root_data):
return hasattr(data, root_data)
def get_data(self, data, root_data):
return getattr(data, root_data)
|
Java
|
UTF-8
| 580
| 1.765625
| 2
|
[] |
no_license
|
package com.idream.commons.lib.dto.activity;
import com.idream.commons.lib.dto.PagesParam;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import javax.validation.constraints.NotNull;
/**
* @Description :
* @Created by xiaogang on 2018/5/2.
*/
@ApiModel(value = "动态ID参数")
public class AppLifeIdParam {
@ApiModelProperty("动态id")
@NotNull(message = "id 不能为空")
private Integer id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
|
Shell
|
UTF-8
| 1,968
| 4
| 4
|
[
"MIT"
] |
permissive
|
#!/bin/bash
set -e
ROOTDIR=`dirname "$0"`
ROOTDIR=`cd "$ROOTDIR/.." && pwd`
source "$ROOTDIR/shared/lib/library.sh"
INPUT_DIR=
ARCHITECTURE=
OUTPUT_DIR=
function usage()
{
echo "Usage: ./package [OPTIONS]"
echo "Package built Passenger binaries."
echo
echo "Required options:"
echo " -i DIR The output directory written to by build script"
echo " -a ARCH Architecture of the build (x86_64, arm64)"
echo " -o DIR Path in which to store output products"
echo
echo "Optional options:"
echo " -h Show usage"
}
function parse_options()
{
local OPTIND=1
local opt
while getopts "i:a:o:h" opt; do
case "$opt" in
i)
INPUT_DIR="$OPTARG"
;;
a)
ARCHITECTURE="$OPTARG"
;;
o)
OUTPUT_DIR="$OPTARG"
;;
h)
usage
exit
;;
*)
return 1
;;
esac
done
if [[ "$INPUT_DIR" = "" ]]; then
echo "ERROR: please specify an input directory with -i."
exit 1
fi
if [[ "$ARCHITECTURE" = "" ]]; then
echo "ERROR: please specify an architecture with -a."
exit 1
fi
if [[ "$OUTPUT_DIR" = "" ]]; then
echo "ERROR: please specify an output directory with -o."
exit 1
fi
}
parse_options "$@"
set -o pipefail
export GZIP=--best
INPUT_DIR="`absolute_path \"$INPUT_DIR\"`"
OUTPUT_DIR="`absolute_path \"$OUTPUT_DIR\"`"
NGINX_VERSION=`/bin/ls -1 "$INPUT_DIR"/support-binaries/nginx-* | sed 's/.*-//'`
run mkdir -p "$OUTPUT_DIR"
run tar -czf "$OUTPUT_DIR/agent-$ARCHITECTURE-linux.tar.gz" \
-C "$INPUT_DIR/support-binaries" PassengerAgent
run tar -czf "$OUTPUT_DIR/agent-$ARCHITECTURE-linux.dbg.tar.gz" \
-C "$INPUT_DIR/support-binaries" PassengerAgent.dbg
run tar -czf "$OUTPUT_DIR/nginx-$NGINX_VERSION-$ARCHITECTURE-linux.tar.gz" \
-C "$INPUT_DIR/support-binaries" "nginx-$NGINX_VERSION"
for RUBY_EXT_DIR in `/bin/ls -1 "$INPUT_DIR/ruby-extensions"`; do
run tar -czf "$OUTPUT_DIR/rubyext-$RUBY_EXT_DIR.tar.gz" \
-C "$INPUT_DIR/ruby-extensions/$RUBY_EXT_DIR" \
passenger_native_support.so
done
|
PHP
|
UTF-8
| 4,092
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
<?php
/**
* Generate image thumbnail URL
*
* @param string $imagePath
* @param int $width
* @param int $height
* @param bool $zoom_crop
* @param bool $upsize
* @return string Thumbnail URL
* @throws Exception if image dimensions are missing
*/
function thumb_url($imagePath, $width = null, $height = null, $zoom_crop = false, $upsize = false)
{
if (is_null($width) && is_null($height)) {
throw new Exception('Image dimensions are missing.');
}
$extension = File::extension($imagePath);
if ($extension == 'svg') {
return URL::asset($imagePath);
}
$params = '-';
$params .= !is_null($width) ? $width : '';
$params .= 'x';
$params .= !is_null($height) ? $height : '';
$params .= $zoom_crop ? '-crop' : '';
$params .= $upsize ? '-upsize' : '';
$imagePath = substr($imagePath, 0, - strlen($extension) - 1);
$thumb_url = URL::asset('thumbs/' . $imagePath . $params . '.' . $extension);
return $thumb_url;
}
/**
* Get image ID from path
*
* @param string $path
* @return integer
*/
function get_image_id($path)
{
$imageId = ImageLibraryLanguage::where('image_path', $path)->pluck('image_id');
if (!is_null($imageId)) {
return $imageId;
}
return 0;
}
/*Get File ID*/
function get_file_id($path)
{
$fileId = FileLibraryLanguage::where('file_path', $path)->pluck('file_id');
if (!is_null($fileId)) {
return $fileId;
}
return 0;
}
/**
* Get image path from ID
*
* @param integer $id
* @return string
*/
function get_image_path($id)
{
$imagePath = ImageLibraryLanguage::where(['lang' => LANG, 'image_id' => $id])->pluck('image_path');
if (!is_null($imagePath)) {
return $imagePath;
}
return '';
}
function get_file_path($id)
{
$filePath = FileLibraryLanguage::where(['lang' => LANG, 'file_id' => $id])->pluck('file_path');
if (!is_null($filePath)) {
return $filePath;
}
return '';
}
/**
* Create image html from ID
*
* @param integer $id
* @param array $attributes
* @return string
*/
function get_image($id, $attributes = [])
{
$image = ImageLibraryLanguage::where(['lang' => LANG, 'image_id' => $id])->first();
if (!is_null($image)) {
$attributes = array_merge(['title' => $image->title], $attributes);
return HTML::image($image->image_path, $image->alt, $attributes);
}
return '';
}
/**
* Create image thumb html from ID
*
* @param integer $id
* @param integer $width
* @param integer $height
* @param bool $zoom_crop
* @param bool $upsize
* @param array $attributes
* @return string
*/
function get_image_thumb($id, $width = null, $height = null, $zoom_crop = false, $upsize = false, $attributes = [])
{
$image = ImageLibraryLanguage::where(['lang' => LANG, 'image_id' => $id])->first();
if (!is_null($image)) {
$attributes = array_merge(['title' => $image->title], $attributes);
return HTML::image(thumb_url($image->image_path, $width, $height, $zoom_crop, $upsize), $image->alt, $attributes);
}
return '';
}
#return id after uploading
function upload_image($image){
$year = date("Y");
$month = date("m");
$path = public_path('thumbs/uploads');
$url = $path.'/'.$year.'/'.$month;
$fullPath = '';
if ($image)
{
$file = $image;
$fileName = str_random(5).$file->getClientOriginalName();
$file->move($url, $fileName);
}
$imageLibrary = new ImageLibrary;
$imageLibrary->author_id = Auth::user()->id;
if ($imageLibrary->save()) {
$imageLibraryLanguage = new ImageLibraryLanguage;
$imageLibraryLanguage->lang = LANG;
$imageLibraryLanguage->image_id = $imageLibrary->id;
$imageLibraryLanguage->image_path = 'uploads/'.$year.'/'.$month.'/'.$fileName;
if ($imageLibraryLanguage->save()) {
return $imageLibrary->id;
}
else
{
return 0;
}
}
}
|
Markdown
|
UTF-8
| 4,201
| 3.40625
| 3
|
[
"MIT"
] |
permissive
|
---
categories:
- golang
tags:
- golang,从零开始golang
keywords: 知识铺
date: 2019-10-20T22:37:27+08:00
title: golang入门圣经 ch11- 11.2.2. 测试一个命令
author: 知识铺
weight: -1
---
### 11.2.2. 测试一个命令
对于测试包`go test`是一个有用的工具,但是稍加努力我们也可以用它来测试可执行程序。如果一个包的名字是 main,那么在构建时会生成一个可执行程序,不过main包可以作为一个包被测试器代码导入。
让我们为2.3.2节的echo程序编写一个测试。我们先将程序拆分为两个函数:echo函数完成真正的工作,main函数用于处理命令行输入参数和echo可能返回的错误。
<u><i>gopl.io/ch11/echo</i></u>
```Go
// Echo prints its command-line arguments.
package main
import (
"flag"
"fmt"
"io"
"os"
"strings"
)
var (
n = flag.Bool("n", false, "omit trailing newline")
s = flag.String("s", " ", "separator")
)
var out io.Writer = os.Stdout // modified during testing
func main() {
flag.Parse()
if err := echo(!*n, *s, flag.Args()); err != nil {
fmt.Fprintf(os.Stderr, "echo: %v\n", err)
os.Exit(1)
}
}
func echo(newline bool, sep string, args []string) error {
fmt.Fprint(out, strings.Join(args, sep))
if newline {
fmt.Fprintln(out)
}
return nil
}
```
在测试中我们可以用各种参数和标志调用echo函数,然后检测它的输出是否正确,我们通过增加参数来减少echo函数对全局变量的依赖。我们还增加了一个全局名为out的变量来替代直接使用os.Stdout,这样测试代码可以根据需要将out修改为不同的对象以便于检查。下面就是echo_test.go文件中的测试代码:
```Go
package main
import (
"bytes"
"fmt"
"testing"
)
func TestEcho(t *testing.T) {
var tests = []struct {
newline bool
sep string
args []string
want string
}{
{true, "", []string{}, "\n"},
{false, "", []string{}, ""},
{true, "\t", []string{"one", "two", "three"}, "one\ttwo\tthree\n"},
{true, ",", []string{"a", "b", "c"}, "a,b,c\n"},
{false, ":", []string{"1", "2", "3"}, "1:2:3"},
}
for _, test := range tests {
descr := fmt.Sprintf("echo(%v, %q, %q)",
test.newline, test.sep, test.args)
out = new(bytes.Buffer) // captured output
if err := echo(test.newline, test.sep, test.args); err != nil {
t.Errorf("%s failed: %v", descr, err)
continue
}
got := out.(*bytes.Buffer).String()
if got != test.want {
t.Errorf("%s = %q, want %q", descr, got, test.want)
}
}
}
```
要注意的是测试代码和产品代码在同一个包。虽然是main包,也有对应的main入口函数,但是在测试的时候main包只是TestEcho测试函数导入的一个普通包,里面main函数并没有被导出,而是被忽略的。
通过将测试放到表格中,我们很容易添加新的测试用例。让我通过增加下面的测试用例来看看失败的情况是怎么样的:
```Go
{true, ",", []string{"a", "b", "c"}, "a b c\n"}, // NOTE: wrong expectation!
```
`go test`输出如下:
```
$ go test gopl.io/ch11/echo
--- FAIL: TestEcho (0.00s)
echo_test.go:31: echo(true, ",", ["a" "b" "c"]) = "a,b,c", want "a b c\n"
FAIL
FAIL gopl.io/ch11/echo 0.006s
```
错误信息描述了尝试的操作(使用Go类似语法),实际的结果和期望的结果。通过这样的错误信息,你可以在检视代码之前就很容易定位错误的原因。
要注意的是在测试代码中并没有调用log.Fatal或os.Exit,因为调用这类函数会导致程序提前退出;调用这些函数的特权应该放在main函数中。如果真的有意外的事情导致函数发生panic异常,测试驱动应该尝试用recover捕获异常,然后将当前测试当作失败处理。如果是可预期的错误,例如非法的用户输入、找不到文件或配置文件不当等应该通过返回一个非空的error的方式处理。幸运的是(上面的意外只是一个插曲),我们的echo示例是比较简单的也没有需要返回非空error的情况。
|
PHP
|
UTF-8
| 1,604
| 2.640625
| 3
|
[] |
no_license
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateActivitiesTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('activities', function(Blueprint $table)
{
$table->string('id', 36);
$table->integer('user_id')->unsigned();
$table->string('type');
$table->string('title');
$table->text('body');
$table->timestamp('starts_at');
$table->timestamp('ends_at');
$table->timestamps();
$table->primary('id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
$table->engine = 'InnoDB';
});
DB::unprepared('CREATE TRIGGER activities_insert_trigger
BEFORE INSERT ON activities
FOR EACH ROW
BEGIN
SET NEW.created_at = CURRENT_TIMESTAMP();
SET NEW.updated_at = CURRENT_TIMESTAMP();
END;
CREATE TRIGGER activities_update_trigger
BEFORE UPDATE ON activities
FOR EACH ROW
BEGIN
SET NEW.created_at = OLD.created_at;
SET NEW.updated_at = CURRENT_TIMESTAMP();
END;');
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('activities');
DB::unprepared('DROP TRIGGER IF EXISTS activities_insert_trigger;
DROP TRIGGER IF EXISTS activities_update_trigger;');
}
}
|
Java
|
UTF-8
| 223
| 2.140625
| 2
|
[] |
no_license
|
package feuchtwanger.weather;
import java.io.IOException;
public class WeatherMain {
public static void main(String[] args) throws IOException{
WeatherJFrame frame = new WeatherJFrame();
frame.setVisible(true);
}
}
|
Java
|
UTF-8
| 802
| 1.703125
| 2
|
[] |
no_license
|
package org.c2psi.gpointvente.services.facture.factureappro;
import org.c2psi.gpointvente.entities.facture.factureAppro.Factureappro;
import org.c2psi.gpointvente.entities.facture.factureAppro.Factureapproespece;
import org.c2psi.gpointvente.entities.produit.Arrivageparespece;
import java.util.Optional;
public interface FactureapproespeceService {
Optional<Factureapproespece> findFactureapproespeceByIdFactureapproespece(String idFactureapproespece);
Factureapproespece saveFactureapproespece(double montantAttendu, double montantverse,
Factureappro factureappro);
int addArrivageparespeceToFactureapproespece(Arrivageparespece arrivageparespece,
Factureapproespece factureapproespece);
}
|
Java
|
UTF-8
| 266
| 1.539063
| 2
|
[] |
no_license
|
package com.tmt.document.tb;
import com.sg.business.commons.dataset.AbstractTableDataSetFactory;
public class ProductProposalSet extends AbstractTableDataSetFactory {
@Override
protected String getDataEditorFieldName() {
return "product";
}
}
|
Python
|
UTF-8
| 586
| 2.890625
| 3
|
[
"MIT"
] |
permissive
|
from domHttpx.colors import Color
def tab():
print('\n')
def info(text):
print('[' + Color.CBLUE2 + 'INFO' + Color.ENDC + '] ' + text)
def success(text):
print('\n[' + Color.CGREEN2 + 'SUCCESS' + Color.ENDC + '] ' + text)
def error(text):
print('[' + Color.CRED2 + 'ERROR' + Color.ENDC + '] ' + text)
def title(title):
return f"[{Color.CCYAN2}{title}{Color.ENDC}]"
def sc_200(sc):
return f"[{Color.CGREEN2}{sc}{Color.ENDC}]"
def sc_500(sc):
return f"[{Color.CYELLOW2}{sc}{Color.ENDC}]"
def sc_other(sc):
return f"[{Color.CRED2}{sc}{Color.ENDC}]"
|
Markdown
|
UTF-8
| 2,867
| 2.828125
| 3
|
[
"MIT"
] |
permissive
|
# admob_banner_stabilizer
A package to use banner ads in firebase_admob package easily.

## Features
### Banner ads appear in the same position as the Widget
The build method of AdmobBannerWidget simply returns a Container, but an ad with the same height is placed exactly on the Container.
### Widget height and ad height match, so it's easy to layout
This ensures that the ad and the button do not overlap.
### When the widget is removed from the widget tree, the ad disappears
The ad itself can be treated as if it were in the widget. You don't have to write an additional process to remove the ad.
### Navigator is supported
When another page is pushed from above, the ad disappears.
### Supports changing the orientation of the device
If you change the orientation of the device, the ad will be erased first, and then reappear in the new position.
### No crashes after consecutive screen transitions
You can dispose this widget continuously.
## Getting Started
This package depends on the firebase_admob plugin.
Please read the linked pages carefully and complete the necessary preparations.
[Add Firebase to your Flutter app](https://firebase.google.com/docs/flutter/setup?hl=en)
[firebase_admob plugin](https://pub.dev/packages/firebase_admob)
If you just want to run examples, these preparations is not necessary.
## Usage
Initialize the firebase_admob plugin before use AdMobBannerWidget.
```dart
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await FirebaseAdMob.instance.initialize(
appId: Platform.isAndroid
// AdMob App ID for Firebase Demo Project (Flood-It!)
? 'ca-app-pub-8123415297019784~2664022459'
// test GADApplicationIdentifier. see https://developers.google.com/admob/ios/quick-start?hl=en
: 'ca-app-pub-3940256099942544~1458002511');
runApp(MyApp());
}
```
Place the AdMobBannerWidget where you want the ad to appear.
```dart
class MyApp extends StatelessWidget {
const MyApp();
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(),
body: AdMobBannerWidget(
adUnitId: BannerAd.testAdUnitId,
),
),
);
}
}
```
## Notes
### You cannot specify the size of the ads
The ad size will be the largest one that can be displayed within 1/8th of the height of the SafeArea.
AdMobBanner's SmartBanner standard is used as a reference.
### Ads cannot be moved as the widget is moved
They just appear and disappear.
You can't use it as a part of the list to scroll.
### You can't leave an ad running behind the scenes
It only calculates the position of the widget and puts the ad in front of it. You can't hide ads.
|
Python
|
UTF-8
| 134
| 2.640625
| 3
|
[] |
no_license
|
l=[1,2,2,6,6,6,6,7,10]
a=l.count(6)
print(a)
print(0.25*len(l))
for i in l:
if (l.count(i)>.25*len(l)):
print(i)
break
|
C++
|
UTF-8
| 1,422
| 2.78125
| 3
|
[
"BSL-1.0"
] |
permissive
|
// Author(s): Wieger Wesselink
// Copyright: see the accompanying file COPYING or copy at
// https://svn.win.tue.nl/trac/MCRL2/browser/trunk/COPYING
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
/// \file text_utility_test.cpp
/// \brief Add your file description here.
#include <boost/test/minimal.hpp>
#include "mcrl2/utilities/text_utility.h"
using namespace mcrl2;
std::string TEXT1 =
"abc % afdsd \n"
"% \n"
"% \n"
"ddasdfsd%adsfs%-\n"
;
std::string TEXT2 =
"abc \n"
"\n"
"\n"
"ddasdfsd\n"
;
void test_remove_comments()
{
std::string text = utilities::remove_comments(TEXT1);
BOOST_CHECK(text == TEXT2);
}
std::string TEXT3 =
"abcdef gh \n"
"c\n"
"\n"
"abcde ghi"
;
std::string TEXT4 =
"abcde\n"
"f gh\n"
"c\n"
"\n"
"abcde\n"
"ghi"
;
void test_word_wrap()
{
std::string text = utilities::word_wrap_text(TEXT3, 5);
BOOST_CHECK(text == TEXT4);
}
void test_number2string()
{
BOOST_CHECK(utilities::number2string(0) == "0");
BOOST_CHECK(utilities::number2string(1) == "1");
BOOST_CHECK(utilities::number2string(10) == "10");
BOOST_CHECK(utilities::number2string(123456789) == "123456789");
}
int test_main(int, char*[])
{
test_remove_comments();
test_word_wrap();
test_number2string();
return 0;
}
|
JavaScript
|
UTF-8
| 2,751
| 3.09375
| 3
|
[] |
no_license
|
// TODO: Paste the Firebase initialization code first
// Initialize Firebase
var config = {
apiKey: "AIzaSyAvqFB4q2j7ZektW6_wvSk_4c2zm3odccc",
authDomain: "fir-project-7fa52.firebaseapp.com",
databaseURL: "https://fir-project-7fa52.firebaseio.com",
storageBucket: "",
};
firebase.initializeApp(config);
// TODO: Your code below
/*firebase.database().ref('tasks/').push({
title: 'Learn CRUD',
done: true
});
firebase.database().ref('tasks/').set({
abc123: {
title: 'Overwrite data',
done: true
}
});
firebase.database().ref('tasks/xyz890/').set({
title: 'Set new data',
done: true
});
firebase.database().ref('tasks/xyz890').update({
title: 'Updated value'
});
firebase.database().ref('tasks/xyz890').remove()
firebase.database().ref('tasks/abc123').remove()
*/
delegate("body","click","#add",(event) => {
var inputId=document.querySelector("#new-item");
var inputValue=inputId.value;
firebase.database().ref('tasks/').push({
listItem: inputValue,
checkedData: false
});
})
var container=document.querySelector(".container");
var buttonContainer=document.querySelector(".buttonContainer")
renderInput(buttonContainer)
/*render input button area*/
function renderInput(into){
into.innerHTML = `
<input type="text" id="new-item" />
<button id="add">Add</button>
<button id="delete">Delete</button>
`
}
function renderList(listData, into){
if (listData != null && listData !==''){
var listItemData=Object.keys(listData).map((key)=>{
return `${renderListItem(listData[key].listItem)}`
}).join('')
}
into.innerHTML=`
<ul>
${listItemData}
</ul>
`
}
function renderListItem(listItem){
return `
<li><input type="checkbox" class="checkboxClass" data-label="${listItem}">${listItem}</li>
`
}
firebase.database().ref('tasks/').on('value', function(snapshot) {
var data=snapshot.val();
if (data != null && data !==''){
renderList(data, container);
}
delegate(".container","click","input.checkboxClass",(event) => {
if(event.target.checked){
Object.keys(data).map((itemKey)=>{
if(event.target.getAttribute('data-label')==data[itemKey].listItem){
firebase.database().ref('tasks/'+itemKey).update({
checkedData: true
});
}
});
}else{
Object.keys(data).map((itemKey)=>{
if(event.target.getAttribute('data-label')==data[itemKey].listItem){
firebase.database().ref('tasks/'+itemKey).update({
checkedData: false
});
}
});
}
});
delegate(".buttonContainer","click","#delete",(event) => {
if (data != null && data !==''){
Object.keys(data).map((itemKey)=>{
var dataResult=data[itemKey];
if(dataResult){
if(dataResult.checkedData){
firebase.database().ref('tasks/'+itemKey).remove()
}
}
});
}
});
});
|
JavaScript
|
UTF-8
| 1,269
| 2.609375
| 3
|
[
"Apache-2.0"
] |
permissive
|
export function Readme({ asyncapi, params }) {
return `# ${asyncapi.info().title()}
${asyncapi.info().description()}
## Install Maven
For instructions on installing maven for your operating system, please see the [Apache Maven site](https://maven.apache.org/install.html).
## Running the Publisher/Subscriber template
These commands will allow you to run the template publisher/subscriber model using IBM MQ.
1. Install dependencies
\`\`\`sh
mvn compile
\`\`\`
This command uses maven to install all the required dependences needed for this template to run.
2. Create .jar package
\`\`\`sh
mvn package
\`\`\`
Using maven generate the .jar file to run.
3. Run Publisher
\`\`\`sh
java -cp target/asyncapi-java-generator-0.1.0.jar: ${params.package}.DemoProducer
\`\`\`
This command runs the publisher function of this template from the generated .jar file.
4. In a seperate terminal, Run Subscriber
\`\`\`sh
java -cp target/asyncapi-java-generator-0.1.0.jar: ${params.package}.DemoSubscriber
\`\`\`
This command runs the subscriber function of this template from the generated .jar file.
The messages should now be sent from the running publisher to the running subscriber, using MQ topics.
`;
}
|
C#
|
UTF-8
| 3,796
| 2.546875
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace OnixLibrary.CustomControls
{
public partial class FlatOnix : UserControl
{
private string _Texto;
private Image _Imagen;
public FlatOnix()
{
InitializeComponent();
}
GraphicsPath GetRoundPath(RectangleF Rect, int radius)
{
float r2 = radius / 2f;
GraphicsPath GraphPath = new GraphicsPath();
GraphPath.AddArc(Rect.X, Rect.Y, radius, radius, 180, 90);
GraphPath.AddLine(Rect.X + r2, Rect.Y, Rect.Width - r2, Rect.Y);
GraphPath.AddArc(Rect.X + Rect.Width - radius, Rect.Y, radius, radius, 270, 90);
GraphPath.AddLine(Rect.Width, Rect.Y + r2, Rect.Width, Rect.Height - r2);
GraphPath.AddArc(Rect.X + Rect.Width - radius,
Rect.Y + Rect.Height - radius, radius, radius, 0, 90);
GraphPath.AddLine(Rect.Width - r2, Rect.Height, Rect.X + r2, Rect.Height);
GraphPath.AddArc(Rect.X, Rect.Y + Rect.Height - radius, radius, radius, 90, 90);
GraphPath.AddLine(Rect.X, Rect.Height - r2, Rect.X, Rect.Y + r2);
GraphPath.CloseFigure();
return GraphPath;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
RectangleF Rect = new RectangleF(0, 0, this.Width, this.Height);
using ( GraphicsPath GraphPath = GetRoundPath(Rect, 50))
{
this.Region = new Region(GraphPath);
using (Pen pen = new Pen(Color.White, 3.75f))
{
pen.Alignment = PenAlignment.Inset;
e.Graphics.DrawPath(pen, GraphPath);
}
}
}
protected override void OnMouseEnter(EventArgs e)
{
base.OnMouseEnter(e);
cambiarColores(true);
}
private void cambiarColores(bool onHover)
{
if (onHover)
{
if (this.BackColor != Color.FromArgb(255, 100, 83))
{
this.BackColor = Color.FromArgb(255, 100, 83);
}
}
else
{
this.BackColor = Color.Coral;
}
}
protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseLeave(e);
cambiarColores(false);
}
public Image Imagen {
get { return this._Imagen; }
set { _Imagen = value;
foto.Image = Imagen;
}
}
public string Texto {
get{ return this._Texto; }
set {_Texto = value;
labelmenu.Text = Texto;
}
}
private void foto_MouseEnter(object sender, EventArgs e)
{
cambiarColores(true);
}
private void labelmenu_MouseEnter(object sender, EventArgs e)
{
cambiarColores(true);
}
private void foto_MouseLeave(object sender, EventArgs e)
{
cambiarColores(false);
}
private void labelmenu_MouseLeave(object sender, EventArgs e)
{
cambiarColores(false);
}
private void foto_Click(object sender, EventArgs e)
{
}
protected override void OnClick(EventArgs e)
{
base.OnClick(e);
}
private void labelmenu_Click(object sender, EventArgs e)
{
}
}
}
|
C#
|
UTF-8
| 660
| 2.734375
| 3
|
[] |
no_license
|
using System;
using System.Globalization;
using Xamarin.Forms;
namespace TodoList.Converters
{
public class StatusToSymbol : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var isDone = (bool) value;
var isDoneString = "";
if (!isDone) return isDoneString;
isDoneString = ((char)0x2713).ToString();
return isDoneString;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
|
C#
|
UTF-8
| 1,715
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
using System;
using System.Windows.Input;
namespace PremiseWebClient {
public class PremiseCommand : ICommand {
private string _propertyName;
private dynamic _holdingObject;
public PremiseCommand(PremiseObject holdingObject, string propertyName) {
_holdingObject = holdingObject;
_propertyName = propertyName;
}
public string PropertyName {
get { return _propertyName; }
set {
_propertyName = value;
if (_holdingObject != null && !String.IsNullOrEmpty(_propertyName)) {
OnCanExecuteChanged();
}
}
}
public PremiseObject HoldingObject {
get { return _holdingObject; }
set {
_holdingObject = value;
if (_holdingObject != null && !String.IsNullOrEmpty(_propertyName)) {
OnCanExecuteChanged();
}
}
}
public bool CanExecute(object parameter) {
return _holdingObject != null
&& !String.IsNullOrEmpty(_propertyName)
&& PremiseServer.Instance.Connected;
}
public void Execute(object parameter) {
if (_holdingObject != null && !String.IsNullOrEmpty(_propertyName))
_holdingObject.SetMember(_propertyName, true);
}
public event EventHandler CanExecuteChanged;
protected virtual void OnCanExecuteChanged() {
EventHandler handler = CanExecuteChanged;
if (handler != null) handler(this, new EventArgs());
}
}
}
|
JavaScript
|
UTF-8
| 1,606
| 2.546875
| 3
|
[] |
no_license
|
import Api from 'services/api';
const initialState = {
loading: false,
error: false,
result: {
categories: [],
products: [],
},
};
const actionTypes = {
FETCH_SEARCH_PENDING: 'app/search/FETCH_SEARCH_PENDING',
FETCH_SEARCH_SUCCESS: 'app/search/FETCH_SEARCH_SUCCESS',
FETCH_SEARCH_ERROR: 'app/search/FETCH_SEARCH_ERROR',
};
const { FETCH_SEARCH_PENDING, FETCH_SEARCH_SUCCESS, FETCH_SEARCH_ERROR } = actionTypes;
const fetchSearchPending = () => ({
type: FETCH_SEARCH_PENDING,
});
const fetchSearchSuccess = (payload) => ({
type: FETCH_SEARCH_SUCCESS,
payload,
});
const fetchSearchError = () => ({
type: FETCH_SEARCH_ERROR,
});
const reducer = (state = initialState, action) => {
switch (action.type) {
case FETCH_SEARCH_PENDING: {
return {
...state,
loading: true,
};
}
case FETCH_SEARCH_SUCCESS: {
const result = {
categories: action.payload.categories || [],
products: action.payload.items || [],
};
return {
...state,
result,
error: false,
loading: false,
};
}
case FETCH_SEARCH_ERROR: {
return {
...state,
error: true,
loading: false,
};
}
default:
return state;
}
};
const fetchSearch = (q) => {
const { getProducts } = new Api();
return async (dispatch) => {
dispatch(fetchSearchPending());
try {
const result = await getProducts(q);
dispatch(fetchSearchSuccess(result));
} catch (e) {
dispatch(fetchSearchError());
}
};
};
export { initialState, fetchSearch, actionTypes };
export default reducer;
|
C++
|
UTF-8
| 606
| 2.984375
| 3
|
[
"Unlicense"
] |
permissive
|
//
//
//
/// @brief A private member function to set zero all the
/// current rank's length and the @c data pointer to @c
/// NULL. Its usage is highly recommended just after any
/// delete or move operation of the data members.
//
/// @return None.
//
inline void clear_internals()
{
#if CURRENT_RANK == 1
{
data = NULL;
rank1 = 0;
}
#elif CURRENT_RANK == 2
{
data = NULL;
rank1 = rank2 = 0;
}
#elif CURRENT_RANK == 3
{
data = NULL;
rank1 = rank2 = rank3 = 0;
}
#elif CURRENT_RANK == 4
{
data = NULL;
rank1 = rank2 = rank3 = rank4 = 0;
}
#else
{
data = NULL;
}
#endif
};
|
C++
|
UTF-8
| 1,772
| 2.984375
| 3
|
[] |
no_license
|
// ------------------------------------------------ ROBUS KIDSY -------------------------------------------------
// EJEMPLO DE USO DEL NEOPIXEL
// Este ejemplo es de uso libre y esta pensado para dar una introduccion al hardware del robot Robus Kidsy.
// Autor: Fabian Alfonso Flores
// Empresa: Proyectil Mx
// Fecha: 17 de febrero de 2020
// --------------------------------------------------------------------------------------------------------------
#include<RobusKidsy.h>
Robus Kidsy; // Declara una instancia tipo Kidsy, llamada de igual forma
void setup() {
Serial.begin(115200); // Inicializa comunicacion serial a 115200 baudios
Kidsy.begin(); // Inicializa el hardware del Robus Kidsy
}
void loop() {
// Si se presiona boton A, Neopixel en modo arcoiris con una separacion de 15ms entre cada cambio de tono
if(Kidsy.ButtonA.read() == PRESSED) {
Kidsy.Neopixel.rainbow(15);
Kidsy.Neopixel.off(); // despues del efecto apaga Neopixel
}
// Si se presiona boton B, Neopixel en color aleatorio rojo verde azul
if(Kidsy.ButtonB.read() == PRESSED) Kidsy.Neopixel.color(random(0,255), random(0,255), random(0,255));
// Si se presiona flecha Arriba, efecto de latido en color rojo
if(Kidsy.ArrowUp.readDigital() == TOUCHED) Kidsy.Neopixel.heartBeat(RED);
// Si se presiona flecha Abajo, efecto de latido en color verde
if(Kidsy.ArrowDown.readDigital() == TOUCHED) Kidsy.Neopixel.heartBeat(GREEN);
// Si se preiona flecha Izquierda, efecto de latido en color azul
if(Kidsy.ArrowLeft.readDigital() == TOUCHED) Kidsy.Neopixel.heartBeat(BLUE);
// Si se presiona flecha Derecha, efecto de latido en color Magenta
if(Kidsy.ArrowRight.readDigital() == TOUCHED) Kidsy.Neopixel.heartBeat(MAGENTA);
}
|
PHP
|
UTF-8
| 2,252
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use App\Utils\Utils;
use Illuminate\Support\Facades\Hash;
use Validator;
class UserController extends Controller
{
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|unique:users|max:20',
'password' => 'required|min:6'
]);
if ($validator->fails()) {
return Utils::err($validator->errors()->first());
}
$user = new User();
$user->name = $request->name;
$user->password = Hash::make($request->password);
if ($user->save()) {
return Utils::suc('register success!');
}
return Utils::err('register failed!');
}
public function login(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required',
'password' => 'required'
]);
if ($validator->fails()) {
return Utils::err($validator->errors()->first());
}
if (!$user = User::where('name', $request->name)->first()) {
return Utils::err('username not found, register first?');
}
if (!Hash::check($request->password, $user->password)) {
return Utils::err('password incorrect!');
}
$request->session()->put('user_id', $user->id);
return Utils::suc($user->id);
}
public function is_login()
{
return Utils::suc(session('user_id') ? session('user_id') : 0);
}
public function logout(Request $request)
{
$request->session()->forget('user_id');
return Utils::suc('logout success!');
}
public function user($id)
{
$user = User::select(['id', 'name', 'email', 'created_at'])->find($id);
return $user;
}
public function questions($id)
{
$user = User::find($id);
$questions = $user->questions()->orderBy('created_at', 'desc')->get();
return $questions;
}
public function answers($id)
{
$user = User::find($id);
$answers = $user->answers()->orderBy('created_at', 'desc')->get();
return $answers;
}
}
|
Python
|
UTF-8
| 422
| 3.859375
| 4
|
[] |
no_license
|
#05-019.py
class SimpleA:
value = 0
def add (self, a, b):
return a+b
def sub (self, a, b):
return a-b
s = SimpleA()
print(s.add(20, 10))
print(s.sub(20, 10))
fadd = lambda self, a, b : a+b
fsub = lambda self, a, b : a-b
members = {'value' : 0, 'add' : fadd, 'sub' : fsub }
SimpleB = type('B', (object,), members)
s = SimpleB()
print(s.add(20, 10))
print(s.sub(20, 10))
|
C
|
UTF-8
| 461
| 3.1875
| 3
|
[] |
no_license
|
#include<stdio.h>
#include<math.h>
int abs(int n)
{
if(n<0)
return -n;
return n;
}
int main()
{
int n,i,max=0,j,a;
scanf("%d",&n);
int ara[n];
for(i=0;i<n;i++)
{
scanf("%d",&ara[i]);
}
for(i=0;i<n-1;i++)
{
a=0;
for(j=i;j<n-1;j++)
{
a=a+abs(ara[j]-ara[j+1])*pow(-1,j-i);
if(max<a)
max=a;
}
}
printf("%d",max);
return 0;
}
|
C++
|
UTF-8
| 1,003
| 2.796875
| 3
|
[] |
no_license
|
#include "SerialJson.h"
void SerialJson::init(int bps){
Serial.begin(bps);
}
String SerialJson::getJson(){
return _incomingMessage;
}
bool SerialJson::isThereNewJson(){
bool result = false;
_incomingMessage = "";
_bracketCount = 0;
if (Serial.available() > 0) {
unsigned long previousMillis = millis();
do {
Serial.flush();
_incomingByte = Serial.read();
_incomingChar = char(_incomingByte);
_incomingMessage += char(_incomingByte);
if (_incomingChar == '{') {
_bracketCount++;
result = true;
}
if (_incomingChar == '}') _bracketCount--;
// say what you got:
Serial.print(".");
Serial.flush();
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= _interval ) {
Serial.println("[Timeout]");
result = false;
_incomingMessage = "";
break;
}
} while (_bracketCount > 0);
return result;
}
}
|
C#
|
UTF-8
| 1,977
| 2.921875
| 3
|
[] |
no_license
|
namespace Faktura.GUI
{
/// <summary>
/// This is class for managing all the windows in the application.
/// </summary>
class WindowManager
{
// Window's fields are static because the general in concern is
// that there can be only one instance of each window class.
// Upon accessing window's class properties if any given
// window has not been created yet it is created first.
// Upon closing coresponding window's field is set to null
// to avoid exceptions thrown by using window's class with
// deallocated resources.
private static InvoiceSettingsWindow _InvoiceSettingsWin;
public InvoiceSettingsWindow InvoiceSettingsWin
{
get
{
if (null == _InvoiceSettingsWin)
{
_InvoiceSettingsWin = new InvoiceSettingsWindow();
_InvoiceSettingsWin.Closed += (sender, e) => { _InvoiceSettingsWin = null; };
}
return _InvoiceSettingsWin;
}
}
private static CompanySettingsWindow _CompanySettingsWin;
public CompanySettingsWindow CompanySettingsWin
{
get
{
if (null == _CompanySettingsWin)
{
_CompanySettingsWin = new CompanySettingsWindow();
_CompanySettingsWin.Closed += (sender, e) => { _CompanySettingsWin = null; };
}
return _CompanySettingsWin;
}
}
private static MainWindow _MainWindow;
public MainWindow MainWin
{
get
{
if (null == _MainWindow)
{
_MainWindow = new MainWindow();
_MainWindow.Closed += (sender, e) => { _MainWindow = null; };
}
return _MainWindow;
}
}
}
}
|
Python
|
UTF-8
| 969
| 2.78125
| 3
|
[] |
no_license
|
from datetime import timedelta
class abstractTime:
def __init__(self,item):
self.item=item
class newTime(abstractTime):
def time(self):
objc={}
objc['hours']=houer(self.item)
objc['minutes'] = minutes(self.item)
objc['weeks'] = weeks(self.item)
objc['days'] = weeks(self.item)
objc['seconds'] = weeks(self.item)
return objc[self.item.cyclycetype.name].setTime()
class houer(abstractTime):
def setTime(self):
return timedelta(hours=self.item.cyclycetvalue)
class minutes(abstractTime):
def setTime(self):
return timedelta(minutes=self.item.cyclycetvalue)
class weeks(abstractTime):
def setTime(self):
return timedelta(weeks=self.item.cyclycetvalue)
class days(abstractTime):
def setTime(self):
return timedelta(days=self.item.cyclycetvalue)
class seconds(abstractTime):
def setTime(self):
return timedelta(seconds=self.item.cyclycetvalue)
|
Java
|
UTF-8
| 171
| 1.75
| 2
|
[] |
no_license
|
package cz.system.police.services;
import cz.system.police.data.RadarData;
public interface ReceiveDataService {
Long checkAndStoreDataFromRadar(RadarData data);
}
|
Markdown
|
UTF-8
| 545
| 3.03125
| 3
|
[
"MIT"
] |
permissive
|
# ArrayUtility.Clone<T> method
Clones the specified array.
```csharp
public static T[] Clone<T>(T[] array)
```
| parameter | description |
| --- | --- |
| array | The array to clone. |
## Return Value
A clone of the specified array.
## Remarks
This method is merely useful in avoiding the cast that is otherwise necessary when calling Clone.
## See Also
* class [ArrayUtility](../ArrayUtility.md)
* namespace [Faithlife.Utility](../../Faithlife.Utility.md)
<!-- DO NOT EDIT: generated by xmldocmd for Faithlife.Utility.dll -->
|
Markdown
|
UTF-8
| 501
| 2.515625
| 3
|
[] |
no_license
|
---
layout: post
status: publish
date: 2010-07-20 03:09:50+00:00
title: The creativity crisis (Newsweek) « Scott Berkun
link: http://www.scottberkun.com/blog/2010/the-creativity-crisis-newsweek/
type: aside
categories:
- creativity
- culture
- education
- scott berkun
---
Scott Berkun reflects on the American creativity crisis as Newsweek reported it. He takes a look at a story that seemed to give hope, and then reminds us of its implications for the way we teach, do, and reward teachers in our country.
|
Markdown
|
UTF-8
| 22,968
| 2.609375
| 3
|
[
"BSD-2-Clause",
"LGPL-3.0-only",
"LGPL-2.1-only",
"W3C",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
---
title: DocxConverter Attributes Conversion Spec
author: Vladimir Schneider
version: 1.0
date: '2019-11-15'
license: '[CC-BY-SA 4.0](http://creativecommons.org/licenses/by-sa/4.0/)'
...
---
# DocxConverter
## Form Controls
### Text
text, class name `.text`
attributes:
* `name` - name for the form field
* `default` - default value
* `help` - text to show in status bar and on hitting F1
* `max-length` - number or leave out for unlimited
* `type`
* `regular` - default, regular text
* `format` - "UPPERCASE", "LOWERCASE", "FIRST CAPITAL", "TITLE CASE", case not sensitive,
space between words can be eliminated or replaced by `-`
* `date` - date
* `format` - word date format
* `number` - number
* `format` - word number format
* `current-date` - current date
* `format` - word date format
* `current-time` - current time
* `format` - word time format
#### Regular
```````````````````````````````` example(Form Controls - Text - Regular: 1) options(form-controls-input)
Text: [input]{.text default=test}
.
<w:body>
<w:p>
<w:pPr>
<w:pStyle w:val="ParagraphTextBody"/>
</w:pPr>
<w:r>
<w:t xml:space="preserve">Text: </w:t>
</w:r>
<w:r>
<w:fldChar w:fldCharType="begin">
<w:ffData>
<w:name w:val="Text1"/>
<w:enabled/>
<w:calcOnExit w:val="false"/>
<w:textInput>
<w:type w:val="regular"/>
<w:default w:val="test"/>
</w:textInput>
</w:ffData>
</w:fldChar>
</w:r>
<w:r>
<w:instrText xml:space="preserve"> FORMTEXT </w:instrText>
</w:r>
<w:r>
<w:fldChar w:fldCharType="separate"/>
</w:r>
<w:r>
<w:rPr>
<w:noProof/>
</w:rPr>
<w:t>test</w:t>
</w:r>
<w:r>
<w:fldChar w:fldCharType="end"/>
</w:r>
</w:p>
</w:body>
````````````````````````````````
```````````````````````````````` example(Form Controls - Text - Regular: 2) options(form-controls-form)
Text: [form]{.text default=test}
.
<w:body>
<w:p>
<w:pPr>
<w:pStyle w:val="ParagraphTextBody"/>
</w:pPr>
<w:r>
<w:t xml:space="preserve">Text: </w:t>
</w:r>
<w:r>
<w:fldChar w:fldCharType="begin">
<w:ffData>
<w:name w:val="Text1"/>
<w:enabled/>
<w:calcOnExit w:val="false"/>
<w:textInput>
<w:type w:val="regular"/>
<w:default w:val="test"/>
</w:textInput>
</w:ffData>
</w:fldChar>
</w:r>
<w:r>
<w:instrText xml:space="preserve"> FORMTEXT </w:instrText>
</w:r>
<w:r>
<w:fldChar w:fldCharType="separate"/>
</w:r>
<w:r>
<w:rPr>
<w:noProof/>
</w:rPr>
<w:t>test</w:t>
</w:r>
<w:r>
<w:fldChar w:fldCharType="end"/>
</w:r>
</w:p>
</w:body>
````````````````````````````````
```````````````````````````````` example(Form Controls - Text - Regular: 3) options(form-controls-input)
Text: [input]{.text default=test help="Help String for field"}
.
<w:body>
<w:p>
<w:pPr>
<w:pStyle w:val="ParagraphTextBody"/>
</w:pPr>
<w:r>
<w:t xml:space="preserve">Text: </w:t>
</w:r>
<w:r>
<w:fldChar w:fldCharType="begin">
<w:ffData>
<w:name w:val="Text1"/>
<w:enabled/>
<w:calcOnExit w:val="false"/>
<w:helpText w:type="text" w:val="Help String for field"/>
<w:statusText w:type="text" w:val="Help String for field"/>
<w:textInput>
<w:type w:val="regular"/>
<w:default w:val="test"/>
</w:textInput>
</w:ffData>
</w:fldChar>
</w:r>
<w:r>
<w:instrText xml:space="preserve"> FORMTEXT </w:instrText>
</w:r>
<w:r>
<w:fldChar w:fldCharType="separate"/>
</w:r>
<w:r>
<w:rPr>
<w:noProof/>
</w:rPr>
<w:t>test</w:t>
</w:r>
<w:r>
<w:fldChar w:fldCharType="end"/>
</w:r>
</w:p>
</w:body>
````````````````````````````````
#### Number
```````````````````````````````` example(Form Controls - Text - Number: 1) options(form-controls-input)
Number: [input]{.text type=number format=#,##0}
.
<w:body>
<w:p>
<w:pPr>
<w:pStyle w:val="ParagraphTextBody"/>
</w:pPr>
<w:r>
<w:t xml:space="preserve">Number: </w:t>
</w:r>
<w:r>
<w:fldChar w:fldCharType="begin">
<w:ffData>
<w:name w:val="Number1"/>
<w:enabled/>
<w:calcOnExit w:val="false"/>
<w:textInput>
<w:type w:val="number"/>
<w:default w:val="0"/>
<w:format w:val="#,##0"/>
</w:textInput>
</w:ffData>
</w:fldChar>
</w:r>
<w:r>
<w:instrText xml:space="preserve"> FORMTEXT </w:instrText>
</w:r>
<w:r>
<w:fldChar w:fldCharType="separate"/>
</w:r>
<w:r>
<w:rPr>
<w:noProof/>
</w:rPr>
<w:t>0</w:t>
</w:r>
<w:r>
<w:fldChar w:fldCharType="end"/>
</w:r>
</w:p>
</w:body>
````````````````````````````````
#### Date
```````````````````````````````` example(Form Controls - Text - Date: 1) options(form-controls-input, IGNORED)
Date No Default: [input]{.text type=date format=yyyy/M/d}
.
<w:body>
<w:p>
<w:pPr>
<w:pStyle w:val="ParagraphTextBody"/>
</w:pPr>
<w:r>
<w:t xml:space="preserve">Date No Default: </w:t>
</w:r>
<w:r>
<w:fldChar w:fldCharType="begin">
<w:ffData>
<w:name w:val="Date1"/>
<w:enabled/>
<w:calcOnExit w:val="false"/>
<w:textInput>
<w:type w:val="date"/>
<w:default w:val="2001/9/11"/>
<w:format w:val="yyyy/M/d"/>
</w:textInput>
</w:ffData>
</w:fldChar>
</w:r>
<w:r>
<w:instrText xml:space="preserve"> FORMTEXT </w:instrText>
</w:r>
<w:r>
<w:fldChar w:fldCharType="separate"/>
</w:r>
<w:r>
<w:rPr>
<w:noProof/>
</w:rPr>
<w:t>2001/9/11</w:t>
</w:r>
<w:r>
<w:fldChar w:fldCharType="end"/>
</w:r>
</w:p>
</w:body>
````````````````````````````````
```````````````````````````````` example(Form Controls - Text - Date: 2) options(form-controls-input, IGNORED)
Date: [input]{.text type=date default=2019/11/11 format=yyyy/M/d}
.
<w:body>
<w:p>
<w:pPr>
<w:pStyle w:val="ParagraphTextBody"/>
</w:pPr>
<w:r>
<w:t xml:space="preserve">Date: </w:t>
</w:r>
<w:r>
<w:fldChar w:fldCharType="begin">
<w:ffData>
<w:name w:val="Date1"/>
<w:enabled/>
<w:calcOnExit w:val="false"/>
<w:textInput>
<w:type w:val="date"/>
<w:default w:val="2019/11/11"/>
<w:format w:val="yyyy/M/d"/>
</w:textInput>
</w:ffData>
</w:fldChar>
</w:r>
<w:r>
<w:instrText xml:space="preserve"> FORMTEXT </w:instrText>
</w:r>
<w:r>
<w:fldChar w:fldCharType="separate"/>
</w:r>
<w:r>
<w:rPr>
<w:noProof/>
</w:rPr>
<w:t>2019/11/11</w:t>
</w:r>
<w:r>
<w:fldChar w:fldCharType="end"/>
</w:r>
</w:p>
</w:body>
````````````````````````````````
#### Current Date
```````````````````````````````` example(Form Controls - Text - Current Date: 1) options(form-controls-input, IGNORED)
Current Date: [input]{.text type=current-date format=yyyy/M/d}
.
<w:body>
<w:p>
<w:pPr>
<w:pStyle w:val="ParagraphTextBody"/>
</w:pPr>
<w:r>
<w:t xml:space="preserve">Current Date: </w:t>
</w:r>
<w:r>
<w:fldChar w:fldCharType="begin">
<w:ffData>
<w:name w:val="CurrentDate1"/>
<w:enabled/>
<w:calcOnExit w:val="false"/>
<w:textInput>
<w:type w:val="currentTime"/>
<w:default w:val="2001/9/11"/>
<w:format w:val="yyyy/M/d"/>
</w:textInput>
</w:ffData>
</w:fldChar>
</w:r>
<w:r>
<w:instrText xml:space="preserve"> FORMTEXT </w:instrText>
</w:r>
<w:r>
<w:fldChar w:fldCharType="begin"/>
</w:r>
<w:r>
<w:instrText xml:space="preserve"> DATE \@ "yyyy/M/d" </w:instrText>
</w:r>
<w:r>
<w:fldChar w:fldCharType="separate"/>
</w:r>
<w:r>
<w:rPr>
<w:noProof/>
</w:rPr>
<w:instrText>2001/9/11</w:instrText>
</w:r>
<w:r>
<w:fldChar w:fldCharType="end"/>
</w:r>
<w:r>
<w:fldChar w:fldCharType="separate"/>
</w:r>
<w:r>
<w:rPr>
<w:noProof/>
</w:rPr>
<w:t>2001/9/11</w:t>
</w:r>
<w:r>
<w:fldChar w:fldCharType="end"/>
</w:r>
</w:p>
</w:body>
````````````````````````````````
#### Current Time
```````````````````````````````` example(Form Controls - Text - Current Time: 1) options(form-controls-input, IGNORED)
Current Time: [input]{.text type=current-time format=hh:mm:ss}
.
<w:body>
<w:p>
<w:pPr>
<w:pStyle w:val="ParagraphTextBody"/>
</w:pPr>
<w:r>
<w:t xml:space="preserve">Current Time: </w:t>
</w:r>
<w:r>
<w:fldChar w:fldCharType="begin">
<w:ffData>
<w:name w:val="CurrentTime1"/>
<w:enabled/>
<w:calcOnExit w:val="false"/>
<w:textInput>
<w:type w:val="currentDate"/>
<w:default w:val="09:46:40"/>
<w:format w:val="hh:mm:ss"/>
</w:textInput>
</w:ffData>
</w:fldChar>
</w:r>
<w:r>
<w:instrText xml:space="preserve"> FORMTEXT </w:instrText>
</w:r>
<w:r>
<w:fldChar w:fldCharType="begin"/>
</w:r>
<w:r>
<w:instrText xml:space="preserve"> TIME \@ "hh:mm:ss" </w:instrText>
</w:r>
<w:r>
<w:fldChar w:fldCharType="separate"/>
</w:r>
<w:r>
<w:rPr>
<w:noProof/>
</w:rPr>
<w:instrText>09:46:40</w:instrText>
</w:r>
<w:r>
<w:fldChar w:fldCharType="end"/>
</w:r>
<w:r>
<w:fldChar w:fldCharType="separate"/>
</w:r>
<w:r>
<w:rPr>
<w:noProof/>
</w:rPr>
<w:t>09:46:40</w:t>
</w:r>
<w:r>
<w:fldChar w:fldCharType="end"/>
</w:r>
</w:p>
</w:body>
````````````````````````````````
### Checkbox
class name `.checkbox`
* `name` - name for the form field
* `checked` - default will be checked, otherwise unchecked
* `help` - text to show in status bar and on hitting F1
```````````````````````````````` example(Form Controls - Checkbox: 1) options(form-controls-input)
Trial: [input]{.checkbox name="Trial"}
.
<w:body>
<w:p>
<w:pPr>
<w:pStyle w:val="ParagraphTextBody"/>
</w:pPr>
<w:r>
<w:t xml:space="preserve">Trial: </w:t>
</w:r>
<w:r>
<w:fldChar w:fldCharType="begin">
<w:ffData>
<w:name w:val="Trial"/>
<w:enabled/>
<w:calcOnExit w:val="false"/>
<w:checkBox>
<w:sizeAuto/>
<w:default w:val="false"/>
</w:checkBox>
</w:ffData>
</w:fldChar>
</w:r>
<w:r>
<w:instrText xml:space="preserve"> FORMCHECKBOX </w:instrText>
</w:r>
<w:r>
<w:fldChar w:fldCharType="end"/>
</w:r>
</w:p>
</w:body>
````````````````````````````````
```````````````````````````````` example(Form Controls - Checkbox: 2) options(form-controls-input)
Checked: [input]{.checkbox checked}
.
<w:body>
<w:p>
<w:pPr>
<w:pStyle w:val="ParagraphTextBody"/>
</w:pPr>
<w:r>
<w:t xml:space="preserve">Checked: </w:t>
</w:r>
<w:r>
<w:fldChar w:fldCharType="begin">
<w:ffData>
<w:name w:val="Check1"/>
<w:enabled/>
<w:calcOnExit w:val="false"/>
<w:checkBox>
<w:sizeAuto/>
<w:default w:val="true"/>
</w:checkBox>
</w:ffData>
</w:fldChar>
</w:r>
<w:r>
<w:instrText xml:space="preserve"> FORMCHECKBOX </w:instrText>
</w:r>
<w:r>
<w:fldChar w:fldCharType="end"/>
</w:r>
</w:p>
</w:body>
````````````````````````````````
### Dropdown
class name `.dropdown`
* `name` - name for the form field
* `default` - default selection first item if no default provided. Can be option text (case
sensitive tried first, if no match then case insensitive is tried), if text match fails then
attempted to parse as an integer index 1..number of options
* `help` - text to show in status bar and on hitting F1
* `options` - list of options separated by `|`, individual options will be trimmed but otherwise
left as is
```````````````````````````````` example(Form Controls - Dropdown: 1) options(form-controls-input)
No Default: [input]{.dropdown options="Item 1 | Item 2 | Item 3"}
.
<w:body>
<w:p>
<w:pPr>
<w:pStyle w:val="ParagraphTextBody"/>
</w:pPr>
<w:r>
<w:t xml:space="preserve">No Default: </w:t>
</w:r>
<w:r>
<w:fldChar w:fldCharType="begin">
<w:ffData>
<w:name w:val="Dropdown1"/>
<w:enabled/>
<w:calcOnExit w:val="false"/>
<w:ddList>
<w:listEntry w:val="Item 1"/>
<w:listEntry w:val="Item 2"/>
<w:listEntry w:val="Item 3"/>
</w:ddList>
</w:ffData>
</w:fldChar>
</w:r>
<w:r>
<w:instrText xml:space="preserve"> FORMDROPDOWN </w:instrText>
</w:r>
<w:r>
<w:fldChar w:fldCharType="end"/>
</w:r>
</w:p>
</w:body>
````````````````````````````````
```````````````````````````````` example(Form Controls - Dropdown: 2) options(form-controls-input)
1: [input]{.dropdown options="Item 1 | Item 2 | Item 3" default=1}
.
<w:body>
<w:p>
<w:pPr>
<w:pStyle w:val="ParagraphTextBody"/>
</w:pPr>
<w:r>
<w:t xml:space="preserve">1: </w:t>
</w:r>
<w:r>
<w:fldChar w:fldCharType="begin">
<w:ffData>
<w:name w:val="Dropdown1"/>
<w:enabled/>
<w:calcOnExit w:val="false"/>
<w:ddList>
<w:default w:val="0"/>
<w:listEntry w:val="Item 1"/>
<w:listEntry w:val="Item 2"/>
<w:listEntry w:val="Item 3"/>
</w:ddList>
</w:ffData>
</w:fldChar>
</w:r>
<w:r>
<w:instrText xml:space="preserve"> FORMDROPDOWN </w:instrText>
</w:r>
<w:r>
<w:fldChar w:fldCharType="end"/>
</w:r>
</w:p>
</w:body>
````````````````````````````````
```````````````````````````````` example(Form Controls - Dropdown: 3) options(form-controls-input)
2: [input]{.dropdown options="Item 1 | Item 2 | Item 3" default=2}
.
<w:body>
<w:p>
<w:pPr>
<w:pStyle w:val="ParagraphTextBody"/>
</w:pPr>
<w:r>
<w:t xml:space="preserve">2: </w:t>
</w:r>
<w:r>
<w:fldChar w:fldCharType="begin">
<w:ffData>
<w:name w:val="Dropdown1"/>
<w:enabled/>
<w:calcOnExit w:val="false"/>
<w:ddList>
<w:default w:val="1"/>
<w:listEntry w:val="Item 1"/>
<w:listEntry w:val="Item 2"/>
<w:listEntry w:val="Item 3"/>
</w:ddList>
</w:ffData>
</w:fldChar>
</w:r>
<w:r>
<w:instrText xml:space="preserve"> FORMDROPDOWN </w:instrText>
</w:r>
<w:r>
<w:fldChar w:fldCharType="end"/>
</w:r>
</w:p>
</w:body>
````````````````````````````````
```````````````````````````````` example(Form Controls - Dropdown: 4) options(form-controls-input)
3: [input]{.dropdown options="Item 1 | Item 2 | Item 3" default=3}
.
<w:body>
<w:p>
<w:pPr>
<w:pStyle w:val="ParagraphTextBody"/>
</w:pPr>
<w:r>
<w:t xml:space="preserve">3: </w:t>
</w:r>
<w:r>
<w:fldChar w:fldCharType="begin">
<w:ffData>
<w:name w:val="Dropdown1"/>
<w:enabled/>
<w:calcOnExit w:val="false"/>
<w:ddList>
<w:default w:val="2"/>
<w:listEntry w:val="Item 1"/>
<w:listEntry w:val="Item 2"/>
<w:listEntry w:val="Item 3"/>
</w:ddList>
</w:ffData>
</w:fldChar>
</w:r>
<w:r>
<w:instrText xml:space="preserve"> FORMDROPDOWN </w:instrText>
</w:r>
<w:r>
<w:fldChar w:fldCharType="end"/>
</w:r>
</w:p>
</w:body>
````````````````````````````````
```````````````````````````````` example(Form Controls - Dropdown: 5) options(form-controls-input)
Item 2: [input]{.dropdown default="Item 2" options="Item 1 | Item 2 | Item 3"}
.
<w:body>
<w:p>
<w:pPr>
<w:pStyle w:val="ParagraphTextBody"/>
</w:pPr>
<w:r>
<w:t xml:space="preserve">Item 2: </w:t>
</w:r>
<w:r>
<w:fldChar w:fldCharType="begin">
<w:ffData>
<w:name w:val="Dropdown1"/>
<w:enabled/>
<w:calcOnExit w:val="false"/>
<w:ddList>
<w:default w:val="1"/>
<w:listEntry w:val="Item 1"/>
<w:listEntry w:val="Item 2"/>
<w:listEntry w:val="Item 3"/>
</w:ddList>
</w:ffData>
</w:fldChar>
</w:r>
<w:r>
<w:instrText xml:space="preserve"> FORMDROPDOWN </w:instrText>
</w:r>
<w:r>
<w:fldChar w:fldCharType="end"/>
</w:r>
</w:p>
</w:body>
````````````````````````````````
```````````````````````````````` example(Form Controls - Dropdown: 6) options(form-controls-input)
item 1: [input]{.dropdown default="item 1" options="Item 1 | item 1 | Item 3"}
.
<w:body>
<w:p>
<w:pPr>
<w:pStyle w:val="ParagraphTextBody"/>
</w:pPr>
<w:r>
<w:t xml:space="preserve">item 1: </w:t>
</w:r>
<w:r>
<w:fldChar w:fldCharType="begin">
<w:ffData>
<w:name w:val="Dropdown1"/>
<w:enabled/>
<w:calcOnExit w:val="false"/>
<w:ddList>
<w:default w:val="1"/>
<w:listEntry w:val="Item 1"/>
<w:listEntry w:val="item 1"/>
<w:listEntry w:val="Item 3"/>
</w:ddList>
</w:ffData>
</w:fldChar>
</w:r>
<w:r>
<w:instrText xml:space="preserve"> FORMDROPDOWN </w:instrText>
</w:r>
<w:r>
<w:fldChar w:fldCharType="end"/>
</w:r>
</w:p>
</w:body>
````````````````````````````````
```````````````````````````````` example(Form Controls - Dropdown: 7) options(form-controls-input)
Item 3: [input]{.dropdown default="item 3" options="Item 1 | item 1 | Item 3"}
.
<w:body>
<w:p>
<w:pPr>
<w:pStyle w:val="ParagraphTextBody"/>
</w:pPr>
<w:r>
<w:t xml:space="preserve">Item 3: </w:t>
</w:r>
<w:r>
<w:fldChar w:fldCharType="begin">
<w:ffData>
<w:name w:val="Dropdown1"/>
<w:enabled/>
<w:calcOnExit w:val="false"/>
<w:ddList>
<w:default w:val="2"/>
<w:listEntry w:val="Item 1"/>
<w:listEntry w:val="item 1"/>
<w:listEntry w:val="Item 3"/>
</w:ddList>
</w:ffData>
</w:fldChar>
</w:r>
<w:r>
<w:instrText xml:space="preserve"> FORMDROPDOWN </w:instrText>
</w:r>
<w:r>
<w:fldChar w:fldCharType="end"/>
</w:r>
</w:p>
</w:body>
````````````````````````````````
|
C#
|
UTF-8
| 2,528
| 2.75
| 3
|
[] |
no_license
|
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using NetCoreConfiguration.Models;
namespace NetCoreConfiguration.Pages
{
public class OptionsPatternModel : PageModel
{
private readonly IConfiguration Configuration;
public PositionOptions positionOptions { get; private set; }
private readonly PositionOptions _options;
public OptionsPatternModel(IConfiguration configuration, IOptions<PositionOptions> options)
{
Configuration = configuration;
_options = options.Value;
}
public ContentResult OnGet()
{
var positionOptions = new PositionOptions();
// Bind the PositionOptions class to the Position section of appSettings.json file
// In the preceding code, by default, changes to the JSON configuration file after the app has started are read.
//Configuration.GetSection(PositionOptions.Position).Bind(positionOptions);
//return Content($"Title: {positionOptions.Title} \n" +
// $"Name: {positionOptions.Name}");
// ConfigurationBinder.Get<T> binds and returns the specified type.
// ConfigurationBinder.Get<T> may be more convenient than using ConfigurationBinder.Bind.
// The following code shows how to use ConfigurationBinder.Get<T> with the PositionOptions class.
// In the preceding code, by default, changes to the JSON configuration file after the app has started are read
//positionOptions = Configuration.GetSection(PositionOptions.Position)
// .Get<PositionOptions>();
//return Content($"Title: {positionOptions.Title} \n" +
// $"Name: {positionOptions.Name}");
// An alternative approach when using the options pattern is to bind the Position section and add it to the dependency injection service container.
// In the following code, PositionOptions is added to the service container with Configure and bound to configuration.
// In the preceding code, changes to the JSON configuration file after the app has started are NOT read.
// To read changes after the app has started, use IOptionsSnapshot
return Content($"Title: {_options.Title} \n" +
$"Name: {_options.Name}");
}
}
}
|
Java
|
UTF-8
| 1,089
| 2.171875
| 2
|
[] |
no_license
|
package com.roc.mapper;
import com.roc.pojo.PraiseOrDisagree;
/**
* @author Roc
* @version 1.0
* @date 2019/12/18 16:30
* @description 点赞(踩) mapper接口
*/
public interface PraiseOrDisagreeMapper {
/**
* 插入实体
* @param praiseOrDisagree 对象
* @return
*/
int insertPojo(PraiseOrDisagree praiseOrDisagree);
/**
* 获取实体
* @param operateObject 操作对象
* @param operateTarget 操作目标(心得id或者回复id)
* @param targetType 目标类型(0心得,1回复)
* @return
*/
PraiseOrDisagree getPojo(int operateObject,int operateTarget,int targetType);
/**
* 删除实体
* @return
*/
int deletePojo(int id);
/**
* 统计该心得(回复)的点赞(踩)总数
* @param operateTarget 操作目标(心得id或者回复id)
* @param targetType 目标类型(0心得,1回复)
* @param operateType 0点赞 1踩
* @return
*/
int countLikeNumORHateNum(int operateTarget,int targetType,int operateType);
}
|
C#
|
UTF-8
| 1,300
| 2.609375
| 3
|
[] |
no_license
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Sirenix.OdinInspector;
[System.Serializable]
public class MappedListID : IDeepCopyable {
//TODO: make this a generic class for all IDs like ItemID, SkillID, PerkID, implement == operators
[ValueDropdown("DropdownValues"), SerializeField] protected string name;
public MappedListID()
{
name = string.Empty;
}
public MappedListID(string name)
{
this.name = name;
}
public object DeepCopy()
{
return new MappedListID(this);
}
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
return false;
var id = (MappedListID)obj;
return name == id.name;
}
public override int GetHashCode()
{
return name != null ? name.GetHashCode() : 0;
}
public static implicit operator string(MappedListID id)
{
return id.name;
}
public static implicit operator MappedListID (string str)
{
return new MappedListID(str);
}
public override string ToString()
{
return name;
}
protected virtual IList<string> DropdownValues()
{
return null;
}
public string Name => name;
}
|
Java
|
UTF-8
| 1,435
| 1.648438
| 2
|
[] |
no_license
|
package net.simplifiedcoding.mvvmsampleapp.util;
import java.lang.System;
@kotlin.Metadata(mv = {1, 1, 16}, bv = {1, 0, 3}, k = 2, d1 = {"\u0000 \n\u0000\n\u0002\u0010\u0002\n\u0002\u0018\u0002\n\u0002\b\u0002\n\u0002\u0018\u0002\n\u0000\n\u0002\u0010\u000e\n\u0000\n\u0002\u0018\u0002\n\u0000\u001a\n\u0010\u0000\u001a\u00020\u0001*\u00020\u0002\u001a\n\u0010\u0003\u001a\u00020\u0001*\u00020\u0002\u001a\u0012\u0010\u0004\u001a\u00020\u0001*\u00020\u00052\u0006\u0010\u0006\u001a\u00020\u0007\u001a\u0012\u0010\b\u001a\u00020\u0001*\u00020\t2\u0006\u0010\u0006\u001a\u00020\u0007\u00a8\u0006\n"}, d2 = {"hide", "", "Landroid/widget/ProgressBar;", "show", "snackbar", "Landroid/view/View;", "message", "", "toast", "Landroid/content/Context;", "app_debug"})
public final class ViewUtilsKt {
public static final void toast(@org.jetbrains.annotations.NotNull()
android.content.Context $this$toast, @org.jetbrains.annotations.NotNull()
java.lang.String message) {
}
public static final void show(@org.jetbrains.annotations.NotNull()
android.widget.ProgressBar $this$show) {
}
public static final void hide(@org.jetbrains.annotations.NotNull()
android.widget.ProgressBar $this$hide) {
}
public static final void snackbar(@org.jetbrains.annotations.NotNull()
android.view.View $this$snackbar, @org.jetbrains.annotations.NotNull()
java.lang.String message) {
}
}
|
Java
|
UTF-8
| 4,078
| 2.21875
| 2
|
[] |
no_license
|
package jp.co.asahi.util;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import jp.co.asahi.dao.db.OrderDetailDao;
import jp.co.asahi.model.OrderDetail;
import com.google.common.base.Strings;
class CsvData {
public static void main(String[] A00){
/**
ExportItemlList2011-01-01_2013-05-07.csv
ExportItemlList2013-05-07_2013-08-31.csv
ExportItemlList2013-09-01_2013-12-31.csv
ExportItemlList2014-01-01_2014-04-30.csv
ExportItemlList2014-05-01_2014-08-31.csv
ExportItemlList2014-09-01_2014-12-31.csv
ExportItemlList2015-01-01_2015-03-31.csv
*/
String[] strs = new String[] {
"ExportItemlList2011-01-01_2013-05-07.csv",
"ExportItemlList2013-05-07_2013-08-31.csv",
"ExportItemlList2013-09-01_2013-12-31.csv",
"ExportItemlList2014-01-01_2014-04-30.csv",
"ExportItemlList2014-05-01_2014-08-31.csv",
"ExportItemlList2014-09-01_2014-12-31.csv",
"ExportItemlList2015-01-01_2015-03-31.csv"
};
OrderDetailDao dao = null;
try {
dao = new OrderDetailDao();
for (String string : strs) {
String L00 = string;
DataInputStream in = new DataInputStream(new FileInputStream(new File(L00)));
BufferedReader L01= new BufferedReader(new InputStreamReader(in,"GBK"));
String L02;
int count = 0;
while( (L02 = L01.readLine()) != null ) {
if (count == 0) {
count++;
continue;
}
String[] L03 = Arrays.copyOf(L02.split(","), 9);
/** 订单编号 */
String dingdanBianhao = filterStr(L03[0]);
/** 标题 */
String biaoti = filterStr(L03[1]);
/** 价格 */
double jiage = 0;
if (!Strings.isNullOrEmpty(filterStr(L03[2]))) {
jiage = Double.valueOf(filterStr(L03[2]));
}
/** 购买数量 */
int goumaiShuliang = 0;
if (!Strings.isNullOrEmpty(filterStr(L03[3]))) {
goumaiShuliang = Integer.valueOf(filterStr(L03[3]));
}
/** 外部系统编号 */
String waibuXitongBianhao = filterStr(L03[4]);
/** 商品属性 */
String shangpinShuxing = filterStr(L03[5]);
/** 套餐信息 */
String taocanXinxi = filterStr(L03[6]);
/** 备注 */
String beizhu = filterStr(L03[7]);
/** 订单状态 */
String dingdanZhuangtai = filterStr(L03[8]);
/** 商家编码 */
String shangjiaBianma = filterStr(L03[9]);
OrderDetail orderDetail = new OrderDetail();
orderDetail.setDingdanBianhao(dingdanBianhao);
orderDetail.setBiaoti(biaoti);
orderDetail.setJiage(jiage);
orderDetail.setGoumaiShuliang(goumaiShuliang);
orderDetail.setWaibuXitongBianhao(waibuXitongBianhao);
orderDetail.setShangpinShuxing(shangpinShuxing);
orderDetail.setTaocanXinxi(taocanXinxi);
orderDetail.setBeizhu(beizhu);
orderDetail.setDingdanZhuangtai(dingdanZhuangtai);
orderDetail.setShangjiaBianma(shangjiaBianma);
System.out.printf("订单编号:%s %n", L03[0]);
dao.insert(orderDetail);
}
L01.close();
}
} catch(FileNotFoundException L04) {
} catch(IOException L05) {
} finally {
dao.closeConnection();
}
}
public static String filterStr(String str) {
if (str == null)
return null;
return str.replaceAll("\"", "");
}
}
|
C++
|
GB18030
| 1,396
| 3.453125
| 3
|
[] |
no_license
|
#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
while (cin >> s) {
int S_length = s.length();
string new_S = "";
for (int i = 0; i < S_length;) {
int j = i + 1;
while (s[i] == s[j]) { //ҵȵǸj
j++;
}
if (j - i == 1) { // ظǰһֵ
new_S += s[i];
i++;
}
else
i = j; //jֵiظַ
}
if (new_S == "")
cout << "no" << endl;
else
cout << new_S << endl;
}
return 0;
}
/*
//abee12
string s_string(string &s, int begin, int end)
{
string tmp = "";
for (int i = 0; i < begin; i++) {
tmp += s[i];
}
for (int i = end; i < s.length(); i++) {
tmp += s[i];
}
return tmp;
}
void s_com_string(string &s, int len)
{
int begin = 0;
int end = 0;
string tmp = "", res = "";
for (int i = 1; i < s.length(); i++) {
if (s[i] == s[i - 1]) {
end = i + 1;
}
else {
tmp = s_string(s, begin, end);
begin = i;
end++;
}
}
if (begin + 1 != end) {
tmp = s_string(tmp, begin, end);
}
s = tmp;
}
int main()
{
string s;
while (cin >> s) {
if (s.length() <= 1) {
cout << s << endl;
}
else {
s_com_string(s, s.length());
if (s.length() == 0) {
cout << "no" << endl;
}
else {
cout << s << endl;
}
}
}
return 0;
}
*/
|
C++
|
UTF-8
| 37,277
| 3
| 3
|
[] |
no_license
|
#include "Cube.h"
#include "UnitTest++.h"
#include <iostream>
/*
* This file contains unit tests for the turn function of the Cube class
* there are 18 tests (1 for each possible configuration of the turn)
* for a Cube 3x3x3. Later on more unittest may be added
* for the solve function of Cube and some other utility functions
* but currently it is vital to know that the turn function is working properly
* so as to look for any future bugs in the GUI part.
*/
#define CHECK_SIDES_EQUAL bool topMatch = (top == myCube.getCubeSide()[static_cast<int> (Side::TOP)]); \
bool bottomMatch = (bottom == myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)]); \
bool leftMatch = (left == myCube.getCubeSide()[static_cast<int> (Side::LEFT)]); \
bool rightMatch = (right == myCube.getCubeSide()[static_cast<int> (Side::RIGHT)]); \
bool frontMatch = (front == myCube.getCubeSide()[static_cast<int> (Side::FRONT)]); \
bool backMatch = (back == myCube.getCubeSide()[static_cast<int> (Side::BACK)]); \
CHECK_EQUAL(true, topMatch); \
CHECK_EQUAL(true, bottomMatch); \
CHECK_EQUAL(true, leftMatch); \
CHECK_EQUAL(true, rightMatch); \
CHECK_EQUAL(true, frontMatch); \
CHECK_EQUAL(true, backMatch); \
/*
* Fixture class containing common variables for the unittests and
* some utility functions for them. Also build up and tear down functions
* ( the constructor and destructo of the class)
*/
struct Fixture
{
Fixture() {
myCube.setChoice (-1);
for (int i=0;i<Cube::SIDES_COUNT;i++){
myCube.getCubeSide()[i] = CubeSide(rows ,static_cast<Color> (i));
}
}
~Fixture() {
for (int i=0;i<Cube::SIDES_COUNT;i++){
myCube.getCubeSide()[i] = CubeSide(rows ,static_cast<Color> (i));
}
}
CubeSide top, bottom, left, right, front, back ;
void debugPrint(){
myCube.print();
std::cout<<std::endl;
std::cout<<"bottom:\n";
bottom.print();
std::cout<<"\n";
std::cout<<"top:\n";
top.print();
std::cout<<"\n";
std::cout<<"left:\n";
left.print();
std::cout<<"\n";
std::cout<<"right:\n";
right.print();
std::cout<<"\n";
std::cout<<"front:\n";
front.print();
std::cout<<"\n";
std::cout<<"back:\n";
back.print();
std::cout<<"\n";
}
const int rows = 3;
Cube& myCube = Cube::instance(rows,Mode::TOP_TO_BOTTOM,-1,5);
};
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//BottomToTop mode, clockwise & anticlockwise, choices 0,1,2 (tested with 3 rows cube)
TEST_FIXTURE(Fixture, BottomToTopClockwise0){
int choice = 0;
myCube.setChoice(choice);
myCube.setMode(Mode::TOP_TO_BOTTOM);
for (int i=0;i<rows;i++){
myCube.getCubeSide()[static_cast<int> (Side::TOP)].getWall()[i][i] = Color::RED;
myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)].getWall()[i][i] = Color::BLUE;
}
myCube.getCubeSide()[static_cast<int> (Side::TOP)].getWall()[0][2] = Color::GREY;
myCube.getCubeSide()[static_cast<int> (Side::TOP)].getWall()[2][0] = Color::BLACK;
myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)].getWall()[0][2] = Color::GREY;
myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)].getWall()[2][0] = Color::BLACK;
top = myCube.getCubeSide()[static_cast<int> (Side::TOP)];
bottom = myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)];
left = myCube.getCubeSide()[static_cast<int> (Side::LEFT)];
right = myCube.getCubeSide()[static_cast<int> (Side::RIGHT)];
front = myCube.getCubeSide()[static_cast<int> (Side::FRONT)];
back = myCube.getCubeSide()[static_cast<int> (Side::BACK)];
//myCube.turn(Direction::CLOCK_WISE);
myCube.setDir(Direction::CLOCK_WISE);
myCube.turn();
for (int i=0;i<rows;i++){
Color temp = front.getWall()[choice][i];
Color &lhs1 = front.getWall()[choice][i];
lhs1 = right.getWall()[choice][i];
Color &lhs2 = right.getWall()[choice][i];
lhs2 = back.getWall()[choice][i];
Color &lhs3 = back.getWall()[choice][i];
lhs3 = left.getWall()[choice][i];
Color &lhs4 = left.getWall()[choice][i];
lhs4 = temp;
}
top.getWall()[0][2] = Color::RED;
top.getWall()[2][0] = Color::RED;
top.getWall()[0][0] = Color::BLACK;
top.getWall()[2][2] = Color::GREY;
CHECK_SIDES_EQUAL;
}
TEST_FIXTURE(Fixture, BottomToTopCounterClockwise0){
int choice = 0;
myCube.setChoice(choice);
myCube.setMode(Mode::TOP_TO_BOTTOM);
for (int i=0;i<rows;i++){
myCube.getCubeSide()[static_cast<int> (Side::TOP)].getWall()[i][i] = Color::RED;
myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)].getWall()[i][i] = Color::BLUE;
}
myCube.getCubeSide()[static_cast<int> (Side::TOP)].getWall()[0][2] = Color::GREY;
myCube.getCubeSide()[static_cast<int> (Side::TOP)].getWall()[2][0] = Color::BLACK;
myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)].getWall()[0][2] = Color::GREY;
myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)].getWall()[2][0] = Color::BLACK;
top = myCube.getCubeSide()[static_cast<int> (Side::TOP)];
bottom = myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)];
left = myCube.getCubeSide()[static_cast<int> (Side::LEFT)];
right = myCube.getCubeSide()[static_cast<int> (Side::RIGHT)];
front = myCube.getCubeSide()[static_cast<int> (Side::FRONT)];
back = myCube.getCubeSide()[static_cast<int> (Side::BACK)];
//myCube.turn(Direction::COUNTER_CLOCK_WISE);
myCube.setDir(Direction::COUNTER_CLOCK_WISE);
myCube.turn();
for (int i=0;i<rows;i++){
Color temp = front.getWall()[choice][i];
Color &lhs1 = front.getWall()[choice][i];
lhs1 = left.getWall()[choice][i];
Color &lhs2 = left.getWall()[choice][i];
lhs2 = back.getWall()[choice][i];
Color &lhs3 = back.getWall()[choice][i];
lhs3 = right.getWall()[choice][i];
Color &lhs4 = right.getWall()[choice][i];
lhs4 = temp;
}
top.getWall()[0][2] = Color::RED;
top.getWall()[2][0] = Color::RED;
top.getWall()[0][0] = Color::GREY;
top.getWall()[2][2] = Color::BLACK;
CHECK_SIDES_EQUAL;
}
TEST_FIXTURE(Fixture, BottomToTopClockwise1){
int choice = 1;
myCube.setChoice(choice);
myCube.setMode(Mode::TOP_TO_BOTTOM);
for (int i=0;i<rows;i++){
myCube.getCubeSide()[static_cast<int> (Side::TOP)].getWall()[i][i] = Color::RED;
myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)].getWall()[i][i] = Color::BLUE;
}
myCube.getCubeSide()[static_cast<int> (Side::TOP)].getWall()[0][2] = Color::GREY;
myCube.getCubeSide()[static_cast<int> (Side::TOP)].getWall()[2][0] = Color::BLACK;
myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)].getWall()[0][2] = Color::GREY;
myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)].getWall()[2][0] = Color::BLACK;
top = myCube.getCubeSide()[static_cast<int> (Side::TOP)];
bottom = myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)];
left = myCube.getCubeSide()[static_cast<int> (Side::LEFT)];
right = myCube.getCubeSide()[static_cast<int> (Side::RIGHT)];
front = myCube.getCubeSide()[static_cast<int> (Side::FRONT)];
back = myCube.getCubeSide()[static_cast<int> (Side::BACK)];
//myCube.turn(Direction::CLOCK_WISE);
myCube.setDir(Direction::CLOCK_WISE);
myCube.turn();
for (int i=0;i<rows;i++){
Color temp = front.getWall()[choice][i];
Color &lhs1 = front.getWall()[choice][i];
lhs1 = right.getWall()[choice][i];
Color &lhs2 = right.getWall()[choice][i];
lhs2 = back.getWall()[choice][i];
Color &lhs3 = back.getWall()[choice][i];
lhs3 = left.getWall()[choice][i];
Color &lhs4 = left.getWall()[choice][i];
lhs4 = temp;
}
CHECK_SIDES_EQUAL;
}
TEST_FIXTURE(Fixture, BottomToTopCounterClockwise1){
int choice = 1;
myCube.setChoice(choice);
myCube.setMode(Mode::TOP_TO_BOTTOM);
for (int i=0;i<rows;i++){
myCube.getCubeSide()[static_cast<int> (Side::TOP)].getWall()[i][i] = Color::RED;
myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)].getWall()[i][i] = Color::BLUE;
}
myCube.getCubeSide()[static_cast<int> (Side::TOP)].getWall()[0][2] = Color::GREY;
myCube.getCubeSide()[static_cast<int> (Side::TOP)].getWall()[2][0] = Color::BLACK;
myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)].getWall()[0][2] = Color::GREY;
myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)].getWall()[2][0] = Color::BLACK;
top = myCube.getCubeSide()[static_cast<int> (Side::TOP)];
bottom = myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)];
left = myCube.getCubeSide()[static_cast<int> (Side::LEFT)];
right = myCube.getCubeSide()[static_cast<int> (Side::RIGHT)];
front = myCube.getCubeSide()[static_cast<int> (Side::FRONT)];
back = myCube.getCubeSide()[static_cast<int> (Side::BACK)];
//myCube.turn(Direction::COUNTER_CLOCK_WISE);
myCube.setDir(Direction::COUNTER_CLOCK_WISE);
myCube.turn();
for (int i=0;i<rows;i++){
Color temp = front.getWall()[choice][i];
Color &lhs1 = front.getWall()[choice][i];
lhs1 = left.getWall()[choice][i];
Color &lhs2 = left.getWall()[choice][i];
lhs2 = back.getWall()[choice][i];
Color &lhs3 = back.getWall()[choice][i];
lhs3 = right.getWall()[choice][i];
Color &lhs4 = right.getWall()[choice][i];
lhs4 = temp;
}
CHECK_SIDES_EQUAL;
}
TEST_FIXTURE(Fixture, BottomToTopClockwise2){
int choice = 2;
myCube.setChoice(choice);
myCube.setMode(Mode::TOP_TO_BOTTOM);
for (int i=0;i<rows;i++){
myCube.getCubeSide()[static_cast<int> (Side::TOP)].getWall()[i][i] = Color::RED;
myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)].getWall()[i][i] = Color::BLUE;
}
myCube.getCubeSide()[static_cast<int> (Side::TOP)].getWall()[0][2] = Color::GREY;
myCube.getCubeSide()[static_cast<int> (Side::TOP)].getWall()[2][0] = Color::BLACK;
myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)].getWall()[0][2] = Color::GREY;
myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)].getWall()[2][0] = Color::BLACK;
top = myCube.getCubeSide()[static_cast<int> (Side::TOP)];
bottom = myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)];
left = myCube.getCubeSide()[static_cast<int> (Side::LEFT)];
right = myCube.getCubeSide()[static_cast<int> (Side::RIGHT)];
front = myCube.getCubeSide()[static_cast<int> (Side::FRONT)];
back = myCube.getCubeSide()[static_cast<int> (Side::BACK)];
//myCube.turn(Direction::CLOCK_WISE);
myCube.setDir(Direction::CLOCK_WISE);
myCube.turn();
for (int i=0;i<rows;i++){
Color temp = front.getWall()[choice][i];
Color &lhs1 = front.getWall()[choice][i];
lhs1 = right.getWall()[choice][i];
Color &lhs2 = right.getWall()[choice][i];
lhs2 = back.getWall()[choice][i];
Color &lhs3 = back.getWall()[choice][i];
lhs3 = left.getWall()[choice][i];
Color &lhs4 = left.getWall()[choice][i];
lhs4 = temp;
}
bottom.getWall()[0][2] = Color::BLUE;
bottom.getWall()[2][0] = Color::BLUE;
bottom.getWall()[0][0] = Color::BLACK;
bottom.getWall()[2][2] = Color::GREY;
CHECK_SIDES_EQUAL;
}
TEST_FIXTURE(Fixture, BottomToTopCounterClockwise2){
int choice = 2;
myCube.setChoice(choice);
myCube.setMode(Mode::TOP_TO_BOTTOM);
for (int i=0;i<rows;i++){
myCube.getCubeSide()[static_cast<int> (Side::TOP)].getWall()[i][i] = Color::RED;
myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)].getWall()[i][i] = Color::BLUE;
}
myCube.getCubeSide()[static_cast<int> (Side::TOP)].getWall()[0][2] = Color::GREY;
myCube.getCubeSide()[static_cast<int> (Side::TOP)].getWall()[2][0] = Color::BLACK;
myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)].getWall()[0][2] = Color::GREY;
myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)].getWall()[2][0] = Color::BLACK;
top = myCube.getCubeSide()[static_cast<int> (Side::TOP)];
bottom = myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)];
left = myCube.getCubeSide()[static_cast<int> (Side::LEFT)];
right = myCube.getCubeSide()[static_cast<int> (Side::RIGHT)];
front = myCube.getCubeSide()[static_cast<int> (Side::FRONT)];
back = myCube.getCubeSide()[static_cast<int> (Side::BACK)];
//myCube.turn(Direction::COUNTER_CLOCK_WISE);
myCube.setDir(Direction::COUNTER_CLOCK_WISE);
myCube.turn();
for (int i=0;i<rows;i++){
Color temp = front.getWall()[choice][i];
Color &lhs1 = front.getWall()[choice][i];
lhs1 = left.getWall()[choice][i];
Color &lhs2 = left.getWall()[choice][i];
lhs2 = back.getWall()[choice][i];
Color &lhs3 = back.getWall()[choice][i];
lhs3 = right.getWall()[choice][i];
Color &lhs4 = right.getWall()[choice][i];
lhs4 = temp;
}
bottom.getWall()[0][2] = Color::BLUE;
bottom.getWall()[2][0] = Color::BLUE;
bottom.getWall()[0][0] = Color::GREY;
bottom.getWall()[2][2] = Color::BLACK;
CHECK_SIDES_EQUAL;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//FrontToBack mode, clockwise & anticlockwise, choices 0,1,2 (tested with 3 rows cube)
TEST_FIXTURE(Fixture, FrontToBackClockwise0){
int choice = 0;
int shiftChoice = (rows - 1 - choice)%rows;
myCube.setChoice(choice);
myCube.setMode(Mode::FRONT_TO_BACK);
for (int i=0;i<rows;i++){
myCube.getCubeSide()[static_cast<int> (Side::FRONT)].getWall()[i][i] = Color::ORANGE;
myCube.getCubeSide()[static_cast<int> (Side::BACK)].getWall()[i][i] = Color::WHITE;
}
myCube.getCubeSide()[static_cast<int> (Side::FRONT)].getWall()[0][2] = Color::GREY;
myCube.getCubeSide()[static_cast<int> (Side::FRONT)].getWall()[2][0] = Color::BLACK;
myCube.getCubeSide()[static_cast<int> (Side::BACK)].getWall()[0][2] = Color::GREY;
myCube.getCubeSide()[static_cast<int> (Side::BACK)].getWall()[2][0] = Color::BLACK;
top = myCube.getCubeSide()[static_cast<int> (Side::TOP)];
bottom = myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)];
left = myCube.getCubeSide()[static_cast<int> (Side::LEFT)];
right = myCube.getCubeSide()[static_cast<int> (Side::RIGHT)];
front = myCube.getCubeSide()[static_cast<int> (Side::FRONT)];
back = myCube.getCubeSide()[static_cast<int> (Side::BACK)];
//myCube.turn(Direction::CLOCK_WISE);
myCube.setDir(Direction::CLOCK_WISE);
myCube.turn();
for (int i=0;i<rows;i++){
int shift = (rows-i-1)%rows;
Color temp = top.getWall()[shiftChoice][i];
Color &lhs1 = top.getWall()[shiftChoice][i];
lhs1 = left.getWall()[shift][shiftChoice];
Color &lhs2 = left.getWall()[shift][shiftChoice];
lhs2 = bottom.getWall()[shiftChoice][i];
Color &lhs3 = bottom.getWall()[shiftChoice][i];
lhs3 = right.getWall()[i][choice];
Color &lhs4 = right.getWall()[i][choice];
lhs4 = temp;
}
front.getWall()[0][2] = Color::ORANGE;
front.getWall()[2][0] = Color::ORANGE;
front.getWall()[0][0] = Color::BLACK;
front.getWall()[2][2] = Color::GREY;
CHECK_SIDES_EQUAL;
}
TEST_FIXTURE(Fixture, FrontToBackClockwise1){
int choice = 1;
int shiftChoice = (rows - 1 - choice)%rows;
myCube.setChoice(choice);
myCube.setMode(Mode::FRONT_TO_BACK);
for (int i=0;i<rows;i++){
myCube.getCubeSide()[static_cast<int> (Side::FRONT)].getWall()[i][i] = Color::ORANGE;
myCube.getCubeSide()[static_cast<int> (Side::BACK)].getWall()[i][i] = Color::WHITE;
}
myCube.getCubeSide()[static_cast<int> (Side::FRONT)].getWall()[0][2] = Color::GREY;
myCube.getCubeSide()[static_cast<int> (Side::FRONT)].getWall()[2][0] = Color::BLACK;
myCube.getCubeSide()[static_cast<int> (Side::BACK)].getWall()[0][2] = Color::GREY;
myCube.getCubeSide()[static_cast<int> (Side::BACK)].getWall()[2][0] = Color::BLACK;
top = myCube.getCubeSide()[static_cast<int> (Side::TOP)];
bottom = myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)];
left = myCube.getCubeSide()[static_cast<int> (Side::LEFT)];
right = myCube.getCubeSide()[static_cast<int> (Side::RIGHT)];
front = myCube.getCubeSide()[static_cast<int> (Side::FRONT)];
back = myCube.getCubeSide()[static_cast<int> (Side::BACK)];
//myCube.turn(Direction::CLOCK_WISE);
myCube.setDir(Direction::CLOCK_WISE);
myCube.turn();
for (int i=0;i<rows;i++){
int shift = (rows-i-1)%rows;
Color temp = top.getWall()[shiftChoice][i];
Color &lhs1 = top.getWall()[shiftChoice][i];
lhs1 = left.getWall()[shift][shiftChoice];
Color &lhs2 = left.getWall()[shift][shiftChoice];
lhs2 = bottom.getWall()[shiftChoice][i];
Color &lhs3 = bottom.getWall()[shiftChoice][i];
lhs3 = right.getWall()[i][choice];
Color &lhs4 = right.getWall()[i][choice];
lhs4 = temp;
}
CHECK_SIDES_EQUAL;
}
TEST_FIXTURE(Fixture, FrontToBackClockwise2){
int choice = 2;
int shiftChoice = (rows - 1 - choice)%rows;
myCube.setChoice(choice);
myCube.setMode(Mode::FRONT_TO_BACK);
for (int i=0;i<rows;i++){
myCube.getCubeSide()[static_cast<int> (Side::FRONT)].getWall()[i][i] = Color::ORANGE;
myCube.getCubeSide()[static_cast<int> (Side::BACK)].getWall()[i][i] = Color::WHITE;
}
myCube.getCubeSide()[static_cast<int> (Side::FRONT)].getWall()[0][2] = Color::GREY;
myCube.getCubeSide()[static_cast<int> (Side::FRONT)].getWall()[2][0] = Color::BLACK;
myCube.getCubeSide()[static_cast<int> (Side::BACK)].getWall()[0][2] = Color::GREY;
myCube.getCubeSide()[static_cast<int> (Side::BACK)].getWall()[2][0] = Color::BLACK;
top = myCube.getCubeSide()[static_cast<int> (Side::TOP)];
bottom = myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)];
left = myCube.getCubeSide()[static_cast<int> (Side::LEFT)];
right = myCube.getCubeSide()[static_cast<int> (Side::RIGHT)];
front = myCube.getCubeSide()[static_cast<int> (Side::FRONT)];
back = myCube.getCubeSide()[static_cast<int> (Side::BACK)];
//myCube.turn(Direction::CLOCK_WISE);
myCube.setDir(Direction::CLOCK_WISE);
myCube.turn();
for (int i=0;i<rows;i++){
int shift = (rows-i-1)%rows;
Color temp = top.getWall()[shiftChoice][i];
Color &lhs1 = top.getWall()[shiftChoice][i];
lhs1 = left.getWall()[shift][shiftChoice];
Color &lhs2 = left.getWall()[shift][shiftChoice];
lhs2 = bottom.getWall()[shiftChoice][i];
Color &lhs3 = bottom.getWall()[shiftChoice][i];
lhs3 = right.getWall()[i][choice];
Color &lhs4 = right.getWall()[i][choice];
lhs4 = temp;
}
back.getWall()[0][2] = Color::WHITE;
back.getWall()[2][0] = Color::WHITE;
back.getWall()[0][0] = Color::BLACK;
back.getWall()[2][2] = Color::GREY;
CHECK_SIDES_EQUAL;
}
TEST_FIXTURE(Fixture, FrontToBackCounterClockwise0){
int choice = 0;
int shiftChoice = (rows - 1 - choice)%rows;
myCube.setChoice(choice);
myCube.setMode(Mode::FRONT_TO_BACK);
for (int i=0;i<rows;i++){
myCube.getCubeSide()[static_cast<int> (Side::FRONT)].getWall()[i][i] = Color::ORANGE;
myCube.getCubeSide()[static_cast<int> (Side::BACK)].getWall()[i][i] = Color::WHITE;
}
myCube.getCubeSide()[static_cast<int> (Side::FRONT)].getWall()[0][2] = Color::GREY;
myCube.getCubeSide()[static_cast<int> (Side::FRONT)].getWall()[2][0] = Color::BLACK;
myCube.getCubeSide()[static_cast<int> (Side::BACK)].getWall()[0][2] = Color::GREY;
myCube.getCubeSide()[static_cast<int> (Side::BACK)].getWall()[2][0] = Color::BLACK;
top = myCube.getCubeSide()[static_cast<int> (Side::TOP)];
bottom = myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)];
left = myCube.getCubeSide()[static_cast<int> (Side::LEFT)];
right = myCube.getCubeSide()[static_cast<int> (Side::RIGHT)];
front = myCube.getCubeSide()[static_cast<int> (Side::FRONT)];
back = myCube.getCubeSide()[static_cast<int> (Side::BACK)];
//myCube.turn(Direction::COUNTER_CLOCK_WISE);
myCube.setDir(Direction::COUNTER_CLOCK_WISE);
myCube.turn();
for (int i=0;i<rows;i++){
int shift = (rows-i-1)%rows;
Color temp = top.getWall()[shiftChoice][i];
Color &lhs1 = top.getWall()[shiftChoice][i];
lhs1 = right.getWall()[i][choice];
Color &lhs2 = right.getWall()[i][choice];
lhs2 = bottom.getWall()[shiftChoice][i];
Color &lhs3 = bottom.getWall()[shiftChoice][i];
lhs3 = left.getWall()[shift][shiftChoice];
Color &lhs4 = left.getWall()[shift][shiftChoice];
lhs4 = temp;
}
front.getWall()[0][2] = Color::ORANGE;
front.getWall()[2][0] = Color::ORANGE;
front.getWall()[0][0] = Color::GREY;
front.getWall()[2][2] = Color::BLACK;
CHECK_SIDES_EQUAL;
}
TEST_FIXTURE(Fixture, FrontToBackCounterClockwise1){
int choice = 1;
int shiftChoice = (rows - 1 - choice)%rows;
myCube.setChoice(choice);
myCube.setMode(Mode::FRONT_TO_BACK);
for (int i=0;i<rows;i++){
myCube.getCubeSide()[static_cast<int> (Side::FRONT)].getWall()[i][i] = Color::ORANGE;
myCube.getCubeSide()[static_cast<int> (Side::BACK)].getWall()[i][i] = Color::WHITE;
}
myCube.getCubeSide()[static_cast<int> (Side::FRONT)].getWall()[0][2] = Color::GREY;
myCube.getCubeSide()[static_cast<int> (Side::FRONT)].getWall()[2][0] = Color::BLACK;
myCube.getCubeSide()[static_cast<int> (Side::BACK)].getWall()[0][2] = Color::GREY;
myCube.getCubeSide()[static_cast<int> (Side::BACK)].getWall()[2][0] = Color::BLACK;
top = myCube.getCubeSide()[static_cast<int> (Side::TOP)];
bottom = myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)];
left = myCube.getCubeSide()[static_cast<int> (Side::LEFT)];
right = myCube.getCubeSide()[static_cast<int> (Side::RIGHT)];
front = myCube.getCubeSide()[static_cast<int> (Side::FRONT)];
back = myCube.getCubeSide()[static_cast<int> (Side::BACK)];
//myCube.turn(Direction::COUNTER_CLOCK_WISE);
myCube.setDir(Direction::COUNTER_CLOCK_WISE);
myCube.turn();
for (int i=0;i<rows;i++){
int shift = (rows-i-1)%rows;
Color temp = top.getWall()[shiftChoice][i];
Color &lhs1 = top.getWall()[shiftChoice][i];
lhs1 = right.getWall()[i][choice];
Color &lhs2 = right.getWall()[i][choice];
lhs2 = bottom.getWall()[shiftChoice][i];
Color &lhs3 = bottom.getWall()[shiftChoice][i];
lhs3 = left.getWall()[shift][shiftChoice];
Color &lhs4 = left.getWall()[shift][shiftChoice];
lhs4 = temp;
}
CHECK_SIDES_EQUAL;
}
TEST_FIXTURE(Fixture, FrontToBackCounterClockwise2){
int choice = 2;
int shiftChoice = (rows - 1 - choice)%rows;
myCube.setChoice(choice);
myCube.setMode(Mode::FRONT_TO_BACK);
for (int i=0;i<rows;i++){
myCube.getCubeSide()[static_cast<int> (Side::FRONT)].getWall()[i][i] = Color::ORANGE;
myCube.getCubeSide()[static_cast<int> (Side::BACK)].getWall()[i][i] = Color::WHITE;
}
myCube.getCubeSide()[static_cast<int> (Side::FRONT)].getWall()[0][2] = Color::GREY;
myCube.getCubeSide()[static_cast<int> (Side::FRONT)].getWall()[2][0] = Color::BLACK;
myCube.getCubeSide()[static_cast<int> (Side::BACK)].getWall()[0][2] = Color::GREY;
myCube.getCubeSide()[static_cast<int> (Side::BACK)].getWall()[2][0] = Color::BLACK;
top = myCube.getCubeSide()[static_cast<int> (Side::TOP)];
bottom = myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)];
left = myCube.getCubeSide()[static_cast<int> (Side::LEFT)];
right = myCube.getCubeSide()[static_cast<int> (Side::RIGHT)];
front = myCube.getCubeSide()[static_cast<int> (Side::FRONT)];
back = myCube.getCubeSide()[static_cast<int> (Side::BACK)];
//myCube.turn(Direction::COUNTER_CLOCK_WISE);
myCube.setDir(Direction::COUNTER_CLOCK_WISE);
myCube.turn();
for (int i=0;i<rows;i++){
int shift = (rows-i-1)%rows;
Color temp = top.getWall()[shiftChoice][i];
Color &lhs1 = top.getWall()[shiftChoice][i];
lhs1 = right.getWall()[i][choice];
Color &lhs2 = right.getWall()[i][choice];
lhs2 = bottom.getWall()[shiftChoice][i];
Color &lhs3 = bottom.getWall()[shiftChoice][i];
lhs3 = left.getWall()[shift][shiftChoice];
Color &lhs4 = left.getWall()[shift][shiftChoice];
lhs4 = temp;
}
back.getWall()[0][2] = Color::WHITE;
back.getWall()[2][0] = Color::WHITE;
back.getWall()[0][0] = Color::GREY;
back.getWall()[2][2] = Color::BLACK;
CHECK_SIDES_EQUAL;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//LeftToRight mode, clockwise & anticlockwise, choices 0,1,2 (tested with 3 rows cube)
TEST_FIXTURE(Fixture, LeftToRightClockwise0){
int choice = 0;
int shiftChoice = (rows - 1 - choice)%rows;
myCube.setChoice(choice);
myCube.setMode(Mode::LEFT_TO_RIGHT);
for (int i=0;i<rows;i++){
myCube.getCubeSide()[static_cast<int> (Side::LEFT)].getWall()[i][i] = Color::YELLOW;
myCube.getCubeSide()[static_cast<int> (Side::RIGHT)].getWall()[i][i] = Color::GREEN;
}
myCube.getCubeSide()[static_cast<int> (Side::LEFT)].getWall()[0][2] = Color::GREY;
myCube.getCubeSide()[static_cast<int> (Side::LEFT)].getWall()[2][0] = Color::BLACK;
myCube.getCubeSide()[static_cast<int> (Side::RIGHT)].getWall()[0][2] = Color::GREY;
myCube.getCubeSide()[static_cast<int> (Side::RIGHT)].getWall()[2][0] = Color::BLACK;
top = myCube.getCubeSide()[static_cast<int> (Side::TOP)];
bottom = myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)];
left = myCube.getCubeSide()[static_cast<int> (Side::LEFT)];
right = myCube.getCubeSide()[static_cast<int> (Side::RIGHT)];
front = myCube.getCubeSide()[static_cast<int> (Side::FRONT)];
back = myCube.getCubeSide()[static_cast<int> (Side::BACK)];
//myCube.turn(Direction::CLOCK_WISE);
myCube.setDir(Direction::CLOCK_WISE);
myCube.turn();
for (int i=0;i<rows;i++){
int shift = (rows-i-1)%rows;
Color temp = top.getWall()[i][choice];
Color &lhs1 = top.getWall()[i][choice];
lhs1 = back.getWall()[shift][shiftChoice];
Color &lhs2 = back.getWall()[shift][shiftChoice];
lhs2 = bottom.getWall()[shift][shiftChoice];
Color &lhs3 = bottom.getWall()[shift][shiftChoice];
lhs3 = front.getWall()[i][choice];
Color &lhs4 = front.getWall()[i][choice];
lhs4 = temp;
}
left.getWall()[0][2] = Color::YELLOW;
left.getWall()[2][0] = Color::YELLOW;
left.getWall()[0][0] = Color::BLACK;
left.getWall()[2][2] = Color::GREY;
CHECK_SIDES_EQUAL;
}
TEST_FIXTURE(Fixture, LeftToRightClockwise1){
int choice = 1;
int shiftChoice = (rows - 1 - choice)%rows;
myCube.setChoice(choice);
myCube.setMode(Mode::LEFT_TO_RIGHT);
for (int i=0;i<rows;i++){
myCube.getCubeSide()[static_cast<int> (Side::LEFT)].getWall()[i][i] = Color::YELLOW;
myCube.getCubeSide()[static_cast<int> (Side::RIGHT)].getWall()[i][i] = Color::GREEN;
}
myCube.getCubeSide()[static_cast<int> (Side::LEFT)].getWall()[0][2] = Color::GREY;
myCube.getCubeSide()[static_cast<int> (Side::LEFT)].getWall()[2][0] = Color::BLACK;
myCube.getCubeSide()[static_cast<int> (Side::RIGHT)].getWall()[0][2] = Color::GREY;
myCube.getCubeSide()[static_cast<int> (Side::RIGHT)].getWall()[2][0] = Color::BLACK;
top = myCube.getCubeSide()[static_cast<int> (Side::TOP)];
bottom = myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)];
left = myCube.getCubeSide()[static_cast<int> (Side::LEFT)];
right = myCube.getCubeSide()[static_cast<int> (Side::RIGHT)];
front = myCube.getCubeSide()[static_cast<int> (Side::FRONT)];
back = myCube.getCubeSide()[static_cast<int> (Side::BACK)];
//myCube.turn(Direction::CLOCK_WISE);
myCube.setDir(Direction::CLOCK_WISE);
myCube.turn();
for (int i=0;i<rows;i++){
int shift = (rows-i-1)%rows;
Color temp = top.getWall()[i][choice];
Color &lhs1 = top.getWall()[i][choice];
lhs1 = back.getWall()[shift][shiftChoice];
Color &lhs2 = back.getWall()[shift][shiftChoice];
lhs2 = bottom.getWall()[shift][shiftChoice];
Color &lhs3 = bottom.getWall()[shift][shiftChoice];
lhs3 = front.getWall()[i][choice];
Color &lhs4 = front.getWall()[i][choice];
lhs4 = temp;
}
CHECK_SIDES_EQUAL;
}
TEST_FIXTURE(Fixture, LeftToRightClockwise2){
int choice = 2;
int shiftChoice = (rows - 1 - choice)%rows;
myCube.setChoice(choice);
myCube.setMode(Mode::LEFT_TO_RIGHT);
for (int i=0;i<rows;i++){
myCube.getCubeSide()[static_cast<int> (Side::LEFT)].getWall()[i][i] = Color::YELLOW;
myCube.getCubeSide()[static_cast<int> (Side::RIGHT)].getWall()[i][i] = Color::GREEN;
}
myCube.getCubeSide()[static_cast<int> (Side::LEFT)].getWall()[0][2] = Color::GREY;
myCube.getCubeSide()[static_cast<int> (Side::LEFT)].getWall()[2][0] = Color::BLACK;
myCube.getCubeSide()[static_cast<int> (Side::RIGHT)].getWall()[0][2] = Color::GREY;
myCube.getCubeSide()[static_cast<int> (Side::RIGHT)].getWall()[2][0] = Color::BLACK;
top = myCube.getCubeSide()[static_cast<int> (Side::TOP)];
bottom = myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)];
left = myCube.getCubeSide()[static_cast<int> (Side::LEFT)];
right = myCube.getCubeSide()[static_cast<int> (Side::RIGHT)];
front = myCube.getCubeSide()[static_cast<int> (Side::FRONT)];
back = myCube.getCubeSide()[static_cast<int> (Side::BACK)];
//myCube.turn(Direction::CLOCK_WISE);
myCube.setDir(Direction::CLOCK_WISE);
myCube.turn();
for (int i=0;i<rows;i++){
int shift = (rows-i-1)%rows;
Color temp = top.getWall()[i][choice];
Color &lhs1 = top.getWall()[i][choice];
lhs1 = back.getWall()[shift][shiftChoice];
Color &lhs2 = back.getWall()[shift][shiftChoice];
lhs2 = bottom.getWall()[shift][shiftChoice];
Color &lhs3 = bottom.getWall()[shift][shiftChoice];
lhs3 = front.getWall()[i][choice];
Color &lhs4 = front.getWall()[i][choice];
lhs4 = temp;
}
right.getWall()[0][2] = Color::GREEN;
right.getWall()[2][0] = Color::GREEN;
right.getWall()[0][0] = Color::BLACK;
right.getWall()[2][2] = Color::GREY;
CHECK_SIDES_EQUAL;
}
TEST_FIXTURE(Fixture, LeftToRightCounterClockwise0){
int choice = 0;
int shiftChoice = (rows - 1 - choice)%rows;
myCube.setChoice(choice);
myCube.setMode(Mode::LEFT_TO_RIGHT);
for (int i=0;i<rows;i++){
myCube.getCubeSide()[static_cast<int> (Side::LEFT)].getWall()[i][i] = Color::YELLOW;
myCube.getCubeSide()[static_cast<int> (Side::RIGHT)].getWall()[i][i] = Color::GREEN;
}
myCube.getCubeSide()[static_cast<int> (Side::LEFT)].getWall()[0][2] = Color::GREY;
myCube.getCubeSide()[static_cast<int> (Side::LEFT)].getWall()[2][0] = Color::BLACK;
myCube.getCubeSide()[static_cast<int> (Side::RIGHT)].getWall()[0][2] = Color::GREY;
myCube.getCubeSide()[static_cast<int> (Side::RIGHT)].getWall()[2][0] = Color::BLACK;
top = myCube.getCubeSide()[static_cast<int> (Side::TOP)];
bottom = myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)];
left = myCube.getCubeSide()[static_cast<int> (Side::LEFT)];
right = myCube.getCubeSide()[static_cast<int> (Side::RIGHT)];
front = myCube.getCubeSide()[static_cast<int> (Side::FRONT)];
back = myCube.getCubeSide()[static_cast<int> (Side::BACK)];
//myCube.turn(Direction::COUNTER_CLOCK_WISE);
myCube.setDir(Direction::COUNTER_CLOCK_WISE);
myCube.turn();
for (int i=0;i<rows;i++){
int shift = (rows-i-1)%rows;
Color temp = top.getWall()[i][choice];
Color &lhs1 = top.getWall()[i][choice];
lhs1 = front.getWall()[i][choice];
Color &lhs2 = front.getWall()[i][choice];
lhs2 = bottom.getWall()[shift][shiftChoice];
Color &lhs3 = bottom.getWall()[shift][shiftChoice];
lhs3 = back.getWall()[shift][shiftChoice];
Color &lhs4 = back.getWall()[shift][shiftChoice];
lhs4 = temp;
}
left.getWall()[0][2] = Color::YELLOW;
left.getWall()[2][0] = Color::YELLOW;
left.getWall()[0][0] = Color::GREY;
left.getWall()[2][2] = Color::BLACK;
CHECK_SIDES_EQUAL;
}
TEST_FIXTURE(Fixture, LeftToRightCounterClockwise1){
int choice = 1;
int shiftChoice = (rows - 1 - choice)%rows;
myCube.setChoice(choice);
myCube.setMode(Mode::LEFT_TO_RIGHT);
for (int i=0;i<rows;i++){
myCube.getCubeSide()[static_cast<int> (Side::LEFT)].getWall()[i][i] = Color::YELLOW;
myCube.getCubeSide()[static_cast<int> (Side::RIGHT)].getWall()[i][i] = Color::GREEN;
}
myCube.getCubeSide()[static_cast<int> (Side::LEFT)].getWall()[0][2] = Color::GREY;
myCube.getCubeSide()[static_cast<int> (Side::LEFT)].getWall()[2][0] = Color::BLACK;
myCube.getCubeSide()[static_cast<int> (Side::RIGHT)].getWall()[0][2] = Color::GREY;
myCube.getCubeSide()[static_cast<int> (Side::RIGHT)].getWall()[2][0] = Color::BLACK;
top = myCube.getCubeSide()[static_cast<int> (Side::TOP)];
bottom = myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)];
left = myCube.getCubeSide()[static_cast<int> (Side::LEFT)];
right = myCube.getCubeSide()[static_cast<int> (Side::RIGHT)];
front = myCube.getCubeSide()[static_cast<int> (Side::FRONT)];
back = myCube.getCubeSide()[static_cast<int> (Side::BACK)];
//myCube.turn(Direction::COUNTER_CLOCK_WISE);
myCube.setDir(Direction::COUNTER_CLOCK_WISE);
myCube.turn();
for (int i=0;i<rows;i++){
int shift = (rows-i-1)%rows;
Color temp = top.getWall()[i][choice];
Color &lhs1 = top.getWall()[i][choice];
lhs1 = front.getWall()[i][choice];
Color &lhs2 = front.getWall()[i][choice];
lhs2 = bottom.getWall()[shift][shiftChoice];
Color &lhs3 = bottom.getWall()[shift][shiftChoice];
lhs3 = back.getWall()[shift][shiftChoice];
Color &lhs4 = back.getWall()[shift][shiftChoice];
lhs4 = temp;
}
CHECK_SIDES_EQUAL;
}
TEST_FIXTURE(Fixture, LeftToRightCounterClockwise2){
int choice = 2;
int shiftChoice = (rows - 1 - choice)%rows;
myCube.setChoice(choice);
myCube.setMode(Mode::LEFT_TO_RIGHT);
for (int i=0;i<rows;i++){
myCube.getCubeSide()[static_cast<int> (Side::LEFT)].getWall()[i][i] = Color::YELLOW;
myCube.getCubeSide()[static_cast<int> (Side::RIGHT)].getWall()[i][i] = Color::GREEN;
}
myCube.getCubeSide()[static_cast<int> (Side::LEFT)].getWall()[0][2] = Color::GREY;
myCube.getCubeSide()[static_cast<int> (Side::LEFT)].getWall()[2][0] = Color::BLACK;
myCube.getCubeSide()[static_cast<int> (Side::RIGHT)].getWall()[0][2] = Color::GREY;
myCube.getCubeSide()[static_cast<int> (Side::RIGHT)].getWall()[2][0] = Color::BLACK;
top = myCube.getCubeSide()[static_cast<int> (Side::TOP)];
bottom = myCube.getCubeSide()[static_cast<int> (Side::BOTTOM)];
left = myCube.getCubeSide()[static_cast<int> (Side::LEFT)];
right = myCube.getCubeSide()[static_cast<int> (Side::RIGHT)];
front = myCube.getCubeSide()[static_cast<int> (Side::FRONT)];
back = myCube.getCubeSide()[static_cast<int> (Side::BACK)];
//fmyCube.turn(Direction::COUNTER_CLOCK_WISE);
myCube.setDir(Direction::COUNTER_CLOCK_WISE);
myCube.turn();
for (int i=0;i<rows;i++){
int shift = (rows-i-1)%rows;
Color temp = top.getWall()[i][choice];
Color &lhs1 = top.getWall()[i][choice];
lhs1 = front.getWall()[i][choice];
Color &lhs2 = front.getWall()[i][choice];
lhs2 = bottom.getWall()[shift][shiftChoice];
Color &lhs3 = bottom.getWall()[shift][shiftChoice];
lhs3 = back.getWall()[shift][shiftChoice];
Color &lhs4 = back.getWall()[shift][shiftChoice];
lhs4 = temp;
}
right.getWall()[0][2] = Color::GREEN;
right.getWall()[2][0] = Color::GREEN;
right.getWall()[0][0] = Color::GREY;
right.getWall()[2][2] = Color::BLACK;
CHECK_SIDES_EQUAL;
}
|
Python
|
UTF-8
| 350
| 3.125
| 3
|
[] |
no_license
|
N=int(input())
d= [[0]*N for _ in range (N)]
x,y,r =map(int,input().split())
a = 0
for i in range(0,N):
for j in range(0,N):
a=abs(x-1-i)+abs(y-1-j)
if a<=r :
d[i][j]=a
else:
d[i][j]=0
if i+1==x and j+1==y :
d[i][j]='x'
for i in range(0,N):
for j in range(0,N):
print(d[i][j],end=' ')
print()
|
C++
|
UTF-8
| 2,809
| 3.4375
| 3
|
[] |
no_license
|
//
// Created by hqnddw on 2019/9/24.
//
#include <vector>
#include <stack>
using namespace std;
//双指针
class Solution1 {
public:
int trap(vector<int> &height) {
int left = 0;
int right = height.size() - 1;
int max_left = 0;
int max_right = 0;
int res = 0;
while (left < right) {
if (height[left] < height[right]) {
if (height[left] > max_left)
max_left = height[left];
else res += (max_left - height[left]);
left++;
} else {
if (height[right] > max_right)
max_right = height[right];
else res += (max_right - height[right]);
right--;
}
}
return res;
}
};
//栈
class Solution2 {
public:
int trap(vector<int> &height) {
stack<int> s;
int cur = 0;
int res = 0;
while (cur < height.size()) {
while (!s.empty() && height[cur] > height[s.top()]) {
int top = s.top();
s.pop();
if (s.empty())
break;
int distance = cur - s.top() - 1;
int bound_height = min(height[cur], height[s.top()]) - height[top];
res += distance * bound_height;
}
s.push(cur);
}
return res;
}
};
class Solution3 {
public:
int trap(vector<int> &height) {
int left = 0;
int right = height.size() - 1;
int max_left = 0;
int max_right = 0;
int res = 0;
while (left < right) {
if (height[left] < height[right]) {
if (height[left] > max_left)
max_left = height[left];
else res += (max_left - height[left]);
left++;
} else {
if (height[right] > max_right)
max_right = height[right];
else res += (max_right - height[right]);
right--;
}
}
return res;
}
};
class Solution4 {
public:
int trap(vector<int> &height) {
int n = height.size();
int left = 0, right = n - 1;
int max_left = 0, max_right = 0;
int res = 0;
while (left <= right) {
if (height[left] < height[right]) {
if (height[left] < max_left)
res += (max_left - height[left]);
else max_left = height[left];
left++;
} else {
if (height[right] > max_right)
max_right = height[right];
else res += (max_right - height[right]);
right--;
}
}
return res;
}
};
|
Markdown
|
UTF-8
| 6,052
| 2.546875
| 3
|
[
"OGL-Canada-2.0"
] |
permissive
|
> [Go to French version](/fr/Règlements/Textes%20réglementaires/2010/81.md)
# Statistics Canada Census and Survey Related Term Employment Exclusion Approval Order
**SI/2010-81**
Enabling authorities:
- [PUBLIC SERVICE EMPLOYMENT ACT](/en/Acts/Statutes%20of%20Canada/2003/c.%2022,%20ss.%2012,%2013%20.md)
Date registered: 10 November 2010
----------
His Excellency the Governor General in Council, on the recommendation of the Minister of Canadian Heritage, pursuant to section 20 of the [Public Service Employment Act](/en/Acts/Statutes%20of%20Canada/2003/c.%2022,%20ss.%2012,%2013%20.md)<sup><a href='#fn_1a'>[a]</a></sup>, hereby approves
<a name='fn_1a'><sup>a</sup></a>: S.C. 2003, c. 22, ss. 12 and 13<br />
**(a)** the re-application of the provisions of that Act to the positions excluded pursuant to the [Statistics Canada Census-Related Term Employment Exclusion Approval Order](/en/Regulations/Statutory%20Instruments/2010/45.md)<sup><a href='#fn_1b'>[b]</a></sup> and the persons occupying them, and
<a name='fn_1b'><sup>b</sup></a>: SI/2010-45<br />
**(b)** the exclusion from the application of the definitions deployment and internal appointment process in subsection 2(1) and of paragraphs 22(2)(a) to (c)<sup><a href='#fn_1c'>[c]</a></sup>, and sections 40, 41<sup><a href='#fn_1d'>[d]</a></sup>, 48, 51 to 53<sup><a href='#fn_1e'>[e]</a></sup>, 57, 59 and 62 of that Act to positions in Statistics Canada whose function is solely to provide administrative or management support or to perform data processing duties for the purpose of conducting the population census and the agriculture census as described in the [Statistics Act](/en/Acts/Revised%20Statutes%20of%20Canada/S/S-19.md)<sup><a href='#fn_1f'>[f]</a></sup>, or the National Household Survey made pursuant to sections 7 and 8 of the [Statistics Act](/en/Acts/Revised%20Statutes%20of%20Canada/S/S-19.md)<sup><a href='#fn_1f'>[f]</a></sup> when the survey replaces the population census long-form questionnaire and is conducted in conjunction with the population census and to the persons appointed or deployed to those positions on a specified term basis, except for other persons mentioned in subsection 5(1) of the Statistic Act<sup><a href='#fn_1f'>[f]</a></sup>.
<a name='fn_1c'><sup>c</sup></a>: S.C. 2006, c. 9, s. 100<br />
<a name='fn_1d'><sup>d</sup></a>: S.C. 2006, c. 9, s. 103<br />
<a name='fn_1e'><sup>e</sup></a>: S.C. 2006, c. 9, s. 104<br />
<a name='fn_1f'><sup>f</sup></a>: R.S., c. S-19<br />
Whereas the Public Service Commission has decided that it is neither practicable nor in the best interests of the public service to apply certain provisions of the [Public Service Employment Act](/en/Acts/Statutes%20of%20Canada/2003/c.%2022,%20ss.%2012,%2013%20.md)<sup><a href='#fn_1a'>[a]</a></sup> to positions in Statistics Canada whose function is solely to provide administrative or management support or to perform data processing duties for the purpose of conducting the population census and the agriculture census as described in the [Statistics Act](/en/Acts/Revised%20Statutes%20of%20Canada/S/S-19.md)<sup><a href='#fn_1f'>[f]</a></sup>, or the National Household Survey made pursuant to sections 7 and 8 of the [Statistics Act](/en/Acts/Revised%20Statutes%20of%20Canada/S/S-19.md)<sup><a href='#fn_1f'>[f]</a></sup> when it replaces the population census long-form questionnaire and is conducted in conjunction with the population census and to the persons appointed or deployed to those positions on a specified term basis, except for other persons mentioned in subsection 5(1) of the [Statistics Act](/en/Acts/Revised%20Statutes%20of%20Canada/S/S-19.md)<sup><a href='#fn_1f'>[f]</a></sup>;
And whereas, pursuant to subsection 20(2) of the [Public Service Employment Act](/en/Acts/Statutes%20of%20Canada/2003/c.%2022,%20ss.%2012,%2013%20.md)<sup><a href='#fn_1a'>[a]</a></sup>, the Public Service Commission has consulted with the employer;
Therefore, the Public Service Commission, pursuant to section 20 of the [Public Service Employment Act](/en/Acts/Statutes%20of%20Canada/2003/c.%2022,%20ss.%2012,%2013%20.md)<sup><a href='#fn_1a'>[a]</a></sup>, hereby
**(a)** reapplies the provisions of that Act to the positions excluded pursuant to the [Statistics Canada Census-Related Term Employment Exclusion Approval Order](/en/Regulations/Statutory%20Instruments/2010/45.md)<sup><a href='#fn_1b'>[b]</a></sup> and the persons occupying them, and
**(b)** excludes from the application of the definitions deployment and internal appointment process in subsection 2(1) and of paragraphs 22(2)(a) to (c)<sup><a href='#fn_1c'>[c]</a></sup>, and sections 40, 41<sup><a href='#fn_1d'>[d]</a></sup>, 48, 51 to 53<sup><a href='#fn_1e'>[e]</a></sup>, 57, 59 and 62 of that Act to positions in Statistics Canada whose function is solely to provide administrative or management support or to perform data processing duties for the purpose of conducting the population census and the agriculture census as described in the [Statistics Act](/en/Acts/Revised%20Statutes%20of%20Canada/S/S-19.md)<sup><a href='#fn_1f'>[f]</a></sup>, or the National Household Survey made pursuant to sections 7 and 8 of the [Statistics Act](/en/Acts/Revised%20Statutes%20of%20Canada/S/S-19.md)<sup><a href='#fn_1f'>[f]</a></sup> when the survey replaces the population census long-form questionnaire and is conducted in conjunction with the population census and to the persons appointed or deployed to those positions on a specified term basis, except for other persons mentioned in subsection 5(1) of the [Statistics Act](/en/Acts/Revised%20Statutes%20of%20Canada/S/S-19.md)<sup><a href='#fn_1f'>[f]</a></sup>.
This Order may be cited as the Statistics Canada Census and Survey Related Term Employment Exclusion Approval Order.
Ottawa, September 29, 2010
<p>MARIA BARRADOS<br />*President of the Public Service Commission*<br />MANON VENNAT<br />*Commissioner*<br />DAVID ZUSSMAN<br />*Commissioner*<br /></p>
|
C++
|
UTF-8
| 3,274
| 3.328125
| 3
|
[] |
no_license
|
#include "stdafx.h"
#include "book.h"
Book::Book(int bookID,std::string title, std::string author, std::string genre, int numberOfPages, Date dateOfPublication, bool availability) : bookID(bookID), title(title), author(author), genre(genre),
numberOfPages(numberOfPages), dateOfPublication(dateOfPublication), availability(availability)
{
}
Book::~Book()
{
}
bool Book::operator==(Book book)
{
if (this->GetBookID() == book.GetBookID())
return true;
else
return false;
}
int Book::GetBookID() const
{
return bookID;
}
std::string Book::GetTitle() const
{
return title;
}
std::string Book::GetAuthor() const
{
return author;
}
std::string Book::GetGenre() const
{
return genre;
}
int Book::GetNumberOfPages() const
{
return numberOfPages;
}
Date Book::GetDateOfPublication() const
{
return dateOfPublication;
}
bool Book::GetAvailability() const
{
return availability;
}
void Book::SetBookID(int bookID)
{
this->bookID = bookID;
}
void Book::SetTitle(std::string title)
{
this->title = title;
}
void Book::SetAuthor(std::string author)
{
this->author = author;
}
void Book::SetGenre(std::string genre)
{
this->genre = genre;
}
void Book::SetNumberOfPages(int numberOfPages)
{
this->numberOfPages = numberOfPages;
}
void Book::SetDateOfPublication(Date dateOfPublication)
{
this->dateOfPublication = dateOfPublication;
}
void Book::SetAvailability(bool availability)
{
this->availability = availability;
}
Book Book::createNew()
{
int ID;
std::string title;
std::string author;
std::string genre;
int numberOfPages;
Date dateOfPublication;
bool availability = 1;
std::cout << std::endl;
std::cout << "PODAJ NUMER INDENTYFIKACYJNY KSIAZKI : ";
std::cin >> ID;
std::cout << "PODAJ TYTUL KSIAZKI : ";
std::cin >> title;
std::cout << "PODAJ NAZWIKO AUTORA : ";
std::cin >> author;
std::cout << "PODAJ GATUNEK KSIAZKI : ";
std::cin >> genre;
std::cout << "PODAJ ILOSC STRON : ";
std::cin >> numberOfPages;
std::cout << "PODAJ DATE WYDANIA : ";
std::cin >> dateOfPublication;
return Book(ID,title, author, genre, numberOfPages, dateOfPublication, availability);
}
void Book::headLineBook()
{
std::cout << "ID|tytul|autor|gatunek|strony|data wydania|STATUS" << std::endl;
}
void Book::bookConsoleOut()
{
std::cout << bookID << " " << title << " " << author << " " << genre << " " << numberOfPages << " ";
dateOfPublication.dateConsoleOut();
std::cout << " ";
if (availability == 1)
std::cout << "DOSTEPNA";
else
std::cout << "NIEDOSTEPNA";
std::cout << std::endl;
}
std::ostream & operator<<(std::ostream & os, Book & book)
{
os << book.bookID << " " << book.title << " " << book.author << " " << book.genre << " " << book.numberOfPages << " "
<< book.dateOfPublication << " " << book.availability << std::endl;
return os;
}
//ewentualnie oddzielna metoda do wypisywania na konsoli
std::istream & operator>>(std::istream & is, Book & book)
{
is >> book.bookID;
is >> book.title;
is >> book.author;
is >> book.genre;
is >> book.numberOfPages;
is >> book.dateOfPublication;
is >> book.availability;
return is;
}
|
Shell
|
UTF-8
| 2,016
| 2.9375
| 3
|
[] |
no_license
|
#!/usr/bin/env zsh
function VmOpp(){
vmrun
}
function git_init_gitignore(){
echo "#----autogenerated gitignore----
.idea
*.iml
public/assets
.DS_Store
.ember.pid
node_modules/
bower_components/
/vendor/bundle
disabledServer/
/public/
#CocoaPods
Pods/
GpeneratedDocumentation/
Carthage.checkout/
/.bundle
#ios injection Project
iOSInjectionProject/
# Ignore the default SQLite database.
/db/*.sqlite3
/target
/log/*.log
/tmp
" >>| .gitignore
}
function git_setup(){
if [[ -d .git ]]; then
echo "Go home, You're drunk";
return;
fi
git_init_gitignore;
git init;
git add .
git commit -m "Initial commit"
if [ ! -z $1 ]; then
git_push_to_github $1
fi
}
function git_push_to_github(){
git remote add origin $1
git push origin master
}
function no_index_here(){
touch .metadata_never_index;
}
function all_update(){
if [[ -e ./Gemfile ]] {
bundle install
}
if [[ -e ./package.json ]] {
npm install
}
if [[ -e ./bower.json ]] {
bower install
}
if [[ -e ./cartfile ]] {
carthage update --no-use-binaries
}
if [[ -e ./Podfile ]] {
pod update
}
if [[ -d ./frontend ]] {
cd frontend;
all_update
cd ..;
}
}
reinstall_alcatraz(){
curl -fsSL https://raw.githubusercontent.com/supermarin/Alcatraz/deploy/Scripts/install.sh | sh;
}
clear_derived_data(){
rm -rf /Users/Joe/Library/Developer/Xcode/DerivedData
}
checksum_diff(){
local chk1=`cksum $1 | awk -F" " '{print $1}'`
local chk2=`cksum $2 | awk -F" " '{print $1}'`
if [ $chk1 -eq $chk2 ]
then
echo "File is identical"
else
echo "File is not identical"
fi
}
current_host_platform(){
if [[ "$(uname)" == "Darwin" ]]; then
echo "osx"
elif [ "$(expr substr $(uname -s) 1 5)" = "Linux" ]; then
echo "linux"
elif [ "$(expr substr $(uname -s) 1 10)" == "MINGW32_NT" ]; then
echo "win"
fi
}
synchronize_defaults(){
cd ~/Library/Preferences;
for f (IntelliJIdea2016.2 AppCode2016.2 AppCode2016.3); do
done
}
|
Java
|
UTF-8
| 424
| 2.640625
| 3
|
[] |
no_license
|
package com.buyalskaya.bookstorage.utility;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class DataParser {
private static final String REGEX_COMMA = ",";
public List<String> authorParser(String author) {
String[] authorsArray = author.split(REGEX_COMMA);
return Stream.of(authorsArray).map(p -> p.trim()).collect(Collectors.toList());
}
}
|
Java
|
UTF-8
| 9,003
| 2.21875
| 2
|
[] |
no_license
|
package com.example.rene.myarrow.misc;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.util.Log;
import com.example.rene.myarrow.R;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
/**
* Created by nily on 24.12.15.
*/
public class GetPicture extends Activity {
/** Kuerzel fuers Logging. */
private static final String TAG = GetPicture.class.getSimpleName();
// lokale Variablen
private Uri currentImageUri;
private String mDatei;
private Intent myIntent;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
// Context/Intent abspeichern
myIntent = getIntent();
// Übergangparameter abholen
final Bundle extras = getIntent().getExtras();
if (extras!=null && extras.containsKey(Konstante.IN_PARAM_DATEINAME_ID)) {
mDatei = extras.getString(Konstante.IN_PARAM_DATEINAME_ID);
mDatei = mDatei.replace(" ", "_");
} else {
Log.w(TAG, "oncreate(): Nichts übergeben");
}
// URI für Dateiname erstellen
if(currentImageUri==null && savedInstanceState==null){
currentImageUri = getImageFileUri(mDatei);
// es wurde kein Dateinamen übergeben
if (currentImageUri==null) return;
}
String currentImagePath;
if(savedInstanceState!=null){
currentImagePath = savedInstanceState.getString("currentImagePath");
currentImageUri = Uri.fromFile(new File(currentImagePath));
}else{
// Camera/Galerie starten
startActivityForResult(getPickImageIntent(this, currentImageUri), 1234);
}
}
private static Uri getImageFileUri(String m){
// TODO: Klasse für den Dateinamen erstellen
// Create a storage directory for the images
// To be safe(er), you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this
// Falls Verzeichnis nicht existiert, anlegen
File imagePath = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM), "MyArrow");
if (!imagePath.exists()){
if (!imagePath.mkdirs()){
Log.d(TAG, "getImageFileUri(): CameraTestIntent, failed to create directory");
return null;
}else{
Log.d(TAG,"create new MyArrow folder");
}
}
//
// Create an image file name
//
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.GERMAN).format(new Date());
String mFile = "MYA_" + m + "_" + timeStamp + ".jpg";
File image = new File(imagePath, mFile);
//
// Create an File Uri
//
return Uri.fromFile(image);
}
private void galleryAddPic() {
Log.d(TAG, "galleryAddPic(): Start");
/*
copy current image to Galerry
*/
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(currentImageUri);
this.sendBroadcast(mediaScanIntent);
Log.d(TAG, "galleryAddPic(): End");
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
Log.d(TAG, "onSaveInstanceState(): Start");
super.onSaveInstanceState(savedInstanceState);
Log.d(TAG, "onSaveInstanceState(): putString");
if (currentImageUri!=null) {
savedInstanceState.putString("currentImagePath", currentImageUri.getPath());
Log.d(TAG, "onSaveInstanceState(): currentImagePath - " + currentImageUri.getPath());
}
Log.d(TAG, "onSaveInstanceState(): End");
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//data available only when default environment is setting. null for customize filename.
switch (requestCode) {
case 1234:
if (resultCode == Activity.RESULT_OK) {
// Kamera oder Gallerie ?
final boolean isCamera;
if (data == null) {
// Keine Daten zurückbekommen, also wurde die Kamera benutzt
isCamera = true;
} else {
final String action = data.getAction();
// getAction hat nichts zurückgemeldet, also wurde die Kamera NICHT benutzt
isCamera = action != null && action.equals(MediaStore.ACTION_IMAGE_CAPTURE);
// keine Ahnung.....
}
// Path- und Dateinamen auslesen
String selectedImage;
if (isCamera) {
// Kamera - keine Änderung
// Dateiname
String mTemp = currentImageUri.toString();
mTemp = mTemp.replace("file://", "");
selectedImage = mTemp;
} else {
// Gallerie, wurde ausgewählt
// Let's read picked image data - its URI
Uri pickedImage = data.getData();
// Let's read picked image path using content resolver
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
if (cursor.moveToFirst()) {
selectedImage = cursor.getString(cursor.getColumnIndex(filePath[0]));
} else {
selectedImage = null;
}
cursor.close();
}
//
// Dateiname ist nicht leer....
//
if (selectedImage!=null && !selectedImage.equals("")) {
//
// In der Gallerie bekanntmachen
//
galleryAddPic();
//
// nur den Dateinamen zurückgeben, nicht den Pathnamen
//
myIntent.putExtra(Konstante.OUT_PARAM_DATEINAME_ID,
selectedImage.substring(selectedImage.indexOf("MYA_")));
setResult(Activity.RESULT_OK, myIntent);
}
} else if (resultCode == Activity.RESULT_CANCELED) {
// User cancelled the image capture
setResult(Activity.RESULT_CANCELED, myIntent);
} else {
// Image capture failed, advise user
setResult(Activity.RESULT_CANCELED, myIntent);
}
break;
}
finish();
}
public static Intent getPickImageIntent(Context context, Uri currentImageUri) {
Intent chooserIntent = null;
List<Intent> intentList = new ArrayList<>();
// aus der Gallerie auswählen
Intent pickIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/*");
// ein Foto aufnehmen
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePhotoIntent.putExtra("return-data", true);
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, currentImageUri);
intentList = addIntentsToList(context, intentList, pickIntent);
intentList = addIntentsToList(context, intentList, takePhotoIntent);
if (intentList.size() > 0) {
chooserIntent = Intent.createChooser(intentList.remove(intentList.size() - 1),
context.getString(R.string.txt_bitte_waehlen));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentList.toArray(new Parcelable[]{}));
}
return chooserIntent;
}
private static List<Intent> addIntentsToList(Context context, List<Intent> list, Intent intent) {
List<ResolveInfo> resInfo = context.getPackageManager().queryIntentActivities(intent, 0);
for (ResolveInfo resolveInfo : resInfo) {
String packageName = resolveInfo.activityInfo.packageName;
Intent targetedIntent = new Intent(intent);
targetedIntent.setPackage(packageName);
list.add(targetedIntent);
}
return list;
}
}
|
C#
|
UTF-8
| 3,785
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using ReactiveValidation.Validators.PropertyValueTransformers;
namespace ReactiveValidation
{
/// <summary>
/// Builder which allow create validation rules for properties.
/// </summary>
/// <typeparam name="TObject">Validatable object.</typeparam>
public interface IValidationBuilder <TObject>
where TObject : IValidatableObject
{
/// <summary>
/// Specifies how rules of property should cascade when one fails.
/// </summary>
public CascadeMode? PropertyCascadeMode { get; set; }
/// <summary>
/// Create validator for single strongly typed property.
/// </summary>
/// <typeparam name="TProp">The type of property.</typeparam>
/// <param name="property">Validatable property.</param>
/// <returns>Single property validator for <typeparamref name="TProp" /> type.</returns>
ISinglePropertyRuleBuilderInitial<TObject, TProp> RuleFor<TProp>(Expression<Func<TObject, TProp>> property);
/// <summary>
/// Create validator for single property with object type by its name.
/// </summary>
/// <param name="propertyName">Name of validatable property.</param>
/// <returns>Single property validator for <see cref="object"/> type.</returns>
ISinglePropertyRuleBuilderInitial<TObject, object?> RuleFor(string propertyName);
/// <summary>
/// Create validator for single strongly typed property with transforming type.
/// </summary>
/// <param name="property">Validatable property.</param>
/// <param name="valueTransformer">Value converter.</param>
/// <typeparam name="TProp">The source type of property.</typeparam>
/// <typeparam name="TPropConverter">The target type of property.</typeparam>
/// <returns>Single property validator for <typeparamref name="TPropConverter" /> type.</returns>
ISinglePropertyRuleBuilderInitial<TObject, TPropConverter> Transform<TProp, TPropConverter>(
Expression<Func<TObject, TProp>> property,
IValueTransformer<TObject, TPropConverter> valueTransformer);
/// <summary>
/// Create validator for collection of properties.
/// </summary>
/// <param name="properties">Validatable properties.</param>
/// <returns>Properties collection validator.</returns>
IPropertiesRuleBuilderInitial<TObject> RuleFor(params Expression<Func<TObject, object?>>[] properties);
/// <summary>
/// Create validator for collection of properties names.
/// </summary>
/// <param name="propertiesNames">Names of validatable properties.</param>
/// <returns>Properties collection validator.</returns>
IPropertiesRuleBuilderInitial<TObject> RuleFor(params string[] propertiesNames);
/// <summary>
/// Created validator for strongly typed collection.
/// </summary>
/// <typeparam name="TCollection">The type of collection.</typeparam>
/// <typeparam name="TProp">The type of element of collection.</typeparam>
/// <param name="collection">Property with collection type.</param>
/// <returns>Validator for property with <typeparamref name="TCollection"/> type.</returns>
ICollectionRuleBuilderInitial<TObject, TCollection, TProp> RuleForCollection<TCollection, TProp>(
Expression<Func<TObject, TCollection>> collection)
where TCollection : IEnumerable<TProp>;
/// <summary>
/// Create validator for instance.
/// </summary>
IObjectValidator Build(TObject instance);
}
}
|
C++
|
UTF-8
| 1,132
| 2.640625
| 3
|
[] |
no_license
|
#ifndef SPECIES_H
#define SPECIES_H
#include "player.h"
class Species
{
public:
Species(Genome *g);
bool isSameSpecies(const Genome &gen); // Is current genome in the same species as 'gen'
void calcAverageFitness(); // Average fitness (setter, not getter)
void sortGenomesByFitness();
void addToSpecies(Genome* genome);
Genome* selectParent(); // Select a genome from this species
Genome* createOffspring();
void decimateSpecies(); // Get rid of the unfit genomes in this species
void explicitFitnessSharing(); // Stops species from becoming too big
bool allowedReproduction; // If the staleness is high, species should not reproduce
Genome *representGenome; // pointer ?
double bestFitness;
double averageFitness;
unsigned stagnantCoeff;
std::vector<Genome*> genomes;
private:
// How many generations without an improvement
// Parameters for compatibility function
double excessCoeff;
double weightDiffCoeff;
double compatibilityThreshold;
};
#endif // SPECIES_H
|
C++
|
UTF-8
| 770
| 3.15625
| 3
|
[] |
no_license
|
/**
* @file bitByte.h
* @author Jan Wielgus (jan.wielgus12@gmail.com)
* @brief
* @date 2021-04-26
*
*/
#ifndef BITBYTE_H
#define BITBYTE_H
#include <IByteType.h>
class bitByte : public IByteType
{
union
{
bool bits[8];
uint8_t byte;
} data;
public:
bitByte()
{
}
bitByte(const bitByte& other)
{
data.byte = other.data.byte;
}
bitByte& operator=(const bitByte& other)
{
data.byte = other.data.byte; // don't need to check if this != &other
return *this;
}
uint8_t* byteArray() override
{
return &data.byte;
}
const uint8_t* byteArray() const override
{
return &data.byte;
}
uint8_t byteSize() const override
{
return 1;
}
bool* bitArray()
{
return data.bits;
}
const bool* bitArray() const
{
return data.bits;
}
};
#endif
|
Java
|
UTF-8
| 5,829
| 3.921875
| 4
|
[] |
no_license
|
import java.io.*;
import java.util.*;
public class expressionEvaluator {
static String delimiters="+-*%()";
/* This method evaluates the given arithmetic expression and returns
* its Integer value. The method throws an Exception if the expression
* is malformed.*/
static Integer evaluate( String expr ) throws Exception {
StringTokenizer st = new StringTokenizer( expr , delimiters , true );
Stack<Integer> intArgs = new Stack<Integer>();
Stack<String> delimiterArgs = new Stack<String>();
if(!bracketMatch(expr)){
throw new Exception() ;//Malformed expression given as input, throw exception
}
/*Fill the integer and delimiter argument stacks with tokens from input string*/
while (st.hasMoreTokens() ) {
String token = st.nextToken();//Store current token for sorting
if(token.equals(")")){
/*\ Do not add bracket to delimiterArgs, stripping it from expression. Instead, take contents of brackets
* and perform specified operation on them
\*/
Integer product = performOperation(intArgs.pop(), intArgs.pop(), delimiterArgs.pop());
intArgs.push(product);
}
else if(token.equals("("));//Do nothing in this case. This strips the bracket from the expression
else if(isInt(token)){ //Store the integer in the stack
intArgs.push(Integer.parseInt(token));
}
else{ //Store the operator
delimiterArgs.push(token);
}
}
/*Evaluate the simplified expression contained in our stacks*/
while(!(delimiterArgs.empty())){
Integer product = performOperation(intArgs.pop(), intArgs.pop(), delimiterArgs.pop());
intArgs.push(product);
}
return intArgs.pop();
} // end of evaluate
/*\
* Helper method for evaluate. Takes as input the user generated expression, and tests it to make sure that
* , at least in terms of brackets, it is a well formed expression. Method tests for:
* ->Bracket matching. Every open bracket must have a closing bracket
* ->Integer values and arithmatic operators inside brackets. An expression such as 3+() would be considered malformed.
* Method returns boolean value true if expression is well formed, and false otherwise
\*/
static boolean bracketMatch(String expression)throws Exception{
Stack<Character> bracketSum = new Stack<Character>();//This stack will keep track of brackets which are yet to be closed
for(int i = 0; i < expression.length()-1; i++){
if(expression.charAt(i) == '('){
//Check for empty sets of brackets
if(expression.charAt(i+1) == ')'){
return false;
}
Character openBrac = new Character(expression.charAt(i));
bracketSum.push(openBrac);//Add open bracket to total
}
else if(expression.charAt(i) == ')'){
/*\ Two cases covered here. Either we have a closing bracket where there should not be one, in which case
* an EmptyStackException is thrown, or else we have closed an open bracket, in which case we
* remove a bracket from bracketSun
\*/
bracketSum.pop();
}
}
//Check last character in expression.
if(expression.charAt(expression.length()-1) == '(')
return false;
else if(expression.charAt(expression.length()-1) == ')'){
bracketSum.pop();
}
//Check to see if all brackets closed
else if(!bracketSum.empty()){
return false;
}
return true;
}
/*\
* Helper method for evaluate. Tests a token to see if it is an integer, returns boolean value to this effect.
* Used in sorting tokens into integer and delimiter arguments
\*/
static boolean isInt(String token){
try{
Integer.parseInt(token);
return true;
}
catch(NumberFormatException e){
return false;
}
}
/*\
* Helper method for evaluate. Performs arithmatical operation defined by operand on the two Integer parameters
*
\*/
static Integer performOperation(Integer a, Integer b, String op){
Integer opProduct;
if(op.equals("+")){
opProduct = b + a;
}
else if(op.equals("-")){
opProduct = b - a;
}
else if(op.equals("*")){
opProduct = b * a;
}
else if(op.equals("%")){
opProduct = b / a;
}
else{
opProduct = null;
}
return opProduct;
}
/* This method repeatedly asks the user for an expression and evaluates it.
The loop stops when the user enters an empty expression */
public void queryAndEvaluate() throws Exception {
String line;
BufferedReader stdin = new BufferedReader(new InputStreamReader( System.in ) );
System.out.println("Enter an expression");
line = stdin.readLine();
while ( line.length() > 0 ) {
try {
Integer value = evaluate( line );
System.out.println("value = " + value );
}
catch (Exception e)
{
System.out.println("Malformed Expression.");
}
System.out.println( "Enter an expression" );
line = stdin.readLine();
} // end of while loop
} // end of query and evaluate
public static void main(String args[]) throws Exception {
expressionEvaluator e=new expressionEvaluator();
e.queryAndEvaluate();
} // end of main
}
// 2013
|
C++
|
UHC
| 1,806
| 3.4375
| 3
|
[] |
no_license
|
// https://www.acmicpc.net/problem/1316
/*
ܾ ܾ ϴ ڿ ؼ, ڰ ؼ Ÿ 츸 Ѵ. , ccazzzzbb c, a, z, b ؼ Ÿ, kin k, i, n ؼ Ÿ ܾ, aabbbccb b Ÿ ܾ ƴϴ.
ܾ N Է ܾ ϴ α ۼϽÿ.
Է
ù° ٿ ܾ N ´. N 100 ۰ų ڿ̴. ° ٺ N ٿ ܾ ´. ܾ ĺ ҹڷθ Ǿְ ߺ , ̴ ִ 100̴.
ù° ٿ ܾ Ѵ.
*/
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int N;
cin >> N; // case
int count = 0; // ܾ count
string str;
for (int i = 0; i < N; ++i)
{
cin >> str;
int j = 0;
vector<char>ch;
while (str[j] != '\0') // Null character ƴҰ
{
if (str[j] != str[j + 1])
{
ch.push_back(str[j]);
vector<char>::iterator itr;
itr = find(ch.begin(), ch.end(), str[j + 1]); // <algorithm> findҵ str[j+1] ִٸ index iterator ϰ, ٸ .end() iterator
if (itr != ch.end()) // str[j+1]
break;
}
j++;
}
if (str[j] == '\0') // while Ƿ ̴ܾ.
count++;
}
cout << count;
return 0;
}
|
PHP
|
UTF-8
| 2,518
| 3.078125
| 3
|
[] |
no_license
|
<?php
namespace DevBoardLib\GithubCore\Commit;
use DevBoardLib\GithubCore\User\GithubUserId;
/**
* @todo: Reason this class exists
*/
class GithubCommitCommitter
{
/** @var string */
private $name;
/** @var string */
private $email;
/** @var GithubUserId */
private $githubUserId;
/** @var string */
private $username;
/** @var string */
private $avatarUrl;
/**
* Author constructor.
*
* @param $name
* @param $email
* @param $githubUserId
* @param $username
* @param $avatarUrl
*/
public function __construct(
string $name,
string $email,
GithubUserId $githubUserId = null,
string $username = null,
string $avatarUrl = null
) {
$this->name = $name;
$this->email = $email;
$this->githubUserId = $githubUserId;
$this->username = $username;
$this->avatarUrl = $avatarUrl;
}
/** @return string */
public function getName() : string
{
return $this->name;
}
/** @return string */
public function getEmail() : string
{
return $this->email;
}
/** @return GithubUserId */
public function getGithubUserId() : GithubUserId
{
return $this->githubUserId;
}
/** @return string */
public function getUsername() : string
{
return $this->username;
}
/** @return string */
public function getAvatarUrl() : string
{
return $this->avatarUrl;
}
/** @return array */
public function serialize()
{
return [
'name' => $this->name,
'email' => $this->email,
'githubUserId' => (string) $this->githubUserId,
'username' => $this->username,
'avatarUrl' => $this->avatarUrl,
];
}
/**
* @param array $data
*
* @throws \Exception
*
* @return static
*/
public static function deserialize(array $data)
{
return new static(
$data['name'],
$data['email'],
self::unSerializeId($data['githubUserId']),
$data['username'],
$data['avatarUrl']
);
}
/**
* @param $id
*
* @return GithubUserId|null
*/
private static function unSerializeId($id)
{
if (null === $id) {
return null;
}
return new GithubUserId((int) $id);
}
}
|
Java
|
UTF-8
| 377
| 1.9375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.singularitylab.infakt.client;
import org.singularitylab.infakt.client.model.Invoice;
import org.singularitylab.infakt.client.model.InvoiceLanguage;
import java.util.List;
/**
* @author Jakub Dzon
*/
public interface InvoiceClient {
List<Invoice> findAll();
Invoice create(Invoice invoice);
byte[] print(Invoice invoice, InvoiceLanguage language);
}
|
Java
|
UTF-8
| 1,299
| 2.109375
| 2
|
[] |
no_license
|
package com.ruhul.study.controller;
import org.camunda.bpm.engine.ProcessEngine;
import org.camunda.bpm.engine.variable.Variables;
import org.camunda.bpm.model.dmn.instance.Variable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.UUID;
@RestController
//@RequestMapping("/order")
public class CumundaController {
@Autowired
ProcessEngine camunda;
@RequestMapping(path="/order", method = RequestMethod.POST)
public void placeOrder(String orderId, int amount){
System.out.println("Starting the process");
camunda.getRuntimeService().startProcessInstanceByKey("order", Variables.putValue("OrderId", orderId).putValue("amount", amount));
}
@RequestMapping(path = "/confirm", method = RequestMethod.POST)
public void confirmShipment(String orderId){
camunda.getRuntimeService().createMessageCorrelation("Message_GoodsShipped") //
.processInstanceVariableEquals("OrderId", orderId) //
.setVariable("shipmentId", UUID.randomUUID().toString()) //
.correlateWithResult();
}
}
|
JavaScript
|
UTF-8
| 598
| 4.09375
| 4
|
[] |
no_license
|
// Generators
// functions that can be paused resume cycle midway through executions
// allows us to create a special type of iterator, whose execution can
// be suspended and retained while keeping the context
// it contains one or more yield expressions
// it uses the function * syntax
function *gen() {
yield "Hello";
yield "from";
yield "generator";
}
// it will not be executed; instead it returns an iterator that will be
// used to execute the code inside it.
let obj = gen();
console.log(obj.next());
console.log(obj.next());
console.log(obj.next());
console.log(obj.next());
|
Java
|
UTF-8
| 177
| 1.875
| 2
|
[] |
no_license
|
package dao;
import model.Admin;;
public interface AdminDao {
//-------- 관리자 id 찾기
public Admin findByAdminId(Admin admin);
public String findId(String id);
}
|
PHP
|
UTF-8
| 9,516
| 2.859375
| 3
|
[] |
no_license
|
<?php
//namespace phpProject;
class Post
{
private $image;
private $image_text;
/**
* Get the value of image.
*/
public function getImage()
{
return $this->image;
}
/**
* Set the value of image.
*
* @return self
*/
public function setImage($image)
{
$this->image = $image;
return $this;
}
/**
* Get the value of image_text.
*/
public function getImage_text()
{
return $this->image_text;
}
/**
* Set the value of image_text.
*
* @return self
*/
public function setImage_text($image_text)
{
$this->image_text = $image_text;
return $this;
}
/*
Alle posts van de databank halen
*/
public static function get($limit = 20, $offset = 0)
{
$conn = Db::getInstance();
// ID uit de database halen
$stm = $conn->prepare("SELECT id FROM users WHERE email = '".$_SESSION['email']."'");
$stm->execute();
$id = $stm->fetch(PDO::FETCH_COLUMN);
// Alle post laden van de gevolgde personen
$statement = $conn->prepare("SELECT posts.id,posts.image,posts.image_text,posts.user_id,
posts.date AS images_date,users.profileImg,filters.name
FROM posts,followers,users,filters
WHERE followers.user_id1=:id
AND followers.user_id2=posts.user_id
AND followers.user_id2 = users.id
AND posts.filter_id = filters.id
UNION SELECT posts.id,posts.image,posts.image_text,posts.user_id,posts.date,users.profileImg,filters.name
FROM posts,users,filters
WHERE posts.user_id =:id AND users.id=:id AND posts.filter_id = filters.id ORDER BY `images_date` DESC limit $limit offset $offset");
$statement->bindValue(':id', $id);
$statement->execute();
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
public static function detailPagina($id)
{
$conn = Db::getInstance();
$statement = $conn->prepare("SELECT posts.id,posts.image,posts.image_text,posts.user_id,posts.date,posts.filter_id, filters.name, users.profileImg, posts.date
FROM posts,filters,users where posts.id = $id AND filters.id=posts.filter_id AND users.id= posts.user_id");
$statement->execute();
$collection = $statement->fetchAll();
return $collection;
}
public static function profilePic($id)
{
$conn = Db::getInstance();
$statement = $conn->prepare("SELECT users.profileImg FROM posts,users
WHERE posts.user_id = users.id AND posts.id = $id");
$statement->execute();
$profilePic = $statement->fetch();
return $profilePic;
}
public static function detectColors($image, $num, $level = 5)
{
// aantal kleuren
$level = (int) $level;
// een array voor het pallet
$palette = array();
// de afbeelding
$size = getimagesize($image);
if (!$size) {
return false;
}
switch ($size['mime']) {
case 'image/jpeg':
// returns an image identifier representing the image obtained from the given filename.
$img = imagecreatefromjpeg($image);
break;
case 'image/png':
$img = imagecreatefrompng($image);
break;
case 'image/gif':
$img = imagecreatefromgif($image);
break;
default:
return false;
}
if (!$img) {
return false;
}
// inde hoogte en breedte de foto afgaan en daar de 5 meest primare kleuren zoeken
for ($i = 0; $i < $size[0]; $i += $level) {
for ($j = 0; $j < $size[1]; $j += $level) {
$thisColor = imagecolorat($img, $i, $j);
$rgb = imagecolorsforindex($img, $thisColor);
$color = sprintf('%02X%02X%02X', (round(round(($rgb['red'] / 0x66)) * 0x66)), round(round(($rgb['green'] / 0x66)) * 0x66), round(round(($rgb['blue'] / 0x66)) * 0x66));
$palette[$color] = isset($palette[$color]) ? ++$palette[$color] : 1;
}
}
arsort($palette);
return array_slice(array_keys($palette), 0, $num);
}
public static function search($search)
{
$conn = Db::getInstance();
$stmt = $conn->prepare("SELECT posts.id,posts.image,posts.image_text,posts.date,filters.name,users.profileImg FROM users,colors,posts,filters
WHERE posts.image_text like CONCAT('%', :search, '%')
AND filters.id =posts.filter_id AND users.id=posts.user_id
UNION SELECT posts.id,posts.image,posts.image_text,posts.date,filters.name,users.profileImg
FROM users,colors,posts,filters WHERE colors.color like
CONCAT('%', :search, '%') AND filters.id =posts.filter_id AND users.id=posts.user_id
AND posts.id=colors.post_id");
$stmt->bindParam(':search', $search);
$stmt->execute();
$search = $stmt->fetchAll();
return $search;
}
public static function getLikes($id)
{
$conn = Db::getInstance();
$statement = $conn->prepare('SELECT count(*) AS count FROM likes WHERE likes.post_id = :post_id');
$statement->bindParam(':post_id', $id);
$statement->execute();
$result = $statement->fetch(PDO::FETCH_COLUMN);
return $result;
}
public static function getColors($id)
{
$conn = Db::getInstance();
$statement = $conn->prepare("SELECT color FROM colors where post_id = $id");
$statement->execute();
$colors = $statement->fetchAll(PDO::FETCH_COLUMN);
return $colors;
}
public static function getFilters()
{
$conn = Db::getInstance();
$statement = $conn->prepare('SELECT * FROM filters');
$statement->execute();
$filters = $statement->fetchAll(PDO::FETCH_ASSOC);
return $filters;
}
public static function getOwnPosts()
{
$conn = Db::getInstance();
// ID uit de database halen
$stm = $conn->prepare("SELECT id FROM users WHERE email = '".$_SESSION['email']."'");
$stm->execute();
$id = $stm->fetch(PDO::FETCH_COLUMN);
$statement = $conn->prepare('SELECT posts.id,posts.image,posts.image_text,posts.user_id, posts.date,users.profileImg,filters.name
FROM posts,users,filters WHERE posts.filter_id = filters.id
AND users.id = posts.user_id AND users.id=:id ORDER BY posts.date DESC');
$statement->bindValue(':id', $id);
$statement->execute();
$posts = $statement->fetchAll();
return $posts;
}
public static function getPosts($id)
{
$conn = Db::getInstance();
$statement = $conn->prepare('SELECT posts.id,posts.image,posts.image_text,posts.user_id, posts.date,users.profileImg,filters.name
FROM posts,users,filters WHERE posts.filter_id = filters.id
AND users.id = posts.user_id AND users.id=:id ORDER BY posts.date DESC');
$statement->bindValue(':id', $id);
$statement->execute();
$posts = $statement->fetchAll();
return $posts;
}
public static function getTimeAgo($time)
{
$conn = Db::getInstance();
$stm = $conn->prepare("SELECT id FROM users WHERE email = '".$_SESSION['email']."'");
$stm->execute();
$id = $stm->fetch(PDO::FETCH_COLUMN);
$statement = $conn->prepare('SELECT posts.id,posts.date FROM posts WHERE posts.date = :time');
$statement->bindValue(':time', $time);
$statement->execute();
$estimate_time = time() - $time;
if ($estimate_time < 1) {
return 'less than 1 second ago';
}
$condition = array(
12 * 30 * 24 * 60 * 60 => 'year',
30 * 24 * 60 * 60 => 'month',
24 * 60 * 60 => 'day',
60 * 60 => 'hour',
60 => 'minute',
1 => 'second',
);
foreach ($condition as $sec => $str) {
$d = $estimate_time / $sec;
if ($d >= 1) {
$r = round($d);
return ' About '.$r.' '.$str.($r > 1 ? 's' : ' ').' ago ';
}
}
}
public static function getAll()
{
$conn = Db::getInstance();
$statement = $conn->prepare('SELECT posts.id,posts.image,posts.image_text,posts.user_id, posts.date,users.profileImg,filters.name
FROM posts,users,filters WHERE posts.filter_id = filters.id
AND users.id = posts.user_id ORDER BY posts.date DESC');
$statement->execute();
$posts = $statement->fetchAll();
return $posts;
}
/* public static function deleteEdit()
{
$conn = Db::getInstance();
if(isset($_POST['submit'])){
}
$stm = $conn->prepare("SELECT id FROM users WHERE email = '".$_SESSION['email']."'");
$stm->execute();
$userid = $stm->fetch(PDO::FETCH_COLUMN);
$stm = $conn->prepare("DELETE FROM posts WHERE posts.id,posts.image_text,posts.image,posts.date WHERE posts.id = $postsid");
$insert->bindParam(':bio', $bio);
$insert->execute();
if($stm->execute())
{
$msg = 'Uw post is verwijderd.';
header('location:profiel.php');
}
else {
$msg = 'Something went wrong.';
}
}
}*/
}
|
Java
|
UTF-8
| 5,831
| 1.664063
| 2
|
[] |
no_license
|
package com.platform.top.xiaoyu.run.service.finance.controller.backstage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.platform.top.xiaoyu.run.service.api.auth.annotaions.ButtonDefine;
import com.platform.top.xiaoyu.run.service.api.auth.enums.InternalResource;
import com.platform.top.xiaoyu.run.service.api.common.token.SecurityUtil;
import com.platform.top.xiaoyu.run.service.api.common.vo.req.IdReq;
import com.platform.top.xiaoyu.run.service.api.common.vo.resp.PageResp;
import com.platform.top.xiaoyu.run.service.api.finance.constant.TopBookConstant;
import com.platform.top.xiaoyu.run.service.api.finance.exception.BaseExceptionType;
import com.platform.top.xiaoyu.run.service.api.finance.vo.BankBindingVO;
import com.platform.top.xiaoyu.run.service.api.finance.vo.BusinessVO;
import com.platform.top.xiaoyu.run.service.api.finance.vo.req.bankbinding.BankBindingPageReq;
import com.platform.top.xiaoyu.run.service.finance.service.IBankBindingService;
import com.top.xiaoyu.rearend.boot.controller.TopBaseController;
import com.top.xiaoyu.rearend.component.swagger.controller.BackstageController;
import com.top.xiaoyu.rearend.log.annotation.ApiLog;
import com.top.xiaoyu.rearend.tool.api.R;
import com.top.xiaoyu.rearend.tool.exception.BizBusinessException;
import com.top.xiaoyu.rearend.tool.util.bean.BeanCopyUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
//import org.chwin.firefighting.apiserver.data.SpringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.function.Consumer;
/**
* 绑定银行卡 控制器
*
* @author coffey
*/
@RestController
@AllArgsConstructor
@RequestMapping(TopBookConstant.BACKSTAGE_BANDKBD)
@Api(value = "绑定银行卡", tags = "绑定银行卡")
@BackstageController
//@MenuDefine(name = "绑定银行卡", moduleName = "BankBinding", parentCode = "financeManage")
public class BankBindingController extends TopBaseController {
public static void main(String[] args) {
System.out.println( System.getProperty("spring.profiles.active"));
System.out.println( System.getProperty("top.env"));
// BankBindingController bean = SpringUtil.getBean(BankBindingController.class);
// BankBindingController bean = SpringUtil.get (BankBindingController.class);
// BankBindingPageReq pagereq=new BankBindingPageReq();
// System.out.println(bean.findPage(pagereq ));
}
BankBindingController(){}
@Value("${top.fastdfs.url}")
private String fastDfsUrl;
@Autowired
private IBankBindingService iBankBindingService;
@PostMapping("/findPage")
@ApiOperation(value = "分页查询绑定银行卡记录", notes = "分页查询绑定银行卡记录")
@ApiLog("分页查询绑定银行卡记录")
@ButtonDefine(name = "分页查询绑定银行卡记录", internal = InternalResource.ADMIN)
public R<PageResp<BankBindingVO>> findPage(@RequestBody @Validated BankBindingPageReq req) {
if(req.getPage() <= 0 ) {
throw new BizBusinessException(BaseExceptionType.PARAM_PAGE);
}
if(req.getSize() <= 0 ) {
throw new BizBusinessException(BaseExceptionType.PARAM_SIZE);
}
Page<BankBindingVO> page = new Page<BankBindingVO>(req.getPage(), req.getSize());
BankBindingVO vo = BeanCopyUtils.copyBean(req, BankBindingVO.class);
vo.setPlatformId(SecurityUtil.getLoginAccount().getPlatformId());
Page<BankBindingVO> page1 = iBankBindingService.findPage(page, vo);
//set abs path
try{
page1.getRecords().forEach(new Consumer<BankBindingVO>() {
@Override
public void accept(BankBindingVO bankBindingVO) {
if( !bankBindingVO.getUrlIcon().startsWith("htt")) {
bankBindingVO.setUrlBackroug(fastDfsUrl + bankBindingVO.getUrlBackroug());
bankBindingVO.setUrlIcon(fastDfsUrl + "" + bankBindingVO.getUrlIcon());
}
}
});
}catch(Exception e ){
e.printStackTrace();
}
return R.data(new PageResp( page1));
}
@PostMapping("/updateCancel")
@ApiOperation(value = "作废数据", notes = "作废数据")
@ApiLog("作废数据")
@ButtonDefine(name = "作废数据", internal = InternalResource.ADMIN)
public R updateCancel(@RequestBody @Validated IdReq req) {
if( null != req && req.getId() != null && req.getId() > 0 ) {
return R.data(iBankBindingService.updateCancal(req.getId(), SecurityUtil.getLoginAccount().getPlatformId()));
}
throw new BizBusinessException(BaseExceptionType.PARAM_ID);
}
@PostMapping("/updateEnable")
@ApiOperation(value = "启用数据", notes = "启用数据")
@ApiLog("启用数据")
@ButtonDefine(name = "启用数据", internal = InternalResource.ADMIN)
public R updateEnable(@RequestBody @Validated IdReq req) {
if( null != req && req.getId() != null && req.getId() > 0 ) {
return R.data(iBankBindingService.updateEnable(req.getId(), SecurityUtil.getLoginAccount().getPlatformId()));
}
throw new BizBusinessException(BaseExceptionType.PARAM_ID);
}
@PostMapping("/del")
@ApiOperation(value = "删除数据", notes = "删除数据")
@ApiLog("删除数据")
@ButtonDefine(name = "删除数据", internal = InternalResource.ADMIN)
public R del(@RequestBody @Validated List<Long> ids) {
if(CollectionUtils.isEmpty(ids)) {
throw new BizBusinessException(BaseExceptionType.PARAM_ID);
}
return R.data(iBankBindingService.del(ids, SecurityUtil.getLoginAccount().getPlatformId()));
}
}
|
JavaScript
|
UTF-8
| 2,004
| 2.984375
| 3
|
[] |
no_license
|
export const ADD_DATA = 'LOAD_DATA';
export const SET_SORTING_FIELD = 'SET_SORTING_FIELD';
function requestApi(url) {
const promise = new Promise((resolve, reject)=>{
let xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = () => {
if (xhr.status == 200) {
resolve(xhr.response);
} else {
reject(xhr.statusText);
}
};
xhr.onerror = () => reject(xhr.statusText);
xhr.send();
});
return promise;
}
function assembleData(houses, characters) {
let data = [];
houses.forEach((house)=>{
data.push({
name: house.name,
region: house.region,
characters: house.swornMembers.map((characterId)=>{
return characters[characterId] !== undefined ? characters[characterId].name : '';
})
})
})
return data;
}
export function loadData() {
return function(dispatch) {
let houses = [],
characterIds = [],
characters = {},
assembledData;
requestApi('https://www.anapioficeandfire.com/api/houses').then(
result => {
let intervalCounter = 0,
interval;
houses = JSON.parse(result);
houses.forEach((house)=>{
house.swornMembers.forEach((characterId)=>{
if (characterIds.indexOf(characterId) === -1){
characterIds.push(characterId);
requestApi(characterId).then(
result => {
characters[characterId] = JSON.parse(result);
}
);
};
});
});
interval = setInterval(()=>{
if (intervalCounter > 200) {
clearInterval(interval);
};
if (Object.keys(characters).length === characterIds.length ){
assembledData = assembleData(houses, characters);
dispatch(addData(assembledData));
clearInterval(interval);
}
intervalCounter++;
}, 30);
}
);
}
}
export function addData(data) {
return {
type: ADD_DATA,
data: data
}
}
export function setSortingField(field) {
return {
type: SET_SORTING_FIELD,
field: field
}
}
|
Java
|
UTF-8
| 13,920
| 1.945313
| 2
|
[] |
no_license
|
package com.ysmind.modules.form.model;
import java.util.Date;
import com.ysmind.modules.sys.model.BaseModel;
public class CreateProjectModel extends BaseModel{
private String serialNumber;//流水号
private String flowStatus;//表单状态,即流程状态,因为一个表单只允许发起一条流程
private String officeId; // 归属机构(分公司/办事处)
private String officeCode;
private String officeName;
private String flowId;// '流程id',这个还是要比较好,虽然是通过分公司及表单类型可以去找到绑定当前类型的流程,
private String applyUserId;// '申请人id',
private String applyUserName;// '申请人id',
private Date applyDate;// '申请时间',
private String projectType;// '项目类型',
private String projectName;// '项目名称',
private String projectNumber;// '项目编号',
private String isCreateProject;// '是否为创新类项目',
private String isReplaceProject;// '是否为替代类项目',
private String ifNewType;//是否新型
private String sponsorIds;// 'Sponsor',
private String sponsorNames;// 'Sponsor',
private String leaderIds;// 'Leader',
private String leaderNames;// 'Leader',
private String projectSponsorType;// '项目发起分类',
private String acsNumber;// 'ACS编号',
private String fixedAssets;// '是否固定资产,是否涉及固定资产:选选择是,则需要增加运营总监审批节点',
private String clientYearDemanded;// '客户年需求量',
private String clientYearDemandedAmount;//客户年需求金额
private String clientYearDemandedUnit;// '单位',
private String myPortion;// '我司的份额(%)',
private String competitorSituation;// '竞争对手情况',
private String yearSaleroom;// '年销售额=客户年需求金额*我司的份额(%)',
private String weOpportunity;// '我们的机会%',
private String gcm;// 'GCM',
private String sampleCostInput;// '样品费用投入',
private String fixedAssetsInput;// '固定资产投入',
private String advantage;// '优势',
private String projectInvolveGuest;// '项目涉及的客户',
private String projectInvolveGuestId;// '项目涉及的客户',
private String projectInvolveGuestNumber;// '项目涉及的客户',
private String technologyDifficulty;// '技术难点',
private String productConstruction;// '对应的产品结构',
private String businessTarget;// '商务方面',
private String level;//'level等级',
private String levelValue;//'level等级',
private Date projectStartTime;// '项目开始时间',
private Date projectVerifyTime;// '项目验证时间',
private Date businessOrderTime;// '商务订单时间',
private Date projectFinishTime;// '项目完成时间',
private String researchPrincipalIds;// '研发负责人',
private String researchPrincipalNames;// '研发负责人',
private String sellPrincipalIds;// '销售负责人',
private String sellPrincipalNames;// '销售负责人',
private String teamParticipantIds;// '团队其他成员',
private String teamParticipantNames;// '团队其他成员',
private String onlySign;//标记,因为一个流程可以同时发起多个审批,所以每个审批之间要区分开来
private String terminationStatus;//终止、正常
private String sampleApplyTimes;//样品申请次数
private String currentOperator;//当前显示当前激活的节点对应的审批人
private Date applyDateEnd;// '申请时间',
private Date projectStartTimeEnd;// '项目开始时间',
private Date projectVerifyTimeEnd;// '项目验证时间',
private Date businessOrderTimeEnd;// '商务订单时间',
private Date projectFinishTimeEnd;// '项目完成时间',
private String queryCascade;//是否级联查询,用于优化查询速度
public String getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(String serialNumber) {
this.serialNumber = serialNumber;
}
public String getFlowStatus() {
return flowStatus;
}
public void setFlowStatus(String flowStatus) {
this.flowStatus = flowStatus;
}
public String getOfficeId() {
return officeId;
}
public void setOfficeId(String officeId) {
this.officeId = officeId;
}
public String getOfficeCode() {
return officeCode;
}
public void setOfficeCode(String officeCode) {
this.officeCode = officeCode;
}
public String getOfficeName() {
return officeName;
}
public void setOfficeName(String officeName) {
this.officeName = officeName;
}
public String getFlowId() {
return flowId;
}
public void setFlowId(String flowId) {
this.flowId = flowId;
}
public String getApplyUserId() {
return applyUserId;
}
public void setApplyUserId(String applyUserId) {
this.applyUserId = applyUserId;
}
public String getApplyUserName() {
return applyUserName;
}
public void setApplyUserName(String applyUserName) {
this.applyUserName = applyUserName;
}
public Date getApplyDate() {
return applyDate;
}
public void setApplyDate(Date applyDate) {
this.applyDate = applyDate;
}
public String getProjectType() {
return projectType;
}
public void setProjectType(String projectType) {
this.projectType = projectType;
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public String getProjectNumber() {
return projectNumber;
}
public void setProjectNumber(String projectNumber) {
this.projectNumber = projectNumber;
}
public String getIsCreateProject() {
return isCreateProject;
}
public void setIsCreateProject(String isCreateProject) {
this.isCreateProject = isCreateProject;
}
public String getIsReplaceProject() {
return isReplaceProject;
}
public void setIsReplaceProject(String isReplaceProject) {
this.isReplaceProject = isReplaceProject;
}
public String getIfNewType() {
return ifNewType;
}
public void setIfNewType(String ifNewType) {
this.ifNewType = ifNewType;
}
public String getSponsorIds() {
return sponsorIds;
}
public void setSponsorIds(String sponsorIds) {
this.sponsorIds = sponsorIds;
}
public String getSponsorNames() {
return sponsorNames;
}
public void setSponsorNames(String sponsorNames) {
this.sponsorNames = sponsorNames;
}
public String getLeaderIds() {
return leaderIds;
}
public void setLeaderIds(String leaderIds) {
this.leaderIds = leaderIds;
}
public String getLeaderNames() {
return leaderNames;
}
public void setLeaderNames(String leaderNames) {
this.leaderNames = leaderNames;
}
public String getProjectSponsorType() {
return projectSponsorType;
}
public void setProjectSponsorType(String projectSponsorType) {
this.projectSponsorType = projectSponsorType;
}
public String getAcsNumber() {
return acsNumber;
}
public void setAcsNumber(String acsNumber) {
this.acsNumber = acsNumber;
}
public String getFixedAssets() {
return fixedAssets;
}
public void setFixedAssets(String fixedAssets) {
this.fixedAssets = fixedAssets;
}
public String getClientYearDemanded() {
return clientYearDemanded;
}
public void setClientYearDemanded(String clientYearDemanded) {
this.clientYearDemanded = clientYearDemanded;
}
public String getClientYearDemandedAmount() {
return clientYearDemandedAmount;
}
public void setClientYearDemandedAmount(String clientYearDemandedAmount) {
this.clientYearDemandedAmount = clientYearDemandedAmount;
}
public String getClientYearDemandedUnit() {
return clientYearDemandedUnit;
}
public void setClientYearDemandedUnit(String clientYearDemandedUnit) {
this.clientYearDemandedUnit = clientYearDemandedUnit;
}
public String getMyPortion() {
return myPortion;
}
public void setMyPortion(String myPortion) {
this.myPortion = myPortion;
}
public String getCompetitorSituation() {
return competitorSituation;
}
public void setCompetitorSituation(String competitorSituation) {
this.competitorSituation = competitorSituation;
}
public String getYearSaleroom() {
return yearSaleroom;
}
public void setYearSaleroom(String yearSaleroom) {
this.yearSaleroom = yearSaleroom;
}
public String getWeOpportunity() {
return weOpportunity;
}
public void setWeOpportunity(String weOpportunity) {
this.weOpportunity = weOpportunity;
}
public String getGcm() {
return gcm;
}
public void setGcm(String gcm) {
this.gcm = gcm;
}
public String getSampleCostInput() {
return sampleCostInput;
}
public void setSampleCostInput(String sampleCostInput) {
this.sampleCostInput = sampleCostInput;
}
public String getFixedAssetsInput() {
return fixedAssetsInput;
}
public void setFixedAssetsInput(String fixedAssetsInput) {
this.fixedAssetsInput = fixedAssetsInput;
}
public String getAdvantage() {
return advantage;
}
public void setAdvantage(String advantage) {
this.advantage = advantage;
}
public String getProjectInvolveGuest() {
return projectInvolveGuest;
}
public void setProjectInvolveGuest(String projectInvolveGuest) {
this.projectInvolveGuest = projectInvolveGuest;
}
public String getProjectInvolveGuestId() {
return projectInvolveGuestId;
}
public void setProjectInvolveGuestId(String projectInvolveGuestId) {
this.projectInvolveGuestId = projectInvolveGuestId;
}
public String getProjectInvolveGuestNumber() {
return projectInvolveGuestNumber;
}
public void setProjectInvolveGuestNumber(String projectInvolveGuestNumber) {
this.projectInvolveGuestNumber = projectInvolveGuestNumber;
}
public String getTechnologyDifficulty() {
return technologyDifficulty;
}
public void setTechnologyDifficulty(String technologyDifficulty) {
this.technologyDifficulty = technologyDifficulty;
}
public String getProductConstruction() {
return productConstruction;
}
public void setProductConstruction(String productConstruction) {
this.productConstruction = productConstruction;
}
public String getBusinessTarget() {
return businessTarget;
}
public void setBusinessTarget(String businessTarget) {
this.businessTarget = businessTarget;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public Date getProjectStartTime() {
return projectStartTime;
}
public void setProjectStartTime(Date projectStartTime) {
this.projectStartTime = projectStartTime;
}
public Date getProjectVerifyTime() {
return projectVerifyTime;
}
public void setProjectVerifyTime(Date projectVerifyTime) {
this.projectVerifyTime = projectVerifyTime;
}
public Date getBusinessOrderTime() {
return businessOrderTime;
}
public void setBusinessOrderTime(Date businessOrderTime) {
this.businessOrderTime = businessOrderTime;
}
public Date getProjectFinishTime() {
return projectFinishTime;
}
public void setProjectFinishTime(Date projectFinishTime) {
this.projectFinishTime = projectFinishTime;
}
public String getResearchPrincipalIds() {
return researchPrincipalIds;
}
public void setResearchPrincipalIds(String researchPrincipalIds) {
this.researchPrincipalIds = researchPrincipalIds;
}
public String getResearchPrincipalNames() {
return researchPrincipalNames;
}
public void setResearchPrincipalNames(String researchPrincipalNames) {
this.researchPrincipalNames = researchPrincipalNames;
}
public String getSellPrincipalIds() {
return sellPrincipalIds;
}
public void setSellPrincipalIds(String sellPrincipalIds) {
this.sellPrincipalIds = sellPrincipalIds;
}
public String getSellPrincipalNames() {
return sellPrincipalNames;
}
public void setSellPrincipalNames(String sellPrincipalNames) {
this.sellPrincipalNames = sellPrincipalNames;
}
public String getTeamParticipantIds() {
return teamParticipantIds;
}
public void setTeamParticipantIds(String teamParticipantIds) {
this.teamParticipantIds = teamParticipantIds;
}
public String getTeamParticipantNames() {
return teamParticipantNames;
}
public void setTeamParticipantNames(String teamParticipantNames) {
this.teamParticipantNames = teamParticipantNames;
}
public String getOnlySign() {
return onlySign;
}
public void setOnlySign(String onlySign) {
this.onlySign = onlySign;
}
public String getSampleApplyTimes() {
return sampleApplyTimes;
}
public void setSampleApplyTimes(String sampleApplyTimes) {
this.sampleApplyTimes = sampleApplyTimes;
}
public String getCurrentOperator() {
return currentOperator;
}
public void setCurrentOperator(String currentOperator) {
this.currentOperator = currentOperator;
}
public Date getApplyDateEnd() {
return applyDateEnd;
}
public void setApplyDateEnd(Date applyDateEnd) {
this.applyDateEnd = applyDateEnd;
}
public Date getProjectStartTimeEnd() {
return projectStartTimeEnd;
}
public void setProjectStartTimeEnd(Date projectStartTimeEnd) {
this.projectStartTimeEnd = projectStartTimeEnd;
}
public Date getProjectVerifyTimeEnd() {
return projectVerifyTimeEnd;
}
public void setProjectVerifyTimeEnd(Date projectVerifyTimeEnd) {
this.projectVerifyTimeEnd = projectVerifyTimeEnd;
}
public Date getBusinessOrderTimeEnd() {
return businessOrderTimeEnd;
}
public void setBusinessOrderTimeEnd(Date businessOrderTimeEnd) {
this.businessOrderTimeEnd = businessOrderTimeEnd;
}
public Date getProjectFinishTimeEnd() {
return projectFinishTimeEnd;
}
public void setProjectFinishTimeEnd(Date projectFinishTimeEnd) {
this.projectFinishTimeEnd = projectFinishTimeEnd;
}
public String getQueryCascade() {
return queryCascade;
}
public void setQueryCascade(String queryCascade) {
this.queryCascade = queryCascade;
}
public String getTerminationStatus() {
return terminationStatus;
}
public void setTerminationStatus(String terminationStatus) {
this.terminationStatus = terminationStatus;
}
public String getLevelValue() {
return levelValue;
}
public void setLevelValue(String levelValue) {
this.levelValue = levelValue;
}
}
|
TypeScript
|
UTF-8
| 787
| 2.578125
| 3
|
[] |
no_license
|
import Knex from 'knex'
import { Acronym } from 'db/interfaces/acronyms'
import { ResponseError } from 'helpers/errors'
import { getRandomNonAdjacentItems } from './helpers'
type Params = {
db: Knex
count: number
}
async function getRandomAcronyms({ db, count }: Params): Promise<Acronym[]> {
const getAcronyms = db.select('acronym', 'definitions').from('acronyms')
const countAcronyms = db('acronyms').count('id as count').first()
const [acronyms, total] = await Promise.all([getAcronyms, countAcronyms])
if (count > Number(total.count)) {
throw new ResponseError(`'count' can't be greater than ${total.count}.`, 400)
}
const randomAcronyms = getRandomNonAdjacentItems(acronyms, count) as Acronym[]
return randomAcronyms
}
export default getRandomAcronyms
|
Java
|
UTF-8
| 981
| 3.328125
| 3
|
[] |
no_license
|
package com.example;
public class Main {
private static void quicksort(int[] ar, int low, int high) {
if (low >= high)
return;
int pivot = ar[high];
int q = low;
for (int i = low; i < high; i++) {
if (ar[i] <= pivot) {
int temp = ar[q];
ar[q] = ar[i];
ar[i] = temp;
q++;
}
}
// Put pivot in place
int temp = ar[high];
ar[high] = ar[q];
ar[q] = temp;
quicksort(ar, low, q-1);
quicksort(ar, q+1, high);
}
public static void main(String[] args) {
int[] ar = {2, 5, 3, 1};//{18, 6, 9, 1, 4, 15, 12, 5, 6, 7, 11};
// int[] ar = {18, 6};
quicksort(ar, 0, ar.length-1);
printArray(ar);
}
private static void printArray(int[] ar) {
for(int n: ar){
System.out.print(n+" ");
}
System.out.println("");
}
}
|
Markdown
|
UTF-8
| 350
| 2.53125
| 3
|
[] |
no_license
|
## About
h-rs is a Rust port of the [h](https://github.com/savetheinternet/h) program. It aims to be entirely compatible with the original [h](https://github.com/savetheinternet/h) program.
H is a small program which, upon execution, prints the lowercase letter `h` (ASCII character 104).
## Usage
1. `cargo build --release`
2. `./target/release/h`
|
Java
|
UTF-8
| 940
| 2.375
| 2
|
[] |
no_license
|
package edu.nefu.gdms.daoImpl;
import java.util.List;
import edu.nefu.gdms.dao.PaperDao;
import edu.nefu.gdms.domain.Grour;
import edu.nefu.gdms.domain.Paper;
import edu.nefu.gdms.support.GdmsHibernateDaoSupport;
public class PaperDaoHibernate extends GdmsHibernateDaoSupport implements PaperDao{
@Override
public Paper get(String id) {
return getHibernateTemplate().get(Paper.class,id);
}
@Override
public String save(Paper paper) {
return (String) getHibernateTemplate().save(paper);
}
@Override
public void update(Paper paper) {
getHibernateTemplate().merge(paper);
}
@Override
public void delete(Paper paper) {
getHibernateTemplate().delete(paper);
}
@Override
public void delete(String id) {
Paper paper = getHibernateTemplate().get(Paper.class, id);
getHibernateTemplate().delete(paper);
}
@Override
public List<Paper> getAll() {
return getHibernateTemplate().find("from Paper");
}
}
|
Java
|
UTF-8
| 1,372
| 2.390625
| 2
|
[] |
no_license
|
package com.stackroute.apigateway.apiauthenticate;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.Serializable;
@Component
public class JWTSecurityTokenUtil implements Serializable {
private static final long serialVersionUID = -2550185165626007488L;
public static final long JWT_TOKEN_VALIDITY = 5 * 60 * 60;
@Value("${jwt.secret}")
private String jwtSecretKey;
//retrieve username from jwt token
public String getUsernameFromToken(String token) {
Claims claims = getClaimFromToken(token);
return (String)claims.get("username");
}
public Claims getClaimFromToken(String token) {
final Claims claims = getAllClaimsFromToken(token);
return claims;
}
//for retrieveing any information from token we will need the secret key
private Claims getAllClaimsFromToken(String token) {
return Jwts.parser().setSigningKey(jwtSecretKey).parseClaimsJws(token).getBody();
}
//validate token
public Boolean validateToken(String token) {
System.out.println("secret" + jwtSecretKey);
final String username = getUsernameFromToken(token);
if(username != null) {
return true;
}
return false;
}
}
|
Java
|
UTF-8
| 844
| 1.953125
| 2
|
[] |
no_license
|
package com.example.demo;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.json.JsonTest;
import org.springframework.boot.test.json.JacksonTester;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@JsonTest
public class UserWithEmailTest {
@Autowired
private JacksonTester<UserWithEmail> json;
private UserWithEmail user;
@Before
public void setUp() throws Exception {
user = new UserWithEmail("test", new Email("test@exmaple.com"));
}
@Test
public void test() throws Exception {
assertThat(json.write(user)).isEqualToJson("user_with_email.json");
}
}
|
Markdown
|
UTF-8
| 1,808
| 3.09375
| 3
|
[] |
no_license
|
---
layout: blog
title: "Error Simulation And API Testing"
author: "Vanessa"
description: "There are many tools for API testing out there, and although APItools is not specifically designed for testing, its flexible structure allows us to use it for that."
gh-author: vramosp
categories: blog
tags: middleware testing
---
There are many tools for API testing out there, and although APItools is not specifically designed for testing, its flexible structure allows us to use it for that.
Just recently we created a middleware module to randomly skip some API calls to test an app’s performance. The purpose of the test was to see how this app would respond to API errors or to a lack of availability of the API.
Here’s the code of the middleware module that allowed us to do that just routing the calls through APItools (easy, uh?):
```lua
return function (request, next_middleware)
-- ~ 90% of the calls will pass, 10% will fail.
-- Change it to whatever you want
local success_probability = 0.9
if math.random() <= success_probability then
return next_middleware()
else
return {
status = 500,
body = '{"error": "simulated error"}',
headers = {['Content-Type']= 'application/json'}
}
end
end
```
That got us thinking… would people be interested in middleware modules to force failing calls / timeouts to test their apps? Or to test their APIs? We’re planning on investing some time on this but **wanted to ask what types of middleware modules for testing people would like to see implemented on APItools**.
Please share your thoughts by leaving a comment here, sending us an [email](mailto:hello@apitools.com 'Email hello @ APItools'), or an idea on our [Uservoice](https://apitools.uservoice.com/forums/229502-apitools 'APItools Uservoice'). Thanks!
|
Markdown
|
UTF-8
| 2,728
| 3.75
| 4
|
[] |
no_license
|
---
draft: true
title: "Object Orientated Database (Static Schema)"
description: How classic object-oriented databases encode their data
date: 2018-02-19
tags:
- IPT
- Data-Structure
hide:
- navigation
---
# Object Orientated Database (Static Schema)
Since object-oriented databases are an evolution of Relational table DMBS, it is best to understand [RDMBSs](/p?3) before you try to understand OODBs.
## Structures
An OODB schema can be broken down into different sub-sections called structures.
Each structure is like a description of a tuple. It describes the name of each attribute as well as it's data type.
For instance, you can describe the structure of a database of which stores GPS locations like so;
```
GPS {
latt: float32,
long: float32,
alt: float32
}
root {
locations: gps[]
}
```
You can see that within locations you can store the individual locations the same as you would a tuple within a table. However, the interesting problem is how you handle having more than one unset length array. How can each of them infinitely expand without colliding with each other?
## N-Length Arrays
The simplest way is to chunk the array.
In this case, we will pick a chunk size of ``50``. This means that when the array is initiated it will allocate ``50 × GPS.size + 8`` bytes.
This means that the array now has 50 empty slots to fill, once these slots are filled, you can then use the last 6 bytes as a direct pointer to the start of another chunk.
Thus, you can continuously expand your array without conflicting with any other arrays.
> It can be beneficial to add structure set chunk sizes.
> For instance if you have an array with a list of all accounts on a website, then you should have your default chunk size quite large to have fewer pointers,
> However if those accounts then have their own array, i.e. friends, they do not need their chunk size to be so big, since it would be a waste to have massive chunks for only a few items.
> Personally I prefer the syntax for such arrays to be like this ``arr[~chunksize]``
## Pointer
This allows you to directly reference other data. This is done by storing the exact byte index of where the target starts, as well as what data type is there so that it can be read properly.
> It is recommended to state that something is a reference via having a leading ``&``, since that follows on the pre-existing standards created by C
This example shows how you can have a list of people, and reference all their friends so that you can read their data easily.
```
person: {
given: string[15],
family: string[15],
street: string[30],
suburb: string[10],
state: string[4],
friends: &person[~5]
}
root{
people: person[~50]
}
```
|
C
|
UTF-8
| 568
| 3.5625
| 4
|
[] |
no_license
|
#include<stdio.h>
#include <conio.h>
copy(int a[], int b[],int n,int i)
{
if(i<n)
{
b[i]=a[i];
copy(a,b,n,++i);
}
}
print(int a[],int n){
int i;
for(i=0; i<n; i++)
{
printf("%d ",a[i]);
}
}
int main()
{
int a[1000],b[1000],i,n;
printf("Enter size of the array: ");
scanf("%d", &n);
printf("Enter elements in array: ");
for(i=0; i<n; i++)
{
scanf("%d", &a[i]);
}
copy(a,b,n,0);
printf("first array: ");
print(a,n);
printf("\nsecond array: ");
print(b,n);
}
|
Go
|
UTF-8
| 1,424
| 2.875
| 3
|
[] |
no_license
|
package dataputter
import "testing"
func TestSetTicketStatus(t *testing.T) {
var err error
err = SetTicketStatus("ticketID", TicketStatus[TicketNew])
if err != nil {
t.Errorf("Expected no error, got %v\n", err)
}
status, err := GetTicketStatus("ticketID")
if err != nil {
t.Errorf("Expected no errors, got %v\n", err)
}
if status != "new" {
t.Errorf("Expected 'new', got %s\n", status)
}
}
func TestSetTicketStatusInSequence(t *testing.T) {
tests := []string{"new", "saved", "error", "saved"}
for _, status := range tests {
err := SetTicketStatus("ticketID", status)
if err != nil {
t.Errorf("Expected to set initial status of %s but failed\n", status)
}
storedStatus, err := GetTicketStatus("ticketID")
if err != nil {
t.Errorf("Expected to get status for %s but failed\n", status)
}
if status != storedStatus {
t.Errorf("Expected ticket status %s, got %s\n", storedStatus, status)
}
}
}
func TestGetObjectTickets(t *testing.T) {
defer DeleteTicket("TEST_OBJECT_ID", "TEST_TICKET_ID")
err := CreateTicket("TEST_TICKET_ID", "TEST_OBJECT_ID", "TEST_NODE_ID", 0, 10, 10)
if err != nil {
t.Errorf("Expected to write one ticket, got %v\n", err)
}
tickets, err := GetObjectTickets("TEST_OBJECT_ID")
if err != nil {
t.Errorf("Expected tickets for 'TEST_OBJECT_ID', got %v\n", err)
}
if len(tickets) != 1 {
t.Errorf("Expected 1 ticket, got %d\n", len(tickets))
}
}
|
Markdown
|
UTF-8
| 3,359
| 2.984375
| 3
|
[
"MIT"
] |
permissive
|
linotify
========
A Lua binding for the Linux inotify library
Building
--------
To build `inotify.so`, simply type `make`.
Usage
-----
All of the constants are contained in the `inotify` table returned by
require. Constants are named after their counterparts in the C header
file (for example: `inotify.IN_ACCESS`).
The only function to be found in the inotify table is `init`, which returns an
inotify handle.
`init` can optionally take a single argument, a boolean value to specify
whether to run in non-blocking mode.
Inotify handles have a variety of methods:
### handle:read()
Reads events from the handle, returning a table. Each element of the table
is itself a table, with the members of the `inotify_event` struct as its
keys and values (except for len). If an error occurs, `nil`, the error
message, and errno are returned.
### handle:events()
Returns an iterator that reads events from the handle, one at a time.
Each value yielded from the iterator is a table with the members of the
`inotify_event` struct as its keys and values (except for len). If an
error occurs during reading, an error is thrown.
### handle:close()
Closes the inotify event handle. This is done automatically on garbage
collection.
### handle:addwatch(path, [event_masks...])
Adds a watch on `event_masks` for the file located at path, returning a
watch identifier on success, and the traditional `nil, error, errno` triplet
on error. `event_masks` is a variadic sequence of integer constants, taken
from `inotify.IN_*`.
All of the values in `event_masks` are OR'd together but this can also be done
manually with `bit.bor()`. The following two examples are equivalent:
```lua
-- Event masks passed as arguments
local handle = inotify.init()
local wd = handle:addwatch('/tmp/foo/', inotify.IN_CREATE, inotify.IN_MOVE)
-- Event masks passed as a single, manually OR'd variable
local handle = inotify.init()
local options = bit.bor(inotify.IN_CREATE, inotify.IN_MOVE)
local wd = handle:addwatch('/tmp/foo/', options)
```
### handle:rmwatch(watchid)
Removes the watch specified by watchid from the list of watches for this
inotify handle. Returns true on success, and `nil, error, errno` on error.
Example
-------
```lua
local inotify = require 'inotify'
local handle = inotify.init()
-- Watch for new files and renames
local wd = handle:addwatch('/home/rob/', inotify.IN_CREATE, inotify.IN_MOVE)
local events = handle:read()
for _, ev in ipairs(events) do
print(ev.name .. ' was created or renamed')
end
-- Done automatically on close, I think, but kept to be thorough
handle:rmwatch(wd)
handle:close()
```
Example (Iterator)
------------------
```lua
local inotify = require 'inotify'
local handle = inotify.init()
-- Watch for new files and renames
local wd = handle:addwatch('/home/rob/', inotify.IN_CREATE, inotify.IN_MOVE)
for ev in handle:events()
print(ev.name .. ' was created or renamed')
end
-- Done automatically on close, I think, but kept to be thorough
handle:rmwatch(wd)
handle:close()
```
Deprecation Warning
-------------------
As version 0.2, relying on the global `inotify` (as opposed to using the
return value of `require`) is deprecated. Doing this will result in
a warning. If you do not wish to see this warning, simply downgrade to
linotify 0.1 (the versions are identical except for this warning).
|
Python
|
UTF-8
| 782
| 2.796875
| 3
|
[] |
no_license
|
import pylab
import pickle
import matplotlib.pyplot as plt
import numpy as np
data = pickle.load(open("enron.pkl", "r"))
salary = list()
bonus = list()
poi = list()
for ii in data.keys():
if data[ii]['total_stock_value'] == 'NaN' or data[ii]['total_payments'] == 'NaN':
continue
else:
salary.append(data[ii]['total_payments'])
bonus.append(data[ii]['total_stock_value'])
if data[ii]['poi']:
poi.append('red')
else:
poi.append('green')
fig = pylab.figure()
salary = np.array(salary)
bonus = np.array(bonus)
poi = np.array(poi)
plt.scatter(salary, bonus, marker = 'o', color = poi)
plt.xlim(0, 120000000)
plt.ylim(0, 60000000)
plt.xlabel('Payments')
plt.ylabel('Stock Value')
plt.grid()
plt.savefig('Stock_Vs_Payment.png', transparent = True)
|
C#
|
UTF-8
| 2,749
| 2.515625
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using OnlineCourse.Business.Model;
using OnlineCourse.Business.Model.Helpers;
using OnlineCourse.Business.Service.Interfaces;
using OnlineCourse.Business.Service.Mappers;
using OnlineCourse.Data.Repo;
using OnlineCourse.Data.Repo.DataContext;
using OnlineCourse.Data.Repo.RepositoryFactory;
namespace OnlineCourse.Business.Service
{
public class UserService : IUserService
{
private readonly IRepositoryFactory<OCDataContext> repositoryFactory;
private readonly IRepository repository;
private readonly AppSettings appSettings;
public UserService(IRepositoryFactory<OCDataContext> repositoryFactory, OCDataContext dataContext, IOptions<AppSettings> appSettings)
{
this.repositoryFactory = repositoryFactory;
this.repository = this.repositoryFactory.CreateRepository(dataContext);
this.appSettings = appSettings.Value;
}
public UserDto Authenticate(string username, string password)
{
var users = new List<UserDto>
{
new UserDto()
{
Id = 1,
Username = "test", Password = "test"
}
};
var user = users.SingleOrDefault(x => x.Username == username && x.Password == password);
if (user == null)
{
return null;
}
// authentication successful so generate jwt token
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(appSettings.Secret);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, user.Id.ToString())
}),
Expires = DateTime.UtcNow.AddDays(7),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
user.Token = tokenHandler.WriteToken(token);
return user;
}
public UserDto GetById(int userId)
{
var users = new List<UserDto>
{
new UserDto()
{
Username = "test", Password = "test"
}
};
return users.FirstOrDefault();
}
}
}
|
C++
|
UTF-8
| 7,538
| 2.65625
| 3
|
[
"Apache-2.0"
] |
permissive
|
#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstring>
#include <sstream>
#include <string>
#include <thread>
#include "MemoryTrace.hh"
MemoryRequest::MemoryRequest(const int tid, const int size, const int bundle_kind,
const bool is_write, const uint64_t address,
const uint64_t pc)
: tid(tid),
size(size),
bundle_kind(bundle_kind),
is_write(is_write),
address(address),
pc(pc) { }
bool MemoryRequest::is_bundle() const { return bundle_kind != 0; }
bool MemoryRequest::is_bundle_start() const { return bundle_kind & 0x1; }
bool MemoryRequest::is_bundle_middle() const { return bundle_kind & 0x2; }
bool MemoryRequest::is_bundle_end() const { return bundle_kind & 0x4; }
namespace MemoryTraceTools {
/* Guess if the given file is a text file */
TraceFileType guess_file_type(const std::string& fname) {
std::ifstream f { fname };
if (!f.is_open()) throw std::invalid_argument("Cannot open trace file: " + fname);
size_t check_count { 500 };
std::unique_ptr<char> data { new char[check_count + 1] };
f.read(data.get(), check_count);
if (f.eof()) check_count = f.gcount();
if (std::memchr(data.get(), '\0', check_count) != NULL)
return TraceFileType::Binary;
else
return TraceFileType::Text;
}
} // namespace MemoryTraceTools
MemoryTrace::MemoryTrace(std::istream& tracefile, TraceFileType ftype) {
switch (ftype) {
case TraceFileType::Text:
construct_from_text_(tracefile);
break;
case TraceFileType::Binary:
construct_from_binary_serial_(tracefile);
break;
default:
throw std::invalid_argument("Unknown trace file type");
}
}
MemoryTrace::MemoryTrace(std::istream&& tracefile, TraceFileType ftype)
: MemoryTrace(tracefile, ftype) { }
MemoryTrace::MemoryTrace(const std::string& trace_fname, TraceFileType ftype,
int io_threads) {
switch (ftype) {
case TraceFileType::Text:
construct_from_text_(trace_fname);
break;
case TraceFileType::Binary:
construct_from_binary_parallel_(trace_fname, io_threads);
break;
default:
throw std::invalid_argument("Unknown trace file type");
}
}
const std::vector<MemoryRequest> MemoryTrace::getRequests() const { return requests; }
const std::vector<uint64_t> MemoryTrace::getRequestAddresses() const {
if (requests.size() != requestAddresses.size()) {
assert(false && "This should never happen");
}
return requestAddresses;
}
void MemoryTrace::construct_from_text_(std::istream& tracefile) {
std::istringstream iss;
for (std::string line; std::getline(tracefile, line);) {
if (line.empty()) continue;
line.erase(std::remove(line.begin(), line.end(), ','), line.end());
#ifdef DEBUG
std::cout << "Line: " << line << "\n";
#endif
iss.clear();
iss.str(line);
int seq, tid, size, bundle_kind;
bool is_write;
uint64_t address, pc;
iss >> std::dec >> seq >> tid >> bundle_kind >> is_write >> size;
iss >> std::hex >> address >> pc;
#ifdef DEBUG
std::cout << "Values: " << seq << " " << tid << " " << bundle_kind << " " << is_write
<< " " << size << " " << address << " " << pc << "\n";
#endif
requests.emplace_back(tid, size, bundle_kind, is_write, address, pc);
requestAddresses.push_back(address);
}
}
void MemoryTrace::construct_from_text_(const std::string& trace_fname) {
std::ifstream tracefile { trace_fname };
construct_from_text_(tracefile);
}
void MemoryTrace::construct_from_binary_serial_(std::istream& tracefile) {
size_t elements;
tracefile.read(reinterpret_cast<char*>(&elements), sizeof(size_t));
requests.reserve(elements);
requestAddresses.reserve(elements);
for (size_t i = 0; i < elements; i++) {
int tid, size, bundle_kind;
bool is_write;
uint64_t address, pc;
tracefile.read(reinterpret_cast<char*>(&tid), sizeof(int));
tracefile.read(reinterpret_cast<char*>(&size), sizeof(int));
tracefile.read(reinterpret_cast<char*>(&bundle_kind), sizeof(int));
tracefile.read(reinterpret_cast<char*>(&is_write), sizeof(bool));
tracefile.read(reinterpret_cast<char*>(&address), sizeof(uint64_t));
tracefile.read(reinterpret_cast<char*>(&pc), sizeof(uint64_t));
requests.emplace_back(tid, size, bundle_kind, is_write, address, pc);
requestAddresses.push_back(address);
}
}
void MemoryTrace::construct_from_binary_parallel_(const std::string& trace_fname,
int io_threads) {
std::ifstream tracefile { trace_fname, std::ios::binary };
size_t elements;
tracefile.read(reinterpret_cast<char*>(&elements), sizeof(size_t));
tracefile.close();
requests = std::vector<MemoryRequest>(elements);
requestAddresses = std::vector<uint64_t>(elements);
const size_t max_threads =
std::min(static_cast<unsigned>(io_threads), std::thread::hardware_concurrency());
const auto nthreads = std::min(elements, max_threads);
const size_t elements_per_thread = std::ceil(elements / static_cast<double>(nthreads));
const size_t bytes_per_thread =
elements_per_thread * (3 * sizeof(int) + sizeof(bool) + 2 * sizeof(uint64_t));
std::vector<std::thread> threads;
threads.reserve(nthreads);
for (size_t thread_num = 0; thread_num < nthreads; thread_num++) {
threads.emplace_back([&, thread_num]() {
std::ifstream tracefile { trace_fname, std::ios::binary };
const size_t file_offset = sizeof(size_t) + bytes_per_thread * thread_num;
tracefile.seekg(file_offset);
for (size_t i = 0;
i < elements_per_thread && i + elements_per_thread * thread_num < elements;
i++) {
const size_t global_element = elements_per_thread * thread_num + i;
uint64_t address;
tracefile.read(reinterpret_cast<char*>(&requests[global_element].tid),
sizeof(int));
tracefile.read(reinterpret_cast<char*>(&requests[global_element].size),
sizeof(int));
tracefile.read(reinterpret_cast<char*>(&requests[global_element].bundle_kind),
sizeof(int));
tracefile.read(reinterpret_cast<char*>(&requests[global_element].is_write),
sizeof(bool));
tracefile.read(reinterpret_cast<char*>(&address), sizeof(uint64_t));
tracefile.read(reinterpret_cast<char*>(&requests[global_element].pc),
sizeof(uint64_t));
requests[global_element].address = address;
requestAddresses[global_element] = address;
}
});
}
for (auto& t : threads) t.join();
}
size_t MemoryTrace::getLength() const {
assert(requests.size() == requestAddresses.size());
return requests.size();
}
void MemoryTrace::write_binary(const std::string& fname) const {
std::ofstream f { fname };
const size_t length = getLength();
f.write(reinterpret_cast<const char*>(&length), sizeof(size_t));
for (const auto& request : requests) {
f.write(reinterpret_cast<const char*>(&request.tid), sizeof(int));
f.write(reinterpret_cast<const char*>(&request.size), sizeof(int));
f.write(reinterpret_cast<const char*>(&request.bundle_kind), sizeof(int));
f.write(reinterpret_cast<const char*>(&request.is_write), sizeof(bool));
f.write(reinterpret_cast<const char*>(&request.address), sizeof(uint64_t));
f.write(reinterpret_cast<const char*>(&request.pc), sizeof(uint64_t));
}
}
|
Python
|
UTF-8
| 251
| 4.9375
| 5
|
[] |
no_license
|
# Write a program to check whether a character is vowel or consonant
c = input("Enter a character: ")
if c.lower() in ["a", "e", "i", "o", "u"]:
print("The entered character is a vowel")
else:
print("The entered character is a consonant")
|
Java
|
UTF-8
| 4,121
| 2.34375
| 2
|
[] |
no_license
|
package com.diffpath.hackday;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.diffpath.hackday.object.ActionObject;
import java.util.ArrayList;
/**
* Created by Heedeok on 15. 4. 20..
*/
public class DefineActionActivity extends ActionBarActivity {
private ArrayList<ActionObject> action_lists;
private int btn_no;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_define);
btn_no = getIntent().getIntExtra("btn", 0);
ListView lv = (ListView) findViewById(R.id.defile_list);
setLists();
ActionAdapter adapter = new ActionAdapter(this, android.R.layout.simple_list_item_2, action_lists);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
sendResult(i);
}
});
}
private void setLists()
{
action_lists = new ArrayList<ActionObject>();
ActionObject obj = new ActionObject();
obj.setId(0);
obj.setDescription("휴대전화의 위치를 찾습니다");
obj.setName("나를 찾아줘");
obj.setImg(R.drawable.transmission3);
action_lists.add(obj);
obj = new ActionObject();
obj.setId(1);
obj.setDescription("여자친구에게 문자를 전송합니다");
obj.setName("간편한 사랑");
obj.setImg(R.drawable.message20);
action_lists.add(obj);
obj = new ActionObject();
obj.setId(2);
obj.setDescription("그녀와 늘 함께합니다");
obj.setName("수지플레이어");
obj.setImg(R.drawable.television24);
action_lists.add(obj);
obj = new ActionObject();
obj.setId(3);
obj.setDescription("이젠 글올리기도 귀찮습니다");
obj.setName("페이스북 작성");
obj.setImg(R.drawable.pencil108);
action_lists.add(obj);
obj = new ActionObject();
obj.setId(4);
obj.setDescription("이젠 당신도 인기남녀!");
obj.setName("까똑");
obj.setImg(R.drawable.support);
action_lists.add(obj);
}
private void sendResult(int i)
{
Bundle extra = new Bundle();
Intent intent = new Intent();
extra.putInt("btn", btn_no);
extra.putInt("action", i);
intent.putExtras(extra);
this.setResult(RESULT_OK, intent);
this.finish();
}
public class ActionAdapter extends ArrayAdapter<ActionObject>{
public ArrayList<ActionObject> items;
private Context mcontext;
public ActionAdapter(Context context, int textViewResourceId, ArrayList<ActionObject> items) {
super(context, textViewResourceId, items);
mcontext = context;
this.items = items;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(android.R.layout.simple_list_item_2, null);
}
ActionObject areaInfo = items.get(position);
if (areaInfo != null) {
TextView title1 = (TextView) v.findViewById(android.R.id.text1);
TextView title2 = (TextView) v.findViewById(android.R.id.text2);
title1.setText(areaInfo.getName());
title2.setText(areaInfo.getDescription());
}
return v;
}
}
}
|
Python
|
UTF-8
| 641
| 2.84375
| 3
|
[] |
no_license
|
from sklearn.ensemble import RandomForestRegressor
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
data, labels = load_digits(return_X_y=True)
model = RandomForestRegressor(random_state=1, max_depth=10)
# df=pd.get_dummies(df)
model.fit(data,labels)
features = data.columns
importances = model.feature_importances_
indices = np.argsort(importances)[-9:] # top 10 features
plt.title('Feature Importances')
plt.barh(range(len(indices)), importances[indices], color='b', align='center')
plt.yticks(range(len(indices)), [features[i] for i in indices])
plt.xlabel('Relative Importance')
plt.show()
|
C#
|
UTF-8
| 10,020
| 2.5625
| 3
|
[] |
no_license
|
using System.Collections.ObjectModel;
namespace FalloutRPG.Constants
{
public static class Pages
{
#region HELP GROUP
#region Index Help Pages
public static readonly ReadOnlyCollection<string> HELP_PAGE1_TITLES = new ReadOnlyCollection<string>(new []
{
"$help general",
"$help character",
"$help roll",
"$help skills",
"$help craps"
});
public static readonly ReadOnlyCollection<string> HELP_PAGE1_CONTENTS = new ReadOnlyCollection<string>(new []
{
"Displays general help menu.",
"Displays character help menu.",
"Displays roll help menu.",
"Displays a list of skills.",
"Displays craps help page."
});
#endregion
#region General Help Pages
public static readonly ReadOnlyCollection<string> HELP_GENERAL_PAGE1_TITLES = new ReadOnlyCollection<string>(new []
{
"$pay [@user] [amount]",
"$daysleft",
"$highscores"
});
public static readonly ReadOnlyCollection<string> HELP_GENERAL_PAGE1_CONTENTS = new ReadOnlyCollection<string>(new []
{
"Pays a user the specified amount of caps.",
"Shows how many days are left until the release of Fallout 76 using UTC.",
"Shows the top 10 characters ordered by experience."
});
#endregion
#region Character Help Pages
public static readonly ReadOnlyCollection<string> HELP_CHAR_PAGE1_TITLES = new ReadOnlyCollection<string>(new []
{
"$char show",
"$char show [@user]",
"$char create [name]",
"$char story",
"$char story [@user]",
"$char story update [story]",
"$char desc",
"$char desc [@user]",
"$char desc update [desc]"
});
public static readonly ReadOnlyCollection<string> HELP_CHAR_PAGE1_CONTENTS = new ReadOnlyCollection<string>(new []
{
"Displays your character.",
"Displays specified user's character.",
"Creates your character.",
"Displays your character's story.",
"Displays specified user's character story.",
"Updates your character's story.",
"Displays your character's description.",
"Displays specified user's character description.",
"Updates your character's description."
});
public static readonly ReadOnlyCollection<string> HELP_CHAR_PAGE2_TITLES = new ReadOnlyCollection<string>(new []
{
"$char stats",
"$char stats [@user]",
"$char highscores",
"$char skills",
"$char skills [@user]",
"$char skills set [tag1] [tag2] [tag3]",
"$char skills spend [skill] [points]",
"$char special",
"$char special [@user]",
"$char special set [S] [P] [E] [C] [I] [A] [L]"
});
public static readonly ReadOnlyCollection<string> HELP_CHAR_PAGE2_CONTENTS = new ReadOnlyCollection<string>(new []
{
"Displays your level and experience.",
"Displays specified user's level and experience.",
"Displays the top 10 players ordered by experience.",
"Displays your character's skills.",
"Displays specified user's character skills.",
"Sets your initial tag skills.",
"Puts points in one of your skills.",
"Displays your character's SPECIAL.",
"Displays specified user's character SPECIAL.",
"Sets your SPECIAL."
});
#endregion
#region NPC Help Pages
public static readonly ReadOnlyCollection<string> HELP_NPC_PAGE1_TITLES = new ReadOnlyCollection<string>(new []
{
"$npc create [NPC type] [First Name]",
"$npc roll [Skill/SPECIAL to roll] [First name]"
});
public static readonly ReadOnlyCollection<string> HELP_NPC_PAGE1_CONTENTS = new ReadOnlyCollection<string>(new []
{
"Creates a new NPC with slightly random stats influenced by the given NPC type.",
"Gets a roll result based on the NPC's skills or S.P.E.C.I.A.L.."
});
public static readonly ReadOnlyCollection<string> HELP_NPC_PRESETS_PAGE1_TITLES = new ReadOnlyCollection<string>(new []
{
"$npc preset create [Name]",
"$npc preset create [Name] [STR] [PER] [END] [CHA] [INT] [AGI] [LUC]",
"$npc preset enable [Name]",
"$npc preset disable [Name]",
"$npc preset edit [Name] [Attribute] [Value]",
"$npc preset edit [Name] [STR] [PER] [END] [CHA] [INT] [AGI] [LUC]",
"$npc preset init",
"$npc preset view",
});
public static readonly ReadOnlyCollection<string> HELP_NPC_PRESETS_PAGE1_CONTENTS = new ReadOnlyCollection<string>(new []
{
"Creates a new NPC preset with the given name. Note: this preset will be completely empty.",
"Creates a new NPC preset with the given name and S.P.E.C.I.A.L.. This preset will have its Skills set to what a player's would look like without 'Tag!'.",
"Enables the preset with the given name. This command must be run before users are able to create NPCs with that preset.",
"Disables the preset with the given name. Users will no longer be able to create NPCs with the given preset after execution.",
"Edits the specified attribute of the preset with the given name. 'Attribute' can be the name of a S.P.E.C.I.A.L. stat or Skill.",
"Edits the S.P.E.C.I.A.L. of the preset with the given name. Helpful for when you don't want to type the same command 7 times.",
"Sets the NPC preset's Skills to what they'd look like if it were a new player's without Tag!.",
"Sends a DM to you with all of the NPC preset's current properties (Skills, S.P.E.C.I.A.L., other stuff...)"
});
#endregion
#region Roll Help Pages
public static readonly ReadOnlyCollection<string> HELP_ROLL_PAGE1_TITLES = new ReadOnlyCollection<string>(new []
{
"$roll [skill]",
"$roll [special]"
});
public static readonly ReadOnlyCollection<string> HELP_ROLL_PAGE1_CONTENTS = new ReadOnlyCollection<string>(new []
{
"Gets a roll result based on the skill level.",
"Gets a roll result based on the SPECIAL level."
});
#endregion
#region Craps Help Pages
public static readonly ReadOnlyCollection<string> HELP_CRAPS_PAGE1_TITLES = new ReadOnlyCollection<string>(new []
{
"$craps join",
"$craps leave",
"$craps roll",
"$craps bet [type] [amount]",
"$craps pass",
"Bet Types"
});
public static readonly ReadOnlyCollection<string> HELP_CRAPS_PAGE1_CONTENTS = new ReadOnlyCollection<string>(new []
{
"Joins current craps game.",
"Leaves current craps game.",
"Rolls the dice.",
"Makes a bet of the type and amount. Types can be found below.",
"Pass the dice to another user.",
"pass, dontpass, come, dontcome"
});
#endregion
#region Admin Help Pages
public static readonly ReadOnlyCollection<string> HELP_ADMIN_PAGE1_TITLES = new ReadOnlyCollection<string>(new []
{
"$admin givemoney [@user] [amount]",
"$admin giveskillpoints [@user] [amount]",
"$admin changename [@user] [name]",
"$admin reset [@user]"
});
public static readonly ReadOnlyCollection<string> HELP_ADMIN_PAGE1_CONTENTS = new ReadOnlyCollection<string>(new []
{
"Gives a character the specified amount of caps.",
"Gives a character the specified amount of skill points.",
"Changes a character's name.",
"Resets a character's skill points and SPECIAL. They will then be able to use *$char skills claim* to claim their skill points back."
});
#endregion
#region Tutorial
public static readonly ReadOnlyCollection<string> TUTORIAL_TITLES = new ReadOnlyCollection<string>(new []
{
"STEP 1: CREATING A CHARACTER",
"STEP 2: SETTING A STORY AND DESCRIPTION",
"STEP 3: SETTING A SPECIAL",
"STEP 4: SETTING TAG SKILLS",
"STEP 5: ROLLING"
});
public static readonly ReadOnlyCollection<string> TUTORIAL_CONTENTS = new ReadOnlyCollection<string>(new []
{
"Use $char create [firstname] [lastname] to create your character.",
"Use $char story set [story] and $char desc set [desc] to set your story and description.",
"Use $char spec set [S] [P] [E] [C] [I] [A] [L] to set your SPECIAL.",
"Use $char skills set [tag1] [tag2] [tag3] to set tag skills.",
"Use $roll [special] and $roll [skill] to roll."
});
#endregion
#endregion
#region CHARACTER GROUP
#region Display Character
public static readonly ReadOnlyCollection<string> CHAR_PAGE1_TITLES = new ReadOnlyCollection<string>(new []
{
"Name",
"Description",
"Level",
"Experience",
"To Next Level",
"Caps"
});
public static readonly ReadOnlyCollection<string> CHAR_PAGE2_TITLES = new ReadOnlyCollection<string>(new []
{
""
});
public static readonly ReadOnlyCollection<string> CHAR_PAGE1_CONTENTS = new ReadOnlyCollection<string>(new []
{
""
});
#endregion
#endregion
}
}
|
Ruby
|
UTF-8
| 3,911
| 2.84375
| 3
|
[
"Apache-2.0"
] |
permissive
|
#!/usr/bin/ruby
# Used to prepare a directory for commit to Subversion. This is necessary for certain file types on Mac OS X because what appear to be files in the Finder
# are actually directories (Mac uses the term "bundle" for this concept). It is useless to put the .svn folder inside such a directory, because it will
# tend to be deleted whenever the "file" is saved.
#
# Instead, we want to compress the directory to a single archive file; the bundle will be marked as svn:ignore.
#
# We use tar with Bzip2 compression, which is resource intensive to create, but compresses much better than GZip or PKZip.
#
# The trick is that we only want to create the archive version when necessary; when the archive does not exist, or when any file
# in the bundle is newer than the archive.
require 'optparse'
# Set via command line options
$extensions = %w{pages key oo3 graffle}
$recursive = true
$dry_run = false
# Queue of folders to search (for bundles)
$queue = []
def matching_extension(name)
dotx = name.rindex('.')
return false unless dotx
ext = name[dotx + 1 .. -1]
return $extensions.include?(ext)
end
# Iterate over the directory, identify bundles that may need to be compressed and (if recursive) subdirectories
# to search.
#
# path: string path for a directory
def search_directory(dirpath)
Dir.foreach(dirpath) do |name|
# Skip hidden files and directories
next if name[0..0] == "."
path = File.join(dirpath, name)
next unless File.directory?(path)
if matching_extension(name)
update_archive path
next
end
if $recursive
$queue << path
end
end
end
def needs_update(bundle_path, archive_path)
return true unless File.exists?(archive_path)
archive_mtime = File.mtime(archive_path)
# The archive exists ... can we find a file inside the bundle thats newer?
# This won't catch deletions, but that's ok. Bundles tend to get completly
# overwritten when any tiny thing changes.
dirqueue = [bundle_path]
until dirqueue.empty?
dirpath = dirqueue.pop
Dir.foreach(dirpath) do |name|
path = File.join(dirpath, name)
if File.directory?(path)
dirqueue << path unless [".", ".."].include?(name)
next
end
# Is this file newer?
if File.mtime(path) > archive_mtime
return true
end
end
end
return false
end
def update_archive(path)
archive = path + ".tar.bz2"
return unless needs_update(path, archive)
if $dry_run
puts "Would create #{archive}"
return
end
puts "Creating #{archive}"
dir = File.dirname(path)
bundle = File.basename(path)
# Could probably fork and do it in a subshell
system "tar --create --file=#{archive} --bzip2 --directory=#{dir} #{bundle}"
end
$opts = OptionParser.new do |opts|
opts.banner = "Usage: prepsvn [options]"
opts.on("-d", "--dir DIR", "Add directory to search (if no directory specify, current directory is searched)") do |value|
$queue << value
end
opts.on("-e", "--extension EXTENSION", "Add another extension to match when searching for bundles to archive") do |value|
$extensions << value
end
opts.on("-N", "--non-recursive", "Do not search non-bundle sub directories for files to archive") do
$recursive = false
end
opts.on("-D", "--dry-run", "Identify what archives would be created") do
$dry_run = true
end
opts.on("-h", "--help", "Help for this command") do
puts opts
exit
end
end
def fail(message)
puts "Error: #{message}"
puts $opts
end
begin
$opts.parse!
rescue OptionParser::InvalidOption
fail $!
end
# If no --dir specified, use the current directory.
if $queue.empty?
$queue << Dir.getwd
end
until $queue.empty?
search_directory $queue.pop
end
|
JavaScript
|
UTF-8
| 653
| 3.265625
| 3
|
[] |
no_license
|
function getinput(){
var pa = document.getElementById('myinput1').value;
var ia = document.getElementById('myinput2').value;
var y = document.getElementById('myinput3').value;
calculate(pa,ia,y);
}
function calculate(pa,ia,y){
var r = ia/12/100;
var a = Math.pow(r+1,y*12);
var b = a/(a-1)
var res = pa*r*b
var total = res*y*12
var temi = total-pa
output(res,total,temi)
}
function output(res,total,temi){
document.getElementsByName('displayemi')[0].value= res.toFixed(0);
document.getElementsByName('displaytemi')[0].value= Math.round(temi);
document.getElementsByName('displaytotal')[0].value= Math.round(total);
}
|
Ruby
|
UTF-8
| 929
| 3.640625
| 4
|
[] |
no_license
|
require_relative './instacart'
items = {
"bread" => 200,
"chicken" => 300,
"spinach" => 150,
"fish" => 600
}
purchase = ""
cart = {}
puts "--------------------"
puts "Welcome to Instacart"
puts "--------------------"
puts "In our store today:"
items.each{|item, price|
puts "#{item}" + " - " + "#{price} JPY"
}
until purchase == "q"
puts "What do you want? Please enter names('q' to checkout)"
print ">"
purchase = gets.chomp
if items.has_key?(purchase)
if cart.key?(purchase)
cart[purchase] += items[purchase]
else
cart[purchase] = items[purchase]
end
elsif purchase != "q"
puts "#{purchase} is not an available item.Pleaes enter another."
else
puts "Your total comes to #{checkout(cart)} JPY"
end
end
#puts cart
#puts "Your total amount is #{checkout(cart)}-JPY"
|
Markdown
|
UTF-8
| 2,579
| 2.515625
| 3
|
[] |
no_license
|
# sqlview -- A simple browser-based viewer for seeing output of SQL queries
sqlview is a tool for running SQL queries on a remote database using an ODBC (or similar) style connection mechanism and displaying the results in a web browser.
I wrote this because I prefer to edit my SQL code in my editor (SublimeText), and I wanted to be able to run the query and see the results from a single keystroke in the editor.
The project is broken in to three components:
* *agent* -- You start this once and leave it running in the background. It will connect to your database, and run a little Flask-based http server that will accept connections from the local command line client and the browser-based viewer.
* *viewer* -- The collection of HTML and JavaScript that runs in the browser to show queries and results.
* *client* -- A command-line client that opens an http connection to the agent, submits a SQL query to execute, and immediately exits. Does not return query results to the client, but instead makes submitted query and result available to the web-based viewer. Could probably be implemented entirely with wget or curl.
# Installation and Getting Started
These are quick-start instructions for using sqlview with the Analytics Inbox (ai) Project
### Clone This Repository
$ git clone https://github.com/antonycourtney/sqlview.git
### Build the JavaScript Viewer
Install npm dependencies, run gulp:
$ cd sqlview/viewer
$ npm install
$ gulp
And pop back up to the sqlview directory:
$ cd ..
### Source the Glen Mistro env vars
You need this to connect to Redshift. Skip if you already do this in your `.profile` or equivalent.
$ . ~/glenmistro/env_vars.sh
### Run the agent
$ python svagent.py
### Connect to the viewer from a web browser:
In your web browser open the URL http://localhost:5000/viewer/viewer.html
### Run an ai query:
In the `ai/analytics_db` dir, hack `tq.sh` to have the path to your `sqlview` directory, and then run:
$ ./tq.sh -u 1 allCorrespondents
If all went well, you should see the query and a grid with the query result in your browser window.
( And yes, I should fix the absolute path in that shell script...)
### Optional : Install Sublime Text Plugin
( I would skip this for now...this is from when I was writing queries directly in a file with just SQL, before setting up inbox_queries.js ).
To install the Sublime Text plugin, copy or link RunSqlPlugin.py in to the Sublime Text plugins directory. For me, this is ~//Library/Application Support/Sublime Text 3/Packages/User.
|
Markdown
|
UTF-8
| 826
| 2.5625
| 3
|
[] |
no_license
|
# c-projects
<h2>Personal projects to practice fundamentals and learn C</h2>
<h5>/mini-db</h5>
This project is a small database like SQLite. I'm following a tutorial found [here](https://cstack.github.io/db_tutorial/).
It is divided into the following sections:
* Part 1 - Introduction and Setting up the REPL
* Part 2 - World’s Simplest SQL Compiler and Virtual Machine
* Part 3 - An In-Memory, Append-Only, Single-Table Database
* Part 4 - Our First Tests (and Bugs)
* Part 5 - Persistence to Disk
* Part 6 - The Cursor Abstraction
* Part 7 - Introduction to the B-Tree
* Part 8 - B-Tree Leaf Node Format
* Part 9 - Binary Search and Duplicate Keys
* Part 10 - Splitting a Leaf Node
* Part 11 - Recursively Searching the B-Tree
* Part 12 - Scanning a Multi-Level B-Tree
* Part 13 - Updating Parent Node After a Split
|
Java
|
UTF-8
| 3,408
| 1.789063
| 2
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
// Generated by data binding compiler. Do not edit!
package com.ajdi.yassin.popularmovies.databinding;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.recyclerview.widget.RecyclerView;
import com.ajdi.yassin.popularmovies.R;
import java.lang.Deprecated;
import java.lang.Object;
public abstract class FragmentDiscoverMoviesBinding extends ViewDataBinding {
@NonNull
public final RecyclerView rvMovieList;
protected FragmentDiscoverMoviesBinding(Object _bindingComponent, View _root,
int _localFieldCount, RecyclerView rvMovieList) {
super(_bindingComponent, _root, _localFieldCount);
this.rvMovieList = rvMovieList;
}
@NonNull
public static FragmentDiscoverMoviesBinding inflate(@NonNull LayoutInflater inflater,
@Nullable ViewGroup root, boolean attachToRoot) {
return inflate(inflater, root, attachToRoot, DataBindingUtil.getDefaultComponent());
}
/**
* This method receives DataBindingComponent instance as type Object instead of
* type DataBindingComponent to avoid causing too many compilation errors if
* compilation fails for another reason.
* https://issuetracker.google.com/issues/116541301
* @Deprecated Use DataBindingUtil.inflate(inflater, R.layout.fragment_discover_movies, root, attachToRoot, component)
*/
@NonNull
@Deprecated
public static FragmentDiscoverMoviesBinding inflate(@NonNull LayoutInflater inflater,
@Nullable ViewGroup root, boolean attachToRoot, @Nullable Object component) {
return ViewDataBinding.<FragmentDiscoverMoviesBinding>inflateInternal(inflater, R.layout.fragment_discover_movies, root, attachToRoot, component);
}
@NonNull
public static FragmentDiscoverMoviesBinding inflate(@NonNull LayoutInflater inflater) {
return inflate(inflater, DataBindingUtil.getDefaultComponent());
}
/**
* This method receives DataBindingComponent instance as type Object instead of
* type DataBindingComponent to avoid causing too many compilation errors if
* compilation fails for another reason.
* https://issuetracker.google.com/issues/116541301
* @Deprecated Use DataBindingUtil.inflate(inflater, R.layout.fragment_discover_movies, null, false, component)
*/
@NonNull
@Deprecated
public static FragmentDiscoverMoviesBinding inflate(@NonNull LayoutInflater inflater,
@Nullable Object component) {
return ViewDataBinding.<FragmentDiscoverMoviesBinding>inflateInternal(inflater, R.layout.fragment_discover_movies, null, false, component);
}
public static FragmentDiscoverMoviesBinding bind(@NonNull View view) {
return bind(view, DataBindingUtil.getDefaultComponent());
}
/**
* This method receives DataBindingComponent instance as type Object instead of
* type DataBindingComponent to avoid causing too many compilation errors if
* compilation fails for another reason.
* https://issuetracker.google.com/issues/116541301
* @Deprecated Use DataBindingUtil.bind(view, component)
*/
@Deprecated
public static FragmentDiscoverMoviesBinding bind(@NonNull View view, @Nullable Object component) {
return (FragmentDiscoverMoviesBinding)bind(component, view, R.layout.fragment_discover_movies);
}
}
|
Java
|
UTF-8
| 622
| 2.59375
| 3
|
[
"CC-PDDC",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
package org.mapdb.impl.binaryserializer;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.mapdb.ValueSerializer;
public class LongValueSerializer implements ValueSerializer<Long>
{
@Override
public void serialize(DataOutput out, Long value) throws IOException
{
if(value != null)
out.writeLong(value);
}
@Override
public Long deserialize(DataInput in, int available) throws IOException {
if(available==0) return null;
return in.readLong();
}
@Override
public int fixedSize() {
return 8;
}
}
|
C++
|
UTF-8
| 5,873
| 3.75
| 4
|
[] |
no_license
|
#include "User.h"
#include "HighScoreManager.h"
#include <string>
#include <cstring>
#include <iostream>
#include <fstream>
User User::login(string userName){
User currentUser;
bool existingUser = CheckIfUserExists(userName);
if (existingUser == true) {
string line;
size_t pos = 0;
string delimiter = ",";
bool keepChecking = true;
//Check list of users stored in users
fstream usersFile("Users.txt", ios::in);
if (usersFile.is_open()) {
//While there's another line
while (getline(usersFile, line) && keepChecking)
{
//Grab the first delimiter position (username)
pos = line.find(delimiter);
//If they match, set user info
if ((line.substr(0, pos)) == userName) {
int section = 1;
currentUser.setUsername(line.substr(0, pos));
while ((pos = line.find(delimiter)) != std::string::npos)
{
//Based on what section we are at, update the information
if (section == 2) {
currentUser.setFirstName(line.substr(0, pos));
}
else if (section == 3) {
currentUser.setLastName(line.substr(0, pos));
}
else if (section == 4){
if (line.substr(0, pos) == ""){
currentUser.setAge(-1);
}
else {
currentUser.setAge(std::stoi(line.substr(0, pos)));
}
}
section++;
line.erase(0, pos + delimiter.length());
}
keepChecking = false;
}
}
}
else {
cout << "The file was not found!";
}
cout << "Welcome back, " << currentUser.getUsername() << endl;
}
else{
//Create user
currentUser.setUsername(userName);
currentUser.setAge(-1);
cout << "Nice to meet you, " << currentUser.getUsername() << "! A new account has been created for you!" << endl
<< "By default, your first & last name as well as your age will not be set." << endl;
}
return User(currentUser);
}
bool User::CheckIfUserExists(string userName)
{
string line;
size_t pos = 0;
string delimiter = ",";
//Check list of users stored in users
fstream usersFile("Users.txt", ios::in);
if (usersFile.is_open()) {
while (getline(usersFile, line))
{
pos = line.find(delimiter);
if((line.substr(0, pos)) == userName) {
return true;
}
}
}
else {
cout << "The file was not found!";
}
//Read in first line from users file
//check name against name
//if there's a match return true, else false
return false;
}
User User::UpdateUser(User user)
{
string menuChoice, userInput;
int updateMenuChoice;
do {
//Prompt the user for what they want to update
cout << "What would you like to edit?" << endl <<
"1) First Name" << endl << "2) Last Name" << endl << "3) Age" << endl << "4) Exit" << endl;
cin >> menuChoice;
updateMenuChoice = std::stoi(menuChoice);
//Set the user's information to the new info based on their choice
if (updateMenuChoice == 1)
{
cout << "New First Name: ";
cin >> userInput;
user.setFirstName(userInput);
}
else if (updateMenuChoice == 2)
{
cout << "New Last Name: ";
cin >> userInput;
user.setLastName(userInput);
}
else if (updateMenuChoice == 3)
{
cout << "New Age: ";
cin >> userInput;
int newAge = std::stoi(userInput);
user.setAge(newAge);
}
else if (updateMenuChoice == 4)
{
cout << "Thank you. Your information has been updated. You will now be returned to the main menu." << endl;
}
else
{
cout << "Invalid Choice" << endl;
}
} while (updateMenuChoice != 4);
//Return the updated user instance
return user;
}
void User::DeleteUser(User currentUser)
{
string line;
size_t pos = 0;
string delimiter = ",";
//Check list of users stored in users
fstream usersFile("Users.txt", ios::in);
ofstream updateFile;
updateFile.open("tempUser.txt", ofstream::out | ofstream::trunc);
if (usersFile.is_open()) {
while (getline(usersFile, line))
{
pos = line.find(delimiter);
//If the username is NOT a match, add it to the temp file
//where it does match, that user will be skipped over
if ((line.substr(0, pos)) != currentUser.username) {
updateFile << line << endl;
}
}
}
else {
cout << "The file was not found!";
}
usersFile.close();
updateFile.close();
remove("Users.txt");
rename("tempUser.txt", "Users.txt");
}
void User::SetHighScore(string userName)
{
HighScoreManager highScores;
int newScore = highScores.CreateHighScore(userName);
highScores.UpdateHighScore(newScore, userName);
}
void User::UpdateUserList(User currentUser)
{
string userAge;
if (currentUser.age == -1)
{
userAge = "";
}
else {
userAge = std::to_string(currentUser.getAge());
}
bool userFound = false;
string line;
size_t pos = 0;
string delimiter = ",";
//Check list of users stored in users
fstream usersFile("Users.txt", ios::in);
ofstream updateFile;
updateFile.open("tempUser.txt", ofstream::out | ofstream::trunc);
if (usersFile.is_open()) {
while (getline(usersFile, line))
{
//If username is a match, update it based on their current settings
pos = line.find(delimiter);
if ((line.substr(0, pos)) == (currentUser.getUsername())) {
updateFile << currentUser.getUsername() << "," << currentUser.getFirstName() << "," <<
currentUser.getLastName() << "," << userAge << "," << endl;
userFound = true;
}
//If it's not a match, then just add the original line
else
{
updateFile << line << endl;
}
}
//If we found no match for the user, it's a new user, add their info
if (userFound == false) {
updateFile << currentUser.getUsername() << "," << currentUser.getFirstName() << "," <<
currentUser.getLastName() << "," << userAge << "," << endl;
}
}
else {
cout << "The file was not found!";
}
//Close the files, overwrite the old Users file with the temp one holding the updated info
usersFile.close();
updateFile.close();
remove("Users.txt");
rename("tempUser.txt", "Users.txt");
}
|
Java
|
UTF-8
| 1,266
| 2.5625
| 3
|
[] |
no_license
|
package com.example.shubhampandey.parceldrop.util;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by SHUBHAM PANDEY on 3/6/2016.
*/
public class FetchPickupRates {
public static JSONObject getJSON(int weight) {
String OPEN_API =
"https://hackerearth.0x10.info/api/ipickup?type=json&query=current_rates&weight=" + weight;
try {
URL url = new URL(OPEN_API);
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(inputStreamReader);
StringBuilder json = new StringBuilder(1024);
String tmp = "";
while ((tmp = reader.readLine()) != null)
json.append(tmp).append("\n");
reader.close();
JSONObject jsonObject = new JSONObject(json.toString());
return jsonObject.getJSONArray("current_rates").getJSONObject(0);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
|
JavaScript
|
UTF-8
| 3,041
| 4.34375
| 4
|
[] |
no_license
|
/*
In the exercise below, write your own code where indicated
to achieve the desired result.
Make sure to run the file with node in your command line.
*/
//-------------------
// Part 1: Syntax and Naming Conventions
//-------------------
// For each prompt:
// Write a class skeleton
// Create 2 object instances and store in variables
// Log each variable to the console.
// You do not need any properties at this time!!
// Prompt 1: Dog
class Dog {
}
var milo = new Dog()
var marley = new Dog()
console.log(milo)
console.log(marley)
// Prompt 2: Snack
class Snack {
}
var doritos = new Snack()
var kale = new Snack()
console.log(doritos);
console.log(kale);
// Prompt 3: Shirt
class Shirt {
}
var abercrombie = new Shirt()
var aeropostale = new Shirt()
console.log(abercrombie)
console.log(aeropostale)
//-------------------
// Part 2: Properties
//-------------------
// For each prompt:
// Write a class skeleton
// Add a constructor method
// Assign 3 properties (names and values of your choice) to each class
// Create an object instance and store in variable
// Log that variable to the console.
// Prompt 1: Dog
class Doggy {
constructor(breed, age, size) {
}
}
var milo = new Doggy()
var marley = new Doggy()
console.log(milo)
console.log(marley)
// Prompt 2: Snack
class Snacky {
constructor(amt, flavor, healtyStr) {
}
}
var doritos = new Snacky()
var kale = new Snacky()
console.log(doritos);
console.log(kale);
// Prompt 3: Shirt
class Shirty {
constructor(size, cottonStr, sleeves) {
}
}
var abercrombie = new Shirt()
var aeropostale = new Shirt()
console.log(abercrombie)
console.log(aeropostale)
//-------------------
// Part 3: Dynamic Properties
//-------------------
// For each prompt:
// Write a class skeleton
// Add a constructor method
// Declare 3 parameters in the consutructor
// Assign 3 properties (names and values of your choice), using the parameters
// Create 2 object instances and store in variables (passing in different arguments)
// Log those variables to the console.
// Prompt 1: Dog
class Dogg {
constructor(breed, age, size) {
this.breed = breed
this.age = age
this.size = size
}
}
var milo = new Dogg('husky', 3,'large')
var marley = new Dogg('toy poodle', 2, 'small')
console.log(milo)
console.log(marley)
// Prompt 2: Snack
class Snaack {
constructor(amt, flavor, healthStr) {
this.price = amt
this.flaver = flavor
this.healthy = healthStr
}
}
var doritos = new Snaack (3, "salty", "no")
var kale = new Snaack (2, "bitter", "yes")
console.log(doritos);
console.log(kale);
// Prompt 3: Shirt
class Shiirt {
constructor(size, cottonStr, sleeves) {
this.shirtSize = size
this.isCotton = cottonStr
this.sleeves = sleeves
}
}
var abercrombie = new Shiirt ("medium", true, "long sleeves")
var aeropostale = new Shiirt ("large", false, "short sleeves")
console.log(abercrombie)
console.log(aeropostale)
|
Java
|
UTF-8
| 2,324
| 2.59375
| 3
|
[] |
no_license
|
package com.dh.project.Face_Recognition.gui;
import com.dh.project.Face_Recognition.service.MyVideoCapture;
import org.opencv.core.Core;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
public class MyFrame extends JFrame {
private static final long serialVersionUID = 1L;
private static boolean isChecked = true;
private JLabel lblVideo;
private MyVideoCapture videoCapture = new MyVideoCapture();
public MyFrame() throws IOException, InterruptedException {
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(0, 0, dim.width, dim.height);
getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(10, 11, dim.width, dim.height);
getContentPane().add(panel);
panel.setLayout(null);
lblVideo = new JLabel();
lblVideo.setBounds(0, 0, dim.width, dim.height);
// lblVideo.setVisible(true);
panel.add(lblVideo);
new MyThread().start();
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MyFrame frame = new MyFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
class MyThread extends Thread {
@Override
public void run() {
long start = System.currentTimeMillis();
while (MyFrame.isChecked) {
long time = System.currentTimeMillis() - start;
int seconds = (int) (time / 1000);
BufferedImage img = null;
try {
img = videoCapture.getOneFrame();
} catch (IOException e) {
e.printStackTrace();
}
if(img != null) {
lblVideo.setIcon(new ImageIcon(img));
}
}
}
}
private void close() {
this.dispose();
}
}
|
Java
|
UTF-8
| 795
| 2.5
| 2
|
[] |
no_license
|
package com.vinodshivaram.practice.springboot.model;
import sun.security.util.Password;
public class Authentication {
private String userName;
private Password password;
private String token;
public Authentication(String userName, Password password) {
this.userName = userName;
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Password getPassword() {
return password;
}
public void setPassword(Password password) {
this.password = password;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
|
JavaScript
|
UTF-8
| 865
| 2.515625
| 3
|
[] |
no_license
|
import React, { Component } from "react";
import { connect } from "react-redux";
import { addTodo } from "../action";
class AddTodo extends Component {
render() {
return (
<div>
<form
onSubmit={e => {
e.preventDefault();
this.addTodoClick(this.input);
}}
>
<input
ref={node => {
this.input = node;
}}
/>
<button type="submit">Add Todo</button>
</form>
</div>
);
}
addTodoClick(input) {
if (!input.value.trim()) {
return;
}
this.props.addTodoAction(input.value);
input.value = "";
}
}
const mapDispatchToProps = dispatch => {
return {
addTodoAction: text => {
dispatch(addTodo(text));
}
};
};
export default connect(
null,
mapDispatchToProps
)(AddTodo);
|
Java
|
UTF-8
| 2,016
| 2.484375
| 2
|
[] |
no_license
|
package pages;
import io.appium.java_client.MobileElement;
import io.appium.java_client.pagefactory.AndroidFindBy;
import io.appium.java_client.pagefactory.WithTimeout;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.testng.Assert;
import java.time.temporal.ChronoUnit;
public class SignInPage extends Page {
Logger logger = LogManager.getLogger(SignIntoYourAccountPage.class.getName());
@AndroidFindBy(xpath = "//*[@text = 'Sign-In']")
@WithTimeout(time = 5, chronoUnit = ChronoUnit.SECONDS)
MobileElement pageRef;
@AndroidFindBy(xpath = "//*[@resource-id = 'ap_password']")
@WithTimeout(time = 5, chronoUnit = ChronoUnit.SECONDS)
MobileElement passwordTextField;
@AndroidFindBy(xpath = "//*[@resource-id = 'signInSubmit']")
@WithTimeout(time = 5, chronoUnit = ChronoUnit.SECONDS)
MobileElement signInButton;
@AndroidFindBy(xpath = "//*[@resource-id = 'auth-signin-show-password-checkbox']")
@WithTimeout(time = 5, chronoUnit = ChronoUnit.SECONDS)
MobileElement showPassword;
@AndroidFindBy(xpath = "//*[contains(@text, 'Keep me signed in')]")
@WithTimeout(time = 5, chronoUnit = ChronoUnit.SECONDS)
MobileElement keepMeSignedIn;
public SignInPage() {
super();
pageRefObj = pageRef;
}
/**
* Enter Password
*
* @param password Password to be entered
*/
public void enterPassword(String password) {
logger.info("Entering Password");
if(!setText(passwordTextField, password)) {
Assert.fail("Failed to enter password");
} else {
logger.info("Entered Password successfully");
}
}
/**
* Click Sign In
*/
public void clickSignIn() {
logger.info("Clicking on Sign In");
if(!clickButton(signInButton)) {
Assert.fail("Failed to click on sign in buttom");
} else {
logger.info("Clicked on sign in button");
}
}
}
|
JavaScript
|
UTF-8
| 1,492
| 2.640625
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
var Jasmine = require('jasmine')
var jasmine = new Jasmine()
jasmine.loadConfig({
spec_dir: 'test',
spec_files: ['test.js'],
random: false,
seed: null,
stopSpecOnExpectationFailure: false,
})
class MyConsoleReporter {
constructor() {
this.suiteSeq = 1
}
_indentPrint(str) {
str
.trim()
.split('\n')
.forEach((line) => {
process.stdout.write(' ' + line + '\n')
})
}
jasmineStarted(suiteInfo) {
console.log(`Running suite with ${suiteInfo.totalSpecsDefined} tests.`)
}
suiteStarted(result) {
console.log(`\n${this.suiteSeq}. ${result.fullName}`)
this.suiteSeq++
}
specStarted(result) {
process.stdout.write(` - ${result.description} `)
}
specDone(result) {
process.stdout.write(
` ${result.status} [${result.passedExpectations.length}] (${result.duration} ms)`
)
for (var i = 0; i < result.failedExpectations.length; i++) {
console.log()
this._indentPrint(result.failedExpectations[i].message)
this._indentPrint(result.failedExpectations[i].stack)
}
process.stdout.write(`\n`)
}
jasmineDone(result) {
console.log('Overall result: ' + result.overallStatus)
for (var i = 0; i < result.failedExpectations.length; i++) {
console.log('Global ' + result.failedExpectations[i].message)
console.log(result.failedExpectations[i].stack)
}
}
}
jasmine.jasmine.getEnv().addReporter(new MyConsoleReporter())
jasmine.execute()
|
Java
|
UTF-8
| 1,288
| 4.21875
| 4
|
[] |
no_license
|
import java.util.*;
public class Question9
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
System.out.println(legal(str, 0, str.length() - 1));
}
public static boolean legal(String str, int index, int n)
{
if(index == 0 && str.charAt(0) != 'a')
return false;
if(index < n)
{
char ch = str.charAt(index);
if(ch == 'b')
{
if(str.charAt(index + 1) != 'b')
return false;
else
return legal(str, index + 2, n);
}
else
{
if(str.charAt(index + 1) != 'b' && str.charAt(index + 1) != 'a')
return false;
else
return legal(str, index + 1, n);
}
}
return true;
}
}
/*
Question :-
Take as input str, a string. Write a recursive function that checks if the string was
generated using the following rules and returns a Boolean value: a. the string
begins with an 'a' b. each 'a' is followed by nothing or an 'a' or "bb" c. each "bb" is
followed by nothing or an 'a' Print the value returned.
Eg: abba
Output: true
*/
|
JavaScript
|
UTF-8
| 3,707
| 2.59375
| 3
|
[] |
no_license
|
document.addEventListener("deviceready", function () { init(myPath); }, false);
var myPath = 'file:///';
var musicData = [];
var current;
function init(myPath) {
window.resolveLocalFileSystemURL(myPath,
function (dir) {
var reader = dir.createReader();
reader.readEntries(function (entries) {
console.log("readEntries");
console.dir(entries);
var data = [];
//var reader = new FileReader();
var process = function (index, cb) {
console.log("doing index " + index);
var entry = entries[index];
//var name = entry.name;
if (entry.isDirectory) {
data.push({ url: entry.nativeURL, name: entry.name, fileType: false });
}
else if (entry.isFile) {
data.push({ url: entry.nativeURL, name: entry.name, fileType: true });
musicData.push({ url: entry.nativeURL, name: entry.name, fileType: true });
}
if (index + 1 < entries.length) {
process(++index, cb);
} else {
cb(data);
}
};
process(0, function (data) {
console.dir(data);
var s = "";
for (var i = 0; i < data.length; i++) {
if (data[i].fileType === false)
s += '<li onclick="init(' + "'" + data[i].url + "'" + ');">' + data[i].name + '</li>';
else if (checkFileExtension(data[i].name) === true)
s += '<li onclick="playMP3(' + "'" + data[i].url + "'"+","+"'" + i + "'" + ');">' + data[i].name + '</li>';
}
document.getElementById("select-demo").innerHTML = s;
});
});
}, function (err) {
});
}
var media;
function playMP3(l, post) {
if (media) { media.stop(); media.release(); }
media = new Media(l, null, function (err) { console.dir(err); });
media.play();
current = post;
}
function stopMP3(l) {
if (media) { media.stop(); media.release(); }
}
function processMP3File(url) {
var s;
entry.file(function (file) {
data.push({ name: entry.name });
ID3.loadTags(entry.name, function () {
var tags = ID3.getAllTags(name);
data.push({ name: entry.name, tags: tags });
console.log("got tags for " + entry.name, tags);
document.getElementById("details").innerHTML += "*";
}, {
dataReader: FileAPIReader(file)
});
});
s += "<p>";
s += "<b>" + data[i].tags.title + "</b><br/>";
s += "By " + data[i].tags.artist + "<br/>";
s += "Album: " + data[i].tags.album + "<br/>";
s += "</p>";
document.getElementById("details").innerHTML = s;
}
/*document.addEventListener('backbutton', function () {
if (menu is visible) {
//Hide the menu
//This is also working fine
return false;
}
else //nothing is visible, exit the app
{
navigator.app.exitApp();
}
});*/
function checkFileExtension(fileName) {
if (fileName.indexOf(".mp3") > -1)
return true;
return false;
}
function checkFolderName(folderName) {
if (folderName.indexOf("storage") > -1 || folderName.indexOf("sdcard") > -1)
return true;
return false;
}
|
JavaScript
|
UTF-8
| 1,131
| 2.765625
| 3
|
[] |
no_license
|
export function ColourSwatches({ setCurrentColour }) {
const colourSwatches = [
"hsl(352, 100%, 65%)",
"hsl(41, 100%, 65%)",
"hsl(193, 72%, 63%)",
"hsl(0, 0%, 100%)",
"hsl(0, 0%, 50%)",
"hsl(0, 0%, 0%)",
];
return (
<ul className="colour-swatches">
{colourSwatches.map((swatch, index) => {
return (
<li
className={index === 0 ? "colour-swatch current-swatch" : "colour-swatch"}
onClick={(e) => {setCurrentColour(swatch); setAsCurrentSwatch(e.target)}}
key={index}>
<svg
xmlns="http://www.w3.org/2000/svg"
height="24"
viewBox="0 0 24 24"
width="24"
fill={swatch}
>
<path d="M0 0h24v24H0z" fill="none" />
<path d="M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2z" />
</svg>
</li>
);
})}
</ul>
);
}
function setAsCurrentSwatch(element){
document.querySelector(".current-swatch").classList.remove("current-swatch");
element.classList.add("current-swatch");
}
|
Markdown
|
UTF-8
| 584
| 2.6875
| 3
|
[] |
no_license
|
Before compiling , please make sure you have the OpenSSL dev package installed .</br>
Compile using : </br>
<b> gcc -Wall -g -o shell shell.c -lssl -lcrypto </b></br>
You will probably want to link statically against the library to avoid dependencies issues on the target .
You can either use ncat (http://edoceo.com/cli/ncat) or any other tool with ssl support to send commands to the client .</br>
To test the client, you can use openssl s_server utility on your server and wait for connections:</br>
<b>openssl s_server -key key.pem -cert cert.pem -accept 443</b>
|
Markdown
|
UTF-8
| 6,571
| 3.28125
| 3
|
[] |
no_license
|
---
layout: post
title: How I Got Into Computers University Edition
date: 2020-08-17T00:00:00.0000000-05:00
---
This is the second post in a series about how I got into computers and how my career has unfolded. [Part 1 was pre-university](https://blog.lhotka.net/2020/08/15/How-I-Got-Into-Computers).
I went to two universities: the US Air Force Academy in Colorado, and Bemidji State University in northern Minnesota.
At USAFA I did take a computer class; some sort of intro to computing where we used Turtle Graphics (logo?) to control a pen that drew shapes on the screen. I think we might have learned some Pascal as well.
I ended up leaving USAFA after a year and transferred to Bemidji State in Minnesota. With most of my non-major classes out of the way, I focused largely on a Computer Science major and Mathematics minor. The minor was kind of a no-brainer, because it was just 1-2 extra classes beyond the requirements for Computer Science.
My biggest regret about my university time, is that I didn't really take advantage of my _non-major_ classes. I did them because they were required get to the stuff I really wanted to learn. Now, decades later, I find myself very interested in things like philosophy and some aspects of history, and wish I'd put more energy into those topics when I had the chance.
BSU used DEC VAX computers (and so did USAFA) for their curriculum. The primary language used by the CS department was Pascal, specifically DEC Pascal, which was in many ways closer to Modula II than Pascal, in that we had access to a type of module concept, multiple compiled output units, and a linker that combined the compiled files into a final executable.
What is interesting, when I compare my youngest son's experience (he recently got a EE degree with a CS minor) to mine, is how much is the same, and what is different.
1. Both of us took basic programming and algorithms type classes
1. He learned object oriented concepts, which didn't exist yet when I was in school
1. He used a combination of Java and C#, where I used Pascal
1. We both had assembly language classes
1. I took a class on how to create an assembler, he did not
1. We both used command line interfaces and simple text editors (I used something called TPU (text processing utility) and he used vim)
1. The fact that universities still use text editors rather than modern tools like sublime, vscode, eclipse, visual studio, etc. just boggles my mind!!
1. We both took a computer architecture class; how gates work, how memory is addressed, etc. For him this was an intro class and he went way deeper in subsequent classes, while for me this was the only "hardware" class I ever took
1. Both of us took ridiculous amounts of mathematics
1. Where he spent a lot of time in engineering classes, I spent my time in classes on how to write compilers, operating systems, numerical analysis, software modeling and simulations, and other high end CS content
1. Neither of us took a database class; in my case it was because relational data theory didn't have a class yet, and in his case because it wasn't required for the CS minor
That last point is, in my mind, a big sticking point. Even for me, with my degree predating relational database engines, the _concepts_ of data relationships were known and should have been taught. As I'll talk about in a future post, not knowing even basic data relationship concepts was a hardship!
What I think is most important from my time in school is this: you get out of it what you put into it.
BSU was not a big school, and some teachers were pretty iffy, and a couple were amazingly good (in particular, thank you Dave Miller!).
The thing is, I was doing what I loved. I was generally more interested in writing software than partying or doing a lot of other "normal college stuff".
I wrote my own MUD (multi-user dungeon) called Mordecai. Inspired by the MUD I'd played in middle and high school. As a side bar, it turns out that there's a fairly direct line between me writing Mordecai (and it becoming very popular) and how I met the woman who's now my wife.
The thing is, I learned so much by writing and maintaining this game. Concepts that they didn't teach in class, like
* how to build a large scale bit of software
* how to handle bug and feature requests
* how to debug something that became quite large
* how to read/write configuration and data files (even without understanding data relationships)
* basic natural language parsing
* actual applications for many of the algorithms and data structures I'd learned in class
* multi-user contention issues
* multi-user communication in a near realtime setting
Now I'm not saying everyone should write a MUD in university. But I do think there's value in writing _something real_, because most classes never have students write anything of size. And size brings complexity, and an understanding of how to deal with complexity. This is important, because in the "real world" most software is big and complex, and has multiple concurrent users and performance requirements and bug reports and feature requests.
That MUD isn't the only thing I wrote. I love table-top gaming (strategy, role-playing, etc.) and I wrote software to help run various games.
I'd also moved off-campus and would dial in to the school's VAX using a 1200 baud modem (so fast!!). The problem was, I had a Commodore 64 with a very poor VT100 terminal emulator. So I wrote my own terminal emulator using C, including my own font rendering to get 80 characters across the screen (the C64 itself had no such capability).
I also took every software language class offered, including those from the Business School (COBOL and RPG II). So I finished school knowing Pascal, FORTRAN, COBOL, RPG II, BASIC, and DCL (sort of like powershell or bash). And bits and pieces of some other languages from my numerical analysis and simulation classes.
I didn't _have to_ take all those language classes, and all my CS friends though it was really weird that I'd take classes in the business languages, because they weren't "real programming".
In the end, I come back to the idea that I threw myself into learning everything I could about computing and software, and I got a lot out of it. And I practiced _a lot_ by writing software for myself and others outside of the requirements for any classes.
All that time, in retrospect, was incredibly well spent, because many of the opportunities I've had in my career came about because I'd done or learned something few other people knew, and knowledge is power.
|
Java
|
UTF-8
| 733
| 2.546875
| 3
|
[
"Apache-2.0"
] |
permissive
|
package com.ftfl.icare.modelclass;
public class NoteModel {
Integer mNoteId = 0;
String mDate = null;
String mNote = null;
public NoteModel() {
}
public NoteModel(int eNoteId, String eDate, String eNote) {
this.mNoteId = eNoteId;
this.mDate = eDate;
this.mNote = eNote;
}
public NoteModel(String eDate, String eNote) {
this.mDate = eDate;
this.mNote = eNote;
}
public Integer getmNoteId() {
return mNoteId;
}
public void setmNoteId(int mNoteId) {
this.mNoteId = mNoteId;
}
public String getmDate() {
return mDate;
}
public void setmDate(String mDate) {
this.mDate = mDate;
}
public String getmNote() {
return mNote;
}
public void setmNote(String mNote) {
this.mNote = mNote;
}
}
|
C++
|
UTF-8
| 6,635
| 2.671875
| 3
|
[] |
no_license
|
#include "komi.h"
#include <QString>
#include <QFile>
#include <QTextStream>
QFile mainSize("C:/Users/79194/Documents/test/MatrixSize.txt");
QTextStream MainstreamSize(&mainSize);
QFile mainMatrix("C:/Users/79194/Documents/test/Matrix.txt");
QTextStream MainstreamMatrix(&mainMatrix);
Komi::Komi()
{
}
void Komi::SetSize_Matrix()
{
way = "";
counter = 1;
// 1 Создание матрицы смежности
mainSize.open(QFile::ReadOnly | QFile::Text);
Mainlen = MainstreamSize.readLine().toInt(0, 10);
mainSize.flush();
mainSize.close();
mainSize.open(QFile::WriteOnly | QFile::Text);
MainstreamSize << QString::number(Mainlen);
mainSize.flush();
mainSize.close();
di = Mainlen;
MainMatrix = new int* [Mainlen + 1];
Mtemp = new int* [Mainlen];
roads = new int* [Mainlen];
for (int i = 0; i < Mainlen; i++)
{
MainMatrix[i] = new int [Mainlen + 1];
roads[i] = new int[2];
Mtemp[i] = new int[Mainlen];
}
MainMatrix[di] = new int[Mainlen + 1];
// 2 Заполнение матрицы
mainMatrix.close();
mainMatrix.open(QFile::ReadOnly | QFile::Text);
for (int i = 0; i < Mainlen; i++)
{
for (int j = 0; j < Mainlen; j++)
{
MainMatrix[i][j] = MainstreamMatrix.readLine().toInt(0, 10);
Mtemp[i][j] = MainMatrix[i][j];
}
}
mainMatrix.flush();
mainMatrix.close();
mainMatrix.open(QFile::WriteOnly | QFile::Text);
for (int i = 0; i < Mainlen; i++)
{
for (int j = 0; j < Mainlen; j++)
{
MainstreamMatrix << QString::number(MainMatrix[i][j]) << "\n";
}
}
mainMatrix.close();
// 3 Заменим размер дороги от одного к тому же городу или отсуствие дорог числом 10000 (будем считать, что это число является бесконечностью)
for (int i = 0; i < Mainlen; i++)
{
for (int j = 0; j < Mainlen; j++)
{
if (MainMatrix[i][j] == 0)
{
MainMatrix[i][j] = 10000;
}
}
}
MainMatrix[di][di] = 0;
}
int Komi::getNumber(int I, int J)
{
int k = 0, resJ, resI;
while(k == J)
{
k++;
}
resJ = MainMatrix[I][k];
k = 0;
while(k == I)
{
k++;
}
resI = MainMatrix[k][J];
for (k = 0; k < Mainlen; k++) // Проход по строкам и столбцам
{
if (MainMatrix[I][k] < resJ && k != J)
{
resJ = MainMatrix[I][k];
}
if (MainMatrix[k][J] < resI && k != I)
{
resI = MainMatrix[k][J];
}
}
return resI + resJ;
}
void Komi::RemoveNode(int I, int J)
{
for (int k = 0; k < Mainlen; k++)
{
MainMatrix[k][J] = 10000;
MainMatrix[I][k] = 10000;
MainMatrix[k][k] = 10000;
}
if (MainMatrix[J][I] == 0)
{
MainMatrix[J][I] = 10000;
}
}
void Komi::GetWay(int Node)
{
if (roads[Node][0] != start || counter > 0)
{
counter--;
way += " -> ";
way += QString::number(roads[Node][1]);
for (int i = 0; i < Mainlen; i++)
{
if (roads[i][0] == roads[Node][1])
{
GetWay(i);
break;
}
}
}
}
QString Komi::GetResult(QString root)
{
SetSize_Matrix();
start = root.toInt(0, 10);
bool ok;
if (!(root.toInt(&ok, 10)) || (root.toInt(0, 10) < 1 && root.toInt(0, 10) > Mainlen) || Mainlen < 3)
{
return "";
}
// В цикле
for (int nodes = 0; nodes < Mainlen; nodes++)
{
// 4 Нахождение минимума по строкам + Шаг 3. Редукция строк
// 5 Нахождение минимума по столбцам + Шаг 5. Редукция столбцов
for (int i = 0; i < Mainlen; i++)
{
MainMatrix[i][di] = MainMatrix[i][0]; // Первый элемент в строке минимальный
MainMatrix[di][i] = MainMatrix[0][i]; // Первый элемент в столбце минимальный
for (int j = 1; j < Mainlen; j++)
{
if (MainMatrix[i][j] < MainMatrix[i][di]) // Строка
{
MainMatrix[i][di] = MainMatrix[i][j];
}
if (MainMatrix[j][i] < MainMatrix[di][i]) // Столбец
{
MainMatrix[di][i] = MainMatrix[j][i];
}
}
if (MainMatrix[i][di] == 10000) // Строка
{
MainMatrix[i][di] = 0;
}
if (MainMatrix[di][i] == 10000) // Столбец
{
MainMatrix[di][i] = 0;
}
for (int j = 0; j < Mainlen; j++)
{
if (MainMatrix[i][j] != 10000) // Строка
{
MainMatrix[i][j] -= MainMatrix[i][di];
}
if (MainMatrix[j][i] != 10000) // Столбец
{
MainMatrix[j][i] -= MainMatrix[di][i];
}
}
}
// 6 Вычисление оценок нулевых клеток + Редукция матрицы
int max = 0,
Imax = -1,
Jmax = -1;
for (int i = 0; i < Mainlen; i++)
{
for (int j = 0; j < Mainlen; j++)
{
if (MainMatrix[i][j] == 0)
{
if (getNumber(i, j) >= max)
{
max = getNumber(i, j);
Imax = i;
Jmax = j;
}
}
}
}
RemoveNode(Imax, Jmax);
roads[nodes][0] = Imax + 1;
roads[nodes][1] = Jmax + 1;
MainMatrix[di][di] += Mtemp[Imax][Jmax];
}
for (int i = 0; i < Mainlen; i++)
{
if (roads[i][0] == start)
{
way += QString::number(roads[i][0]);
GetWay(i);
break;
}
}
return way;
}
QString Komi::WayLength(QString root)
{
bool ok;
if (!(root.toInt(&ok, 10)) || (root.toInt(0, 10) < 1 || root.toInt(0, 10) > Mainlen) || Mainlen < 3)
{
return "";
}
return QString::number(MainMatrix[di][di]);
}
Komi::~Komi()
{
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.