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 |
|---|---|---|---|---|---|---|---|
Shell | UTF-8 | 544 | 3.09375 | 3 | [] | no_license | #!/bin/bash
source "./00_check_condition.include"
create_veth_pair_data() {
DATA_NS=$1
DATA_VETH_NS=$2
DATA_VETH_HOST=$3
DATA_VETH_IP_NS=$4
DATA_VETH_BR=$5
if [ ! -z $DATA_VETH_NS ]; then
echo "*** create DATA veth pair"
create_veth_pair_link_host $DATA_NS \
$DATA_VETH_NS $DATA_VETH_HOST \
$DATA_VETH_IP_NS \
$DATA_VETH_BR
fi
}
create_veth_pair_data $NS_NAME $DATA_DEV_NS $DATA_DEV_HOST $DATA_IP_NS $DATA_BR
create_veth_pair_data $END_4_NS_NAME $DATA_1_DEV_NS $DATA_1_DEV_HOST $DATA_1_IP_NS $DATA_1_BR
|
JavaScript | UTF-8 | 998 | 3.375 | 3 | [] | no_license | 'use strict';
function showCirclePromise(radius) {
return new Promise(resolve => {
let circle = document.createElement('div');
Object.assign(circle.style, configureStyles(radius));
circle.id = 'circle2';
let prevCircle = document.getElementById("circle2");
let container = document.getElementById('circle-container2');
if (prevCircle) prevCircle.remove();
container.append(circle);
setTimeout(() => {
circle.style.width = radius * 2 + 'px';
circle.style.height = radius * 2 + 'px';
circle.addEventListener('transitionend', function handler() {
circle.removeEventListener('transitionend', handler);
resolve("Hello");
});
}, 10);
});
}
function showTextPromise(text) {
let container = document.createElement('div');
container.append(text);
let circle = document.getElementById("circle2");
circle.append(container);
} |
Python | UTF-8 | 4,005 | 2.671875 | 3 | [
"MIT"
] | permissive | from bs4 import BeautifulSoup
import re
import csv
import time
import requests
DEFAULT_MENU_PATH = "./get_industy_name/classify/menu.csv"
class SearchClassify(object):
def __init__(self, csv_file):
self.companyinfo = {}
self.count = 0
self.company_name = ""
self.company_name_full = ""
self.api = 'https://ja.wikipedia.org/w/api.php?format=json&action=query&prop=revisions&titles={company_name}&rvprop=content&rvparse'
self.html_text = ""
self.classify = ""
self.category = ""
self.csv_file = csv_file
self.menu_file = DEFAULT_MENU_PATH
def input_company(self, company_name_full):
self.company_name_full = company_name_full
self.company_name = self.company_name_full.replace("株式会社", "")
self.company_name = self.company_name.replace("合同会社", "")
url = self.api.format(company_name=self.company_name)
self._find_classify(url)
self._find_category()
self.companyinfo.update({
"name{}".format(str(self.count)): self.company_name_full,
"classify{}".format(str(self.count)): self.classify,
"category{}".format(str(self.count)): self.category
})
self.count += 1
return self.companyinfo
def _find_classify(self, url):
time.sleep(3)
try:
request = requests.get(url)
json_content = request.json()
json_query_pages = json_content["query"]["pages"]
for id in json_query_pages:
company_id = id
self.html_text = json_query_pages[company_id]["revisions"][0]["*"]
except:
self.classify = ""
self.category = ""
return self.classify, self.category
if self.html_text:
try:
soup = BeautifulSoup(self.html_text, "lxml")
candidates = soup.find_all("a")
a_tag_gyousyu = soup.find("a", title=re.compile("業種"))
tag_classify = candidates[candidates.index(a_tag_gyousyu) + 1]
self.classify = self._remove_tag(tag_classify)
except:
pass
elif self.html_text.find("th", text=re.compile("団体種類")):
try:
str_page_all = self.html_text
dantai_split1 = str_page_all.split('団体種類</th>')
dantai_split2 = dantai_split1[1].split('td class="" itemprop="" style="">')
dantai_split3 = dantai_split2[1].split('</td>')
tag_classify = dantai_split3[0]
self.classify = self._remove_tag(tag_classify)
except:
pass
elif "省" in self.company_name or "庁" in self.company_name:
self.classify = "官公庁"
elif "大学" in self.company_name or "学園" in self.company_name:
self.classify = "文教"
elif "市" in self.company_name \
or "区" in self.company_name \
or "町" in self.company_name \
or "村" in self.company_name:
self.classify = "市区町村"
else:
self.category = ""
self.classify = ""
return self.classify, self.category
def _remove_tag(self, tag_classify):
item_str = str(tag_classify)
classify_split1 = item_str.split('">')
classify_split2 = classify_split1[1].split("</a>")
classify = classify_split2[0]
return classify
def _find_category(self):
with open(self.menu_file, 'r+') as f:
reader = csv.reader(f)
templist = []
tempcount = 0
for r in reader:
templist[tempcount*2:tempcount*2] = r
tempcount += 1
try:
i = templist.index(self.classify) + 1
self.category = templist[i]
except:
pass
return self.category
|
Ruby | UTF-8 | 87 | 2.90625 | 3 | [] | no_license | fibonacci = 8.times.inject([0,1]) do |a, idx|
a << a[-2] + a[-1]
end
puts fibonacci |
Markdown | UTF-8 | 13,220 | 3.09375 | 3 | [] | no_license | ---
order: 1
title: Start Here
---
# Alpine.js を始めましょう!
まずは、`i-love-alpine.html`という名前で、空のHTMLファイルを作成します。
テキストエディタを使用して、ファイルに以下の内容を入力します。
```alpine
<html>
<head>
<script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>
</head>
<body>
<h1 x-data="{ message: 'I ❤️ Alpine' }" x-text="message"></h1>
</body>
</html>
```
Webブラウザーで保存したファイルを開いてみましょう。`I ❤️ Alpine`と表示されていれば大丈夫です!
準備が整ったので、アルパインの基本を教えるための基礎として、3つの実用的な例を見てみましょう。この演習の終わりまでに、あなたは自分でものを作り始める準備ができているはずです。それでは、レッツゴー!
<!-- START_VERBATIM -->
<ul class="flex flex-col space-y-2 list-inside !list-decimal">
<li><a href="#building-a-counter">カウンターを作る</a></li>
<li><a href="#building-a-dropdown">ドロップダウンの作成</a></li>
<li><a href="#building-a-search-input">検索入力の作成</a></li>
</ul>
<!-- END_VERBATIM -->
<a name="building-a-counter"></a>
## カウンターを作る
簡単な「カウンター」コンポーネントから始めて、2つのコア機能であるアルパインでの状態とイベントのリスニングの基本を示しましょう。
`<body>` タグに以下を挿入します。
```alpine
<div x-data="{ count: 0 }">
<button x-on:click="count++">Increment</button>
<span x-text="count"></span>
</div>
```
<!-- START_VERBATIM -->
<div class="demo">
<div x-data="{ count: 0 }">
<button x-on:click="count++">Increment</button>
<span x-text="count"></span>
</div>
</div>
<!-- END_VERBATIM -->
このHTMLに3ビットのアルパインが散りばめられていることがわかります。インタラクティブな「カウンター」コンポーネントを作成しました。
何が起こっているのかを簡単に見ていきましょう。
<a name="declaring-data"></a>
### データの宣言
```alpine
<div x-data="{ count: 0 }">
```
アルパインのすべては `x-data` ディレクティブで始まります。内部で`x-data` は、プレーンJavaScriptで、Alpineが追跡するデータのオブジェクトを宣言します。
このオブジェクト内のすべてのプロパティは、このHTML要素内の他のディレクティブで使用できるようになります。さらに、これらのプロパティの1つが変更されると、それに依存するすべてのものも変更されます。
[→ 詳細を読む `x-data`](/directives/data)
`x-on` がどのようにして、`count` プロパティにアクセスして変更するかを見てみましょう。
<a name="listening-for-events"></a>
### イベントのリッスン
```alpine
<button x-on:click="count++">Increment</button>
```
When a `click` event happens, Alpine will call the associated JavaScript expression, `count++` in our case. As you can see, we have direct access to data declared in the `x-data` expression.
`x-on` は、要素のイベントをリッスンするために使用できるディレクティブです。上記の場合、clickイベントをリッスンしているので、`x-on:click` という形になります。
あなたが想像するように、あなたは他のイベントを聞くことができます。たとえば、`mouseenter` イベントをリッスンするのであれば、`x-on:mouseenter` という書き方になります。
この場合、`click` イベントが発生すると、Alpineは関連するJavaScript式を呼び出します(上記のケースでは`count++`になります)。ご覧のとおり、`x-data`で宣言されたデータに直接アクセスできます。
> `x-on` の代わりに`@`をよく見ませんか。これは、多くの人が好む、短くて親しみやすい構文です。今後、このドキュメントでは`x-on` の 代わりに`@`を使用する可能性があります。
[→ Read more about `x-on`](/directives/on)
<a name="reacting-to-changes"></a>
### Reacting to changes
```alpine
<h1 x-text="count"></h1>
```
`x-text` is an Alpine directive you can use to set the text content of an element to the result of a JavaScript expression.
In this case, we're telling Alpine to always make sure that the contents of this `h1` tag reflect the value of the `count` property.
In case it's not clear, `x-text`, like most directives accepts a plain JavaScript expression as an argument. So for example, you could instead set its contents to: `x-text="count * 2"` and the text content of the `h1` will now always be 2 times the value of `count`.
[→ Read more about `x-text`](/directives/text)
<a name="building-a-dropdown"></a>
## Building a dropdown
Now that we've seen some basic functionality, let's keep going and look at an important directive in Alpine: `x-show`, by building a contrived "dropdown" component.
Insert the following code into the `<body>` tag:
```alpine
<div x-data="{ open: false }">
<button @click="open = ! open">Toggle</button>
<div x-show="open" @click.outside="open = false">Contents...</div>
</div>
```
<!-- START_VERBATIM -->
<div class="demo">
<div x-data="{ open: false }">
<button @click="open = ! open">Toggle</button>
<div x-show="open" @click.outside="open = false">Contents...</div>
</div>
</div>
<!-- END_VERBATIM -->
If you load this component, you should see that the "Contents..." are hidden by default. You can toggle showing them on the page by clicking the "Toggle" button.
The `x-data` and `x-on` directives should be familiar to you from the previous example, so we'll skip those explanations.
<a name="toggling-elements"></a>
### Toggling elements
```alpine
<div x-show="open" ...>Contents...</div>
```
`x-show` is an extremely powerful directive in Alpine that can be used to show and hide a block of HTML on a page based on the result of a JavaScript expression, in our case: `open`.
[→ Read more about `x-show`](/directives/show)
<a name="listening-for-a-click-outside"></a>
### Listening for a click outside
```alpine
<div ... @click.outside="open = false">Contents...</div>
```
You'll notice something new in this example: `.outside`. Many directives in Alpine accept "modifiers" that are chained onto the end of the directive and are separated by periods.
In this case, `.outside` tells Alpine to instead of listening for a click INSIDE the `<div>`, to listen for the click only if it happens OUTSIDE the `<div>`.
This is a convenience helper built into Alpine because this is a common need and implementing it by hand is annoying and complex.
[→ Read more about `x-on` modifiers](/directives/on#modifiers)
<a name="building-a-search-input"></a>
## Building a search input
Let's now build a more complex component and introduce a handful of other directives and patterns.
Insert the following code into the `<body>` tag:
```alpine
<div
x-data="{
search: '',
items: ['foo', 'bar', 'baz'],
get filteredItems() {
return this.items.filter(
i => i.startsWith(this.search)
)
}
}"
>
<input x-model="search" placeholder="Search...">
<ul>
<template x-for="item in filteredItems" :key="item">
<li x-text="item"></li>
</template>
</ul>
</div>
```
<!-- START_VERBATIM -->
<div class="demo">
<div
x-data="{
search: '',
items: ['foo', 'bar', 'baz'],
get filteredItems() {
return this.items.filter(
i => i.startsWith(this.search)
)
}
}"
>
<input x-model="search" placeholder="Search...">
<ul class="pl-6 pt-2">
<template x-for="item in filteredItems" :key="item">
<li x-text="item"></li>
</template>
</ul>
</div>
</div>
<!-- END_VERBATIM -->
By default, all of the "items" (foo, bar, and baz) will be shown on the page, but you can filter them by typing into the text input. As you type, the list of items will change to reflect what you're searching for.
Now there's quite a bit happening here, so let's go through this snippet piece by piece.
<a name="multi-line-formatting"></a>
### Multi line formatting
The first thing I'd like to point out is that `x-data` now has a lot more going on in it than before. To make it easier to write and read, we've split it up into multiple lines in our HTML. This is completely optional and we'll talk more in a bit about how to avoid this problem altogether, but for now, we'll keep all of this JavaScript directly in the HTML.
<a name="binding-to-inputs"></a>
### Binding to inputs
```alpine
<input x-model="search" placeholder="Search...">
```
You'll notice a new directive we haven't seen yet: `x-model`.
`x-model` is used to "bind" the value of an input element with a data property: "search" from `x-data="{ search: '', ... }"` in our case.
This means that anytime the value of the input changes, the value of "search" will change to reflect that.
`x-model` is capable of much more than this simple example.
[→ Read more about `x-model`](/directives/model)
<a name="computed-properties-using-getters"></a>
### Computed properties using getters
The next bit I'd like to draw your attention to is the `items` and `filteredItems` properties from the `x-data` directive.
```js
{
...
items: ['foo', 'bar', 'baz'],
get filteredItems() {
return this.items.filter(
i => i.startsWith(this.search)
)
}
}
```
The `items` property should be self-explanatory. Here we are setting the value of `items` to a JavaScript array of 3 different items (foo, bar, and baz).
The interesting part of this snippet is the `filteredItems` property.
Denoted by the `get` prefix for this property, `filteredItems` is a "getter" property in this object. This means we can access `filteredItems` as if it was a normal property in our data object, but when we do, JavaScript will evaluate the provided function under the hood and return the result.
It's completely acceptable to forgo the `get` and just make this a method that you can call from the template, but some prefer the nicer syntax of the getter.
[→ Read more about JavaScript getters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get)
Now let's look inside the `filteredItems` getter and make sure we understand what's going on there:
```js
return this.items.filter(
i => i.startsWith(this.search)
)
```
This is all plain JavaScript. We are first getting the array of items (foo, bar, and baz) and filtering them using the provided callback: `i => i.startsWith(this.search)`.
By passing in this callback to `filter`, we are telling JavaScript to only return the items that start with the string: `this.search`, which like we saw with `x-model` will always reflect the value of the input.
You may notice that up until now, we haven't had to use `this.` to reference properties. However, because we are working directly inside the `x-data` object, we must reference any properties using `this.[property]` instead of simply `[property]`.
Because Alpine is a "reactive" framework. Any time the value of `this.search` changes, parts of the template that use `filteredItems` will automatically be updated.
<a name="looping-elements"></a>
### Looping elements
Now that we understand the data part of our component, let's understand what's happening in the template that allows us to loop through `filteredItems` on the page.
```alpine
<ul>
<template x-for="item in filteredItems">
<li x-text="item"></li>
</template>
</ul>
```
The first thing to notice here is the `x-for` directive. `x-for` expressions take the following form: `[item] in [items]` where [items] is any array of data, and [item] is the name of the variable that will be assigned to an iteration inside the loop.
Also notice that `x-for` is declared on a `<template>` element and not directly on the `<li>`. This is a requirement of using `x-for`. It allows Alpine to leverage the existing behavior of `<template>` tags in the browser to its advantage.
Now any element inside the `<template>` tag will be repeated for every item inside `filteredItems` and all expressions evaluated inside the loop will have direct access to the iteration variable (`item` in this case).
[→ Read more about `x-for`](/directives/for)
<a name="recap"></a>
## Recap
If you've made it this far, you've been exposed to the following directives in Alpine:
* x-data
* x-on
* x-text
* x-show
* x-model
* x-for
That's a great start, however, there are many more directives to sink your teeth into. The best way to absorb Alpine is to read through this documentation. No need to comb over every word, but if you at least glance through every page you will be MUCH more effective when using Alpine.
Happy Coding!
|
Java | UTF-8 | 163 | 2.171875 | 2 | [] | no_license | #include <stdio.h>
#include <string.h>
int main()
{
char a[100];
int length;
gets(a);
length = strlen(a);
printf("%d",length);
return 0;
} |
Java | UTF-8 | 3,335 | 2.609375 | 3 | [] | no_license | package presentation;
import business.ValidateTextbox;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.DateTime;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.events.VerifyEvent;
/**
* Manages the adding of data for features at a given time period
*/
public abstract class BaseFeatureHistoryDrawer
{
protected Composite composite;
protected Text txtNotes;
protected Button btnAction;
protected Composite buttonComposite;
protected Button btnCancel;
protected GridData gd_txtNotes;
protected Label lblValue;
protected Text txtValue;
protected Label lblDatePeriod;
protected DateTime dateTime;
/**
* Adds a given tracked feature
* @param container The composite
*/
public BaseFeatureHistoryDrawer( Composite container )
{
composite = new Composite( container, SWT.BORDER );
// organizes the component
GridLayout compositeLayout = new GridLayout();
compositeLayout.numColumns = 2;
composite.setLayout( compositeLayout );
lblValue = new Label(composite, SWT.NONE);
lblValue.setText("Value");
txtValue = new Text(composite, SWT.BORDER);
txtValue.addVerifyListener(new VerifyListener()
{
public void verifyText(VerifyEvent event)
{
ValidateTextbox.verifyMonetaryValue(event);
}
});
txtValue.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
lblDatePeriod = new Label(composite, SWT.NONE);
lblDatePeriod.setText("Date Period");
dateTime = new DateTime(composite, SWT.BORDER);
dateTime.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
// Notes
Label lblNotes = new Label( composite, SWT.None );
lblNotes.setText( "Additional Details" );
new Label(composite, SWT.NONE);
txtNotes = new Text( composite, SWT.BORDER | SWT.MULTI );
gd_txtNotes = new GridData( GridData.FILL_BOTH );
gd_txtNotes.horizontalSpan = 2;
txtNotes.setLayoutData( gd_txtNotes );
buttonComposite = new Composite(composite, SWT.NONE);
GridData gd_buttonComposite = new GridData(SWT.CENTER, SWT.CENTER, false, false, 2, 1);
gd_buttonComposite.heightHint = 48;
gd_buttonComposite.widthHint = 155;
buttonComposite.setLayoutData(gd_buttonComposite);
btnAction = new Button(buttonComposite, SWT.NONE);
btnAction.addSelectionListener(new SelectionAdapter()
{
@Override
public void widgetSelected(SelectionEvent event)
{
processActionButton();
}
});
btnAction.setBounds(10, 10, 64, 25);
btnAction.setText("Add");
btnCancel = new Button(buttonComposite, SWT.NONE);
btnCancel.addSelectionListener(new SelectionAdapter()
{
@Override
public void widgetSelected(SelectionEvent event)
{
backToPreviousScreen();
}
});
btnCancel.setText("Cancel");
btnCancel.setBounds(80, 10, 64, 25);
}
/**
* Processes an action on button press
*/
protected abstract void processActionButton();
/**
* Go back to the previous screen
*/
protected abstract void backToPreviousScreen();
}
|
JavaScript | UTF-8 | 887 | 4.09375 | 4 | [] | no_license | //cria um array de objetos de faixa de precos para ele possa ser usado em um site o mercado livre
//faixa, tooltip, min.max
//1 opção por objetos
let faixas = [
{tooltip: '1000 a 2000', min: 1000, max: 2000 },
{tooltip: '2000 a 3000', min: 2000, max: 3000 },
{tooltip: '4000 a 5000', min: 4000, max: 5000 }
];
// 2 opcao factoryFunction
function criarFaixas (tooltip, min, max){
return {
tooltip,
min,
max
}
}
let faixas2 = [
criarFaixas('a',1,100),
criarFaixas('b',100,1000),
criarFaixas('c',1000,10000)
]
//terceira opção por construtor
function FaixaPrecos(tooltip, min,max){
this.tooltip = tooltip,
this.min = min,
this.max = max
}
let faixa3 = [
new FaixaPrecos('a',10,20),
new FaixaPrecos('b', 30, 40),
new FaixaPrecos('c',50,60)
]
console.log(faixas);
console.log(faixas2);
console.log(faixa3)
|
C# | UTF-8 | 4,858 | 2.703125 | 3 | [] | no_license | using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
namespace Kwaazaar.Config
{
public static class ConfigExtensions
{
private static bool _enabled = false;
private static ICustomizedTenantsSet _customizedTenants = null;
private static Dictionary<string, IConfigurationSection> _customizedTenantsDictionary = null;
public static IServiceCollection EnableMultiTenancySupport(this IServiceCollection services, IConfiguration config)
{
if (_enabled) throw new InvalidOperationException("MultiTenancySupport has already been enabled");
// Ensure support for AspNetCore's configuration options
services.AddOptions();
// Create set for holding registration of customized tenants
_customizedTenants = new CustomizedTenantsSet();
_customizedTenantsDictionary = new Dictionary<string, IConfigurationSection>();
var customizedTenantsSection = config.GetSection("CustomizedTenants");
if (customizedTenantsSection.Exists())
{
foreach (var tenant in customizedTenantsSection.GetChildren())
{
// Customized tenants must have their properties ALWAYS be fully customized, so for non-customized configuration load the default (unnamed) configuration
var tenantId = tenant.Key;
_customizedTenants.AddTenantId(tenantId);
_customizedTenantsDictionary.Add(tenantId, tenant);
}
}
// Make sure the DI-action can access the list of customized tenants
services.AddSingleton(_customizedTenants);
_enabled = true;
return services;
}
/// <summary>
/// Add configuration options support (DI-registered, auto-reloading configuration models) with multi-tenancy support
/// </summary>
/// <param name="services">IServiceCollection</param>
/// <param name="config">IConfiguration to load from</param>
/// <param name="sectionName">Optional: sectionName for where to find the configuration from. When not specified, the classname will be used as sectionName.</param>
/// <returns>IServiceCollection</returns>
public static IServiceCollection AutoConfigure<TModel>(this IServiceCollection services, IConfiguration config, string sectionName = null)
where TModel: class, new()
{
if (!_enabled) throw new InvalidOperationException("You must first call EnableMultiTenancySupport");
var sectionNameToUse = sectionName ?? typeof(TModel).Name;
// Configure the default/non-tenant specific model
services.Configure<TModel>(Options.DefaultName, config.GetSection(sectionNameToUse));
// Configure the tenant-specific model (only for customized tenants)
foreach (KeyValuePair<string, IConfigurationSection> tenant in _customizedTenantsDictionary)
{
var tenantSpecificModelSection = tenant.Value.GetSection(sectionNameToUse); // See if the tenant-specific config contains this section
services.Configure<TModel>(tenant.Key, tenantSpecificModelSection.Exists() ? tenant.Value.GetSection(sectionNameToUse) : config.GetSection(sectionNameToUse));
}
// Register the DI retrieval
services.AddScoped<TModel>(sp => // Scoped lifetime (ASP.Net creates scope for every request, non-scoped attempts will fail)
{
// This code is executed when DI tries to resolve a constructor parameter
var currentTenantId = sp.GetService<ITenantIdProvider>().GetTenantId();
// This custom action retrieves an IOptionsSnapshot<TModel>, so that the value will be auto-reloaded on live config changes
var obj = sp.GetService<ICustomizedTenantsSet>().ContainsTenantId(currentTenantId)
? sp.GetService<IOptionsSnapshot<TModel>>().Get(currentTenantId) // IOptionsSnapshot<T> will always return a value (empty instance when there is nothing configured for this tenant)
: sp.GetService<IOptionsSnapshot<TModel>>().Value;
// If it derives from out ConfigModel, we can support additional calls for validation and setting the tenant
if (obj != null)
{
if (obj is ConfigModel tc)
{
tc.SetTenantId(currentTenantId);
tc.Validate();
}
}
return obj;
});
return services;
}
}
}
|
Python | UTF-8 | 6,741 | 3.875 | 4 | [] | no_license | #! /usr/bin/env python
# -*- coding:Utf8 -*-
"""LEARN DECORATOR WITH SAM AND MAX"""
"""SAM AND MAX"""
########################################
#### Classes and Methods imported : ####
########################################
from functools import wraps
#####################
#### Constants : ####
#####################
#######################################
#### Classes, Methods, Functions : ####
#######################################
#
# Initiation : décorateur manuel
#
def decorator_tout_neuf(fonction):
# Englobe la fonction originale
def wrapper_fonction_origin():
# Ici on ajoute ce qui doit être réalisé avant la fonction décorée
print("Eh oui je suis juste avant la fonction")
# Fonction décoré
fonction()
print("Eh oui cette fois je suis après ... Je suis partout")
# Attention on a juste défini la fonction, on ne l'a en aucun cas appelé
return wrapper_fonction_origin
def intouchable():
print("Je suis Dieu, je suis la création, personne ne m'ursupe")
# Ici on décore pythoniquement la fonction
@decorator_tout_neuf
def intouchable2():
print("Dieu est mort, pouvoir au peuple")
#
# Introspection et décorateur
#
def inutile(func):
def wrapper():
func()
return wrapper
# Le décorateur va détruire les informations permettant d'accéder à la doc
# par exemple (help(fonction) ou fonction.__doc__)
@inutile
def fonction_doc():
"""Super !!!!!!!!"""
pass
#
# Utilisation du module wraps pour lire la doc d'une fonction
#
def decorator_inutile(func):
@wraps(func)
def wrapper():
# Decorateur inutile^^
func()
return wrapper
@decorator_inutile
def ma_fonction():
"""Super doc , super doc, mais tu peux pas la lire"""
pass
#
# On peut ajouter des arguments aux fonctions décorées
#
def decorateur_argumente(fonc):
def wrapper_arg(arg1, arg2):
print("Ben oui j'ai des arguments, normal quoi",
arg1, arg2)
fonc(arg1, arg2)
return wrapper_arg
@decorateur_argumente
def fonction_argumente(nom, prenom):
print("My name is : {}, {}".format(nom, prenom))
#
# Passer des arguments au décorateur
#
def createur_de_decorateur():
print("Je fabrique des décorateurs. Je suis éxécuté une seule fois :" +
"à la création du décorateur 1")
def mon_decorateur(func):
print("Je suis un décorateur, je suis éxécuté une seule fois quand" +
" on décore la fonction 3")
def wrapper():
print("Je suis le wrapper autour de la fonction décorée. 5"
"Je suis appelé quand on appelle la fonction décorée. "
"En tant que wrapper, je retourne le RESULTAT de la fonction décorée.")
return func()
print("En tant que décorateur, je retourne le wrapper 4")
return wrapper
print("En tant que créateur de décorateur, je retourne un décorateur 2")
return mon_decorateur
def fonction_decore():
print("Je suis un joli sapin de Noël")
# On peut maintenant tester avec des arguments
def createur_de_decorateur_avec_arguments(decorator_arg1, decorator_arg2):
print("Je créé des décorateur et j'accepte des arguments:",
decorator_arg1, decorator_arg2)
def mon_decorateur(func):
print("Je suis un décorateur, vous me passez des arguments:",
decorator_arg1, decorator_arg2)
# Ne pas mélanger les arguments du décorateurs et de la fonction !
def wrapped(function_arg1, function_arg2):
print(("Je suis le wrapper autour de la fonction décorée.\n"
"Je peux accéder à toutes les variables\n"
"\t- du décorateur: {0} {1}\n"
"\t- de l'appel de la fonction: {2} {3}\n"
"Et je les passe ensuite à la fonction décorée"
.format(decorator_arg1, decorator_arg2,
function_arg1, function_arg2)))
return func(function_arg1, function_arg2)
return wrapped
return mon_decorateur
@createur_de_decorateur_avec_arguments("Leonard", "Sheldon")
def fonction_decoree_avec_arguments(function_arg1, function_arg2):
print(("Je suis une fonctions décorée, je ne me soucie que de mes " +
"arguments: {0} {1}".format(function_arg1, function_arg2)))
# Quelques décorateurs
def benchmark(func):
"""
Un décorateur qui affiche le temps qu'une fonction met à s'éxécuter
"""
import time
def wrapper(*args, **kwargs):
t = time.clock()
res = func(*args, **kwargs)
print(func.__name__, time.clock()-t)
return res
return wrapper
def logging(func):
"""
Un décorateur qui log l'activité d'un script.
(Ok, en vrai ça fait un print, mais ça pourrait logger !)
"""
def wrapper(*args, **kwargs):
res = func(*args, **kwargs)
print(func.__name__, args, kwargs)
return res
return wrapper
def counter(func):
"""
Un compter qui compte et affiche le nombre de fonction qu'une fonction
a été éxécutée
"""
def wrapper(*args, **kwargs):
wrapper.count = wrapper.count + 1
res = func(*args, **kwargs)
print("{0} a été utilisée: {1}x".format(func.__name__, wrapper.count))
return res
wrapper.count = 0
return wrapper
# Exemple
@counter
@benchmark
@logging
def reverse_string(string):
return string[::-1]
########################
#### Main Program : ####
########################
# intouchable()
# je_te_decore = decorator_tout_neuf(intouchable)
# je_te_decore()
# # On peut écraser la fonction originale qui aura ainsi la même comportement que
# # la fonction décorée
# intouchable = decorator_tout_neuf(intouchable)
# intouchable()
# intouchable2()
# # Introspection
# # La nouvelle fonction contient maintenant wrapper()
# print(fonction_doc.__doc__, help(fonction_doc))
# # Utilisation du module wraps pour lire la doc de la fonction decorée
# print(ma_fonction.__doc__ + "\n")
# print(help(ma_fonction))
# # Decorateur avec paramètres
# fonction_argumente("Jeremy", "Bois")
# Argument au décorateur
# nouveau_decorateur = createur_de_decorateur()
# print("pause")
# fonction_decore = nouveau_decorateur(fonction_decore)
# print("pause")
# fonction_decore()
# print("pause")
# fonction_decore = createur_de_decorateur()(fonction_decore)()
# On teste avec les arguments
# fonction_decoree_avec_arguments("Marabou", "Bouclier")
# Ordre des décorateurs et décorateurs utiles
# print(reverse_string("Karine alla en Irak"))
# print(reverse_string("Sa nana snob porte de trop bons ananas"))
|
Java | UTF-8 | 280 | 1.90625 | 2 | [] | no_license | package com.ymd.nioserver.server;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;
public interface IMessageReader {
public void read(Socket socket, ByteBuffer byteBuffer) throws IOException;
public List<Message> getMessages();
}
|
Go | UTF-8 | 845 | 2.9375 | 3 | [] | no_license | package server
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/gorilla/mux"
)
func Run() {
router := mux.NewRouter()
router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("Hello, GraphQL!"))
}).Methods(http.MethodGet)
srv := http.Server{
Addr: ":3000",
Handler: router,
}
done := make(chan os.Signal, 1)
signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
go func() {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %s\n", err)
}
}()
<-done
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer func() {
cancel()
}()
if err := srv.Shutdown(ctx); err != nil {
log.Fatalf("Server Shutdown Failed: %+v", err)
}
}
|
C | UTF-8 | 2,124 | 3.171875 | 3 | [] | no_license | #include<stdio.h>
#include<string.h>
void creatArrOfShift(int *arrOfShift, char *temp, int tempLen){
for (int i = 0; i < 256; i++)
arrOfShift[i] = tempLen;
for (int i = 0; i < tempLen - 1; ++i){
arrOfShift[(int)temp[i]] = tempLen - 1 - i;
}
}
int main(){
FILE* inputFile = fopen("in.txt", "r");
char temp[16];
int tempLen = 0;
for (int i = 0; i < 16; ++i) {
char a;
if (!fscanf(inputFile, "%c", &a)) {
fclose(inputFile);
return 0;
}
if (a == '\n') {
tempLen = i;
break;
}
temp[i] = a;
}
if (!tempLen){
tempLen = 16;
char a;
if (!fscanf(inputFile, "%c", &a)) {
fclose(inputFile);
return 0;
}
}
int arrOfShift[256];
creatArrOfShift(arrOfShift, temp, tempLen);
char buf[8192];
int link = tempLen - 1, bufSize;
bufSize = fread(buf, 1, 8192, inputFile);
long long bufCount = 0;
while (bufSize){
while(link < bufSize) {
int flag = 0;
for (int i = tempLen - 1; i >= 0; --i) {
int nextInBuf = link - tempLen + 1 + i;
printf("%lli ", bufCount + nextInBuf + 1);
if (temp[i] == buf[nextInBuf]) {
flag = 1;
if (!i) {
link += tempLen;
break;
}
}
else if (!flag) {
link += arrOfShift[(int)buf[nextInBuf]];
break;
}
else {
link += arrOfShift[(int)temp[tempLen - 1]];
break;
}
}
}
bufSize = 0;
if (link >= 8192){
int idx = link - tempLen + 1;
if (link < 8191 + tempLen)
memcpy(buf, &buf[idx], (8192 - idx));
bufSize = fread(&buf[8192 - idx], 1, idx, inputFile);
link = tempLen - 1;
bufCount += 8192;
}
}
fclose(inputFile);
}
|
Python | UTF-8 | 544 | 3.4375 | 3 | [] | no_license | with open('sachintendulkar.txt') as f: #Reading the file
data=f.read()
f.closed
print(data)
datalist = data.split() #Splitting the words in the file into lists
datafreq = []
for w in datalist: #looping through the words in the file
datafreq.append(datalist.count(w))
print("\nParagraph\n" + data +"\n") #Printing the output
print("List\n" + str(datalist) + "\n")
print("Frequencies\n" + str(datafreq) + "\n")
print("Words along with their frequency\n" + str(list(zip(datalist, datafreq))))
|
Java | UTF-8 | 5,242 | 2.625 | 3 | [] | no_license | import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jgit.revwalk.DepthWalk;
/**
* A continuous integration server which listens to Github push events.
* The server clones the repository and checks out the last commit of the push event.
* Tries to build the project using Gradle, this CI sever only supports projects using Gradle.
* Summarizes the build result and sends an email to the pusher.
*/
public class ContinuousIntegrationServer extends AbstractHandler {
private MysqlDatabase database;
public ContinuousIntegrationServer() {
database = new MysqlDatabase();
}
/**
* Handles incoming requests to the server.
*
* @param target
* @param baseRequest
* @param request
* @param response
* @throws IOException
* @throws ServletException
*/
@Override
public void handle(
String target,
Request baseRequest,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html;charset=utf-8");
response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK);
try {
List<CommitStructure> commits = database.selectAllCommits();
if (target.equals("/builds")) {
String html = DocumentBuilder.createMainPage(commits);
response.getWriter().println(html);
response.flushBuffer();
} else if (target.equals("/commit")) {
String commitID = request.getParameter("commitID");
CommitStructure commit = database.selectSpecificRow(commitID);
if(commit==null){
response.getWriter().println("404: The selected commit ID is non existant");
}
else{
String html = DocumentBuilder.createBuildDetails(commit);
response.getWriter().println(html);
}
response.flushBuffer();
} else {
baseRequest.setHandled(true);
// see https://stackoverflow.com/questions/8100634/get-the-post-request-body-from-httpservletrequest
String reqString = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
Payload payload = Payload.parse(reqString);
File dir = Files.createTempDirectory("temp").toFile();
try {
// Clones repo
System.out.println("Cloning repo...");
File repo = new RepoSnapshot(payload).cloneFiles(dir);
System.out.println("Repo cloned");
// Executes gradle build
System.out.println("Start building...");
Report buildReport = GradleHandler.build(repo);
System.out.println("Build finished");
// Sends mail
System.out.println("Sending results...");
Mailserver mailserver = new Mailserver();
mailserver.useGmailSMTP();
SendMail sendMail = new SendMail();
sendMail.sendMail(buildReport, payload, mailserver, payload.getPusherEmail(), "Hello");
System.out.println("Email sent");
// Insert results into database
System.out.println("Insert build results into database..");
CommitStructure newBuild = new CommitStructure(payload.getCommitHash(),
buildReport.getFormatedDate(),
buildReport.getFormatedLogs(),
buildReport.isSuccess());
database.insertCommitToDatabase(newBuild);
System.out.println("Database updated!");
} catch (Exception e) {
System.out.println("Failed to process repo: " + e.getMessage());
}
response.getWriter().println("CI job done");
response.flushBuffer();
System.out.println("CI job done");
}
} catch(SQLException e){e.printStackTrace();}
}
// used to start the CI server in command line
/**
* Starts the server.
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception
{
Server server = new Server(8080);
server.setHandler(new ContinuousIntegrationServer());
server.start();
server.join();
}
} |
C++ | UTF-8 | 585 | 3.171875 | 3 | [] | no_license | //
// FindSignAndMagnitude.cpp
// CppPractice
//
// Created by Justin Owen on 10/26/18.
// Copyright © 2018 Justin Owen. All rights reserved.
//
#include "FindSignAndMagnitude.hpp"
#include <iostream>
#include <cmath>
#include <utility>
#include <iomanip>
std::pair<int, double> FindSignAndMagnitude(const double &V){
double VA = std::abs(V);
std::pair<int, double> SignMagnitude(V/VA, VA);
return SignMagnitude;
}
void PrintPair(const std::pair<int, double> &Pair){
std::cout << std::setprecision(10) << "(" << Pair.first << ", "<< Pair.second << ")"<< "\n";
}
|
Python | UTF-8 | 631 | 2.953125 | 3 | [] | no_license | import tensorflow as tf
# Just disables the warning, doesn't enable AVX/FMA
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
matrix1 = tf.constant([[3, 3]])
matrix2 = tf.constant([[2],
[2]])
product = tf.matmul(matrix1, matrix2) # matrix multiply np.dot(m1, m2)
# method 1
sess = tf.compat.v1.Session() # 创建session
result = sess.run(product) # 通过session来运行部分图
print(result)
sess.close() # 关闭会话
# method 2
with tf.compat.v1.Session() as sess: # 通过with 自动关闭这次会话 降低内存占用
result2 = sess.run(product)
print(result2)
|
Java | ISO-8859-1 | 13,218 | 2.46875 | 2 | [] | no_license | package fr.picresenar.esquisse3D.etapes;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import fr.picresenar.esquisse3D.MainEsquisse;
import fr.picresenar.esquisse3D.commands.Fonctions;
import fr.picresenar.esquisse3D.commands.parameter.Dessins;
public class Builders {
public MainEsquisse main;
public Builders(MainEsquisse mainEsquisse) {
this.main = mainEsquisse;
}
public void ConstructionSalles(boolean destroy,boolean protection){
Double Xmin=main.SallesXmin;
Double Ymin=main.SallesYmin;
Double Zmin=main.SallesZmin;
Double Xmax=main.SallesXmax;
Double Ymax=main.SallesYmax;
Double Zmax=main.SallesZmax;
Integer Jmax=main.getConfig().getInt("Joueurs.max");
Material material=main.MurMaterial;
Integer JmaxX;
Integer JmaxZ;
String AxePrincipal;
//Dessins d= new Dessins(main);
Fonctions f= new Fonctions(main);
if((Xmax-Xmin)>(Zmax-Zmin)) {
AxePrincipal="X";
JmaxX =Jmax;
JmaxZ=Jmax/2;
}else {
AxePrincipal="Z";
JmaxX=Jmax/2;
JmaxZ=Jmax;
}
Double X;
Double Z;
Integer PasX= (int)(Xmax-Xmin)/JmaxX;
Integer PasZ= (int)(Zmax-Zmin)/JmaxZ;
//Effacer tout
if(destroy) {
f.FillBlocks(Xmin,Ymin,Zmin,Xmax,Ymax,Zmax,Material.AIR);
f.KillEntityInArea(Xmin,Ymin,Zmin,Xmax,Ymax,Zmax);
}
//Protger les bords avec de la bedrock et le toit avec une barrire
if(protection) {
f.FillBlocks(Xmin-1,Ymin,Zmin,Xmin-1,Ymax,Zmax,Material.BEDROCK);
f.FillBlocks(Xmin,Ymin,Zmin-1,Xmax,Ymax,Zmin-1,Material.BEDROCK);
f.FillBlocks(Xmin,Ymin-1,Zmin,Xmax,Ymin-1,Zmax,Material.BEDROCK);
f.FillBlocks(Xmax+1,Ymin,Zmin,Xmax+1,Ymax,Zmax,Material.BEDROCK);
f.FillBlocks(Xmin,Ymin,Zmax+1,Xmax,Ymax,Zmax+1,Material.BEDROCK);
f.FillBlocks(Xmin,Ymax+1,Zmin,Xmax,Ymax+1,Zmax,Material.BARRIER);
}else {
f.FillBlocks(Xmin-1,Ymin,Zmin,Xmin-1,Ymax,Zmax,Material.AIR);
f.FillBlocks(Xmin,Ymin,Zmin-1,Xmax,Ymax,Zmin-1,Material.AIR);
f.FillBlocks(Xmin,Ymin-1,Zmin,Xmax,Ymin-1,Zmax,Material.AIR);
f.FillBlocks(Xmax+1,Ymin,Zmin,Xmax+1,Ymax,Zmax,Material.AIR);
f.FillBlocks(Xmin,Ymin,Zmax+1,Xmax,Ymax,Zmax+1,Material.AIR);
f.FillBlocks(Xmin,Ymax+1,Zmin,Xmax,Ymax+1,Zmax,Material.AIR);
}
//Sol Salle
f.FillBlocks(Xmin,Ymin,Zmin,Xmax,Ymin,Zmax,material);
//Plafond Urnes
f.FillBlocks(Xmin,Ymax,Zmin,Xmax,Ymax,Zmax,Material.BARRIER);
//Murs X Salle
for(X=Xmin;X<=Xmax;X=X+PasX) {
f.FillBlocks(X,Ymin,Zmin,X,Ymax,Zmax,material);
}
//Murs Z Salle
for(Z=Zmin;Z<=Zmax;Z=Z+PasZ) {
f.FillBlocks(Xmin,Ymin,Z,Xmax,Ymax,Z,material);
}
//Enclumes Salles
if(AxePrincipal=="Z") {
for(X=Xmin+1;X<=Xmax;X=X+PasX) {
for(Z=Zmin+PasZ/2;Z<=Zmax;Z=Z+PasZ) {
f.FillBlocks(X,Ymin+1,Z,X,Ymin+1,Z,Material.ANVIL);
Location anvilloc=new Location(Bukkit.getWorld(main.world),X,Ymin+1,Z);
main.AnvilList.add(anvilloc);
}
}
}else {
for(X=Xmin+PasX/2;X<=Xmax;X=X+PasX) {
for(Z=Zmin+1;Z<=Zmax;Z=Z+PasZ) {
f.FillBlocks(X,Ymin+1,Z,X,Ymin+1,Z,Material.ANVIL);
Location anvilloc=new Location(Bukkit.getWorld(main.world),X,Ymin+1,Z);
main.AnvilList.add(anvilloc);
}
}
}
}
public void ConstructionUrnes(boolean destroy){
Double Xmin=main.UrnesXmin;
Double Ymin=main.UrnesYmin;
Double Zmin=main.UrnesZmin;
Double Xmax=main.UrnesXmax;
Double Ymax=main.UrnesYmax;
Double Zmax=main.UrnesZmax;
Integer Jmax=main.Jmax;
Material material=main.MurMaterial;
Integer JmaxX;
Integer JmaxZ;
String AxePrincipal;
Fonctions f= new Fonctions(main);
if((Xmax-Xmin)>(Zmax-Zmin)) {
AxePrincipal="X";
JmaxX =Jmax;
JmaxZ=Jmax/2;
}else {
AxePrincipal="Z";
JmaxX=Jmax/2;
JmaxZ=Jmax;
}
Double X;
Double Z;
Integer PasX= (int)(Xmax-Xmin)/JmaxX;
Integer PasZ= (int)(Zmax-Zmin)/JmaxZ;
//Effacer tout
if(destroy) {
//System.out.println("Pendant construction : " + main.destroy);
f.FillBlocks(Xmin,Ymin,Zmin,Xmax,Ymax,Zmax,Material.AIR);
f.KillEntityInArea(Xmin,Ymin,Zmin,Xmax,Ymax,Zmax);
}
//Sol Urnes
f.FillBlocks(Xmin,Ymin,Zmin,Xmax,Ymin,Zmax,material);
if(AxePrincipal=="X") {
//Murs X Urnes
for(X=Xmin;X<=Xmax;X=X+PasX) {
f.FillBlocks(X,Ymin,Zmin,X,Ymax,Zmax,material);
}
//Murs Z Urnes
f.FillBlocks(Xmin,Ymin,Zmin,Xmax,Ymax,Zmin,material);
f.FillBlocks(Xmin,Ymin,Zmax,Xmax,Ymax,Zmax,material);
}else {
//Murs X Urnes
f.FillBlocks(Xmin,Ymin,Zmin,Xmin,Ymax,Zmax,material);
f.FillBlocks(Xmax,Ymin,Zmin,Xmax,Ymax,Zmax,material);
//Murs Z Urnes
for(Z=Zmin;Z<=Zmax;Z=Z+PasZ) {
f.FillBlocks(Xmin,Ymin,Z,Xmax,Ymax,Z,material);
}
}
//Plafond Urnes
f.FillBlocks(Xmin,Ymax,Zmin,Xmax,Ymax,Zmax,Material.BARRIER);
//Enclumes Urnes
if(AxePrincipal=="X") {
for(X=Xmin+PasX/2;X<=Xmax;X=X+PasX) {
f.FillBlocks(X,Ymin+1,Zmin+1,X,Ymin+1,Zmin+1,Material.ANVIL);
}
}else {
for(Z=Zmin+PasZ/2;Z<=Zmax;Z=Z+PasZ) {
f.FillBlocks(Xmin+1,Ymin+1,Z,Xmin+1,Ymin+1,Z,Material.ANVIL);
}
}
//Panneaux Urnes
String TextePanneau[] = {"","","",""};
Integer i=0;
for(String string: main.getConfig().getStringList("Panneaux.EnclumeGuess")) {
TextePanneau[i]=string;
i++;
}
if(AxePrincipal=="X") {
for(X=Xmin+PasX/2;X<=Xmax;X=X+PasX) {
f.FillBlocks(X,Ymin+2,Zmin+1,X,Ymin+2,Zmin+1,Material.AIR);
f.PutSign(X,Ymin+2,Zmin+1, BlockFace.SOUTH, TextePanneau);
}
}else {
for(Z=Zmin+PasZ/2;Z<=Zmax;Z=Z+PasZ) {
f.FillBlocks(Xmin+1,Ymin+2,Z,Xmin+1,Ymin+2,Z,Material.AIR);
f.PutSign(Xmin+1,Ymin+2,Z, BlockFace.EAST, TextePanneau);
}
}
}
public void ConstructionPanneauxSalles(String TextePanneau[]){
Double Xmin=main.SallesXmin;
Double Ymin=main.SallesYmin;
Double Zmin=main.SallesZmin;
Double Xmax=main.SallesXmax;
//Double Ymax=main.SallesYmax;
Double Zmax=main.SallesZmax;
Integer Jmax=main.getConfig().getInt("Joueurs.max");
Integer JmaxX;
Integer JmaxZ;
String AxePrincipal;
//Dessins d= new Dessins(main);
Fonctions f= new Fonctions(main);
if((Xmax-Xmin)>(Zmax-Zmin)) {
AxePrincipal="X";
JmaxX =Jmax;
JmaxZ=Jmax/2;
}else {
AxePrincipal="Z";
JmaxX=Jmax/2;
JmaxZ=Jmax;
}
Double X;
Double Z;
Integer PasX= (int)(Xmax-Xmin)/JmaxX;
Integer PasZ= (int)(Zmax-Zmin)/JmaxZ;
//Panneaux Salles
if(AxePrincipal=="Z") {
for(X=Xmin+1;X<=Xmax;X=X+PasX) {
for(Z=Zmin+PasZ/2;Z<=Zmax;Z=Z+PasZ) {
f.FillBlocks(X,Ymin+2,Z,X,Ymin+2,Z,Material.AIR);
f.PutSign(X,Ymin+2,Z, BlockFace.EAST, TextePanneau);
}
}
}else {
for(X=Xmin+PasX/2;X<=Xmax;X=X+PasX) {
for(Z=Zmin+1;Z<=Zmax;Z=Z+PasZ) {
f.FillBlocks(X,Ymin+2,Z,X,Ymin+1,Z,Material.AIR);
f.PutSign(X,Ymin+2,Z, BlockFace.SOUTH, TextePanneau);
}
}
}
}
public void GetRefSalles() {
Integer JmaxX=1;
Integer JmaxZ=1;
Integer UrneX;
Integer MinXSalle;
Integer MinZSalle;
Integer Jmax=main.getConfig().getInt("Joueurs.max");
Double XminU=main.UrnesXmin;
// Double YminU=main.UrnesYmin;
Double ZminU=main.UrnesZmin;
Double XmaxU=main.UrnesXmax;
// Double YmaxU=main.UrnesYmax;
Double ZmaxU=main.UrnesZmax;
Double XminS=main.SallesXmin;
// Double YminS=main.SallesYmin;
Double ZminS=main.SallesZmin;
Double XmaxS=main.SallesXmax;
// Double YmaxS=main.SallesYmax;
Double ZmaxS=main.SallesZmax;
Boolean AxeXPrincipal=isAxePrincipalX(false);
if(AxeXPrincipal) {
JmaxX =Jmax;
JmaxZ=Jmax/2;
}else {
JmaxX=Jmax/2;
JmaxZ=Jmax;
}
Integer PasX= (int)(XmaxS-XminS)/JmaxX;
Integer PasZ= (int)(ZmaxS-ZminS)/JmaxZ;
for(int i=0;i<=JmaxX;i++) {
for(int j=0;j<=JmaxZ;j++) {
MinXSalle=(int) (XminS +(i)*PasX);
MinZSalle=(int) (ZminS +(j)*PasZ);
if(!AxeXPrincipal) {
main.RefSallesX[j][i]= MinXSalle;
main.RefSallesZ[j][i]= MinZSalle;
}else{
main.RefSallesX[i][j]= MinXSalle;
main.RefSallesZ[i][j]= MinZSalle;
}
}
}
AxeXPrincipal=isAxePrincipalX(true);
//Ref Urnes
if(AxeXPrincipal) {
JmaxX =Jmax;
JmaxZ=1;
UrneX=1;
}else {
JmaxX=1;
JmaxZ=Jmax;
UrneX=0;
}
PasX= (int)(XmaxU-XminU)/JmaxX;
PasZ= (int)(ZmaxU-ZminU)/JmaxZ;
for(int i=0;i<=(Jmax-1);i++) {
MinXSalle=(int) (XminU+(UrneX*((i)*PasX)));
MinZSalle=(int) (ZminU+((1-UrneX)*((i)*PasZ)));
// Bukkit.broadcastMessage(MinXSalle+" "+MinZSalle+" "+MaxXSalle+" "+MaxZSalle);
// Bukkit.broadcastMessage(location.getBlockX()+" "+location.getBlockY()+" "+location.getBlockZ());
main.RefUrnesX[i]=MinXSalle;
main.RefUrnesZ[i]=MinZSalle;
}
main.RefUrnesX[Jmax]=(int)(Math.round(XmaxU));
main.RefUrnesZ[Jmax]=(int)(Math.round(ZmaxU));
}
public void ConstruireDessin() {
Double Xmin=main.SallesXmin;
Double Ymin=main.SallesYmin;
Double Zmin=main.SallesZmin;
Double Xmax=main.SallesXmax;
//Double Ymax=main.SallesYmax;
Double Zmax=main.SallesZmax;
Integer Jmax=main.Jmax;
Integer JmaxX;
Integer JmaxZ;
//Dessins d= new Dessins(main);
Dessins d=new Dessins(main);
if((Xmax-Xmin)>(Zmax-Zmin)) {
JmaxX =Jmax;
JmaxZ=Jmax/2;
}else {
JmaxX=Jmax/2;
JmaxZ=Jmax;
}
Double X;
Double Z;
Integer PasX= (int)(Xmax-Xmin)/JmaxX;
Integer PasZ= (int)(Zmax-Zmin)/JmaxZ;
//Murs Dessins
for(X=Xmin;X<=Xmax-PasX;X=X+PasX) {
for(Z=Zmin;Z<=Zmax-PasZ;Z=Z+PasZ) {
Integer Tableau[][]=d.TitreEsquisse();
for(Integer i=1;i<=12;i++) {
for(Integer j=1;j<28;j++) {
if(Tableau[i][j]==0) Bukkit.getWorld(main.world).getBlockAt((int)Math.round(X),(int)Math.round(Ymin+20-i),(int)Math.round(Z+PasZ-j-1)).setType(Material.GLOWSTONE);;
}
}
}
}
}
public void EffacerTout() {
Fonctions f= new Fonctions(main);
//Effacer (absolument) tout
main.destroyall=true;
f.FillBlocks(main.UrnesXmin-1,main.UrnesYmin-1,main.UrnesZmin-1,main.UrnesXmax+1,main.UrnesYmax+1,main.UrnesZmax+1,Material.AIR);
f.FillBlocks(main.SallesXmin-1,main.SallesYmin-1,main.SallesZmin-1,main.SallesXmax+1,main.SallesYmax+1,main.SallesZmax+1,Material.AIR);
main.destroyall=false;
}
public Entity SpawnCochons(Boolean UrnesouSalles,Integer Joueur,Integer Dessin){
Integer Xmin;
Integer Ymin;
Integer Zmin;
Double X;
Double Y;
Double Z;
Entity entity;
Location destination;
// Float orientation;
if(UrnesouSalles) {
Xmin=main.RefUrnesX[Joueur];
Ymin=(int) Math.round(main.UrnesYmin);
Zmin=main.RefUrnesZ[Joueur];
}else {
Xmin=main.RefSallesX[Joueur][Dessin];
Ymin=(int) Math.round(main.SallesYmin);
Zmin=main.RefSallesZ[Joueur][Dessin];
}
//System.out.println("Coordonnes salle : "+Xmin+"/"+Ymin+"/"+Zmin);
//System.out.println("Pas dplacement : "+PasX(UrnesouSalles)+"/"+PasZ(UrnesouSalles));
//
if(isAxePrincipalX(UrnesouSalles)) {
X=Xmin+PasX(UrnesouSalles)*(0.5)-1;
Y=Ymin+(0.5)*2;
Z=Zmin+(1.5);
// orientation=0f;
}else {
X=Xmin+(1.5);
Y=Ymin+(0.5)*2;
Z=Zmin+PasZ(UrnesouSalles)*(0.5)-1;
// orientation=90f;
}
//System.out.println("Cochon apparu sur "+ main.world +" en :"+X+"/"+Y+"/"+Z);
destination = new Location(Bukkit.getWorld(main.world),X,Y,Z);
Chunk chunk=destination.getChunk();
if(chunk.isLoaded()) {
entity=Bukkit.getWorld(main.world).spawnEntity(destination, EntityType.PIG);
return entity;
}
System.out.println("Erreur cochon non apparu : Chunk non charg");
return null;
}
public boolean isAxePrincipalX(Boolean UrnesouSalles) {
Double Xmin;
Double Zmin;
Double Xmax;
Double Zmax;
if(UrnesouSalles) {
Xmin=main.UrnesXmin;
Zmin=main.UrnesZmin;
Xmax=main.UrnesXmax;
Zmax=main.UrnesZmax;
}else {
Xmin=main.SallesXmin;
Zmin=main.SallesZmin;
Xmax=main.SallesXmax;
Zmax=main.SallesZmax;
}
if((Xmax-Xmin)>(Zmax-Zmin)) {
return true;
}else {
return false;
}
}
public Integer PasX(Boolean UrnesouSalles) {
Double Xmin;
Double Xmax;
Integer JmaxX=1;
if(UrnesouSalles) {
Xmin=main.UrnesXmin;
Xmax=main.UrnesXmax;
}else {
Xmin=main.SallesXmin;
Xmax=main.SallesXmax;
}
if(isAxePrincipalX(UrnesouSalles)) {
JmaxX =main.Jmax;
}else {
JmaxX=main.Jmax/2;
}
Integer PasX= (int)(Xmax-Xmin)/JmaxX;
return PasX;
}
public Integer PasZ(Boolean UrnesouSalles) {
Double Zmin;
Double Zmax;
Integer JmaxZ=1;
if(UrnesouSalles) {
Zmin=main.UrnesZmin;
Zmax=main.UrnesZmax;
}else {
Zmin=main.SallesZmin;
Zmax=main.SallesZmax;
}
if(!isAxePrincipalX(UrnesouSalles)) {
JmaxZ =main.Jmax;
}else {
JmaxZ=main.Jmax/2 ;
}
Integer PasZ= (int)(Zmax-Zmin)/JmaxZ;
return PasZ;
}
}
|
C++ | UTF-8 | 1,654 | 2.796875 | 3 | [] | no_license | #include <stdint.h>
const uint8_t pins[8] = {
11, 12, 13, 14, 15, 16, 17, 18,
};
const uint8_t CS = 1;
const uint8_t SK = 2;
const uint8_t DI = 3;
const uint8_t DO = 4;
const uint8_t GND = 5;
const uint8_t TEST = 6;
const uint8_t NC = 7;
const uint8_t VCC = 8;
void setPin(uint8_t pin, uint8_t value) {
digitalWrite(pins[pin-1],value);
}
uint8_t getPin(uint8_t pin) {
return digitalRead(pins[pin-1]);
}
void initPin(uint8_t pin, uint8_t value, uint8_t dir) {
pinMode(pins[pin-1],dir);
setPin(pin,value);
}
// When you're all wired up, hit the reset button
// to start dumping the hex codes.
void setup() {
initPin(CS,LOW,OUTPUT);
initPin(GND,LOW,OUTPUT);
initPin(VCC,HIGH,OUTPUT);
initPin(DO,HIGH,INPUT);
initPin(DI,LOW,OUTPUT);
initPin(TEST,LOW,OUTPUT);
initPin(SK,LOW,OUTPUT);
Serial.begin(115200);
}
uint8_t doBit(uint8_t out) {
setPin(DI,out);
setPin(SK,HIGH);
setPin(SK,LOW);
return getPin(DO);
}
const int ADDR_BITS = 9;
void startRead(uint16_t addr) {
setPin(CS,LOW);
setPin(CS,HIGH);
doBit(1); // start bit
doBit(1); // read op 0
doBit(0); // read op 1
doBit(0); // don't care
for (int i = 0; i < ADDR_BITS; i++) {
int bit = (addr >> (ADDR_BITS-i)) & 0x01;
doBit(bit);
}
}
void endRead() {
setPin(CS,LOW);
}
uint16_t readWord() {
uint16_t data = 0;
for (int i = 0; i < 16; i++) {
data = data << 1;
data = data | ((doBit(0) == HIGH)?1:0);
}
return data;
}
void loop() {
delay(5000);
startRead(0);
for (int i = 0; i < 512; i++) {
uint16_t w = readWord();
Serial.write((w>>8) & 0xff);
Serial.write(w & 0xff);
}
endRead();
while(1);
}
|
Python | UTF-8 | 6,137 | 3.734375 | 4 | [] | no_license | #! /usr/bin/python
# - coding: utf-8 -*-
"""现有i张10元纸币, j 张5元纸币, k张两元纸币, 购物后要支付n元(n为整数),
要求编写一个时间复杂度为O(1)的函数FindSolution(i, j, k, n), 功能是算出是否能用现在手上拥有的纸币拼凑成n元, 而不需要找零.
如:共有5张10元纸币,5张5元纸币,5张2元纸币,许凑齐27元,需2张10元纸币,1张5元纸币,1张2元纸币
共有5张10元纸币,5张5元纸币,5张2元纸币,需凑齐100元,无法凑齐
"""
def find_solution(i: int, j: int, k: int, n: int):
if n % 2 == 0: # n是偶数
ten_page = n // 10
if ten_page <= i:
five_page = 0 # 当10元纸币够用时,n为偶数时,5元纸币用不上
remain_num = n - ten_page % 10
two_page = remain_num // 2
if two_page <= k:
return '共有{0}张10元纸币,{1}张5元纸币,{2}张2元纸币,要凑齐{3}元,' \
'需{4}张10元纸币,{5}张5元纸币,{6}张2元纸币'.format(i, j, k, n, ten_page, five_page, two_page)
else:
return '共有{0}张10元纸币,{1}张5元纸币,{2}张2元纸币,要凑齐{3}元,无法凑齐'\
.format(i, j, k, n)
else: # 当10元纸币不够用时,用两张5元凑10元
remain_num = n - ten_page * 10
five_page = remain_num // 5
if five_page <= j: # 当5元纸币足够时,且组为偶数张
if five_page % 2 == 0: # 偶数张5元纸币
pass
else: # 基数张5元纸币
five_page -= 1
remain_num_2 = remain_num - 5 * five_page
two_page = remain_num_2 // 2
if two_page <= j:
return '共有{0}张10元纸币,{1}张5元纸币,{2}张2元纸币,要凑齐{3}元,' \
'需{4}张10元纸币,{5}张5元纸币,{6}张2元纸币'.format(i, j, k, n, ten_page, five_page, two_page)
else:
return '共有{0}张10元纸币,{1}张5元纸币,{2}张2元纸币,要凑齐{3}元,无法凑齐'.format(i, j, k, n)
else: # 5元纸币不够时
if five_page % 2 == 0:
five_page = j
else:
five_page = j - 1
remain_num_2 = remain_num - 5 * five_page
two_page = remain_num_2 // 2
if two_page <= j:
return '共有{0}张10元纸币,{1}张5元纸币,{2}张2元纸币,要凑齐{3}元,' \
'需{4}张10元纸币,{5}张5元纸币,{6}张2元纸币'.format(i, j, k, n, ten_page, five_page, two_page)
else:
return '共有{0}张10元纸币,{1}张5元纸币,{2}张2元纸币,要凑齐{3}元,无法凑齐'.format(i, j, k, n)
else: # n为基数时
if j == 0: # 只有10元纸币和2元纸币凑不到基数
return '共有{0}张10元纸币,{1}张5元纸币,{2}张2元纸币,要凑齐{3}元,无法凑齐'.format(i, j, k, n)
elif n in (1, 3): # 1,3为基数,但是凑不到
return '共有{0}张10元纸币,{1}张5元纸币,{2}张2元纸币,要凑齐{3}元,无法凑齐'.format(i, j, k, n)
else:
ten_page = n // 10
if ten_page <= i: # 10元够用
remain_num = n - ten_page * 10
if remain_num < 5:
ten_page -= 1
remain_num = n - ten_page * 10
five_page = 1
remain_num_2 = remain_num - 5
two_page = remain_num_2 // 2
if two_page <= j:
return '共有{0}张10元纸币,{1}张5元纸币,{2}张2元纸币,要凑齐{3}元,' \
'需{4}张10元纸币,{5}张5元纸币,{6}张2元纸币'.format(i, j, k, n, ten_page, five_page, two_page)
else:
return '共有{0}张10元纸币,{1}张5元纸币,{2}张2元纸币,要凑齐{3}元,无法凑齐'.format(i, j, k, n)
else: # 10元不够用时
ten_page = i
remain_num = n - ten_page * 10
five_page = remain_num // 5
if five_page <= j: # 5元够用时且为基数张
remain_num_2 = remain_num - five_page * 5
if remain_num_2 < 5:
five_page -= 1
remain_num_2 = remain_num - five_page * 5
two_page = remain_num_2 // 2
if two_page <= j:
return '共有{0}张10元纸币,{1}张5元纸币,{2}张2元纸币,要凑齐{3}元,' \
'需{4}张10元纸币,{5}张5元纸币,{6}张2元纸币'.format(i, j, k, n, ten_page, five_page, two_page)
else:
return '共有{0}张10元纸币,{1}张5元纸币,{2}张2元纸币,要凑齐{3}元,无法凑齐'.format(i, j, k, n)
else: # 5元不够用
five_page = j
if five_page % 2 == 0: # j必须为基数
five_page -= 1
remain_num_2 = remain_num - five_page * 5
two_page = remain_num_2 // 2
if two_page <= j:
return '共有{0}张10元纸币,{1}张5元纸币,{2}张2元纸币,要凑齐{3}元,' \
'需{4}张10元纸币,{5}张5元纸币,{6}张2元纸币'.format(i, j, k, n, ten_page, five_page, two_page)
else:
return '共有{0}张10元纸币,{1}张5元纸币,{2}张2元纸币,要凑齐{3}元,无法凑齐'.format(i, j, k, n)
if __name__ == '__main__':
for i in range(5, 100, 2):
print(find_solution(3, 10, 10, i))
|
Rust | UTF-8 | 14,942 | 2.609375 | 3 | [] | no_license | use std::ops::Range;
use iced_graphics::{Backend, Defaults, Primitive, Renderer};
use iced_native::{
layout, mouse, scrollable, text, Align, Background, Color, Element, Hasher,
HorizontalAlignment, Layout, Length, Point, Rectangle, Row, Size, Widget, Container, Column, Scrollable
};
use super::{cell::Cell, SubsControlsValues};
// Container properties
const CONTAINER_PADDING: u16 = 1;
// Scrollbar properties
const SCROLLBAR_MARGIN: u16 = 10;
const SCROLLBAR_WIDTH: u16 = 10;
const SCROLLER_WIDTH: u16 = 10;
// Cell properties
const CELL_PADDING: u16 = 4;
const HEADER_TEXT_SIZE: u16 = 20;
const CELL_TEXT_SIZE: u16 = 15;
// Units length step (counted as the number of digits, 1 digit = 10 units)
// for the number contained in the first cell of a row
const FIRST_CELL_STEP: u16 = 10;
pub struct TableViewer<'a, Message, B>
where
B: 'a + Backend + iced_graphics::backend::Text,
{
state: &'a mut State,
header: Element<'a, Message, Renderer<B>>,
rows: Vec<Element<'a, Message, Renderer<B>>>,
width: Length,
height: Length,
on_click: Option<Box<dyn Fn(usize) -> Message + 'a>>,
on_drag: Option<Box<dyn Fn(&'a [usize]) -> Message + 'a>>,
}
// , Start, End, Style, Actor, Text, Note, Duration, CPS
impl<'a, Message, B> TableViewer<'a, Message, B>
where
B: 'a + Backend + iced_graphics::backend::Text,
Message: 'a + Clone,
{
pub fn new(
state: &'a mut State,
subs_data: &'a [SubsControlsValues],
focused_rows: &Range<usize>,
) -> Self {
let max_first_cell_units =
subs_data.len().to_string().chars().count() as u16 * FIRST_CELL_STEP;
let header = Self::create_header(max_first_cell_units).into();
let center_align = HorizontalAlignment::Center;
let max_first_cell_units =
subs_data.len().to_string().chars().count() as u16 * FIRST_CELL_STEP;
let rows = subs_data
.into_iter()
.enumerate()
.map(|(row, sub)| {
if focused_rows.contains(&row) {
Row::with_children(vec![
Self::first_cell(row, max_first_cell_units, true),
Self::cell_row(row, &sub.start_time, center_align, true),
Self::cell_row(row, &sub.end_time, center_align, true),
Self::cell_row(row, sub.style_list.into(), center_align, true),
Self::cell_row(row, sub.actor_list.into(), center_align, true),
Self::cell_row(row, &sub.text, HorizontalAlignment::Left, true),
Self::cell_row(row, &sub.notes, HorizontalAlignment::Left, true),
Self::cell_row(row, &sub.duration, center_align, true),
Self::cell_row(row, "CPS", center_align, true),
])
.align_items(Align::Center)
.width(Length::Fill)
.height(Length::Shrink).into()
} else {
Row::with_children(vec![
Self::first_cell(row, max_first_cell_units, false),
Self::cell_row(row, &sub.start_time, center_align, false),
Self::cell_row(row, &sub.end_time, center_align, false),
Self::cell_row(row, sub.style_list.into(), center_align, false),
Self::cell_row(row, sub.actor_list.into(), center_align, false),
Self::cell_row(row, &sub.text, HorizontalAlignment::Left, false),
Self::cell_row(row, &sub.notes, HorizontalAlignment::Left, false),
Self::cell_row(row, &sub.duration, center_align, false),
Self::cell_row(row, "CPS", center_align, false),
])
.align_items(Align::Center)
.width(Length::Fill)
.height(Length::Shrink).into()
}
})
.collect();
Self {
state,
header,
rows,
width: Length::Fill,
height: Length::Fill,
on_click: None,
on_drag: None,
}
}
pub fn on_click<F>(mut self, f: F) -> Self
where
F: 'a + Fn(usize) -> Message,
{
self.on_click = Some(Box::new(f));
self
}
pub fn on_drag<F>(mut self, f: F) -> Self
where
F: 'a + Fn(&'a [usize]) -> Message,
{
self.on_drag = Some(Box::new(f));
self
}
fn create_header(length_units: u16) -> Row<'a, Message, Renderer<B>> {
Row::with_children(vec![
Self::first_header(length_units),
Self::header_center("Start"),
Self::header_center("End"),
Self::header_center("Style"),
Self::header_center("Actor"),
Self::header_left("Text"),
Self::header_left("Note"),
Self::header_center("Duration"),
Self::header_center("CPS"),
])
.align_items(Align::Center)
.width(Length::Fill)
.height(Length::Shrink)
}
#[inline(always)]
fn first_header(length_units: u16) -> Element<'a, Message, Renderer<B>> {
Cell::no_interactive("")
.padding(CELL_PADDING)
.size(HEADER_TEXT_SIZE)
.width(Length::Units(length_units))
.style(style::Header)
.horizontal_alignment(HorizontalAlignment::Center)
.into()
}
#[inline(always)]
fn header_center(value: &'a str) -> Element<Message, Renderer<B>> {
Cell::no_interactive(value)
.padding(CELL_PADDING)
.size(HEADER_TEXT_SIZE)
.style(style::Header)
.horizontal_alignment(HorizontalAlignment::Center)
.into()
}
#[inline(always)]
fn header_left(value: &'a str) -> Element<Message, Renderer<B>> {
Cell::no_interactive(value)
.padding(CELL_PADDING)
.size(HEADER_TEXT_SIZE)
.style(style::Header)
.into()
}
#[inline(always)]
fn first_cell(
row: usize,
length_units: u16,
is_focused: bool,
) -> Element<'a, Message, Renderer<B>> {
let value = (row + 1).to_string();
Cell::interactive(row, &value)
.padding(CELL_PADDING)
.size(CELL_TEXT_SIZE)
.width(Length::Units(length_units))
.horizontal_alignment(HorizontalAlignment::Center)
.style(style::FirstCell)
.focus(is_focused)
.into()
}
#[inline(always)]
fn cell_row(
row: usize,
value: &str,
alignment: HorizontalAlignment,
is_focused: bool,
) -> Element<'a, Message, Renderer<B>> {
Cell::interactive(row, value)
.padding(CELL_PADDING)
.size(CELL_TEXT_SIZE)
.horizontal_alignment(alignment)
.style(style::Cell)
.focus(is_focused)
.into()
}
}
impl<'a, Message, B> Widget<Message, Renderer<B>> for TableViewer<'a, Message, B>
where
B: 'a + Backend + iced_graphics::backend::Text,
{
fn width(&self) -> Length {
self.width
}
fn height(&self) -> Length {
self.height
}
fn layout(&self, renderer: &Renderer<B>, limits: &layout::Limits) -> layout::Node {
let limits = limits.width(self.width).height(self.height);
let size = limits.resolve(Size::ZERO);
let columns = Column::<Message, Renderer<B>>::with_children(self.rows)
.align_items(Align::Center)
.width(self.width)
.height(self.height);
let scrollable = Scrollable::<Message, Renderer<B>>::new(&mut self.state.scroll)
.scrollbar_margin(SCROLLBAR_MARGIN)
.scrollbar_width(SCROLLBAR_WIDTH)
.scroller_width(SCROLLER_WIDTH)
.push(columns);
let final_column = Column::<Message, Renderer<B>>::new()
.width(Length::Fill)
.height(Length::Fill)
.push(self.header)
.push(scrollable);
let container = Container::<Message, Renderer<B>>::new(final_column)
.padding(CONTAINER_PADDING)
.width(self.width)
.height(self.height).layout(renderer, &limits.loose());
/*let children: Vec<layout::Node> = self
.rows
.iter()
.filter_map(|row| {
let mut node = row.layout(renderer, &limits.loose());
Some(node)
})
.collect();*/
layout::Node::with_children(size, container)
}
fn hash_layout(&self, state: &mut Hasher) {
use std::hash::Hash;
struct Marker;
std::any::TypeId::of::<Marker>().hash(state);
self.width.hash(state);
self.height.hash(state);
for row in &self.rows {
row.hash_layout(state);
}
}
fn draw(
&self,
_renderer: &mut Renderer<B>,
_defaults: &Defaults,
layout: Layout<'_>,
_cursor_position: Point,
_viewport: &Rectangle,
) -> (Primitive, mouse::Interaction) {
let
(
Primitive::Quad {
bounds: layout.bounds(),
background: Background::Color(Color::BLACK),
border_radius: self.radius,
border_width: 0.0,
border_color: Color::TRANSPARENT,
},
mouse::Interaction::default(),
)
}
}
impl<'a, Message, B> From<TableViewer<'a, Message, B>> for Element<'a, Message, Renderer<B>>
where
Message: 'a + Clone,
B: 'a + Backend + iced_graphics::backend::Text,
{
fn from(table_viewer: TableViewer<'a, Message, B>) -> Self {
Element::new(table_viewer)
}
}
#[derive(Default, Clone, Debug)]
pub struct State {
scroll: scrollable::State,
}
impl State {
#[must_use]
pub fn new() -> Self {
Self::default()
}
}
mod style {
use iced::Color;
use super::super::cell::{Directions, Style, StyleSheet};
const SURFACE: Color = Color::from_rgb(
0xF2 as f32 / 255.0,
0xF3 as f32 / 255.0,
0xF5 as f32 / 255.0,
);
const HEADER_BG: Color =
Color::from_rgb(85 as f32 / 255.0, 86 as f32 / 255.0, 89 as f32 / 255.0);
const HEADER_SEPARATOR: Color = Color::from_rgba(
153 as f32 / 255.0,
153 as f32 / 255.0,
153 as f32 / 255.0,
0.51,
);
const CELL_HIGHLIGHTED: Color = Color::from_rgba(
169 as f32 / 255.0,
169 as f32 / 255.0,
226 as f32 / 255.0,
0.42,
);
pub struct Header;
impl StyleSheet for Header {
fn active(&self) -> Style {
Style {
background: HEADER_BG.into(),
border_width: 0.,
border_color: Color::BLACK,
text_color: Color::WHITE,
separator: Some((HEADER_SEPARATOR, Directions::new().right())),
}
}
fn hovered(&self) -> Style {
Style {
background: HEADER_BG.into(),
border_width: 0.,
border_color: Color::BLACK,
text_color: Color::WHITE,
separator: Some((HEADER_SEPARATOR, Directions::new().right())),
}
}
fn highlight(&self) -> Style {
Style {
background: HEADER_BG.into(),
border_width: 0.,
border_color: Color::BLACK,
text_color: Color::WHITE,
separator: Some((HEADER_SEPARATOR, Directions::new().right())),
}
}
fn hover_highlight(&self) -> Style {
Style {
background: HEADER_BG.into(),
border_width: 0.,
border_color: Color::BLACK,
text_color: Color::WHITE,
separator: Some((HEADER_SEPARATOR, Directions::new().right())),
}
}
}
pub struct FirstCell;
impl StyleSheet for FirstCell {
fn active(&self) -> Style {
Style {
background: HEADER_BG.into(),
border_width: 0.,
border_color: Color::BLACK,
text_color: Color::WHITE,
separator: Some((HEADER_SEPARATOR, Directions::new().right())),
}
}
fn hovered(&self) -> Style {
Style {
background: HEADER_BG.into(),
border_width: 0.,
border_color: Color::BLACK,
text_color: Color::WHITE,
separator: Some((HEADER_SEPARATOR, Directions::new().right())),
}
}
fn highlight(&self) -> Style {
Style {
background: CELL_HIGHLIGHTED.into(),
border_width: 0.,
border_color: HEADER_SEPARATOR,
text_color: Color::BLACK,
separator: Some((HEADER_BG, Directions::new().right())),
}
}
fn hover_highlight(&self) -> Style {
Style {
background: CELL_HIGHLIGHTED.into(),
border_width: 0.,
border_color: HEADER_SEPARATOR,
text_color: Color::WHITE,
separator: Some((HEADER_BG, Directions::new().right())),
}
}
}
pub struct Cell;
impl StyleSheet for Cell {
fn active(&self) -> Style {
Style {
background: SURFACE.into(),
border_width: 0.,
border_color: HEADER_BG,
text_color: Color::BLACK,
separator: Some((HEADER_BG, Directions::new().right().bottom())),
}
}
fn hovered(&self) -> Style {
Style {
background: HEADER_BG.into(),
border_width: 0.,
border_color: HEADER_BG,
text_color: Color::WHITE,
separator: Some((HEADER_BG, Directions::new().right().bottom())),
}
}
fn highlight(&self) -> Style {
Style {
background: CELL_HIGHLIGHTED.into(),
border_width: 0.,
border_color: HEADER_SEPARATOR,
text_color: Color::BLACK,
separator: Some((HEADER_BG, Directions::new().right().bottom())),
}
}
fn hover_highlight(&self) -> Style {
Style {
background: CELL_HIGHLIGHTED.into(),
border_width: 0.,
border_color: HEADER_SEPARATOR,
text_color: Color::WHITE,
separator: Some((HEADER_BG, Directions::new().right().bottom())),
}
}
}
}
|
Markdown | UTF-8 | 1,899 | 2.65625 | 3 | [
"MIT"
] | permissive | # Scanner Soundboard
Reads codes via RFID or 1D/2D barcode USB scanners and plays soundfiles
mapped to them.
The input device is grabbed exlusively so that scanned codes will be
passed to the program regardless of what program/window currently has
focus.
I originally developed this to play insider jokes as custom sounds
(generated via text-to-speech engines) during regular internal evenings
of [Among Us](https://www.innersloth.com/games/among-us/) games. The
sounds are triggered by placing 3D-printed Among Us figurines (glued to
coin-size RFID tags) on a cheap (~12 €) USB RFID reader, itself covered
by a 3D-printed plan of a map from the game.
## Usage
1. Have a bunch of sound files.
2. Have a bunch of codes to trigger the sounds. Those codes can come
from RFID tags (10-digit strings seem to be common) or whatever you
can fit in a 1D barcode or matrix/2D barcode (Aztec Code, Data
Matrix, QR code, etc.). Anything your scanner supports.
3. Specify the path of the sound files and map the codes to sound
filenames in a configuration file (see `config-example.toml` for an
example).
4. Find out where your scanner is available as a device. `sudo lsinput`
and `sudo dmesg | tail` can help you here. Note that the path can
change over time, depending on the order devices are connected.
5. Run the program, pointing to the configuration file and input device:
```sh
$ scanner-soundboard -c config.toml -i /dev/input/event23
```
## Sound Formats
Ogg Vorbis and MP3 are supported out of the box. However, the employed
audio playback library ([rodio](https://github.com/RustAudio/rodio))
also supports FLAC, WAV, MP4 and AAC, but those have to be enabled as
features in `Cargo.toml` and require recompilation of the program.
## License
Scanner Soundboard is licensed under the MIT license.
## Author
Scanner Soundboard was created by Jochen Kupperschmidt.
|
Markdown | UTF-8 | 2,529 | 3.359375 | 3 | [] | no_license | # In Short
## Developing Flow
(short version)
1. `git pull/checkout` (clean checkout, no node_modules)
2. `npm install`
3. Make changes
4. Build - run `npm run ES6-to-ES5` (_lib_ folder will be updated)
5. Test (with Centralized-App - see the _Developing Flow_ _In Detail_ below)
6. Commit and push your changes
## Releasing Flow
(short version)
1. Make sure all changes are committed (step 6. in _Developing Flow_)
2. `npm version patch|minor|major|...` (this creates a tag and commits it - without pushing it)
3. Push the version change and the new generated tag
## Alternative Release Flow
(short version)
1. Commit changes
2. Run `npm run release <version-string>` to release (compiles and creates a tag)
# In Detail
## Developing Flow
1. Make sure you have a clean checkout and no _node_modules/_ (delete it if present)
2. Get dependencies with `npm install`
3. Make your changes
4. Build - run `npm run ES6-to-ES5` (_lib_ folder will be updated)
5. Test by following these steps:
- copy the current working _Service-Layer_ folder into _Centralized-App/node_modules/locktrip-svc-layer_
- run _Centralized-App_ and make sure your changes working as expected
**NOTE:** Alternatively you can directly checkout and work in the _Centralized-App/node_modules/locktrip-svc-layer/_ folder - but you have to know what you are doing. For examlpe running `npm install` could delete _node_modules/locktrip-svc-layer/_ and your canges would be lost if you hadn't committed your changes before running `npm install`.
6. Push changes to _Service-Layer_ GitHub. This should contain both changes in _src/_ and _lib/_ folders as well as any _package.json_ _package-lock.json_ files.
## Releasing Flow
1. Make sure all code is pushed to _Service-Layer_ on GitHub (step 6. in _Developing Flow_)
2. Run `npm version patch` to update version (or whatever other neded `npm version` alternative - minor, major etc.).
3. Push the version change and tag (created by `npm version ...` command in previous step 2.)
## Alternative Release Flow
1. Commit all changes to files in _src/_
2. Run `npm run release <version-string>` to both transpile from ES6 to ES5 and create a release with a git tag.
For example
`npm version release 1.1.9-rc1` would:
* compile with `npm run ES6-to-ES5`
* then commit with message "Prepare a release"
* then run `npm version 1.1.9-rc1` - this will change and commit _package.json_ and _package-lock.json_ with new version and create a git tag with this version
|
JavaScript | UTF-8 | 773 | 2.671875 | 3 | [] | no_license | app.factory('validations', function () {
return {
isEmpty: function (value) {
if (value === "" || value === null || value === undefined) {
return true;
} else {
return false;
};
},
isNumeric: function (value) {
if (!value) { return;};
if (value.match(/^[0-9]+$/)) {
return true;
} else {
return false;
}
},
isEmail: function (value) {
if (!value) { return; }
if (value.match(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/)) {
return true;
} else {
return false;
}
}
}
}); |
Java | UTF-8 | 491 | 1.71875 | 2 | [] | no_license | package com.xd.smartconstruction.pojo.vo.response;
import com.xd.smartconstruction.pojo.vo.BaseVO;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.List;
/**
* @author mm
* @Date 2021-02-01 11:18
*/
@ApiModel("分页返回模型")
@Data
public class GridPageVO<T> extends BaseVO {
@ApiModelProperty("总条数")
private Integer total;
@ApiModelProperty("内容")
private List<T> content;
}
|
Java | UTF-8 | 856 | 2.53125 | 3 | [] | no_license | package com.example.hello.model;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.UUID;
@Entity
@Table(name = "greetings")
public class Greeting {
@Id
@GeneratedValue(generator = "UUID")
@GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
private UUID id;
private String message;
public Greeting(String message) {
this.message = message;
}
public Greeting() {
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
|
Python | UTF-8 | 1,110 | 2.875 | 3 | [] | no_license | import cv2
import numpy
capLeft = cv2.VideoCapture(1) #sets cap1 as the first camera (0 is the default laptop camera which isn't being used)
capRight = cv2.VideoCapture(0) #sets cap2 as the second camera
while(True):
# creates the frames for each camera
ret, frameLeft = capLeft.read()
ret, frameRight = capRight.read()
grayL = cv2.cvtColor(frameLeft, cv2.COLOR_BGR2GRAY)
grayR = cv2.cvtColor(frameRight, cv2.COLOR_BGR2GRAY)
HSV_L = cv2.cvtColor(frameLeft, cv2.COLOR_BGR2HSV)
HSV_R = cv2.cvtColor(frameRight, cv2.COLOR_BGR2HSV)
# Shows the content each camera is recording
cv2.imshow('frame_video_left', frameLeft)
cv2.imshow('frame_video_gray_left', grayL)
cv2.imshow('frame_video_HSV_left', HSV_L)
cv2.imshow('frame_video_right', frameRight)
cv2.imshow('frame_video_gray_right', grayR)
cv2.imshow('frame_video_HSV_right', HSV_R)
# if loop to break the camera feed when completed. The waitKey determines the number of frames
if cv2.waitKey(5) & 0xFF == ord('q'):
break
capLeft.release()
capRight.release()
cv2.destroyAllWindows() |
JavaScript | UTF-8 | 5,916 | 2.6875 | 3 | [] | no_license | 'use strict'
function Workspace(w, h, gridX, gridY, grid) {
var ws = this;
this.id = uniqueId();
this.width = w || 10000;
this.height = h || 10000;
this.backgroundColor = "#000000";
this.gridSizeX = gridX || 32;
this.gridSizeY = gridY || 32;
this.grid = grid;
this.gridify();
this.cotr = "Workspace";
}
Workspace.selectedCells = [];
Workspace.selectCells = function(cells) {
if(Array.isArray(cells)) {
this.selectedCells = cells;
} else {
this.selectedCells = [cells];
}
}
Workspace.prototype.save = function() {
return this;
}
Workspace.prototype.updateGridSize = function(w, h) {
this.gridSizeX = w;
this.gridSizeY = h;
};
Workspace.prototype.gridify = function() {
var grid = {};
for(var i = 0; i < this.width; i += this.gridSizeX) {
for(var j = 0; j < this.height; j += this.gridSizeY) {
let key = i + ":" + j;
let c = new Cell(i, j, this.gridSizeX, this.gridSizeY);
grid[key] = c;
if(this.grid && this.grid[key] && this.grid[key].size) {
grid[key].merge(this.grid[key])
}
}
}
this.grid = grid;
};
Workspace.prototype.getGridTile = function(x, y) {
var gridX = x - (x % this.gridSizeX);
var gridY = y - (y % this.gridSizeY);
return this.grid[gridX + ":" + gridY];
};
Workspace.prototype.getGridTilesFrom = function(sx, sy, ex, ey) {
var out = [];
for(var y = sy; y < ey; y += this.gridSizeY) {
for(var x = sx; x < ex; x += this.gridSizeX) {
out.push(this.getGridTile(x, y));
}
}
return out;
}
Workspace.prototype.getGridTilesOnObject = function(obj) {
var out = [];
for(var x = obj.xmin; x < obj.xmax; x += this.gridSizeX) {
for(var y = obj.ymin; y < obj.ymax; y += this.gridSizeX) {
let cell = this.getGridTile(x, y);
if(cell && cell.size) out.push(cell);
}
}
return out;
};
Workspace.prototype.deleteOnId = function(id, dolog) {
var keys = Object.keys(this.grid);
var i = 0, l = keys.length;
for(i; i < l; i++) {
if(this.grid[keys[i]][id]) {
delete this.grid[keys[i]][id];
}
}
}
Workspace.prototype.tilesOnId = function(id) {
var out = [];
var keys = Object.keys(this.grid);
var i = 0, l = keys.length;
for(i; i < l; i++) {
if(this.grid[keys[i]][id]) {
out.push({key: keys[i], tile: this.grid[keys[i]]});
}
}
return out;
}
Workspace.prototype.addToCell = function(obj, snap) {
var tile = this.getGridTile(obj.x, obj.y);
obj.x = tile.x;
obj.y = tile.y;
obj.setBB();
tile.content[obj.id] = obj;
tile.size += 1;
return tile;
}
Workspace.prototype.addToGrid = function(obj, snap) {
for(var x = obj.xmin; x < obj.xmax; x += this.gridSizeX) {
for(var y = obj.ymin; y < obj.ymax; y += this.gridSizeX) {
var tile = this.getGridTile(x, y);
if(tile) {
if(snap) {
obj.x = tile.x;
obj.y = tile.y;
obj.setBB();
}
tile.content[obj.id] = obj;
tile.size += 1;
}
}
}
};
Workspace.prototype.purgeCell = function(cell, layerId) {
if(layerId) {
var tile = cell.onLayer(layerId);
if(tile) {
delete cell.content[tile.id];
cell.size -= 1;
}
} else {
cell.content = {};
cell.size = 0;
}
}
Workspace.prototype.removeFromGrid = function(obj, dolog) {
for(var x = obj.xmin; x < obj.xmax; x += this.gridSizeX) {
for(var y = obj.ymin; y < obj.ymax; y += this.gridSizeX) {
var tile = this.getGridTile(x, y);
if(tile) {
delete tile.content[obj.id];
tile.size -= 1;
}
}
}
};
Workspace.prototype.updateGrid = function(x, y, obj, snap) {
this.deleteOnId(obj.id);
this.addToGrid(obj, snap);
};
class Cell {
constructor(x, y, w, h) {
this.id = uniqueId();
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.content = {};
this.size = 0;
}
static get tilesContainer() {
return document.getElementById('tiles');
}
get tiles() {
return Object.keys(this.content).map(k => this.content[k]);
}
renderTilesPreview() {
Cell.tilesContainer.innerHTML = '';
this.tiles.forEach(t => {
var c = new Canvas(this.w, this.h);
t.renderPreview(c.context, 0, 0, this.w, this.h);
Cell.tilesContainer.appendChild(c.canvas);
})
}
get stats() {
var stats = {};
this.tiles.sort((a, b) => {
return a.layer.index < b.layer.index ? -1 : 1;
})
.forEach(tile => {
Object.assign(stats, tile.stats);
});
return new Stats(stats)
}
add(obj, snap) {
if(!this.content[obj.id]) this.size += 1;
this.content[obj.id] = obj;
}
merge(cell) {
Object.keys(cell.content)
.forEach(tileId => {
let tile = cell.content[tileId];
let ntile = new Tile(tile.swatchId, tile.layerId, tile.stats);
ntile.id = tileId;
this.add(ntile);
})
}
}
Cell.prototype.renderStats = function() {
this.stats.render();
}
Cell.prototype.each = function(fn) {
Object.keys(this.content).forEach(key => {
fn(this.content[key], key);
})
}
Cell.prototype.onLayer = function(layerId) {
var out;
Object.keys(this.content).find((key) => {
if(this.content[key].layerId == layerId) {
return out = this.content[key];
}
})
return out;
}
Cell.prototype.removeContent = function(layerId) {
Object.keys(this.content).forEach(tileId => {
if(layerId) {
let tile = this.content[tileId];
if(tile.layerId !== layerId) return;
}
delete this.content[tileId];
})
}
Cell.prototype.setBB = function() {
this.xmin = this.x - this.w/2;
this.xmax = this.x + this.w/2;
this.ymin = this.y - this.h/2;
this.ymax = this.y + this.h/2;
};
|
Swift | UTF-8 | 5,713 | 2.59375 | 3 | [
"BSD-3-Clause"
] | permissive | // Copyright © 2020 Itty Bitty Apps. All rights reserved.
import Foundation
struct ColourSection {
var title: String?
var rows: [ColourItem]
}
extension RevertItems {
static var coloursData: [ColourSection] {
if #available(iOS 13.0, *) {
let labelSection = ColourSection(title: "LABEL", rows: [
ColourItem(name: #keyPath(UIColor.label), color: .label),
ColourItem(name: #keyPath(UIColor.secondaryLabel), color: .secondaryLabel),
ColourItem(name: #keyPath(UIColor.tertiaryLabel), color: .tertiaryLabel),
ColourItem(name: #keyPath(UIColor.quaternaryLabel), color: .quaternaryLabel)
])
let fillSection = ColourSection(title: "FILL", rows: [
ColourItem(name: #keyPath(UIColor.systemFill), color: .systemFill),
ColourItem(name: #keyPath(UIColor.secondarySystemFill), color: .secondarySystemFill),
ColourItem(name: #keyPath(UIColor.tertiarySystemFill), color: .tertiarySystemFill),
ColourItem(name: #keyPath(UIColor.quaternarySystemFill), color: .quaternarySystemFill)
])
let textSection: ColourSection = ColourSection(title: "TEXT", rows: [
ColourItem(name: #keyPath(UIColor.placeholderText), color: .placeholderText)
])
let standardContentBackgroundSection = ColourSection(title: "STANDARD CONTENT BACKGROUND", rows: [
ColourItem(name: #keyPath(UIColor.systemBackground), color: .systemBackground),
ColourItem(name: #keyPath(UIColor.secondarySystemBackground), color: .secondarySystemBackground),
ColourItem(name: #keyPath(UIColor.tertiarySystemBackground), color: .tertiarySystemBackground)
])
let groupedContentBackgroundSection = ColourSection(title: "GROUPED CONTENT BACKGROUND", rows: [
ColourItem(name: #keyPath(UIColor.systemGroupedBackground), color: .systemGroupedBackground),
ColourItem(name: #keyPath(UIColor.secondarySystemGroupedBackground), color: .secondarySystemGroupedBackground),
ColourItem(name: #keyPath(UIColor.tertiarySystemGroupedBackground), color: .tertiarySystemGroupedBackground)
])
let separatorSection: ColourSection = ColourSection(title: "SEPARATOR", rows: [
ColourItem(name: #keyPath(UIColor.separator), color: .separator),
ColourItem(name: #keyPath(UIColor.opaqueSeparator), color: .opaqueSeparator)
])
let linkSection: ColourSection = ColourSection(title: "LINK", rows: [
ColourItem(name: #keyPath(UIColor.link), color: .link)
])
let adaptableSection = ColourSection(title: "ADAPTABLE", rows: [
ColourItem(name: #keyPath(UIColor.systemBlue), color: .systemBlue),
ColourItem(name: #keyPath(UIColor.systemGreen), color: .systemGreen),
ColourItem(name: #keyPath(UIColor.systemIndigo), color: .systemIndigo),
ColourItem(name: #keyPath(UIColor.systemOrange), color: .systemOrange),
ColourItem(name: #keyPath(UIColor.systemPink), color: .systemPink),
ColourItem(name: #keyPath(UIColor.systemPurple), color: .systemPurple),
ColourItem(name: #keyPath(UIColor.systemRed), color: .systemRed),
ColourItem(name: #keyPath(UIColor.systemTeal), color: .systemTeal),
ColourItem(name: #keyPath(UIColor.systemYellow), color: .systemYellow)
])
let adaptableGraySection = ColourSection(title: "ADAPTABLE GRAY", rows: [
ColourItem(name: #keyPath(UIColor.systemGray), color: .systemGray),
ColourItem(name: #keyPath(UIColor.systemGray2), color: .systemGray2),
ColourItem(name: #keyPath(UIColor.systemGray3), color: .systemGray3),
ColourItem(name: #keyPath(UIColor.systemGray4), color: .systemGray4),
ColourItem(name: #keyPath(UIColor.systemGray5), color: .systemGray5),
ColourItem(name: #keyPath(UIColor.systemGray6), color: .systemGray6)
])
let nonAdaptableSection = ColourSection(title: "NONADAPTABLE", rows: [
ColourItem(name: #keyPath(UIColor.darkText), color: .darkText),
ColourItem(name: #keyPath(UIColor.lightText), color: .lightText)
])
let transparentSection = ColourSection(title: "TRANSPARENT", rows: [
ColourItem(name: #keyPath(UIColor.clear), color: .clear)
])
let fixedSection = ColourSection(title: "FIXED", rows: [
ColourItem(name: #keyPath(UIColor.black), color: .black),
ColourItem(name: #keyPath(UIColor.blue), color: .blue),
ColourItem(name: #keyPath(UIColor.brown), color: .brown),
ColourItem(name: #keyPath(UIColor.cyan), color: .cyan),
ColourItem(name: #keyPath(UIColor.darkGray), color: .darkGray),
ColourItem(name: #keyPath(UIColor.gray), color: .gray),
ColourItem(name: #keyPath(UIColor.green), color: .green),
ColourItem(name: #keyPath(UIColor.lightGray), color: .lightGray),
ColourItem(name: #keyPath(UIColor.magenta), color: .magenta),
ColourItem(name: #keyPath(UIColor.orange), color: .orange),
ColourItem(name: #keyPath(UIColor.purple), color: .purple),
ColourItem(name: #keyPath(UIColor.red), color: .red),
ColourItem(name: #keyPath(UIColor.white), color: .white),
ColourItem(name: #keyPath(UIColor.yellow), color: .yellow)
])
return [
labelSection,
fillSection,
textSection,
standardContentBackgroundSection,
groupedContentBackgroundSection,
separatorSection,
linkSection,
adaptableSection,
adaptableGraySection,
nonAdaptableSection,
transparentSection,
fixedSection
]
} else {
return [ColourSection(title: "Dynamic Colours only available in iOS 13 and above", rows: [])]
}
}
}
|
Java | UTF-8 | 5,228 | 2.015625 | 2 | [
"Apache-2.0"
] | permissive | /*
* 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.
*/
package io.trino.plugin.deltalake;
import io.trino.testing.AbstractTestQueryFramework;
import org.testng.annotations.Test;
import static io.trino.testing.TestingNames.randomNameSuffix;
import static org.assertj.core.api.Assertions.assertThat;
import static org.testng.Assert.assertEquals;
public abstract class BaseDeltaLakeSharedMetastoreWithTableRedirectionsTest
extends AbstractTestQueryFramework
{
protected final String schema = "test_shared_schema_" + randomNameSuffix();
protected abstract String getExpectedHiveCreateSchema(String catalogName);
protected abstract String getExpectedDeltaLakeCreateSchema(String catalogName);
@Test
public void testReadInformationSchema()
{
assertThat(query("SELECT table_schema FROM hive_with_redirections.information_schema.tables WHERE table_name = 'hive_table' AND table_schema='" + schema + "'"))
.skippingTypesCheck()
.containsAll("VALUES '" + schema + "'");
assertThat(query("SELECT table_schema FROM hive_with_redirections.information_schema.tables WHERE table_name = 'delta_table' AND table_schema='" + schema + "'"))
.skippingTypesCheck()
.containsAll("VALUES '" + schema + "'");
assertThat(query("SELECT table_schema FROM delta_with_redirections.information_schema.tables WHERE table_name = 'hive_table' AND table_schema='" + schema + "'"))
.skippingTypesCheck()
.containsAll("VALUES '" + schema + "'");
assertThat(query("SELECT table_schema FROM delta_with_redirections.information_schema.tables WHERE table_name = 'delta_table' AND table_schema='" + schema + "'"))
.skippingTypesCheck()
.containsAll("VALUES '" + schema + "'");
assertQuery("SELECT table_name, column_name from hive_with_redirections.information_schema.columns WHERE table_schema = '" + schema + "'",
"VALUES" +
"('hive_table', 'a_integer'), " +
"('delta_table', 'a_varchar')");
assertQuery("SELECT table_name, column_name from delta_with_redirections.information_schema.columns WHERE table_schema = '" + schema + "'",
"VALUES" +
"('hive_table', 'a_integer'), " +
"('delta_table', 'a_varchar')");
}
@Test
public void testSelect()
{
assertThat(query("SELECT * FROM hive_with_redirections." + schema + ".hive_table")).matches("VALUES 1, 2, 3");
assertThat(query("SELECT * FROM hive_with_redirections." + schema + ".delta_table")).matches("VALUES CAST('a' AS varchar), CAST('b' AS varchar), CAST('c' AS varchar)");
assertThat(query("SELECT * FROM delta_with_redirections." + schema + ".hive_table")).matches("VALUES 1, 2, 3");
assertThat(query("SELECT * FROM delta_with_redirections." + schema + ".delta_table")).matches("VALUES CAST('a' AS varchar), CAST('b' AS varchar), CAST('c' AS varchar)");
}
@Test
public void testShowTables()
{
assertThat(query("SHOW TABLES FROM hive_with_redirections." + schema)).matches("VALUES CAST('hive_table' AS varchar), CAST('delta_table' AS varchar)");
assertThat(query("SHOW TABLES FROM delta_with_redirections." + schema)).matches("VALUES CAST('hive_table' AS varchar), CAST('delta_table' AS varchar)");
}
@Test
public void testShowSchemas()
{
assertThat(query("SHOW SCHEMAS FROM hive_with_redirections"))
.skippingTypesCheck()
.containsAll("VALUES '" + schema + "'");
assertThat(query("SHOW SCHEMAS FROM delta_with_redirections"))
.skippingTypesCheck()
.containsAll("VALUES '" + schema + "'");
String showCreateHiveWithRedirectionsSchema = (String) computeActual("SHOW CREATE SCHEMA hive_with_redirections." + schema).getOnlyValue();
assertEquals(
showCreateHiveWithRedirectionsSchema,
getExpectedHiveCreateSchema("hive_with_redirections"));
String showCreateDeltaLakeWithRedirectionsSchema = (String) computeActual("SHOW CREATE SCHEMA delta_with_redirections." + schema).getOnlyValue();
assertEquals(
showCreateDeltaLakeWithRedirectionsSchema,
getExpectedDeltaLakeCreateSchema("delta_with_redirections"));
}
@Test
public void testPropertiesTable()
{
assertThat(query("SELECT * FROM delta_with_redirections." + schema + ".\"delta_table$properties\""))
.matches("SELECT * FROM hive_with_redirections." + schema + ".\"delta_table$properties\"");
}
}
|
Markdown | UTF-8 | 372 | 3.015625 | 3 | [
"Apache-2.0"
] | permissive | # DateToWords
Write a program that accepts as input from the user the date in dd-mm-yyyy format. The output should be the date in words. Sample input: Input date: 04-04-1982 Output: Fourth of April, Nineteen Eighty Two
#To Run
```
javac DateToWords.java
java DateToWords
Please enter date in dd-mm-yyyy format
04-12-1989
fourth of december nineteen eighty nine
```
|
Python | UTF-8 | 1,045 | 3.234375 | 3 | [] | no_license | import requests
from bs4 import BeautifulSoup
import bs4
def gethtml(url):
try:
r=requests.get(url, timeout = 30)
r.raise_for_status
r.encoding = r.apparent_encoding
return r.text
except:
print('哈哈错了吧')
def transf(ulist,html):
soup = BeautifulSoup(html,"html.parser")
for tr in soup.find('tbody').children:
if isinstance(tr,bs4.element.Tag):
tdss=tr('td')
ulist.append([tdss[0].string,tdss[1].string,tdss[3].string])
def finalprint(uulist,num1,num2):
ttlist='{0:{3}^10}\t\t{1:{3}^10}\t\t{2:{3}^10}'
print(ttlist.format('名次',"学校","分数",chr(12288)))
for i in range(num1,num2):
nn = uulist[i]
print(ttlist.format(nn[0],nn[1],nn[2],chr(12288)))
def main(num1,num2): #打印前多少名的大学
url = 'http://www.zuihaodaxue.com/zuihaodaxuepaiming2018.html'
uulist = []
html = gethtml(url)
transf(uulist,html)
finalprint(uulist,num1,num2)
if __name__ == '__main__':
main(24,46)
|
Python | UTF-8 | 668 | 3.765625 | 4 | [] | no_license | def tambah(a, b, c=0, d=0 ):
if a == 0:
print("hasil b")
return b + c + d
elif b == 0:
print("hasil a")
return a + c + d
return a + b + c + d
def cetak(p):
if p == 1:
print("angka 1")
return
tulisan = str(p) # casting
print("Hasilnya adalah " + tulisan)
return
# 5! = 5 * 4! = 5 * 4 * 3 * 2 * 1 = 120
# 2! = 2 * 1! = 2
# 3! = 3 * 2! = 3 * 2 * 1 = 6
# 1! = 1 * 0! = 1
# 0! = 1 = 1
# n! = n * (n-1)!
# rekursif
def faktorial(n):
#base case
if n == 0:
return 1
if n == 1:
return 1
#normal case
return n * faktorial(n-1)
hasil = faktorial(100)
cetak(hasil) |
Java | UTF-8 | 6,120 | 1.875 | 2 | [] | no_license | package com.example.ressenger;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
import yuku.ambilwarna.AmbilWarnaDialog;
public class AddPeopleBottomSheet extends BottomSheetDialogFragment implements AdapterView.OnItemSelectedListener {
Context mContext;
List<UserDetails> selectedUsers = new ArrayList<>();
private BottomSheetListener listener;
Boolean chatRoom;
public AddPeopleBottomSheet(Context context, Boolean chatRoom)
{
mContext=context;
this.chatRoom=chatRoom;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.layout_add_people_bottomsheet, container, false);
final TextInputLayout groupTitle = v.findViewById(R.id.groupTitle);
final Button okButton = v.findViewById(R.id.okButtonAddPeople);
final RecyclerView addPeopleRecycler=v.findViewById(R.id.addPeopleRecyclerBottomsheet);
final DatabaseReference usersRef= FirebaseDatabase.getInstance().getReference("users");
DatabaseReference friendsRef=FirebaseDatabase.getInstance().getReference("friends/"+ FirebaseAuth.getInstance().getUid());
friendsRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
final List<String> friends = new ArrayList<String>();
for(DataSnapshot ds : dataSnapshot.getChildren())
friends.add(ds.getKey());
usersRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
List<UserDetails> userDetails = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren())
{
if(!friends.contains(ds.getKey())) continue;
userDetails.add(ds.getValue(UserDetails.class));
}
addPeopleRecycler.setAdapter(new AddPeopleAdapter(mContext, userDetails, new AddPeopleAdapter.OnItemCheckListener() {
@Override
public void onItemCheck(UserDetails user) {
selectedUsers.add(user);}
@Override
public void onItemUncheck(UserDetails user) {
selectedUsers.remove(user);}
}));
addPeopleRecycler.setLayoutManager(new LinearLayoutManager(mContext));
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) { }
});
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
okButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String title = groupTitle.getEditText().getText().toString().trim();
if(!title.equals("")) {
if(!chatRoom) {
for (UserDetails selectedUser : selectedUsers)
FirebaseDatabase.getInstance().getReference("people/" + FirebaseAuth.getInstance().getUid()).child(title + '/' + selectedUser.getUid()).setValue("");
}
else
{
String id = FirebaseDatabase.getInstance().getReference("conversations").push().getKey();
DatabaseReference conversationsRef = FirebaseDatabase.getInstance().getReference("conversations/"+id),
chatroomsRef = FirebaseDatabase.getInstance().getReference("chatrooms/"+id);
for (UserDetails selectedUser : selectedUsers)
conversationsRef.child("participants/"+selectedUser.getUid()).setValue(true);
conversationsRef.child("participants/" + FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(true);
conversationsRef.child("private").setValue(false);
chatroomsRef.child("title").setValue(title);
chatroomsRef.child("admins/"+FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(true);
}
}
dismiss();
}
});
return v;
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(mContext);
}
public interface BottomSheetListener
{}
}
|
Shell | UTF-8 | 664 | 3.640625 | 4 | [] | no_license | #/bin/bash
[ -f $HOME/.vault ] && mv $HOME/.vault $HOME/.vault.bckp
[ -f $HOME/.token-helper.sh ] && rm $HOME/.token-helper.sh
printf "Creating token helper..\n"
tee -a ~/.token-helper.sh << END
#/bin/bash
case "\$1" in
"get")
[ -f $HOME/.vault-token ] && cat $HOME/.vault-token
exit 0
;;
"erase")
rm $HOME/.vault-token
exit 0
;;
"store")
read -r token
printf "\$token" > $HOME/.vault-token
exit 0
;;
*)
echo "Unknown method '\$1'."
exit 1
;;
esac
END
chmod 744 $HOME/.token-helper.sh
printf "Creating vault config..\n"
tee -a ~/.vault << END
# ~/.vault
token_helper = "$HOME/.token-helper.sh"
END
|
JavaScript | UTF-8 | 934 | 2.984375 | 3 | [] | no_license |
function handleLoginResult(resultDataString) {
resultDataJson = JSON.parse(resultDataString);
console.log("handle login response");
console.log(resultDataJson);
console.log(resultDataJson["status"]);
if (resultDataJson["status"] === "success") {
console.log("u made it");
window.location.replace("mainPage.html");
} else {
$("#login_error_message").text(resultDataJson["message"]);
}
}
function submitLoginForm(formSubmitEvent) {
console.log("submit login form");
formSubmitEvent.preventDefault();
$.post(
"api/login",
$("#login_form").serialize(),
(resultDataString) => handleLoginResult(resultDataString)
);
}
console.log(window.location.href);
// Bind the submit action of the form to a handler function
$("#login_form").submit((event) => submitLoginForm(event));
|
Java | ISO-8859-7 | 516 | 2.625 | 3 | [] | no_license | package com.saray.sinotk.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class DateTimeUtil {
public static Date GetDate(String testtime)
{
Date date = null;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);//趨ʽ
dateFormat.setLenient(false);
try {
date = dateFormat.parse(testtime);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}
|
Python | UTF-8 | 231 | 3.34375 | 3 | [] | no_license | n = int(input())
num = list(map(int,input().split()))
temp = []
for i in range(n):
if num[i] == i:
temp.append(num[i])
if len(temp) == 0:
print(-1)
else:
for i in sorted(temp):
print(i,end=' ')
|
Python | UTF-8 | 1,563 | 2.859375 | 3 | [] | no_license | import unittest
from Lesson17 import ex6_1
from Lesson17 import ex7_2
from Lesson17 import ex11_2
from Lesson17 import ex16_2
class AllTests(unittest.TestCase):
def test_dict(self):
self.assertEqual(ex6_1.for_dict(('Bitcoin', 'Ether', 'Ripple', 'Litecoin'), ('BTC', 'ETH', 'XRP', 'LTC')),
{'Bitcoin': 'BTC', 'Ether': 'ETH', 'Ripple': 'XRP', 'Litecoin': 'LTC'})
def test_cel_calc(self):
self.assertEqual(ex7_2.cels(0), 'Температура по Кельвину: 273.15 Температура по Фарренгейту: 32.0')
def test_kel_calc(self):
self.assertEqual(ex7_2.kelv(0), 'Tемпература по Цельсию: -273.15 Температура по Фарренгейту: -459.67')
def test_far_calc(self):
self.assertEqual(ex7_2.farren(0), 'Температура по Кельвину: 255.37 Tемпература по Цельсию: -17.78')
def test_email(self):
self.assertEqual(ex11_2.hide_email('dinay8@gmail.com'), 'din***@**.com')
def test_num_phone(self):
self.assertEqual(ex16_2.phone_num('063-999-99-99'), '(+38) 063 999-99-99')
self.assertEqual(ex16_2.phone_num('063 999-99-99'), '(+38) 063 999-99-99')
self.assertEqual(ex16_2.phone_num('063-99999-99'), '(+38) 063 999-99-99')
self.assertEqual(ex16_2.phone_num('+38063999-99-99'), '(+38) 063 999-99-99')
self.assertEqual(ex16_2.phone_num('380639999999'), '(+38) 063 999-99-99')
if __name__ == '__main__':
unittest.main() |
Java | UTF-8 | 59,404 | 2.015625 | 2 | [] | no_license | package distanceProj;
import location.Location;
import kml.PathToKML;
import email.GoogleMail;
import shortestPath.ShortestDistance;
import helpFiles.HelpWindow;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Scanner;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
/**
* Class: LoginGui
*
* This is the driving class. Everything starts here from the login screen.
* @author amanda
*
*/
public class LoginGui extends JFrame implements ActionListener, ItemListener
{
String userName = null;
final int MIN_LOCATIONS_CHECKED = 2;
// User buttons
JButton registerButton, loginButton, backButton1, logoutButton1, submitButton, createAccountButton;
JButton nextScreenButton1, nextScreenButton2, nextScreenButton3, backButton2, backButton3;
JButton logoutButton2, logoutButton3, backButton4, backButton5, backButton6, continueButton;
JButton helpButton1, helpButton2, helpButton3, helpButton4, helpButton5, helpButton6;
// Admin specific buttons
JButton addLocationButton, removeLocationButton, changeLocationButton, submitButton1, submitButton2;
JButton submitButton3, submitButton4;
JRadioButton chosenModifyLocButton;
ButtonGroup startLocationGroup = new ButtonGroup();
ButtonGroup stopLocationGroup = new ButtonGroup();
ButtonGroup modifyLocGroup = new ButtonGroup();
JLabel usernameLabel, passwordLabel, chooseUsernameLabel, choosePasswordLabel, reenterPasswordLabel;
JLabel userExists, emptyPassword;
JTextArea dateLabel;
JTextArea emailLabel;
// Admin specific labels
JLabel modifiedNameLabel, modifiedLatLabel, modifiedLongLabel, modifyTitle;
JTextArea introduction;
// Error Labels
JLabel badUserLabel, passwordsNotSame, needMoreLocError, selectStartError;
// Admin specific error labels
JLabel newLocNameLabel, newLocLatLabel, newLocLongLabel, existingLocError, emptyFieldsError;
JLabel emptyFieldsError2, chooseLocError, badLatOrLongError, badLatOrLongError2;
JLabel commaError1, commaError2, commaError3, commaError4;
JPasswordField passwordField;
JTextField usernameField, newUsernameField, newPasswordField, reenterPasswordField, emailField;
JTextField dateField;
// Admin specific textfields
JTextField newLocNameField, newLocLatField, newLocLongField, modifiedNameField, modifiedLatField;
JTextField modifiedLongField;
JPanel cards, loginScreen, startLocationScreen, stopLocationScreen, allLocationsScreen, addLocScreen;
JPanel removeLocScreen, changeLocScreen, newAccountScreen, startPanel, stopPanel, checkPanel;
JPanel adminScreen;
// Admin specific panels
JPanel removeLocPanel, modifyPanel, changeLocScreen2, modifySidePane, infoPane, addErrorPanel;
JPanel addLocSidePane;
JScrollPane scrollThroughLocations, scrollThroughChangeLocs, scrollThroughRemoveLocs;
Location startLocation;
Location stopLocation;
ArrayList<JCheckBox> allLocCheckBoxes = new ArrayList<JCheckBox>();
ArrayList<JCheckBox> checkedBoxes = new ArrayList<JCheckBox>();
ArrayList<JRadioButton> startLocationButtons = new ArrayList<JRadioButton>();
ArrayList<JRadioButton> stopLocationButtons = new ArrayList<JRadioButton>();
ArrayList<JRadioButton> modifyLocButtons = new ArrayList<JRadioButton>();
ArrayList<Location> locations = new ArrayList<Location>();
Color backGroundColor = new Color(0, 153, 153); // Dark Turquois
Color titleColor = new Color(153, 204, 255); // Lighter turquois
Color textColor = new Color(255, 255, 255); // White
Color otherColor = new Color(51, 153, 255); // Blue
Color backGroundColor2 = new Color(0, 102, 51); // Forest Green
Color lightBackColor = new Color(204, 255, 153); // Light Green
Color textColor2 = new Color(0, 0, 0); // Black
Color errorColor = new Color(255, 144, 88); // Orange
Color errorColor2 = Color.red;
public LoginGui()
{
super("Mapping Shortest Distance"); // The title appearing at the top
setLocation(100, 100); // Where the window pops up
setSize(800, 500); // Size of the window
// Setting up the layout - each screen is a card that is shown one at a time
cards = new JPanel(new CardLayout());
// Set up the first screen - login to your account
loginScreen = new JPanel(null);
loginScreen.setBackground(backGroundColor2);
usernameLabel = new JLabel("Username:");
usernameLabel.setLocation(520, 90);
usernameLabel.setSize(100, 30);
usernameLabel.setForeground(textColor);
loginScreen.add(usernameLabel);
usernameField = new JTextField();
usernameField.setLocation(600, 90);
usernameField.setSize(160, 30);
loginScreen.add(usernameField);
passwordLabel = new JLabel("Password:");
passwordLabel.setSize(100, 30);
passwordLabel.setLocation(520, 130);
passwordLabel.setForeground(textColor);
loginScreen.add(passwordLabel);
passwordField = new JPasswordField();
passwordField.setLocation(600, 130);
passwordField.setSize(160, 30);
loginScreen.add(passwordField);
loginButton = new JButton("Log in");
loginButton.setLocation(600, 200);
loginButton.setSize(160, 30);
loginScreen.add(loginButton);
registerButton = new JButton("Create a new account");
registerButton.setLocation(600, 240);
registerButton.setSize(160, 30);
loginScreen.add(registerButton);
helpButton1 = new JButton("HELP");
helpButton1.setLocation(600, 5);
helpButton1.setSize(100, 30);
loginScreen.add(helpButton1);
badUserLabel = new JLabel("Your username or password was incorrect");
badUserLabel.setForeground(errorColor);
badUserLabel.setLocation(500, 300);
badUserLabel.setSize(250, 15);
loginScreen.add(badUserLabel);
badUserLabel.setVisible(false);
commaError1 = new JLabel("You may not use a comma in the username or password.");
commaError1.setForeground(errorColor);
commaError1.setLocation(500, 300);
commaError1.setSize(250, 15);
commaError1.setVisible(false);
loginScreen.add(commaError1);
ImageIcon titleIcon = new ImageIcon("mappingMaestroTitle.jpg");
JLabel title = new JLabel(titleIcon);
title.setSize(320, 320);
title.setLocation(240, 5);
String intro = "\n Welcome to MappingMaestro by Code2Joy.\n\n";
intro += " MappingMaestro will allow you to select\n";
intro += " from several National Parks in the United\n";
intro += " States and Canada that you would like to\n";
intro += " visit. Then you choose the parks where you\n";
intro += " would like to start and stop. Next,\n";
intro += " MappingMaestro will find the shortest\n";
intro += " distance for you to travel to all of them\n";
intro += " by plotting the trip on Google Earth.\n\n";
intro += " Log in to your account or create a new\n";
intro += " one to continue.";
introduction = new JTextArea(intro);
introduction.setEditable(false);
introduction.setSize(280, 300);
introduction.setLocation(30, 90);
introduction.setOpaque(false);
introduction.setForeground(textColor);
loginScreen.add(introduction);
loginScreen.add(title);
// Set up the screen to create a new account
newAccountScreen = new JPanel(null);
newAccountScreen.setBackground(lightBackColor);
JLabel newAccountLabel = new JLabel("Create Account");
newAccountLabel.setFont(new Font("Serif", Font.ITALIC, 30));
newAccountLabel.setLocation(300, 20);
newAccountLabel.setSize(300, 30);
newAccountLabel.setForeground(backGroundColor2);
newAccountScreen.add(newAccountLabel);
chooseUsernameLabel = new JLabel("Choose a username: ");
chooseUsernameLabel.setLocation(250, 100);
chooseUsernameLabel.setSize(200, 30);
newAccountScreen.add(chooseUsernameLabel);
newUsernameField = new JTextField(20);
newUsernameField.setLocation(400, 100);
newUsernameField.setSize(200, 30);
newAccountScreen.add(newUsernameField);
choosePasswordLabel = new JLabel("Choose a password: ");
choosePasswordLabel.setLocation(250, 150);
choosePasswordLabel.setSize(200, 30);
newAccountScreen.add(choosePasswordLabel);
newPasswordField = new JTextField(20);
newPasswordField.setLocation(400, 150);
newPasswordField.setSize(200, 30);
newAccountScreen.add(newPasswordField);
reenterPasswordLabel = new JLabel("Re-enter password: ");
reenterPasswordLabel.setLocation(250, 200);
reenterPasswordLabel.setSize(200, 30);
newAccountScreen.add(reenterPasswordLabel);
reenterPasswordField = new JTextField(20);
reenterPasswordField.setLocation(400, 200);
reenterPasswordField.setSize(200, 30);
newAccountScreen.add(reenterPasswordField);
createAccountButton = new JButton("Create Account");
createAccountButton.setLocation(400, 250);
createAccountButton.setSize(200, 30);
newAccountScreen.add(createAccountButton);
helpButton2 = new JButton("HELP");
helpButton2.setLocation(600, 5);
helpButton2.setSize(100, 30);
newAccountScreen.add(helpButton2);
backButton1 = new JButton("Back to Login Screen");
backButton1.setSize(200, 30);
backButton1.setLocation(400, 300);
newAccountScreen.add(backButton1);
passwordsNotSame = new JLabel("The passwords do not match.");
passwordsNotSame.setLocation(400, 350);
passwordsNotSame.setSize(250, 30);
passwordsNotSame.setForeground(errorColor2);
newAccountScreen.add(passwordsNotSame);
passwordsNotSame.setVisible(false);
userExists = new JLabel("This account already exists.");
userExists.setForeground(errorColor2);
userExists.setLocation(400, 350);
userExists.setSize(250, 30);
newAccountScreen.add(userExists);
userExists.setVisible(false);
emptyPassword = new JLabel("You must enter a username and password");
emptyPassword.setForeground(errorColor2);
emptyPassword.setLocation(400, 350);
emptyPassword.setSize(250, 30);
newAccountScreen.add(emptyPassword);
emptyPassword.setVisible(false);
commaError2 = new JLabel("You may not enter a comma in the username or password.");
commaError2.setForeground(errorColor2);
commaError2.setLocation(400, 350);
commaError2.setSize(350, 30);
newAccountScreen.add(commaError2);
commaError2.setVisible(false);
// Set up the third screen - choose the locations
allLocationsScreen = new JPanel(new BorderLayout());
// Set up the top panel and its buttons/labels
JPanel topPanel = new JPanel(new FlowLayout());
JLabel chooseLocation = new JLabel("Choose the locations to map.");
topPanel.add(chooseLocation);
topPanel.setBackground(lightBackColor);
helpButton3 = new JButton("HELP");
topPanel.add(helpButton3);
allLocationsScreen.add(topPanel, BorderLayout.NORTH);
// Set up the right panel and its buttons/labels
JPanel rightPanel = new JPanel(new BorderLayout());
nextScreenButton1 = new JButton("NEXT");
rightPanel.add(nextScreenButton1, BorderLayout.NORTH);
logoutButton1 = new JButton("Logout"); // Go back to the login screen
topPanel.add(logoutButton1);
rightPanel.setBackground(backGroundColor2);
allLocationsScreen.add(rightPanel, BorderLayout.EAST);
// Make that panel scrollable
checkPanel = new JPanel(new GridLayout(0,1));
scrollThroughLocations = new JScrollPane(checkPanel);
allLocationsScreen.add(scrollThroughLocations, BorderLayout.CENTER);
needMoreLocError = new JLabel("You must choose at least " + MIN_LOCATIONS_CHECKED + " locations.");
needMoreLocError.setForeground(Color.red);
allLocationsScreen.add(needMoreLocError, BorderLayout.SOUTH);
needMoreLocError.setVisible(false);
// Set up the fourth screen - select start location
startLocationScreen = new JPanel(new BorderLayout());
startPanel = new JPanel(new GridLayout(0,1));
JPanel startTopPanel = new JPanel(new FlowLayout());
JLabel selectStartLabel = new JLabel("Select the starting location");
startTopPanel.setBackground(lightBackColor);
startTopPanel.add(selectStartLabel);
helpButton4 = new JButton("HELP");
startTopPanel.add(helpButton4);
startLocationScreen.add(startTopPanel, BorderLayout.NORTH);
JPanel sidePanel = new JPanel(new BorderLayout());
sidePanel.setBackground(backGroundColor2);
nextScreenButton2 = new JButton("NEXT");
sidePanel.add(nextScreenButton2, BorderLayout.NORTH);
selectStartError = new JLabel("You must choose a starting location");
selectStartError.setForeground(Color.red);
startLocationScreen.add(selectStartError, BorderLayout.SOUTH);
selectStartError.setVisible(false);
JScrollPane scrollThroughStart = new JScrollPane(startPanel);
startLocationScreen.add(scrollThroughStart, BorderLayout.CENTER);
/*
backButton2 = new JButton("Back");
sidePanel.add(backButton2);
*/
logoutButton2 = new JButton("Logout");
startTopPanel.add(logoutButton2);
startLocationScreen.add(sidePanel, BorderLayout.EAST);
// Set up the fifth screen - select the stop location
stopLocationScreen = new JPanel(new BorderLayout());
stopPanel = new JPanel(new GridLayout(0,1));
JPanel stopTopPanel = new JPanel(new FlowLayout());
JLabel selectStopLabel = new JLabel("Select the ending location");
stopTopPanel.setBackground(lightBackColor);
stopTopPanel.add(selectStopLabel);
helpButton5 = new JButton("HELP");
stopTopPanel.add(helpButton5);
stopLocationScreen.add(stopTopPanel, BorderLayout.NORTH);
JScrollPane scrollThroughStop = new JScrollPane(stopPanel);
stopLocationScreen.add(scrollThroughStop, BorderLayout.CENTER);
JPanel emailPanel = new JPanel();
emailPanel.setLayout(new BoxLayout(emailPanel, BoxLayout.Y_AXIS));
emailPanel.add(Box.createRigidArea(new Dimension(0,30)));
String emailInstructions = "\n If you would like to ";
emailInstructions += "\n send your trip to your";
emailInstructions += "\n email address, enter your ";
emailInstructions += "\n information below. \n\n";
JTextArea emailInfo = new JTextArea(emailInstructions);
emailInfo.setOpaque(false);
emailInfo.setEditable(false);
emailInfo.setForeground(textColor);
emailPanel.add(emailInfo);
emailPanel.add(Box.createVerticalGlue());
emailLabel = new JTextArea("Enter your email address:");
emailLabel.setForeground(textColor);
emailLabel.setOpaque(false);
emailLabel.setEditable(false);
emailPanel.add(emailLabel);
emailPanel.add(Box.createRigidArea(new Dimension(0,10)));
emailPanel.add(Box.createVerticalGlue());
emailField = new JTextField();
emailField.setPreferredSize(new Dimension(100, 30));
emailField.setMaximumSize(new Dimension(200, 30));
emailPanel.add(emailField);
emailPanel.add(Box.createRigidArea(new Dimension(0,30)));
dateLabel = new JTextArea("Enter the date of the trip:");
dateLabel.setForeground(textColor);
dateLabel.setOpaque(false);
dateLabel.setEditable(false);
emailPanel.add(dateLabel);
emailPanel.add(Box.createRigidArea(new Dimension(0,10)));
emailPanel.add(Box.createVerticalGlue());
dateField = new JTextField();
dateField.setPreferredSize(new Dimension(100, 30));
dateField.setMaximumSize(new Dimension(200, 30));
emailPanel.add(dateField);
emailPanel.add(Box.createRigidArea(new Dimension(0,10)));
emailPanel.setBackground(backGroundColor2);
nextScreenButton3 = new JButton("LAUNCH TRIP");
emailPanel.add(nextScreenButton3);
/*
backButton3 = new JButton("Back");
sidePanel2.add(backButton3);
*/
logoutButton3 = new JButton("Logout");
stopTopPanel.add(logoutButton3);
stopLocationScreen.add(emailPanel, BorderLayout.EAST);
// Set up the screen to add a location
addLocScreen = new JPanel(new BorderLayout());
JPanel addLocTopPanel = new JPanel(new FlowLayout());
addLocTopPanel.setBackground(lightBackColor);
JLabel addLocTitle = new JLabel("Add a new Location");
addLocTopPanel.add(addLocTitle);
addLocScreen.add(addLocTopPanel, BorderLayout.NORTH);
JPanel newLocPanel = new JPanel();
newLocPanel.setLayout(new BoxLayout(newLocPanel, BoxLayout.Y_AXIS));
newLocPanel.setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
newLocPanel.setBackground(lightBackColor);
newLocNameLabel = new JLabel("Location Name: ");
newLocNameField = new JTextField(20);
newLocPanel.add(newLocNameLabel);
newLocPanel.add(newLocNameField);
newLocLatLabel = new JLabel("Location Latitude: ");
newLocLatField = new JTextField(20);
newLocPanel.add(newLocLatLabel);
newLocPanel.add(newLocLatField);
newLocLongLabel = new JLabel("Location Longitude: ");
newLocLongField = new JTextField(20);
newLocPanel.add(newLocLongLabel);
newLocPanel.add(newLocLongField);
addLocSidePane = new JPanel();
addLocSidePane.setLayout(new BoxLayout(addLocSidePane, BoxLayout.Y_AXIS));
addLocSidePane.setBackground(lightBackColor);
submitButton1 = new JButton("Submit new location");
addLocSidePane.add(submitButton1);
addLocSidePane.add(Box.createRigidArea(new Dimension(0, 20)));
backButton4 = new JButton("CANCEL");
addLocSidePane.add(backButton4);
addLocScreen.add(addLocSidePane, BorderLayout.EAST);
existingLocError = new JLabel("That location already exists, you may not use it.");
existingLocError.setVisible(false);
existingLocError.setForeground(Color.red);
emptyFieldsError = new JLabel("You must enter something in each field.");
emptyFieldsError.setVisible(false);
emptyFieldsError.setForeground(Color.red);
badLatOrLongError = new JLabel("You have entered an invalid latitude or longitude.");
badLatOrLongError.setVisible(false);
badLatOrLongError.setForeground(Color.red);
commaError3 = new JLabel("You may not enter a comma in the name.");
commaError3.setVisible(false);
commaError3.setForeground(Color.red);
addErrorPanel = new JPanel();
addErrorPanel.setLayout(new BoxLayout(addErrorPanel, BoxLayout.Y_AXIS));
addErrorPanel.add(existingLocError);
addErrorPanel.add(emptyFieldsError);
addErrorPanel.add(badLatOrLongError);
addErrorPanel.add(commaError3);
addLocScreen.add(newLocPanel, BorderLayout.CENTER);
addLocScreen.add(addErrorPanel, BorderLayout.SOUTH);
// Set up the screen to remove a location
removeLocPanel = new JPanel(new GridLayout(0,1));
removeLocScreen = new JPanel(new BorderLayout());
JPanel removeTopPanel = new JPanel(new FlowLayout());
JLabel removeLocTitle = new JLabel("Remove a Location");
removeTopPanel.setBackground(lightBackColor);
removeTopPanel.add(removeLocTitle);
removeLocScreen.add(removeTopPanel, BorderLayout.NORTH);
JPanel removeSidePanel = new JPanel();
removeSidePanel.setLayout(new BoxLayout(removeSidePanel, BoxLayout.Y_AXIS));
removeSidePanel.setBackground(lightBackColor);
submitButton2 = new JButton("Submit removed locations");
removeSidePanel.add(submitButton2);
removeSidePanel.add(Box.createRigidArea(new Dimension(0,20)));
backButton5 = new JButton("CANCEL");
removeSidePanel.add(backButton5);
removeLocScreen.add(removeSidePanel, BorderLayout.EAST);
// Make that panel scrollable
scrollThroughRemoveLocs = new JScrollPane(removeLocPanel);
removeLocScreen.add(scrollThroughRemoveLocs, BorderLayout.CENTER);
// Set up the screen to choose a location to modify
changeLocScreen = new JPanel(new BorderLayout());
JPanel changeLocTopPanel = new JPanel(new FlowLayout());
changeLocTopPanel.setBackground(lightBackColor);
JLabel changeLocTitle = new JLabel("Change a Location");
changeLocTopPanel.add(changeLocTitle);
changeLocScreen.add(changeLocTopPanel, BorderLayout.NORTH);
modifyPanel = new JPanel(new GridLayout(0,1));
// Make that panel scrollable
scrollThroughChangeLocs = new JScrollPane(modifyPanel);
changeLocScreen.add(scrollThroughChangeLocs, BorderLayout.CENTER);
modifySidePane = new JPanel();
modifySidePane.setLayout(new BoxLayout(modifySidePane, BoxLayout.Y_AXIS));
modifySidePane.setBackground(lightBackColor);
//modifySidePane.add(Box.createVerticalGlue());
submitButton3 = new JButton("Submit location to modify");
modifySidePane.add(submitButton3);
modifySidePane.add(Box.createRigidArea(new Dimension(0, 10)));
backButton6 = new JButton("CANCEL");
modifySidePane.add(backButton6);
chooseLocError = new JLabel("You must choose a location.");
chooseLocError.setVisible(false);
chooseLocError.setForeground(Color.red);
changeLocScreen.add(chooseLocError, BorderLayout.SOUTH);
changeLocScreen.add(modifySidePane, BorderLayout.EAST);
// Set up the screen to actually input information to modify
changeLocScreen2 = new JPanel(new BorderLayout());
JPanel infoTopPanel = new JPanel(new FlowLayout());
modifyTitle = new JLabel(); // Depends on what location to modify
infoTopPanel.add(modifyTitle);
infoTopPanel.setBackground(lightBackColor);
changeLocScreen2.add(infoTopPanel, BorderLayout.NORTH);
infoPane = new JPanel();
infoPane.setLayout(new BoxLayout(infoPane, BoxLayout.Y_AXIS));
infoPane.setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
infoPane.setBackground(lightBackColor);
modifiedNameLabel = new JLabel("Enter the new name: ");
infoPane.add(modifiedNameLabel);
modifiedNameField = new JTextField(20);
infoPane.add(modifiedNameField);
modifiedLatLabel = new JLabel("Enter the new latitude: ");
infoPane.add(modifiedLatLabel);
modifiedLatField = new JTextField(20);
infoPane.add(modifiedLatField);
modifiedLongLabel = new JLabel("Enter the new longitude: ");
infoPane.add(modifiedLongLabel);
modifiedLongField = new JTextField(20);
infoPane.add(modifiedLongField);
JPanel sidePane2 = new JPanel(new FlowLayout());
sidePane2.setBackground(lightBackColor);
submitButton4 = new JButton("Submit the new location.");
sidePane2.add(submitButton4);
JPanel modifyErrorPanel = new JPanel();
modifyErrorPanel.setLayout(new BoxLayout(modifyErrorPanel, BoxLayout.Y_AXIS ));
emptyFieldsError2 = new JLabel("You must enter something in each field.");
emptyFieldsError2.setForeground(Color.red);
emptyFieldsError2.setVisible(false);
modifyErrorPanel.add(emptyFieldsError2);
badLatOrLongError2 = new JLabel("You have entered an invalid latitude or longitude.");
badLatOrLongError2.setForeground(Color.red);
badLatOrLongError2.setVisible(false);
modifyErrorPanel.add(badLatOrLongError2);
commaError4 = new JLabel("You may not enter a comma in the name.");
commaError4.setForeground(Color.red);
commaError4.setVisible(false);
modifyErrorPanel.add(commaError4);
changeLocScreen2.add(infoPane);
changeLocScreen2.add(sidePane2, BorderLayout.EAST);
changeLocScreen2.add(modifyErrorPanel, BorderLayout.SOUTH);
// Set up admin screen - can choose if want to change locations or continue
adminScreen = new JPanel(null);
adminScreen.setBackground(lightBackColor);
addLocationButton = new JButton("Add New Location");
addLocationButton.setSize(200, 50);
addLocationButton.setLocation(300, 50);
adminScreen.add(addLocationButton);
removeLocationButton = new JButton("Delete Location");
removeLocationButton.setSize(200, 50);
removeLocationButton.setLocation(300, 150);
adminScreen.add(removeLocationButton);
changeLocationButton = new JButton("Modify Existing Location");
changeLocationButton.setSize(200, 50);
changeLocationButton.setLocation(300, 250);
adminScreen.add(changeLocationButton);
continueButton = new JButton("Continue");
continueButton.setSize(200, 50);
continueButton.setLocation(300, 350);
adminScreen.add(continueButton);
helpButton6 = new JButton("HELP");
helpButton6.setSize(100, 30);
helpButton6.setLocation(600, 5);
adminScreen.add(helpButton6);
// Allows something to happen when you press the button
registerButton.addActionListener(this);
backButton1.addActionListener(this);
//backButton2.addActionListener(this);
//backButton3.addActionListener(this);
backButton4.addActionListener(this);
backButton5.addActionListener(this);
backButton6.addActionListener(this);
loginButton.addActionListener(this);
logoutButton1.addActionListener(this);
logoutButton2.addActionListener(this);
logoutButton3.addActionListener(this);
nextScreenButton1.addActionListener(this);
nextScreenButton2.addActionListener(this);
nextScreenButton3.addActionListener(this);
createAccountButton.addActionListener(this);
addLocationButton.addActionListener(this);
removeLocationButton.addActionListener(this);
changeLocationButton.addActionListener(this);
continueButton.addActionListener(this);
submitButton1.addActionListener(this);
submitButton2.addActionListener(this);
submitButton3.addActionListener(this);
submitButton4.addActionListener(this);
helpButton1.addActionListener(this);
helpButton2.addActionListener(this);
helpButton3.addActionListener(this);
helpButton4.addActionListener(this);
helpButton5.addActionListener(this);
helpButton6.addActionListener(this);
// Add all the "cards" or different screens to the deck
cards.add(loginScreen, "Login");
cards.add(newAccountScreen, "Create new account");
cards.add(allLocationsScreen, "Locations");
cards.add(startLocationScreen, "Start Location");
cards.add(stopLocationScreen, "Stop Location");
cards.add(adminScreen, "Admin Screen");
cards.add(addLocScreen, "New Location");
cards.add(removeLocScreen, "Remove Location");
cards.add(changeLocScreen, "Modify Location");
cards.add(changeLocScreen2, "Modify Chosen Location");
getContentPane().add(cards);
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public void itemStateChanged(ItemEvent e)
{
// The only thing that will make an item event is a checkbox, so it's safe to cast
if (e.getStateChange() == ItemEvent.SELECTED)
{
JCheckBox checked = (JCheckBox) e.getSource();
boolean containsItem = false;
for (int i = 0; i < checkedBoxes.size(); i++)
{
if (checked.getText().equals(checkedBoxes.get(i).getText()))
{
containsItem = true;
}
}
if (!containsItem)
{
checkedBoxes.add((JCheckBox) e.getSource());
}
}else{
JCheckBox checked = (JCheckBox) e.getSource();
for (int i = 0; i < checkedBoxes.size(); i++)
{
if (checked.getText().equals(checkedBoxes.get(i).getText()))
{
checkedBoxes.remove(i);
}
}
}
}
// Make the buttons do things
public void actionPerformed(ActionEvent e)
{
// Click register to create a new account
if (e.getSource() == registerButton)
{
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, "Create new account");
}
else if (e.getSource() == helpButton1 || e.getSource() == helpButton2 ||
e.getSource() == helpButton3 || e.getSource() == helpButton4 ||
e.getSource() == helpButton5 || e.getSource() == helpButton6)
{
URL index = ClassLoader.getSystemResource("helpInfo.html");
new HelpWindow("Help", index);
}
// Click back from the new account page to get back to the login screen
else if (e.getSource() == backButton1)
{
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, "Login");
}
// Go back from start locations page to all locations page
else if (e.getSource() == backButton2)
{
showLocationScreen();
}
// Go back from stop locations page to start location page
else if (e.getSource() == backButton3)
{
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, "Start Location");
}
// From the add location screen back to all locations screen
else if (e.getSource() == backButton4)
{
badLatOrLongError.setVisible(false);
existingLocError.setVisible(false);
emptyFieldsError.setVisible(false);
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, "Admin Screen");
}
// From the remove location screen to all locations screen
else if (e.getSource() == backButton5)
{
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, "Admin Screen");
}
// From the modify location screen to all location screen
else if (e.getSource() == backButton6)
{
// Remove all the radiobuttons from the panel because they get re-added each time
for (int n = 0; n < modifyLocButtons.size(); n++)
{
modifyLocGroup.remove(modifyLocButtons.get(n));
modifyPanel.remove(modifyLocButtons.get(n));
}
modifyLocButtons.clear();
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, "Admin Screen");
}
// Creates a new user account
if (e.getSource() == createAccountButton)
{
userExists.setVisible(false);
passwordsNotSame.setVisible(false);
emptyPassword.setVisible(false);
String newUsernameFromGui = newUsernameField.getText().trim();
String newPasswordFromGui = newPasswordField.getText().trim();
String newPasswordAgainFromGui = reenterPasswordField.getText().trim();
userName = newUsernameFromGui;
if (!newPasswordFromGui.equals(newPasswordAgainFromGui))
{
badUserLabel.setVisible(false);
commaError2.setVisible(false);
passwordsNotSame.setVisible(true);
validate();
}
else if (newUsernameFromGui.equals("") || newPasswordFromGui.equals("") ||
newPasswordAgainFromGui.equals(""))
{
badUserLabel.setVisible(false);
commaError2.setVisible(false);
emptyPassword.setVisible(true);
validate();
}
else if (containsComma(newUsernameFromGui) || containsComma(newPasswordFromGui) ||
containsComma(newPasswordAgainFromGui))
{
badUserLabel.setVisible(false);
emptyPassword.setVisible(false);
commaError2.setVisible(true);
validate();
}
else
{
try
{
// Check if the user has an account
boolean usernameExists = false;
BufferedReader buffReader = new BufferedReader(new FileReader("users.txt"));
// Read in each line from the users file
String line = buffReader.readLine();
while (line != null)
{
// Each line has comma separated values of username, password, A/U
// Make that into a user and add to the array
String delimiter = "[,]+";
String[] userTokens = line.split(delimiter);
for (int i = 0; i < userTokens.length; i++)
{
String usernameFromFile = userTokens[i];
usernameFromFile = usernameFromFile.trim();
i++; // pass the password
i++; // pass the user/admin letter
if (usernameFromFile.equals(newUsernameFromGui))
{
usernameExists = true;
userName = usernameFromFile;
}
}
line = buffReader.readLine();
}
if (usernameExists)
{
throw new BadUserException("This account already exists");
}
else
{
// Add the new user to the user file
// Right now the users get added as regular users. Admins must be added manually.
BufferedWriter out;
out = new BufferedWriter(new FileWriter("users.txt", true));
out.write(newUsernameFromGui + ", " + newPasswordFromGui + ", U\n");
out.close();
// Go to the next screen
showLocationScreen();
}
buffReader.close();
}
catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
catch (IOException e2)
{
e2.printStackTrace();
}
catch (BadUserException e3)
{
userExists.setVisible(true);
validate();
}
}
}
// Click "login" to get to the location menu
if (e.getSource() == loginButton)
{
String usernameFromGui = usernameField.getText().trim();
String passwordFromGui = passwordField.getText().trim();
userName = usernameFromGui;
User enteredUser = new User(usernameFromGui, passwordFromGui, false);
// Each line should have a new user
try
{
BufferedReader buffReader = new BufferedReader(new FileReader("users.txt"));
// An array of users already entered into the file "users.txt"
ArrayList<User> users = new ArrayList<User>();
// Read in each line from the users file
String line = buffReader.readLine();
while (line != null)
{
// Each line has comma separated values of username, password, A/U
// Make that into a user and add to the array
String delimiter = "[,]+";
String[] userTokens = line.split(delimiter);
for (int i = 0; i < userTokens.length; i++)
{
String usernameFromFile = userTokens[i];
usernameFromFile = usernameFromFile.trim();
i++;
String passwordFromFile = userTokens[i];
passwordFromFile = passwordFromFile.trim();
i++;
String isAdminFromFile = userTokens[i];
isAdminFromFile = isAdminFromFile.trim();
boolean admin = false;
if (isAdminFromFile.equals("A") || isAdminFromFile.equals("a"))
{
admin = true;
}
users.add(new User(usernameFromFile, passwordFromFile, admin));
}
line = buffReader.readLine();
}
// Check if the user has an account
boolean userExists = false;
boolean userIsAdmin = false;
for (int j = 0; j < users.size(); j++)
{
if (users.get(j).equals(enteredUser))
{
userExists = true;
if (users.get(j).isAdmin)
{
userIsAdmin = true;
}
}
}
// If the username or password are incorrect
if (!userExists)
{
throw new BadUserException();
}
else if (containsComma(usernameFromGui) || containsComma(passwordFromGui))
{
commaError1.setVisible(true);
}
// Otherwise, continue to the next screen
else
{
// Show an extra screen to modify things if the user has admin privileges
if (userIsAdmin == true)
{
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, "Admin Screen");
}
else
{
showLocationScreen();
}
buffReader.close();
}
}
catch(FileNotFoundException fnf)
{
System.out.println("Unable to open 'users.txt'");
}
catch(IOException io)
{
io.printStackTrace();
}
catch(BadUserException bu)
{
badUserLabel.setVisible(true);
validate();
}
}
// Go from picking all locations to picking start location
if (e.getSource() == nextScreenButton1)
{
if (checkedBoxes.size() < MIN_LOCATIONS_CHECKED)
{
needMoreLocError.setVisible(true);
validate();
repaint();
}
else
{
// Make radio buttons for the start location choices
for (int i = 0; i < checkedBoxes.size(); i++)
{
JRadioButton startRadio = new JRadioButton(checkedBoxes.get(i).getText());
startLocationButtons.add(startRadio);
startLocationGroup.add(startRadio);
startPanel.add(startRadio);
}
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, "Start Location");
}
}
// Go from picking start location to picking stop location
else if (e.getSource() == nextScreenButton2)
{
if (startLocationGroup.getSelection() == null)
{
selectStartError.setVisible(true);
validate();
}
else
{
for (int i = 0; i < startLocationButtons.size(); i++)
{
if (!startLocationButtons.get(i).isSelected())
{
stopLocationButtons.add(startLocationButtons.get(i));
stopLocationGroup.add(startLocationButtons.get(i));
stopPanel.add(startLocationButtons.get(i));
}
else
{
startLocation = getLocation(startLocationButtons.get(i).getText());
}
}
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, "Stop Location");
}
}
// Last next button - launch the application
else if (e.getSource() == nextScreenButton3)
{
if (stopLocationGroup.getSelection() == null)
{
JLabel selectStopError = new JLabel("You must choose an end location");
selectStopError.setForeground(Color.red);
stopLocationScreen.add(selectStopError, BorderLayout.SOUTH);
validate();
}
else
{
for (int i = 0; i < stopLocationButtons.size(); i++)
{
if (stopLocationButtons.get(i).isSelected())
{
stopLocation = getLocation(stopLocationButtons.get(i).getText());
}
}
ArrayList<Location> trip = getTrip();
trip = ShortestDistance.getShortestPath(trip);
try
{
PathToKML.createPath(trip, userName);
}
catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
String path = new File(LoginGui.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getParent();
String programLoc = path + "\\client\\googleearth.exe";
String fileLoc = path + "\\" + userName + ".kml";
PathToKML.openFile(programLoc, fileLoc);
// If the fields aren't empty, email the trip to the user
if (!emailField.getText().equals("") && !dateField.getText().equals(""))
{
String email = emailField.getText();
String date = dateField.getText();
String title = "Scheduled trip for " + date;
String message = "You have a schedule'd trip for " + date + ".\nHere is your trip's order of locations:\n";
int count = 1;
for(Location a: trip)
{
message += "\t" + count++ + ".) " + a.getName() + "\n";
}
try
{
GoogleMail.Send("CodeToJoy.345", "cmsc345pw", email, title, message);
}
catch (AddressException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
catch (MessagingException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
e.setSource(logoutButton1);
}
}
// Click "logout" from the application screen to go back to login screen
if (e.getSource() == logoutButton1 || e.getSource() == logoutButton2 ||
e.getSource() == logoutButton3)
{
for (int i = 0; i < allLocCheckBoxes.size(); i++)
{
allLocCheckBoxes.get(i).setSelected(false);
}
//allLocCheckBoxes.clear();
for (int j = 0; j < checkedBoxes.size(); j++)
{
checkedBoxes.get(j).setSelected(false);
}
checkedBoxes.clear();
//locations.clear();
usernameField.setText("");
passwordField.setText("");
newUsernameField.setText("");
newPasswordField.setText("");
reenterPasswordField.setText("");
badLatOrLongError.setVisible(false);
existingLocError.setVisible(false);
emptyFieldsError.setVisible(false);
// Takes all the buttons out of the group, then clears all the buttons
int numStartButtons = startLocationGroup.getButtonCount();
for (int k = 0; k < numStartButtons; k++)
{
startLocationGroup.remove(startLocationButtons.get(k));
startPanel.remove(startLocationButtons.get(k));
}
startLocationButtons.clear();
int numStopButtons = stopLocationGroup.getButtonCount();
for (int m = 0; m < numStopButtons; m++)
{
stopLocationGroup.remove(stopLocationButtons.get(m));
stopPanel.remove(stopLocationButtons.get(m));
}
stopLocationButtons.clear();
needMoreLocError.setVisible(false);
badUserLabel.setVisible(false);
passwordsNotSame.setVisible(false);
selectStartError.setVisible(false);
// Remove all the checkboxes from the panel because they get re-added each time
for (int n = 0; n < allLocCheckBoxes.size(); n++)
{
removeLocPanel.remove(allLocCheckBoxes.get(n));
}
// Remove all the checkboxes from the panel because they get re-added each time
for (int p = 0; p < allLocCheckBoxes.size(); p++)
{
checkPanel.remove(allLocCheckBoxes.get(p));
}
// Remove all the radiobuttons from the panel because they get re-added each time
for (int n = 0; n < modifyLocButtons.size(); n++)
{
modifyPanel.remove(modifyLocButtons.get(n));
modifyLocGroup.remove(modifyLocButtons.get(n));
}
validate();
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, "Login");
}
// Admin can add a new location to the list
else if (e.getSource() == addLocationButton)
{
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, "New Location");
}
// Add the new location to the file and go back to the admin screen
else if (e.getSource() == submitButton1)
{
// Get the input from the gui
String getName = newLocNameField.getText();
getName = getName.trim();
String getLat = newLocLatField.getText();
getLat = getLat.trim();
String getLong = newLocLongField.getText();
getLong = getLong.trim();
// Make sure the location does not already exist in the file
// Maybe because cannot add two widget to the same space.
if (getLocation(getName) != null)
{
emptyFieldsError.setVisible(false);
badLatOrLongError.setVisible(false);
commaError3.setVisible(false);
existingLocError.setVisible(true);
validate();
}
else if (containsComma(getName))
{
emptyFieldsError.setVisible(false);
badLatOrLongError.setVisible(false);
existingLocError.setVisible(false);
commaError3.setVisible(true);
validate();
}
// Make sure the user has entered something in each field
else if (getName.equals("") || getLat.equals("") || getLong.equals(""))
{
existingLocError.setVisible(false);
badLatOrLongError.setVisible(false);
commaError3.setVisible(false);
emptyFieldsError.setVisible(true);
validate();
}
else if (!isValidLat(getLat) || !isValidLong(getLong))
{
existingLocError.setVisible(false);
emptyFieldsError.setVisible(false);
commaError3.setVisible(false);
badLatOrLongError.setVisible(true);
}
// If not, we're good to go. Add it to the file.
// Idk why else isn't working correctly
//if (getLocation(getName) == null && (!(getName.equals("") || getLat.equals("") || getLong.equals(""))))
else
{
BufferedWriter writeToLocFile;
try
{
double lat = Double.parseDouble(getLat);
double lon = Double.parseDouble(getLong);
Location location = new Location(getName, lat, lon);
boolean added = false;
int size = locations.size();
for(int i = 0; i < size; i++){
if(location.compareTo(locations.get(i)) < 0 && added == false){
locations.add(i, location);
added = true;
}
}
if (added == false){
locations.add(location);
}
writeToLocFile = new BufferedWriter(new FileWriter("locations.txt", false));
for(Location l: locations){
writeToLocFile.write(l.getName() + ", " + l.getLat() + ", " + l.getLon() + "\n");
}
writeToLocFile.close();
}
catch(IOException e1)
{
e1.printStackTrace();
}
// Remove all the checkboxes from the panel because they get re-added each time
for (int i = 0; i < allLocCheckBoxes.size(); i++)
{
removeLocPanel.remove(allLocCheckBoxes.get(i));
}
// Go to the next screen
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, "Admin Screen");
}
}
// Admin can remove a location from the list
else if (e.getSource() == removeLocationButton)
{
// Remove all the checkboxes from the panel because they get re-added each time
for (int n = 0; n < allLocCheckBoxes.size(); n++)
{
removeLocPanel.remove(allLocCheckBoxes.get(n));
}
allLocCheckBoxes.clear();
locations = createLocationList();
// For each location in the file, make it into a checkbox
for (int j = 0; j < locations.size(); j++)
{
JCheckBox locCheck = new JCheckBox(locations.get(j).getName());
locCheck.addItemListener(this);
locCheck.setSelected(false);
allLocCheckBoxes.add(locCheck);
}
// Add each checkbox to the panel on the locations screen
for (int k = 0; k < allLocCheckBoxes.size(); k++)
{
removeLocPanel.add(allLocCheckBoxes.get(k));
}
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, "Remove Location");
}
// Remove the selected locations from the file
else if (e.getSource() == submitButton2)
{
try
{
File inputFile = new File("locations.txt");
File tempFile = new File("temp.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
while((currentLine = reader.readLine()) != null)
{
// Search the location checked to remove
String trimmedLine = currentLine.trim();
boolean canDelete = false;
for (int i = 0; i < checkedBoxes.size(); i++)
{
if (trimmedLine.startsWith(checkedBoxes.get(i).getText()))
{
canDelete = true;
}
}
// If the location in the line was not one of those checked,
// rewrite it to the temporary file.
if(!canDelete)
{
writer.write(currentLine + "\n");
}
}
writer.close();
reader.close();
if(!inputFile.delete())
{
System.out.println("Cannot remove.");
}
if(!tempFile.renameTo(inputFile))
{
System.out.println("Cannot rename");
}
// Remove all the checkboxes from the panel because they get re-added each time
for (int i = 0; i < allLocCheckBoxes.size(); i++)
{
removeLocPanel.remove(allLocCheckBoxes.get(i));
}
}
catch(Exception e1)
{
e1.printStackTrace();
}
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, "Admin Screen");
}
// Admin can modify a location in the list
else if (e.getSource() == changeLocationButton)
{
// Remove all the radiobuttons from the panel because they get re-added each time
for (int n = 0; n < modifyLocButtons.size(); n++)
{
modifyLocGroup.remove(modifyLocButtons.get(n));
modifyPanel.remove(modifyLocButtons.get(n));
}
modifyLocButtons.clear();
locations = createLocationList();
// For each location in the file, make it into a radio button
for (int j = 0; j < locations.size(); j++)
{
JRadioButton locRadio = new JRadioButton(locations.get(j).getName());
locRadio.setSelected(false);
modifyLocButtons.add(locRadio);
}
// Add each radio button to the panel on the change locations screen
for (int k = 0; k < modifyLocButtons.size(); k++)
{
modifyLocGroup.add(modifyLocButtons.get(k));
modifyPanel.add(modifyLocButtons.get(k));
}
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, "Modify Location");
}
// Submit a location to modify
else if (e.getSource() == submitButton3)
{
// Get the chosen button
boolean buttonSelected = false;
for (int i = 0; i < modifyLocButtons.size(); i++)
{
if (modifyLocButtons.get(i).isSelected())
{
chosenModifyLocButton = modifyLocButtons.get(i);
buttonSelected = true;
}
}
if (!buttonSelected)
{
chooseLocError.setVisible(true);
validate();
}
else
{
modifyTitle.setText("Selected location to modify: " + chosenModifyLocButton.getText());
validate();
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, "Modify Chosen Location");
}
}
// Show the screen to enter new info to modify location
else if (e.getSource() == submitButton4)
{
// Remove all the radiobuttons from the panel because they get re-added each time
for (int n = 0; n < modifyLocButtons.size(); n++)
{
modifyLocGroup.remove(modifyLocButtons.get(n));
modifyPanel.remove(modifyLocButtons.get(n));
}
modifyLocButtons.clear();
String modifiedLocName = modifiedNameField.getText();
modifiedLocName = modifiedLocName.trim();
String modifiedLocLat = modifiedLatField.getText();
modifiedLocLat = modifiedLocLat.trim();
String modifiedLocLong = modifiedLongField.getText();
modifiedLocLong = modifiedLocLong.trim();
// Make sure all the fields aren't empty
if (modifiedLocName.equals("") || modifiedLocLat.equals("") || modifiedLocLong.equals(""))
{
badLatOrLongError2.setVisible(false);
commaError4.setVisible(false);
emptyFieldsError2.setVisible(true);
validate();
}
else if (!isValidLat(modifiedLocLat) || !isValidLong(modifiedLocLong))
{
emptyFieldsError2.setVisible(false);
commaError4.setVisible(false);
badLatOrLongError2.setVisible(true);
validate();
}
else if (containsComma(modifiedLocName))
{
emptyFieldsError2.setVisible(false);
badLatOrLongError2.setVisible(false);
commaError4.setVisible(true);
validate();
}
// Else, find that line in the file, and rewrite as given
// Continue back to the admin screen
else
{
try
{
File inputFile = new File("locations.txt");
File tempFile = new File("temp.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
while((currentLine = reader.readLine()) != null)
{
// Search the location checked to remove
String trimmedLine = currentLine.trim();
boolean canDelete = false;
if (trimmedLine.startsWith(chosenModifyLocButton.getText()))
{
canDelete = true;
}
// If the location in the line was not the one to be modified, just rewrite it
if(!canDelete)
{
writer.write(currentLine + "\n");
}
// Otherwise, modify it and write it to the file
else
{
writer.write(modifiedLocName + ", " + modifiedLocLat + ", " + modifiedLocLong + "\n");
}
}
writer.close();
reader.close();
// Delete the original file
if(!inputFile.delete())
{
System.out.println("Cannot remove.");
}
// Rename the temporary file as the original
if(!tempFile.renameTo(inputFile))
{
System.out.println("Cannot rename");
}
}
catch(Exception e1)
{
e1.printStackTrace();
}
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, "Admin Screen");
}
}
else if (e.getSource() == continueButton)
{
showLocationScreen();
}
}
private ArrayList<Location> getTrip()
{
int start = 0;
int end = 0;
Location temp = null;
ArrayList<Location> trip = new ArrayList<Location>();
for (int i = 0; i < checkedBoxes.size(); i++)
{
if(getLocation(checkedBoxes.get(i).getText()).getName().equals(startLocation.getName())){
start = i;
}
if(getLocation(checkedBoxes.get(i).getText()).getName().equals(stopLocation.getName())){
end = i;
}
trip.add(getLocation(checkedBoxes.get(i).getText()));
}
temp =trip.get(0);
trip.set(0, trip.get(start));
trip.set(start, temp);
temp =trip.get(trip.size()-1);
trip.set(trip.size()-1, trip.get(end));
trip.set(end, temp);
return trip;
}
//
private Location getLocation(String locationName)
{
createLocationList();
for (int i = 0; i < locations.size(); i++)
{
if (locations.get(i).getName().equals(locationName))
{
return locations.get(i);
}
}
return null;
}
private ArrayList<Location> createLocationList()
{
try
{
locations.clear();
BufferedReader bR = new BufferedReader(new FileReader("locations.txt"));
// Read in all the locations from the file
String locLine = bR.readLine();
while(locLine != null)
{
String[] data = locLine.split(",");
double lat = Double.parseDouble(data[1]);
double lon = Double.parseDouble(data[2]);
locations.add(new Location(data[0], lat, lon));
locLine = bR.readLine();
}
bR.close();
}
catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
catch (IOException e2)
{
e2.printStackTrace();
}
return locations;
}
/** 1. Parse in locations from the file
2. Store in the ArrayList
3. Use it to make checkboxes
4. Go to the location screen
**/
private void showLocationScreen()
{
createLocationList();
for (int h = 0; h < checkedBoxes.size(); h++)
{
checkedBoxes.get(h).setSelected(false);
}
checkedBoxes.clear(); // If the admin used this, make sure it is clear again.
for (int g = 0; g < allLocCheckBoxes.size(); g++)
{
allLocCheckBoxes.get(g).setSelected(false);
}
allLocCheckBoxes.clear();
locations = createLocationList();
// For each location in the file, make it into a checkbox
for (int j = 0; j < locations.size(); j++)
{
JCheckBox locCheck = new JCheckBox(locations.get(j).getName());
locCheck.addItemListener(this);
locCheck.setSelected(false);
allLocCheckBoxes.add(locCheck);
}
// Add each checkbox to the panel on the locations screen
for (int k = 0; k < allLocCheckBoxes.size(); k++)
{
checkPanel.add(allLocCheckBoxes.get(k));
}
badUserLabel.setVisible(false);
validate();
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, "Locations");
}
private static boolean containsComma(String str)
{
int size = str.length();
for (int i = 0; i < size; i++)
{
if (str.charAt(i) == ',')
{
return true;
}
}
return false;
}
/**
* Checks to see if you have a valid latitude
* @param str
* @return
*/
private static boolean isValidLat(String str)
{
int size = str.length();
for (int i = 0; i < size; i++)
{
if (!Character.isDigit(str.charAt(i)) && str.charAt(i) != '-' && str.charAt(i) != '.')
{
return false;
}
}
double strToDouble = Double.parseDouble(str);
if (strToDouble > 90 || strToDouble < -90)
{
return false;
}
return true;
}
private static boolean isValidLong(String str)
{
int size = str.length();
for (int i = 0; i < size; i++)
{
if (!Character.isDigit(str.charAt(i)) && str.charAt(i) != '-' && str.charAt(i) != '.')
{
return false;
}
}
double strToDouble = Double.parseDouble(str);
if (strToDouble > 180 || strToDouble < -180)
{
return false;
}
return true;
}
public static void main(String[] args)
{
LoginGui logingui = new LoginGui();
}
}
|
Java | UTF-8 | 563 | 2.109375 | 2 | [] | no_license | package com.pliniosalazar.todo.repositories;
import com.pliniosalazar.todo.domain.Todo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
public interface TodoRepository extends JpaRepository<Todo, Integer> {
@Query("SELECT obj FROM Todo obj WHERE obj.finalizado = false ORDER BY obj.dataParaFinalizar")
List<Todo> findAllOpen();
@Query("SELECT obj FROM Todo obj WHERE obj.finalizado = true ORDER BY obj.dataParaFinalizar")
List<Todo> findAllClose();
}
|
Java | UTF-8 | 916 | 2.265625 | 2 | [] | no_license | package ibtikar.Fakhr;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class LoginPage extends PageBase{
public LoginPage(WebDriver driver) {
super(driver);
}
//home login button
@FindBy(xpath = "//a[@href='/ar/login']")
WebElement homeLoginBtn;
//user name field
@FindBy(name = "username")
WebElement userNameField;
//password field
@FindBy(name = "password")
WebElement passwordField;
//login button
@FindBy(xpath = "*//form/div[4]/button")
WebElement loginBtn;
//response message (repeated data)
@FindBy(xpath = "*//div/div[1]/div/div[2]/p")
WebElement resMsg;
public void loginMethod(String username,String password) {
userNameField.sendKeys(username);
passwordField.sendKeys(password);
loginBtn.click();
}
public String getResponseMessage() {
return resMsg.getText();
}
}
|
PHP | UTF-8 | 499 | 2.53125 | 3 | [] | no_license | <?php
require_once "config.php";
//$user = new User();
//
//$user->loadById(1);
//
//echo $user
//
//;
//
//$userList = User::getList();
//echo json_encode($userList);
//$expecificUsename = User::searchUser("Andre");
//echo json_encode($expecificUsename);
//$user = new User();
//
//
//$user->login("Andre","123456789");
//echo $user;
//$aluno = new User("Aluno","server45");
//
//$aluno->insert();
//
//echo $aluno;
$user = new User();
$user->loadById(3);
$user->update("Luis","server7Luis"); |
Java | UTF-8 | 784 | 2.15625 | 2 | [] | no_license | package edu.nju.hostelworld.dao;
import edu.nju.hostelworld.model.Hostel;
import edu.nju.hostelworld.util.City;
import edu.nju.hostelworld.util.HostelState;
import edu.nju.hostelworld.util.ResultMessage;
import java.util.List;
/**
* Created by Sorumi on 17/2/5.
*/
public interface HostelDao {
public ResultMessage addHostel(Hostel hostel);
public ResultMessage updateHostel(Hostel hostel);
public long countHostels();
public Hostel findHostelByID(String ID);
public Hostel findHostelByUsername(String username);
public List<Hostel> findAllHostels();
public List<Hostel> findHostelsByState(HostelState state);
public List<Hostel> findHostelsByCity(City city);
public List<Hostel> findHostelByKeyword(String keyword, String value);
}
|
JavaScript | UTF-8 | 3,890 | 2.703125 | 3 | [
"Apache-2.0"
] | permissive | /*
Import the internal libraries:
- CountryController
*/
import {
CountryController,
} from '../controller';
// Create instance of CountryController otherwise you can't use it
const countryController = new CountryController();
const initializeEndpoints = (parentRouter, authService) => {
/**
* @swagger
* /api/v1/countries:
* get:
* tags:
* - Categories
* description: Returns all countries
* produces:
* - application/json
* responses:
* 200:
* description: An array of countries
*/
parentRouter.get('/countries', countryController.index);
/**
* @swagger
* /api/v1/countries/create:
* get:
* tags:
* - Country
* description: Returns specific viewmodel such as countries
* produces:
* - application/json
* responses:
* 200:
* description: Create post
*/
parentRouter.get('/countries/create/', countryController.create);
/**
* @swagger
* /api/v1/countries/{id}:
* get:
* tags:
* - Country
* description: Returns specific post
* produces:
* - application/json
* parameters:
* - name: id
* description: Country id
* in: path
* required: true
* type: string
* responses:
* 200:
* description: Get post by id
*/
parentRouter.get('/countries/:id', countryController.show);
/**
* @swagger
* /api/v1/countries:
* post:
* tags:
* - Country
* description: Save post
* produces:
* - application/json
* parameters:
* - name: post
* description: Country object
* in: body
* required: true
* responses:
* 200:
* description: Return saved post
*/
parentRouter.post('/countries', countryController.store);
/**
* @swagger
* /api/v1/countries/{id}/edit:
* get:
* tags:
* - Country
* description: Returns specific viewmodel such as post, countries
* produces:
* - application/json
* parameters:
* - name: id
* description: Country id
* in: path
* required: true
* type: string
* responses:
* 200:
* description: Edit post by id
*/
parentRouter.get('/countries/:id/edit', countryController.edit);
/**
* @swagger
* /api/v1/countries/{id}:
* put:
* tags:
* - Country
* description: Update specific post detail
* produces:
* - application/json
* parameters:
* - name: id
* description: Country id
* in: path
* required: true
* type: string
* - name: post object
* description: post data
* in: body
* required: true
* responses:
* 200:
* description: Update post
*/
parentRouter.put('/countries/:id', countryController.update);
/**
* @swagger
* /api/v1/countries/{id}:
* delete:
* tags:
* - Country
* description: Delete specific post detail
* produces:
* - application/json
* parameters:
* - name: id
* description: Country id
* in: path
* required: true
* type: string
* responses:
* 200:
* description: Delete post
*/
parentRouter.delete('/countries/:id', countryController.destroy);
};
export default initializeEndpoints;
|
C++ | UTF-8 | 998 | 2.53125 | 3 | [] | no_license | #ifndef BULLET_H_
#define BULLET_H_
#include <Entity.h>
#include <Weapon.h>
#include <QVector2D>
#include <CommonGlobal.h>
//Наследуется от MovingEntity (координаты точки + направление) и от QGraphicsRectItem (прямоугольник)
class KW_COMMON_EXPORT Bullet: public MovingEntity, public QGraphicsRectItem
{
public:
Bullet (int, const QPointF, QPointF, quint16, Weapon::Type);
virtual
//отрисовывает пулю
void paint (
QPainter * painter,
const QStyleOptionGraphicsItem * option,
QWidget * widget = 0
);
//определяет, попало или нет
bool isTargetReach ();
Weapon getBulletWeapon() const;
private:
Bullet ();
Bullet (const Bullet& rhs);
Bullet& operator= (const Bullet& rhs);
Weapon weapon;
bool reached; //temporary flag, this flag needs until bullets don't removed
};
#endif /* BULLET_H_ */
|
Java | UTF-8 | 2,531 | 2.109375 | 2 | [] | no_license | package dsc.echo2app;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import nextapp.echo2.app.ApplicationInstance;
import nextapp.echo2.webcontainer.WebContainerServlet;
import nextapp.echo2.webrender.ServiceRegistry;
import nextapp.echo2.webrender.WebRenderServlet;
import org.apache.log4j.xml.DOMConfigurator;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.web.context.support.WebApplicationContextUtils;
/**
* EchoServer implementation.
*/
public class Echo2AppServlet extends WebContainerServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public static final String SPRING_CONTEXT = "ctx";
/**
* Logger for this class
*/
// private static final Log logger = LogFactory.getLog(Echo2AppServlet.class);
//
// private String fApplicationName;
private ApplicationContext fSpringContext;
public Echo2AppServlet() {
super();
ServiceRegistry serviceRegistry = WebRenderServlet.getServiceRegistry();
serviceRegistry.add(ReportService.INSTANCE);
}
/**
* Returns the ApplicationInstance object defined within the Spring context.
*/
public ApplicationInstance newApplicationInstance() {
/*
* Configure Log4J library and periodically monitor log4j.xml for any
* update.
*/
// fApplicationName = "app";
initApplicationContextIfNeeded();
ApplicationInstance app = new Application();
app.setContextProperty(SPRING_CONTEXT, fSpringContext);
Resource res = fSpringContext.getResource("classpath:log4j.xml");
try {
DOMConfigurator.configureAndWatch(res.getFile().getAbsolutePath(), 10000);
} catch (IOException e) {
System.err.println("can not found your log configuration file [log4j.xml] in classpath");
}
assert app != null : "spring context init fail!";
return (ApplicationInstance) app;
}
/**
* Initializes the Spring application context.
*/
private void initApplicationContextIfNeeded() {
if (fSpringContext == null) {
fSpringContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
}
}
@Override
protected void process(HttpServletRequest arg0, HttpServletResponse arg1) throws IOException, ServletException {
String enc = arg0.getCharacterEncoding();
if (enc == null) {
enc = "UTF-8";
arg0.setCharacterEncoding(enc);
}
super.process(arg0, arg1);
}
}
|
JavaScript | UTF-8 | 2,893 | 2.609375 | 3 | [] | no_license | //небольшие ф-ции которые встраиваются и работают с тем что мы dispatchнули до того как вызовется оригинальный редуксовый dispatch
//Задача middleware привести в понятный для redux формат данные которые мы dispatchнули до самого rewdux
import * as types from '../actions/types';
import {selectStore,insertStore,deleteStore,saveStore,getTrack,search} from "../api/data";
const middleware = store => next => action =>{
console.log("middleware action.type:",action.type);
if(action.type !== types.LOAD &&
action.type !== types.INSERT &&
action.type !== types.DELETE &&
action.type !== types.SAVE &&
action.type !== types.GET_TRACKS &&
action.type !== types.SEARCH_LOAD){
return next(action);
}
if(action.type == types.DELETE){
deleteStore(action.payload);// удалим запись
// обновим store
store.dispatch({
type:types.SELECT,
payload:selectStore()
});
}
else if(action.type == types.LOAD){
// вызов действия с типом SELECT
store.dispatch({
type:types.SELECT,
payload:selectStore()
});
}
else if(action.type == types.INSERT){
insertStore(action.payload);// добавим запись
// обновим store
store.dispatch({
type:types.SELECT,
payload:selectStore()
});
}else if(action.type == types.SAVE){
saveStore(action.id,action.payload);// обновим запись
// обновим store
store.dispatch({
type:types.SELECT,
payload:selectStore()
});
store.dispatch({
type:types.SEARCH,
payload:[]
});
}
else if(action.type == types.GET_TRACKS){
// обновим store
store.dispatch({
type:types.SELECT_TRACKS,
payload:getTrack()
});
} else if(action.type == types.SEARCH_LOAD){
if(!action.payload){
store.dispatch({
type:types.SEARCH,
payload:[]
});
}else{
store.dispatch({
type:types.SEARCH,
payload:search(action.payload)
});
}
}
/* const [startAction,successAction,failureAction] = action.actions;
store.dispatch({
type:startAction
});
action.promise.then(
(data)=>store.dispatch({
type:successAction,
payload:data
}),
(error)=>store.dispatch({
type:failureAction,
payload:error})
);
*/
};
export default middleware; |
Python | UTF-8 | 2,272 | 2.734375 | 3 | [] | no_license | from web3 import Web3, HTTPProvider
import json
import requests
def getWeb3():
'''
Return web3 object
'''
return Web3(HTTPProvider('https://mainnet.infura.io/'))
def loadContracts():
'''
Loads contracts from MEW git, falls back to local instance if fails
'''
ETH_TOKEN_URI = '''
https://raw.githubusercontent.com/kvhnuke/etherwallet/
mercury/app/scripts/tokens/ethTokens.json
'''
try:
contracts = requests.get(ETH_TOKEN_URI).json()
except:
file = open('ethTokens.json', 'r')
contracts = json.loads(file.read())
return contracts
def decompressToken(token):
'''
Searches local database using known token data
'''
response = {}
response['address'] = None
response['symbol'] = None
response['decimal'] = None
# check if token is an address
if len(token) == 42 and token[:2] == '0x':
# check to see if we know the address
for contract in loadContracts():
if contract['address'] == token:
response['address'] = contract['address']
response['symbol'] = contract['symbol']
response['decimal'] = contract['decimal']
return response
# lookup failed, going in raw
response['address'] = token
else:
# Get contract params
for contract in loadContracts():
if contract['symbol'].upper() == token.upper():
response['address'] = contract['address']
response['symbol'] = contract['symbol']
response['decimal'] = contract['decimal']
return response
return response
def makeABICall(address):
web3 = getWeb3()
GENERIC_ABI = '''
[{"constant":true,"inputs":[{"name":"_owner","type":"address"}],
"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],
"payable":false,"stateMutability":"view","type":"function"}]
'''
abi = json.loads(GENERIC_ABI)
token = web3.eth.contract(address, abi=abi)
return token
def getBalance(decimal, token, wallet):
try:
divisor = 10 ** decimal
return token.call().balanceOf(wallet) / divisor
except:
return token.call().balanceOf(wallet)
|
Markdown | UTF-8 | 3,112 | 2.703125 | 3 | [
"CC-BY-4.0",
"MIT"
] | permissive | ---
description: "Learn more about: Threading objects and features"
title: "Threading objects and features"
ms.date: "10/01/2018"
helpviewer_keywords:
- "threading [.NET], features"
- "managed threading"
ms.assetid: 239b2e8d-581b-4ca3-992b-0e8525b9321c
---
# Threading objects and features
Along with the <xref:System.Threading.Thread?displayProperty=nameWithType> class, .NET provides a number of classes that help you develop multithreaded applications. The following articles provide overview of those classes:
|Title|Description|
|-----------|-----------------|
|[The managed thread pool](the-managed-thread-pool.md)|Describes the <xref:System.Threading.ThreadPool?displayProperty=nameWithType> class, which provides a pool of worker threads that are managed by .NET.|
|[Timers](timers.md)|Describes .NET timers that can be used in a multithreaded environment.|
|[Overview of synchronization primitives](overview-of-synchronization-primitives.md)|Describes types that can be used to synchronize access to a shared resource or control thread interaction.|
|[EventWaitHandle](eventwaithandle.md)|Describes the <xref:System.Threading.EventWaitHandle?displayProperty=nameWithType> class, which represents a thread synchronization event.|
|[CountdownEvent](countdownevent.md)|Describes the <xref:System.Threading.CountdownEvent?displayProperty=nameWithType> class, which represents a thread synchronization event that becomes set when its count is zero.|
|[Mutexes](mutexes.md)|Describes the <xref:System.Threading.Mutex?displayProperty=nameWithType> class, which grants exclusive access to a shared resource.|
|[Semaphore and SemaphoreSlim](semaphore-and-semaphoreslim.md)|Describes the <xref:System.Threading.Semaphore?displayProperty=nameWithType> class, which limits number of threads that can access a shared resource or a pool of resources concurrently.|
|[Barrier](barrier.md)|Describes the <xref:System.Threading.Barrier?displayProperty=nameWithType> class, which implements the barrier pattern for coordination of threads in phased operations.|
|[SpinLock](spinlock.md)|Describes the <xref:System.Threading.SpinLock?displayProperty=nameWithType> structure, which is a lightweight alternative to the <xref:System.Threading.Monitor?displayProperty=nameWithType> class for certain low-level locking scenarios.|
|[SpinWait](spinwait.md)|Describes the <xref:System.Threading.SpinWait?displayProperty=nameWithType> structure, which provides support for spin-based waiting.|
## See also
- <xref:System.Threading.Monitor?displayProperty=nameWithType>
- <xref:System.Threading.WaitHandle?displayProperty=nameWithType>
- <xref:System.ComponentModel.BackgroundWorker?displayProperty=nameWithType>
- <xref:System.Threading.Tasks.Parallel?displayProperty=nameWithType>
- <xref:System.Threading.Tasks.Task?displayProperty=nameWithType>
- [Using threads and threading](using-threads-and-threading.md)
- [Asynchronous File I/O](../io/asynchronous-file-i-o.md)
- [Parallel Programming](../parallel-programming/index.md)
- [Task Parallel Library (TPL)](../parallel-programming/task-parallel-library-tpl.md)
|
Java | UTF-8 | 1,463 | 3.375 | 3 | [] | no_license | package OopPrinciples;
public class Student {
private String StudentsFirstName;
private String StudentsLastName;
private int StudentsAge;
private String StudentsDateOfBirth;
private String StudentsFaculty;
private String StudentsPassingYear;
public Student(String StudentsFirstName, String StudentsLastName, int StudentsAge, String StudentsDateOfBirth, String StudentsFaculty, String StudentsPassingYear) {
this.StudentsFirstName = StudentsFirstName;
this.StudentsLastName = StudentsLastName;
this.StudentsAge = StudentsAge;
this.StudentsDateOfBirth = StudentsDateOfBirth;
this.StudentsFaculty =StudentsFaculty;
this.StudentsPassingYear=StudentsPassingYear;
}
@Override
public String toString() {
return "PersonStudent.Student: " + StudentsFirstName + " " + StudentsLastName + " " + StudentsAge +" "+ StudentsDateOfBirth +" "
+ StudentsFaculty +" "+ StudentsPassingYear; }
public String getFirstName() {
return StudentsFirstName;
}
public String getLastName() {
return StudentsLastName;
}
public int getAge() {
return StudentsAge;
}
public String getDateOfBirth() {
return StudentsDateOfBirth;
}
public String getStudentsFaculty() {
return StudentsFaculty;
}
public String getStudentsPassingYear() {
return StudentsPassingYear;
}
}
|
Ruby | UTF-8 | 483 | 2.6875 | 3 | [] | no_license | module CheckinHelper
def success_names(names)
if names.empty?
''
elsif names.length == 1
"#{names.first} was successfully checked in. "
else
"#{names.collect {|n| n}.to_sentence} were successfully checked in."
end
end
def fail_names(names)
if names.empty?
''
elsif names.length == 1
"#{names.first} wasn't checked in. "
else
"#{names.collect {|n| n}.to_sentence} were not checked in. "
end
end
end
|
Python | UTF-8 | 2,256 | 3.15625 | 3 | [
"MIT"
] | permissive | """Houses the Pegasus parser class
Unicode characters not being read correctly?
Check out http://stackoverflow.com/a/844443/510036
"""
from __future__ import unicode_literals
import inspect
from itertools import chain as iterchain
from pegasus.rules import _build_rule, ParseError, Lazy
class EmptyRuleException(Exception):
pass
class NoDefaultRuleException(Exception):
pass
class NotARuleException(Exception):
pass
def rule(*rules):
stack = inspect.stack()[1]
caller_module = stack[3]
caller_file = stack[1]
"""Marks a method as a rule"""
def wrapper(fn):
_rules = rules
if len(_rules) == 0:
raise EmptyRuleException('cannot supply an empty rule')
Lazy._LOOKUPS[(caller_file, caller_module, fn.__name__)] = fn
setattr(fn, '_rule', rules)
return fn
return wrapper
class Parser(object):
"""The Pegasus Parser base class
Extend this class and write visitor methods annotated with the @rule decorator,
create an instance of the parser and call .parse('some str') on it.
"""
def parse(self, rule, iterable, match=True):
"""Parses and visits an iterable"""
if not hasattr(rule, '_rule') or not inspect.ismethod(rule):
raise NotARuleException('the specified `rule\' value is not actually a rule: %r' % (rule,))
prule = _build_rule(rule)
itr = iterchain.from_iterable(iterable)
c = None
grule = None
for c in itr:
reconsume = True
while reconsume:
if grule is None:
grule = prule(lambda: c, self)
result, reconsume = next(grule)
if result is not None:
if match:
raise ParseError(got='result (rule returned a result without fully exhausting input)')
else:
return result[0]
if grule:
c = None
reconsume = True
result = None
while reconsume:
result, reconsume = next(grule)
if result is not None and not match:
return result[0]
return result[0]
return None
|
Python | UTF-8 | 725 | 3.328125 | 3 | [] | no_license | import sys
def find_row(arr, x):
for i, row in enumerate(arr):
if x in row:
return i
return -1
T = int(sys.stdin.readline())
for i in range(T):
r1 = int(sys.stdin.readline()) - 1
arr1 = [map(int, sys.stdin.readline().split()) for j in range(4)]
r2 = int(sys.stdin.readline()) - 1
arr2 = [map(int, sys.stdin.readline().split()) for j in range(4)]
res = []
for j in range(1, 17):
if find_row(arr1, j) == r1 and find_row(arr2, j) == r2:
res.append(j)
if len(res) == 1:
print 'Case #%d: %d' % (i+1, res[0])
elif len(res) == 0:
print 'Case #%d: Volunteer cheated!' % (i+1)
else:
print 'Case #%d: Bad magician!' % (i+1)
|
JavaScript | UTF-8 | 3,778 | 2.75 | 3 | [] | no_license | const browserUtils = require('../../src/browserUtils')
document.body.innerHTML = `
<div class="app">
<nav class="app__nav">
<a href="" class="app__link"></a>
<a href="" class="app__link"></a>
</nav>
<main class="app__cont">
<a href="" class="app__link"></a>
<a href="" class="app__link"></a>
</main>
</div>
`
describe('$', () => {
test('$(".app__father") should equal []', () => {
expect(browserUtils.$('.app__father')).toEqual([])
})
test('$("a") should equal Array.from(document.querySelectorAll("a"))', () => {
expect(browserUtils.$('a')).toEqual(
Array.from(document.querySelectorAll('a'))
)
})
test('$("a",document.querySelector(\'.app__nav\')) should equal Array.from(document.querySelector(\'.app__nav\').querySelectorAll("a"))', () => {
expect(browserUtils.$('a', document.querySelector('.app__nav'))).toEqual(
Array.from(document.querySelector('.app__nav').querySelectorAll('a'))
)
})
})
describe('closest', () => {
let lastAppLink = Array.from(document.querySelectorAll('.app__link')).pop()
let appCont = document.querySelectorAll('.app__cont')[0]
let app = document.querySelectorAll('.app')[0]
test('(lastAppLink,\'.app\',appCont) should return null', () => {
let result = browserUtils.closest(lastAppLink, '.app', appCont)
expect(result).toBe(null)
})
test('(lastAppLink,\'.app\') should return app', () => {
let result = browserUtils.closest(lastAppLink, '.app')
expect(result).toBe(app)
})
})
describe('getElOffsetToEvent', () => {
test('({},document.body)', () => {
let result = browserUtils.getElOffsetToEvent(
{ clientX: 50, clientY: 50 },
document.body
)
expect(typeof result.left).toBe('number')
expect(typeof result.top).toBe('number')
expect(typeof result.right).toBe('number')
expect(typeof result.bottom).toBe('number')
})
})
describe('isElement', () => {
test('(document) should return true', () => {
expect(browserUtils.isElement(document)).toBe(true)
})
test('(document.documentElement) should return true', () => {
expect(browserUtils.isElement(document.documentElement)).toBe(true)
})
test('(document.createElement(\'svg\')) should return true', () => {
expect(browserUtils.isElement(document.createElement('svg'))).toBe(true)
})
test('(document.createDocumentFragment()) should return false', () => {
expect(browserUtils.isElement(document.createDocumentFragment())).toBe(
false
)
})
test('([]) should return false', () => {
expect(browserUtils.isElement([])).toBe(false)
})
test('("") should return false', () => {
expect(browserUtils.isElement('')).toBe(false)
})
test('(null) should return false', () => {
expect(browserUtils.isElement(null)).toBe(false)
})
})
describe('htmlEncodeByDom', () => {
test('(<script></script>) should return <script></script>', () => {
let result = browserUtils.htmlEncodeByDom('<script></script>')
expect(result).toBe('<script></script>')
})
test('(<script>) should return <script>', () => {
let result = browserUtils.htmlEncodeByDom('<script>')
expect(result).toBe('<script>')
})
})
describe('htmlDecodeByDom', () => {
test('(<script></script>) should return <script></script>', () => {
let result = browserUtils.htmlDecodeByDom('<script></script>')
expect(result).toBe('<script></script>')
})
test('(<script>) should return <script>', () => {
let result = browserUtils.htmlDecodeByDom('<script>')
expect(result).toBe('<script>')
})
})
describe('isLandscape', () => {
test('() should return true', () => {
let result = browserUtils.isLandscape()
expect(result).toBe(true)
})
})
|
C | UTF-8 | 2,959 | 2.78125 | 3 | [] | no_license | //
// main.c
// gps
//
// Created by 20161104586 on 17/6/26.
// Copyright © 2017年 马德辉. All rights reserved.
//
#include <stdio.h>
#include <string.h>
int main()
{
char num1[63];
char num2[70];
char date[7];
char time[7];
char eastlongitude[10];
char northlat[9];
char high[5];
int i,math,math1,math2;
FILE *fp1,*fp2;
fp1=fopen("//Users//a20161104586//Desktop//gps//gps//GPS170510.log","r");
fp2=fopen("//Users//a20161104586//Desktop//gps//gps.csv","w+");
if(fp1==NULL)
printf("打开文件错误");
else
fprintf(fp2,"日期 ,北京时间 , 北纬 ,东经 ,海拔\n");
while(!feof(fp1))
{
{
{
fscanf(fp1,"%s%s",num1,num2);
printf("%s\n%s\n",num1,num2);
for(i=0; i<2; i++)
date[i]=num1[i+55];
date[2]='\0';
fprintf(fp2,"20%s年",date);
for(i=0; i<2; i++)
date[i]=num1[i+51];
date[2]='\0';
fprintf(fp2,"%s月",date);
for(i=0; i<2; i++)
date[i]=num1[i+53];
date[2]='\0';
fprintf(fp2,"%s日,",date);
}
{
for(i=0; i<2; i++)
time[i]=num1[i+7];
math1=10*(time[0]-'0');
math2=1*(time[1]-'0');
math=math1+math2+8;
fprintf(fp2,"%d小时",math);
for(i=0; i<2; i++)
time[i]=num1[i+9];
math1=10*(time[0]-'0');
math2=1*(time[1]-'0');
math=math1+math2;
time[2]='\0';
fprintf(fp2,"%d分",math);
for(i=0; i<2;i++)
time[i]=num1[i+11];
math1=10*(time[0]-'0');
math2=1*(time[1]-'0');
math=math1+math2;
time[2]='\0';
fprintf(fp2,"%d秒, ",math);
}
for(i=0; i<2; i++)
northlat[i]=num1[i+16];
northlat[2]='\0';
fprintf(fp2,"%s.",northlat);
for(i=0; i<6; i++)
northlat[i]=num1[i+18];
northlat[6]='\0';
fprintf(fp2,"%s, ",northlat);
for(i=0; i<3; i++)
eastlongitude[i]=num1[i+27];
eastlongitude[3]='\0';
fprintf(fp2,"%s.",eastlongitude);
for(i=0; i<9; i++)
eastlongitude[i]=num1[i+30];
eastlongitude[6]='\0';
fprintf(fp2,"%s, ",eastlongitude);
for(i=0; i<4; i++)
high[i]=num1[i+43];
high[4]='\0';
fprintf(fp2,"%sm\n",high);
}
}
fclose(fp1);
fclose(fp2);
return 0;
}
|
Java | UTF-8 | 495 | 1.734375 | 2 | [] | no_license | package com.yolo.dao.chat;
import javax.annotation.Resource;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import com.yolo.dao.chat.inf.BookIncomeDaoInf;
@Repository
public class BookIncomeDao implements BookIncomeDaoInf{
@Resource(name="sqlSessionTemplate")
private SqlSessionTemplate sessionTemplate;
Logger logger = LoggerFactory.getLogger(getClass());
}
|
PHP | UTF-8 | 4,049 | 2.859375 | 3 | [] | no_license | <?php
use model\StructureProfile\infrastructure\GeoJsonStatementBuilder;
use model\StructureProfile\application\Profile;
use model\StructureProfile\application\DTO\GeoJsonSelection;
use model\StructureProfile\application\DTO\SelectionType;
use model\StructureProfile\application\exception\InvalidSelectionTypeException;
use PHPUnit\Framework\TestCase;
class GeoJsonStatementBuilderTest extends TestCase {
private static \DB $db;
public static function setUpBeforeClass() : void {
global $framework;
$config = $framework->get('config');
self::$db = new \DB(
$config->get('db_structure_type'),
$config->get('db_structure_hostname'),
$config->get('db_structure_username'),
$config->get('db_structure_password'),
$config->get('db_structure_database'),
$config->get('db_structure_port')
);
self::$db->command("DELETE FROM feature");
}
public function test_If_StatementBuilder_Returns_Sql_Statement_Correctly() {
self::$db->command("CREATE TABLE IF NOT EXISTS feature (
id SERIAL PRIMARY KEY,
cad_object_id INT NULL,
type VARCHAR(32) NOT NULL,
geometry GEOMETRY NOT NULL
)");
self::$db->command( "INSERT INTO feature (id, cad_object_id, type, geometry) VALUES (1, 1, 'kale', geometry(POINT(2,2)) ) ");
$reflection = new ReflectionClass(GeoJsonStatementBuilder::class);
$statement_builder = $reflection->newInstanceWithoutConstructor();
$geojson = array( // <- geojson in php format
'type' => 'Point',
'features' => array(
'type' => 'Feature',
"geometry" => array(
'type' => 'Point',
'coordinates' => array(
[125.6, 10.1],
[125.6, 10.2]
)
)
)
);
$geo_json_selection = new GeoJsonSelection(1, $geojson, null);
$selection = array($geo_json_selection, SelectionType::Point() );
$field = 'field';
$second_ref = new ReflectionClass(Profile::class);
$profile = $second_ref->newInstanceWithoutConstructor();
$sql_statement = $statement_builder->buildStatement($geo_json_selection, $field, $profile);
$this->assertEquals($geojson['type'], 'Point');
$this->assertEquals($geojson['features']['geometry']['coordinates'][0][0], 125.6);
$this->assertEquals($geojson['features']['geometry']['coordinates'][0][1], 10.1);
}
public function test_If_Exception_Is_Thrown_When_Invalid_Selection_Type_Is_Provided() {
$this->expectException(InvalidSelectionTypeException::class);
$reflection = new ReflectionClass(GeoJsonStatementBuilder::class);
$statement_builder = $reflection->newInstanceWithoutConstructor();
$geojson = array(
'type' => 'Point',
'features' => array(
'type' => 'Feature',
"geometry" => array(
'type' => 'Point',
'coordinates' => array(
[125.6, 10.1],
[125.6, 10.2]
)
)
)
);
$arr = array(); // array without selection type must throw an exception.
$geo_json_selection = new GeoJsonSelection(1, $arr , null);
$selection = array($geo_json_selection, SelectionType::Point() );
$field = 'field';
$second_ref = new ReflectionClass(Profile::class);
$profile = $second_ref->newInstanceWithoutConstructor();
$sql_statement = $statement_builder->buildStatement($geo_json_selection, $field, $profile);
$this->assertEquals($geojson['type'], 'Point');
$this->assertEquals($geojson['features']['geometry']['coordinates'][0][0], 125.6);
$this->assertEquals($geojson['features']['geometry']['coordinates'][0][1], 10.1);
}
}
?> |
Shell | UTF-8 | 816 | 4.03125 | 4 | [
"BSD-3-Clause"
] | permissive | #!/bin/bash
if [ -z "$1" ]; then
echo "Error! You have to provide a known architecture name"
return 1
else
TARGET_NAME=$1
echo "TARGET_ARCHITECTURE set to '$TARGET_NAME'"
fi
export TARGET_ARCHITECTURE=$TARGET_NAME
#Check target architecture toolchain script
THIS_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )"
TOOLCHAIN_SCRIPT=$THIS_DIR/toolchains/$TARGET_ARCHITECTURE.sh
if [ ! -e "$TOOLCHAIN_SCRIPT" ]; then
echo "ERROR: File $TOOLCHAIN_SCRIPT does not exist!!!."
return 1
else
echo "Environment sourced correctly!"
echo "These paths will be used as target for the cross-compilation"
echo "Path to sysroot: $THIS_DIR/sysroots/$TARGET_ARCHITECTURE"
echo "Path to target specific toolchain: $THIS_DIR/toolchains/$TARGET_ARCHITECTURE.sh"
return 0
fi |
Python | UTF-8 | 1,450 | 3.1875 | 3 | [] | no_license | import logging
import random
from minichess.games.abstract.board import AbstractBoardStatus
from minichess.games.abstract.piece import PieceColor
class Simulator:
def __init__(self, env_class, board, active_color, simulation_iterations=75):
self.env = env_class()
self.env.board = board
self.active_color = active_color
self.simulation_iterations = simulation_iterations
def rollout_to_completion(self):
'''
Simulates this game with random moves to completion, or the simulation iteration count, whichever comes first.
Returns
-------
terminal status, reward
'''
sim_iter = 0
reward = 0
done = False
while not done and sim_iter < self.simulation_iterations:
actions = self.env.legal_actions()
if len(actions) == 0:
done = True
break
action = random.choice(actions)
_, reward, done, _ = self.env.step(action)
sim_iter += 1
if sim_iter >= self.simulation_iterations:
logging.debug('Cut simulation at iteration {}. Forced Result: {}.'.format(sim_iter, AbstractBoardStatus.DRAW))
return AbstractBoardStatus.DRAW, reward
logging.debug('Finished simulation at iteration {}. Result: {}.'.format(sim_iter, self.env.board.status))
return self.env.board.status, reward
|
Go | UTF-8 | 970 | 2.75 | 3 | [] | no_license | package kit
import (
"fmt"
"github.com/stretchr/testify/assert"
"testing"
)
func TestNewTrees(t *testing.T) {
//tc := []int{1, 2, 3,4,5,6,7, 8, Null,9,9,Null,Null,10}
//tc := []int{1,Null,2,Null,3}
tc := []int{1, 2, 3,4,5, Null,6}
nodes := NewTrees(tc)
//fmt.Println(nodes.InOrder(), nodes.depth)
fmt.Println(nodes.String(), nodes.PostOrder())
}
func Test_toIntsPreOrderIterate(t *testing.T) {
tc := []int{1, 2, 3,4,5, Null,6}
ans := []int{1,2,4,5,3,6}
trees := NewTrees(tc)
ast := assert.New(t)
ast.Equal(ans, preOrderIterate(trees.Root))
}
func Test_toIntsInOrderIterate(t *testing.T) {
tc := []int{1, 2, 3,4,5, Null,6}
ans := []int{4,2,5,1,3,6}
trees := NewTrees(tc)
ast := assert.New(t)
ast.Equal(ans, inOrderIterate(trees.Root))
}
func Test_postOrderIterate(t *testing.T) {
tc := []int{1, 2, 3,4,5, Null,6}
ans := []int{4,5,2,6,3,1}
trees := NewTrees(tc)
ast := assert.New(t)
ast.Equal(ans, postOrderIterate(trees.Root))
} |
Python | UTF-8 | 3,156 | 3.453125 | 3 | [] | no_license | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright © 1999, 2000, 2001, 2002 Progiciels Bourbeau-Pinard inc.
# François Pinard <pinard@iro.umontreal.ca>, 1999.
"""\
A graph is made from a set of vertices, and a set of oriented arcs.
Each vertex should be immutable and not None. An arc is a tuple. The first
and second element of an arc are mandatory, and represent the starting
vertex and ending vertex for that arc. The optional third element of an
arc is its associate positive cost, a cost of one is implied if none given.
"""
def path(before, after, arcs):
"""\
Return the most economical path from the BEFORE vertex to the AFTER vertex,
given a set of ARCS representing possible partial paths. The path is
returned as a list of successive arcs connecting BEFORE to AFTER, or None
is there is no such path.
"""
# With each vertex, associate a best forward arc and total cost.
table = {after: (None, 0)}
changed = True
while changed:
changed = False
for arc in arcs:
entry = table.get(arc[1])
if entry is not None:
if len(arc) < 3:
cost = 1 + entry[1]
else:
cost = arc[2] + entry[1]
previous = table.get(arc[0])
if previous is None or cost < previous[1]:
table[arc[0]] = arc, cost
changed = True
# Rebuild best path.
entry = table.get(before)
if entry is None:
return None
path = []
arc = entry[0]
while arc is not None:
path.append(arc)
arc = table[arc[1]][0]
return path
def sort(vertices, arcs):
"""\
Topologically sort VERTICES, while obeying the constraints described
in ARCS. Arcs referring to non-listed vertices are ignored. Return two
lists, which together hold all original VERTICES, with none repeated.
The first list is the sorted result, the second list gives all vertices
involved into some cycle.
"""
# With each vertex, associate a predecessor count and the set of all
# follower vertices.
table = {}
for vertex in vertices:
table[vertex] = [vertex, 0, []]
for arc in arcs:
before = table.get(arc[0])
after = table.get(arc[1])
if before is not None and after is not None and after not in before[2]:
before[2].append(after)
after[1] += 1
vertices = table.values()
del table
# Accumulate sorted vertices in the SORTED list.
zeroes = []
for vertex in vertices[:]:
if vertex[1] == 0:
vertices.remove(vertex)
zeroes.append(vertex)
sorted = []
while zeroes:
new_zeroes = []
zeroes.sort()
for zero in zeroes:
sorted.append(zero[0])
for vertex in zero[2]:
vertex[1] -= 1
if vertex[1] == 0:
vertices.remove(vertex)
new_zeroes.append(vertex)
zeroes = new_zeroes
# Unprocessed vertices participate into various cycles.
cycles = []
for vertex in vertices:
cycles.append(vertex[0])
del vertex[2]
return sorted, cycles
|
PHP | UTF-8 | 6,260 | 3.09375 | 3 | [] | no_license | <?php
/**
* Miscellaneous utility functions used by Sugar.
*
* Provides several utility functions used by the Sugar codebase.
*
* PHP version 5
*
* LICENSE:
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @category Template
* @package Sugar
* @author Sean Middleditch <sean@mojodo.com>
* @copyright 2008-2009 Mojodo, Inc. and contributors
* @license http://opensource.org/licenses/mit-license.php MIT
* @version SVN: $Id$
* @link http://php-sugar.net
*/
/**
* Returns an argument from a function parameter list, supporting both
* position and named parameters and default values.
*
* @param array $params Function parameter list.
* @param string $name Parameter name.
* @param mixed $default Default value if parameter is not specified.
*
* @return mixed Value of parameter if given, or the default value otherwise.
*/
function Sugar_Util_GetArg($params, $name, $default = null)
{
return isset($params[$name]) ? $params[$name] : $default;
}
/**
* Checks if an array is a "vector," or an array with only integral
* indexes starting at zero and incrementally increasing. Used only
* for nice exporting to JavaScript.
*
* Only really used for {@link Sugar_Util_Json}.
*
* @param array $array Array to check.
*
* @return bool True if array is a vector.
*/
function Sugar_Util_IsVector($array)
{
if (!is_array($array)) {
return false;
}
$next = 0;
foreach ($array as $k=>$v) {
if ($k !== $next) {
return false;
}
++$next;
}
return true;
}
/**
* Performs string-escaping for JavaScript values.
*
* This is the equivalent of running addslashes() and then replacing
* control characters with their escaped equivalents.
*
* @param mixed $string String to escape.
*
* @return string Formatted result.
*/
function Sugar_Util_EscapeJavascript($string) {
$escaped = addslashes($string);
$escaped = str_replace(array("\n", "\r", "\r\n"), '\\n', $escaped);
return $escaped;
}
/**
* Formats a PHP value in JavaScript format.
*
* We can probably juse use json_encode() instead of this, except
* json_encode() is PHP 5.2 only.
*
* @param mixed $value Value to format.
*
* @return string Formatted result.
*/
function Sugar_Util_Json($value)
{
// use json_encode, if defined
if (function_exists('json_encode')) {
return json_encode($value);
}
switch (gettype($value)) {
case 'integer':
case 'float':
return $value;
case 'array':
if (Sugar_Util_IsVector($value)) {
$escaped = array_map('Sugar_Util_Json', $value);
return '['.implode(',', $escaped).']';
}
$result = '{';
$first = true;
foreach ($value as $k=>$v) {
if (!$first) {
$result .= ',';
} else {
$first = false;
}
$result .= Sugar_Util_Json($k).':'.Sugar_Util_Json($v);
}
$result .= '}';
return $result;
case 'object':
$result = '{\'phpType\':'.Sugar_Util_Json(get_class($value));
foreach (get_object_vars($value) as $k=>$v) {
$result .= ',' . Sugar_Util_Json($k).':'.Sugar_Util_Json($v);
}
$result .= '}';
return $result;
case 'null':
return 'null';
default:
$escaped = Sugar_Util_EscapeJavascript($value);
return '"'.$escaped.'"';
}
}
/**
* Convert a value into a timestamp. This is essentially strtotime(),
* except that if an integer timestamp is passed in it is returned
* verbatim, and if the value cannot be parsed, it returns the current
* timestamp.
*
* @param mixed $value Time value to parse.
*
* @return int Timestamp.
*/
function Sugar_Util_ValueToTime($value)
{
if (is_int($value)) {
// raw int? it's a timestamp
return $value;
} elseif (is_string($value)) {
// otherwise, convert it with strtotime
return strtotime($value);
} else {
// something... use current time
return time();
}
}
/**
* Attempt to locate a file in one or more source directories.
*
* @param mixed $haystack The directory/directories to search in.
* @param string $needle The file being searched for.
* @param string $backup Second haystack (optional).
*
* @return mixed The full path to the file if found, false otherwise.
*/
function Sugar_Util_SearchForFile($haystack, $needle, $backup = null)
{
// search multiple directories if templateDir is an array,
// otherwise only search the given dir
if (is_array($haystack)) {
foreach ($haystack as $dir) {
$path = $dir.'/'.$needle;
if (is_file($path) && is_readable($path)) {
return $path;
}
}
} else {
$path = $haystack.'/'.$needle;
if (is_file($path) && is_readable($path)) {
return $path;
}
}
// try the backup directory
if (!is_null($backup)) {
$path = $backup.'/'.$needle;
if (is_file($path) && is_readable($path)) {
return $path;
}
}
// no matches found
return false;
}
// vim: set expandtab shiftwidth=4 tabstop=4 :
?>
|
C++ | UTF-8 | 1,190 | 3.203125 | 3 | [] | no_license | /*le2*/
#ifndef NAME_H
#define NAME_H
class Name {
public:
Name(const std::string& fname) : fname_{fname} {}
Name(const Name& other) : fname_{other.fname_} {} //kop.konst
Name(Name&& ) { swap(other); } //move.konst
Name& operator=(const Name& rhs) & {
Name{rhs}.swap(*this);
return *this;
}
Name& operator=(const std::string& rhs) & {
Name{rhs}.swap(*this);
return *this;
}
Name& operator=(Name&& rhs) & {
swap(rhs);
return *this;
}
virtual void print(ostream& os);
void swap(Name& other) noexcep;
private:
std::string fname_:
};
class Double_Name : public Name {
public:
Double_Name(const strig& fname, const string& sname) : Name(fname), sname_{sname} {};
Double_Name(const Double_Name& other) : Name(other), sname_{other.sname_} {};
Double_Name(Double_Name&& other) { swap(other); }
Double_Name& operator=(const Double_Name& rhs) & {
Double_Name{rhs}.swap(*this);
return *this;
}
Double_Name& operator=(Double_Name&& rhs) & {
swap(rhs);
return *this;
}
virtual void print(ostream& os) override;
void swap(Double_Name& other) noexcept;
private:
std::string sname_;
}
#endif // NAME_H
|
Ruby | UTF-8 | 661 | 3.015625 | 3 | [
"MIT"
] | permissive | class Hero
attr_accessor :name
attr_writer :biography, :appearance, :connections
@@all = []
def initialize(name, biography, appearance, connections)
self.name = name
self.biography = biography
self.appearance = appearance
self.connections = connections
self.class.all << self
end
def self.all
@@all
end
def biography
@biography.collect {|key,value| "#{key}: #{value}"}
end
def appearance
@appearance.collect {|key,value| "#{key}: #{value}"}
end
def connections
@connections.collect {|key,value| "#{key}: #{value}"}
end
end
|
C++ | UTF-8 | 1,173 | 2.625 | 3 | [
"BSD-2-Clause",
"Apache-2.0"
] | permissive | /*
Part of BridgeData.
Copyright (C) 2016-17 by Soren Hein.
See LICENSE and README.
*/
#ifndef BRIDGE_GROUP_H
#define BRIDGE_GROUP_H
#include <string>
#include <list>
#include "Segment.h"
using namespace std;
class Group
{
private:
string nameVal;
Format formatVal;
list<Segment> segments;
bool flagCOCO;
public:
Group();
~Group();
void reset();
list<Segment>::const_iterator begin() const { return segments.begin(); }
list<Segment>::const_iterator end() const { return segments.end(); }
list<Segment>::iterator mbegin() { return segments.begin(); }
list<Segment>::iterator mend() { return segments.end(); }
void setName(const string& fname);
string name() const;
void setFormat(const Format format);
Format format() const;
Segment * make();
void setCOCO(const Format format = BRIDGE_FORMAT_SIZE);
bool isCOCO() const;
unsigned size() const;
unsigned count() const;
unsigned countBoards() const;
bool operator == (const Group& group2) const;
bool operator != (const Group& group2) const;
bool operator <= (const Group& group2) const;
};
#endif
|
C++ | UTF-8 | 393 | 2.65625 | 3 | [] | no_license | #include <cstdio>
#define ll long long
using namespace std;
inline void fastRead(ll *a)
{
register char c=0;
while (c<33)
c=getchar_unlocked();
*a=0;
while (c>33)
{
*a=*a*10+c-'0';
c=getchar_unlocked();
}
}
int main()
{
ll n, k;
fastRead(&n);
fastRead(&k);
ll count = 0;
while(n--){
ll a;
fastRead(&a);
if(a%k == 0)
count++;
}
printf("%lld", count);
return 0;
}
|
Markdown | UTF-8 | 1,531 | 3.65625 | 4 | [] | no_license | # 1.6 存储设备形成层次结构
在处理器和一个较大较慢的设备(例如主存)之间插**入**一个更小更快的存储设备(例如高速缓存)的想法已经成为一个普遍的观念。实际上,每个计算机系统中的存储设备都被组织成了一个**存储器层次结构**,如图 1-9 所示。在这个层次结构中,从上至下,设备的访问速度越来越慢、容量越来越大,并且每字节的造价也越来越便宜。寄存器文件在层次结构中位于最顶部,也就是第 0 级或记为 L0。这里我们展示的是三层高速缓存 L1 到 L3,占据存储器层次结构的第 1 层到第 3 层。主存在第 4 层,以此类推。

存储器层次结构的主要思想是上一层的存储器作为低一层存储器的高速缓存。因此,寄存器文件就是 L1 的高速缓存,L1 是 L2 的高速缓存,L2 是 L3 的高速缓存,L3 是主存的高速缓存,而主存又是磁盘的高速缓存。在某些具有分布式文件系统的网络系统中,本地磁盘就是存储在其他系统中磁盘上的数据的高速缓存。 正如可以运用不同的高速缓存的知识来提高程序性能一样,程序员同样可以利用对整个存储器层次结构的理解来提高程序性能。第 6 章将更详细地讨论这个问题。
|
Markdown | UTF-8 | 702 | 2.515625 | 3 | [
"BSD-2-Clause"
] | permissive | # Configuring Widgets
The blog module comes bundled with some useful widgets. To take advantage of them, you'll need to install the
[SilverStripe widgets module](https://github.com/silverstripe/silverstripe-widgets). Widgets are totally optional -
so your blog will work just fine without having widgets installed.
You can enable the widgets by adding the following YML config:
```yaml
SilverStripe\Blog\Model\Blog:
extensions:
- SilverStripe\Widgets\Extensions\WidgetPageExtension
SilverStripe\Blog\Model\BlogPost:
extensions:
- SilverStripe\Widgets\Extensions\WidgetPageExtension
```
Once you have widgets installed you'll see the "Widgets" tab in the content section of your blog.
|
Markdown | UTF-8 | 7,748 | 2.90625 | 3 | [
"Apache-2.0"
] | permissive | [#]: subject: "How I configure Vim as my default editor on Linux"
[#]: via: "https://opensource.com/article/22/2/configure-vim-default-editor"
[#]: author: "David Both https://opensource.com/users/dboth"
[#]: collector: "lujun9972"
[#]: translator: "lkxed"
[#]: reviewer: "wxy"
[#]: publisher: "wxy"
[#]: url: "https://linux.cn/article-14475-1.html"
我如何在 Linux 上把 Vim 配置为默认编辑器
======
> Vim 是我最喜爱的编辑器。对于那些默认使用其他编辑器的程序,我对系统所做的这些改变可以使得 Vim 成为它们默认编辑器。

我使用 Linux 大概有 25 年了,在那之前我还使用了几年的 Unix。在这段时间里,我对一些日常使用的工具形成了偏好。Vim 是我使用的最重要的工具之一。
我在 90 年代初学习 Solaris 时,就开始使用 Vi 了,因为有人告诉我,它在任何系统上都能使用。从我的经验来看,确实是这样。我也试过其他编辑器,它们都能够胜任工作。但是,对于我来说,Vim 的使用效果最好。我经常使用它,以至于形成了肌肉记忆,甚至我在使用其他编辑器时也会下意识地去按 Vim 的快捷键。
另外,我只是单纯地喜欢 Vim 而已。
许多配置文件使用的名字是 Vi 而不是 Vim,你可以运行 `vi` 命令。不过,`vi` 命令其实是 `vim` 命令的一个链接。
许多 Linux 工具使用的编辑器都是在模拟或是直接调用的 [Nano][2]、[Emacs][3] 或者 Vim。其他的一些工具允许用户(比如那些有着明确偏好的用户)使用他们喜欢的编辑器。举两个对我影响最大的例子,一个是 Bash 命令行,它默认使用 Emacs;另一个是 Alpine 文本模式的邮件客户端,它默认使用 Pico。事实上,Pico 是专门为 Pine 邮件客户端编写的,而 Pine 是 Alpine 的前身。
并非所有使用外部编辑器的程序都是可配置的。有些程序只使用开发者指定的编辑器。对于那些可配置的应用程序,有不同的方法来选择你喜欢的编辑器。
### 在 Linux 命令行中编辑
除了实际编辑文本文件外,另一个我经常使用,且和编辑密切相关的工具是 Bash shell。Bash 的默认编辑器是 Emacs。虽然我也用过 Emacs,但我肯定更喜欢 Vim。所以很多年前,我把 Bash 命令行的默认编辑器从 Emacs 换成了 Vim,这对我来说更舒服。
有很多种方法可以配置 Bash。你可以使用一个本地配置文件,比如 `/home/yourhomedirectory/.bashrc`,它只对你的用户账户进行默认修改,而不对同一系统的其他用户进行修改。我个人倾向于让这些改变成为全局性的,基本上就是我的个人账户和 root。如果你也想全局配置,你可以创建你自己的配置文件,并把它放在 `/etc/profile.d` 目录中。
我在 `/etc/profile.d` 中添加了一个名为 `myBashConfig.sh` 的文件。`/etc/profile.d` 目录中存放了所有已安装的 shell 的启动文件。在启动终端会话时,每个 shell 仅会根据文件名的扩展名,读取为其准备的启动文件。例如,Bash shell 只读取扩展名为 `.sh` 的文件。
```
<截断>
alias vim='vim -c "colorscheme desert" '
# 把 vi 设置为 Bash 的默认编辑器
set -o vi
# 为所有检查 $EDITOR 变量的程序设置默认编辑器为 vi
EDITOR=vi
<截断>
```
在这个全局 Bash 配置文件段中,`set -o vi` 将 Vi 设置为默认编辑器。这个 `set` 命令中的 `-o` 选项将 `vi` 定义为编辑器。为使配置生效,你需要关闭所有正在运行的 Bash 会话,并打开新的会话。
现在,你现在可以使用所有你熟悉的 Vim 命令,包括光标移动。只要按下 `Esc` 键就可以进入 Vim 编辑模式。我特别喜欢多次使用 `b` 将光标移回多个字的功能。
### 将 Vim 设置为其他程序的默认值
一些 Linux 命令行工具和程序会检查 `$EDITOR` 环境变量来决定使用哪个编辑器。你可以用下面的命令检查这个变量的当前值。我在一个新安装的虚拟机上运行过该命令,以查看默认的编辑器到底是什么。
```
# echo $EDITOR
/usr/bin/nano
#
```
默认情况下,检查 `$EDITOR` 环境变量的 Fedora 程序会使用 Nano 编辑器。在 `myBashConfig.sh` 中添加一行 `EDITOR=vi`(如上面的片段所示),可以将默认值改为 Vi(Vim)编辑器。然而,不是所有使用外部编辑器的命令行程序都会检查这个环境变量。
### 在 Alpine 中编辑电子邮件
几周前,我认为 Pico 不太适合作为我的电子邮件编辑器。我可以使用它,而且在从 Thunderbird 转到 [Alpine][4] 之后的一段时间内我也用了一段时间。但我发现,Pico 妨碍了我,我总是习惯使用 Vim 按键序列,这影响了我的工作效率。
我在 Alpine 的用户帮助中看到,默认编辑器是可以修改的。我决定把它改成 Vim。实际上这很容易做到。
在 Alpine 主菜单上,按 `S` 键进入设置,然后按 `C` 键进行配置。在 “<ruby>编辑器设置<rt>Composer Preferences</rt></ruby>” 部分,按 `X` 选择 “<ruby>启用外部编辑器命令<rt>Enable Alternate Editor Command</rt></ruby>” 和 “<ruby>隐式启用外部编辑器<rt>Enable Alternate Editor Implicitly</rt></ruby>” 项目。在往下滚动几页的 “<ruby>高级用户设置<rt>Advanced User Preferences</rt></ruby>” 部分,找到 `Editor 那一行。如果它还没有被修改的话,它应该是这样的:
```
Editor = <No Value Set>
```
用光标栏突出显示 `Editor` 这一行,然后按回车键来编辑。将 `<No Value Set>` 改为 `vim`,再按回车键,然后按 `E` 键退出,最后按 `Y` 键保存修改。
要用 Vim 编辑电子邮件,只需进入电子邮件正文,Vim 就会自动启动,就像 Pico 那样。所有我喜欢的编辑功能都还在,因为它实际上是在使用 Vim。甚至退出 Vim 的 `Esc :wq` 序列也是一样的。
### 总结
与其他编辑器相比,我更喜欢 Vim,对我的系统进行的这些改动后,那些默认使用其他编辑器的应用程序,将使用 Vim 来替代它们的默认编辑器。有些程序使用 `$EDITOR` 环境变量,因此你只需要做一次修改就够了。其他有用户配置选项的程序,如 Alpine,则必须为每个程序单独设置。
这种可以选择你喜欢的外部编辑器的能力,非常符合 Unix 哲学的宗旨:“每个程序都只做一件事,而且要做得出色”。既然已经有几个优秀的编辑器,为什么还要再写一个呢?而且它也符合 Linux 哲学的宗旨:“使用你最喜欢的编辑器”。
当然,你可以把你的默认文本编辑器改为 Nano、Pico、Emacs 或任何其他你喜欢的编辑器。
--------------------------------------------------------------------------------
via: https://opensource.com/article/22/2/configure-vim-default-editor
作者:[David Both][a]
选题:[lujun9972][b]
译者:[lkxed](https://github.com/lkxed)
校对:[wxy](https://github.com/wxy)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://opensource.com/users/dboth
[b]: https://github.com/lujun9972
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/laptop_screen_desk_work_chat_text.png?itok=UXqIDRDD (Person using a laptop)
[2]: https://opensource.com/article/20/12/gnu-nano
[3]: https://opensource.com/tags/emacs
[4]: https://opensource.com/article/21/5/alpine-linux-email
|
C++ | UTF-8 | 7,426 | 2.609375 | 3 | [] | no_license | //
// Created by shenc on 2017/11/7.
//
#include "Window.h"
#include "VulkanSupport.h"
#include "PhysicalDevice.h"
#include "Device.h"
Window::Window(Device* device,const char *title, int x, int y, int w, int h, bool isFullScreen) :
m_strWindowTitle(title),
m_iWindowWidth(w),
m_iWindowHeight(h),
m_bIsFullScreen(isFullScreen),
m_bIsClose(false),
m_pSurface(VK_NULL_HANDLE),
m_pDevice(device),
m_pSwapchain(VK_NULL_HANDLE),
m_pFormat(VK_FORMAT_B8G8R8A8_UNORM),
m_iPresentQueueIndex(0)
{
}
Window::~Window()
{
_uninit_swapchain();
}
void Window::_init_swapchain()
{
//检查当前格式的表面是否能被绘制到屏幕
const PhysicalDevice* physicalDevice = m_pDevice->getPhysicalDevice();
int queueCount = physicalDevice->getQueueIndexCount();
VkPhysicalDevice vkPhysicalDevice = physicalDevice->getVkPhysicalDevice();
VkBool32* surfaceSuppor = (VkBool32*)malloc(sizeof(VkBool32)*queueCount);
for (int i = 0; i < queueCount; ++i)
{
//获取每一个索引是否能被找到能够支持绘制到屏幕
vkGetPhysicalDeviceSurfaceSupportKHR(vkPhysicalDevice,i,m_pSurface,&surfaceSuppor[i]);
}
int graphicsIndex = physicalDevice->getQueueIndexOfGraphics();
//判断当前制图的索引是否能被渲染到表面
if (surfaceSuppor[graphicsIndex]) //能支持
m_iPresentQueueIndex = graphicsIndex;
else //不能支持
{
for (int i = 0; i < queueCount; ++i)
{
if (surfaceSuppor[i] == VK_TRUE)
{
m_iPresentQueueIndex = i;
break;
}
}
}
free(surfaceSuppor);
//检查索引是否正确
assert(m_iPresentQueueIndex < queueCount);
//取得物理设备的支持当前绘图表面的支持格式
std::vector<VkSurfaceFormatKHR> surfaceFormats;
UINT32 sfcount = 0;
vkGetPhysicalDeviceSurfaceFormatsKHR(vkPhysicalDevice,m_pSurface,&sfcount, nullptr);
surfaceFormats.resize(sfcount);
vkGetPhysicalDeviceSurfaceFormatsKHR(vkPhysicalDevice,m_pSurface,&sfcount,surfaceFormats.data());
if (sfcount == 1 && surfaceFormats[0].format == VK_FORMAT_UNDEFINED)
{
//没有合适的表面格式
m_pFormat = VK_FORMAT_B8G8R8A8_UNORM;
} else if (sfcount > 0)
m_pFormat = surfaceFormats[0].format;
//取得表面的能力
VkSurfaceCapabilitiesKHR surfaceCapabilitiesKHR;
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(vkPhysicalDevice,m_pSurface,&surfaceCapabilitiesKHR);
//
std::vector<VkPresentModeKHR> presentModes;
uint32_t presentModeCount = 0;
vkGetPhysicalDeviceSurfacePresentModesKHR(vkPhysicalDevice,m_pSurface,&presentModeCount, nullptr);
presentModes.resize(presentModeCount);
vkGetPhysicalDeviceSurfacePresentModesKHR(vkPhysicalDevice,m_pSurface,&presentModeCount, presentModes.data());
VkExtent2D swapchainExtent;
if (surfaceCapabilitiesKHR.currentExtent.width == 0xFFFFFFFF)
{
swapchainExtent.width = std::min((uint32_t)m_iWindowWidth,surfaceCapabilitiesKHR.maxImageExtent.width);
swapchainExtent.height = std::max((uint32_t)m_iWindowHeight,surfaceCapabilitiesKHR.maxImageExtent.height);
} else
swapchainExtent = surfaceCapabilitiesKHR.currentExtent;
VkSwapchainCreateInfoKHR swapchainCreateInfoKHR = {};
swapchainCreateInfoKHR.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
swapchainCreateInfoKHR.pNext = nullptr;
swapchainCreateInfoKHR.surface = m_pSurface;
swapchainCreateInfoKHR.minImageCount = surfaceCapabilitiesKHR.minImageCount;
swapchainCreateInfoKHR.imageFormat = m_pFormat;
swapchainCreateInfoKHR.imageExtent.width = swapchainExtent.width;
swapchainCreateInfoKHR.imageExtent.height = swapchainExtent.height;
swapchainCreateInfoKHR.preTransform =
(surfaceCapabilitiesKHR.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR)?
VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR:surfaceCapabilitiesKHR.currentTransform;
swapchainCreateInfoKHR.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
swapchainCreateInfoKHR.imageArrayLayers = 1;
swapchainCreateInfoKHR.presentMode = VK_PRESENT_MODE_FIFO_KHR;
swapchainCreateInfoKHR.oldSwapchain = nullptr;
swapchainCreateInfoKHR.clipped = true;
swapchainCreateInfoKHR.imageColorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
swapchainCreateInfoKHR.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
swapchainCreateInfoKHR.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
swapchainCreateInfoKHR.queueFamilyIndexCount = 0;
swapchainCreateInfoKHR.pQueueFamilyIndices = nullptr;
uint32_t queueFamilyIndices[2] = {(uint32_t)graphicsIndex,(uint32_t)m_iPresentQueueIndex};
if (graphicsIndex != m_iPresentQueueIndex)
{
swapchainCreateInfoKHR.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
swapchainCreateInfoKHR.queueFamilyIndexCount = 2;
swapchainCreateInfoKHR.pQueueFamilyIndices = queueFamilyIndices;
}
VkResult result = vkCreateSwapchainKHR(m_pDevice->getVulkanDevice(),&swapchainCreateInfoKHR, nullptr,&m_pSwapchain);
if (result != VK_SUCCESS)
{
#ifdef RS_DEBUG
std::cout << "vkCreateSwapchainKHR Error" << std::endl;
#endif
}
uint32_t siCount = 0;
vkGetSwapchainImagesKHR(m_pDevice->getVulkanDevice(),m_pSwapchain,&siCount, nullptr);
m_pSwapchainImage.resize(siCount);
m_pSwapchainImageView.resize(siCount);
vkGetSwapchainImagesKHR(m_pDevice->getVulkanDevice(),m_pSwapchain,&siCount, m_pSwapchainImage.data());
for (int j = 0; j < siCount; ++j) {
VkImageViewCreateInfo imageViewCreateInfo = {};
imageViewCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
imageViewCreateInfo.pNext = nullptr;
imageViewCreateInfo.flags = 0;
imageViewCreateInfo.image = m_pSwapchainImage[j];
imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
imageViewCreateInfo.format = m_pFormat;
imageViewCreateInfo.components.a = VK_COMPONENT_SWIZZLE_A;
imageViewCreateInfo.components.b = VK_COMPONENT_SWIZZLE_B;
imageViewCreateInfo.components.g = VK_COMPONENT_SWIZZLE_G;
imageViewCreateInfo.components.r = VK_COMPONENT_SWIZZLE_R;
imageViewCreateInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
imageViewCreateInfo.subresourceRange.baseArrayLayer = 0;
imageViewCreateInfo.subresourceRange.layerCount = 1;
imageViewCreateInfo.subresourceRange.baseMipLevel = 0;
imageViewCreateInfo.subresourceRange.levelCount = 1;
vkCreateImageView(m_pDevice->getVulkanDevice(),&imageViewCreateInfo, nullptr,&m_pSwapchainImageView[j]);
}
}
void Window::_uninit_swapchain()
{
if (m_pSwapchain)
{
VkDevice device = m_pDevice->getVulkanDevice();
for (auto i :m_pSwapchainImageView)
{
vkDestroyImageView(device,i, nullptr);
}
m_pSwapchainImageView.clear();
m_pSwapchainImage.clear();
vkDestroySwapchainKHR(device,m_pSwapchain, nullptr);
m_pSwapchain = nullptr;
}
if (m_pSurface)
{
VkInstance instance = VulkanSupport::getSingletonPrt()->getVkInstance();
vkDestroySurfaceKHR(instance,m_pSurface, nullptr);
m_pSurface = VK_NULL_HANDLE;
}
}
|
Java | UTF-8 | 4,983 | 2.609375 | 3 | [] | no_license | package com.westosia.TradingPlugin.trading;
import co.aikar.commands.BaseCommand;
import co.aikar.commands.annotation.CommandAlias;
import co.aikar.commands.annotation.CommandPermission;
import co.aikar.commands.annotation.Default;
import co.aikar.commands.annotation.Description;
import com.westosia.TradingPlugin.listener.TradeListener;
import com.westosia.westosiaapi.WestosiaAPI;
import com.westosia.westosiaapi.api.Notifier;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import java.util.HashMap;
@CommandAlias("trade")
@CommandPermission("essentials.command.trade")
public class TradeCommand extends BaseCommand {
HashMap<Player, Player> requestTrade = new HashMap<Player, Player>();
TradeListener tradeList;
public TradeCommand(TradeListener listener) {
tradeList = listener;
}
@Default
@Description("creates a trade request or accept a trade request")
public void trade(Player player, String[] args) {
if (args.length == 2) {
if (args[0].equalsIgnoreCase("request")) {
Player tradeWith = Bukkit.getPlayer(args[1]);
if (tradeWith != player) {
if (Bukkit.getOnlinePlayers().contains(tradeWith)) {
WestosiaAPI.getNotifier().sendChatMessage(player, Notifier.NotifyStatus.SUCCESS, "Trade request has been sent to " + args[1]);
requestTrade.put(tradeWith, player);
WestosiaAPI.getNotifier().sendChatMessage(tradeWith, Notifier.NotifyStatus.INFO, "You have a trade request from " + player.getName());
} else {
WestosiaAPI.getNotifier().sendChatMessage(player, Notifier.NotifyStatus.ERROR, "Player requested is not online.");
}
} else {
WestosiaAPI.getNotifier().sendChatMessage(player, Notifier.NotifyStatus.ERROR, "Cannot trade with yourself");
}
}
}
if (args.length == 1) {
if (args[0].equalsIgnoreCase("accept")) {
if (requestTrade.containsKey(player)) {
Player tradeWith = requestTrade.get(player);
if (Bukkit.getOnlinePlayers().contains(tradeWith)) {
Inventory tradeInv = Bukkit.createInventory(null, 27, "TRADE INVENTORY");
ItemStack glass = new ItemStack(Material.LIGHT_GRAY_STAINED_GLASS_PANE);
ItemStack button = new ItemStack(Material.RED_STAINED_GLASS_PANE);
tradeInv.setItem(9, glass);
tradeInv.setItem(10, glass);
tradeInv.setItem(11, glass);
tradeInv.setItem(12, glass);
tradeInv.setItem(13, glass);
tradeInv.setItem(14, glass);
tradeInv.setItem(15, glass);
tradeInv.setItem(16, glass);
tradeInv.setItem(17, button);
player.openInventory(tradeInv);
tradeWith.openInventory(tradeInv);
requestTrade.remove(player);
tradeList.addPlayersToTradelist(player, tradeWith);
} else {
WestosiaAPI.getNotifier().sendChatMessage(player, Notifier.NotifyStatus.ERROR, "Player isn't online anymore");
requestTrade.remove(player);
}
} else {
WestosiaAPI.getNotifier().sendChatMessage(player, Notifier.NotifyStatus.ERROR, "No active trade requests");
}
} else if(args[0].equalsIgnoreCase("decline")) {
if (requestTrade.containsKey(player)) {
Player tradeWith = requestTrade.get(player);
WestosiaAPI.getNotifier().sendChatMessage(tradeWith, Notifier.NotifyStatus.ERROR, "Player declined your trade request");
requestTrade.remove(player);
}
} else if(args[0].equalsIgnoreCase("help")) {
WestosiaAPI.getNotifier().sendChatMessage(player, Notifier.NotifyStatus.INFO, "Help with Trading?");
WestosiaAPI.getNotifier().sendChatMessage(player, Notifier.NotifyStatus.BLANK, " ");
WestosiaAPI.getNotifier().sendChatMessage(player, Notifier.NotifyStatus.INFO, "To initiate a trade, type: /trade request {player}");
WestosiaAPI.getNotifier().sendChatMessage(player, Notifier.NotifyStatus.INFO, "To accept a trade type: /trade accept");
WestosiaAPI.getNotifier().sendChatMessage(player, Notifier.NotifyStatus.INFO, "To decline a trade type: /trade decline");
requestTrade.remove(player);
}
}
}
}
|
Python | UTF-8 | 1,046 | 3.015625 | 3 | [
"MIT"
] | permissive | from modules import connection
from modules import formatter
def get_errors_per_day():
conn = connection.get_connection()
conn.execute('''
WITH t AS
(SELECT DATE(log.time) AS failureDate,
ROUND((SUM(CASE WHEN
SUBSTRING(log.status, 0, 4)::INTEGER >= 400
THEN 1
ELSE 0
END
) * 100.0)::DECIMAL /
(COUNT(log.status)), 1) AS totalErrors
FROM log GROUP BY DATE (log.time)
)
Select CONCAT(t.totalErrors, '%') AS failure,
to_char(t.failureDate, 'Month DD, YYYY') AS date
FROM t
GROUP BY t.totalErrors, t.failureDate
HAVING t.totalErrors > 1
''')
return conn
def print_errors_per_day():
print("Errors per day:")
formatter.repeat_separator()
for item in get_errors_per_day():
print(
"The day that has more than 1% of errors per day are '" +
str(item[1]) +
"' with a total percent of errors of '" +str(item[0]) + "'")
formatter.repeat_separator() |
Java | UTF-8 | 637 | 2.671875 | 3 | [] | no_license | package com.abin.lee.distribute.algorithm.classic.manage;
import com.abin.lee.distribute.algorithm.classic.Acceptor;
public class AcceptorDaemon extends Thread{
private Acceptor acceptor;
public AcceptorDaemon(Acceptor acceptor){
this.acceptor = acceptor;
}
@Override
public void run(){
while(true){
try{
acceptor.sentLearntValue();
Thread.sleep(5000);
}catch(Exception e){
e.printStackTrace();
System.out.println("Exception during sending message to learners");
}
}
}
}
|
Java | UTF-8 | 4,663 | 2.640625 | 3 | [] | no_license | package net.equj65.indexgenerator.generator;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;
import net.equj65.indexgenerator.constants.DBMS;
import net.equj65.indexgenerator.domain.EntireSQL;
import net.equj65.indexgenerator.parser.SQLParser;
/**
* UniqueIndexのGeneratorです。
* TODO javadoc
* @author W.Ryozo
* @version 1.0
*/
public class UniqueIndexGenerator {
/** 論理削除フラグのデフォルト名 */
public static final String DEFAULT_DELFLAG_NAME = "is_deleted";
/** デフォルトDBMS */
public static final DBMS DEFAULT_DBMS = DBMS.POSTGRESQL;
public static void generate(File inputSqlFile, File outputSqlFile, String fileEncoding) {
generate(inputSqlFile, outputSqlFile, fileEncoding, DEFAULT_DBMS, DEFAULT_DELFLAG_NAME, Boolean.FALSE);
}
public static void generate(File inputSqlFile, File outputSqlFile, String fileEncoding, DBMS targetDBMS) {
generate(inputSqlFile, outputSqlFile, fileEncoding, targetDBMS, DEFAULT_DELFLAG_NAME, Boolean.FALSE);
}
public static void generate(File inputSqlFile, File outputSqlFile, String fileEncoding, String conditionField, Object conditionValue) {
generate(inputSqlFile, outputSqlFile, fileEncoding, DEFAULT_DBMS, conditionField, conditionValue);
}
public static void generate(File inputSqlFile, File outputSqlFile, String fileEncoding, Map<String, Object> conditionMap) {
generate(inputSqlFile, outputSqlFile, fileEncoding, DEFAULT_DBMS, conditionMap);
}
public static void generate(File inputSqlFile, File outputSqlFile, String fileEncoding, DBMS targetDBMS, String conditionField, Object conditionValue) {
Map<String, Object> conditionMap = new HashMap<>();
conditionMap.put(conditionField, conditionValue);
generate(inputSqlFile, outputSqlFile, fileEncoding, targetDBMS, conditionMap);
}
// TODO javadoc
// TODO Exceptionの取り扱いを修正
public static void generate(File inputSqlFile,
File outputSqlFile,
String fileEncoding,
DBMS targetDBMS,
Map<String, Object> conditionMap) {
// arguments validate
if (inputSqlFile == null) {
throw new IllegalArgumentException("読み込み対象のSQLファイルが指定されていません。");
}
if (!inputSqlFile.isFile()) {
throw new IllegalArgumentException("読み込み対象SQLファイルが存在しないかファイルではありません");
}
if (outputSqlFile == null) {
throw new IllegalArgumentException("出力用のSQLファイルが指定されていません");
}
if (outputSqlFile.exists()) {
throw new IllegalArgumentException("出力用のSQLファイルが既に存在します。存在しないファイル名を指定してください");
}
try {
String sql = readSqlFile(inputSqlFile, fileEncoding);
SQLParser sqlParser = new SQLParser();
EntireSQL entireSql = sqlParser.parse(sql);
// TODO ここでDBMSを渡さないようにする。
entireSql.addConditionToAllUniqueConstraint(targetDBMS, conditionMap);
writeSqlFile(outputSqlFile, entireSql.toString(), fileEncoding);
} catch (Exception e) {
// TODO 例外処理の実装
e.printStackTrace();
}
}
/**
* SQLファイル全体を読み込みます。
* @param sqlFile 読み込み対象のSQLファイル
* @param encoding SQLファイルの文字コード
* @return 読み込んだSQLファイル(改行コード含む)
*/
private static String readSqlFile(File sqlFile, String encoding) throws IOException {
StringBuilder builder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(sqlFile), encoding))){
int c;
while ((c = reader.read()) != -1) {
// TODO サロゲート文字が含まれていた場合問題無いのか?
builder.append((char) c);
}
}
return builder.toString();
}
/**
* ファイルを書き込みます。
* @param outputFile 出力先ファイルを表すFileオブジェクト
* @param writeString 出力対象の文字列
* @param encoding 出力先ファイルのエンコーディング
* @throws IOException
*/
private static void writeSqlFile(File outputFile, String writeString, String encoding) throws IOException {
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), encoding))) {
// TODO 削除
System.out.println(writeString);
writer.write(writeString);
}
}
}
|
Java | UTF-8 | 634 | 2.015625 | 2 | [] | no_license | package com.javadeveloperzone.service;
import com.javadeveloperzone.modal.OrderDetails;
import com.javadeveloperzone.repository.OrderDetailsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class OrderService {
@Autowired
private OrderDetailsRepository orderRepository;
public OrderDetails save(OrderDetails order){
return this.orderRepository.save(order);
}
public List<OrderDetails> findOrderByUserId(Long userId){
return this.orderRepository.findOrdersByUserId(userId);
}
}
|
Python | UTF-8 | 1,901 | 4.03125 | 4 | [] | no_license |
# I wrote this code to help me with math homework
# because my calculator gave decimals when I needed
# simplified square roots. It is a combination/modification
# of two other programs I had previously written as experiments:
# a quadratic formula calculator and a prime number checker.
while True:
num = int(input("Enter an integer to take the square root of: "))
coef = 1
while True:
if num < 0:
print("Domain Error")
break
if num > 3:
end = num
n = int(4)
while True:
fac = int(2)
while True:
if n > fac and n%fac != 0:
fac += 1
continue
if n%fac == 0 and n != fac:
break
elif fac == n:
if (num >= (n**2)) and (num%(n**2) == 0):
num = num/(n**2)
coef = coef*n
break
if n < end:
n += 1
continue
elif n == end:
break
if num >= 4 and (num%4) == 0:
num = num/4
coef = coef*2
continue
if num >= 9 and (num%9) == 0:
num = num/9
coef = coef*3
continue
else:
coeff = str(int(coef))
root = str(int(num))
if (num == 1) or (num == 0):
print(coeff)
elif (coef > 1) and (num > 1):
print(coeff + " root " + root)
if (num != 1) or (coef == 1):
print(coef*num**0.5)
elif (coef == 1):
print(num**0.5)
break
|
C++ | UTF-8 | 24,008 | 3.25 | 3 | [] | no_license | /* -*- mode: c++; -*- */
/** @file map_store.h
*
* Implementation of the MapStore class.
*
* This file implements the MapStore class, which is used to store
* growable grid-based maps. Map data is stored in double values.
*/
#ifndef MAP_STORE_H
#define MAP_STORE_H
#include <list>
#include "map_store_error.h"
#include "map_store_beam.h"
namespace mapstore {
/** Representation of one grid cell.
*
* This structure represents a map cell for those occasions where
* individual grid cells are passed between function and classes. It
* is primarily used with the MapStore::trace() function and the
* MapStoreTrace class returned by that function.
*
* The MapStore class itself uses another, more memory-efficient
* internal representation.
*/
struct MapStoreCell {
/** Default constructor. Not used.*/
MapStoreCell() : x(0), y(0), val(0) {}
/** Create new MapStoreCell for cell (@a x, @a y) with cell value
* @a aval. */
MapStoreCell(int ax, int ay, double aval) : x(ax), y(ay), val(aval) {}
int x; /** x-coordinate of cell. */
int y; /** y-coordinate of cell. */
double val; /** The value stored in this cell. */
};
/** This class reperesents a trace (or beam) through a map.
*
* This class records all cells touched by a beam through a map,
* starting at a point (x, y) in the some direct, using instances of
* MapStoreCell.
*
* This class' primariy use is as result of a call to
* MapStore::trace().
*/
class MapStoreTrace {
public:
/** Default constructor, create an empty trace.*/
MapStoreTrace();
/** Add a cell to the trace.
*
* Cells @em must be added in the correct order, i.e. in the order
* a beam / trace would touche the cells!
*
* The supplied MapStoreCell instance is copied and can be reused
* to add another cell or can be destroyed.
*/
void add(const MapStoreCell &c);
/** Add a cell to the trace.
*
* Cells @em must be added in the correct order, i.e. in the order
* a beam / trace would touche the cells!
*/
void add(int x, int y, double val);
/** Public iterator type to walk through the trace.
*
* This iterator allows one to access all cells in the trace one by
* one.
* @code
* MapStore mapstore;
* // ... do something with the map store ...
*
* // obtain a trace
* MapStoreTrace mst = mapstore.trace(...);
*
* // walk the trace
* MapIt myIterator = mst.traceStart();
* MapIt myEnd = mst.traceEnd();
* while (myIterator != myEnd) {
* MapStoreCell msc = *myIterator;
* myIterator++;
* // ... do something with the cell ...
* printf("cell (%d, %d) has value %f\n", msc.x, msc.y, msc.val);
* }
* @endcode
*
* Not to be confused with MapStore::MapIt.
*/
typedef std::list<MapStoreCell>::iterator MapIt;
/** Returns an iterator pointing to the beginning of the trace.
*
* See MapStoreTrace::MapIt for details.
*/
MapIt traceStart(void) {
return cells.begin();
}
/** Returns an iterator pointing to the end of the trace.
*
* See MapStoreTrace::MapIt for details.
*/
MapIt traceEnd(void) {
return cells.end();
}
private:
/** We use a standard lib "list" as storage backend. */
std::list<MapStoreCell> cells;
};
/** This class implements a storage for a grid-based map.
*
* Initially the map is zero-centered, that is the coordinates (0,0)
* are in its center. However the map can be grown at arbitrary
* places, what may shift the map's center away from (0,0).
*
* The grid cells are addressed by integer numbers. Conceptionally
* each cell (x,y) occupies the space from (x-0.5, y-0.5) exclusive
* to (x+0.5, y+0.5) inclusive. However this comes only into
* importance, when tracing a beam through the map to identifiy which
* cells are touched by the beam.
*
* The class does not make any assumption about the unit size of the
* grid cells. Cells are simple numbered by integer coordinates.
* See class SonarMap which does care about unit size.
*/
class MapStore {
public:
/** Constructor to create empty map of given size.
*
* Creates a map of the requested size with zero-centred origin.
* The map includes all coordiante points from -sizeX/2 to sizeX/2
* in x and -sizeY/2 to sizeY/2 y direction. If sizeX or sizeY is
* odd, it will be rounded down first.
*
* @param initSizeX Initial size in x direction. The map's center
* coordinate will be 0,0, with the map extending initSizeX/2
* cells in both directions.
*
* @param initSizeY Initial size in y direction. The map's center
* coordinate will be 0,0, with the map extending initSzeX/2
* cells in both directions.
*/
MapStore(int initSizeX, int initSizeY);
/** Constructor to load map from file.
*
* Cretes a new map object from the map data stored in the named
* file. See loadMap() for a documentation of the file format.
* This constructor throws an exception of type
* MapStoreError::Format in case of unreadable file or file format
* error.
* */
MapStore(const char *mapFileName);
/** Destructor of this class. */
~MapStore();
/** Load a map from the named file.
*
* This function loads the maps content from the named file. See
* loadMap(FILE *fh) for more details.
*
* @p Map file format
* The map file format is line-based. The file starts with a
* header describing the size and possibly resolution of the map.
* The resolution is not used by MapStore. The header is
* recognized by the keywords defining map properties starting in
* the first column of a line. The header must be present as one
* continuous sequence of lines without empty lines in between.
*
* The header may be followed by additional lines holding
* information on how to print the map using the GNUPlot data
* visualizer. These lines are identified by starting with a
* lower-case letter and not holding as first word one of the map
* property keywords.
*
* The optional visualization information is followed by the raw
* map data. The map data is stored as (long) lines of decimal
* numbers, each row representing one row of the map and each
* column representing one column of the map.
*
* @p Map header
* The map header can hold the following keyword in arbitrary order:
* * MapSize: columns rows
* * MapRes: cell_size_in_meters
* * MapType: type_name
* * MapOrigin: center_x center_y
*
*
* @return flag if the load was successful or not.
* */
bool loadMap(const char *mapFileName);
/** Load map from alredy open file handle.
*
* This function loads the map data stored in the open file fh
* into the map. It checks if the file starts at its current read
* position with a map header or with raw map data. If a map
* header is found, then its information is used to reconfigure
* the map (i.e. resize) as specified in the header. If no header
* is found, then the map data is read into the existing map. It
* is a fatal error, if the raw data does not fit the maps current
* configuration.
*
* In case of unrecoverable error, i.e. the function already
* modified the map and then discovered a format error in the data
* file, an exception of type MapStoreError::Format is thrown.
*
* See loadMap(const char *mapfileName) for a documentation of the
* required map file format.
*
* @retval true : This function returns true if the map could
* successfully loaded.
* @retval false : This function returns false if the map could
* not be loaded, for example because no valid data was found,
* and the map is unaltered. If a problem is found after the
* function already modified the map, then an exception of type
* MapStoreError::Format is thrown.
* */
bool loadMap(FILE *mapFH);
/** Add space to map.
*
* This method adds the quadratic area around (x,y) with size @a size
* to the map. These are the coordinates (inclusive) from x-size
* to x+size and y-size to y+size.
*
* @param x Center coordinate where to add space. Note that this
* coordinates does not need to be within the already defined
* part of the map. The map can be grown everywhere.
*
* @param y Center coordinate where to add space. Note that this
* coordinates does not need to be within the already defined
* part of the map. The map can be grown everywhere.
*
* @param size amount of space to add into both directions around
* cell (@a x, @ y). Example: grow(2, 3, 4) will add the
* rectagular space covering the coordinates from (-2, -1) to (6,
* 7).
*/
bool grow(int x, int y, int size);
/** Set map point to given value.
*
* Will throw a MapStoreError exception if (x,y) is outside the
* map.
*/
void set(int x, int y, double val);
/** Get map point value.
*
* Will throw a MapStoreError exception if (x,y) is outside the
* map.
*/
double get(int x, int y) const;
/** Get a constant pointer to the internal data storage. */
const double* getRawData() const
{
return data;
}
/** Trace a beam through the map and report all map points visited.
*
* This method trace a beam through the map. Opposed to the set()
* and get() methods it takes double values as coordinates and a
* direction (measured in radians). While the map works on a
* discrete, integer-based grid, this method takes real numbers to
* be able to accurately trace the beam. It computes which grid
* cells are touched and reports the integer coordinates of the
* touched cells along with that cells value. Each cell with
* integer coordinates (x,y) occupies the space from x,y -0.5
* exclusive to x,y + 0.5 inclusive.
*
* The touched cells are returned as a MapStoreTrace object.
*
* Search for cells stops if the given length limit has been
* reached or the beam leaves the defined map area. If no length
* has been specified, or length is zero, then the search stops at
* the first cell with a value bigger than 0. This cell is part of
* the result set returned.
*
* Will throw a MapStoreError exception if (x,y) is outside the map.
*
* @param x X start coordinate of beam. Note that x can be a
* double, not just an integer. The integer cell (@c a, @c b)
* covers the space from (@c a - 0.5, @c b - 0.5) to (@c a + 0.5,
* @c b + 0.5).
*
* @param y See parameter @a x.
*
* @param dir direction of beam, in radians measured against
* map's x axis.
*
* @param length Length ofbem in units of cell egde length.
*/
MapStoreTrace trace(double x, double y, double dir, double length) const;
/** Find max value along a beam.
*
* This method is similar to trace(), except that this method
* returns only the cell with the maximum value in the beam.
*
* @sa trace(double x, double y, double dir, double length)
*/
MapStoreCell traceMax(double x, double y, double dir, double length);
/** Find max value in a cone.
*
* This method is similar to trace(), except it returns the cell
* with maximum value inside a cone of angular width @a width
* around the beam from (x,y) into direction dir with length len.
*
* @sa trace(double x, double y, double dir, double length)
*/
MapStoreCell traceConeMax(double x, double y, double dir, double width, double len);
/** Set a rectangular region to value.
*
* Will throw a MapStoreError exception if the whole rectangle is
* outside the map.
*
* @param x,y corrdinates of uper-left corner of rectangle.
*
* @param @adx,dy number of cells to fill in x and y direction.
* If dx or dy are negativ, then the rectangle is filled to the
* lft or top of (x, y), respectively. (I.e dx < 0 and dy < 0
* makes (x, y) the lower right corner of the filled rectangle.
* Neither dx nor dy may be zero.
*/
void fillRect(int x, int y, int dx, int dy, double val);
/** Set a cone-shaped region to value.
*
* Will throw a MapStoreError exception if the whole cone is
* outside the map.
*
* @param x,y Origin of the cone.
*
* @param dir Direction of the center beam of the cone.
*
* @param len Length (radius) of the cone, in units of cell egde
* length.
*/
void fillCone(double x, double y, double dir, double width, double len, double val);
/** Declare rectangular region as undefined.
*
* Equivalent to calling fillRect with a zero value, excpet that
* this function may free some storage space for some storage
* engines.
*/
void eraseRect(int x, int y, int dx, int dy);
/** Return minimum cell coordinate in x direction. */
int minX(void) const {
return -originX;
}
/** Return map size in x direction. */
int getSizeX(void) const {
return sizeX;
}
/** Return map size in y direction. */
int getSizeY(void) const {
return sizeY;
}
/** Return map resolution. */
double getResolution(void) const {
return resolution;
}
/** Return minimum cell coordinate in y direction. */
int minY(void) const {
return -originY;
}
/** Return maximum cell coordinate in x direction. */
int maxX(void) const {
return sizeX-originX-1;
}
/** Return maximun cell coordinate in y direction. */
int maxY(void) const {
return sizeY-originY-1;
}
/** Check if @a x is a in its valid range.
*
* The value @a x is taken as the x-value of a cell coordinate
*/
bool isInX(int x) const {
// -originX <= x < sizeX-originX
// 0 <= (x+originX) < sizeX
x += originX;
return ((0 <= x) && (x < sizeX));
}
/** Check if @a y is a in its valid range.
*
* The value @a y is taken as the y-value of a cell coordinate
*/
bool isInY(int y) const {
// -originY <= y < sizeY-originY
// 0 <= (y+originY) < sizeY
y += originY;
return ((0 <= y) && (y < sizeY));
}
/** Special iterator to walk through a Mapstore.
*
* For details, refere the the constructor documentation.
*
* This class is not to be confused with MapStoreTrace::MapIt.
*/
struct MapIt {
/** Construct beam iterator through a MapStore.
*
* This convenient structure encapsulates an instance of the
* MapStoreBeam class to trace a beam from cell (@a x1, @a y1) to
* cell (@a x2, @a y2). For allowed values see the documentation
* of class MapStoreBeam.
*
* The iterator is created for the map @a a_map and has a
* dependency to the map @a a_map. The map may not be
* destroyed while this iterator exists. Modifying the map
* (including growing it) is fine.
*
* @param x1,y1 Start cells of beam. The beam originates at
* the center of the named cell.
*
* @param x2,y2 End cells of beam. The beam terminates at the
* center of the named cell.
*
*/
MapIt(int x1, int y1, int x2, int y2, const MapStore &a_map) : beam(x1,y1, x2,y2), map(a_map) {
}
/** Return next cell in the trace.
*
* this function determines the next cell in the trace and
* updates the functions parameters to refelct the next cell. It
* returns "true" if there was a next cell, and "false" if the
* end of the trace had been reached. In case of returning
* "false", the values of the parameters are undefined.
*
* @param x Return parameter, the functions set @a x to the
* x-coordinate of the next cell.
*
* @param y Return parameter, the functions set @a y to the
* y-coordinate of the next cell.
*
* @param val Return parameter, the function sewt @a val to the
* next cell's value.
*
* @retval true @a x, @a y and @a val have been updated.
*
* @retval false The last cell has been reached (in the
* previous call). The return parameters are undefined.
*/
bool next(int &x, int &y, double &val) {
bool res = beam.nextCell(x,y);
if (res) {
val = map.get(x,y);
}
return res;
}
/** The underlying beam instance.
*
* This MapStoreBeam class implements the actual computation of
* the next cell.
*/
MapStoreBeam beam;
/** Reference to the map for which this iterator has been created.*/
const MapStore ↦
};
/** Create a map iterator.
*
* This function creates an iterator travering the map from cell
* (@a x1, @a y1) to cell (@a x2, @a y2). For allowed values see
* the documentation of class MapStoreBeam. It checks if the
* supplied coordinates are within the map and throws an exception
* of type MapStoreError::Range if not.
*
* The created iterator has a dependency to this map. The map
* may not be destroyed while this iterator exists. Modifying
* the map (including growing it) is fine.
*
* @param x1,y1 Start cells of beam. The beam originates at the
* center of the named cell.
*
* @param x2,y2 End cells of beam. The beam terminates at the
* center of the named cell.
*
*/
MapIt it(int x1, int y1, int x2, int y2) {
if ( isInX(x1) && isInX(x2) && isInY(y1) && isInY(y2) ) {
MapIt mi(x1, y1, x2, y2, *this);
return mi;
} else
throw MapStoreError(MapStoreError::Range);
}
/** Write the map content to the file @a fh in GnuPlot format.
*
* @param fh An open C-StdLib file handle. This can also be a
* process handle created using the Posix popen() function.
*
* @param title The title text to use in the gnuplot drawing.
*
* @sa startGPMultiplot(), commitGPMultiplot().
*/
void dumpGP(FILE *fh, const char *title) const;
/** Setup multiple plots on one GNUPlot page.
*
* This function sends GNUPlot commands to @a fh to configure
* GNUPlot for drawing up to @a numMaps maps in a grid on one
* sheet.
*
* @param fh An open C-StdLib file handle. This can also be a
* process handle created using the Posix popen() function.
*
* @param numMaps Number of maps to plot. Must be 2..4.
*
* @sa commitGPMultiplot()
*/
static void startGPMultiplot(FILE *fh, int numMaps);
/** Commit a series of at most n plots as specified with startGPMultiplot.
*
* This function ends a series of map plots which are drawn on the
* same sheet. At most as many plots as specified by the numMaps
* parameter of startGPMultiplot maps can be commited. If more
* maps have been send to the file @a fh, then gnulpot may abort.
* Sending less maps then announced with startGPMultiplot is fine.
*
* Example:
* @code
* MapStore map1(size_X, sizeY), map2(size_X, sizeY), map3(size_X, sizeY);
*
* FILE *myFH = fopen("mapdata.txt","w");
*
* while(run_loop) {
* // process sensor data
*
* // update map
*
* // decide if we should log the map
* if (time_to_dump_map) {
* MapStore::startGPMultiplot(myFH, 3);
* map1.dumpGP(myFH, "first map");
* map2.dumpGP(myFH, "next map");
* map3.dumpGP(myFH, "yet another map");
* MapStore::commitGPMultiplot(myFH);
* }
* }
* @endcode
*
* @param fh An open C-StdLib file handle. This can also be a
* process handle created using the Posix popen() function.
*/
static void commitGPMultiplot(FILE *fh);
/** Create GNUPlot child process.
*
* This function creates a child process running GNUPlot, which
* can be used as a file for writing map data. Use in conjunction
* with dumpGP() and/or startGPMultiplot().
*
* Example:
* @code
* MapStore map1(size_X, sizeY);
*
* FILE *myFH = MapStore::startGP();
*
* while(run_loop) {
* // process sensor data
*
* // update map
*
* // decide if we should log the map
* if (time_to_dump_map) {
* map1.dumpGP(myFH, "first map");
*
* // to plot multiple maps on one sheet,
* // see commitGPMultiplot() example.
* }
* }
* @endcode
*
* @return C-StdLib file handle, opened for writing, connected to
* GNUPlot. This @em must be closed using stopGP()! I t can
* @em not be closed by simply calling fclose().
*
*/
static FILE *startGP(void);
/** Disconnect from a GNUPlot child process.
*
* This function closes the link to a GNUPlot child process,
* causing GNUPlot to terminate.
*
* @param fh A file handle connected to a GNUPlot process. This
* @em must be opened by a call to startGP().
*/
static void stopGP(FILE *fh);
/** Dump a double-array in a gnuplot compatible way.
*
* This function creates a gnuplot dump from the map data
* starting at @a data. The map data is assumed to be a double
* array of sizeX columns and sizeY rows. The flag rowMajor
* (defaults to true) determines if the map dat is stored in
* rowMajor mode (all columns of the first row follow directly
* after eachother, then all columns from the second row etc.)
* or in column major mode.
*
* @param fh An open C-StdLib file handle.
*
* @param title The title text to use in the gnuplot drawing.
*
* @param data Address of the double array holding the actual map
* data. Note that this function assumes a flat array, that is
* all cells follow one after the other. It does @em not work
* with a pointer array, i.e. somthing that can be addresed by
* the data[x][y] notation!
*
* @param sizeX Number of columns of the map data array.
*
* @param sizeY Number of rows of the map data array.
*
* @param rowMajor Flag if the data is organized by rows (all
* columns of the first row after eachother,then all columns of
* the second row etc.) or in column major mode. If true, the
* rowMajor mode is assumed.
*/
static void dumpDoubleToGP(FILE *fh, const char *title, double *data, int sizeX, int sizeY, bool rowMajor = true);
private:
// disable constructors and operators
MapStore();
MapStore(const MapStore &old);
MapStore &operator=(const MapStore &old);
/* The following private methods are documented in the
implementation file. */
bool convX(int &x) const;
bool convY(int &y) const;
void convXRange(int &x, int &dx) const;
void convYRange(int &y, int &dy) const;
int makeIdx(const int x, const int y) const;
void internalFillRect(int x, int y, int dx, int dy, double val);
int sizeX;
int sizeY;
int originX;
int originY;
double resolution;
int maxIdx;
double *data;
};
} // closes namespace mapstore
#endif // MAP_STORE_H
|
JavaScript | UTF-8 | 1,704 | 2.671875 | 3 | [
"MIT"
] | permissive | const DAO = require("../../lib/dao");
const mySQLWrapper = require("../../lib/mysqlWrapper");
class User extends DAO {
/**
* Overrides TABLE_NAME with this class' backing table at MySQL
*/
static get TABLE_NAME() {
return "users";
}
/**
* Returns a user by its ID
*/
static async getByID(_, { id }) {
return await this.find(id);
}
/**
* Returns a list of users matching the passed fields
* @param {*} fields - Fields to be matched
*/
static async findMatching(_, fields) {
// Returns early with all users if no criteria was passed
if (Object.keys(fields).length === 0) return this.findAll();
// Find matching users
return this.findByFields({
fields,
});
}
/**
* Creates a new user
*/
static async createEntry(_, { name, email, password }) {
const connection = await mySQLWrapper.getConnectionFromPool();
try {
let _result = await this.insert(connection, {
data: {
name,
email,
password,
},
});
return this.getByID(_, { id: _result.insertId });
} finally {
// Releases the connection
if (connection != null) connection.release();
}
}
/**
* Updates a user
*/
static async updateEntry(_, { id, name, email, password }) {
const connection = await mySQLWrapper.getConnectionFromPool();
try {
await this.update(connection, {
id,
data: {
name,
email,
password
},
});
return this.getByID(_, { id });
} finally {
// Releases the connection
if (connection != null) connection.release();
}
}
}
module.exports = User;
|
Java | UTF-8 | 1,409 | 2.9375 | 3 | [] | no_license | package forRank;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.StringTokenizer;
public class Q5533 {
private static final int ROUND = 3;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int n = Integer.parseInt(br.readLine());
int submmitedScores[][] = new int[n][ROUND];
int playerScore[] = new int[n];
HashMap<Integer, Boolean> hm;
for (int i = 0; i < n; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
for (int j = 0; j < ROUND; j++)
submmitedScores[i][j] = Integer.parseInt(st.nextToken());
}
for (int i = 0; i < ROUND; i++) {
hm = new HashMap<Integer, Boolean>();
for (int j = 0; j < n; j++) {
hm.computeIfPresent(submmitedScores[j][i], (Integer key, Boolean value) -> false);
hm.putIfAbsent(submmitedScores[j][i], true);
}
for (int j = 0; j < n; j++) {
if(hm.get(submmitedScores[j][i]))
playerScore[j] += submmitedScores[j][i];
}
}
for (int i = 0; i < n; i++)
bw.write(playerScore[i] + "\n");
br.close();
bw.close();
}
}
|
Markdown | UTF-8 | 3,635 | 4.09375 | 4 | [] | no_license | ## 正则-模式-学习笔记
### 正则模式
+ 贪婪匹配
+ 非贪婪匹配
+ 独占模式
贪婪模式,简单说就是尽可能进行最长匹配。非贪婪模式呢,则会尽可能进行最短匹配。
### 贪婪模式
在正则中,表示次数的量词默认是贪婪的,在贪婪模式下,会尝试尽可能最大长度去匹配。
使用`+`的正则匹配
```python
# 使用+号的正则贪婪(默认),只匹配到一个匹配项
>>> import re
>>> re.findall(r'a+', 'aaabb')
['aaa']
# 下面是*好的正则贪婪(默认),匹配到4个(包含三个空串),如下图
>>> import re
>>> re.findall(r'a*', 'aaabb')
['aaa', '', '', '']
```

### 非贪婪模式
在量词后面加上英文的问号 `?`,正则就变成了非贪婪模式,如下
```python
>>> import re
>>> re.findall(r'a*', 'aaabb') # 贪婪模式
['aaa', '', '', '']
>>> re.findall(r'a*?', 'aaabb') # 非贪婪模式
['', 'a', '', 'a', '', 'a', '', '', '']
```
### 独占模式
独占模式会尽可能多地去匹配,如果匹配失败就结束,不会进行回溯,这样的话就比较节省时间。具体的方法就是在量词后面加上加号`+`
#### 回溯
**贪婪的回溯**
例如下面的正则:
```python
regex = “xy{1,3}z”
text = “xyyz”
```
在匹配时,y{1,3}会尽可能长地去匹配,当匹配完 xyy 后,由于 y 要尽可能匹配最长,即三个,但字符串中后面是个 z 就会导致匹配不上,这时候正则就会向前回溯,吐出当前字符 z,接着用正则中的 z 去匹配。

**非贪婪的回溯**
```python
regex = “xy{1,3}?z”
text = “xyyz”
```
由于 y{1,3}? 代表匹配 1 到 3 个 y,尽可能少地匹配。匹配上一个 y 之后,也就是在匹配上 text 中的 xy 后,正则会使用 z 和 text 中的 xy 后面的 y 比较,发现正则 z 和 y 不匹配,这时正则就会向前回溯,重新查看 y 匹配两个的情况,匹配上正则中的 xyy,然后再用 z 去匹配 text 中的 z,匹配成功。

**独占模式**
```python
# 注意:需要先安装 regex 模块,pip install regex
>>> import regex
>>> regex.findall(r'xy{1,3}z', 'xyyz') # 贪婪模式
['xyyz']
>>> regex.findall(r'xy{1,3}+z', 'xyyz') # 独占模式
['xyyz']
>>> regex.findall(r'xy{1,2}+yz', 'xyyz') # 独占模式
[]
```

如果只是判断文本是否符合规则,则可以使用独占模式; 如果需要获取匹配的结果,则根据需要使用贪婪或非贪婪。
### 思考题
we found “the little cat” is in the hat, we like “the little cat”
其中 the little cat 需要看成一个单词,现在你需要提取出文章中所有的单词。
```python
# 简单讲正则就是 \w+|“[^”]+”
>>> import re
>>> text = '''we found “the little cat” is in the hat, we like “the little cat”''' # 注意: 例句中的双引号是中文状态下的
>>> pattern = re.compile(r'''\w+|“[^”]+”''')
>>> pattern.findall(text)
['we', 'found', '"the little cat"', 'is', 'in', 'the', 'hat', 'we', 'like', '"the little cat"']
```
### 工具网站
[正则问题检查](https://regex101.com/)
 |
Java | UTF-8 | 3,964 | 2.34375 | 2 | [] | no_license | package com.julibo.demo.sb2x.controller;
import com.github.pagehelper.PageInfo;
import com.julibo.demo.sb2x.exception.CustomException;
import com.julibo.demo.sb2x.model.StudentModel;
import com.julibo.demo.sb2x.service.StudentService;
import com.julibo.demo.sb2x.vo.StudentVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import com.battcn.swagger.properties.ApiDataType;
import com.battcn.swagger.properties.ApiParamType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @author carson
* @date 2019-11-25
*/
@RestController
@RequestMapping("/student")
@Api(tags = "0.0.1", value = "用户管理")
public class StudentController {
Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private StudentService studentService;
@GetMapping("/page")
@ApiOperation(value = "分页查询")
@ApiImplicitParams({
@ApiImplicitParam(name = "pageNum", value = "页码", dataType = ApiDataType.INT, paramType = ApiParamType.QUERY),
@ApiImplicitParam(name = "pageSize", value = "条数", dataType = ApiDataType.INT, paramType = ApiParamType.QUERY),
})
public PageInfo<StudentVo> getStudentPage(
@RequestParam(name = "pageNum", required = false, defaultValue = "1") int pageNum,
@RequestParam(name = "pageSize", required = false, defaultValue = "10") int pageSize
) {
return studentService.selectPage(pageNum, pageSize);
}
@GetMapping("")
public ResponseEntity getStudents() {
return ResponseEntity.ok(studentService.selectAll());
}
@PostMapping("")
public ResponseEntity addUser(
@RequestParam(value = "name") String name,
@RequestParam(value = "code") String code,
@RequestParam(value = "sex") Integer sex,
@RequestParam(value = "birthday") Date birthday,
@RequestParam(value = "village") String village,
@RequestParam(value = "remark", required = false) String remark
)
{
StudentModel studentModel = new StudentModel();
studentModel.setName(name);
studentModel.setCode(code);
studentModel.setSex(sex);
studentModel.setBirthday(birthday);
studentModel.setVillage(village);
studentModel.setRemark(remark);
studentService.insert(studentModel);
return ResponseEntity.ok("添加成功");
}
@GetMapping("/log")
public ResponseEntity logging() {
// 级别由低到高 trace<debug<info<warn<error
logger.trace("这是一个trace日志...");
logger.debug("这是一个debug日志...");
// SpringBoot默认是info级别,只会输出info及以上级别的日志
logger.info("这是一个info日志...");
logger.warn("这是一个warn日志...");
logger.error("这是一个error日志...");
return ResponseEntity.ok("日志配置");
}
@GetMapping("/test1")
public String test1() {
// TODO 这里只是模拟异常,假设业务处理的时候出现错误了,或者空指针了等等...
int i = 10 / 0;
return "test1";
}
@GetMapping("/test2")
public Map<String, String> test2() {
Map<String, String> result = new HashMap<>(16);
// TODO 直接捕获所有代码块,然后在 cache
try {
int i = 10 / 0;
result.put("code", "200");
result.put("data", "具体返回的结果集");
} catch (Exception e) {
throw new CustomException(500, "请求错误");
}
return result;
}
}
|
Python | UTF-8 | 1,582 | 4.25 | 4 | [] | no_license | """
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
Approach
______________
Two Pointers
+++++++++++++++
Start from the end
while index1 >=0 or index2 >=0 or carry:
maintain
new_node = cur1 + cur2 + carry %2
carry = carry + cur1 + cur2 /2
Complexity
_______________
Time - O(N)
Space - O(N)
"""
# class Solution(object):
# def addBinary(self, a, b):
# """
# :type a: str
# :type b: str
# :rtype: str
# """
# return self.tento2(self.twoto10(a) + self.twoto10(b))
# def twoto10(self,n):
# base = 1
# s = 0
# for i in xrange(len(n)-1,-1,-1):
# s += int(n[i]) * base
# base *= 2
# return s
# def tento2(self,n):
# if n == 0:
# return '0'
# if n == 1:
# return '1'
# return self.tento2(n/2) + str(n%2)
class Solution:
# @param {string} a a number
# @param {string} b a number
# @return {string} the result
def addBinary(self, a, b):
indexa = len(a) - 1
indexb = len(b) - 1
carry = 0
sum = ""
while indexa >= 0 or indexb >=0 or carry:
x = int(a[indexa]) if indexa >= 0 else 0
y = int(b[indexb]) if indexb >= 0 else 0
if (x + y + carry) % 2 == 0:
sum = '0' + sum
else:
sum = '1' + sum
carry = (x + y + carry) / 2
indexa, indexb = indexa - 1, indexb - 1
return sum
|
TypeScript | UTF-8 | 1,612 | 2.671875 | 3 | [
"MIT"
] | permissive | const { When, Then } = require('cucumber');
const { expect } = require('chai');
import { ViewerPage } from './../pages/viewer.po';
const page = new ViewerPage();
When(
'the user swipe {string} and the velocity is between {string}',
async (direction: string, velocity: string) => {
if (direction === 'left-to-right') {
const start = {
x: 200,
y: 0,
};
const end = {
x: 0,
y: 0,
};
await page.swipe(start, end);
}
}
);
When(
'the user swipe {string} and the velocity is equal or greater than {string}',
async (direction: string, velocity: string) => {
return 'pending';
}
);
When(
'the user swipe {string} but the velocity is less than {string}',
async (direction: string, velocity: string) => {
return 'pending';
}
);
When(
'the user drags the page slider to page {int}',
async (canvasGroupIndex: number) => {
await page.slideToCanvasGroup(canvasGroupIndex - 1);
}
);
When(
'the user enters {int} in the page dialog',
async (canvasGroupIndex: number) => {
await page.goToCanvasGroupWithDialog(canvasGroupIndex);
}
);
Then('page {word} is displayed', async (canvasGroupIndex: string) => {
const currentCanvasGroupString = await page.getCurrentCanvasGroupLabel();
expect(currentCanvasGroupString.includes(canvasGroupIndex)).to.eql(true);
});
When('the user click the {word} button', async (navigationButton: string) => {
if (navigationButton === 'next') {
await page.clickNextButton();
} else if (navigationButton === 'previous') {
await page.clickPreviousButton();
}
});
|
Java | UTF-8 | 336 | 1.867188 | 2 | [] | no_license | package com.mallproject.generator.dao;
import com.mallproject.generator.domain.TbBrand;
import java.util.List;
public interface TbBrandMapper {
int deleteByPrimaryKey(Long id);
int insert(TbBrand record);
TbBrand selectByPrimaryKey(Long id);
List<TbBrand> selectAll();
int updateByPrimaryKey(TbBrand record);
} |
PHP | UTF-8 | 4,923 | 2.6875 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: sOxOs
* Date: 2014/12/19
* Time: 15:24
* Packed from alipay_core
*/
namespace Common\Lib\Alipay;
class AlipayCore
{
/**
* Convert parameter array into URL parameter
* @param $params array Array with key and value
* @return string Key-Value Pair in URL form
*/
public static function LinkUrlParameters($params)
{
$urlParams = "";
while (list ($key, $val) = each($params)) {
$urlParams .= $key . "=" . $val . "&";
}
$urlParams = substr($urlParams, 0, count($urlParams) - 2);
if (get_magic_quotes_gpc()) $urlParams = stripslashes($urlParams);
return $urlParams;
}
/**
* Convert parameter array into URL parameter
* @param $params array Array with key and value
* @return string Key-Encoded Value Pair in URL form
*/
public static function LinkEncodedUrlParameters($params)
{
$urlParams = "";
while (list ($key, $val) = each($params)) {
$urlParams .= $key . "=" . urlencode($val) . "&";
}
$urlParams = substr($urlParams, 0, count($urlParams) - 2);
if (get_magic_quotes_gpc()) $urlParams = stripslashes($urlParams);
return $urlParams;
}
/**
* Filter EMPTY value and sign in parameters
* @param $params array Array with key and encoded value
* @return array Parameters without EMPTY
*/
public static function FilterParameters($params)
{
$filteredParams = array();
while (list ($key, $value) = each($params)) {
if ($key == "sign" || $key == "sign_type" || $key == "s" || $value == "") continue;
else $filteredParams[$key] = $params[$key];
}
return $filteredParams;
}
/**
* Sort array by key
* @param $arr array Array need to be sort
* @return array Sorted array
*/
public static function SortArray($arr)
{
ksort($arr);
return $arr;
}
/**
* HTTP Post
* @param $url string POST url
* @param $sslCert string SSL Cert
* @param $postData array POST data
* @param $sourceEncode string Submit encoding (Default=Empty String)
* @return string HTTP server response
*/
public static function postUrl($url, $sslCert, $postData, $sourceEncode = '')
{
if (trim($sourceEncode) != '') $url = $url . "_input_charset=" . $sourceEncode;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($curl, CURLOPT_CAINFO, $sslCert);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
$responseText = curl_exec($curl);
curl_close($curl);
return $responseText;
}
/**
* HTTP Get
* @param $url string GET url
* @param $sslCert string SSL Cert
* @return string HTTP server response
*/
public static function getUrl($url, $sslCert)
{
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($curl, CURLOPT_CAINFO, $sslCert);
$responseText = curl_exec($curl);
curl_close($curl);
return $responseText;
}
/**
* Convert encoding
* @param $str string Raw string
* @param $sourceEncode string Source encoding
* @param $destEncode string Destination encoding
* @return string Encode converted string
*/
public static function encodingConvert($str, $sourceEncode, $destEncode)
{
$output = "";
if ($sourceEncode == $destEncode || $str == null)
$output = $str;
elseif (function_exists("mb_convert_encoding"))
$output = mb_convert_encoding($str, $destEncode, $sourceEncode);
elseif (function_exists("iconv"))
$output = iconv($sourceEncode, $destEncode, $str);
else return null;
return $output;
}
/**
* Sign with MD5
* @param $rawStr string String to sign
* @param $key string Signing key
* @return string Signed string
*/
public static function sign($rawStr, $key) {
return md5($rawStr . $key);
}
/**
* Verify MD5 signing
* @param $rawStr string String to sign
* @param $signedStr string Signed string
* @param $key string Signing key
* @return boolean Is valid or not
*/
public static function veritySign($rawStr, $signedStr, $key) {
$curSignedStr = md5($rawStr . $key);
return ($curSignedStr == $signedStr);
}
} |
C# | UTF-8 | 1,122 | 2.5625 | 3 | [
"MIT"
] | permissive | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace MS.Internal.Text.TextInterface
{
// Compatibility warning:
/************************/
// This enum has a mirror enum CSharp\System\Windows\Media\StyleSimulations.cs
// If any changes happens to FontSimulation they should be reflected
// in StyleSimulations.cs
/// <summary>
/// Specifies algorithmic style simulations to be applied to the font face.
/// Bold and oblique simulations can be combined via bitwise OR operation.
/// </summary>
[Flags]
public enum FontSimulations
{
/// <summary>
/// No simulations are performed.
/// </summary>
None = 0x0000,
/// <summary>
/// Algorithmic emboldening is performed.
/// </summary>
Bold = 0x0001,
/// <summary>
/// Algorithmic italicization is performed.
/// </summary>
Oblique = 0x0002
}
}
|
Java | UTF-8 | 3,316 | 2.265625 | 2 | [] | 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.
*/
package project.lavanderia.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import project.lavanderia.entity.Pelanggan;
import project.lavanderia.error.pelangganException;
import project.lavanderia.service.PelangganDao;
/**
*
* @author Dean
*/
public class PelangganDaoImpl implements PelangganDao{
private Connection connection;
private final String insertPelanggan = "INSERT INTO PELANGGAN"
+ " (NAMA, TANGGAL, ALAMAT, TELP, JENIS, BERAT, HARGA) VALUES"
+ " (?,?,?,?,?,?,?)";
public PelangganDaoImpl(Connection connection) {
this.connection = connection;
}
@Override
public void insertPelanggan(Pelanggan pelanggan) throws pelangganException {
PreparedStatement statement = null;
try {
connection.setAutoCommit(false);
statement = connection.prepareStatement(insertPelanggan);
statement.setString(1, pelanggan.getNama());
statement.setString(2, pelanggan.getTanggal());
statement.setString(3, pelanggan.getAlamat());
statement.setString(4, pelanggan.getTelp());
statement.setString(5, pelanggan.getJenis());
statement.setDouble(6, pelanggan.getBerat());
statement.setDouble(7, pelanggan.getHarga());
statement.executeUpdate();
connection.commit();
} catch (SQLException e) {
try {
connection.rollback();
} catch (SQLException ex) {
}
throw new pelangganException(e.getMessage());
} finally {
try {
connection.setAutoCommit(true);
} catch (SQLException ex) {
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e){
}
}
}
}
@Override
public List<Pelanggan> selectAllPelanggan() throws pelangganException {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void updatePelanggan(Pelanggan pelanggan) throws pelangganException {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void deletePelanggan(Integer id) throws pelangganException {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void getPelanggan(Integer id) throws pelangganException {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
|
Java | UTF-8 | 1,498 | 2.4375 | 2 | [] | no_license | package com.bdcom.bean.ncimport;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* @author Jianan
* @Date
*/
public class NCImpHeader {
Long id;
String ncOrg = "01"; //库存组织
String impDate;
String kb; //库别
String type = "40-01";
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNcOrg() {
return ncOrg;
}
public void setNcOrg(String ncOrg) {
this.ncOrg = ncOrg;
}
public String getImpDate() {
return impDate;
}
public void setImpDate(String impDate) {
this.impDate = impDate;
}
public String getKb() {
return kb;
}
public void setKb(String kb) {
this.kb = kb;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
static Map<String, NCImpHeader> orgKbToHeader = new HashMap<String, NCImpHeader>();
public static NCImpHeader getHeader(String orgNo, String kbNo){
String key = orgNo + kbNo;
NCImpHeader header = orgKbToHeader.get(key);
if(header == null){
header = new NCImpHeader();
header.setNcOrg(orgNo);
header.setKb(kbNo);
orgKbToHeader.put(key, header);
}
return header;
}
public static void main(String[] args){
Set<NCImpHeader> set = new HashSet<NCImpHeader>();
set.add(getHeader("01", "86"));
set.add(getHeader("01", "86"));
set.add(getHeader("01", "86"));
set.add(getHeader("01", "30"));
System.out.println(set.size());
}
}
|
C++ | UHC | 544 | 2.875 | 3 | [] | no_license |
#include "PlayerUnit.h"
#include "Bullet.h"
PlayerUnit player;
extern Bullet bulletArr[BULLET_COUNT];
void SetPlayerPos(UINT x, UINT y)
{
player.posX = x;
player.posY = y;
}
void PlayerShoot()
{
// Ⱦ̴ Ѿ ã
bool bfoundBullet = false;
for (size_t i = 0; i < BULLET_COUNT; i++)
{
if (bulletArr[i].isAlive == false)
{
bfoundBullet = true;
bulletArr[i].isAlive = true;
bulletArr[i].type = PlayerBullet;
bulletArr[i].posX = player.posX;
bulletArr[i].posY = player.posY;
return;
}
}
} |
Markdown | UTF-8 | 72 | 2.59375 | 3 | [] | no_license | # angular-custom-webpack
Example project for configuring custom webpack
|
Java | UTF-8 | 4,279 | 2.671875 | 3 | [] | no_license | package com.Diamond.Finder.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import com.Diamond.Finder.GameMap.TilesMap;
import com.Diamond.Finder.States.Content;
public class MistStudent extends Entity {
private BufferedImage[] downSprites;
private BufferedImage[] leftSprites;
private BufferedImage[] rightSprites;
private BufferedImage[] upSprites;
private BufferedImage[] downBoatSprites;
private BufferedImage[] leftBoatSprites;
private BufferedImage[] rightBoatSprites;
private BufferedImage[] upBoatSprites;
private final int DOWN = 0;
private final int LEFT = 1;
private final int RIGHT = 2;
private final int UP = 3;
private final int DOWNBOAT = 4;
private final int LEFTBOAT = 5;
private final int RIGHTBOAT = 6;
private final int UPBOAT = 7;
private int numDiamonds;
private int totalDiamonds;
private boolean hasBoat;
private boolean hasAxe;
private boolean onWater;
private long ticks;
public MistStudent(TilesMap tm) {
super(tm);
width = 16;
height = 16;
cwidth = 12;
cheight = 12;
moveSpeed = 2;
numDiamonds = 0;
downSprites = Content.PLAYER[0];
leftSprites = Content.PLAYER[1];
rightSprites = Content.PLAYER[2];
upSprites = Content.PLAYER[3];
downBoatSprites = Content.PLAYER[4];
leftBoatSprites = Content.PLAYER[5];
rightBoatSprites = Content.PLAYER[6];
upBoatSprites = Content.PLAYER[7];
animation.loadImages(downSprites);
animation.setDelay(10);
}
private void setAnimation(int i, BufferedImage[] bi, int d) {
currentAnimation = i;
animation.loadImages(bi);
animation.setDelay(d);
}
public void collectedDiamond() {
numDiamonds++;
}
public int numDiamonds() {
return numDiamonds;
}
public int getTotalDiamonds() {
return totalDiamonds;
}
public void setTotalDiamonds(int i) {
totalDiamonds = i;
}
public void gotBoat() {
hasBoat = true;
tileMap.replace(22, 4);
}
public void gotAxe() {
hasAxe = true;
}
public boolean hasBoat() {
return hasBoat;
}
public boolean hasAxe() {
return hasAxe;
}
public long getTicks() {
return ticks;
}
@Override
public void setDown() {
super.setDown();
}
@Override
public void setLeft() {
super.setLeft();
}
@Override
public void setRight() {
super.setRight();
}
@Override
public void setUp() {
super.setUp();
}
public void setAction() {
if (hasAxe) {
if (currentAnimation == UP && tileMap.getIndex(rowTile - 1, colTile) == 21) {
tileMap.setTile(rowTile - 1, colTile, 1);
// JukeBox.play("tilechange");
}
if (currentAnimation == DOWN && tileMap.getIndex(rowTile + 1, colTile) == 21) {
tileMap.setTile(rowTile + 1, colTile, 1);
// JukeBox.play("tilechange");
}
if (currentAnimation == LEFT && tileMap.getIndex(rowTile, colTile - 1) == 21) {
tileMap.setTile(rowTile, colTile - 1, 1);
// JukeBox.play("tilechange");
}
if (currentAnimation == RIGHT && tileMap.getIndex(rowTile, colTile + 1) == 21) {
tileMap.setTile(rowTile, colTile + 1, 1);
// JukeBox.play("tilechange");
}
}
}
@Override
public void update() {
ticks++;
boolean current = onWater;
if (tileMap.getIndex(ydest / tileSize, xdest / tileSize) == 4) {
onWater = true;
} else {
onWater = false;
}
if (!current && onWater) {
// JukeBox.play("splash");
}
if (down) {
if (onWater && currentAnimation != DOWNBOAT) {
setAnimation(DOWNBOAT, downBoatSprites, 10);
} else if (!onWater && currentAnimation != DOWN) {
setAnimation(DOWN, downSprites, 10);
}
}
if (left) {
if (onWater && currentAnimation != LEFTBOAT) {
setAnimation(LEFTBOAT, leftBoatSprites, 10);
} else if (!onWater && currentAnimation != LEFT) {
setAnimation(LEFT, leftSprites, 10);
}
}
if (right) {
if (onWater && currentAnimation != RIGHTBOAT) {
setAnimation(RIGHTBOAT, rightBoatSprites, 10);
} else if (!onWater && currentAnimation != RIGHT) {
setAnimation(RIGHT, rightSprites, 10);
}
}
if (up) {
if (onWater && currentAnimation != UPBOAT) {
setAnimation(UPBOAT, upBoatSprites, 10);
} else if (!onWater && currentAnimation != UP) {
setAnimation(UP, upSprites, 10);
}
}
super.update();
}
@Override
public void draw(Graphics2D g) {
super.draw(g);
}
}
|
PHP | UTF-8 | 1,306 | 2.5625 | 3 | [] | no_license | <?php
//Insert Header
require('header.php');
?>
<div class="row">
<div class="two columns">
<a class="button" href="add-recipe.php">Add Recipe</a>
</div>
</div>
<table class="u-full-width recipeList">
<thead>
<tr>
<th>Recipe</th>
<th>Prep Time</th>
<th>Cook Time</th>
<th>Level</th>
</tr>
</thead>
<tbody>
<?php
$document_root = $_SERVER['DOCUMENT_ROOT'];
$filepath = join(DIRECTORY_SEPARATOR, array($document_root, "IAT352", "A1", "recipes", "recipes.txt"));
if (!file_exists($filepath)) {
require('header.php');
echo "<strong>Recipe File Not Found.</strong>";
require('footer.php');
exit;
}
$fp = @fopen($filepath,"r");
if(!$fp) {
require('header.php');
echo "<strong>Unable to load Recipes. Please try again later.</strong>";
require('footer.php');
exit;
}
while ($entry = fgetcsv($fp)) {
$recipeURL = "details.php" . '?id=' . $entry[0];
echo "<tr>";
echo "<td><a href=\"./$recipeURL\">". $entry[1] ."</a></td>";
echo "<td>" . $entry[5] . " " . $entry[6] ."</td>";
echo "<td>" . $entry[7] . " " . $entry[8] ."</td>";
echo "<td>" . $entry[10] . "</td>";
echo "</tr>";
}
?>
</tbody>
</table>
<?php
//Insert Footer
require('footer.php');
?>
|
Java | UTF-8 | 703 | 1.703125 | 2 | [
"Apache-2.0"
] | permissive | package wang.ismy.blb.aggregation;
import com.spring4all.swagger.EnableSwagger2Doc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan;
/**
* @author MY
* @date 2020/5/18 9:03
*/
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@ComponentScan("wang.ismy.blb")
@EnableSwagger2Doc
public class SellerAggApp {
public static void main(String[] args) {
SpringApplication.run(SellerAggApp.class,args);
}
}
|
Markdown | UTF-8 | 423 | 2.8125 | 3 | [] | no_license | >现在每个我遇见的笑着的人,他们都不曾因为苦而放弃,他们只因扛而成长。
>
>谁不希望自己活得轻松,没有压力,一切随性,但如果你真的那样去做的话,你会发现这个世界都在和你作对。
>
>如果有一天你真的觉得自己轻松了,那也不是因为生活越来越容易了,而是因为我们越来越坚强。
>
——《谁的青春不迷茫》 |
Markdown | UTF-8 | 1,361 | 2.890625 | 3 | [
"WTFPL"
] | permissive | # One Saying Generator
A small Python program generating text as images
## What is One Saying Generator?
This is a simple python 3 program helping you generate text as images. By doing that,
you are allowed to publish beautiful texts in your wechat website.
After running it, input the texts you want to generate like this:

And then you will get a jpeg picture named as out.jpg like:

## How to Run it?
To run it, you just need to install the following software packages:
> [Python 3.5.2 for Windows](https://www.python.org/downloads/)
>
> [CTeX Packages](http://www.ctex.org/CTeXDownload)
>
> [imagemagick for Windows](http://www.imagemagick.org/script/binary-releases.php)
After successful installation of all the softwares above, you can run this gadget freely.
## Will I get any problem?
Of course you might get into trouble unexpectedly. One problem is that I cannot call the xelatex successfully by double click py file. The xelatex log showed that there were something wrong with the permission. But I can call the xelatex manually by using os.system() in IDLE. So I have to manually generate the pdf file by myself, and then run the py file again to generate jpg file. Maybe you can fix this bug.
## License
This program is with WTFPL License. For more info about that please refer to the LICENSE file.
|
C++ | UTF-8 | 1,342 | 2.59375 | 3 | [] | no_license | //
// CVHistogram.hpp
// OpenCV
//
// Created by aa on 16/10/12.
// Copyright © 2016年 yunlian. All rights reserved.
//
//
// 直方图
//
//
//
//
#ifndef CVHistogram_hpp
#define CVHistogram_hpp
#include <stdio.h>
#define k8BitMax 256
using namespace cv;
/*
* 处理灰度图的直方图
*/
class Histogram1D {
private:
//像素颜色个数 灰度图只取灰度值
int histSize[1];
//灰度值的最大和最小值
float histRange[2];
const float *ranges[1];
//仅用到一个通道
int channels[1];
public:
Histogram1D(){
histSize[0] = 256;
histRange[0] = 0.0;
histRange[1] = 255.0;
ranges[0] = histRange;
channels[0] = 0;
}
Mat getHistogram(Mat &image);
Mat getHistogramImage(Mat &image);
};
class HistogramRGB {
private:
int histSize[3];
float histRange[2];
const float *ranges[3];
int channels[3];
public:
HistogramRGB(){
histSize[0] = histSize[1] = histSize[2] = k8BitMax;
histRange[0] = 0.0;
histRange[1] = 255.0;
ranges[0] = histRange;
ranges[1] = histRange;
ranges[2] = histRange;
channels[0] = 0;
channels[1] = 1;
channels[2] = 2;
}
Mat getHistogram(Mat &image);
};
#endif /* CVHistogram_hpp */
|
C++ | UTF-8 | 609 | 2.890625 | 3 | [] | no_license | #ifndef HW_02_STDIOBOARDVIEW_H
#define HW_02_STDIOBOARDVIEW_H
#include "Board.h"
class StdioBoardView {
public:
StdioBoardView(Board &board) : board(board) {};
~StdioBoardView() = default;
/** Основной цикл игры, от начала до конца. */
void runGame();
// Можно добавлять методы при необходимости.
void setSilenceMode();
void printBoard();
bool readCell(int &x, int &y, Player cur_player);
private:
bool silence_mode = false;
Board &board;
};
#endif //HW_02_STDIOBOARDVIEW_H
|
Java | UTF-8 | 868 | 3.28125 | 3 | [] | no_license | /**
* This class holds the Full-time employee informations and calculates salary
* @author Ahmet ORUC
*
*/
public class FullTime extends Employee {
private double severancePay;
private double overWorkSalary;
private int weekNormalHour=40;
private int dayofWork = 20;
/**
* @param str informations of the line that is splitted by 'tab' character in the text file
*/
public FullTime(String[] str) {
super(str);
}
public double getSeverancePay() {
return severancePay;
}
public void setSeverancePay(double severancePay) {
this.severancePay = severancePay;
}
public double getOverWorkSalary() {
return overWorkSalary;
}
public void setOverWorkSalary(double overWorkSalary) {
this.overWorkSalary = overWorkSalary;
}
public int getWeekNormalHour() {
return weekNormalHour;
}
public int getDayofWork() {
return dayofWork;
}
}
|
Markdown | UTF-8 | 1,378 | 2.609375 | 3 | [] | no_license | # Article D422-53-9
A la fin de chaque exercice, l'agent comptable en fonctions prépare le compte financier de l'établissement pour l'exercice
écoulé.
Le compte financier comprend :
1° La balance définitive des comptes ;
2° Le développement des dépenses et des recettes budgétaires ;
3° Le tableau récapitulatif de l'exécution du budget ;
4° Les documents de synthèse comptable ;
5° La balance des comptes des valeurs inactives.
Le compte financier est visé par l'ordonnateur, qui certifie que le montant des ordres de dépenses et des ordres de recettes
est conforme à ses écritures.
Avant l'expiration du quatrième mois suivant la clôture de l'exercice, le conseil d'administration arrête le compte financier
après avoir entendu l'agent comptable ou son représentant et affecte le résultat.
Le compte financier accompagné éventuellement des observations du conseil d'administration et de celles de l'agent comptable
est transmis à l'autorité académique dans les trente jours suivant son adoption.
Avant l'expiration du sixième mois suivant la clôture de l'exercice, l'agent comptable adresse le compte financier et les
pièces annexes nécessaires au juge des comptes.
**Liens relatifs à cet article**
_Créé par_:
- Décret n°2017-1882 du 29 décembre 2017 - art. 6
_Cité par_:
- Code de l'éducation - art. D422-1 (V)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.