language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
Java
|
UTF-8
| 2,150 | 2.40625 | 2 |
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.logica.ndk.tm.fileServer.service.input;
import org.apache.commons.io.IOUtils;
import org.slf4j.LoggerFactory;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.*;
import java.net.URISyntaxException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author brizat
*/
public class Loader {
private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(Loader.class);
public static <V> void save(String path, V object, Class<V> clazz) {
try {
File file = new File(path);
if (!file.exists()) {
try {
file.createNewFile();
}
catch (IOException ex) {
Logger.getLogger(Loader.class.getName()).log(Level.SEVERE, null, ex);
}
}
JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(object, file);
//Only for test
jaxbMarshaller.marshal(object, System.out);
}
catch (JAXBException e) {
e.printStackTrace();
}
}
public static <V> V load(String path, Class<V> clazz) throws JAXBException, URISyntaxException, FileNotFoundException {
InputStream stream = null;
try {
stream = new FileInputStream(new File(path));
JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
V object = (V) jaxbUnmarshaller.unmarshal(stream);
//System.out.println(object);
return object;
}
finally {
IOUtils.closeQuietly(stream);
}
}
public static InputFile load(String path) throws JAXBException, URISyntaxException, FileNotFoundException {
return load(path, InputFile.class);
}
}
|
Python
|
UTF-8
| 481 | 2.625 | 3 |
[] |
no_license
|
#coding:utf-8
class GameStats():
'''statistical information of game tracing'''
def __init__(self, ai_settings):
'''initial the information'''
self.ai_settings = ai_settings
#flag is true when game is active
self.game_active = False
self.high_score = 0
self.reset_stats()
def reset_stats(self):
'''initial the information which probably change during running the game'''
self.ships_remain = self.ai_settings.ship_limit
self.score = 0
self.level = 1
|
Markdown
|
UTF-8
| 5,879 | 2.65625 | 3 |
[] |
no_license
|
---
layout: default
title: HoloLens Dev tips
---
This is a HoloLens development documentation for the project.
---
## [Getting started with HoloToolkit](https://forums.hololens.com/discussion/2364/getting-started-with-holotoolkit)
Here are the steps that you currently need to take to run sample projects in HoloToolkit-Unity:
1. Clone the HoloToolkit-Unity project from GitHub to your PC.
2. Launch Unity and select 'Open'
3. Select the 'HoloToolkit-Unity' folder on your PC to open the project in Unity
4. In the Project panel, expand the HoloToolkit folder
5. Locate the feature that you are interested in (we'll use SpatialMapping as an example)
6. Expand SpatialMapping feature and then select the 'Tests' folder.
7. Double-click on one of the test scenes to open it (I would suggest trying the 'SpatialProcessing' scene, since it can run inside of Unity).
8. Some scenes (like 'SpatialProcessing') can run inside of Unity, so you just need to press the 'Play' button. All scenes will run on the HoloLens, but you need to follow the build/deploy process outlined in our docs and Academy courses.
9. If you're confused about what a test does, locate the ReadMe file associated with the feature (view it on GitHub for nice formatting, or find and double-click it under the feature-level folder in Unity). There should be instructions/explanations for each test scene.
If you want to try more end-to-end samples, then there are several available under the 'HoloToolkit-Examples' folder. To run the SpatialMappingComponent example, you would do the following:
1. Expand the 'HoloToolkit-Examples' folder.
2. Click on the 'SpatialMappingComponent' folder.
3. Double-click on the 'Example' scene to load it.
4. This sample must run on the HoloLens, so build/deploy as usual (In the Build Settings window, don't forget to press the 'AddOpenScenes' button to add the current scene to the build and delete any scene from the list that you may have added before).
5. There should be a ReadMe file associated with each example to help explain what is going on.
If you get to the point where you want to import HoloToolkit into your own Unity project, then you can do the following:
1. In the HoloToolkit-Unity project, right-click on the 'HoloToolkit' folder and select 'Export package'.
2. Wait a few seconds for the export dialog to populate...
3. You can create a custom package by unchecking any folders/scripts that you do not want to export. For example, if you don't need any of the 'Build' 'Cross Platform' 'Sharing' and 'Spatial Sound' components, then uncheck those folders. It's a good idea to uncheck all of the 'test' folders under each feature too, and make sure that the 'HoloToolkit-Examples' folder is not included so you don't get test scenes added to your project.
4. Press the 'Export' button.
5. Save the .unitypackage
6. Open your personal project in Unity or create a new project.
7. Select the 'Assets' file menu option at the top of Unity
8. Select 'Import Package' > 'Custom Package' and then find and select the .unitypackage that you saved in step 5 above. Press the 'Open' button.
9. If there are any files that you don't want to import into your project, you can uncheck them now, otherwise, press the 'Import' button.
10. The 'HoloToolkit' folder should now appear under the 'Assets' folder in the Project panel.
## Unity settings for HoloLens
### 1. Player settings
1. From the Build Settings... window, open Player Settings...
2. Select the Settings for Windows Store tab
3. Expand the Other Settings group
4. In the Rendering section, check the Virtual Reality Supported checkbox to add a new Virtual Reality Devices list and confirm "Windows Holographic" is listed as a supported device.
### 2. Build Settings
1. Select File > Build Settings...
2. Select Windows Store in the Platform list.
3. Set SDK to Universal 10
4. Set Build Type to D3D.
### 3. Performance settings

1. Select Edit > Project Settings > Quality
2. Select the dropdown under the Windows Store logo and select Fastest. You'll know the setting is applied correctly when the box in the Windows Store column and Fastest row is green.
## Visual Studio settings
### Edit `Package.appxmanifest` in VS.
`TargetDeviceFamily Name` & `MaxVersion`.
Example:
```XML
<Dependencies>
<TargetDeviceFamily Name="Windows.Holographic" MinVersion="10.0.10240.0" MaxVersionTested="10.0.10586.0" />
</Dependencies>
```
### VS Build settings

## Mirroring/Accessing HoloLens
1. [Hololens app on Windows 10](https://www.microsoft.com/en-ca/store/p/microsoft-hololens/9nblggh4qwnx)
2. From a web browser on your PC, go to https://<YOUR_HOLOLENS_IP_ADDRESS>
* The browser will display the following message: "There’s a problem with this website’s security certificate". This happens because the certificate which is issued to the Device Portal is a test certificate. You can ignore this certificate error for now and proceed.
## "My cursor is not showing!" or "My C# scripts are not working" or VS fails to build/attach debugger.

_< You MUST add-component your scripts to corresponding objects in Unity in order to let Unity use the scripts. >_
## Build fail in Unity
* Error: `missing path \UnionMetadata\Facade\Windows.winmd`
* [Install Windows 10 SDK](http://answers.unity3d.com/questions/1116443/windows-sdk-installed-but-get-error.html)
## Deploy fail in VS
* Error: `Metadata file '.dll' could not be found`
* [Solution](http://stackoverflow.com/a/17723774):
1. Right click on the solution and click Properties.
2. Click Configuration on the left.
3. Make sure the check box under "Build" for the project it can't find is checked. If it is already checked, uncheck, hit apply and check the boxes again.
|
Markdown
|
UTF-8
| 1,834 | 3.453125 | 3 |
[
"MIT"
] |
permissive
|
<!--|This file generated by command(leetcode description); DO NOT EDIT. |-->
<!--+----------------------------------------------------------------------+-->
<!--|@author openset <openset.wang@gmail.com> |-->
<!--|@link https://github.com/openset |-->
<!--|@home https://github.com/openset/leetcode |-->
<!--+----------------------------------------------------------------------+-->
[< Previous](../degree-of-an-array "Degree of an Array")
[Next >](../falling-squares "Falling Squares")
## [698. Partition to K Equal Sum Subsets (Medium)](https://leetcode.com/problems/partition-to-k-equal-sum-subsets "划分为k个相等的子集")
<p>Given an array of integers <code>nums</code> and a positive integer <code>k</code>, find whether it's possible to divide this array into <code>k</code> non-empty subsets whose sums are all equal.</p>
<p> </p>
<p><b>Example 1:</b></p>
<pre>
<b>Input:</b> nums = [4, 3, 2, 3, 5, 2, 1], k = 4
<b>Output:</b> True
<b>Explanation:</b> It's possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.
</pre>
<p> </p>
<p><b>Note:</b></p>
<ul>
<li><code>1 <= k <= len(nums) <= 16</code>.</li>
<li><code>0 < nums[i] < 10000</code>.</li>
</ul>
### Related Topics
[[Recursion](../../tag/recursion/README.md)]
[[Dynamic Programming](../../tag/dynamic-programming/README.md)]
### Similar Questions
1. [Partition Equal Subset Sum](../partition-equal-subset-sum) (Medium)
### Hints
<details>
<summary>Hint 1</summary>
We can figure out what target each subset must sum to. Then, let's recursively search, where at each call to our function, we choose which of k subsets the next value will join.
</details>
|
Markdown
|
UTF-8
| 1,770 | 2.765625 | 3 |
[] |
no_license
|
#About this repository
The original code was taken from "https://github.com/adeept/Adeept_RFID_Learning_Kit_Python_Code_for_RPi", it is written in Python and intended to be run on Raspberry Pi
As I have bought the kit, and came accross the codes I found some mistakes and incomplete codes and description, so I have made additions and modifications to some files, plus adding circuit wiring and desciption that was missing in the original copy
That's why I will keep their original README content here
#### Adeept Super Starter Kit Python Code for Raspberry Pi
-----------------------------------------------------------------------------
#### About this kit:
This is an RFID learning kit for Raspberry Pi. An RC522 RFID module, some common electronic components and sensors are included. We also prepared an user manual(about 100 pages PDF) for you. Through the learning, you will get a better understanding of RFID and Raspberry Pi, and be able to make fascinating works based on Raspberry Pi.
Now, the kit has been released, you can buy it from our ebay shop:</br>
-----------------------------------------------------------------------------
#### About Adeept:
Adeept is a technical service team of open source software and hardware. Dedicated to applying the Internet and the latest industrial technology in open source area, we strive to provide best hardware support and software service for general makers and electronic enthusiasts around the world. We aim to create infinite possibilities with sharing. No matter what field you are in, we can lead you into the electronic world and bring your ideas into reality.
-----------------------------------------------------------------------------
#### Contact Us:
website:
www.adeept.com
E-mail:
support@adeept.com
|
Java
|
UTF-8
| 570 | 2.9375 | 3 |
[] |
no_license
|
import java.lang.reflect.*;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws IllegalAccessException {
Person person = new Person(123, "张三");
Object proxyInstance = new MyProxy(person).getProxyInstance();
for (Field field : proxyInstance.getClass().getDeclaredFields()) {
field.setAccessible(true);
Object o = field.get(proxyInstance);
System.out.println(field.getName()+":"+o);
}
}
}
|
PHP
|
UTF-8
| 5,331 | 2.578125 | 3 |
[] |
no_license
|
<?php
/**
* Created by PhpStorm.
* User: moroz
* Date: 02.03.19
* Time: 13:37
*/
require __DIR__ . './../vendor/autoload.php';
require __DIR__ . './../core/functions.php';
use Automattic\WooCommerce\Client;
use Automattic\WooCommerce\HttpClient\HttpClientException;
$apiKey = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImE1NDBmNGE1ZjI1NGNmNWFjYzcyYTdlYTE1ZmI5NTI1NzE5YzA2MmI0NDEyNTM2ZjUxMTkwZmU0MjI5ODgyYTE4ZmFiNjM5OTI4MWNhY2NlIn0.eyJhdWQiOiIxIiwianRpIjoiYTU0MGY0YTVmMjU0Y2Y1YWNjNzJhN2VhMTVmYjk1MjU3MTljMDYyYjQ0MTI1MzZmNTExOTBmZTQyMjk4ODJhMThmYWI2Mzk5MjgxY2FjY2UiLCJpYXQiOjE1NDk0MzU5NzMsIm5iZiI6MTU0OTQzNTk3MywiZXhwIjoxNTgwOTcxOTEwLCJzdWIiOiI4MyIsInNjb3BlcyI6W119.OmPbBrx1hn2YWN1jM7IwRJLF_YYLZSDRyl6_u54yp33aACW91CU1zguElipUKljrbsZJ12JyhHMVL0GF1DnUopdlYSrcubHKA3jQ3Vj6ehu6G2hkXObRINX84mzDJtOQedcnGBa1NZiU-cBGwSk3QG799zxIDAnFqwxRG7yGIpbZqC1KOcGrMnad1CxX1b0NTIDq0LFNqY-nSBrwj93uwUjP8J50Bt6AZXtnEvC_y13LbA83AnV2kadbAQluAup2Lh-DVN1Yox0sp4O0cv3jtfgu2KFvRthnS7KvK9a0C9ai7q6IF1px9dLrB2J7km1cSbO-2gTOJ3NkFr91xgE9GJpG_1Q9CpYTv7JuFGPe3vLqS-JgZhYrw47gJ2FUe8v8kbgPWeGY_SueZk9aO5ROlTd60zzvK0Xeuq6nFBsQSfjbQ_VDPwh3kQXJ5BZiosr3JQHf-AARXD_9JAm4fY6br3o4tCqwYZw-syjM_UnZtvcUfm_g4tJI2AEkErm0fzFZnfIrq2X1EWvTqdhk0wRgcpC8CHtBp6FKe7NZktq8rv4C0FD8KhY6nineiwbO0neNOS3W0f8XQoTThHICzfIdHmc5jTYDf0k5aJD_H5yfu0i2EPx9dBXe_Tn6vSpK4K6KCJqthUSwxXbAHrlMCWrV_v9a3FF3NzJxJ7zURs5yQ5s';
$woocommerce = new Client(
'https://armakom.net',
'ck_abfc6cfe0e890d228d8c40494c7e2bd03fa6fae6',
'cs_32c39e1669c8fe8e9232f720e445f6c9d5582ffb',
[
'wp_api' => true,
'version' => 'wc/v3',// 'query_string_auth' => true
]
);
// debugLog(json_encode($woocommerce->get('products/attributes'), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT), 'attributes.txt');
// $attributes = $woocommerce->get('products/attributes');
//
// foreach ($attributes as $attribute) {
// print_r($attribute->slug . PHP_EOL);
// }
function attributeExist($attr, $woocommerce)
{
$attributes = $woocommerce->get('products/attributes');
foreach ($attributes as $attribute) {
// print_r($attribute->slug);
if ($attribute->slug == $attr) {
// print_r($attribute->slug);
return true;
}
// } else {
// return 'false';
// }
// print_r($attribute->slug . PHP_EOL);
}
return false;
}
function getProduct($id, $woocommerce) {
$product = $woocommerce->get('products/' . $id);
var_dump($product);
}
// function getPrice($id, $woocommerce)
// {
// $price = $woocommerce->get('products/' . $id);
// }
function array2File() {
$data = [
'key1' => 'value1',
'key2' => 'value2'
];
$jsonFile = fopen('testArray.json', 'w');
fwrite($jsonFile, json_encode($data, 480));
fclose($jsonFile);
}
/**
* получить id аттрибута или false
* @param $attr
* @param $woocommerce
* @return mixed
*/
function getAttributeId($attr, $attributes)
{
foreach ($attributes as $attribute) {
if ($attribute->name == $attr) {
return $attribute->id;
}
}
return false;
}
/**
* выполнение запроса
* @param $url
* @return mixed
*/
function getCurl($url)
{
$apiKey = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImE1NDBmNGE1ZjI1NGNmNWFjYzcyYTdlYTE1ZmI5NTI1NzE5YzA2MmI0NDEyNTM2ZjUxMTkwZmU0MjI5ODgyYTE4ZmFiNjM5OTI4MWNhY2NlIn0.eyJhdWQiOiIxIiwianRpIjoiYTU0MGY0YTVmMjU0Y2Y1YWNjNzJhN2VhMTVmYjk1MjU3MTljMDYyYjQ0MTI1MzZmNTExOTBmZTQyMjk4ODJhMThmYWI2Mzk5MjgxY2FjY2UiLCJpYXQiOjE1NDk0MzU5NzMsIm5iZiI6MTU0OTQzNTk3MywiZXhwIjoxNTgwOTcxOTEwLCJzdWIiOiI4MyIsInNjb3BlcyI6W119.OmPbBrx1hn2YWN1jM7IwRJLF_YYLZSDRyl6_u54yp33aACW91CU1zguElipUKljrbsZJ12JyhHMVL0GF1DnUopdlYSrcubHKA3jQ3Vj6ehu6G2hkXObRINX84mzDJtOQedcnGBa1NZiU-cBGwSk3QG799zxIDAnFqwxRG7yGIpbZqC1KOcGrMnad1CxX1b0NTIDq0LFNqY-nSBrwj93uwUjP8J50Bt6AZXtnEvC_y13LbA83AnV2kadbAQluAup2Lh-DVN1Yox0sp4O0cv3jtfgu2KFvRthnS7KvK9a0C9ai7q6IF1px9dLrB2J7km1cSbO-2gTOJ3NkFr91xgE9GJpG_1Q9CpYTv7JuFGPe3vLqS-JgZhYrw47gJ2FUe8v8kbgPWeGY_SueZk9aO5ROlTd60zzvK0Xeuq6nFBsQSfjbQ_VDPwh3kQXJ5BZiosr3JQHf-AARXD_9JAm4fY6br3o4tCqwYZw-syjM_UnZtvcUfm_g4tJI2AEkErm0fzFZnfIrq2X1EWvTqdhk0wRgcpC8CHtBp6FKe7NZktq8rv4C0FD8KhY6nineiwbO0neNOS3W0f8XQoTThHICzfIdHmc5jTYDf0k5aJD_H5yfu0i2EPx9dBXe_Tn6vSpK4K6KCJqthUSwxXbAHrlMCWrV_v9a3FF3NzJxJ7zURs5yQ5s';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 60,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Accept: application/json",
"Authorization: Bearer $apiKey"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
return json_decode($response);
}
}
// print_r(attributeExist('pa_nomin-tok', $woocommerce));
// print_r(PHP_EOL);
// array2File();
// getProduct(2311, $woocommerce);
// print_r(array_diff(scandir( './ekf/products'), array('..', '.', 'not')));
// print_r(date('G:i:s')) . PHP_EOL;
// print_r('test', true);
// $wooAttributes = $woocommerce->get('products/attributes');
// $attributeId = getAttributeId('Описание', $wooAttributes);
// var_dump($attributeId);
// print_r($woocommerce->get('products?sku=mcb4763-1-10B-pro'));
// Получаем массив уже импортированных
// $importedProducts = json_decode(file_get_contents($importedProductsFile), true);
$attribute_data = array(
'name' => 'Защитный контакт заземления',
'slug' => 'pa_' . 'Защитный контакт заземления',
'type' => 'select',
'order_by' => 'menu_order',
'has_archives' => true
);
// добавление аттрибутов
// $wc_attribute = $woocommerce->post('products/attributes', $attribute_data);
//
// var_dump($wc_attribute);
// $url = 'https://ekfgroup.com/api/v1/ekf/catalog/prices';
// $param = '?vendorCode=rcbo6-1pn-1B-30-a-av';
// $properties = $this->getCurl($url . $param);
// var_dump($properties->data[0]->properties[3]);
// var_dump(getCurl($url . $param));
// print_r($woocommerce->get('products/categories/704'));
// print_r($woocommerce->get('products/attributes/519'));
// 512 596
$param = ['page' => 7, 'per_page' => 80];
$categories = $woocommerce->get('products/categories', $param);
foreach ($categories as $category) {
$categoryId = $category->id;
print_r($categoryId . PHP_EOL);
print_r($category->name . PHP_EOL);
$productParam = ['category' => $categoryId];
$products = $woocommerce->get('products', $productParam);
// print_r($products[0]->id . PHP_EOL);
$imgSrc = (string)$products[0]->images[0]->src;
// print_r($imgSrc . PHP_EOL);
$data = [
'image' => [
'src' => $imgSrc
]
];
// $data = [];
// $data = [
// 'description' => 'All kinds of clothes.'
// ];
$categoryString = 'products/categories/' . (string)$categoryId;
$woocommerce->put($categoryString, $data);
// print_r($woocommerce->put('products/categories/389', $data));
// break;
}
// for ($i=521; $i<597; $i++) {
// print_r($woocommerce->delete('products/attributes/' . $i));
// }
|
Python
|
UTF-8
| 1,259 | 3.046875 | 3 |
[] |
no_license
|
# encoding:UTF-8
import re
import codecs
from doi_bot import doi2ref
# def re_doi(doi_num):
doi_num = 2
# 保证即使出错文件句柄也会关闭
with open("entry.wiki", "r+", encoding="utf8") as fo:
entry = fo.read()
# 正则参数
doi_pattern = r'({{cite doi\|[ ]*){1}(10\.[^\s\/]+\/[^\s]+)([ ]?}})'
flags = re.I # 大小写不敏感
# 总 DOI 个数核查
pattern = re.compile(doi_pattern, flags)
doi_list = pattern.findall(entry)
re_num = len(doi_list) # 匹配到的 DOI 个数
if(doi_num != re_num):
print("Error: 输入的字符串个数与匹配的DOI个数不符!")
print("共{}个字符串;但匹配到{}个DOI".format(doi_num, re_num))
exit()
# 循环替换:DOI -> <ref>
count = re_num
while (count > 0):
doi_res = re.search(doi_pattern, entry, flags)
print(re_num-count+1)
''' print(doi_res)
print(doi_res.group())
print(doi_res.group(1))
print(doi_res.group(3)) '''
doi = doi_res.group(2)
ref = doi2ref(doi)
entry = re.sub(pattern, ref, entry, 1)
#print(entry)
count = count - 1
# 重置文件指针
fo.seek(0)
fo.write(entry)
print("匹配完成~")
|
Markdown
|
UTF-8
| 1,168 | 2.921875 | 3 |
[] |
no_license
|
Assuming that 3 points.
We can raise an event everyTime the `logError` is called with the `error` parameter.
This way we can separate the manual logging in the text file from the handling of the "counter".
Let's call this event __ERROR_THROW__, and that event should have the __ERROR_DATE__ in UTC.
We will register a handler for __ERROR_THROW__ so every time the event is emitted:
Let's assume that we've some sort of _store_ like 'Redis' (https://redis.io/).
That _store_ will have two variabls there:
- __ERRORS_COLLECTION__ (Date[])
- __APP_NOTIFYING__ (bool)
## Algorythm
- ADD __ERROR_DATE__ TO __ERRORS_COLLECTION__.
- QUERY __APP_NOTIFYING__.
- IF __APP_NOTIFYING__ IS _false_:
- QUERY __ERRORS_COLLECTION__.count() FROM _1 minute_ BEFORE TO __ERROR_DATE__. (*)
- IF COUNT > _10_:
- SET __APP_NOTIFYING__ TO _true_.
- NOTIFY AND WAIT_FOR RESPONSE.
- SET_TIMEOUT _1 minute_ TO:
- SET __APP_NOTIFYING__ to _false_.
- RUN FROM WITH NOW_DATE (*).
_This solution provides_:
- Faster access to the information than reading the file.
- Scalation alternative if the web application starts to run in multiple servers.
|
C++
|
UTF-8
| 310 | 3.625 | 4 |
[] |
no_license
|
#include<iostream>
#include<string>
using namespace std;
int FunctionToDebug(int a, int b) {
int sum = a + b;
return sum;
}
int main(int argc, const char** argv) {
cout<< "Hello World.\n" ;
int sum = FunctionToDebug(2, 3);
cout<< "Sum of 2 + 3 = " << sum << ".\n" << endl;
return 0;
}
|
Java
|
UTF-8
| 14,744 | 2.90625 | 3 |
[] |
no_license
|
package com.warcraftII.player_asset;
//import com.warcraftII.asset.player.PlayerAsset;
import com.warcraftII.position.TilePosition;
import com.warcraftII.position.UnitPosition;
import com.warcraftII.units.Unit;
import java.util.List;
import java.util.Vector;
public class VisibilityMap {
public enum ETileVisibility{
None,
PartialPartial,
Partial,
Visible,
SeenPartial,
Seen
}
public Vector<Vector<ETileVisibility>> gameMap;
public int maxVisibility;
public int totalMapTiles;
public int unseenTiles;
/**
* Constructor, builds visibility gameMap based on input width and height
* Begins with all tiles unseen
*
* @param width The width of the gameMap
* @param height The height of the gameMap
* @param maxVisibility The distance from an asset the user can see
*
*/
public VisibilityMap(int width, int height, int maxVisibility) {
System.out.println("Width " + width);
System.out.println("Height " + height);
System.out.println("MaxVisibility " + maxVisibility);
final int TARGET_WIDTH = width + 2 * maxVisibility;
final int TARGET_HEIGHT = height + 2 * maxVisibility;
this.maxVisibility = maxVisibility;
gameMap = new Vector<Vector<ETileVisibility>>();
for(int i = 0; i < TARGET_HEIGHT; ++i) {
gameMap.add(new Vector<ETileVisibility>(width + 2 * maxVisibility));
for(int j = 0; j < TARGET_WIDTH; ++j) {
gameMap.get(i).add(ETileVisibility.None);
}
}
totalMapTiles = width * height;
unseenTiles = totalMapTiles;
}
/**
* Constructor, copies data members from input visibility gameMap
*
* @param gameMap CVisibilityMap class object that you want to copy
*
*/
public VisibilityMap(final VisibilityMap gameMap){
this.maxVisibility = gameMap.maxVisibility;
this.gameMap = gameMap.gameMap;
this.totalMapTiles = gameMap.totalMapTiles;
this.unseenTiles = gameMap.unseenTiles;
}
/**
* Returns the width of the map, less the added visibility tiles
*
* @return int width of the map
*
*/
public final int getWidth() {
if(gameMap.size() > 0) {
return gameMap.get(0).size() - 2 * maxVisibility;
}
return 0;
}
/**
* Returns the height of the map, less the added visibility tiles
*
* @return int height of the map
*
*/
public final int getHeight() {
return gameMap.size() - 2 * maxVisibility;
}
/**
* Returns the percentage of tiles the user has seen
*
* @param max Usually 100, to convert decimal to percent
*
* @return int percent seen
*
*/
public final int seenPercent(int max) {
return (max * (totalMapTiles - unseenTiles)) / totalMapTiles;
}
public final ETileVisibility TileType(int xIndex, int yIndex) {
if((-maxVisibility > xIndex)||(-maxVisibility > yIndex)){
return ETileVisibility.None;
}
if(gameMap.size() <= yIndex+maxVisibility){
return ETileVisibility.None;
}
if(gameMap.get(yIndex+maxVisibility).size() <= xIndex+maxVisibility){
return ETileVisibility.None;
}
return gameMap.get(yIndex+maxVisibility).get(xIndex+maxVisibility);
}
public void updateAssets(List<StaticAsset> assets) {
for(int i = 0; i < gameMap.size(); ++i) {
for(int j = 0; j < gameMap.get(i).size(); ++j) {
ETileVisibility currentTile = gameMap.get(i).get(j);
if ((ETileVisibility.Visible == currentTile) || (ETileVisibility.Partial == currentTile)) {
gameMap.get(i).set(j, ETileVisibility.Seen);
} else if (ETileVisibility.PartialPartial == currentTile) {
gameMap.get(i).set(j, ETileVisibility.SeenPartial);
}
}
}
for(StaticAsset CurAsset : assets) {
if(CurAsset != null) {
// System.out.println("Altering VisibilityMap with StaticAsset");
TilePosition Anchor = CurAsset.tilePosition();
int Sight = CurAsset.EffectiveSight() + CurAsset.Size()/2;
int SightSquared = Sight * Sight;
// System.out.println("Static is Anchored at: " + Anchor.X() + " " + Anchor.Y());
int oldX = Anchor.X();
int oldY = Anchor.Y();
Anchor.X(Anchor.X() + CurAsset.Size()/2);
Anchor.Y(Anchor.Y() + CurAsset.Size()/2);
//System.out.println("Asset Size " + CurAsset.Size());
//System.out.println("New Anchor: " + Anchor.X() + " " + Anchor.Y());
for(int X = 0; X <= Sight; X++) {
int XSquared = X * X;
int XSquared1 = (X > 0) ? (X - 1) * (X - 1) : 0;
for(int Y = 0; Y <= Sight; Y++){
int YSquared = Y * Y;
int YSquared1 = (Y > 0) ? (Y - 1) * (Y - 1) : 0;
if((XSquared + YSquared) < SightSquared) {
// Visible
// System.out.println("Setting Visible");
if(Anchor.Y() - Y >= 0 && Anchor.X() - X >= 0) {
gameMap.get(Anchor.Y() - Y + maxVisibility).set(Anchor.X() - X + maxVisibility, ETileVisibility.Visible);
gameMap.get(Anchor.Y() - Y + maxVisibility).set(Anchor.X() + X + maxVisibility, ETileVisibility.Visible);
gameMap.get(Anchor.Y() + Y + maxVisibility).set(Anchor.X() - X + maxVisibility, ETileVisibility.Visible);
gameMap.get(Anchor.Y() + Y + maxVisibility).set(Anchor.X() + X + maxVisibility, ETileVisibility.Visible);
}
} else if((XSquared1 + YSquared1) < SightSquared){
// System.out.println("Setting Partial");
// Partial
if(Anchor.Y() - Y >= 0 && Anchor.X() - X >= 0) {
ETileVisibility CurVis = gameMap.get(Anchor.Y() - Y + maxVisibility).get(Anchor.X() - X + maxVisibility);
if (ETileVisibility.Seen == CurVis) {
gameMap.get(Anchor.Y() - Y + maxVisibility).set(Anchor.X() - X + maxVisibility, ETileVisibility.Partial);
} else if ((ETileVisibility.None == CurVis) || (ETileVisibility.SeenPartial == CurVis)) {
gameMap.get(Anchor.Y() - Y + maxVisibility).set(Anchor.X() - X + maxVisibility, ETileVisibility.PartialPartial);
}
CurVis = gameMap.get(Anchor.Y() - Y + maxVisibility).get(Anchor.X() + X + maxVisibility);
if (ETileVisibility.Seen == CurVis) {
gameMap.get(Anchor.Y() - Y + maxVisibility).set(Anchor.X() + X + maxVisibility, ETileVisibility.Partial);
} else if ((ETileVisibility.None == CurVis) || (ETileVisibility.SeenPartial == CurVis)) {
gameMap.get(Anchor.Y() - Y + maxVisibility).set(Anchor.X() + X + maxVisibility, ETileVisibility.PartialPartial);
}
CurVis = gameMap.get(Anchor.Y() + Y + maxVisibility).get(Anchor.X() - X + maxVisibility);
if (ETileVisibility.Seen == CurVis) {
gameMap.get(Anchor.Y() + Y + maxVisibility).set(Anchor.X() - X + maxVisibility, ETileVisibility.Partial);
} else if ((ETileVisibility.None == CurVis) || (ETileVisibility.SeenPartial == CurVis)) {
gameMap.get(Anchor.Y() + Y + maxVisibility).set(Anchor.X() - X + maxVisibility, ETileVisibility.PartialPartial);
}
CurVis = gameMap.get(Anchor.Y() + Y + maxVisibility).get(Anchor.X() + X + maxVisibility);
if (ETileVisibility.Seen == CurVis) {
gameMap.get(Anchor.Y() + Y + maxVisibility).set(Anchor.X() + X + maxVisibility, ETileVisibility.Partial);
} else if ((ETileVisibility.None == CurVis) || (ETileVisibility.SeenPartial == CurVis)) {
gameMap.get(Anchor.Y() + Y + maxVisibility).set(Anchor.X() + X + maxVisibility, ETileVisibility.PartialPartial);
}
}
}
}
}
Anchor.X(oldX);
Anchor.Y(oldY);
}
}
int MinX, MinY, MaxX, MaxY;
MinY = maxVisibility;
MaxY = gameMap.size() - maxVisibility;
MinX = maxVisibility;
MaxX = gameMap.get(0).size() - maxVisibility;
unseenTiles = 0;
for(int Y = MinY; Y < MaxY; Y++){
for(int X = MinX; X < MaxX; X++){
if(ETileVisibility.None == gameMap.get(Y).get(X)){
unseenTiles++;
}
}
}
}
public void updateUnits(List<Unit.IndividualUnit> individualUnitList) {
for(Unit.IndividualUnit unit : individualUnitList) {
if(unit != null) {
//System.out.println("Altering VisibilityMap with IndividualUnit");
TilePosition Anchor = new TilePosition(new UnitPosition((int)(unit.getMidX()), (int)(unit.getMidY())));
// System.out.println("UnitAnchor at: " + Anchor.X() + " " + Anchor.Y());
int Sight = unit.sight;
int SightSquared = Sight * Sight;
//System.out.println("Anchor: " + Anchor.X() + " " + Anchor.Y());
//System.out.println("Sight: " + Sight + " SightSquared " + SightSquared);
//System.out.println("MaxVisibility: " + maxVisibility);
for(int X = 0; X <= Sight; X++) {
int XSquared = X * X;
int XSquared1 = (X > 0) ? (X - 1) * (X - 1) : 0;
for(int Y = 0; Y <= Sight; Y++){
int YSquared = Y * Y;
int YSquared1 = (Y > 0) ? (Y - 1) * (Y - 1) : 0;
if((XSquared + YSquared) < SightSquared) {
// Visible
if(Anchor.Y() - Y >= 0 && Anchor.X() - X >= 0) {
gameMap.get(Anchor.Y() - Y + maxVisibility).set(Anchor.X() - X + maxVisibility, ETileVisibility.Visible);
gameMap.get(Anchor.Y() - Y + maxVisibility).set(Anchor.X() + X + maxVisibility, ETileVisibility.Visible);
gameMap.get(Anchor.Y() + Y + maxVisibility).set(Anchor.X() - X + maxVisibility, ETileVisibility.Visible);
gameMap.get(Anchor.Y() + Y + maxVisibility).set(Anchor.X() + X + maxVisibility, ETileVisibility.Visible);
}
} else if((XSquared1 + YSquared1) < SightSquared){
// Partial
if(Anchor.Y() - Y >= 0 && Anchor.X() - X >= 0) {
ETileVisibility CurVis = gameMap.get(Anchor.Y() - Y + maxVisibility).get(Anchor.X() - X + maxVisibility);
if (ETileVisibility.Seen == CurVis) {
gameMap.get(Anchor.Y() - Y + maxVisibility).set(Anchor.X() - X + maxVisibility, ETileVisibility.Partial);
} else if ((ETileVisibility.None == CurVis) || (ETileVisibility.SeenPartial == CurVis)) {
gameMap.get(Anchor.Y() - Y + maxVisibility).set(Anchor.X() - X + maxVisibility, ETileVisibility.PartialPartial);
}
CurVis = gameMap.get(Anchor.Y() - Y + maxVisibility).get(Anchor.X() + X + maxVisibility);
if (ETileVisibility.Seen == CurVis) {
gameMap.get(Anchor.Y() - Y + maxVisibility).set(Anchor.X() + X + maxVisibility, ETileVisibility.Partial);
} else if ((ETileVisibility.None == CurVis) || (ETileVisibility.SeenPartial == CurVis)) {
gameMap.get(Anchor.Y() - Y + maxVisibility).set(Anchor.X() + X + maxVisibility, ETileVisibility.PartialPartial);
}
CurVis = gameMap.get(Anchor.Y() + Y + maxVisibility).get(Anchor.X() - X + maxVisibility);
if (ETileVisibility.Seen == CurVis) {
gameMap.get(Anchor.Y() + Y + maxVisibility).set(Anchor.X() - X + maxVisibility, ETileVisibility.Partial);
} else if ((ETileVisibility.None == CurVis) || (ETileVisibility.SeenPartial == CurVis)) {
gameMap.get(Anchor.Y() + Y + maxVisibility).set(Anchor.X() - X + maxVisibility, ETileVisibility.PartialPartial);
}
CurVis = gameMap.get(Anchor.Y() + Y + maxVisibility).get(Anchor.X() + X + maxVisibility);
if (ETileVisibility.Seen == CurVis) {
gameMap.get(Anchor.Y() + Y + maxVisibility).set(Anchor.X() + X + maxVisibility, ETileVisibility.Partial);
} else if ((ETileVisibility.None == CurVis) || (ETileVisibility.SeenPartial == CurVis)) {
gameMap.get(Anchor.Y() + Y + maxVisibility).set(Anchor.X() + X + maxVisibility, ETileVisibility.PartialPartial);
}
}
}
}
}
}
}
int MinX, MinY, MaxX, MaxY;
MinY = maxVisibility;
MaxY = gameMap.size() - maxVisibility;
MinX = maxVisibility;
MaxX = gameMap.get(0).size() - maxVisibility;
unseenTiles = 0;
for(int Y = MinY; Y < MaxY; Y++){
for(int X = MinX; X < MaxX; X++){
if(ETileVisibility.None == gameMap.get(Y).get(X)){
unseenTiles++;
}
}
}
}
}
|
Java
|
UTF-8
| 3,425 | 2.6875 | 3 |
[
"WTFPL"
] |
permissive
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package spm;
import java.text.SimpleDateFormat;
import org.w3c.dom.Element;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
/**
*
* @author Alex
*/
public class Entry {
public final int id;
static public byte[] key = null;
private String site;
private String login;
private String pass;
private String comment;
private String date;
public Entry(final String site, final String login, final String pass, final String comment) {
id = 0;
this.site = site;
this.login = login;
this.pass = Crypto.encode(key, pass);
this.comment = comment;
updDate();
}
public Entry(Node node) {
this((Element)node);
}
public Entry(Element node) {
this(node, 0);
}
public Entry(Element node, int id) {
this.id = id;
site = node.getElementsByTagName("site").item(0).getTextContent();
site = Crypto.decode(key, site);
login = node.getElementsByTagName("login").item(0).getTextContent();
login = Crypto.decode(key, login);
pass = node.getElementsByTagName("pass").item(0).getTextContent();
comment = node.getElementsByTagName("comment").item(0).getTextContent();
comment = Crypto.decode(key, comment);
date = node.getElementsByTagName("date").item(0).getTextContent();
}
public String getSite() {return site;}
public String getLogin() {return login;}
public String getComment() {return comment;}
public String getDate() {return date;}
static private void add(Element el, final String tag, final String text) {
Element tmp = el.getOwnerDocument().createElement(tag);
tmp.setTextContent(text);
el.appendChild(tmp);
}
public Element toElement(Document doc, String name) {
Element el = doc.createElement(name);
add(el, "site", Crypto.encode(key, site));
add(el, "login", Crypto.encode(key, login));
add(el, "pass", pass);
add(el, "comment", Crypto.encode(key, comment));
add(el, "date", date);
return el;
}
public Element toElement(Document doc, String name, byte[] newKey) {
Element el = doc.createElement(name);
add(el, "site", Crypto.encode(newKey, site));
add(el, "login", Crypto.encode(newKey, login));
add(el, "pass", Crypto.encode(newKey, Crypto.decode(key, pass)));
add(el, "comment", Crypto.encode(newKey, comment));
add(el, "date", date);
return el;
}
public Boolean like(final String str) {
return site.contains(str) || login.contains(str) || comment.contains(str);
}
public String[] toArray() {
return new String[] {site, login, comment, date};
}
public String name() {
return site + " (" + login + ")";
}
public String getPassword() {
return Crypto.decode(key, pass);
}
private void updDate() {
SimpleDateFormat fmt = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
date = fmt.format(System.currentTimeMillis());
}
}
|
C
|
UTF-8
| 336 | 3.46875 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <conio.h>
void main()
{
int n, c;
long int f = 1;
printf("\n Enter the number");
scanf("%d", &n);
if (n < 0)
goto end;
for (c = 1; c <= n; c++)
f = f * c;
printf("\n factorial = %d ", f);
end:
getch();
}
/*
output:
Enter the number5
factorial = 120
*/
|
C++
|
UTF-8
| 935 | 2.859375 | 3 |
[] |
no_license
|
void createZarray(string str, int Z[])
{
int n = str.length();
int L, R, k;
L = R = 0;
for (int i = 1; i < n; ++i)
{
if (i > R)
{
L = R = i;
while (R < n && str[R - L] == str[R])
R++;
Z[i] = R - L;
R--;
}
else
{
k = i - L;
if (Z[k] < R - i + 1)
Z[i] = Z[k];
else
{
L = i;
while (R < n && str[R - L] == str[R])
R++;
Z[i] = R - L;
R--;
}
}
}
}
void zAlgorithm(string text, string pattern)
{
string str = pattern + "$" + text;
int len = str.length();
int Z[len];
createZarray(str, Z);
for (int i = 0; i < len; ++i)
{
if (Z[i] == pattern.length())
cout << (i - pattern.length() - 1) << "\t";
}
}
|
JavaScript
|
UTF-8
| 2,958 | 2.546875 | 3 |
[
"Apache-2.0"
] |
permissive
|
// Copyright 2010 Google Inc. All Rights Reserved.
// Author: jacobsa@google.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var internalExpectThat = gjstest.internal.expectThat;
function ExpectThatTest() {
this.predicate_ = gjstest.createMockFunction();
this.matcher_ = new gjstest.Matcher('desc', 'negative desc', this.predicate_);
this.stringify_ = gjstest.createMockFunction();
this.reportFailure_ = gjstest.createMockFunction();
// Ignore calls to stringify by default.
expectCall(this.stringify_)(_)
.willRepeatedly(returnWith(''));
}
registerTestSuite(ExpectThatTest);
ExpectThatTest.prototype.CallsMatcher = function() {
var obj = {};
expectCall(this.predicate_)(obj)
.willOnce(returnWith(true));
internalExpectThat(obj, this.matcher_, this.stringify_, this.reportFailure_);
};
ExpectThatTest.prototype.MatcherSaysYes = function() {
var obj = {};
expectCall(this.predicate_)(_)
.willOnce(returnWith(true));
expectCall(this.reportFailure_)(_)
.times(0);
internalExpectThat(obj, this.matcher_, this.stringify_, this.reportFailure_);
};
ExpectThatTest.prototype.MatcherSaysNo = function() {
var obj = {};
expectCall(this.predicate_)(_)
.willOnce(returnWith(false));
expectCall(this.stringify_)(obj)
.willOnce(returnWith('burrito'));
expectCall(this.reportFailure_)('Expected: desc\nActual: burrito');
internalExpectThat(obj, this.matcher_, this.stringify_, this.reportFailure_);
};
ExpectThatTest.prototype.MatcherReturnsString = function() {
var obj = {};
expectCall(this.predicate_)(_)
.willOnce(returnWith('which has too few tacos'));
expectCall(this.stringify_)(obj)
.willOnce(returnWith('burrito'));
expectCall(this.reportFailure_)(
'Expected: desc\nActual: burrito, which has too few tacos');
internalExpectThat(obj, this.matcher_, this.stringify_, this.reportFailure_);
};
ExpectThatTest.prototype.MatcherReturnsStringAndUserGivesErrorMessage =
function() {
var obj = {};
expectCall(this.predicate_)(_)
.willOnce(returnWith('which has too few tacos'));
expectCall(this.stringify_)(obj)
.willOnce(returnWith('burrito'));
expectCall(this.reportFailure_)(
'Expected: desc\n' +
'Actual: burrito, which has too few tacos\n' +
'Grande Failure');
internalExpectThat(
obj,
this.matcher_,
this.stringify_,
this.reportFailure_,
'Grande Failure');
};
|
C++
|
UTF-8
| 442 | 2.65625 | 3 |
[] |
no_license
|
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn=15;
int t, ans;
char str[maxn];
int main()
{
scanf("%d", &t);
while(t--){
scanf("%s", &str);
if(strlen(str)==5)ans=3;
else{
ans=1;
if(str[1]=='w'&&str[2]=='o'||(str[0]=='t'&&(str[1]=='w'||str[2]=='o')))ans=2;
}
printf("%d\n", ans);
}
return 0;
}
|
Python
|
UTF-8
| 961 | 2.84375 | 3 |
[] |
no_license
|
"""
Define classes for an accountability.
"""
from swarm_intelligence_app.models import db
class Accountability(db.Model):
"""
Define a mapping to the database for an accountability.
"""
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(255), nullable=False)
role_id = db.Column(db.Integer, db.ForeignKey('role.id'), nullable=False)
def __init__(self, title, role_id):
"""
Initialize an accountability.
"""
self.title = title
self.role_id = role_id
def __repr__(self):
"""
Return a readable representation of an accountability.
"""
return '<Accountability %r>' % self.id
@property
def serialize(self):
"""
Return a JSON-encoded representation of an accountability.
"""
return {
'id': self.id,
'title': self.title,
'role_id': self.role_id
}
|
JavaScript
|
UTF-8
| 791 | 2.734375 | 3 |
[] |
no_license
|
(function () {
'use strict';
window.onload = function () {
var form = document.forms.contestForm,
input = form.K,
output = form.out,
indicator = document.getElementById('indicator'),
worker;
worker = new Worker('contestWebWorker.js?' + Math.random());
worker.onmessage = function (e) {
if (e.data === 'done') {
indicator.hidden = true;
output.innerHTML += 'Done. Please see the result in the browser console (Ctrl+Shift+I).';
} else {
console.log(e.data);
}
};
form.addEventListener('submit', function (e) {
e.preventDefault();
output.innerHTML = '';
indicator.hidden = false;
console.clear();
worker.postMessage(input.value);
});
}
})();
|
PHP
|
UTF-8
| 963 | 2.546875 | 3 |
[] |
no_license
|
<?php
require_once 'PHP/dbconfig.php';
include 'header.php';
?>
<div class="container">
<div id="tools-wrapper">
<h1 class = "title-line-style">Total Protein Intake</h1>
<div id = "upper-part">
<?php
$servername="localhost";
$username="root";
$password="";
$dbname="snc";
$conn=mysqli_connect($servername,$username,$password,$dbname);
if(!$conn)
{
die("Connection Failed: ". mysqli_connect_error());
}
$sql="select name,protein from foods";
$result=mysqli_query($conn,$sql);
$pcount=0;
$x=0;
foreach($_POST['Quantity'] as $q)
{
$arr[$x]=$q;
$x++;
}
$x=0;
if(mysqli_num_rows($result) > 0)
{
while($row =mysqli_fetch_assoc($result))
{
$food=$row["name"];
$protein=$row["protein"];
$co=0;
foreach($_POST['Food'] as $in)
{
if($food==$in)
{
$pcount=$pcount+($protein*$arr[$x]);
$x++;
}
$co++;
}
}
}
echo "$pcount";
?>
</div>
</div>
</div>
<?php
include 'footer.php'; // FOOTER
?>
|
Markdown
|
UTF-8
| 356 | 3.125 | 3 |
[] |
no_license
|
# Level 0
> The goal of this level is for you to log into the game using SSH. The host to which you need to connect is bandit.labs.overthewire.org, on port 2220. The username is bandit0 and the password is bandit0
To log into the game, simply run this command `ssh bandit0@bandit.labs.overthewire.org -p 2220` and input the password when prompted.
|
JavaScript
|
UTF-8
| 387 | 2.5625 | 3 |
[] |
no_license
|
const ACTION_TYPES = {
SET_IS_LOADING: 'SET_IS_LOADING',
};
export const setIsLoading = payload => ({
type: ACTION_TYPES.SET_IS_LOADING,
payload,
});
const isLoadingReducer = (isLoading = false, action) => {
switch (action.type) {
case ACTION_TYPES.SET_IS_LOADING:
return action.payload;
default:
return isLoading;
}
};
export default isLoadingReducer;
|
JavaScript
|
UTF-8
| 2,994 | 4.28125 | 4 |
[] |
no_license
|
// STEP 1 understanding the problem
//
// 1. restate the question back in my own words
// 2. what are the inputs to the problem
// 3. what are the outputs that are to be returned
// 4. can the outputs be determined from the inputs
// 5. how should i label important pieces of data that are part of the problem
// STEP 2 explore examples
//coming up with examples can help you understand the problem better
// examples also provide sanity checks that your eventual solution works how it should
//1. write down two or three simple examples
//2. progress to more complex examples
//3. examples with empty inputs
//4. examples with invalid inputs
//***** write a function which takes in a string and returns counts of each character in the string
//1.
// charCount("aaaa"); // {a:4}
//2.
// charCount("Hello, my phone number is")
//do we need to seperate upper and lower case??
//3.
// charCount("")
//what do we want to return?
//4.
// charCount(null)
//how would we want to handle this??
// STEP 3 break it down
// explicitly write out the most individual steps needed
// reg. above function
//return object with count for each character present
//str = "Your PIN number is 1234"
// function charCount(str){
// //do something
// return result;
// }
// function charCount(str){
// make object to return at end
// loop over string
// return object at end;
// }
// function charCount(str){
// make object to return at end
// loop over string for each character
//if char is num/letter key in object, add 1 to count
// if char is num/letter not present, add and set val to 1
// if char is anything else, !.#? etc do nothing
// return object at end;
// }
// STEP 4 solve / simplify
// if you cant solve the full problem, solve a simpler version of it
// this will also give insight into the harder part of the problem
// to SIMPLIFY:
// find the core difficulty of the problem
// temporarily ignore it
// write a simplified solution
// incorporate the difficulty back in
function charCount(str){
// make object to return at end
var result = {};
// loop over string for each character
for (var i = 0; i < str.length; i++){
var char = str[i].toLowerCase();
if(result[char] > 0) {
//if char is num/letter key in object, add 1 to count
result[char]++;
} else {
// if char is num/letter not present, add and set val to 1
result[char] = 1;
}
// return result;
}
console.log(result);
}
// if char is anything else, !.#? etc do nothing
// return object at end;
// }
charCount("Hello World")
////
///// LOOK BACK & REFACTOR
/*
- can you check result?
- can you get the result differently?
- can you understand and read it at a glance?
- can the result or method be reused?
- improve performance?
- other ways to refactor
- how have others solved it?
- doesn't necessarily have to be refactored, but good idea to go over and discuss solution with interviewer
*/
//
|
Markdown
|
UTF-8
| 1,070 | 2.578125 | 3 |
[] |
no_license
|
# Collection of Dockerfile
## Debian stack
I used debian as base for all my other application following thhis schema:
<img src="https://github.com/Seba0691/Dockerfiles/raw/master/docker_arch.png">
- **Debian custom** : provides a common layer where the most common utility are installed
- **Python stack** : provides a layer where all the python environment is installed along with utilities such as pip
- **Node stack** : provides a layer where all the node environment is installed along with the most common utilities such as npm and bower
- **Chrisper** : images containing the application [Chrisper](https://github.com/invernizzi/Chrisper)
## Jupyter Notebooks
Images that builds my [Jupyter Notebook](https://hub.docker.com/r/phate/jupyter_notebook_custom/) environment installing and activating my favorites extensions.
## Kali linux
A kali linux images customized with the tools I use the most.
## Realms-wiki-dev
Images that creates an environment setup to test and develop a custom version of [Realms-wiki](https://github.com/scragg0x/realms-wiki)
|
Ruby
|
UTF-8
| 1,400 | 3.46875 | 3 |
[] |
no_license
|
class Action
def place(command)
_command, x, y, f = command.tr(',', ' ').split
Position.new(x.to_i, y.to_i, f)
end
def move(position)
y = position.y
x = position.x
f = position.f
y += 1 if f.match?('NORTH')
x += 1 if f.match?('EAST')
y -= 1 if f.match?('SOUTH')
x -= 1 if f.match?('WEST')
Position.new(x, y, f)
end
def left(position)
Position.new(position.x, position.y, prev_option(position.f))
end
def right(position)
Position.new(position.x, position.y, next_option(position.f))
end
def report(position)
message = "Output: #{position.x},#{position.y},#{position.f} \n"
$stdout.print message
position
end
private
OPTIONS = %w[WEST NORTH EAST SOUTH].freeze
def prev_option(direction)
return unless OPTIONS.include?(direction)
return OPTIONS.last if direction == OPTIONS.first
i = OPTIONS.index { |e| e == direction }
i -= 1
OPTIONS.fetch(i)
end
def next_option(direction)
return unless OPTIONS.include?(direction)
return OPTIONS.first if direction == OPTIONS.last
i = OPTIONS.index { |e| e == direction }
i += 1
OPTIONS.fetch(i)
end
end
|
Ruby
|
UTF-8
| 208 | 2.984375 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def key_for_min_value(name_hash)
if name_hash != {}
m = 100000
msg=""
name_hash.each do |k,v|
if m > v
m = v
msg = k
end
end
else
return nil
end
msg
end
|
Shell
|
UTF-8
| 303 | 3.453125 | 3 |
[] |
permissive
|
#!/bin/sh
set -e
MAKE=${MAKE:-make}
subdir="$1"
tarball="$2"
tmpdir=$(mktemp -d)
trap "rm -rf '$tmpdir'" EXIT
tar xf "$tarball" -C "$tmpdir"
cd "$tmpdir/$subdir"
if [ -n "${CONFIG_PATH}" ]; then
echo "Setting config to ${CONFIG_PATH}"
cp "${CONFIG_PATH}" test/resources/config.json
fi
$MAKE test
|
Shell
|
UTF-8
| 974 | 2.859375 | 3 |
[] |
no_license
|
rm output.csv
#Remove Headers if you dont need
echo "Cluster","Namespace","Deployment Count","Pod Count" >> output.csv
for cluster in $(python3 queryinstana.py label FROM KubernetesCluster where 'entity.selfType:kubernetesCluster' )
do
for namespace in $(python3 queryinstana.py label FROM KubernetesNamespace where entity.kubernetes.cluster.label:$cluster )
do
for deployment in $(python3 queryinstana.py count FROM KubernetesDeployment where 'entity.kubernetes.cluster.label:'$cluster' AND entity.kubernetes.namespace:'$namespace )
do
for pod in $(python3 queryinstana.py count FROM KubernetesPod where 'entity.kubernetes.cluster.label:'$cluster' AND entity.kubernetes.namespace:'$namespace)
do
#Output everything
echo "$cluster","$namespace","$deployment","$pod"
echo "$cluster","$namespace","$deployment","$pod" >> output.csv
done
done
done
done
|
C
|
UTF-8
| 1,644 | 2.703125 | 3 |
[] |
no_license
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* terminates2.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mdonchen <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/11/15 12:38:05 by mdonchen #+# #+# */
/* Updated: 2019/11/15 12:38:14 by mdonchen ### ########.fr */
/* */
/* ************************************************************************** */
#include "asm.h"
void arg_type_err(t_op *op, int i, t_content *content)
{
ft_putstr_fd("Invalid type of parameter #", 2);
ft_putnbr_fd(i + 1, 2);
ft_putstr_fd(" for instruction \"", 2);
ft_putstr_fd(op->op_name, 2);
ft_putstr_fd("\" at [", 2);
ft_putnbr_fd(content->line, 2);
ft_putstr_fd(": ", 2);
ft_putnbr_fd(content->c + 1, 2);
ft_putstr_fd("]\n", 2);
exit(1);
}
void lab_err(t_label *lab)
{
t_mlabel *mlab;
ft_putstr_fd("Undeclared label \"", 2);
ft_putstr_fd(lab->name, 2);
ft_putstr_fd("\" is mentioned at: \n", 2);
mlab = lab->mlabels;
while (mlab)
{
ft_putstr_fd("\t- [", 2);
ft_putnbr_fd(mlab->line, 2);
ft_putstr_fd(": ", 2);
ft_putnbr_fd(mlab->c + 1, 2);
ft_putstr_fd("]\n", 2);
mlab = mlab->next;
}
exit(1);
}
|
PHP
|
UTF-8
| 1,923 | 2.78125 | 3 |
[] |
no_license
|
<?php
/**
* @author JKetelaar
*/
namespace Parabot\BDN\BotBundle\Service\Library\TeamCity\Entity;
use Parabot\BDN\BotBundle\Service\Library\TeamCity\TeamCityPoint;
use Symfony\Component\Serializer\Annotation\Groups;
class TeamCityBuild implements TeamCityEntity {
/**
* @Groups({"default"})
*
* @var int
*/
private $id;
/**
* @Groups({"default"})
*
* @var string
*/
private $status;
/**
* @Groups({"default"})
*
* @var string
*/
private $state;
/**
* TeamCityBuild constructor.
*/
public function __construct() { }
/**
* @return TeamCityPoint
*/
public static function getAPIPoint() {
return TeamCityPoint::BUILDS();
}
/**
* @param $result
*
* @return TeamCityBuild[]
*/
public static function parseResponse($result) {
$builds = [];
if(isset($result->build)) {
foreach($result->build as $build) {
$b = new TeamCityBuild();
$b->setId($build->id);
$b->setStatus($build->status);
$b->setState($build->state);
$builds[] = $b;
}
}
return $builds;
}
/**
* @return int
*/
public function getId() {
return $this->id;
}
/**
* @param int $id
*/
public function setId($id) {
$this->id = $id;
}
/**
* @return string
*/
public function getStatus() {
return $this->status;
}
/**
* @param string $status
*/
public function setStatus($status) {
$this->status = $status;
}
/**
* @return string
*/
public function getState() {
return $this->state;
}
/**
* @param string $state
*/
public function setState($state) {
$this->state = $state;
}
}
|
Java
|
UTF-8
| 12,860 | 1.679688 | 2 |
[] |
no_license
|
/* */ package cn.mopon.scenic.gateway.remote;
/* */ // this is hostA changed HostA pust 2
/* */ // this is hostA changed new hostB
// HOst B Add again
// HOST B ADD 2
/* */ import cn.mopon.scenic.gateway.constant.ResponseConstants;
/* */ import cn.mopon.scenic.gateway.constant.TransactionNo;
/* */ import cn.mopon.scenic.gateway.service.IWSTicketService;
/* */ import cn.mopon.scenic.gateway.service.impl.WSTicketServiceImpl;
/* */ import cn.mopon.scenic.gateway.util.Cache;
/* */ import cn.mopon.scenic.gateway.util.TypeFormat;
/* */ import fr.irec.www.webserviceac.CheckTicket;
/* */ import fr.irec.www.webserviceac.CheckTicketResponse;
/* */ import fr.irec.www.webserviceac.Passage;
/* */ import fr.irec.www.webserviceac.PassageResponse;
/* */ import fr.irec.www.webserviceac.Response;
/* */ import fr.irec.www.webserviceac.ResponseCode;
/* */ import fr.irec.www.webserviceac.TimeoutTicket;
/* */ import java.util.Date;
/* */ import java.util.HashMap;
/* */ import java.util.Map;
/* */ import java.util.UUID;
/* */ import org.slf4j.Logger;
/* */ import org.slf4j.LoggerFactory;
/* */
/* */ public class OffLineWsCall extends RemoteServer
/* */ {
/* 36 */ private static final Logger logger = LoggerFactory.getLogger(OffLineWsCall.class);
/* */
/* 38 */ private static volatile OffLineWsCall offLineWsCall = null;
/* */
/* 40 */ private IWSTicketService wsTicketService = new WSTicketServiceImpl();
/* */
/* */ public static OffLineWsCall getSingleton()
/* */ {
/* 56 */ if (offLineWsCall == null) {
/* 57 */ synchronized (OffLineWsCall.class) {
/* 58 */ if (offLineWsCall == null) {
/* 59 */ offLineWsCall = new OffLineWsCall();
/* */ }
/* */ }
/* */ }
/* 63 */ return offLineWsCall;
/* */ }
/* */
/* */ private String remoteCallConfirm(String packet, String voucherValue)
/* */ {
/* 76 */ logger.info("IREC票确认:" + voucherValue);
/* */
/* 79 */ int nbEntry = 0;
/* 80 */ int nbEntryRemain = 0;
/* 81 */ String cvtResult = null;
/* 82 */ String deviceID = getNodeValue(packet, "DeviceNo");
/* 83 */ String seqID = getNodeValue(packet, "SequenceId");
/* 84 */ String codeControlPoint = Cache.getIrecCodeByEqNo(deviceID);
/* */ try {
/* 86 */ nbEntry = Integer.valueOf(getNodeValue(packet, "PassNumber")).intValue();
/* 87 */ nbEntryRemain = Integer.valueOf(getNodeValue(packet, "CanPassNumber")).intValue();
/* */ } catch (Exception e) {
/* 89 */ logger.error("offline wsCall confirm interface, the parameter PassNumber or CanPassNumber has error ==> " + e.getMessage(), e);
/* 90 */ Map params = new HashMap();
/* 91 */ params.put("${StatusCode}", "1");
/* 92 */ params.put("${Message}", "PassNumber or CanPassNumber 参数错误");
/* 93 */ return cvt2FailProtoclXml(params);
/* */ }
/* 95 */ long begin = System.currentTimeMillis();
/* 96 */ if (nbEntry > 0) {
/* 97 */ Passage passage = new Passage();
/* 98 */ passage.setBarCodeTicket(voucherValue);
/* 99 */ passage.setEntryDateTimeString(TypeFormat.getDatetimeline());
/* 100 */ passage.setIsExit(false);
/* 101 */ passage.setNbEntry(nbEntry);
/* */
/* 103 */ passage.setNbEntryRemain(nbEntryRemain);
/* 104 */ passage.setCodeControlPoint(codeControlPoint);
/* */
/* 106 */ passage.setTransactionId(UUID.randomUUID().toString());
/* */
/* 109 */ logger.info("调用Irec票去人消息参数: 通过人数:" + passage.getNbEntry() + ", 剩余可通过人数:" +
/* 110 */ passage.getNbEntryRemain());
/* */
/* 112 */ PassageResponse response = this.wsTicketService.passage(passage);
/* */
/* 114 */ logger.info("IREC票确认返回信息:" + response.getPassageResult().getMessage());
/* */
/* 116 */ logger.info("<<SPEND TIME>>调用IREC系统确认操作, 流水号: " + seqID + ", 用时: " + (System.currentTimeMillis() - begin));
/* */
/* 118 */ cvtResult = cvt2SuccessConfirmProtoclXml(response, seqID, voucherValue);
/* */ }
/* */ else {
/* 121 */ logger.error("调用Irec超时确认包开始:, parameter barCodeTicket: " + voucherValue + ", CodeControlPoint: " +
/* 122 */ codeControlPoint);
/* */
/* 124 */ TimeoutTicket ticket = new TimeoutTicket();
/* */
/* 128 */ ticket.setBarCodeTicket(voucherValue);
/* 129 */ ticket.setCodeControlPoint(codeControlPoint);
/* 130 */ boolean timeOutNotice = this.wsTicketService.timeOutTicket(ticket);
/* */
/* 132 */ logger.error(" IREC票确认超时确认包,【result】: " + timeOutNotice);
/* */
/* 134 */ logger.error("<<SPEND TIME>>调用IREC系统确认操作返回异常, 流水号: " + seqID + ", 用时:" + (System.currentTimeMillis() - begin));
/* */
/* 136 */ Map params = new HashMap();
/* 137 */ params.put("${StatusCode}", "1");
/* 138 */ params.put("${Message}", "通过人数错误, 不能小于1");
/* 139 */ cvtResult = cvt2FailProtoclXml(params);
/* */ }
/* */
/* 143 */ return cvtResult;
/* */ }
/* */
/* */ public byte[] remoteCall(String packet, String mediaValue, String transactionCode)
/* */ {
/* 150 */ String cvtResult = null;
/* 151 */ if (transactionCode.equals(TransactionNo.V_GATEWAY_CHECK.name()))
/* 152 */ cvtResult = remoteCallConsume(packet, mediaValue);
/* 153 */ else if (transactionCode.equals(TransactionNo.V_GATEWAY_CONFIRM.name())) {
/* 154 */ cvtResult = remoteCallConfirm(packet, mediaValue);
/* */ }
/* 156 */ return cvtResult.getBytes();
/* */ }
/* */
/* */ private String remoteCallConsume(String packet, String mediaValue)
/* */ {
/* 168 */ logger.info("验证IREC系统产生的门票");
/* */
/* 170 */ String deviceID = getNodeValue(packet, "DeviceNo");
/* 171 */ String seqID = getNodeValue(packet, "SequenceId");
/* 172 */ long beginTime = System.currentTimeMillis();
/* 173 */ String trid = UUID.randomUUID().toString();
/* 174 */ CheckTicket ct = new CheckTicket();
/* 175 */ ct.setCodeControlPoint(Cache.getIrecCodeByEqNo(deviceID));
/* 176 */ ct.setBarCodeTicket(mediaValue);
/* 177 */ ct.setEntryDateTimeString(TypeFormat.getDatetimeline());
/* 178 */ ct.setIsExit(false);
/* 179 */ ct.setTransactionId(trid);
/* 180 */ CheckTicketResponse irecResponse = this.wsTicketService.checkTicket(ct);
/* 181 */ logger.info(irecResponse.toString());
/* 182 */ ResponseCode code = irecResponse.getCheckTicketResult().getCode();
/* 183 */ String message = irecResponse.getCheckTicketResult().getMessage();
/* 184 */ int entryCount = irecResponse.getCheckTicketResult().getEntryCount();
/* 185 */ String ticketBarcode = irecResponse.getCheckTicketResult().getTicketBarcode();
/* 186 */ int remainingEntry = irecResponse.getCheckTicketResult().getRemainingEntry();
/* 187 */ String reContent = "code:" + code.getValue() + "\n" +
/* 188 */ "message:" + message + "\n" +
/* 189 */ "entryCount:" + entryCount + "\n" +
/* 190 */ "ticketBarcode:" + ticketBarcode + "\n" +
/* 191 */ "remainingEntry:" + remainingEntry + "\n";
/* 192 */ String cvtResult = null;
/* 193 */ if ((code.getValue().equals(ResponseCode._TicketValid)) ||
/* 194 */ (code.getValue().equals(ResponseCode._TicketValidReentry)) ||
/* 195 */ (code.getValue().equals(ResponseCode._TicketValidOffline))) {
/* 196 */ logger.info("IREC验证票成功:" + reContent);
/* */
/* 207 */ cvtResult = cvt2SuccessConsumeProtoclXml(irecResponse, seqID, mediaValue);
/* */ } else {
/* 209 */ logger.error("IREC验证票失败:" + reContent);
/* */
/* 212 */ Map params = new HashMap();
/* 213 */ params.put("${StatusCode}", "1");
/* 214 */ params.put("${Message}", message);
/* 215 */ cvtResult = cvt2FailProtoclXml(params);
/* */ }
/* */
/* 218 */ logger.info("<<SPEND TIME>>调用IREC系统验票操作, 流水号: " + seqID + ", 用时: " + (System.currentTimeMillis() - beginTime));
/* 219 */ return cvtResult;
/* */ }
/* */
/* */ private String cvt2SuccessConfirmProtoclXml(PassageResponse resp, String seqId, String mediaValue)
/* */ {
/* 231 */ Map params = new HashMap();
/* 232 */ params.put("${VoucherValue}", mediaValue);
/* 233 */ params.put("${CanPassNumber}", resp.getPassageResult().getRemainingEntry());
/* 234 */ int hadPassNumber = resp.getPassageResult().getEntryCount() - resp.getPassageResult().getRemainingEntry();
/* 235 */ if (hadPassNumber < 0) {
/* 236 */ logger.warn("offline wsCall, the entryCount is less than remainingCount, Please check : " + resp.getPassageResult().getTicketBarcode());
/* */ }
/* 238 */ params.put("${HadPassNumber}", hadPassNumber);
/* 239 */ String xml = replaceTemplate(ResponseConstants.RESPONSE_GATES_CONSUME_CONFIRM_BODY, params);
/* */
/* 242 */ params = new HashMap();
/* 243 */ params.put("${TimeStamp}", TypeFormat.getCurrentTime());
/* 244 */ params.put("${Body}", xml);
/* 245 */ params.put("${StatusCode}", "200");
/* 246 */ params.put("${Message}", "成功");
/* 247 */ params.put("${SequenceId}", seqId);
/* */
/* 249 */ xml = replaceTemplate("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Trade><Head><Version>1.0</Version><TimeStamp>${TimeStamp}</TimeStamp><SequenceId>${SequenceId}</SequenceId><StatusCode>${StatusCode}</StatusCode><Message>${Message}</Message></Head><Body>${Body}</Body></Trade>", params);
/* */
/* 251 */ return xml;
/* */ }
/* */
/* */ private String cvt2SuccessConsumeProtoclXml(CheckTicketResponse resp, String seqId, String mediaValue)
/* */ {
/* 265 */ Map params = new HashMap();
/* 266 */ params.put("${DisplayMessage}", "验证成功,请通过!");
/* 267 */ params.put("${AllowEnterNumber}", resp.getCheckTicketResult().getEntryCount());
/* 268 */ params.put("${NeedAdminSwipe}", "1");
/* 269 */ params.put("${HadPassNumber}", resp.getCheckTicketResult().getRemainingEntry());
/* 270 */ int canPassNumber = resp.getCheckTicketResult().getEntryCount() - resp.getCheckTicketResult().getRemainingEntry();
/* 271 */ if (canPassNumber < 0) {
/* 272 */ logger.warn("offline wsCall, the entryCount is less than remainingCount, Please check : " + resp.getCheckTicketResult().getTicketBarcode());
/* */ }
/* 274 */ params.put("${CanPassNumber}", canPassNumber);
/* */
/* 278 */ params.put("${VoucherValue}", mediaValue);
/* 279 */ params.put("${MediaValue}", mediaValue);
/* 280 */ params.put("${MediaType}", "1");
/* */
/* 282 */ params.put("${TransactionTime}", TypeFormat.formatDate(new Date()));
/* */
/* 284 */ String xml = replaceTemplate(ResponseConstants.RESPONSE_GATES_CONSUME_BODY, params);
/* */
/* 286 */ params = new HashMap();
/* 287 */ params.put("${TimeStamp}", TypeFormat.getCurrentTime());
/* 288 */ params.put("${Body}", xml);
/* 289 */ params.put("${StatusCode}", "200");
/* 290 */ params.put("${SequenceId}", seqId);
/* 291 */ params.put("${Message}", "成功");
/* */
/* 293 */ xml = replaceTemplate("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Trade><Head><Version>1.0</Version><TimeStamp>${TimeStamp}</TimeStamp><SequenceId>${SequenceId}</SequenceId><StatusCode>${StatusCode}</StatusCode><Message>${Message}</Message></Head><Body>${Body}</Body></Trade>", params);
/* */
/* 295 */ return xml;
/* */ }
/* */
/* */ private String cvt2FailProtoclXml(Map<String, String> params)
/* */ {
/* 306 */ params.put("${TimeStamp}", TypeFormat.getCurrentTime());
/* 307 */ params.put("${Body}", "");
/* */
/* 309 */ return replaceTemplate("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Trade><Head><Version>1.0</Version><TimeStamp>${TimeStamp}</TimeStamp><SequenceId>${SequenceId}</SequenceId><StatusCode>${StatusCode}</StatusCode><Message>${Message}</Message></Head><Body>${Body}</Body></Trade>", params);
/* */ }
/* */ }
/* Location: D:\TestCode\mopon\new-scenic-gateway\
* Qualified Name: cn.mopon.scenic.gateway.remote.OffLineWsCall
* JD-Core Version: 0.6.2
*/
|
C++
|
UTF-8
| 3,597 | 2.953125 | 3 |
[] |
no_license
|
#include "IPListDAO.h"
IPListDAO::IPListDAO(SQLite &db) : db(db)
{
}
IPListDAO::~IPListDAO()
{
}
int IPListDAO::insert(IPListModel model)
{
string sql = "INSERT INTO `ip_list` (`vps_id`,`ip_type`,`ip`) VALUES (?, ?, ?);";
this->db.setQuery(sql);
this->db.setParamInt(model.getVPSID());
this->db.setParamText(model.getIPType());
this->db.setParamText(model.getIP());
this->db.runQuery();
if( !this->db.getQueryStatus() )
{
this->setErrorMessage("UserDAO::insert() Error: " + this->db.getErrorMessage());
return 0;
}
return this->db.getLastInsertID();
}
IPListModel IPListDAO::findByID(int id)
{
IPListModel model;
model.setID(id);
return this->findBy(model).front();
}
list<IPListModel> IPListDAO::findBy(IPListModel model)
{
list<IPListModel> umodel;
string sql = "SELECT * FROM `ip_list`";
string where = "";
int start = 1;
//LOOP
while(start <= 2)
{
if(model.getID() != 0)
{
if(start == 1)
where += "`id`=? AND ";
else
this->db.setParamInt(model.getID());
}
if(model.getVPSID() != 0)
{
if(start == 1)
where += "`vps_id`=? AND ";
else
this->db.setParamInt(model.getVPSID());
}
if(model.getIPType() != "")
{
if(start == 1)
where += "`ip_type`=? AND ";
else
this->db.setParamText(model.getIPType());
}
if(model.getIP() != "")
{
if(start == 1)
where += "`ip`=? AND ";
else
this->db.setParamText(model.getIP());
}
//FIX SQL STRING + RUN QUERY
if(start == 1)
{
//FIND LAST INSTANCE OF AND + IF EXIST REMOVE IT
string::size_type st = where.find_last_of("AND");
if(st != string::npos)
where = where.substr(0, where.length()-5);
strhelper.trim(where);
if(where.length() > 0)
sql += " WHERE " + where + " LIMIT 1;";
//SET QUERY
this->db.setQuery(sql);
}
else
{
//RUN QUERY
this->db.runQuery();
if( !this->db.getQueryStatus() )
{
this->setErrorMessage("IPListDAO::findBy() Error: " + this->db.getErrorMessage());
return umodel;
}
//IF FOUND SOME RESULTS
if(this->db.getResultCount() > 0)
{
//GET RESULT _ POPULATE MODEL [ONLY ONE RESULT SO LOOP OK]
vector< map<string,string> > result = this->db.fetchArray();
for(vector< map<string,string> >::iterator i = result.begin(); i != result.end(); i++)
{
IPListModel tmpModel;
tmpModel.setData(*i);
umodel.push_back( tmpModel );
}
}
}
start++;
}
return umodel;
}
bool IPListDAO::deleteByID(int id)
{
string sql = "DELETE FROM `ip_list` WHERE `id`=?;";
this->db.setQuery(sql);
this->db.setParamInt(id);
this->db.runQuery();
if( !this->db.getQueryStatus() )
{
this->setErrorMessage("IPList::deleteByID() Error: " + this->db.getErrorMessage());
return false;
}
return true;
}
bool IPListDAO::deleteByModel(IPListModel model)
{
string sql = "DELETE FROM `ip_list` WHERE `id`=?;";
this->db.setQuery(sql);
this->db.setParamInt(model.getID());
this->db.runQuery();
if( !this->db.getQueryStatus() )
{
this->setErrorMessage("IPList::deleteByModel() Error: " + this->db.getErrorMessage());
return false;
}
return true;
}
bool IPListDAO::update(IPListModel model)
{
string sql = "UPDATE `ip_list` SET `vps_id`=?, `ip_type`=?, `ip`=? WHERE `id`=?;";
this->db.setQuery(sql);
this->db.setParamInt(model.getVPSID());
this->db.setParamText(model.getIPType());
this->db.setParamText(model.getIP());
this->db.setParamInt(model.getID());
this->db.runQuery();
if( !this->db.getQueryStatus() )
{
this->setErrorMessage("IPListDAO::update() Error: " + this->db.getErrorMessage());
return false;
}
return true;
}
|
Java
|
UTF-8
| 889 | 3.1875 | 3 |
[] |
no_license
|
package com.company;
import java.io.*;
public class CSVDataWriter implements DataWriter {
private String outputFile;
private FileWriter CSVwriter;
public CSVDataWriter(String outputFileName) throws IOException {
outputFile = outputFileName;
CSVwriter = new FileWriter(outputFile);
}
public CSVDataWriter() throws IOException {
outputFile = "CSVfile.csv";
CSVwriter = new FileWriter(outputFile);
}
public void writeData(String[] data) throws IOException{
String lineToWrite = String.join(";", data);
lineToWrite+=System.lineSeparator();
CSVwriter.write(lineToWrite);
}
public void endOfWork(){
try{
if (CSVwriter != null)
CSVwriter.close();
}catch(IOException ex){
ex.printStackTrace();
}
}
}
|
Swift
|
UTF-8
| 1,046 | 2.921875 | 3 |
[] |
no_license
|
//
// PersonDetailsViewController.swift
// TableMVVM-Example
//
// Created by Flávio Silvério on 07/09/17.
// Copyright © 2017 Flávio Silvério. All rights reserved.
//
import UIKit
class PersonDetailsViewController: UITableViewController {
var viewModel : PersonDetailsViewModel!
init(with style: UITableViewStyle, and vm: PersonDetailsViewModel) {
super.init(style: style)
viewModel = vm
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
extension PersonDetailsViewController {
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return viewModel.numberOfSections
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.numberOfRows(in: section)
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return viewModel.title(for: section)
}
}
|
PHP
|
UTF-8
| 7,547 | 3.03125 | 3 |
[] |
no_license
|
<?php
class Inscription extends Modele
{
public function valide_infos($pseudo,$courriel)
{
$valeur_pseudo = "";
$valeur_confirmation = "";
$type_pseudo = "hidden";
$type_confirmation = "hidden";
$statut_pseudo = true;
$helo_address = "mail.vif.ca";
$verifierdomaine = true;
$verifieradresse = true;
$adresseretour = "etudiant@vif.ca";
$erreursretournees = false;
$essai = new Courriel;
$resultats = array();
// 4 Vérifications pour le pseudo
if ($pseudo == "")
{
$valeur_pseudo = 'entrez le pseudo';
$statut_pseudo = false;
}
else if (strlen($pseudo) < 5)
{
$valeur_pseudo = 'pseudonyme trop court';
$statut_pseudo = false;
}
else if (strlen($pseudo) > 20)
{
$valeur_pseudo = 'pseudonyme trop long';
$statut_pseudo = false;
}
else
{
// Vérification des informations
$sql = "select count(*) as nombre from login where pseudo = ?";
$resultat = $this->executerRequete($sql, array($pseudo));
$ligne = $resultat->fetch();
$nombre = $ligne['nombre'];
if ($nombre > 0)
{
$valeur_pseudo = "pseudonyme déjà présent";
$statut_pseudo = false;
}
}
// vérification pour le courriel
if ($courriel == "")
{
$valeur_confirmation = "entrez le courriel";
$statut_pseudo = false;
}
if ($courriel != "")
{
$bonne_adresse = $this->VerifierAdresseMail($courriel);
if ($bonne_adresse == false)
{
$valeur_confirmation = "format entré incorrect";
$statut_pseudo = false;
}
else
{
$sql = "select count(*) as nombre from users where courriel = ?";
$resultat = $this->executerRequete($sql, array($courriel));
$ligne = $resultat->fetch();
$nombre = $ligne['nombre'];
if ($nombre > 0)
{
$valeur_confirmation = "courriel déjà utilisé";
$statut_pseudo = false;
}
}
}
if ($valeur_confirmation != "")
$type_confirmation = "text";
if ($valeur_pseudo != "")
$type_pseudo = "text";
$resultats['pseudo'] = $valeur_pseudo;
$resultats['confirmation'] = $valeur_confirmation;
$resultats['type_pseudo'] = $type_pseudo;
$resultats['type_confirmation'] = $type_confirmation;
$resultats['pseudo_ok'] = $statut_pseudo;
return $resultats;
}
public function VerifierAdresseMail($adresse)
{
$Syntaxe='#^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,6}$#';
if (preg_match($Syntaxe,$adresse))
return true;
else
return false;
}
public function Genere_Password($size)
{
$password = '';
// Initialisation des caractères utilisables
$characters = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z");
for($i=0;$i<$size;$i++){
$password .= ($i%2) ? strtoupper($characters[array_rand($characters)]) : $characters[array_rand($characters)];
}
return $password;
}
public function EnvoiCourriel($adresse_email,$nom_utilisateur,$pascrypte)
{
// Preparation du mail
$nom = "Adminstrateur du site";
$mail = "denis@etudiant99.com";
// voici la version Mine
$headers = "MIME-Version: 1.0\r\n";
// ici on détermine le mail en format text
$headers .= "Content-type: text/html; charset=UTF-8\r\n";
$headers .= "From: $nom <$mail>\r\nX-Mailer:PHP";
// dans le From tu mets l'expéditeur du mail
$sujet="Validation inscription";
$subject="$sujet";
$destinataire= $nom_utilisateur.' <'.$adresse_email.'>';
$adresse = $_SERVER['PHP_SELF'];
$adresseServeur = $_SERVER['SERVER_ADDR'];
$corps = "<p>Bonjour, ".$nom_utilisateur."</p>";
$corps .= "<p>Votre inscription au site <b><u>jouezauxechecs</b></u> a été réalisée.<br />";
$corps.= "Un mot de passe temporaire vous est envoyé maintenant.<br />";
$corps.= "Il permettra de vous connecter au site, et de jouer des parties d'échecs.</p>";
$corps.= "<p>Je veux vous préciser que ce mot de passe est connu de vous seul.<br />";
$corps.= "Il a été créé automatiquement. Alors, même l'administrateur du site<br />";
$corps.= "ne connaît pas ce mot de passe qui vous a été envoyé.</p>";
$corps.= "<p>De plus, ce mot de passe temporaire a été ajouté, automatiquement, à une <br />";
$corps.= "base de données, mais de facon cryptée, donc illisible par l'administrateur aussi.</p>";
$corps.= "<p>Alors, pour vous connecter au site,</p>";
$corps.="<p> <b><u>Pseudo:</b></u> ".$nom_utilisateur."</p>";
$corps.="<p> <b><u>Mot de passe:</u></b> ".$pascrypte."</p>";
//$corps.='<p><a href="http://etudiant99.com/jouezauxechecs/">Jouer aux echecs</a></p>';
$corps.='<p><a href="http://localhost/jouezauxechecs/">Jouer aux echecs</a></p>'; // en local
$corps.="<p>Vous pouvez modifier votre mot de passe par le menu <b><u>profil</b></u>.<br />";
$corps.="Vous serez déconnecté et devrez vous reconnecter avec le nouveau mot de passe "."</p>";
$corps.="<p>::::::::::::::: MAIL AUTOMATIQUE - NE PAS Y RÉPONDRE :::::::::::::::</p>";
mail($destinataire,$subject,$corps,$headers);
Return;
}
public function enregistrer_joueur($pseudo,$courriel)
{
$panier = $this->valide_infos($pseudo,$courriel);
$valeur_pseudo = $panier['pseudo'];
$valeur_confirmation = $panier['confirmation'];
$type_pseudo = $panier['type_pseudo'];
$type_confirmation = $panier['type_confirmation'];
$statut_pseudo = $panier['pseudo_ok'];
if (($statut_pseudo == true) &&($type_confirmation == "hidden")){
$le_sexe_personne = 'h';
$sql = "insert into users (sexe, courriel, date_inscription)
values ('$le_sexe_personne', '$courriel', now())";
$this->executerRequete($sql);
$sql = "select uid from users order by uid desc";
$resultat = $this->executerRequete($sql);
$ligne = $resultat->fetch();
$mon_uid = $ligne['uid'];
$secret = $this->Genere_Password(8);
$invisible = md5($secret);
$sql = "insert into login (uid, pseudo, bidon, date_inscription) values ($mon_uid, '$pseudo', '$invisible', now())";
$this->executerRequete($sql);
$sql = "insert into statistiques (uid) values ($mon_uid)";
$this->executerRequete($sql);
$this->EnvoiCourriel($courriel,$pseudo,$secret);
}
return $panier;
}
}
?>
|
C++
|
UTF-8
| 1,860 | 2.796875 | 3 |
[] |
no_license
|
#include <GL/gl.h>
#include <GL/glut.h>
#include <stdio.h>
#include <bits/stdc++.h>
#include "userdefined.h"
double dot_prod(double A[2], double B[2]) {
return A[0]*B[0] + A[1]*B[1];
}
double max(double a, double b) {
if(a>b) return a;
return b;
}
double min(double a, double b) {
if(a<b) return a;
return b;
}
void drawborders(double xmin, double ymin, double xmax, double ymax) {
ddaAlgo(xmin,ymin, xmax,ymin);
ddaAlgo(xmin,ymin, xmin,ymax);
ddaAlgo(xmax,ymax, xmax,ymin);
ddaAlgo(xmax,ymax, xmin,ymax);
}
void cyrus_beck(double x1, double y_1, double x2, double y2, double xmin, double xmax, double ymin, double ymax) {
glBegin(GL_POINTS);
drawborders(xmin,ymin,xmax,ymax);
double t[4];
t[0] = -1.0*(y_1-ymax)/(y2-y_1);
t[1] = -1.0*(y_1-ymin)/(y2-y_1);
t[2] = -1.0*(x1-xmax)/(x2-x1);
t[3] = -1.0*(x1-xmin)/(x2-x1);
double N[4][2] = {{0.0,1.0},{0.0,-1.0},{1.0,0.0},{-1.0,0.0}};
double d[2];
d[0] = x2-x1;
d[1] = y2-y_1;
double te=0, tl=1;
for(int i=0;i<4;i++) {
if(dot_prod(d, N[i]) < 0) {
te = max(te, t[i]);
}
else {
tl = min(tl, t[i]);
}
}
if(te>tl) {
printf("Got rejected :(\n");
}
else {
double newx0 = x1+(x2-x1)*te;
double newx1 = x1+(x2-x1)*tl;
double newy0 = y_1+(y2-y_1)*te;
double newy1 = y_1+(y2-y_1)*tl;
printf("%lf %lf %lf %lf\n", newx0,newy0,newx1,newy1);
ddaAlgo(newx0,newy0,newx1,newy1);
}
glEnd();
glFlush();
}
void cymenu() {
printf("[Cyrus-Beck] Enter the points: ");
double x0,y0,x1,y_1;
scanf("%lf %lf %lf %lf", &x0, &y0, &x1, &y_1);
cyrus_beck(x0,y0,x1,y_1,-320,-220,-80,80);
cyrus_beck(x0,y0,x1,y_1,220,320,-80,80);
printf("[Cyrus-Beck] (back/continue/clear/exit): ");
char prompt[10];
scanf("%s", prompt);
if(prompt[0]=='b') menu();
else if(prompt[0]=='c') {
if(prompt[1]=='l') clearWindow();
cymenu();
}
else return;
}
|
C#
|
UTF-8
| 541 | 2.640625 | 3 |
[] |
no_license
|
namespace RPI.WiringPiWrapper.WiringPi.Wrappers.Timing
{
public class TimingWrapper : IWrapTiming
{
public void Delay(uint howLong)
{
WiringPi.Timing.Delay(howLong);
}
public void DelayMicroseconds(uint howLong)
{
WiringPi.Timing.DelayMicroseconds(howLong);
}
public uint Micros()
{
return WiringPi.Timing.Micros();
}
public uint Millis()
{
return WiringPi.Timing.Millis();
}
}
}
|
Markdown
|
UTF-8
| 22,014 | 2.75 | 3 |
[] |
no_license
|
# 通过赔率预测比赛 - unixfy - 博客园
# [程序最美(寻路)](https://www.cnblogs.com/unixfy/)
你还在坚持练习你的技术吗?运动员天天训练,音乐家也会演练更难的曲章。你呢?
## [通过赔率预测比赛](https://www.cnblogs.com/unixfy/p/3476696.html)
通过赔率预测比赛
根据历往博彩公司开的赔率以及每次比赛的胜负,运用分类算法(本质上是二元分类,因为只是针对胜负)进行未来比赛的预测。得到的结果并不算很理想。主场情况下,最好只能达到七成的准确率,客场更差,对于二串一的玩法这种准确率无法胜任。
采用的分类算法是KNN,KNN的实现也可以详见之前的C++Blog上的[博文](http://www.cppblog.com/unixfy/archive/2012/02/14/165537.aspx),特征向量间距离是采用欧氏距离,特征向量间距离和相似度的计算可以详见C++Blog[博文](http://www.cppblog.com/unixfy/archive/2013/09/18/165487.html)。
发表一下个人对于基于统计学习方法的看法:机器学习或者基于统计的方法是没有办法的办法,无法通过规则得到良好的结果,所以只能依赖于历史数据,经过大规模运算得到一个看上去还可以的结果。这种看上去还可以的结果对于一些领域是有用的,但是对准确度要求较高的领域是不适用的。
历往赔率和胜负信息如下:
星期五 20131206[00:00 -- 24:00]
301 欧冠杯 2013/12/6 23:40 费内巴切 中央陆军 3.03 1.35 亚 欧 析 2.8 78:74
302 欧冠杯 2013/12/6 23:40 布罗斯 艾菲斯 4.9 1.16 亚 欧 析 4.8 89:78
303 欧冠杯 2013/12/6 23:40 巴塞隆拿 楠泰尔 1.19 4.52 亚 欧 析 1.06 82:78
304 欧冠杯 2013/12/6 23:40 红星 帕纳辛 4.87 1.16 亚 欧 析 1.06 63:69
305 欧冠杯 2013/12/6 23:40 里塔斯 泰斯拉米卡 5.34 1.13 亚 欧 析 1.03 63:79
306 NBA 2013/12/6 23:40 76人 山猫 3.21 1.34 亚 欧 析 1.31 88:105
307 NBA 2013/12/6 23:40 雄鹿 奇才 4.84 1.17 亚 欧 析 5.1 109:105
308 NBA 2013/12/6 23:40 骑士 老鹰 3.01 1.37 亚 欧 析 1.21 89:108
309 NBA 2013/12/6 23:40 掘金 凯尔特人 1.53 2.46 亚 欧 析 2.63 98:106
310 NBA 2013/12/6 23:40 魔术 尼克斯 2.73 1.44 亚 欧 析 1.3 83:121
311 NBA 2013/12/6 23:40 勇士 火箭 2.58 1.49 亚 欧 析 1.44 83:105
312 NBA 2013/12/6 23:40 雷霆 鹈鹕 1.44 2.73 亚 欧 析 1.23 109:95
313 NBA 2013/12/7 9:45 猛龙 太阳 2.45 1.54 亚 欧 析 1.42 97:106
314 NBA 2013/12/7 10:45 爵士 开拓者 5.91 1.12 亚 欧 析 1.02 98:130
315 NBA 2013/12/7 10:45 湖人 国王 2.36 1.57 亚 欧 析 2.06 106:100
星期六 20131207[00:00 -- 24:00]
301 NBA 2013/12/8 0:40 掘金 76人 1.33 3.21 亚 欧 析 1.2 103:92
302 NBA 2013/12/8 0:40 快船 骑士 1.38 2.96 亚 欧 析 3.17 82:88
303 NBA 2013/12/8 0:40 活塞 公牛 2.14 1.68 亚 欧 析 2 92:75
304 NBA 2013/12/8 0:40 勇士 灰熊 1.75 2.04 亚 欧 析 1.54 108:82
305 NBA 2013/12/8 0:40 热火 森林狼 1.35 3.17 亚 欧 析 1.23 103:82
306 NBA 2013/12/8 9:15 篮网 雄鹿 1.67 2.16 亚 欧 析 1.54 90:82
308 NBA 2013/12/8 9:45 国王 爵士 2.28 1.61 亚 欧 析 2 112:102
309 NBA 2013/12/8 10:45 小牛 开拓者 2.78 1.43 亚 欧 析 2.92 108:106
星期日 20131208[00:00 -- 24:00]
301 NBA 2013/12/9 0:40 凯尔特人 尼克斯 2.76 1.43 亚 欧 析 2.6 114:73
302 NBA 2013/12/9 0:40 热火 活塞 1.57 2.38 亚 欧 析 1.32 110:95
303 NBA 2013/12/9 0:40 魔术 火箭 7.76 1.08 亚 欧 析 1.03 88:98
304 NBA 2013/12/9 0:40 步行者 雷霆 2.56 1.5 亚 欧 析 1.43 94:118
星期一 20131209[00:00 -- 24:00]
301 NBA 2013/12/9 23:40 勇士 山猫 1.41 2.86 亚 欧 析 2.86 111:115
302 NBA 2013/12/9 23:40 快船 76人 1.18 4.63 亚 欧 析 1.11 94:83
303 NBA 2013/12/9 23:40 掘金 奇才 1.82 1.94 亚 欧 析 1.68 75:74
304 NBA 2013/12/9 23:40 魔术 灰熊 4.21 1.21 亚 欧 析 1.1 85:94
305 NBA 2013/12/10 9:45 开拓者 爵士 1.31 3.34 亚 欧 析 1.15 105:94
306 NBA 2013/12/10 10:45 小牛 国王 1.52 2.47 亚 欧 析 2.45 97:112
星期二 20131210[00:00 -- 24:00]
301 NBA 2013/12/11 7:45 尼克斯 骑士 2.13 1.69 亚 欧 析 1.52 94:109
302 NBA 2013/12/11 8:00 热火 步行者 2.26 1.61 亚 欧 析 1.51 84:90
303 NBA 2013/12/11 7:45 马刺 猛龙 1.25 3.84 亚 欧 析 1.11 116:103
304 NBA 2013/12/11 8:15 雷霆 老鹰 1.57 2.37 亚 欧 析 1.36 101:92
305 NBA 2013/12/11 8:15 凯尔特人 篮网 2.07 1.72 亚 欧 析 1.62 96:104
306 NBA 2013/12/11 8:15 森林狼 活塞 1.89 1.88 亚 欧 析 1.76 121:94
307 NBA 2013/12/11 8:45 雄鹿 公牛 3.3 1.33 亚 欧 析 2.86 78:74
308 NBA 2013/12/11 11:15 太阳 湖人 2.23 1.63 亚 欧 析 2.18 114:108
星期三 20131211[00:00 -- 24:00]
301 NBA 2013/12/12 7:45 魔术 山猫 2.69 1.45 亚 欧 析 2.55 92:83
302 NBA 2013/12/12 8:15 快船 凯尔特人 1.43 2.76 亚 欧 析 1.34 96:88
303 NBA 2013/12/12 8:45 雷霆 灰熊 1.37 3.02 亚 欧 析 1.19 116:100
304 NBA 2013/12/12 8:45 马刺 雄鹿 1.12 5.96 亚 欧 析 1.02 109:77
305 NBA 2013/12/12 8:45 76人 森林狼 7.6 1.08 亚 欧 析 1.02 99:106
306 NBA 2013/12/12 8:45 活塞 鹈鹕 2.15 1.67 亚 欧 析 1.57 106:111
307 NBA 2013/12/12 8:45 公牛 尼克斯 2.38 1.57 亚 欧 析 1.42 78:83
308 NBA 2013/12/12 10:45 爵士 国王 3.19 1.33 亚 欧 析 3.4 122:101
309 NBA 2013/12/12 11:15 小牛 勇士 2.81 1.42 亚 欧 析 1.3 93:95
星期四 20131212[00:00 -- 24:00]
301 欧冠杯 2013/12/12 23:35 巴塞隆拿 中央陆军 2.79 1.42 亚 欧 析 1.32 65:79
302 欧冠杯 2013/12/12 23:35 艾菲斯 萨尔基利斯 1.94 1.81 亚 欧 析 1.58 63:65
303 欧冠杯 2013/12/12 23:35 泰斯拉米卡 红星 1.91 1.87 亚 欧 析 1.65 65:81
304 欧冠杯 2013/12/12 23:35 锡耶纳 亚高斯 3.9 1.23 亚 欧 析 1.1 73:78
305 欧冠杯 2013/12/12 23:35 拜仁 乌尼卡哈 2.94 1.37 亚 欧 析 1.28 72:77
306 欧冠杯 2013/12/12 23:35 里塔斯 TA马卡比 6.08 1.1 亚 欧 析 1.02 71:78
307 欧冠杯 2013/12/12 23:35 游击队 费内巴切 5.72 1.12 亚 欧 析 5.3 79:77
308 NBA 2013/12/12 23:35 快船 篮网 1.8 1.98 亚 欧 析 1.92 93:102
309 NBA 2013/12/13 11:15 火箭 开拓者 2.17 1.67 亚 欧 析 1.5 104:111
星期五 20131213[00:00 -- 24:00]
301 欧冠杯 2013/12/13 23:40 帕纳辛 火车头 2.33 1.56 亚 欧 析 2.28 82:63
302 欧冠杯 2013/12/13 23:40 楠泰尔 布迪维林克 2.17 1.65 亚 欧 析 1.5 87:97
303 欧冠杯 2013/12/13 23:40 萨斯图 加拉塔萨雷 3.77 1.24 亚 欧 析 1.09 57:76
304 欧冠杯 2013/12/13 23:40 布罗斯 米兰 3.26 1.31 亚 欧 析 1.14 73:74
306 NBA 2013/12/13 23:40 山猫 步行者 7.08 1.09 亚 欧 析 1 94:99
307 NBA 2013/12/13 23:40 骑士 魔术 2.07 1.73 亚 欧 析 1.88 109:100
308 NBA 2013/12/13 23:40 76人 猛龙 3.43 1.3 亚 欧 析 1.15 100:108
309 NBA 2013/12/13 23:40 奇才 老鹰 2.88 1.4 亚 欧 析 1.28 99:101
310 NBA 2013/12/13 23:40 尼克斯 凯尔特人 2.26 1.62 亚 欧 析 1.4 86:90
311 NBA 2013/12/13 23:40 篮网 活塞 2.9 1.4 亚 欧 析 1.35 99:103
312 NBA 2013/12/13 23:40 灰熊 鹈鹕 2.19 1.65 亚 欧 析 1.56 98:104
313 NBA 2013/12/13 23:40 湖人 雷霆 7.66 1.08 亚 欧 析 1.01 97:122
314 NBA 2013/12/14 9:15 公牛 雄鹿 1.55 2.39 亚 欧 析 1.38 91:90
315 NBA 2013/12/14 9:15 森林狼 马刺 4.1 1.23 亚 欧 析 1.11 110:117
316 NBA 2013/12/14 9:45 爵士 掘金 5.26 1.14 亚 欧 析 4.65 103:93
317 NBA 2013/12/14 9:45 国王 太阳 3.08 1.36 亚 欧 析 1.28 107:116
318 NBA 2013/12/14 11:15 火箭 勇士 2.29 1.61 亚 欧 析 2 116:112
星期六 20131214[00:00 -- 24:00]
301 NBA 2013/12/15 0:40 湖人 山猫 2.18 1.67 亚 欧 析 1.94 88:85
302 NBA 2013/12/15 0:40 快船 奇才 1.51 2.5 亚 欧 析 1.32 113:97
303 NBA 2013/12/15 0:40 骑士 热火 7.7 1.08 亚 欧 析 1.01 107:114
304 NBA 2013/12/15 0:40 老鹰 尼克斯 1.87 1.9 亚 欧 析 1.91 106:111
305 NBA 2013/12/15 0:40 猛龙 公牛 2.27 1.63 亚 欧 析 2.11 99:77
306 NBA 2013/12/15 0:40 开拓者 76人 1.15 5.26 亚 欧 析 1.06 139:105
307 NBA 2013/12/15 9:15 雄鹿 小牛 6.18 1.11 亚 欧 析 1.02 93:106
308 NBA 2013/12/15 9:45 马刺 爵士 1.32 3.28 亚 欧 析 1.17 100:84
**了解程序实现细节可以阅读源码和注释。**
//通过赔率预测比赛\#include <iostream>\#include<fstream>\#include<sstream>\#include<string>\#include<vector>\#include<map>\#include<cassert>usingnamespacestd;//检验数据的规范性boolTestNormal(conststring&filename)
{
ifstream fin(filename.c_str());if(!fin)
{
cerr<<"File error!"<<endl;
exit(1);
}stringline;inttotaltmp =0;boolfirstsample =true;while(getline(fin, line))
{if(line.empty())
{continue;
}if(line[0] !='3')
{continue;
}
istringstream sin(line);stringtmp;intn =0;while(sin >>tmp)
{++n;
}if(firstsample)
{
totaltmp=n;
firstsample=false;
}else{if(totaltmp !=n)
{returnfalse;
}
}
}
fin.close();returntrue;
}//样例结构体structSample
{stringtype;//类型vector<double> data;//数据};//获取类型stringGetType(conststring&scores)
{strings1, s2;
auto pos= scores.find(':');
s1= scores.substr(0, pos);
s2= scores.substr(pos +1);intsa =atoi(s1.c_str());intsb =atoi(s2.c_str());if(sa >sb)
{return"1";
}elseif(sa <sb)
{return"2";
}else{return"-1";
}
}//读取数据voidReadData(conststring& filename,conststring& nonleague, vector<Sample>&samples)
{
ifstream fin("HistoryData.txt");if(!fin)
{
cerr<<"Data file error!"<<endl;
exit(1);
}
samples.clear();stringline;while(getline(fin, line))
{if(line.empty())
{continue;
}if(line[0] !='3')
{continue;
}
istringstream sin(line);stringodds1, odds2, scores;
sin>> odds1 >>odds2;if(odds2 == nonleague)//排除指定联赛{continue;
}
sin>> odds1 >> odds2 >> odds1 >>odds2;
sin>> odds1 >>odds2;
Sample tmpsmp;doubleoddsa =atof(odds1.c_str());doubleoddsb =atof(odds2.c_str());
tmpsmp.data.push_back(oddsa);
tmpsmp.data.push_back(oddsb);
sin>> odds1 >>odds2;
sin>>odds2;
tmpsmp.type=GetType(odds2);
samples.push_back(tmpsmp);
}
fin.clear();
}voidPrintData(constvector<Sample>&samples)
{for(auto i =0; i != samples.size(); ++i)
{
cout<< samples[i].type <<'';for(auto j =0; j != samples[i].data.size(); ++j)
{
cout<< samples[i].data[j] <<'';
}
cout<<endl;
}
}//读取数据后,根据数据得到特征voidGenerateFeatures(vector<Sample>&samples)
{for(auto i =0; i != samples.size(); ++i)
{doublea =0.0, b =0.0;doublex = samples[i].data[0];doubley = samples[i].data[1];//原数据中X、Y已在数据中samples[i].data.clear();//X,Ysamples[i].data.push_back(x);
samples[i].data.push_back(y);//X-1,Y-1a = x -1;
b= y -1;
samples[i].data.push_back(a);
samples[i].data.push_back(b);//1/(Y-1),1/(X-1)a =1/ (y -1);
b=1/ (x -1);
samples[i].data.push_back(a);
samples[i].data.push_back(b);//1+1/(Y-1),1+1/(X-1)a =1+1/ (y -1);
b=1+1/ (x -1);
samples[i].data.push_back(a);
samples[i].data.push_back(b);//(X-1)*(Y-1)a = (x -1) * (y -1);
samples[i].data.push_back(a);//(1/(Y-1))*(1/(X-1))a = (1/ (y -1)) * (1/ (x -1));
samples[i].data.push_back(a);//X*Ya = x *y;
samples[i].data.push_back(a);//(1/(Y-1)+1)*(1/(X-1)+1)a = (1/ (y -1) +1) * (1/ (x -1) +1);
samples[i].data.push_back(a);//X-Y,Y-Xa = x -y;
b= y -x;
samples[i].data.push_back(a);
samples[i].data.push_back(b);//X/Y,Y/Xa = x /y;
b= y /x;
samples[i].data.push_back(a);
samples[i].data.push_back(b);//1/(Y-1)-(X-1),1/(X-1)-(Y-1)a =1/ (y -1) - (x -1);
b=1/ (x -1) - (y -1);
samples[i].data.push_back(a);
samples[i].data.push_back(b);//(1/(Y-1)-(X-1))/(1/(Y-1))//(1/(X-1)-(Y-1))/(1/(X-1))a = (1/ (y -1) - (x -1)) / (1/ (y -1));
b= (1/ (x -1) - (y -1)) / (1/ (x -1));
samples[i].data.push_back(a);
samples[i].data.push_back(b);//(1/(Y-1)-(X-1))/(X-1)//(1/(X-1)-(Y-1))/(Y-1)a = (1/ (y -1) - (x -1)) / (x -1);
b= (1/ (x -1) - (y -1)) / (y -1);
samples[i].data.push_back(a);
samples[i].data.push_back(b);//(1/(Y-1)-(X-1))/(1/(Y-1)+1)//(1/(X-1)-(Y-1))/(1/(X-1)+1)a = (1/ (y -1) - (x -1)) / (1/ (y -1) +1);
b= (1/ (x -1) - (y -1)) / (1/ (x -1) +1);
samples[i].data.push_back(a);
samples[i].data.push_back(b);//(1/(Y-1)-(X-1))/X//(1/(X-1)-(Y-1))/Ya = (1/ (y -1) - (x -1)) /x;
b= (1/ (x -1) - (y -1)) /y;
samples[i].data.push_back(a);
samples[i].data.push_back(b);//总共26个特征}
}//获取训练集和测试集voidGetTrainAndTest(constvector<Sample>& samples, vector<Sample>& train, vector<Sample>& test,inttestnum)
{
assert(testnum>0&& testnum <samples.size());
train.clear();
test.clear();
train.assign(samples.begin(), samples.begin()+ samples.size() -testnum);
test.assign(samples.begin()+ samples.size() -testnum, samples.end());
}//计算欧氏距离//还有其他向量的距离和相似度//这里暂且用欧氏距离doubleEuclideanDistance(constvector<double>& v1,constvector<double>&v2)
{
assert(v1.size()==v2.size());doubleret =0.0;for(auto i =0; i != v1.size(); ++i)
{
ret+= (v1[i] - v2[i]) * (v1[i] -v2[i]);
}returnsqrt(ret);
}//初始化距离矩阵//该距离矩阵根据训练样本和测试样本而得//该矩阵的行数为测试样本集的样本个数//该矩阵的列数为训练样本集的样本个数voidInitEuclideanDistanceMatrix(constvector<Sample>& test,constvector<Sample>& train, vector<vector<double> >&dm)
{
dm.clear();for(auto i =0; i != test.size(); ++i)
{
vector<double>vd;for(auto j =0; j != train.size(); ++j)
{
vd.push_back(EuclideanDistance(test[i].data, train[j].data));
}
dm.push_back(vd);
}
}//KNN算法实现//设定不同的K值,给每个测试样例予以一个类型//距离和权重成反比//还有其他机器学习有监督分类算法,这里暂且用KNN//二元分类算法voidKNNProcess(vector<Sample>& test,constvector<Sample>& train,constvector<vector<double> >& dm,intk)
{
assert(k>0&& k <=train.size());for(auto i =0; i != test.size(); ++i)
{
multimap<double,string>dts;for(auto j =0; j != train.size(); ++j)
{if(dts.size() <k)
{
dts.insert(make_pair(dm[i][j], train[j].type));
}else{
auto cit=dts.end();--cit;if(dm[i][j] < cit->first)
{
dts.erase(cit);
dts.insert(make_pair(dm[i][j], train[j].type));
}
}
}//对最相似的K个样例进行数据统计map<string,double>tds;stringtype ="";doubleweight =0.0;for(auto cit = dts.begin(); cit != dts.end(); ++cit)
{//不考虑权重的情况,在K个最相似的样例,只要出现就加1//++tds[cit->second];//这里是考虑距离与权重的关系,距离和权重成反比tds[cit->second] +=1.0/ cit->first;if(tds[cit->second] >weight)
{
weight= tds[cit->second];
type= cit->second;
}
}
test[i].type=type;
}
}//输出测试样例//每行一个样例//每行先是样例种类,后面是样例数据voidPrintTest(constvector<Sample>&test)
{for(auto i =0; i != test.size(); ++i)
{
cout<< test[i].type <<'';for(auto j =0; j != test[i].data.size(); ++j)
{
cout<< test[i].data[j] <<'';
}
cout<<endl;
}
}//对结果进行评估统计//这里对预测准确的进行统计,得到准确率//一种更为科学的方法是针对每种类别,计算每种类别的召回率、准确率、F值//召回率:类别内预测对的样例数目除以原来这个类别的样例数目//准确率:类别内预测对的样例数目除以所有预测这个类别的样例数目//F值:召回率和准确率的加权值//这里我们只是用所有类别中预测对的样例数目除以测试样例数目//由于所有类别的之前数目和测试数目一直,所以这个值相当于召回率和准确率voidStatisticalEvaluation(constvector<Sample>& test,constvector<Sample>&samples)
{intrightnum =0;for(auto i = samples.size() - test.size(); i != samples.size(); ++i)
{if(test[i - (samples.size() - test.size())].type ==samples[i].type)
{++rightnum;
}
}
cout<< rightnum <<''<< test.size() <<endl;
}//统计准确率和召回率//重要的是准确率,现实操作中,只能通过预测的结果进行选择//召回率再高不起作用,我们只能通过准确率来保证选择的正确voidGetPrecisionAndRecall(constvector<Sample>& test,constvector<Sample>&samples)
{
map<string,int>rights;
map<string,int>result;
map<string,int>truth;for(auto i = samples.size() - test.size(); i != samples.size(); ++i)
{if(test[i - (samples.size() - test.size())].type ==samples[i].type)
{++rights[samples[i].type];
}++result[test[i - (samples.size() -test.size())].type];++truth[samples[i].type];
}for(auto cit = rights.begin(); cit != rights.end(); ++cit)
{
cout<< cit->first <<':';
cout<< cit->second <<'';
cout<< result[cit->first] <<'('<<1.0* cit->second / result[cit->first]/*除0未考虑*/<<')'<<'';
cout<< truth[cit->first] <<'('<<1.0* cit->second / truth[cit->first]/*除0未考虑*/<<')'<<endl;
}
}intmain()
{if(!TestNormal("HistoryData.txt"))
{
cerr<<"数据格式错误!"<<endl;
exit(1);
}else{//cout << "OK!" << endl;}
vector<Sample>samples;
ReadData("HistoryData.txt","", samples);//PrintData(samples);GenerateFeatures(samples);
vector<Sample>train, test;
GetTrainAndTest(samples, train, test, samples.size()*0.3);//GetTrainAndTest(samples, train, test, 10);vector<vector<double> >dm;
InitEuclideanDistanceMatrix(test, train, dm);for(inti =1; i <= train.size(); ++i)
{
KNNProcess(test, train, dm, i);//PrintTest(test);//cout << i << ' ';//StatisticalEvaluation(test, samples);cout << i <<endl;
GetPrecisionAndRecall(test, samples);
}return0;
}

posted on2013-12-16 14:17[unixfy](https://www.cnblogs.com/unixfy/)阅读(...) 评论(...)[编辑](https://i.cnblogs.com/EditPosts.aspx?postid=3476696)[收藏](#)
[刷新评论](javascript:void(0);)[刷新页面](#)[返回顶部](#top)
### 导航
[博客园](https://www.cnblogs.com/)
[首页](https://www.cnblogs.com/unixfy/)
[新随笔](https://i.cnblogs.com/EditPosts.aspx?opt=1)
[联系](https://msg.cnblogs.com/send/unixfy)
[订阅](https://www.cnblogs.com/unixfy/rss)[管理](https://i.cnblogs.com/)
统计
随笔 - 85文章 - 0评论 - 8引用 - 0
公告
Powered by:
博客园
Copyright © unixfy
|
C#
|
UTF-8
| 4,815 | 3.203125 | 3 |
[] |
no_license
|
using System;
class GameBarObject : GameObject
{
private const int MIN_SIZE = 3;
private const int BORDER_WIDTH = 2;
private double percent;
private int max;
private int value;
private string output = "";
private int fillCount = 0;
private ConsoleColor colour;
public GameBarObject(GameContainer gc, int x, int y, ConsoleColor colour, bool isVisible, int maxValue, int startValue, int barWidth) : base(gc, ' ', x, y, colour, colour, isVisible)
{
this.max = Math.Max(1,maxValue);
this.value = Helper.Clamp(startValue, 0, maxValue);
this.colour = colour;
width = Helper.Clamp(barWidth, MIN_SIZE, gc.GetUIWidth() - x - 1);
height = 1;
for (int i = 0; i < width; i++)
{
output += " ";
}
this.percent = CalcPercentage();
fillCount = CalcFillCount();
//Set up grid to handle character text
grid = new char[1, width];
colourGrid = new ColourSet[1, width];
//Set end points
grid[0, 0] = ' ';
colourGrid[0, 0] = new ColourSet(Helper.WHITE, Helper.fgCol);
grid[0, width - 1] = ' ';
colourGrid[0, width - 1] = new ColourSet(Helper.WHITE, Helper.fgCol);
for (int i = 1; i < width - 1; i++)
{
grid[0, i] = ' ';
colourGrid[0, i] = new ColourSet(Helper.DARK_BLUE, Helper.fgCol);
}
SetColours();
}
private double CalcPercentage()
{
return (double)value / (double)max;
}
private int CalcFillCount()
{
return (int)Math.Ceiling((width - BORDER_WIDTH) * percent);
}
private void SetColours()
{
int count = 0;
for (int i = 1; i < width - 1; i++)
{
if (count < fillCount)
{
colourGrid[0, i].SetBG(colour);
}
else
{
colourGrid[0, i].SetBG(Helper.DARK_BLUE);
}
count++;
}
}
/**
* <b><i>GetValue</b></i>
* <p>
* {@code public int GetValue()}
* <p>
* Retrieve the current value of the progress bar
*
* @return The value of the progress bar
*/
public int GetValue()
{
return value;
}
/**
* <b><i>GetMax</b></i>
* <p>
* {@code public int GetMax()}
* <p>
* Retrieve the maximum value of the progress bar
*
* @return The maximum value of the progress bar
*/
public int GetMax()
{
return max;
}
/**
* <b><i>GetPercentage</b></i>
* <p>
* {@code public int GetPercentage()}
* <p>
* Retrieve the current fill percentage of the progress bar
*
* @return The fill percentage of the progress bar
*/
public int GetPercentage()
{
return (int)(percent * 100.0);
}
/**
* <b><i>SetColour</b></i>
* <p>
* {@code public void SetColour(string colour)}
* <p>
* Set the colour of the filled portion of the progress bar
*
* @param colour The new colour of the progress bar
*/
public void SetColour(ConsoleColor colour)
{
this.colour = colour;
SetColours();
}
/**
* <b><i>SetValue</b></i>
* <p>
* {@code public void SetValue(int value)}
* <p>
* Set the value of the progress bar and recalculate its fill percentage
*
* @param value The new value of the progress bar
*/
public void SetValue(int value)
{
this.value = Helper.Clamp(value, 0, max);
this.percent = CalcPercentage();
fillCount = CalcFillCount();
SetColours();
}
/**
* <b><i>ChangeValue</b></i>
* <p>
* {@code public void ChangeValue(int changeAmount)}
* <p>
* Modify the value of the progress bar relative to its current setting
*
* @param changeAmount The amount to change the progress bar's value by
*/
public void ChangeValue(int changeAmount)
{
SetValue(value + changeAmount);
}
public void SetMax(int max)
{
this.max = Math.Max(1, max);
SetValue(value);
}
/**
* <b><i>IsEmpty</b></i>
* <p>
* {@code public bool IsEmpty()}
* <p>
* Check to see if the progress bar is empty
*
* @return True if the value of the progress is zero, False otherwise
*/
public bool IsEmpty()
{
return value == 0;
}
/**
* <b><i>IsFull</b></i>
* <p>
* {@code public bool IsFull()}
* <p>
* Check to see if the progress bar is full (at max value)
*
* @return True if the value of the progress is full, False otherwise
*/
public bool IsFull()
{
return value == max;
}
}
|
Java
|
UTF-8
| 1,219 | 2.484375 | 2 |
[] |
no_license
|
package com.docsis.beans;
import java.util.Date;
public class Cliente {
private int codCliente;// bigint PRIMARY KEY,
private String nome;// varchar(70),
private Date caddata;// date,
private Date bloqdata;// date,
private long contrato;//bigint
private String cpf; //varchar
public long getContrato() {
return contrato;
}
public void setContrato(long contrato) {
this.contrato = contrato;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public int getCodCliente() {
return codCliente;
}
public void setCodCliente(int codCliente) {
this.codCliente = codCliente;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Date getCaddata() {
return caddata;
}
public void setCaddata(Date caddata) {
this.caddata = caddata;
}
public Date getBloqdata() {
return bloqdata;
}
public void setBloqdata(Date bloqdata) {
this.bloqdata = bloqdata;
}
@Override
public String toString() {
return "Cliente [codCliente=" + codCliente + ", nome=" + nome
+ ", caddata=" + caddata + ", bloqdata=" + bloqdata
+ ", contrato=" + contrato + ", cpf=" + cpf + "]";
}
}
|
SQL
|
UTF-8
| 4,637 | 3.484375 | 3 |
[] |
no_license
|
CREATE DATABASE IF NOT EXISTS TPCH DEFAULT CHARACTER SET GBK COLLATE GBK_CHINESE_CI;
CREATE SCHEMA IF NOT EXISTS Sales DEFAULT CHARACTER SET GBK COLLATE GBK_CHINESE_CI;
USE Sales;
CREATE TABLE IF NOT EXISTS Region ( -- 地区表
regionkey INTEGER PRIMARY KEY, -- 地区编号(主键)
name CHAR(25), -- 地区名称
comment VARCHAR(152) -- 备注
);
CREATE TABLE IF NOT EXISTS Nation ( -- 国家表
nationkey INTEGER PRIMARY KEY, -- 国家编号(主键)
name CHAR(25), -- 国家名称
regionkey INTEGER REFERENCES Region (regionkey), -- 地区编号(外键)
comment VARCHAR(152) -- 备注
);
CREATE TABLE IF NOT EXISTS Supplier ( -- 供应商基本表
suppkey INTEGER PRIMARY KEY, -- 供应商编号(主键)
name CHAR(25), -- 供应商名称
address VARCHAR(40), -- 供应商地址
nationkey INTEGER REFERENCES Nation (nationkey), -- 国家编号(外键)
phone CHAR(15), -- 供应商电话
accbal REAL, -- 供应商账户余额
comment VARCHAR(101) -- 备注
);
CREATE TABLE IF NOT EXISTS Part ( -- 零件基本表
partkey INTEGER PRIMARY KEY, -- 零件编号(主键)
name VARCHAR(55), -- 零件名称
mfgr CHAR(25), -- 制造厂
brand CHAR(10), -- 品牌
type VARCHAR(25), -- 零件类型
size INTEGER, -- 尺寸
container CHAR(10), -- 包装
retailprice REAL, -- 零售价格
comment VARCHAR(23) -- 备注
);
CREATE TABLE IF NOT EXISTS PartSupp ( -- 零件供应联系表
partkey INTEGER REFERENCES Part (partkey), -- 零件编号(外键)
suppkey INTEGER REFERENCES Supplier (suppkey), -- 零件供应商编号(外键)
availqty INTEGER, -- 可用数量
supplycost REAL, -- 供应价格
comment VARCHAR(199), -- 备注
PRIMARY KEY (partkey , suppkey) -- 主键,表级约束
);
CREATE TABLE IF NOT EXISTS Customer ( -- 顾客表
custkey INTEGER PRIMARY KEY, -- 顾客编号(主键)
name VARCHAR(25), -- 顾客名字
address VARCHAR(40), -- 地址
nationkey INTEGER REFERENCES Nation (nationkey), -- 国籍编号
phone CHAR(15), -- 电话
acctbal REAL, -- 账户余额
mktsegment CHAR(10), -- 市场分区
comment VARCHAR(117) -- 备注
);
CREATE TABLE IF NOT EXISTS Orders ( -- 订单表
orderkey INTEGER PRIMARY KEY, -- 订单编号(主键)
custkey INTEGER REFERENCES Customer (custkey), -- 顾客编号(外键)
orderstatus CHAR(1), -- 订单状态
totalprice REAL, -- 总金额
orderdate DATE, -- 日期
orderpriority CHAR(15), -- 优先级
clerk CHAR(15), -- 记账员
shippriority INTEGER, -- 运输优先级
comment VARCHAR(79) -- 备注
);
CREATE TABLE IF NOT EXISTS Lineitem ( -- 订单明细表
orderkey INTEGER REFERENCES Orders (orderkey), -- 订单编号
partkey INTEGER REFERENCES Part (partkey), -- 零件编号
suppkey INTEGER REFERENCES Supplier (suppkey), -- 供应商编号
linenumber INTEGER, -- 订单明细编号
quantity REAL, -- 数量
extendedprice REAL, -- 订单明细价格
discount REAL, -- 折扣[0.00, 1.00]
tax REAL, -- 税率[0.00, 0.08]
returnflag CHAR(1), -- 退货标记
linestatus CHAR(1), -- 订单明细状态
shipdate DATE, -- 装运日期
commitdate DATE, -- 委托日期
receipdate DATE, -- 签收日期
shipinstruct CHAR(25), -- 装运说明
shipmode CHAR(10), -- 装运方式
comment VARCHAR(44), -- 备注
PRIMARY KEY (orderkey , linenumber),
FOREIGN KEY (partkey , suppkey)
REFERENCES PartSupp (partkey , suppkey)
);
|
Shell
|
UTF-8
| 3,779 | 3 | 3 |
[] |
no_license
|
#!/bin/sh
set -eu
if [ $# -eq 1 ]; then
re='^[0-9]+$'
if ! [[ $1 =~ $re ]] ; then
echo "Invalid number of cores" >&2; exit 1
fi
jobs=$1
else
jobs=$(sysctl -n hw.logicalcpu_max)
fi
curl -fsSL "https://zlib.net/zlib-$ZLIB_VERSION.tar.gz" -o zlib-$ZLIB_VERSION.tar.gz
shasum -a 256 zlib-$ZLIB_VERSION.tar.gz && \
echo "$ZLIB_HASH zlib-$ZLIB_VERSION.tar.gz" | shasum -a 256 -c - && \
tar -xvzf zlib-$ZLIB_VERSION.tar.gz
cd zlib-$ZLIB_VERSION
./configure --prefix=$PWD/root
make ${jobs:+-j${jobs}} && make ${jobs:+-j$jobs} check && make install
cd ..
curl -fsSL "https://www.openssl.org/source/openssl-$OPENSSL_VERSION.tar.gz" -o openssl-$OPENSSL_VERSION.tar.gz && \
echo "$OPENSSL_HASH openssl-$OPENSSL_VERSION.tar.gz" | shasum -a 256 -c - && \
tar -xvzf openssl-$OPENSSL_VERSION.tar.gz && \
cd openssl-$OPENSSL_VERSION && \
./Configure --prefix=$PWD/root darwin64-x86_64-cc no-shared no-dso && \
make ${jobs:+-j${jobs}} && make install
cd ..
curl -fsSL "https://github.com/libevent/libevent/releases/download/release-$LIBEVENT_VERSION/libevent-$LIBEVENT_VERSION.tar.gz" -o libevent-$LIBEVENT_VERSION.tar.gz && \
curl -fsSL "https://github.com/libevent/libevent/releases/download/release-$LIBEVENT_VERSION/libevent-$LIBEVENT_VERSION.tar.gz.asc" -o libevent-$LIBEVENT_VERSION.tar.gz.asc && \
#Apple messed up getentropy and clock_gettimesymbols when they added two functions in Sierra:
#they forgot to decorate them with appropriate AVAILABLE_MAC_OS_VERSION checks.
#So we have to explicitly disable them for binaries to work on MacOS 10.11.
# Using test/regress.c from a local repo because make check hangs in libevent
# See: https://github.com/libevent/libevent/issues/747 for more details
# Updated test/regress.cc disables: immediatesignal | signal_switchbase
# | signal_while_processing tests
# Updated test/regress_bufferevent.c disables: test_bufferevent_pair_release_lock
gpg --import gpg-keys/libevent.gpg && \
gpg libevent-$LIBEVENT_VERSION.tar.gz.asc && \
echo "$LIBEVENT_HASH libevent-$LIBEVENT_VERSION.tar.gz" | shasum -a 256 -c - && \
tar -zxvf libevent-$LIBEVENT_VERSION.tar.gz && \
cp patch/libevent/test/regress.c libevent-$LIBEVENT_VERSION/test/regress.c && \
cp patch/libevent/test/regress_bufferevent.c libevent-$LIBEVENT_VERSION/test/regress_bufferevent.c && \
cd libevent-$LIBEVENT_VERSION && \
./configure \
LDFLAGS="-L$PWD/../openssl-$OPENSSL_VERSION/root" \
CPPFLAGS="-I$PWD/../openssl-$OPENSSL_VERSION/include" \
--prefix=$PWD/install \
--disable-shared \
--enable-static \
--disable-clock-gettime \
--with-pic && \
make ${jobs:+-j${jobs}} && make check && make install
cd ..
curl -fsSL "https://www.torproject.org/dist/tor-$TOR_VERSION.tar.gz" -o tor-$TOR_VERSION.tar.gz
curl -fsSL "https://www.torproject.org/dist/tor-$TOR_VERSION.tar.gz.asc" -o tor-$TOR_VERSION.tar.gz.asc
gpg --import gpg-keys/tor.gpg && \
gpg tor-$TOR_VERSION.tar.gz.asc && \
echo "$TOR_HASH tor-$TOR_VERSION.tar.gz" | shasum -a 256 -c - && \
tar -xvzf tor-$TOR_VERSION.tar.gz && \
cd tor-$TOR_VERSION && \
./configure --prefix=$PWD/root \
--enable-static-libevent \
--enable-static-openssl \
--enable-static-zlib \
--with-libevent-dir=$PWD/../libevent-$LIBEVENT_VERSION/install \
--with-openssl-dir=$PWD/../openssl-$OPENSSL_VERSION/root \
--with-zlib-dir=$PWD/../zlib-$ZLIB_VERSION/root \
--disable-asciidoc \
--disable-lzma \
ac_cv_func_getentropy=no \
ac_cv_func_clock_gettime=no && \
make ${jobs:+-j${jobs}} && make ${jobs:+-j${jobs}} check && make install
cd ..
cp tor-$TOR_VERSION/root/bin/tor tor-$TOR_VERSION-darwin-brave-$BRAVE_TOR_VERSION
|
Shell
|
UTF-8
| 149 | 2.53125 | 3 |
[] |
no_license
|
#!/bin/bash
FP="./_posts/$(date +%Y-%m-%d)-$1.md"
echo "---" >> $FP
echo "layout: post" >> $FP
echo "title: $1" >> $FP
echo "---" >> $FP
vim $FP
|
C++
|
UTF-8
| 378 | 2.5625 | 3 |
[] |
no_license
|
/* Copyright G. Hemingway @ 2019, All Rights Reserved */
#include "Composite_Binary_Node.h"
// Ctor
Composite_Binary_Node::Composite_Binary_Node(Component_Node* left, Component_Node* right)
: Composite_Unary_Node(right)
, leftChild(left)
{
}
// Return the left child pointer
Component_Node* Composite_Binary_Node::left() const
{
return leftChild.get();
}
|
JavaScript
|
UTF-8
| 1,476 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
"use strict";
import React from 'react';
import { LunchGroupList } from '../components/LunchGroupList';
import LunchGroupService from '../services/LunchGroupService';
export class LunchGroupsListView extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: false,
data: []
};
}
componentWillMount(){
this.setState({
loading: true
});
LunchGroupService.getLunchGroups().then((data) => {
this.setState({
data: [...data],
loading: false
});
}).catch((e) => {
console.error(e);
});
}
/*
deleteMovie(id) {
this.setState({
data: [...this.state.data],
loading: true
});
LunchGroupService.deleteMovie(id).then((message) => {
let movieIndex = this.state.data.map(movie => movie['_id']).indexOf(id);
let movies = this.state.data;
movies.splice(movieIndex, 1);
this.setState({
data: [...movies],
loading: false
});
}).catch((e) => {
console.error(e);
});
}
*/
render() {
if (this.state.loading) {
return (<h2>Loading...</h2>);
}
return (
<LunchGroupList data={this.state.data} onDelete={(id) => this.deleteMovie(id)}/>
);
}
}
|
Java
|
UTF-8
| 6,813 | 1.5 | 2 |
[] |
no_license
|
package org.apache.jsp.view;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class signup_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.List<String> _jspx_dependants;
private org.glassfish.jsp.api.ResourceInjector _jspx_resourceInjector;
public java.util.List<String> getDependants() {
return _jspx_dependants;
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html;charset=UTF-8");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
_jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("<!DOCTYPE html>\n");
out.write("<!--\n");
out.write("To change this license header, choose License Headers in Project Properties.\n");
out.write("To change this template file, choose Tools | Templates\n");
out.write("and open the template in the editor.\n");
out.write("-->\n");
out.write("<html>\n");
out.write(" <head>\n");
out.write(" <title>Sign up to STAR</title>\n");
out.write(" <meta charset=\"UTF-8\">\n");
out.write(" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n");
out.write(" <link href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T\" crossorigin=\"anonymous\">\n");
out.write(" \n");
out.write(" <style>\n");
out.write(" #center{\n");
out.write(" text-align: center;\n");
out.write(" background: linear-gradient(to bottom, rgba(34,86,158,1), rgba(96,147,223,1)) center center no-repeat;\n");
out.write(" }\n");
out.write(" \n");
out.write(" img{\n");
out.write(" height: 250px;\n");
out.write(" width: 250px;\n");
out.write(" }\n");
out.write(" \n");
out.write(" #bgimg{\n");
out.write(" background-image: url(\"img/sign.png\");\n");
out.write(" background-position: center;\n");
out.write(" background-repeat: no-repeat;\n");
out.write(" background-size: cover;\n");
out.write(" }\n");
out.write(" \n");
out.write(" label{\n");
out.write(" color: white;\n");
out.write(" }\n");
out.write(" \n");
out.write(" \n");
out.write(" </style>\n");
out.write(" \n");
out.write(" </head>\n");
out.write(" <body id=\"bgimg\">\n");
out.write(" <div id=\"center\" class=\"jumbotron\" >\n");
out.write(" <img src=\"img/logo.jpg\" alt=\"logo\">\n");
out.write(" <h1>Sign Up</h1>\n");
out.write(" <p>Hello people Register to the STAR service here. Get your best solution for mental issues you are going through...</p>\n");
out.write(" </div>\n");
out.write(" \n");
out.write(" <div class=\"container\">\n");
out.write(" \n");
out.write(" <div class=\"row\">\n");
out.write("\n");
out.write(" <div class=\"col-md-4\"> \n");
out.write(" \n");
out.write(" \n");
out.write(" <form action=\"../signupController\" method=\"post\">\n");
out.write(" <div class=\"form-group\">\n");
out.write(" <label>Full Name : </label><br>\n");
out.write(" <input type=\"text\" name=\"name\" class=\"form-control\"> <br>\n");
out.write("\n");
out.write(" <label>Email : </label><br>\n");
out.write(" <input type=\"text\" name=\"email\" class=\"form-control\"> <br>\n");
out.write("\n");
out.write(" <label>Password : </label><br>\n");
out.write(" <input type=\"password\" name=\"pass\" class=\"form-control\"> <br>\n");
out.write("\n");
out.write(" <label>Phone No. : </label><br>\n");
out.write(" <input type=\"text\" name=\"phone\" class=\"form-control\"><br>\n");
out.write("\n");
out.write(" <button type=\"submit\" class=\"btn btn-success\">Sign Up</button>\n");
out.write(" </div>\n");
out.write(" </form>\n");
out.write("\n");
out.write(" </div>\n");
out.write("\n");
out.write(" <div class=\"col-md-4\">\n");
out.write(" \n");
out.write(" </div>\n");
out.write(" \n");
out.write(" <div class=\"col-md-3\"> \n");
out.write("\n");
out.write("\n");
out.write(" </div>\n");
out.write(" \n");
out.write(" \n");
out.write(" </div>\n");
out.write(" </div>\n");
out.write(" </body>\n");
out.write("</html>\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
|
Java
|
UTF-8
| 465 | 2.6875 | 3 |
[
"Apache-2.0"
] |
permissive
|
package com.bluecatcode.common.base;
/**
* @see java.util.concurrent.Callable
* @see com.bluecatcode.common.base.Consumer
* @see com.bluecatcode.common.base.Effect
* @see com.google.common.base.Function
* @see com.google.common.base.Predicate
* @see com.google.common.base.Supplier
*/
public interface Block<T> {
/**
* Performs this operation returning value.
*
* @throws RuntimeException if unable to compute
*/
T execute();
}
|
Shell
|
UTF-8
| 825 | 3.8125 | 4 |
[] |
no_license
|
echo "Running unit tests"
# create a header for this run in the log
echo "\n" >> tests/tests.log
echo "Starting Test Suite "$(date) >> tests/tests.log
echo "================================================" >> tests/tests.log
for tf in tests/*_tests; do
if test -f $tf; then
# Create a header for this file in the log
# run the test, adding to log, and if exit code is non-zero
# give an error message & abort.
if $VALGRIND ./${tf} 2 >> tests/tests.log; then
echo "$tf PASS"
else
echo "ERROR in test $tf! Here's tests/test.log:"
tail tests/tests.log
exit 1 # I'm not sure I agree with this... sometimes it's useful
# to see a full set of which tests failed in a regression.
fi
fi
done
echo ""
|
SQL
|
UTF-8
| 161 | 3.46875 | 3 |
[] |
no_license
|
SELECT object.MEDIUM, country.COUNTRY
FROM
object NATURAL JOIN country_object NATURAL JOIN country
GROUP BY country.countryid
ORDER BY COUNT(0) DESC
LIMIT 10
|
Java
|
UTF-8
| 641 | 2.828125 | 3 |
[] |
no_license
|
package array;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Random;
public class ArraysSortTest {
public static void main(String[] args) {
String token = "4gService";
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String timestamp = sdf.format(date);
String nonce = String.valueOf(new Random().nextInt(100));
String[] arr = new String[]{token, timestamp, nonce};
Arrays.sort(arr);
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
|
Java
|
UTF-8
| 1,362 | 2.375 | 2 |
[
"Apache-2.0"
] |
permissive
|
package denominator.common;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static denominator.common.Preconditions.checkArgument;
import static denominator.common.Preconditions.checkNotNull;
import static denominator.common.Preconditions.checkState;
import static org.assertj.core.api.Assertions.assertThat;
public class PreconditionsTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test
public void checkArgumentFormatted() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("should be foo");
checkArgument(false, "should be %s", "foo");
}
@Test
public void checkArgumentPass() {
checkArgument(true, "should be %s", "foo");
}
@Test
public void checkStateFormatted() {
thrown.expect(IllegalStateException.class);
thrown.expectMessage("should be foo");
checkState(false, "should be %s", "foo");
}
@Test
public void checkStatePass() {
checkState(true, "should be %s", "foo");
}
@Test
public void checkNotNullFormatted() {
thrown.expect(NullPointerException.class);
thrown.expectMessage("should be foo");
checkNotNull(null, "should be %s", "foo");
}
@Test
public void checkNotNullPass() {
assertThat(checkNotNull("foo", "should be %s", "foo")).isEqualTo("foo");
}
}
|
Python
|
UTF-8
| 1,545 | 2.703125 | 3 |
[] |
no_license
|
from flask import Flask, request, redirect, url_for, render_template
from flask_login import LoginManager, login_user, logout_user, current_user, login_required
from models import User, query_user
# https://www.jianshu.com/p/01384ee741b6
app = Flask(__name__)
app.secret_key = '1234567'
login_manager = LoginManager()
login_manager.login_view = 'login'
login_manager.login_message_category = 'info'
login_manager.login_message = '请登录后台'
login_manager.init_app(app)
@login_manager.user_loader
def load_user(user_id):
if query_user(user_id) is not None:
curr_user = User()
curr_user.id = user_id
return curr_user
@app.route('/')
@login_required
def index():
return 'Logged in as: %s' % current_user.get_id()
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
user_id = request.form.get('userid')
user = query_user(user_id)
if user is not None and request.form['password'] == user['password']:
curr_user = User()
curr_user.id = user_id
# 通过Flask-Login的login_user方法登录用户
login_user(curr_user)
return redirect(url_for('index'))
flash('Wrong username or password!')
# GET 请求
return render_template('login.html')
@app.route('/logout')
@login_required
def logout():
logout_user()
return 'Logged out successfully!'
if __name__ == '__main__':
app.run(debug=True)
|
Markdown
|
UTF-8
| 5,966 | 2.984375 | 3 |
[
"MIT"
] |
permissive
|
---
layout: blog
categories:
- blog
title: "Chi Hack Night's Open Data Pledge for Cook County Clerk of the Circuit Court"
description: "With the initial success of our open data pledge for Cook County State’s Attorney, Chi Hack Night is turning our attention to another important county race. We’re inviting every candidate for Cook County Clerk of the Circuit Court to sign a pledge to, if elected, commit their office to publish open data."
date: 2016-02-16
image: /images/blog/2016-02-16-chi-hack-nights-open-data-pledge-for-cook-county-clerk-of-the-circuit-court/clerk-of-the-circuit-court-candidates.jpg
author: Derek Eder
author_url: https://twitter.com/derekeder
author_image: /images/people/derek_eder.jpg
author_bio: "Derek is an entrepreneur, developer and one of the leaders of the civic technology community in Chicago. He is a co-founder and partner at DataMade — a company that tells stories and builds tools with data — and is the lead organizer for Chi Hack Night."
author2:
author2_url:
author2_image:
published: false
---
<p class="text-center"><img src="/images/blog/2016-02-16-chi-hack-nights-open-data-pledge-for-cook-county-clerk-of-the-circuit-court/clerk-of-the-circuit-court-candidates.jpg" alt="Candidates for Cook County Clerk of the Circuit Court: Jacob Meister (D), Dorothy A. Brown (D), Michelle A. Harris (D) and Diane S. Shapiro (R)" class="img-thumbnail" /><br />
<small>
<em>Candidates for Cook County Clerk of the Circuit Court
<br />Jacob Meister (D), Dorothy A. Brown (D), Michelle A. Harris (D) and Diane S. Shapiro (R)
<br />Photo by Nancy Stone, Antonio Perez, <a href='http://www.chicagotribune.com/news/local/politics/ct-cook-county-circuit-court-clerk-poll-0202-20160201-story.html'>Chicago Tribune</a>
</em>
</small>
</p>
With the initial success of our [open data pledge for Cook County State's Attorney](/blog/2016/02/12/chi-hack-nights-open-data-pledge-for-cook-county-states-attorney.html), Chi Hack Night is turning our attention to another important county race. We're inviting every candidate for Cook County Clerk of the Circuit Court to sign a pledge to, if elected, commit their office to publish open data.
Below is the invitation to all candidates, as well as the text of the Open Data Pledge.
### Candidate responses
* <span style='color: #009538;'><i class='fa fa-fw fa-check'></i></span> **Jacob Meister** (D) - Signed on February 22, 2016
* <span style='color: #F01B16;;'><i class='fa fa-fw fa-circle-o'></i></span> Dorothy A. Brown (D) - No response
* <span style='color: #F01B16;;'><i class='fa fa-fw fa-circle-o'></i></span> Michelle A. Harris (D) - No response
* <span style='color: #F01B16;;'><i class='fa fa-fw fa-circle-o'></i></span> Diane S. Shapiro (R) - No response
### What does the Clerk of the Circuit Court do?
The Clerk of the Circuit Court is the official keeper of records for the [Circuit Court of Cook County](https://en.wikipedia.org/wiki/Circuit_Court_of_Cook_County), the second largest court system in the United States. The court manages over 2.4 million cases every year. The Clerk’s office is responsible for managing an [annual operating budget of $96 million](http://lookatcook.com/#!/?year=2015&fund=&controlOfficer=Clerk+of+the+Circuit+Court) and has a workforce of over 1,800 employees. Dorothy Brown is the current officeholder.
Records maintained by the Clerk are not subject to the Freedom of Information Act (FOIA). Although the court implemented an electronic filing system several years ago, their [open records policy](http://www.cookcountyclerkofcourt.org/gifs/PUBLICACCESS.pdf) only covers records in hard copy paper format and all records requests must be filed in person or by fax.
[Modernization of the court system](https://www.civicfed.org/civic-federation/whycareaboutcookcounty) remains an ongoing issue. Sometimes critical court papers [have gone missing](http://www.huffingtonpost.com/2013/10/24/cook-county-clerk-office_n_4156061.html). A modern, transparent open data policy would contribute to the push for a modern court system with [better communication, fewer errors, and lower costs](http://articles.chicagotribune.com/2013-10-04/news/ct-perspec-1004-zorn-20131004_1_justice-system-writ-branch-court).
### Invitation to all candidates
To: Dorothy A. Brown, Michelle A. Harris, Jacob Meister<br />
From: Derek Eder, Chi Hack Night<br />
Date: Feb 16, 2016<br />
Subject: Open Data Pledge for Cook County Clerk of the Circuit Court
Chi Hack Night ([http://chihacknight.org/](http://chihacknight.org/)) is a group of thousands of designers, academic researchers, data journalists, activists, policy wonks, web developers and curious citizens who strive to make our city more just, equitable, transparent and delightful to live in through data, design and technology.
We volunteer every week to build tools to support and serve the public good. Open government data makes it possible for us to do this work.
Chi Hack Night is inviting every candidate for Cook County Clerk of the Circuit Court to sign a pledge (attached) to, if elected, commit their office to publish open data.
Please sign and return the pledge to Derek Eder at derek@derekeder.com or by phone at (503) 577-0677.
Sincerely,<br />
Derek Eder<br />
Lead Organizer, Chi Hack Night
### Open Data Pledge
Here is the open data pledge, with signatures from the candidates collected so far.
<p class="text-center">
<a href='/docs/CookCountyClerkoftheCircuitCourt-OpenDataPledge-Meister.pdf'><img src="/images/blog/2016-02-16-chi-hack-nights-open-data-pledge-for-cook-county-clerk-of-the-circuit-court/open-data-pledge.jpg" alt="Open Data Pledge for Cook County State's Attorney" class="img-thumbnail" /></a>
<br />
<a href='/docs/CookCountyClerkoftheCircuitCourt-OpenDataPledge-Meister.pdf'>Download the pledge (PDF)</a>
</p>
You can also <a href='https://docs.google.com/document/d/14C1AYK0YRYakXffUDdgc-PPYziUuVs7GJL_hUY6Ain8/edit'>view the original pledge in Google Docs</a>.
The open data pledge was drafted by Steve Ediger, Steven Vance and Derek Eder, with contributions by Rebecca Williams, Dominic Mauro, Christopher Whitaker, David Morrison and Eric Sherman.
|
JavaScript
|
UTF-8
| 1,030 | 2.609375 | 3 |
[] |
no_license
|
var React = require('react');
var UserSignIn = (props) => {
return (
<div className="signin input">
Sign In
<form onSubmit={props.postToSignin}>
<input type='text' id='username' placeholder = 'username' name='usernameInSignin' onChange={props.handleUsernameChange} required/>
<input type='password' id='userpw' placeholder = 'password' name='passwordInSignin' onChange={props.handleUsernameChange} required/>
<button>Sign In</button>
<IncorrectLogin displayMessage={props.incorrectLogin} message={'Not a valid username and password combination'}/>
</form>
</div>
);
}
// PropTypes tell other developers what `props` a component expects
// Warnings will be shown in the console when the defined rules are violated
UserSignIn.propTypes = {
user: React.PropTypes.array.isRequired
};
// In the ES6 spec, files are "modules" and do not share a top-level scope.
// `var` declarations will only exist globally where explicitly defined.
window.UserSignIn = UserSignIn;
|
Python
|
UTF-8
| 4,669 | 2.875 | 3 |
[] |
no_license
|
from yaml import dump
try:
from yaml import CDumper as Dumper
except ImportError:
from yaml import Dumper
import pdb
import re
import logging
from os import path
import sys
import bs4
from .corpus import Queryable
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler(sys.stdout))
def ottawa_university_preprocessor(infile_path, outfile_path):
return OttawaUniversityPreProcessor(infile_path, outfile_path)
# OttawaUniversityPreProcessor performs the end-to-end work of performing the ETL
# work of preparing the corpus of documents to be used by the search engine.
class OttawaUniversityPreProcessor:
# Constructor takes an infile handle representing the raw, uncleaned, input
# and an outfile handle to which the cleaned and processed corpus will be written
def __init__(self, infile_path, outfile_path):
self.infile_path = infile_path
self.outfile_path = outfile_path
self.corpus = []
self.ignored = 0
def preprocess(self):
if path.exists(self.outfile_path):
logger.info(
f"Target corpus ({self.outfile_path}) already exists, skipping preprocessing."
)
return
self._generate_corpus()
print(
f"Found {len(self.corpus)} entries out of a total of {len(self.corpus) + self.ignored}",
"(either missing course description or french course)",
)
self.write_outfile()
def write_outfile(self):
outfile = self._outfile()
for corpus in self.corpus:
dump(
corpus,
outfile,
explicit_start=True,
default_flow_style=False,
sort_keys=False,
indent=2,
Dumper=Dumper,
)
def _generate_corpus(self):
doc = bs4.BeautifulSoup(self._infile().read(), "html.parser")
divs = doc.find_all("div", {"class": "courseblock"})
for raw in divs:
faculty, code, title = self._parse_course_code_and_title(raw)
contents = self._parse_course_description(raw)
course = Course(faculty, code, title, contents)
if course.is_ignored():
self.ignored += 1
continue
self.corpus.append(Document(course))
def _parse_course_code_and_title(self, raw):
title_blocks = raw.find_all("p", attrs={"class": "courseblocktitle"})
if len(title_blocks) != 1:
raise Exception(
"Expected only a single p.courseblocktitle element per document"
)
match = re.search(
r"^([A-Z]{3})\s*([0-9]{4,}\S?)\s+(.*)", title_blocks[0].string
)
if match is None:
raise Exception(f"Couldn't parse course code from {title_blocks[0].string}")
else:
# We expect the faculty code, course code, and title, otherwise fail
assert len(match.groups()) == 3
return match.groups()
def _parse_course_description(self, raw):
descriptions = raw.find_all("p", {"class": "courseblockdesc"})
if len(descriptions) > 1:
raise Exception(
f"Expected only a single courseblockdesc paragraph, but got: {descriptions}"
)
elif len(descriptions) == 0:
return None
return descriptions[0].text.strip()
def _infile(self):
return open(self.infile_path, "r")
def _outfile(self):
return open(self.outfile_path, "w")
# Document objects represent preprocessed objects, ready to be written to the corpus
class Document(Queryable):
DocID = 0
def __init__(self, course):
self.id = Document.next_id()
self.course = course
def __str__(self):
return f"ID: {self.id}, Course: {self.course.faculty} {self.course.code} {self.course.title}"
def read_queryable(self):
return self.course.contents
@staticmethod
def next_id():
Document.DocID += 1
return Document.DocID
# Course is a simple wrapper around the course code of a given class
class Course:
def __init__(self, faculty, code, title, contents):
self.faculty = faculty
self.code = code
self.title = title
self.contents = contents
def __str__(self):
return f"{self.faculty} {self.code}: {self.title}\n{self.contents}"
# We ignore french courses, which are denoted by having the number 5 or 7 in the hundreds digit
def is_ignored(self):
return self.code[1] == "5" or self.code[1] == "7" or self.contents is None
|
Python
|
UTF-8
| 2,123 | 2.609375 | 3 |
[] |
no_license
|
import pandas as pd
from requests import get
from bs4 import BeautifulSoup
import os
################################ Acquire Blogs #################################
def get_blogs(websites, cached = False):
if cached == True:
blogs = pd.read_json('blogs.json')
else:
blogs = []
for blog in websites:
headers = {'User-Agent': 'Codeup Data Science'}
response = get(blog, headers=headers)
soup = BeautifulSoup(response.text, "html.parser")
page = soup.find('div', class_='jupiterx-post-content')
article = {'title':[], 'body':[]}
article['title'] = soup.title.string
article['body'] = page.text
blogs.append(article)
blogs = pd.DataFrame(blogs)
blogs.to_json('blogs.json')
return blogs
################################ Acquire Codeup Blog Articles #################################
def get_inshorts(websites, cached=False):
if cached == True:
articles = pd.read_json('articles.json')
else:
articles = []
for article in websites:
article_dict = {'headline':'','author':'','date':'','article':'','category':''}
headers = {'User-Agent': 'Inshorts'}
data = get(article, headers)
soup = BeautifulSoup(data.text, "html.parser")
article_structure['title'] = soup.find('span', attrs={"itemprop": "headline"}).string
article_structure['author'] = soup.find('span', attrs={"author"}).string
article_structure['body'] = soup.find('div', attrs={"itemprop": "articleBody"}).string
article_structure['date'] = soup.find('span', attrs={"date"}).string
article_structure['category'] = url.split('/')[-2]
articles.append(article_structure)
articles = pd.DataFrame(articles)
articles = articles[['title', 'author','body','date', 'category']]
articles.to_json('articles.json')
return articles
|
Python
|
UTF-8
| 2,790 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
import discord
from discord.ext import commands
import random
import config
description = '''Bot for Kugu discord, all questions should be directed to "Kirsty (Princess Vamps)"'''
bot = commands.Bot(command_prefix='!', description=description)
@bot.event
async def on_ready():
print('Logged in as')
print(bot.user.name)
print(bot.user.id)
print('------')
bot.activeServer = bot.get_server(config.serverID)
@bot.command()
async def list():
"""Lists the channels you can join"""
roles = ""
for role in bot.activeServer.roles:
if (role.name.startswith("auto_")):
roles = "{}*{}\n".format(roles,role.name[5:])
await bot.say('You may join any of the listed groups by typing ``!join channelName``\n{}'.format(roles))
@bot.command(pass_context=True)
async def join(ctx,*groups):
"""Join a discord group (channel). If you want to join multiple groups, then separate the names via a space."""
acceptedRoles = []
user = ctx.message.author
for attemptedGroup in groups:
attemptedGroup = attemptedGroup.lower()
for role in bot.activeServer.roles:
if role.name == "auto_{}".format(attemptedGroup):
try:
await bot.add_roles(user,role)
acceptedRoles.append(role.name[5:])
except Exception as e:
print(e)
continue
if not acceptedRoles:
await bot.say('Could not find any channels with those names')
else:
await bot.say('You joined {}'.format(', '.join(acceptedRoles)))
@bot.command(pass_context=True)
async def leave(ctx,*groups):
"""Leave a discord group (channel). If you want to leave multiple groups, then separate the names via a space."""
acceptedRoles = []
user = ctx.message.author
for attemptedGroup in groups:
attemptedGroup = attemptedGroup.lower()
for role in bot.activeServer.roles:
if role.name == "auto_{}".format(attemptedGroup):
try:
await bot.remove_roles(user,role)
acceptedRoles.append(role.name[5:])
except Exception as e:
print(e)
continue
if not acceptedRoles:
await bot.say('Could not find any channels with those names')
else:
await bot.say('You left {}'.format(', '.join(acceptedRoles)))
@bot.command(pass_context=True)
async def groups(ctx):
"""Lists the discord groups (channels) you are in."""
acceptedRoles = []
user = ctx.message.author
for role in user.roles:
if (role.name.startswith("auto_")):
acceptedRoles.append(role.name[5:])
await bot.reply('You are in {}'.format(', '.join(acceptedRoles)))
bot.run(config.token)
|
Java
|
UTF-8
| 1,186 | 3.03125 | 3 |
[] |
no_license
|
import com.crosswords.controlers.Generator;
import com.crosswords.controlers.GeneratorThread;
/**
* Created by Mariusz on 2014-05-18.
*/
public class Algorithm {
public static char[][] generate(String[] args) {
char[][] matrix=null;
try {
int maxWordsCount = 0;
int maxSizeVertical = Integer.parseInt(args[1]);
int maxSizeHorizontal = Integer.parseInt(args[0]);
Generator gen = new Generator();
GeneratorThread gt = gen.generate(maxWordsCount, maxSizeVertical, maxSizeHorizontal);
matrix = gt.getMatrix();
int minY = gt.getMinY();
int maxY = gt.getMaxY();
int minX = gt.getMinX();
int maxX = gt.getMaxX();
for (int y = minY; y <= maxY; y++) {
for (int x = minX; x <= maxX; x++) {
if (matrix[x][y] == '\u0000') System.out.print(' ');
else
System.out.print(matrix[x][y]);
}
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
}
return matrix;
}
}
|
C
|
GB18030
| 2,401 | 3.265625 | 3 |
[] |
no_license
|
#include"game.h"
void InitArray(char board[ROW][COL], int row, int col)
{
int i = 0;
int j = 0;
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
board[i][j] = ' ';
}
}
}
void PrintArray(char board[ROW][COL], int row, int col)
{
int i = 0;
int j = 0;
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
printf("%c ", board[i][j]);
}
}
printf("\n");
}
// | |
//---|---|---
// | |
//---|---|---
// | |
void DisPlayboard(char board[ROW][COL], int row, int col)
{
int i = 0;
for (i = 0; i < row; i++)
{
//ӡһֵ
int j = 0;
for (j = 0; j < col; j++)
{
printf(" %c ", board[i][j]);
if (j < col - 1)
printf("|");
}
printf("\n");
//ָ
if (i < row - 1)
{
for (j = 0; j < col; j++)
{
printf("---");
if (j < col - 1)
printf("|");
}
printf("\n");
}
}
}
void PlayMove(char board[ROW][COL], int row, int col)
{
int x, y;
printf(":");
while (1)
{
scanf("%d %d", &x, &y);
//жӺϷ
if (x >= 1 && x <= row&&y >= 1 && y <= col)
{
if (board[x - 1][y - 1] == ' ')
{
board[x - 1][y - 1] = '#';
break;
}
else {
printf("걻ռ,:");
}
}
else
{
printf("Ƿ:\n");
}
}
}
int IsFull(char board[ROW][COL], int row, int col)
{
int i = 0;
int j = 0;
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
if (board[i][j] == ' ')
return 0;
}
}
return 1;
}
void PlayComputer(char board[ROW][COL], int row, int col)
{
int x, y;
printf(":\n");
while (1)
{
x = rand() % row;
y = rand() % col;
if (x >= 0 && y >= 0 && board[x][y] == ' ')
{
board[x][y] = '@';
break;
}
}
}
char IsWin(char board[ROW][COL], int row, int col)
{
int i = 0;
for (i = 0; i < row; i++)
{
if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][1] != ' ')
return board[i][1];
}
for (i = 0; i < col; i++)
{
if (board[0][i] == board[1][i] && board[1][i] == board[2][i] && board[1][i] != ' ')
return board[1][i];
}
if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[1][1] != ' ')
return board[1][1];
if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[1][1] != ' ')
return board[1][1];
if (1 == IsFull(board, ROW, COL))
return 'Q';
return 'C';
}
|
Markdown
|
UTF-8
| 717 | 3.453125 | 3 |
[
"MIT"
] |
permissive
|
# Usecase
The following homework is to apply the learning of using an iterator for dealing a deck of cards. It is very similar to the lab for cards, however, you will need to:
1. Create the cards in a ArrayList.
2. Have a class variable that is the iterator of the ArrayList.
You will use the iterator to do the dealing of the cards.
# You TODO
1. Create a file called DeckIteratorImpl.
2. Implement the Deck interface (supplied) on the DeckIteratorImpl file.
3. Implement the business logic using an ArrayList and Iterator.
4. Uncomment the code in the DockerIteratorTest file.
5. Make sure that all the tests run in the DeckIteratorTest (the same tests as DeckTest file has) and pass against the DeckIteratorImpl.
|
C++
|
UTF-8
| 798 | 2.953125 | 3 |
[] |
no_license
|
#include "../Headers/Modyst.h"
#include <sstream>
namespace Text
{
//Enables a modificator in a string
std::string setMod(Code code)
{
std::stringstream stst;
stst << "\033[" << code << "m";
return stst.str();
}
//Disable a modificator in a string
std::string clearMod(Code code)
{
std::stringstream stst;
stst << "\033[2" << code << "m";
return stst.str();
}
//Enables, then disables a modificator in a string
std::string textEffect(Code code, std::string text)
{
std::stringstream stst;
stst << setMod(code) << text << clearMod(code);
return stst.str();
}
//Disable all modificators in a string
std::string clearMods()
{
return setMod(DEFAULT);
}
}
|
Python
|
UTF-8
| 2,047 | 2.59375 | 3 |
[] |
no_license
|
import torch
from torchvision.utils import make_grid
from torchvision.transforms import ToTensor
from torchvision.datasets import MNIST, ImageFolder
from torch.utils.data.dataloader import DataLoader
from torch.utils.data import random_split
import matplotlib.pyplot as plt
import numpy as np
def get_data(batch_size, val_percentage=0.2):
#data_dir = '../data/cifar10'
#dataset = ImageFolder(data_dir + "/train", transform=ToTensor())
dataset = MNIST(root="../data", transform=ToTensor())
img, _ = dataset[0]
input_size = np.prod(img.shape)
print("len dataset=", len(dataset))
validation_size = int(len(dataset)*val_percentage)
train_size = len(dataset) - validation_size
print("train_size=", train_size, ", validation_size=", validation_size)
train_ds, val_ds = random_split(dataset, [train_size, validation_size])
train_loader = DataLoader(train_ds, batch_size, shuffle=True, num_workers=4, pin_memory=True)
val_loader = DataLoader(val_ds, batch_size*2, num_workers=4, pin_memory=True)
return train_loader, val_loader, input_size
def get_images(imgs, labels):
num_images = int(len(imgs)/2)
imgsa = imgs[:num_images]
imgsb = imgs[num_images:]
imgsa_receiver = torch.empty(imgsa.shape)
imgsb_receiver = torch.empty(imgsa.shape)
labels_target = torch.tensor(np.random.randint(2, size=num_images))
targets = torch.tensor(np.random.randint(2, size=num_images))
for i in range(num_images):
labels_target[i] = labels[i]
if targets[i]==0:
imgsa_receiver[i] = imgsa[i]
imgsb_receiver[i] = imgsb[i]
else:
imgsa_receiver[i] = imgsb[i]
imgsb_receiver[i] = imgsa[i]
return imgsa, imgsb, imgsa_receiver, imgsb_receiver, targets, labels_target
def show_batch(dl):
for imgs, labs in dl:
fig, ax = plt.subplots(figsize=(10,10))
ax.set_xticks([])
ax.set_yticks([])
ax.imshow(make_grid(imgs, 10).permute(1,2,0))
plt.show()
break
|
Markdown
|
UTF-8
| 1,062 | 2.8125 | 3 |
[] |
no_license
|
# immobilienscout24
immobilienscout24 Technical Challenge
### Technologies used
* Java 8
* Library
* Jsoup (HTML Parser)
* Guava (Util library)
* Apache commons-validator (Util library)
* Spring-boot (Application)
* Thymeleaf (Template engine)
* Bootstrap (CSS)
### Run the Application
You can package and run the backend application by executing the following command:
```
#!bash
mvn package spring-boot:run
```
This will start an instance running on the default port `8080`.
You can also build a single executable JAR file that contains all the necessary dependencies, classes, and resources, and run that.
The JAR file will be create by executing the command `mvn package`, and the JAR file will be located under target directory.
Then you can run the JAR file:
```
java -jar target/HtmlProcessor-1.0-SNAPSHOT.jar
```
After successfully running the application, you can now open your browser with the following url:
```
http://localhost:8080/htmlinfo
```
Now you can start analyzing the url you want. For example: `https://www.github.com`.
|
Python
|
UTF-8
| 1,647 | 2.859375 | 3 |
[] |
no_license
|
import torch
import matplotlib.pyplot as plt
from data_handler import DataHandler
def display(config_path, model_path):
data_handler = DataHandler(config_path)
height, width = data_handler.raw_image.shape
model = torch.load(model_path)
predicted_image = model(data_handler.torch_data["features"]).detach().numpy().reshape(height, width)
plt.imshow(predicted_image, cmap="gray")
plt.show()
# # Display preprocessing:
#
# for count, element in enumerate(formatted):
# print(f"int16 representation: {int(element, 2)}\n"
# f"16 bits binary representation: {element}\n"
# f"Hexadecimal representation: {hex(int(element, 2))}\n"
# f"8 bits hexadecimal representation: {hex(int(element[:8], 2))}\n")
# if count == 5:
# break
#
# # Display histograms
#
# images = [clipped_image, normalized_image, equalized_image, adapt_equalized_image]
#
# fig = plt.figure()
# gs = fig.add_gridspec(2, 2, hspace=0, wspace=0)
# axs = gs.subplots(sharex='col', sharey='row')
# fig.suptitle('Sharing x per column, y per row')
#
# for counter, image in enumerate(images):
# hist, bins = np.histogram(image, 2**8)
# axs.ravel()[counter] = plt.subplot(2, 2, counter + 1)
# axs.ravel()[counter].plot(bins[:-1], hist)
# plt.tight_layout()
# plt.show()
#
#
# # Display processed image
# images_figure, axs = plt.subplots(2, 2)
# axs[0, 0].imshow(clipped_image, cmap='gray', vmin=clipped_image.min(), vmax=clipped_image.max())
# axs[0, 1].imshow(normalized_image, cmap='gray')
# axs[1, 0].imshow(equalized_image, cmap='gray')
# axs[1, 1].imshow(adapt_equalized_image, cmap='gray')
# plt.show()
|
C#
|
UTF-8
| 486 | 2.578125 | 3 |
[] |
no_license
|
using Microsoft.AspNetCore.Authorization;
namespace Globomantics.Core.Authorization
{
public class RequiredRightAttribute : AuthorizeAttribute
{
public const string PolicyPrefix = "RequiredRight";
public RequiredRightAttribute(string right)
{
Right = right;
}
public string Right
{
get => Policy.Substring(PolicyPrefix.Length);
set => Policy = $"{PolicyPrefix}{value}";
}
}
}
|
PHP
|
UTF-8
| 2,180 | 2.6875 | 3 |
[] |
no_license
|
<html>
<head>
<title>Word List</title>
<!-- Bootstrap CDN -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<?php
session_start();
include("config_short.php");
if (isset($_GET['pageno'])) {
$pageno = $_GET['pageno'];
} else {
$pageno = 1;
}
$counter=0;
$number_of_records_per_page=15;
$offset = (($pageno-1)*$number_of_records_per_page);
$sql = "SELECT COUNT(*) FROM word";
$result = mysqli_query($link, $sql);
$total_rows = mysqli_fetch_array($result)[0];
$total_pages = ceil($total_rows / $number_of_records_per_page);
$query = "SELECT * FROM word LIMIT $offset, $number_of_records_per_page";
$result = mysqli_query($link,$query);
echo('<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
</style>');
echo('<h2>LIST OF WORDS</h2>
<table style:"width:50%">
<tr>
<th>Number</th>
<th>word</th>
</tr>');
while ($row = mysqli_fetch_array($result)) {
$counter++;
echo("<tr>
<td>$counter</td>
<td>$row[1]</td>
<td><a href='delete_word.php?id=$row[0]'?><img src='delete.gif' width='17'></a></td>
<td><a href='edit_word.php?id=$row[0]'><img src='edit.gif' width='17'></a></td>
</tr>");
}
echo('</table>');
echo('<h2><a href="admin.php">Return</a></h2>');
mysqli_close($link);
?>
<ul class="pagination">
<li><a href="?pageno=1">First</a></li>
<li class="<?php if($pageno <= 1){ echo 'disabled'; } ?>">
<a href="<?php if($pageno <= 1){ echo '#'; } else { echo "?pageno=".($pageno - 1); } ?>">Prev</a>
</li>
<li class="<?php if($pageno >= $total_pages){ echo 'disabled'; } ?>">
<a href="<?php if($pageno >= $total_pages){ echo '#'; } else { echo "?pageno=".($pageno + 1); } ?>">Next</a>
</li>
<li><a href="?pageno=<?php echo $total_pages; ?>">Last</a></li>
</ul>
</body>
</html>
|
Markdown
|
UTF-8
| 6,663 | 3.09375 | 3 |
[
"MIT"
] |
permissive
|
---
layout: default
title: "MSEngine ZA Ultra"
date: 2020-06-16 13:35:03 -0400
tags: minesweeper
---
# MSEngine ZA Ultra
### My journey creating a zero allocation minesweeper engine and solver
Before I begin this series of posts documenting this project, I have a confession to make.
> I have never actually played a single minesweeper game using this engine
It seems somewhat ironic to spend countless hours programming such an iconic game and never bother to manually play it. It's really just a combination of not wanting to play from the CLI or build out a front end. If I do ever get around to it, it will definitely be with Unity though. Or maybe the canvas with React. Or Blazor. Probably best to limit the scope, since this has already taken vastly longer than originally anticipated.
## What/Why is MSEngine ZA Ultra?
The initial goal of this project was just to create a simple minesweeper engine containing all the required game logic, but without the UI. I wanted to contribute my first open source project and NuGet package that someone could actually use and implement a full minesweeper game with. (Whether someone has taken on that endeavor, I don't know). I also wanted to experiment with automated testing, since my programming career has not yet afforded that possibility.
After the initial engine was created along with a suite of tests, I figured it only made sense to take a stab at implementing an automated solver. I did not realize at the time what a rabbit hole this would take me down. To this day, I'm still not sure I understand the true scope of a probabilistic solver.
Anyway, after writing a ton of code and eventually getting bored, I needed to think of something to renew my interest in continuing this project. There are three main overlapping drivers for this project now; a matrix/linear algebra based solver, a desire for blazing performance, and learning/using SIMD/instrinsics.
## A Few Notes before the Journey Begins
* Minesweeper/solver is simple to learn, but brutally and deceptively difficult to implement
* If you google minesweeper and play the game on the 2nd link, you may encounter one of the first bugs/edge cases I came across. Imagine a corner tile (or Node as I prefer) surrounded by flags. What should happen if you reveal the corner node and it *does not* contain a mine, and the three flags surrounding it *do not* actually have mines either? It's a weird edge case that I wouldn't expect to occur naturally, but is precisely the type of case I want my engine/tests to consider. (I believe the correct (and original) minesweeper engines would prevent the node revealing chain reaction).
* Even the *first* online minesweeper link has a bizarre bug. Consider the following game...what should happen if the green node is revealed *and* has zero adjacent mines? We can clearly see the top left node has zero adjacent mines...therefore the blue node below definitely does not have a mine.

..and the aftermath. Note the blue node remains *hidden*.

Seems like an obvious bug to me. Maybe this logic is true to the original windows 3.1 version? This is something I would like to explore further. Once again, this realistically doesn't impact normal play, but could potentially interfere with an AI/ML approach.
* Minesweeper intermediate/expert boards are defined at 16/16/40 and 30/16/99, but beginner boards can be considered 8/8/10 or 9/9/10.
* Some implementations ensure the first revealed node does not have a mine, and has an adjacent mine count of zero. Personally, I prefer that approach because otherwise you may be forced to guess on *the second turn*, which significantly reduces the odds of winning.
* Every single time I read over the code, I managed to find possible performance enhancements. It always felt good to pick the low hanging fruit, but there was always the oppurtunity to shave off a few microseconds by some obscure technique.
* Achieving zero allocations felt like a great accomplishment. Without a doubt, it made parts of the code *uglier*, and the inability to use LINQ is depressing, but zero allocations are a requirement for ultra performance.
* Ensuring the mines are randomly/cryptographically scattered is more difficult than I initially assumed.
* I did my best to ensure that the engine/solver/app remain distinct from each other. For example, solver may only take a a `Matrix<Node>` and return `Turns`. The solver never has the ability to mutate the board. The app is responsible for generating a new board if the initial turn would reveal a mine (in the original minesweeper, the engine would just "relocate" the mine to the top left)
* You could write an entire PhD on implementing a probabilistic solver using AI/ML, because the scope is so vast. To my knowledge, nothing like that even exists yet.
* There is still a ton I don't know, and some stuff I definitely got wrong. Please let me know if you find anything.
## Show me your code
The most complicated aspect of any minesweeper engine is without a doubt the "Chain Reaction" logic. Revealing a node with zero adjacement mines will trigger this chain reaction, revealing other nodes and cascading this behavior until certain boundaries are encountered (flags/mines). I've refactored this snippet of code a ton already, but there is still room for improvement. It may look simple/clean now, but the initial version was an ugly mess (something I assume most people encounter).
```c#
internal static void VisitNode(Matrix<Node> matrix, int nodeIndex, ReadOnlySpan<int> visitedIndexes, ref Span<int>.Enumerator enumerator)
{
Debug.Assert(nodeIndex >= 0);
var pass = enumerator.MoveNext();
Debug.Assert(pass);
enumerator.Current = nodeIndex;
Span<int> buffer = stackalloc int[MaxNodeEdges];
buffer.FillAdjacentNodeIndexes(matrix.Nodes.Length, nodeIndex, matrix.ColumnCount);
foreach (var i in buffer)
{
if (i == -1) { continue; }
ref var node = ref matrix.Nodes[i];
if (node.State == NodeState.Flagged) { continue; }
if (node.State == NodeState.Hidden)
{
node = new Node(node, NodeState.Revealed);
}
if (node.MineCount == 0 && !visitedIndexes.Contains(i))
{
VisitNode(matrix, i, visitedIndexes, ref enumerator);
}
}
}
```
## Ok then
I think that is enough for this first post. In the next, I want to discuss deterministic solver strategies, and why that is so difficult to code.
{% include minesweeper.html %}
|
Java
|
UTF-8
| 2,247 | 3.03125 | 3 |
[] |
no_license
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Solution
{
static int map[][];
static boolean visit[][];
static int N, K;
static int max = 0;
static final int dx[] = {0, 0, 1, -1};
static final int dy[] = {1, -1, 0, 0};
static int ans;
static boolean used = false;
public static void main(String[] args) throws NumberFormatException, IOException
{
// TODO Auto-generated method stub
int T;
String tmp[];
BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));
T = Integer.parseInt(scan.readLine());
for(int i = 0; i < T; i++)
{
ans = 0;
max = 0;
tmp = scan.readLine().split(" ");
N = Integer.parseInt(tmp[0]);
K = Integer.parseInt(tmp[1]);
map = new int[N][N];
visit = new boolean[N][N];
for(int j = 0; j < N; j++)
{
tmp = scan.readLine().split(" ");
for(int k = 0; k < tmp.length; k++)
{
map[j][k] = Integer.parseInt(tmp[k]);
}
}
getMax();
for(int x = 0; x < N; x++)
{
for(int y = 0; y < N; y++)
{
if(map[x][y] == max)
{
visit[x][y] = true;
dfs(x, y, 1);
visit[x][y] = false;
}
}
}
System.out.println("#" + (i + 1) + " " + ans);
}
}
public static void dfs(int bx, int by, int cnt)
{
int ax, ay;
int tmp = 0;
ans = Math.max(ans, cnt);
for(int i = 0; i < 4; i++)
{
ax = bx + dx[i];
ay = by + dy[i];
if(0 <= ax && ax <= N - 1 && 0 <= ay && ay <= N - 1)
{
if(map[bx][by] > map[ax][ay] && !visit[ax][ay])
{
visit[ax][ay] = true;
dfs(ax, ay, cnt + 1);
visit[ax][ay] = false;
}
else if(!used && map[bx][by] > map[ax][ay] - K && !visit[ax][ay])
{
used = true;
visit[ax][ay] = true;
tmp = map[ax][ay];
map[ax][ay] = map[bx][by] - 1;
dfs(ax, ay, cnt + 1);
map[ax][ay] = tmp;
visit[ax][ay] = false;
used = false;
}
}
}
}
public static void getMax()
{
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
max = Math.max(max, map[i][j]);
}
}
}
}
|
C++
|
UTF-8
| 631 | 2.90625 | 3 |
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: johnchan
*
* Created on 2016年4月13日, 下午2:16
*/
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
/*
* Display your name and address;
*/
int main(int argc, char** argv) {
string name = "Matrix";
string address = "DG,Guangdong,China.";
cout << "Your name is " << name << endl;
cout << "Your address is " << address << endl;
return 0;
}
|
Markdown
|
UTF-8
| 1,590 | 2.875 | 3 |
[
"MIT"
] |
permissive
|
---
layout: post
title: Online Learning Workshop in Paris
date: 2017-10-20 23:18:45
categories: events
---
An online learning workshop was held at Telecom Paritech on September 20, followed by the PhD defense of <a href="https://www.cvernade.com/" style="color:#3A01DF">Claire Vernade</a>. <a href="https://sites.ualberta.ca/~szepesva/" style="color:#3A01DF">Csaba Szepesvári</a> gave a talk on adaptive convex optimisation, and <a href="http://wouterkoolen.info/" style="color:#3A01DF">Wouter Koolen</a> gave a talk on learning rates in online learning.
As my first official "business" travel during my PhD life, this event truly means something to me. It represents the start of a mesmerizing, hopefully at least, journey. Thank you Claire for the nice <i>pot de thèse</i> ^^.
Fun fact 1: Pot de thèse is a French tradition (exists as well in many other countries of course, but not all) among defending PhD students who shall prepare some buffet for all the attendees of his/her defense. It is usually after the deliberation and the announcement of the final result. One may ask what if the candidate fails, well it could be the case, but remains quite rare in reality. The fact that the candidate is allowed to defend by default implies that he/she will eventually get the degree.
Fun fact 2: In France, attendees are not supposed to applaud after the presentation or the question session. People only applaud after the announcement of the final result.
Fun fact 3: Only PhDs have the right to ask questions during a defense in France, but they usually don't (apart from the exam committee of course).
|
Markdown
|
UTF-8
| 2,089 | 3.09375 | 3 |
[] |
no_license
|
# 115 Distinct Subsequences
1. DFS(TLE)
```c++
class Solution {
public:
string S,T;
int ans=0;
int func(int i,int j,int matched){
if(matched==T.size()){
ans++;
return;
}
if(i==S.size()||j==T.size())return;
func(i+1,j,matched);
if(S[i]==T[j])func(i+1,j+1,matched+1);
}
int numDistinct(string s, string t) {
S=s;
T=t;
func(0,0,0);
return ans;
}
};
```
2. Dynamic Programing
int dp[ ] [ ] -> long long dp[ ] [ ]
**Line 15: Char 43: runtime error: signed integer overflow: 2073949853 + 592325108 cannot be represented in type 'int' (solution.cpp)**
3. Dynamic Programing
4. dp [ ]
执行用时 :8 ms, 在所有 C++ 提交中击败了92.98%的用户
内存消耗 :8.5 MB, 在所有 C++ 提交中击败了95.98%的用户
```c++
class Solution {
public:
int numDistinct(string s, string t) {
if(s.size()==0)return 0;
long long dp[t.size()+1]={0};
dp[0]=1;
for(int i=1;i<=s.size();i++){
for(int j=t.size();j>=1;j--){
if(s[i-1]==t[j-1])dp[j]+=dp[j-1];
}
}
return dp[t.size()];
}
};
```
5. dp [ ] [ ]
执行用时 :0 ms, 在所有 C++ 提交中击败了100.00%的用户
内存消耗 :13.1 MB, 在所有 C++ 提交中击败了59.20%的用户
```c++
class Solution {
public:
int numDistinct(string s, string t) {
int slen=s.size(),tlen=t.size();
long long dp[tlen+1][slen+1];
for(int i=0;i<=tlen;i++){
dp[i][0]=0;
}
for(int i=0;i<=slen;i++){
dp[0][i]=1;
}
for(int i=1;i<=tlen;i++){
for(int j=1;j<=slen;j++){
dp[i][j]=dp[i][j-1];
if(s[j-1]==t[i-1])dp[i][j]+=dp[i-1][j-1];
}
}
return dp[tlen][slen];
}
};
```
|
Python
|
UTF-8
| 3,247 | 3.015625 | 3 |
[] |
no_license
|
import math
import argparse
def get_data(ip):
splt = ip.split("/")
ip = splt[0]
mask = int(splt[1])
return ip,mask
def get_oct_ip(ip):
ip_array=ip.split(".")
octet=[]
for part in ip_array:
octet.append(int(part))
return octet
def bit_not(n, numbits=8):
return (1 << numbits) - 1 - n
def get_oct_cidr(cidr):
i = cidr
octets = []
while(len(octets) < 4):
if (i >= 8):
octets.append((2**8-1))
elif (8 >= i > 0):
octets.append((2**i-1)<<8-i)
else:
octets.append(0)
i = i-8
return octets
def get_cidr_from_mask(oct):
mask_array=oct.split(".")
octet=[]
cidr = 0
for part in mask_array:
binary = bin(int(part))[2:]
cidr += binary.count('1')
return cidr
def op_oct(oct1,op,oct2):
new_oct=[]
for i in range(0,4):
if op == "&":
new_oct.append(oct1[i] & oct2[i])
elif op == "+":
new_oct.append(oct1[i] + oct2[i])
return new_oct
def not_oct(octets):
neg_oct = []
for octet in octets:
neg_oct.append(bit_not(octet))
return neg_oct
def add_to_oct(octets,val):
origin = octets.copy()
for x in range(3,-1,-1):
if val > 255:
val -= 255
origin[x] = 255
elif val+origin[x] > 255:
val = val + origin[x] - 255
origin[x] = 255
elif val+origin[x]<0:
return origin
else:
origin[x]+=val
return origin
def get_cidr_log(hosts):
cidr=int(32-math.log(hosts+2,2))
return cidr
def max_hosts(cidr):
return (2**(32-cidr))-2
def show_oct(my_oct):
str_oct = ""
for octet in my_oct:
str_oct+=str(octet)+"."
return str_oct[:-1]
def show_ip(ip_oct,cidr):
return show_oct(ip_oct)+"/"+str(cidr)
def get_broadcast(ip_oct,mask):
neg_mask = not_oct(mask)
broadcast = op_oct(ip_oct,"+",neg_mask)
return broadcast
def get_subnets_info(ip_v4, hosts_number):
ip,cidr = get_data(ip_v4)
ip_octets = get_oct_ip(ip)
for hosts in hosts_number:
print("-----------------")
cidr = get_cidr_log(hosts)
mask = get_oct_cidr(cidr)
broadcast_ip = get_broadcast(ip_octets,mask)
first_host = add_to_oct(ip_octets,1)
last_host = add_to_oct(broadcast_ip,-1)
print("Adres podsieci",show_ip(ip_octets,cidr))
print("Maska podsieci",show_oct(mask))
print("Adres pierwszego hosta",show_oct(first_host))
print("Adres ostatniego hosta",show_oct(last_host))
print("Adres broadcast",show_oct(broadcast_ip))
print("Max hostow",max_hosts(cidr))
print("Hosty niewykorzystane",max_hosts(cidr)-hosts)
ip_octets = add_to_oct(broadcast_ip,1)
print("-----------------")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Get Subnets of provided ip and host amounts')
parser.add_argument('ip_with_cidr', help='example 203.203.203.0/24')
parser.add_argument('hosts_amounts', nargs="+",type=int,help='example 60 50 40')
args = parser.parse_args()
get_subnets_info(args.ip_with_cidr,args.hosts_amounts)
|
C#
|
UTF-8
| 3,707 | 2.71875 | 3 |
[] |
no_license
|
//Steven Cruickshank
//October 22 2017
//Assignement #2 for OOPL/C#
//
//BIGBUCKSBANK application. create an ATM application called BIGBUCKSBANK. include required
//functions, and data. Calculations are performed, and when the user is finished, a list of
//transactions are printed out as a digital "receipt", and the main screen reappears.
//
//Five usernames have been provided, and loaded upon launch.
//ADMINISTRATOR ACCOUNT:
//USERNAME: admin
//PASSWORD: 1234
///////////
///////////
///////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BigBucksBank
{
public class Record
{
public static int userIndex = 0;
//array list used to store user transactions
public static List<Record> transList = new List<Record>();
//prepared list of users, as requested
public static Record [] recs = { new Record("msmith12", "5643", "5362848211", "0584736252", 0, 3000, 5000, false),
new Record("admin", "1234", "4876528596", "1582569548", 0, 7500, 10000, true),
new Record("b7thomas", "6239", "4811247891", "9652500124", 0, 800, 3000, false),
new Record("big9bucks", "1932", "0185682144", "4258501484", 0, 2500, 5000, false),
new Record("lisaz324", "2348", "8563215697", "8423540366", 0, 1000, 3500, false)};
//member variables
public static bool isUserNameTrue = false;
public static bool isPassWordTrue = false;
public static int warningCount = 0;
public bool isAdmin = false;
public bool isDeposit = false;
public bool isTransfer = false;
public bool isCheckingAcct = false;
public string userName;
public string passWord;
public string userCheckAcct;
public String userSavAcct;
public decimal startBal = 0m;
public decimal chkValue = 0m;
public decimal savValue = 0m;
public string description;
public decimal transAmount = 0m;
//public default constructor
Record() { }
//constructor for a new user Record
public Record(string uname, string pw, string ca, string sa, decimal bal, decimal chk, decimal sav, bool admin)
{
userName = uname;
passWord = pw;
userCheckAcct = ca;
userSavAcct = sa;
startBal = bal;
chkValue = chk;
savValue = sav;
isAdmin = admin;
}
//constructor for transaction list constructor
public Record(string id, string ca, string sa, decimal camt, decimal samt, decimal transamt, string desc, bool isDepo, bool isTran, bool ischk)
{
userName = id.ToString();
userCheckAcct = ca.ToString();
userSavAcct = sa.ToString();
chkValue = Convert.ToDecimal(camt);
savValue = Convert.ToDecimal(samt);
transAmount = transamt;
description = desc;
isDeposit = isDepo;
isTransfer = isTran;
isCheckingAcct = ischk;
}
//few accessors/mutators
public void setAdmin(bool b)
{
this.isAdmin = true;
}
public bool getIsAdmin(Record r)
{
return this.isAdmin;
}
public void setStartBal(decimal b)
{
startBal = b;
}
public decimal getStartBal()
{
return startBal;
}
}
}
|
TypeScript
|
UTF-8
| 533 | 2.5625 | 3 |
[] |
no_license
|
import {
PipeTransform,
Injectable,
BadRequestException
} from '@nestjs/common';
@Injectable()
export class PipeJoiValidation implements PipeTransform {
constructor(private readonly schema: any) {}
transform(value: any) {
const { error } = this.schema.validate(value);
if (error) {
const message = 'Validation failed';
const fields = error.details.map((e) => e.message);
throw new BadRequestException(message, fields);
}
return value;
}
}
|
C++
|
UTF-8
| 5,098 | 2.875 | 3 |
[] |
no_license
|
// Demonstrate creating a spritesheet
#include <SFML/Graphics.hpp>
#include <iostream>
using namespace std;
enum DIR{LEFT,RIGHT};
enum STATE{ON,OFF};
bool flipped = false;
DIR fire = LEFT;
DIR facing = LEFT;
int width = 22;
int height = 25;
int main(int argc, char ** argv){
//create a font
sf::RenderWindow window(sf::VideoMode(1000, 1000), "Demo Game");
sf::Event event;
sf::Texture texture;
// height: 25 pixels
// width: 22 pixels
// rect.top 1st row = 10
texture.loadFromFile("MegaMan Player Spritesheet.png");
sf::IntRect rectSourceSprite(103, 10, width, height);
sf::Sprite sprite(texture,rectSourceSprite);
sprite.setScale(2,2);
sprite.scale(2,2);
sprite.setPosition(300, 300);
window.setVerticalSyncEnabled(true);
sf::Clock clock;
sf::Font font;
if (!font.loadFromFile("sansation.ttf"))
return EXIT_FAILURE;
sf::Text pauseMessage;
pauseMessage.setFont(font);
pauseMessage.setCharacterSize(40);
pauseMessage.setPosition(100.f, 80.f);
pauseMessage.setFillColor(sf::Color::White);
pauseMessage.setString("Welcome to the test of a game!\nThis text is just a test example");
while (window.isOpen()){
while (window.pollEvent(event)){
if (event.type == sf::Event::EventType::Closed)
window.close();
}
if ((sf::Keyboard::isKeyPressed(sf::Keyboard::Z))){
rectSourceSprite.top = 10; rectSourceSprite.left = 353; rectSourceSprite.width = 25; sprite.setTextureRect(rectSourceSprite);}
if ((sf::Keyboard::isKeyPressed(sf::Keyboard::X))){
rectSourceSprite.top = 42; rectSourceSprite.left = 3; rectSourceSprite.width = 17; sprite.setTextureRect(rectSourceSprite);}
if ((sf::Keyboard::isKeyPressed(sf::Keyboard::C))){
rectSourceSprite.top = 42; rectSourceSprite.left = 27; rectSourceSprite.width = 22; sprite.setTextureRect(rectSourceSprite);}
if ((sf::Keyboard::isKeyPressed(sf::Keyboard::V))){
rectSourceSprite.top = 74; rectSourceSprite.left = 105; rectSourceSprite.width = 32; sprite.setTextureRect(rectSourceSprite);}
if ((sf::Keyboard::isKeyPressed(sf::Keyboard::Subtract))){
fire = LEFT;}
if ((sf::Keyboard::isKeyPressed(sf::Keyboard::Add))){
fire = RIGHT;}
if ((sf::Keyboard::isKeyPressed(sf::Keyboard::F))){
flipped = !flipped;
rectSourceSprite.left += rectSourceSprite.width;
rectSourceSprite.width = -rectSourceSprite.width;
sprite.setTextureRect(rectSourceSprite);}
/*switch(fire){
case LEFT:
if(facing == RIGHT){
rectSourceSprite.left = 100;}
if(facing == LEFT){
rectSourceSprite.left = 100;}sprite.setTextureRect(rectSourceSprite);
break;
case RIGHT:
if(facing == RIGHT){
rectSourceSprite.left = 100;}
if(facing == LEFT){ // do not go past 1600 or less than 1340
rectSourceSprite.left = 100;}sprite.setTextureRect(rectSourceSprite);
break;}*/
if (clock.getElapsedTime().asSeconds() > 1.0f){
switch(rectSourceSprite.left){
case 103:
rectSourceSprite.top = 10; rectSourceSprite.left = 353; rectSourceSprite.width = 25;
break;
case 353:
rectSourceSprite.top = 42; rectSourceSprite.left = 3; rectSourceSprite.width = 17;
break;
case 3:
rectSourceSprite.top = 42; rectSourceSprite.left = 27; rectSourceSprite.width = 22;
break;
case 125:
rectSourceSprite.top = 10; rectSourceSprite.left = 378; rectSourceSprite.width = 25;
break;
case 378:
rectSourceSprite.top = 42; rectSourceSprite.left = 3; rectSourceSprite.width = 17;
break;
case 20:
rectSourceSprite.top = 42; rectSourceSprite.left = 27; rectSourceSprite.width = 22;
break;
default:
rectSourceSprite.left = 103; rectSourceSprite.top = 10;
break;
}
sprite.setTextureRect(rectSourceSprite);
clock.restart();
}
if ((sf::Keyboard::isKeyPressed(sf::Keyboard::Right))){
facing = RIGHT;
sprite.move(+4.0,+0.0);}
if ((sf::Keyboard::isKeyPressed(sf::Keyboard::Left))){
facing = LEFT;
sprite.move(-4.0,+0.0);}
if ((sf::Keyboard::isKeyPressed(sf::Keyboard::Down))){
sprite.move(+0.0,+4.0);}
if ((sf::Keyboard::isKeyPressed(sf::Keyboard::Up))){
sprite.move(+0.0,-4.0);}
if ((sf::Keyboard::isKeyPressed(sf::Keyboard::D))){
rectSourceSprite.left += 1;
sprite.setTextureRect(rectSourceSprite);}
if ((sf::Keyboard::isKeyPressed(sf::Keyboard::A))){
rectSourceSprite.left -= 1;
sprite.setTextureRect(rectSourceSprite);}
if ((sf::Keyboard::isKeyPressed(sf::Keyboard::W))){
rectSourceSprite.top += 1;
sprite.setTextureRect(rectSourceSprite);}
if ((sf::Keyboard::isKeyPressed(sf::Keyboard::S))){
rectSourceSprite.top -= 1;
sprite.setTextureRect(rectSourceSprite);}
if ((sf::Keyboard::isKeyPressed(sf::Keyboard::I))){
pauseMessage.move(+0.0,+4.0);}
if ((sf::Keyboard::isKeyPressed(sf::Keyboard::K))){
pauseMessage.move(+0.0,-4.0);}
cout << "rect left " << rectSourceSprite.left;
cout << " rect top " << rectSourceSprite.top << endl;
window.clear();
window.draw(pauseMessage);
window.draw(sprite);
window.display();
}
}
|
Markdown
|
UTF-8
| 1,221 | 3.015625 | 3 |
[] |
no_license
|
# HTN-Demo
This is a demo of a Hierarchical task network.
Created with Unity version 2018.2.10
The demo is a small game. The objective is to collect 5 items (purple) before the The other agent, or have more items if both get caught.
The player is the blue agent.
The AI is the green agent.
Player controls:
A,S,D,W: movement
Space: use trap (2 uses)

There is one item in each alcove, both agent start in random alcoves and must move from alcove to alcove while avoiding the view of
the red agents (yellowish area).
The red agents will patrol the hallways at random speeds (the interval is small). They appear at one of the doors (orange) and will walk towards the other side. Once they reach a door they disapear and will reappear shortlty at a random door.
When the red agents reach the small wall in the middle, it loses its sight while in the wall and 3 things can happend:
- the agent will continue his partol to the other side
- the agent will turn around and walk back
- the agent will disapear and reappear at one of the 4 doors
If the player or the AI is caught they disappear and are no longer able to collect items.
|
Java
|
UTF-8
| 6,097 | 2.59375 | 3 |
[] |
no_license
|
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import factory.ConexaoFactory;
import model.Fabricante;
public class FabricanteDAO extends BasicDAO {
@Override
public void incluir(Object obj) throws SQLException {
if(obj instanceof Fabricante) {
Fabricante f = (Fabricante) obj;
StringBuilder sql = new StringBuilder();
sql.append("INSERT INTO fabricante ");
sql.append("(Nome,CNPJ,Tel,Endereco,Numero,Cidade,Complemento,Bairro,Cep,UF,Email,Obs,Site)");
sql.append("VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)");
Connection conexao = ConexaoFactory.conectar();
PreparedStatement pst = conexao.prepareStatement(sql.toString());
pst.setString(1, f.getNome());
pst.setString(2, f.getCnpj());
pst.setInt(3, f.getTel());
pst.setString(4, f.getEndereco());
pst.setInt(5, f.getNumero());
pst.setString(6, f.getCidade());
pst.setString(7,f.getComplemento());
pst.setString(8, f.getBairro());
pst.setInt(9, f.getCep());
pst.setString(10, f.getUf());
pst.setString(11, f.getEmail());
pst.setString(12, f.getObs());
pst.setString(13, f.getSite());
pst.executeUpdate();
pst.close();
}
}
@Override
public void deletar(Object obj) throws SQLException {
if(obj instanceof Fabricante) {
Fabricante f = (Fabricante) obj;
StringBuilder sql = new StringBuilder();
sql.append("DELETE FROM fabricante ");
sql.append("WHERE idFABRI = ? ");
Connection conexao = ConexaoFactory.conectar();
PreparedStatement pst = conexao.prepareStatement(sql.toString());
pst.setInt(1, f.getIdFABRI());
pst.executeUpdate();
pst.close();
}
}
@Override
public void editar(Object obj) throws SQLException{
if(obj instanceof Fabricante) {
Fabricante f = (Fabricante) obj;
String sql = "UPDATE fabricante SET Nome = ?, CNPJ = ?, Tel = ?, Endereco = ?, Numero = ?, Cidade = ?, Complemento = ?, Bairro = ?, Cep = ?, UF = ?, Email = ?, Obs = ?, Site = ? WHERE idFABRI = ? ";
Connection conexao = ConexaoFactory.conectar();
PreparedStatement pst = conexao.prepareStatement(sql);
pst.setString(1, f.getNome());
pst.setString(2, f.getCnpj());
pst.setInt(3, f.getTel());
pst.setString(4, f.getEndereco());
pst.setInt(5, f.getNumero());
pst.setString(6, f.getCidade());
pst.setString(7,f.getComplemento());
pst.setString(8, f.getBairro());
pst.setInt(9, f.getCep());
pst.setString(10, f.getUf());
pst.setString(11, f.getEmail());
pst.setString(12, f.getObs());
pst.setString(13, f.getSite());
pst.setInt(14, f.getIdFABRI());
pst.executeUpdate();
pst.close();
}
}
public ArrayList<Fabricante> listar() throws SQLException{
StringBuilder sql = new StringBuilder();
sql.append("SELECT * FROM ");
sql.append("fabricante ");
sql.append("ORDER BY nome ASC ");
Connection conexao = ConexaoFactory.conectar();
PreparedStatement pst = conexao.prepareStatement(sql.toString());
ResultSet rs = pst.executeQuery();
ArrayList<Fabricante> lista = new ArrayList<Fabricante>();
while(rs.next()) {
Fabricante f = new Fabricante();
f.setIdFABRI(rs.getInt("idFABRI"));
f.setNome(rs.getString("Nome"));
f.setCnpj(rs.getString("CNPJ"));
f.setTel(rs.getInt("Tel"));
f.setEndereco(rs.getString("Endereco"));
f.setNumero(rs.getInt("Numero"));
f.setCidade(rs.getString("Cidade"));
f.setComplemento(rs.getString("Complemento"));
f.setBairro(rs.getString("Bairro"));
f.setCep(rs.getInt("Cep"));
f.setUf(rs.getString("UF"));
f.setEmail(rs.getString("Email"));
f.setObs(rs.getString("Obs"));
f.setSite(rs.getString("Site"));
lista.add(f);
}
return lista;
}
/*
public static void main(String[] args) {
FabricanteDAO fdao = new FabricanteDAO();
try {
ArrayList<Fabricante> lista = fdao.listar();
for(Fabricante f: lista) {
System.out.println("Resultado: " + f);
}
}catch(SQLException e) {
System.out.println("Erro ao listar");
e.printStackTrace();
}
}*/
/*public static void main(String[] args) {
Fabricante f1 = new Fabricante();
f1.setNome("Leonildo Junior");
f1.setCnpj("126.433.4343/0001");
f1.setTel(432423);
f1.setEndereco("Rua das ruas");
f1.setNumero(123);
f1.setCidade("Recife");
f1.setComplemento("Teste de inclusão");
f1.setBairro("Água Fria");
f1.setCep(52121110);
f1.setUf("lala");
f1.setEmail("leo.junior2810@gmail.com");
f1.setObs("teste 123");
f1.setSite("www.teste.com.br");
f1.setIdFABRI(1);
FabricanteDAO fdao = new FabricanteDAO();
try {
fdao.editar(f1);
System.out.println("Registro atualizado com sucesso");
} catch (SQLException e) {
System.out.println("Erro ao atualizar");
e.printStackTrace();
}
}
*/
public static void main(String[] args) {
Fabricante f1 = new Fabricante();
f1.setNome("Leonildo");
f1.setCnpj("454545454");
f1.setTel(333333);
f1.setEndereco("Rua do cajueiro");
f1.setNumero(1545);
f1.setCidade("Olinda");
f1.setComplemento("Teste de inclusão 2223");
f1.setBairro("Cajueiro");
f1.setCep(52121123);
f1.setUf("nanana");
f1.setEmail("validar@gmail.com");
f1.setObs("obs de teste de inclusão");
f1.setSite("www.aaaaa.com.br");
FabricanteDAO fdao = new FabricanteDAO();
try {
fdao.incluir(f1);
System.out.println("Registro incluido com sucesso");
} catch (SQLException e) {
System.out.println("Erro ao incluir");
e.printStackTrace();
}
}
/*
//Teste para excluir fabricante
Fabricante f1 = new Fabricante();
f1.setIdFABRI(1);
FabricanteDAO fdao = new FabricanteDAO();
try {
fdao.deletar(f1);
System.out.println("Registro excluido com sucesso");
} catch (SQLException e) {
System.out.println("Erro ao excluir");
e.printStackTrace();
}
*/
}
|
Java
|
UTF-8
| 223 | 2.34375 | 2 |
[] |
no_license
|
package edu.cs.fsu.cen4020.weapons;
/**
* Created by Javier on 3/29/2017.
*/
public class IllegalArmorException extends Exception{
public IllegalArmorException() {
super("Armor value is illegal!!");
}
}
|
Rust
|
UTF-8
| 2,954 | 2.765625 | 3 |
[] |
no_license
|
use std::io::Read;
use errors::*;
use lines::Line::*;
use queries::*;
use query::*;
use peg;
pub fn parse<P: Parse>(text: P) -> Result<Queries> { Parse::parse(text) }
pub trait Parse {
fn parse(text: Self) -> Result<Queries>;
}
impl<'a, R: Read> Parse for &'a mut R {
fn parse(text: &mut R) -> Result<Queries> {
try!(read(text).map(|ref s| Parse::parse(s)))
}
}
impl<'a> Parse for &'a String {
fn parse(text: &String) -> Result<Queries> { Parse::parse(text as &str) }
}
impl<'a, P: Parse> Parse for (&'a str, P) {
fn parse(source: (&'a str, P)) -> Result<Queries> {
let noinfo = try!(Parse::parse(source.1));
let withinfo = Queries::new(Some(source.0.into()), noinfo.iter());
Ok(withinfo)
}
}
impl<'a> Parse for &'a str {
fn parse(text: &'a str) -> Result<Queries> {
let mut queries = Vec::default();
let mut warnings: Vec<(usize, String)> = Vec::default();
let mut lineno = 0;
let mut within: Option<(usize, usize, Signature)> = None;
let mut start = 0; // Byte offset: begin-of-declaration-pointer
let mut end = 0; // Byte offset: end-of-declaration-pointer
for line in try!(peg::lines(&text)) {
lineno += 1;
match line { // Consume declaration information if present
Declaration(_, ref signature) => {
if let Some((_, _, sig)) = within {
if start > 0 {
queries.push(query(text, sig, (start, end)));
}
}
start = 0;
within = Some((lineno, line.start(), signature.clone()));
}
BrokenDeclaration(_) => {
warnings.push((lineno, line.text().into()));
}
_ => {}
}
if start == 0 {
start = match line {
Text(_) if !line.blank() => line.start(),
Comment(_) => line.start(),
_ => start,
};
}
end = match line {
Declaration(_, _) => line.end(),
Text(_) if !line.blank() => line.end(),
_ => end,
};
}
// Handle last declaration.
if let Some((_, _, sig)) = within {
if start > 0 {
queries.push(query(text, sig, (start, end)));
}
}
let queries: Queries = queries.iter().collect();
Ok(queries)
}
}
fn read<R: Read>(source: &mut R) -> Result<String> {
let mut s: String = String::default();
try!(source.read_to_string(&mut s));
Ok(s)
}
fn query(text: &str, signature: Signature, body: (usize, usize)) -> Query {
Query {
signature: signature,
text: text[body.0..body.1].trim_right().into(),
}
}
|
Python
|
UTF-8
| 665 | 2.75 | 3 |
[] |
no_license
|
import sys
from PyQt5 import QtCore, QtGui
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import(
QMainWindow,
QApplication,
QLabel
)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.label = QLabel()
canvas = QtGui.QPixmap(400, 300)
canvas.fill(Qt.white)
self.label.setPixmap(canvas)
self.setCentralWidget(self.label)
self.draw_someting()
def draw_someting(self):
painter = QtGui.QPainter(self.label.pixmap())
painter.drawLine(10, 10, 300, 200)
painter.end()
app = QApplication(sys.argv)
w = MainWindow()
w.show()
app.exec_()
|
Java
|
UTF-8
| 3,323 | 2.21875 | 2 |
[] |
no_license
|
package com.es.dao.user;
import java.sql.Timestamp;
import java.util.List;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Component;
import com.es.dao.abst.AbstractDao;
import com.es.data.constant.StatusId;
import com.es.db.metadata.MetaDataUtil;
import com.es.vo.comm.UserDataVo;
@Component("userDataDao")
public class UserDataDao extends AbstractDao {
public UserDataVo getByPrimaryKey(String userId) {
String sql = "select * from User_Data where UserId=?";
Object[] parms = new Object[] {userId};
try {
UserDataVo vo = getJdbcTemplate().queryForObject(sql, parms,
new BeanPropertyRowMapper<UserDataVo>(UserDataVo.class));
return vo;
}
catch (EmptyResultDataAccessException e) {
return null;
}
}
public UserDataVo getForLogin(String userId, String password) {
String sql = "select * from User_Data where UserId=? and Password=?";
Object[] parms = new Object[] {userId, password};
List<UserDataVo> list = getJdbcTemplate().query(sql, parms,
new BeanPropertyRowMapper<UserDataVo>(UserDataVo.class));
if (list.size()>0) {
return list.get(0);
}
else {
return null;
}
}
public List<UserDataVo> getAll(boolean onlyActive) {
String sql = "select * from User_Data ";
if (onlyActive) {
sql += " where StatusId='" + StatusId.ACTIVE.getValue() + "'";
}
List<UserDataVo> list = getJdbcTemplate().query(sql,
new BeanPropertyRowMapper<UserDataVo>(UserDataVo.class));
return list;
}
public int update(UserDataVo userVo) {
if (userVo.getCreateTime()==null) {
userVo.setCreateTime(new Timestamp(System.currentTimeMillis()));
}
SqlParameterSource namedParameters = new BeanPropertySqlParameterSource(userVo);
String sql = MetaDataUtil.buildUpdateStatement("User_Data", userVo);
int rowsUpadted = getNamedParameterJdbcTemplate().update(sql, namedParameters);
return rowsUpadted;
}
public int update4Web(UserDataVo userVo) {
Object[] parms = {
userVo.getSessionId(),
userVo.getLastVisitTime(),
userVo.getHits(),
userVo.getRowId()
};
String sql = "update User_Data set " +
"SessionId=?," +
"LastVisitTime=?," +
"Hits=?" +
" where RowId=?";
int rowsUpadted = getJdbcTemplate().update(sql, parms);
return rowsUpadted;
}
public int deleteByPrimaryKey(String userId) {
String sql = "delete from User_Data where UserId=?";
Object[] parms = new Object[] {userId};
int rowsDeleted = getJdbcTemplate().update(sql, parms);
return rowsDeleted;
}
public int insert(UserDataVo userVo) {
if (userVo.getCreateTime()==null) {
userVo.setCreateTime(new Timestamp(System.currentTimeMillis()));
}
SqlParameterSource namedParameters = new BeanPropertySqlParameterSource(userVo);
String sql = MetaDataUtil.buildInsertStatement("User_Data", userVo);
int rowsInserted = getNamedParameterJdbcTemplate().update(sql, namedParameters);
userVo.setRowId(retrieveRowId());
return rowsInserted;
}
}
|
SQL
|
UTF-8
| 5,781 | 4.09375 | 4 |
[
"MIT"
] |
permissive
|
-- REQUIRES MYSQL-SERVER-5.7.6 OR HIGHER
CREATE DATABASE IF NOT EXISTS TELEPHONE_DIRECTORY;
USE TELEPHONE_DIRECTORY;
CREATE USER IF NOT EXISTS 'DIRECTORY_APP'@'localhost' IDENTIFIED BY 'D!rect0ry';
CREATE TABLE IF NOT EXISTS `CONTACTS` (
`id` VARCHAR(40) NOT NULL COMMENT 'System-generated GUID',
`full_name` VARCHAR(65) NOT NULL COMMENT 'Contact\' s full name',
`first_name` VARCHAR(30) NOT NULL COMMENT ' Contact\'s first name',
`last_name` VARCHAR(30) NOT NULL COMMENT 'Contact\' s last name',
`cre_dt` TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL COMMENT ' Created timestamp ',
`upd_dt` TIMESTAMP DEFAULT NULL NULL COMMENT ' Updated timestamp ',
`deleted` CHAR(1) DEFAULT 'N' NOT NULL COMMENT ' Indicates if the record has been deleted',
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=LATIN1;
CREATE TABLE IF NOT EXISTS `C_NUMS` (
`id` VARCHAR(40) NOT NULL COMMENT ' System-generated ID',
`c_number` VARCHAR(20) DEFAULT NULL,
`category` VARCHAR(100) DEFAULT NULL COMMENT ' Indicate the type of contact number ( work, personal, home, etc ) ',
`is_primary` CHAR(1) NOT NULL DEFAULT 'N' COMMENT ' Indicate if this is the primary contact number.',
`c_id` VARCHAR(40) NOT NULL COMMENT ' Refers to the CONTACTS.id column ',
`cre_dt` TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL COMMENT ' Created timestamp ',
`upd_dt` TIMESTAMP DEFAULT NULL NULL COMMENT ' Updated timestamp ',
PRIMARY KEY (`id`),
KEY `C_NUMS_CONTACTS_FK` (`c_id`),
CONSTRAINT `C_NUMS_CONTACTS_FK` FOREIGN KEY (`c_id`)
REFERENCES `CONTACTS` (`id`)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=INNODB DEFAULT CHARSET=LATIN1;
CREATE TABLE IF NOT EXISTS `EMAILS` (
`id` VARCHAR(40) NOT NULL COMMENT ' System-generated ID',
`email_id` VARCHAR(100) NOT NULL COMMENT ' Contact\'s email id',
`category` VARCHAR(25) DEFAULT NULL COMMENT 'Indicate the type of email id (work, personal, home, etc)',
`is_primary` CHAR(1) NOT NULL DEFAULT 'N' COMMENT 'Indicates if the mail id is primary',
`c_id` VARCHAR(40) NOT NULL COMMENT 'Refers to the CONTACTS table',
`cre_dt` TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL COMMENT 'Created timestamp',
`upd_dt` TIMESTAMP DEFAULT NULL NULL COMMENT 'Updated timestamp',
PRIMARY KEY (`id`),
KEY `EMAILS_CONTACTS_FK` (`c_id`),
CONSTRAINT `EMAILS_CONTACTS_FK` FOREIGN KEY (`c_id`)
REFERENCES `CONTACTS` (`id`)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=INNODB DEFAULT CHARSET=LATIN1;
-- INITIAL, SAMPLE DATA
SELECT
*
FROM
telephone_directory.CONTACTS;
set
@r_count = found_rows() if @r_count = 0 then INSERT
INTO
telephone_directory.CONTACTS ( id,
full_name,
first_name,
last_name,
deleted,
cre_dt,
upd_dt )
VALUES( '4d134c35-b797-11e8-bdb8-0071cc56c4c3',
'Ted Mosby',
'Mosby',
'Ted',
'N',
'2018-09-15 14:13:50.000',
NULL );
INSERT
INTO
telephone_directory.CONTACTS ( id,
full_name,
first_name,
last_name,
deleted,
cre_dt,
upd_dt )
VALUES( '88df9efb-b3c0-11e8-8cde-0071cc56c4c3',
'Chad Murphy',
'Chad',
'Murphy',
'N',
'2018-09-15 14:13:50.000',
NULL );
INSERT
INTO
telephone_directory.CONTACTS ( id,
full_name,
first_name,
last_name,
deleted,
cre_dt,
upd_dt )
VALUES( '97013221-b3c9-11e8-8cde-0071cc56c4c3',
'Victor Spencer',
'Victor',
'Spencer',
'2018-09-15 14:13:50.000',
'N',
NULL );
INSERT
INTO
telephone_directory.CONTACTS ( id,
full_name,
first_name,
last_name,
deleted,
cre_dt,
upd_dt )
VALUES( 'd240feee-b793-11e8-bdb8-0071cc56c4c3',
'Spencer',
'Docks',
'Spencer',
'2018-09-15 14:13:50.000',
'N',
NULL );
end if;
SELECT
*
FROM
telephone_directory.C_NUMS;
set
@count = found_rows() if @count = 0 then INSERT
INTO
telephone_directory.C_NUMS ( id,
c_number,
category,
is_primary,
c_id,
cre_dt,
upd_dt )
VALUES( '19d6f7f7-b3c3-11e8-8cde-0071cc56c4c3',
'+1234567890',
'MOBILE',
0,
'88df9efb-b3c0-11e8-8cde-0071cc56c4c3',
'2018-09-15 14:39:58.000',
NULL );
INSERT
INTO
telephone_directory.C_NUMS ( id,
c_number,
category,
is_primary,
c_id,
cre_dt,
upd_dt )
VALUES( '9c99d984-b3c2-11e8-8cde-0071cc56c4c3',
'+4124257658',
'MOBILE',
1,
'88df9efb-b3c0-11e8-8cde-0071cc56c4c3',
'2018-09-15 14:39:58.000',
NULL );
INSERT
INTO
telephone_directory.C_NUMS ( id,
c_number,
category,
is_primary,
c_id,
cre_dt,
upd_dt )
VALUES( 'aa454933-b3c9-11e8-8cde-0071cc56c4c3',
'++35322410124',
'MOBILE',
0,
'97013221-b3c9-11e8-8cde-0071cc56c4c3',
'2018-09-15 14:39:58.000',
NULL );
INSERT
INTO
telephone_directory.C_NUMS ( id,
c_number,
category,
is_primary,
c_id,
cre_dt,
upd_dt )
VALUES( 'c8f67767-b3c9-11e8-8cde-0071cc56c4c3',
'+91554212452',
'MOBILE',
1,
'97013221-b3c9-11e8-8cde-0071cc56c4c3',
'2018-09-15 14:39:58.000',
NULL );
end if;
SELECT
*
FROM
telephone_directory.EMAILS;
set
@count = found_rows() if @count = 0 then INSERT
INTO
telephone_directory.EMAILS ( id,
email_id,
category,
is_primary,
c_id,
cre_dt,
upd_dt )
VALUES( '0ed878d0-b3c3-11e8-8cde-0071cc56c4c3',
'tedMosby@gmail.com',
'WORK',
0,
'88df9efb-b3c0-11e8-8cde-0071cc56c4c3',
'2018-09-15 14:38:16.000',
NULL );
INSERT
INTO
telephone_directory.EMAILS ( id,
email_id,
category,
is_primary,
c_id,
cre_dt,
upd_dt )
VALUES( 'bc8ddb0b-b3c9-11e8-8cde-0071cc56c4c3',
'victor.spencer@outlook.com',
'PERSONAL',
0,
'97013221-b3c9-11e8-8cde-0071cc56c4c3',
'2018-09-15 14:38:16.000',
NULL );
INSERT
INTO
telephone_directory.EMAILS ( id,
email_id,
category,
is_primary,
c_id,
cre_dt,
upd_dt )
VALUES( 'fe821183-b3c2-11e8-8cde-0071cc56c4c3',
'chadMurphy@gmail.com',
'PERSONAL',
1,
'88df9efb-b3c0-11e8-8cde-0071cc56c4c3',
'2018-09-15 14:38:16.000',
NULL );
end if;
|
C++
|
UTF-8
| 739 | 2.515625 | 3 |
[] |
no_license
|
/**************************************************************************************************
** Program Name:Zoo Tycoon
** Author: Clinton Hawkes
** Date: 04/21/2019
** Description: Header file for the Turtle class. This file contains the constructor and the two
member functions used by this class. This class is derived from the Animal class
so those variables and functions can be seen in Animal.hpp.
**************************************************************************************************/
#ifndef TURTLE_HPP
#define TURTLE_HPP
#include "Animal.hpp"
class Turtle : public Animal{
public:
Turtle();
int getDailyFoodCost();
int getPayoff();
};
#endif
|
JavaScript
|
UTF-8
| 825 | 2.546875 | 3 |
[] |
no_license
|
import axios from 'axios';
/**
* Получить все продукты.
*/
export const getProducts = () => {
return axios.get('http://localhost:1234/product');
}
/**
* Получить продукт по id.
*/
export const getProductById = (id) => {
return axios.get('http://localhost:1234/product/' + id);
}
/**
* Создать продукт.
*/
export const createProduct = (model) => {
return axios.post('http://localhost:1234/product/create', model);
}
/**
* Удалить продукт.
*/
export const deleteProduct = (id) => {
return axios.delete('http://localhost:1234/product/' + id + '/delete');
}
/**
* Обновить запись по id.
*/
export const updateProduct = (id, model) => {
return axios.put('http://localhost:1234/product/' + id + '/update', model);
}
|
C++
|
UTF-8
| 1,202 | 2.515625 | 3 |
[] |
no_license
|
#pragma once
#include <vector>
#include <list>
#include "../Structs/Rectangular.h"
#include "../Structs/Vector.h"
#include "../Interfaces/Updateable.h"
#include "../Structs/Assert.h"
class IBaseObject :
public IUpdateable
{
public:
IBaseObject(const IBaseObject * Owner, EUpdateSpeed UpdateSpeed, bool IsMoveable);
virtual ~IBaseObject();
const std::vector<std::string> & GetTexture() const;
const std::vector<CVector2i> & GetEdges() const;
const CRect & GetBounds() const;
bool IsMortal() const;
bool IsMoveable() const;
void SetIsOnScreen(bool state);
bool IsOnScreen() const;
bool IsDead() const;
void TryKill(const IBaseObject * killer) const;
const IBaseObject * GetKiller() const;
const IBaseObject * const GetOwner() const;
protected:
void SetTexture(std::vector<std::string> & Texture);
void SetPosition(CVector2i Position);
void SetMortality(bool value);
private:
void CalculateEdges();
std::vector<std::string> m_Texture;
std::vector<CVector2i> m_Edges;
CRect m_Bounds;
bool m_IsMoveable;
bool m_IsMortal;
bool m_IsOnScreen;
mutable bool m_IsDead;
mutable const IBaseObject * m_Killer;
const IBaseObject * const m_Owner;
};
|
Markdown
|
UTF-8
| 592 | 3.578125 | 4 |
[
"Apache-2.0"
] |
permissive
|
## リストの要素を前からいくつか削る
drop関数を使います
### フォーマット
drop(削る要素数)
### 実装サンプル
val array = arrayOf(1, 2, 3, 4, 5)
array.drop(1).forEach{println(it)} // => 2, 3, 4, 5
array.drop(2).forEach{println(it)} // => 3, 4, 5
array.drop(3).forEach{println(it)} // => 4, 5
array.drop(4).forEach{println(it)} // => 5
array.drop(5).forEach{println(it)} // => 空のArray
### 参考URL
[Kotlin公式ドキュメント stdlib / kotlin /drop](http://kotlinlang.org/api/latest/jvm/stdlib/kotlin/drop.html)
|
Java
|
UTF-8
| 884 | 2.671875 | 3 |
[] |
no_license
|
package com.imarticus.demo.SpringCoreProject;
import java.util.List;
public class Department {
private int did;
private String name;
private List<String> functions;
public Department() {
super();
// TODO Auto-generated constructor stub
}
public Department(int did, String name, List<String> functions) {
super();
this.did = did;
this.name = name;
this.functions = functions;
}
public int getDid() {
return did;
}
public void setDid(int did) {
this.did = did;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getFunctions() {
return functions;
}
public void setFunctions(List<String> functions) {
this.functions = functions;
}
@Override
public String toString() {
return "Department [did=" + did + ", name=" + name + ", functions=" + functions + "]";
}
}
|
C++
|
UTF-8
| 601 | 2.90625 | 3 |
[] |
no_license
|
/*
NEWPTIT
*/
#include<bits/stdc++.h>
#define ll long long
using namespace std;
string strcpy(string s, int l, int r){
string str="";
for(int i=l;i<=r;i++)
str=str+s[i];
return str;
}
bool searchString(string s2, string s1){
if(s2==s1)
return true;
ll l1= s1.length();
ll l2= s2.length();
for(int i=0; l1 - i >= l2 ;i++)
if(strcpy(s1,i,i+l2-1) == s2)
return true;
return false;
}
int main(){
int t;
cin>>t;cin.ignore();
while(t--){
string s1, s2;
getline(cin,s1);
getline(cin,s2);
if(searchString(s2,s1))
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
return 0;
}
|
C++
|
UTF-8
| 1,103 | 3.578125 | 4 |
[] |
no_license
|
#include <iostream>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
int pos = postorder.size() - 1;
return buildTree(inorder, postorder, 0, inorder.size(), pos);
}
private:
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder, int start, int end, int &pos)
{
if (start >= end)
{
return NULL;
}
int k;
for (k = start; k < end; k++)
{
if (inorder[k] == postorder[pos])
{
break;
}
}
TreeNode *node = new TreeNode(postorder[pos]);
pos--;
node->right = buildTree(inorder, postorder, k + 1, end, pos);
node->left = buildTree(inorder, postorder, start, k, pos);
return node;
}
};
int main()
{
vector<int> inorder;
inorder.push_back(1);
inorder.push_back(2);
vector<int> postorder;
postorder.push_back(1);
postorder.push_back(2);
Solution solution;
cout << solution.buildTree(inorder, postorder);
getchar();
return 0;
}
|
Markdown
|
UTF-8
| 2,248 | 3.25 | 3 |
[] |
no_license
|
**Get All channels**
----
Returns json data about all channels in the system.
* **URL**
api/channels
* **Method:**
`GET`
* **URL Params**
None
* **Data Params**
None
* **Success Response:**
* **Code:** 200 <br />
**Content:** `[{ "name": "C1" }, { "name": "C2" }, { "name": "C3" }]`
* **Error Response:**
* **Code:** 404 NOT FOUND <br />
**Content:** `{ error : "channels are not found" }`
OR
* **Code:** 401 UNAUTHORIZED <br />
**Content:** `{ error : "You are unauthorized to make this request." }`
**Get a channel**
----
Returns json data about one channel based on id.
* **URL**
api/channels/:id
* **Method:**
`GET`
* **URL Params**
**Required:**
`id=[integer]`
* **Data Params**
None
* **Success Response:**
* **Code:** 200 <br />
**Content:** `{ "_id": 1, "name": "g1" }`
* **Error Response:**
* **Code:** 404 NOT FOUND <br />
**Content:** `{ error : "channel doesn't exist" }`
OR
* **Code:** 401 UNAUTHORIZED <br />
**Content:** `{ error : "You are unauthorized to make this request." }`
**Add a channel**
----
Returns json data about the added channel.
* **URL**
api/channels
* **Method:**
`POST`
* **URL Params**
None
* **Data Params**
**Content:** { "_id": 5, "name": "g5" }
* **Success Response:**
* **Code:** 200 <br />
**Content:** `{ "_id": 5, "name": "g5" }`
* **Error Response:**
* **Code:** 404 NOT FOUND <br />
**Content:** `{ error : "channel couldn't be add, channel with the same id already exist" }`
OR
* **Code:** 401 UNAUTHORIZED <br />
**Content:** `{ error : "You are unauthorized to make this request." }`
**Delete a channel**
----
Returns json data about success.
* **URL**
api/channels/:id
* **Method:**
`DELETE`
* **URL Params**
**Required:**
`id=[integer]`
* **Data Params**
None
* **Success Response:**
* **Code:** 200 <br />
**Content:** `{"isSuccess":"true"}`
* **Error Response:**
* **Code:** 404 NOT FOUND <br />
**Content:** `{ error : "channel couldn't be found" }`
OR
* **Code:** 401 UNAUTHORIZED <br />
**Content:** `{ error : "You are unauthorized to make this request." }`
|
Java
|
UTF-8
| 1,373 | 2.546875 | 3 |
[
"Apache-2.0"
] |
permissive
|
package com.talanlabs.taskmanager.engine.manager;
import com.talanlabs.taskmanager.engine.graph.IStatusGraph;
import com.talanlabs.taskmanager.engine.task.IStatusTask;
import com.talanlabs.taskmanager.model.ITaskObject;
import java.util.List;
public interface ITaskObjectManager<E, F extends ITaskObject> {
/**
* Get a class of taskObject
*
* @return a class
*/
Class<F> getTaskObjectClass();
/**
* Get a initial status for task object
*
* @param taskObject a task object
* @return a current status for task object
*/
E getInitialStatus(F taskObject);
/**
* Get next status graphs for task object and current status
* <p>
* Ex : A->(B,C) currentStatus is A then next is B and C
*
* @param statusTask status task
* @param currentStatus a current status
* @return a graph for next status
*/
List<IStatusGraph<E>> getNextStatusGraphsByTaskObjectType(IStatusTask statusTask, E currentStatus);
/**
* Get a rule with task definition between status for sub tasks
* <p>
* ex : A=>(B,C)
*
* @param statusTask status task
* @param currentStatus current status
* @param nextStatus next status
* @return a rule
*/
String getTaskChainCriteria(IStatusTask statusTask, E currentStatus, E nextStatus);
}
|
C++
|
UTF-8
| 1,112 | 2.546875 | 3 |
[] |
no_license
|
#include "stdlib.h"
#include "windows.h"
#include <ChaCha.h>
int main()
{
ChaCha c1;
ChaCha c2;
uint8_t key[ 32u ];
for( int i = 0u; i < sizeof( key ); ++i )
{
key[ i ] = uint8_t( rand() );
}
c1.setKey( key, sizeof( key ) );
c2.setKey( key, sizeof( key ) );
uint8_t iv[ 12u ];
for( int i = 0u; i < sizeof( iv ); ++i )
{
iv[ i ] = uint8_t( rand() );
}
c1.setIV( iv, sizeof( iv ) );
c2.setIV( iv, sizeof( iv ) );
const uint32_t counter = 1u;
c1.setCounter( (const uint8_t*)&counter, sizeof( counter ) );
c2.setCounter( (const uint8_t*)&counter, sizeof( counter ) );
char text[] = "Hello world!";
char buffer[ sizeof( text ) ];
c1.encrypt( (uint8_t*)buffer, (const uint8_t*)text, sizeof( text ) );
char buffer2[ sizeof( text ) ];
c2.decrypt( (uint8_t*)buffer2, (const uint8_t*)buffer, sizeof( buffer ) );
char buffer3[ sizeof( text ) ];
c1.decrypt( (uint8_t*)buffer3, (const uint8_t*)buffer, sizeof( buffer ) );
OutputDebugStringA( "\n" );
OutputDebugStringA( buffer2 );
OutputDebugStringA( "\n" );
OutputDebugStringA( buffer3 );
OutputDebugStringA( "\n" );
return 0;
}
|
Shell
|
UTF-8
| 7,670 | 4.03125 | 4 |
[
"Apache-2.0"
] |
permissive
|
#!/bin/bash
## Tested on:
## Mac OSX 10.11, 10.12 & 10.13
## Ubuntu 16.04
## Amazon Linux & Amazon Linux 2
## Tomato USB Router
## requires jq - available via most Linux package managers, Brew on OSX
## and binaries or source at https://stedolan.github.io/jq/download/
## Cache file settings
## cacheFileDir must end in /
## Recommend /tmp/ddns_cache/ to clear cache on restart
cacheFileDir="/tmp/ddns_cache/"
cacheFileExt=".ddns.tmp"
## Set default to ipv4, can be overridden by --ip-version
ipVersion="ipv4"
fail () {
echo "$(basename $0): $1"
exit 1
}
help () {
cat << EOF
Set the IP for a specific hostname on route53
route53-ddns-client.sh [options]
Options:
-h, --help
Display this help and exit.
--hostname HOSTNAME
Hostname to update. Example: "host1.dyn.example.com."
Hostname requires the trailing '.' in request and the DDB config table entry.
Required argument.
--secret SECRET
Secret to use when validating the request for the hostname.
Required argument.
--api-key
Pass the Amazon API Gateway API Key
--url API_URL
The URL where to send the requests.
Required argument.
--ip-source public | IP | INTERFACE
This arguments defines how to get the IP we update to.
public - use the public IP of the device (default)
IP - use a specific IP passed as argument
INTERFACE - use the IP of an interface passed as argument eg: eth0 eth0.1 or eth0:1
--cache CACHE_TTL_MINUTES
Stores a cache file in $cacheFileDir
Whenever invoked, if the IP we want to update to is already cached, save some
requests and stop. (Note that this will only save significant cost at scale)
TTL is used to invalidate cache.
If omitted, caching is disabled.
--ip-version ipv4 | ipv6
If called, requires an argument.
Assumes ipv4 if omitted.
--list-hosts
List hosts from DynamoDB that belong to the same group as the calling host.
Hosts are grouped by shared secret.
Not yet fully implemented. Will allow a single host to set records for all hosts on
a network segment.
Not required.
No argument.
EOF
}
# Parse arguments
while [[ $# -ge 1 ]]; do
i="$1"
case $i in
-h|--help)
help
exit 0
;;
--hostname)
if [ -z "$2" ]; then
fail "\"$1\" argument needs a value."
fi
if [[ "$2" == *. ]]; then
myHostname=$2
else
## add trailing . if omitted
myHostname=$2
myHostname+='.'
fi
shift
;;
--secret)
if [ -z "$2" ]; then
fail "\"$1\" argument needs a value."
fi
mySharedSecret=$2
shift
;;
--url)
if [ -z "$2" ] ; then
fail "\"$1\" argument needs a value."
fi
if [[ "$2" == "https://"* ]]; then
myAPIURL=$2
else
myAPIURL="https://"$2
fi
shift
;;
--ip-source)
if [ -z "$2" ] ; then
fail "\"$1\" argument needs a value."
fi
ipSource=$2
shift
;;
--cache)
if [ -z "$2" ] ; then
fail "\"$1\" argument needs a value."
fi
if [[ $2 =~ [0-9]+ ]]; then
cacheTtl=$2
cache=true
if [ ! -d $cacheFileDir ]; then mkdir -p $cacheFileDir ; fi
else
fail "\"$1\" argument must be an integer reflecting ttl in minutes."
fi
shift
;;
--ip-version)
if [ -z "$2" ] ; then
fail "\"$1\" argument needs a value."
fi
ipVersion=$2
shift
;;
--list-hosts)
listHosts=true
shift
;;
--api-key)
if [ -z "$2" ] ; then
fail "\"$1\" argument needs a value."
fi
apiKey="$2"
shift
;;
*)
fail "Unrecognized option $1."
;;
esac
shift
done
# If the script is called with no arguments, show an instructional error message.
if [ -z "$myHostname" ] || [ -z "$mySharedSecret" ] || [ -z "$myAPIURL" ]; then
echo "$(basename $0): Required arguments missing."
help
exit 1
fi
cacheFile="$cacheFileDir$myHostname$ipVersion$cacheFileExt"
## get public IP from reflector to generate hash &/or set IP
myPublicIP=$(curl -q --$ipVersion -s -H "x-api-key: $apiKey" "$myAPIURL?mode=get" | jq -r '.return_message //empty')
if [ "$ipSource" = "public" ] || [ -z "$ipSource" ]; then
myIp=$myPublicIP
[ -z "$myIp" ] && fail "Couldn't find your public IP"
## match interface formats eth0 eth0:1 eth0.1
elif [[ $ipSource =~ ^[0-9a-z]+([:.][0-9]+){0,2}$ ]]; then
if [ "$ipVersion" = "ipv4" ]; then
myIp="$(ifconfig "$ipSource" |egrep 'inet\ '|egrep -o '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])' |head -1)"
[ -z "$myIp" ] && fail "Couldn't get the IP of $ipSource"
elif [ "$ipVersion" == "ipv6" ]; then
myIp="$(ifconfig "$ipSource" |egrep 'inet6' |egrep -v 'fe80'|egrep -v 'temporary'|egrep -io '([A-F0-9]{1,4}:){7}[A-F0-9]{1,4}')"
[ -z "$myIp" ] && fail "Couldn't get the IP of $ipSource"
else
fail "Interface source called, but ipVersion is not set." ## This should never happen. Defaults set to ipv4 at top of script
fi
## match ipv4
elif [[ "$ipSource" =~ ^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$ ]]; then
myIp="$ipSource"
## match ipv6
elif [[ "$ipSource" =~ ^[0-9A-Fa-f:]+$ ]]; then
myIp="$ipSource"
else
fail "Invalid --ip-source argument. Check help."
fi
if [ "$cache" = "true" ] && [ -f "$cacheFile" ] && [ `find $cacheFile -mmin -"$cacheTtl" | grep '.*'` ]; then
cached_myIp=$(cat $cacheFile)
if [ "$cached_myIp" = "$myIp" ]; then
echo "$(basename $0): Found a cached update."
exit 0
fi
fi
echo "$(basename $0): Updating $myHostname to IP $myIp"
## Build the hashed token
## Check for shasum (OSX) vs sha256sum (Linux) then execute the appropriate command.
if command -v shasum > /dev/null 2>&1 ; then
myHash=$(printf "$myPublicIP$myHostname$mySharedSecret" | shasum -a 256 | awk '{print $1}')
elif command -v sha256sum > /dev/null 2>&1 ; then
myHash=$(printf "$myPublicIP$myHostname$mySharedSecret" | sha256sum | awk '{print $1}')
else
fail "Neither shasum nor sha256sum executables were found on host."
fi
if [ "$listHosts" = "true" ]; then
reply=$(curl -q --$ipVersion -s -H "x-api-key: $apiKey" "$myAPIURL?mode=list_hosts&hostname=$myHostname&hash=$myHash")
# Call the API in set mode to update Route 53
elif [ "$listHosts" != "true" ] && [ "$ipSource" = "public" ]; then
reply=$(curl -q --$ipVersion -s -H "x-api-key: $apiKey" "$myAPIURL?mode=set&hostname=$myHostname&hash=$myHash")
else
reply=$(curl -q --$ipVersion -s -H "x-api-key: $apiKey" "$myAPIURL?mode=set&hostname=$myHostname&hash=$myHash&internalIp=$myIp")
fi
if [ "$(echo "$reply" | jq -r '.return_status //empty')" == "success" ]; then
if [ "$cache" = "true" ]; then
echo "$myIp" > $cacheFile
fi
echo "$(basename $0): Request succeeded: $(echo "$reply"| jq -r '.return_message //empty')"
else
echo "$(basename $0): Request failed: $(echo "$reply" | jq -r '.return_message //empty')"
exit 1
fi
|
C++
|
GB18030
| 9,597 | 2.546875 | 3 |
[] |
no_license
|
#define _CRT_SECURE_NO_DEPRECATE 0
/*
* Copyright(C), 2007-2008, XUPT Univ.
* ţTTMS_UC_02
* File name: Seat_UI.c
* Description : λ
* Author: XUPT
* Version: v.1
* Date: 2015422
*/
#include "EntityKey_Persist.h"
#include "Seat_UI.h"
#include "Seat.h"
#include "Studio.h"
#include "List.h"
#include <stdio.h>
#include <conio.h>
#pragma warning(disable: 4996)
/*
ʶTTMS_SCU_Seat_UI_S2C
ܣλ״̬ȡʾš
˵statusΪseat_status_tͣʾλ״̬
ֵַͣʾλĽʾš
*/
inline char Seat_UI_Status2Char(seat_status_t status) {
char statusChar;
switch (status) {
case SEAT_GOOD: //λ
statusChar = '#';
break;
case SEAT_BROKEN: //λ
statusChar = '~';
break;
case SEAT_NONE:
statusChar = '/';
break;
default:
//statusChar = '/';//ûλ
break;
}
return statusChar;
}
/*
ʶTTMS_SCU_Seat_UI_C2S
ܣŻȡλ״̬
˵statusCharΪַͣʾλš
ֵseat_status_tͣʾλ״̬
*/
inline seat_status_t Seat_UI_Char2Status(char statusChar) {
seat_status_t status;
switch (statusChar) {
case '#': //λ
status = SEAT_GOOD;
break;
case '~': //λ
status = SEAT_BROKEN;
break;
default:
status = SEAT_NONE;
break;
}
return status;
}
/*
ʶTTMS_SCU_Seat_UI_MgtEnt
ܣλںʾǰλݣṩλӡġɾܲڡ
˵roomIDΪͣҪλݳID
ֵޡ
*/
void Seat_UI_MgtEntry(int roomID) {
int i, j;
char choice;
int seatCount;
int changedCount = 0;
studio_t studioRec;
if (!Studio_Srv_FetchByID(roomID, &studioRec))
{ //öӦidӳϢ
printf("\t\t\tݳ,");
getch();
return;
}
seat_list_t list;
seat_node_t *p;
List_Init(list, seat_node_t);
//ѡӳλ
seatCount = Seat_Srv_FetchByRoomID(list, roomID);
if (!seatCount) { //ӳûλԶλ
seatCount = Seat_Srv_RoomInit(list, roomID, studioRec.rowsCount,
studioRec.colsCount);
//ݳλ
studioRec.seatsCount = seatCount;
Studio_Srv_Modify(&studioRec);
}
do {
system("cls");
printf("\n\t\t\t\t%d ݳλһͼ\n", roomID);
printf("\n\t\t\t\t=========================================================\n\n\n");
printf("%4c ", ' ');
printf("\t\t\t\t\t ");
for (i = 1; i <= studioRec.colsCount; i++) {
printf("%3d", i);
}
printf("\n\n");
//ʾ
for (i = 1; i <= studioRec.rowsCount; i++) {
j = 1;
printf("\t\t\t\t\t%2d %c", i, ' ');
List_ForEach(list, p)
{
if (p->data.row == i) {
while (p->data.column != j) {
// printf("gg");
printf("%3c", ' ');
j++;
}
printf("%3c", Seat_UI_Status2Char(p->data.status));
j++;
}
}
printf("\n");
}
printf("\n\n\n\t\t\t\t 1. 2.ɾ 3. 4. ");
printf("\n\n\t\t\t\t Your choice:");
choice = getche();
switch (choice) {
case '1':
changedCount = Seat_UI_Add(list, roomID, studioRec.rowsCount,
studioRec.colsCount);
if (changedCount > 0) {
seatCount += changedCount;
//ݳλ
studioRec.seatsCount = seatCount;
Studio_Srv_Modify(&studioRec);
}
break;
case '2':
changedCount = Seat_UI_Delete(list, studioRec.rowsCount,
studioRec.colsCount);
if (changedCount > 0) {
seatCount -= changedCount;
//ݳλ
studioRec.seatsCount = seatCount;
Studio_Srv_Modify(&studioRec);
}
break;
case '3':
Seat_UI_Modify(list, studioRec.rowsCount, studioRec.colsCount);
break;
}
} while (choice != '4');
//ͷռ
List_Destroy(list, seat_node_t);
}
/*
ʶTTMS_SCU_Seat_UI_Add
ܣһµλݡ
˵һlistΪseat_list_tָ룬ָλͷָ룬
ڶrowsCountΪͣʾλкţcolsCountΪͣʾλкš
ֵͣʾǷɹλı־
*/
int Seat_UI_Add(seat_list_t list, int roomID, int row, int column) { //һλ
//һλ
seat_t rec;
seat_node_t *p;
int newRecCount = 0;
char choice;
do {
printf("\n\t\t\t==================================================================\n");
printf("\t\t\t µλ \n");
printf("\t\t\t------------------------------------------------------------------\n");
do {
printf("\t\t\tܳ %d вܳ %d!\n", row, column);
printf("\t\t\tλ:");
scanf("%d", &(rec.row));
printf("\t\t\tλ:");
scanf("%d", &(rec.column));
fflush(stdin);
} while (rec.row > row || rec.column > column);
p = Seat_Srv_FindByRowCol(list, rec.row, rec.column);
if (p != NULL) { //кӦλѴڣܲ
printf("\t\t\tΪѴ! \n");
printf("\t\t\t------------------------------------------------------------------\n");
printf("\t\t\t[A] [R] : ");
fflush(stdin);
choice = getche();
continue;
}
rec.id = EntKey_Perst_GetNewKeys("Seat", 1); //λid
rec.roomID = roomID;
rec.status = SEAT_GOOD; //λ״̬ĬΪλ
printf("\t\t\t==================================================================\n");
if (Seat_Srv_Add(&rec)) {
newRecCount++;
printf("\t\t\tλɹ!\n");
p = (seat_node_t*)malloc(sizeof(seat_node_t));
p->data = rec;
Seat_Srv_AddToSoftedList(list, p); //λlist
}
else
printf("\t\t\tλʧ!\n");
printf("\t\t\t------------------------------------------------------------------\n");
printf("\t\t\t[A] [R] : ");
fflush(stdin);
choice = getche();
} while ('a' == choice || 'A' == choice);
//getchar();
return newRecCount;
}
/*
ʶTTMS_SCU_Seat_UI_Mod
ܣһλݡ
˵һlistΪseat_list_tָ룬ָλͷָ룬ڶrowsCountΪͣʾλкţcolsCountΪͣʾλкš
ֵͣʾǷɹλı־
*/
int Seat_UI_Modify(seat_list_t list, int row, int column) {
int rtn = 0;
int newrow, newcolumn;
char choice;
seat_node_t *p;
printf("\n\t\t\t==================================================================\n");
printf("\t\t\t λ \n");
printf("\t\t\t------------------------------------------------------------------\n");
do {
do { //µλϢܳӳ
printf("\t\t\tܳ %d вܳ %d!\n", row, column);
printf("\t\t\tλ :");
scanf("%d", &newrow);
printf("\t\t\tλ :");
scanf("%d", &newcolumn);
getchar();
} while (newrow > row || newcolumn > column);
p = Seat_Srv_FindByRowCol(list, newrow, newcolumn);
if (p) {
printf("\t\t\tλ [%d,%d]: [%c]:", newrow, newcolumn, Seat_UI_Status2Char(p->data.status));
//fflush(stdin);
//getchar();
p->data.status = Seat_UI_Char2Status(getchar());
printf("\t\t\t-------------------------------------------------------------------\n");
if (Seat_Srv_Modify(&(p->data))) {
rtn = 1;
printf("\t\t\tλɹ!\n");
}
else
printf("\t\t\tλʧ!\n");
}
else
printf("\t\t\tλ!\n");
printf("\t\t\t-------------------------------------------------------------------\n\t\t\t");
printf("[U], [R] : ");
choice = getche();
} while ('u' == choice || 'U' == choice);
return rtn;
}
/*
ʶTTMS_SCU_Seat_UI_Del
ܣɾһλݡ
˵һlistΪseat_list_tָ룬ָλͷָ룬ڶrowsCountΪͣʾλкţcolsCountΪͣʾλкš
ֵͣʾǷɹɾλı־
*/
int Seat_UI_Delete(seat_list_t list, int row, int column) {
int delSeatCount = 0;
int newrow, newcolumn;
seat_node_t *p;
char choice;
do {
printf("\n\n\tɾλ\n");
printf("\t=========================================================\n");
do {
fflush(stdin);
printf("\t(Сڵ %d):", row);
scanf("%d", &(newrow));
printf("\t(Сڵ %d):", column);
scanf("%d", &(newcolumn));
fflush(stdin);
} while (newrow > row || newcolumn > column);
p = Seat_Srv_FindByRowCol(list, newrow, newcolumn);
if (p) {
if (Seat_Srv_DeleteByID(p->data.id)) {
printf("\tɾɹ\n");
delSeatCount++;
List_FreeNode(p); //ͷŽλp
}
}
else {
printf("\tλ\n");
}
printf("\t------------------------------------------------------------------\n");
printf("\t[1]ɾ\t[2]");
choice = getche();
} while ('1' == choice);
return delSeatCount;
}
|
Python
|
UTF-8
| 225 | 3.359375 | 3 |
[] |
no_license
|
print('Just another print statement. Nothing special.')
import test
var = input('What is the radius of the circle?')
print('Circumference is', test.Circumference(float(var)), 'and area is', test.Surface_area(float(var)))
|
Python
|
UTF-8
| 1,494 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
def ergMetersPerDay(workoutsData, Activities, DateManager):
chronologicalData = DateManager.getWorkoutsDataChronologically(workoutsData)
ergMetersPerDay = {}
for workout in chronologicalData:
workoutDate = DateManager.fetchDateFromTimestampString(workout['time'])
if (workoutDate not in ergMetersPerDay.keys()):
ergMetersPerDay[workoutDate] = 0
if (workout['type'] == Activities.Erg.name):
ergMetersPerDay[workoutDate] += int(workout['scored_meters'])
return ergMetersPerDay
def ergMetersPerWeek(workoutsData, Activities, DateManager):
chronologicalData = DateManager.getWorkoutsDataChronologically(workoutsData)
ergMetersPerWeek = {}
for workout in chronologicalData:
workoutDate = DateManager.fetchDateFromTimestampString(workout['time'])
workoutDateWeek = DateManager.getMondayDateFromDate(workoutDate)
if (workoutDateWeek not in ergMetersPerWeek.keys()):
ergMetersPerWeek[workoutDateWeek] = 0
if (workout['type'] == Activities.Erg.name):
ergMetersPerWeek[workoutDateWeek] += int(workout['scored_meters'])
return ergMetersPerWeek
def run(workoutsData, Activities, DateManager):
return ergMetersPerDay(workoutsData, Activities, DateManager)
def run(workoutsData, Activities, DateManager, isWeek):
if isWeek:
return ergMetersPerWeek(workoutsData, Activities, DateManager)
return ergMetersPerDay(workoutsData, Activities, DateManager)
|
Java
|
UTF-8
| 859 | 3.5 | 4 |
[] |
no_license
|
public class Example1{
@FunctionalInterface
interface HelloWorld{
default void sayGoodBye(){
System.out.println("adeus mundo");
}
void sayHelloWorld(String message);
//void xpto(String xxxx);
}
class HelloWorldImpl implements HelloWorld{
public void sayHelloWorld(String message){
System.out.println(message);
}
}
public static void main(String[] args){
//HelloWorld msg = new HelloWorldImpl();
HelloWorld msg1 = (String message) -> {System.out.println(message);};
HelloWorld msg2 = (message) -> {System.out.println(message);};
HelloWorld msg3 = message -> {System.out.println(message);};
HelloWorld msg4 = message -> System.out.println(message);
msg1.sayHelloWorld("HelloWorld");
msg2.sayHelloWorld("HelloWorld");
msg3.sayHelloWorld("HelloWorld");
msg4.sayHelloWorld("HelloWorld");
msg1.sayGoodBye();
}
}
|
Markdown
|
UTF-8
| 2,762 | 2.6875 | 3 |
[] |
no_license
|
```python
import equity_backtesting_library as elib
import datetime as dt
result = {}
result['instrument'] = 'SOXX'
result['spread'] = 0
result['sign1'], result['sign2'] = elib.strategy_type('medium')
result['margin_used'] = 1
result['funds'] = 50000
result['levarage'] = 1
result['tx_cost'] = 0
result['strategy'] = "soxx_medium"
```
## Load data
```python
import equity_backtesting_library as elib
import datetime as dt
result = {}
result['instrument'] = 'SOXX'
result['spread'] = 0
result['sign1'], result['sign2'] = elib.strategy_type('medium')
result['margin_used'] = 1
result['funds'] = 50000
result['levarage'] = 1
result['tx_cost'] = 0
result['strategy'] = "soxx_medium"
stock = elib.get_ticker('SOXX')
print(stock)
stock.info
df = stock.history(period="max")
df = elib.compute_signals(df, result['sign1'], result['sign2'])
del(df['Dividends'])
del(df['Stock Splits'])
del(df['Open'])
del(df['High'])
del(df['Low'])
df.tail()
```
## Plot of periods of trading
```python
elib.plot_slice(df, '2005-08-08 00:00:00', '2006-01-22 08:13:00')
```

```python
elib.plot_slice(df, '2016-10-08 00:00:00', '2017-01-22 08:13:00')
```

```python
elib.plot_slice(df, '2017-01-02 08:13:00', '2017-01-25 08:13:00')
```

```python
elib.plot_slice(df, '2017-01-03 08:13:00', '2017-01-06 08:13:00')
```

```python
elib.plot_slice(df, '2019-06-10 08:13:00', '2019-10-16 08:13:00')
```

```python
elib.plot_slice(df, '2020-01-01 08:00:00', '2020-04-24 22:13:00')
```

## Calculation of returns
```python
df = elib.long_returns(df, result)
result['total_returns'] = elib.net_returns(
result['funds'],
result['margin_used'],
df,
result['levarage'])
result['returns'] = elib.inst_returns(
result['funds'],
result['margin_used'],
df,
result['levarage'])
print('Instrument returns: ', result['returns'])
print('strategy returns: ', result['total_returns'])
result['created_at'] = dt.datetime.utcnow()
print('-----------------------------------------------------')
print("Number of transactions: {}".format(sum(df['position'].diff() != 0)))
result['transaction_cost'] = sum(df['position'].diff() != 0) * \
result['funds'] * result['margin_used'] * result['levarage'] * result['spread']
# print("transaction_cost: {}".format(result['transaction_cost']))
print("Transaction cost: {}".format((sum(df['position'].diff() != 0) * 10)))
```
('Instrument returns: ', 68083.94595485604)
('strategy returns: ', 122485.48105221153)
-----------------------------------------------------
Number of transactions: 110
Transaction cost: 1100

|
Markdown
|
UTF-8
| 5,746 | 2.703125 | 3 |
[] |
no_license
|
# Get UniProt Protein Info (GUPPI)
Process TDReports or flat files by getting information from the UniProt webservice and filtering by a selectable FDR value. Install the necessary packages (using `A_install.packages.R`), set input parameters and source `00_run_all.R` to process data.
## Input
All input parameters are given in 00_run_all.R, in the "Initialize Parameters" section. Acceptable input files are tdReport, xlsx, or csv format. Only one kind of file can be processed at a time. Data in xlsx or csv files must be a list of UniProt accession numbers with a column name that includes the word "Accession". Capitalization doesn't matter but spelling does.
- `filedir <- c("Path to Folder or File")` Add the path of files to be processed. There are several options for adding input files:
- Enter the full path to the folder containing multiple files to be scanned, e.g. `filedir <- c("Z:/ICR/David Butcher/TDReports/")`. By default all subdirectories will be checked *unless* the directory has "deprecated" in its name. **Make sure to add the final forward slash** for directory names.
- Enter the full path to a single file, e.g. `filedir <- c("Z:/ICR/David Butcher/TDReports/Specific1.tdReport")`
- Enter the full path to multiple single files, e.g. `filedir <- c("Z:/ICR/David Butcher/TDReports/Specific1.tdReport", "Z:/ICR/David Butcher/TDReports/Specific2.tdReport")`
- `fdr <- 0.01` This is the value used for the False Detection Rate cutoff. Defaults to 0.01 (1% FDR).
- `taxon_number <- 83333` UniProt taxon number for organism of interest. Defaults to 83333 for *E. coli* K12. Value for *Homo sapiens* is 9606. Taxons 83333 and 9606 are predownloaded (in /input), any other taxon number will take some time to download (about 20 minutes for taxon 83333).
- `use_PB <- FALSE` Optional parameter. If set to true, `RPushbullet` will be used to send a Pushbullet notification to your device when the analysis is finished. See `?RPushbullet::pbSetup` for more info.
- `make_report <- FALSE` Controls whether a summary HTML report is generated in the `output/report` folder. Though it will work, I wouldn't reccomend doing this with an analysis of >12 TD reports.
## Analysis
### Flat Files
The taxon number is checked against files in the `/input` directory to see if a corresponding UniProt taxon database has already been downloaded. If not, the UniProt web service is queried for all UniProt accession numbers in the taxon using the package `UniProt.ws`. Protein name, organism, organism taxon ID, protein sequence, protein function, subcellular location, and any associated GO IDs are returned. Note that some of these values may not be found and come back as empty or NA.
The UniProt taxon database is used to add information for all accession number entries in the flat file. GO terms are obtained for all GO IDs using the `GO.db` package and terms corresponding to subcellular locations are saved in column "GO_subcellular_locations". Average and monoisotopic masses are determined using the `Peptides` package.
### TD Reports
A connection is established to the SQLite database in the TD Report using `RSQLite`. The "main" output includes all protein isoform accession numbers with the lowest Q value from among all hits for each isoform and the name of the data file from which the lowest Q value hit was obtained. All isoforms with Q values which are missing or greater than the cutoff value are deleted. Output is also generated which contains all hits for all isoforms that are above the FDR cutoff (`/allproteinhits`) and lowest Q-value hits sorted by data file (`/proteinsbydatafile`).
UniProt data is added as detailed in the `Flat Files` section, with the exception that average and monoisotopic masses are taken directly from the tdReport file.
Minimum Q value from among all hits, average and monoisotopic masses, and data file for lowest Q value hit are obtained for all proteoforms. Proteoforms whose Q values are above the FDR cutoff are deleted. Proteoforms whose corresponding protein isoform entry is above the FDR cutoff are also deleted. UniProt info for every unique proteoform record number is copied from corresponding protein entries to avoid wasting time by querying the UniProt database again.
## Output
Output files are saved to the output directory. Files are timestamped with the time the script was initialized or share the same name as the input file.
* Protein results are saved to `output/YYYYMMDD_hhmmss_protein_results.xlsx` and `rds/YYYYMMDD_hhmmss_protein_results.rds`.
* Proteoform results are saved to `output/YYYYMMDD_hhmmss_proteoform_results.xlsx` and `rds/YYYYMMDD_hhmmss_protein_results.rds`.
+ Output xlsx files contain sheets corresponding to each input file specified in 00_run_all.R and a final summary sheet containing all input file names and counts of cytosolic/membrane proteins.
* Lists of all protein hits including UniProt accession number, Q value, data file, result type (i.e. tight absolute mass, find unexpected modifications, or biomarker) are saved to `output/allproteinhits` and share names with input files.
* Lists of all unique protein hits for each data file in a TDReport (intended for use in UpSet plots, pie charts, waffle plots, etc.) are saved to `output/proteinsbydatafile`.
* Lists of proteins counted by subcellular location for every individual datafile in the analysis are saved to `output/countsbydatafile`.
* Mass histograms for identified proteins and proteoforms are saved to `/png` and `/pdf` in the corresponding formats.
* Workspace images (.Rdata file containing all R objects) from the end of the analysis are saved to `output/workspace_images`.
* If `make_report` is set to TRUE, an HTML report is saved to `output/report`.
|
Java
|
UTF-8
| 4,640 | 2.09375 | 2 |
[] |
no_license
|
/*
Copyright (c) 2004, The JAP-Team
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
- Neither the name of the University of Technology Dresden, Germany nor the names of its contributors
may be used to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE
*/
package anon.tor;
import anon.AnonServerDescription;
public class TorAnonServerDescription implements AnonServerDescription
{
private int m_iTorDirServerPort;
private String m_strTorDirServerAddr;
private final boolean m_bUseInfoService;
private final boolean m_bStartCircuitsAtStartup;
private int m_iMaxRouteLen=Tor.MAX_ROUTE_LEN;
private int m_iMinRouteLen=Tor.MIN_ROUTE_LEN;
private int m_iMaxConnectionsPerRoute=Circuit.MAX_STREAMS_OVER_CIRCUIT;
/**
* Constructor
*/
public TorAnonServerDescription()
{
m_strTorDirServerAddr = Tor.DEFAULT_DIR_SERVER_ADDR;
m_iTorDirServerPort = Tor.DEFAULT_DIR_SERVER_PORT;
m_bUseInfoService = false;
m_bStartCircuitsAtStartup = false;
}
/**
* Constructor
* @param bUseInfoService
* use the info service
*/
public TorAnonServerDescription(boolean bUseInfoService)
{
this(bUseInfoService, false);
}
/**
* Constructor
* @param bUseInfoService
* use the info service
* @param bStartCircuitsAtStartup
* start all circuits at startup
*/
public TorAnonServerDescription(boolean bUseInfoService, boolean bStartCircuitsAtStartup)
{
if (bUseInfoService)
{
m_strTorDirServerAddr = null;
m_iTorDirServerPort = -1;
m_bUseInfoService = true;
}
else
{
m_strTorDirServerAddr = Tor.DEFAULT_DIR_SERVER_ADDR;
m_iTorDirServerPort = Tor.DEFAULT_DIR_SERVER_PORT;
m_bUseInfoService = false;
}
m_bStartCircuitsAtStartup = bStartCircuitsAtStartup;
}
/**
* Constructor
* @param torDirServerAddr
* address of a tor directory server
* @param torDirServerPort
* port of the tor directory server
* @param bStartCircuitsAtStartup
* start all circuits at startup
*/
public TorAnonServerDescription(String torDirServerAddr, int torDirServerPort,
boolean bStartCircuitsAtStartup)
{
m_strTorDirServerAddr = torDirServerAddr;
m_iTorDirServerPort = torDirServerPort;
m_bUseInfoService = false;
m_bStartCircuitsAtStartup = bStartCircuitsAtStartup;
}
public void setTorDirServer(String hostname,int port)
{
m_strTorDirServerAddr=hostname;
m_iTorDirServerPort=port;
}
/**
* gets the address of the tor directory server
* @return
* IP address
*/
public String getTorDirServerAddr()
{
return m_strTorDirServerAddr;
}
/**
* gets the port of the tor directory server
* @return
* port
*/
public int getTorDirServerPort()
{
return m_iTorDirServerPort;
}
/**
* gets if the infoservice is used
* @return
*/
public boolean useInfoService()
{
return m_bUseInfoService;
}
/**
* gets if all circuits are created on startup
* @return
*/
public boolean startCircuitsAtStartup()
{
return m_bStartCircuitsAtStartup;
}
public void setMaxRouteLen(int i)
{
m_iMaxRouteLen=i;
}
public int getMaxRouteLen()
{
return m_iMaxRouteLen;
}
public void setMinRouteLen(int i)
{
m_iMinRouteLen=i;
}
public int getMinRouteLen()
{
return m_iMinRouteLen;
}
public void setMaxConnectionsPerRoute(int i)
{
m_iMaxConnectionsPerRoute=i;
}
public int getMaxConnectionsPerRoute()
{
return m_iMaxConnectionsPerRoute;
}
}
|
C++
|
UTF-8
| 808 | 3.484375 | 3 |
[] |
no_license
|
#pragma once
#include <string>
class Board{
public:
enum Play{
X = -1,
O = 0
};
Board();
~Board();
/**
* @brief Checks if the board has a winner
*
* @return char 'x' if x wins or 'o' of o wins. Otherwise returns a space ' '
*/
char winner();
/**
* @brief Gets the value of the board at a position
*
* @param pos the position to get
* @return int the value at pos
*/
int get(int pos);
/**
* @brief Sets the value of the board at a given position
*
* @param pos position to set
* @param play the value to set
*/
char set(int pos, Board::Play play);
void reset();
private:
int m_board[9];
int check_rows();
int check_cols();
int check_diag();
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.