language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
Markdown
|
UTF-8
| 5,479 | 2.90625 | 3 |
[] |
no_license
|
---
title: Pengenalan Dasar tentang Lumen
date: 2018-01-07 12:14:49
tags: ['laravel','php']
draft: false
description: "Untuk mulai membuat RESTful API, Pengenalan Dasar tentang Lumen sangat perlu dan penting untuk dipelajari agar nantinya kita lebih mudah dalam membuat sebuah API service."
slug: pengenalan-dasar-tentang-lumen
---
Sebagai selingan kita dalam belajar Laravel, mari kita mengenal Lumen lebih jauh. Pengenalan dasar tentang Lumen perlu dan penting untuk diperhatikan bagi yang pengen belajar lebih jauh tentang lumen. Sebagai informasi, artikel ini juga sudah saya pakai untuk kuliah telegram di group Laravel Indonesia. Mari kita mulai ..
Bahasan pertama saya akan bahas sekilas tentang lumen. Apa sih lumen? lumen adalah microframework yang khusus menangani API service sama seperti Slim dan Silex. Lumen ini juga bisa dikatakan sebagai adik kecil nya laravel, jadi kalian inshallah pasti langsung paham dengan struktur dan cara mengimplementasikan lumen.
## WHY LUMEN ?
Sebelum menentukan framework PHP yang akan kita pakai, kita sebaiknya tentukan dulu teknologi dan sistem seperti apa yang akan kita bangun.
Jika web sederhana tanpa banyak melibatkan frontend framework JS misalnya, kita gunakan saja Laravel. Pakai Laravel dengan dipadukan frontend JS juga bisa, misalnya saja Vuejs yang udah include di fresh instalasi nya laravel. Jika web yang membedakan repository project, misalkan untuk backend pakai php, sedangkan frontend pakai full JS maka kita perlu yang namanya API. Bisa juga sih API kita pakai Laravel, tapi sangat disarankan untuk tidak memakai Laravel kalau hanya untuk kebutuhan API saja karena Laravel mempunyai banyak fitur, yang nantinya fitur fitur ini tidak terpakai karena kita hanya memanfaatkan API nya saja. So, kita perlu framework yang khusus untuk API.
Nah why lumen? Kenapa bukan yang lain misalnya Silex / Slim?? Sah sah saja kalau mau pakai selain lumen, tapi berdasarkan benchmark, Lumen lebih mantap daripada Slim. (Benchmark ya, bukan vote)
[https://www.gajotres.net/best-available-php-restful-micro-frameworks/](https://www.gajotres.net/best-available-php-restful-micro-frameworks/)
Karena disini yang di rekomendasikan adalah Slim, Lumen, Silex, Phalcon. Maka benchmark nya dibawah ini
[https://symfony.fi/entry/symfony-benchmarks-microkernel-silex-lumen-and-slim](https://symfony.fi/entry/symfony-benchmarks-microkernel-silex-lumen-and-slim)
## INSTALASI
untuk instalasi, gak perlu saya jelaskan panjang lebar. Hampir sama dengan instalasi laravel yang udah saya bahas di post awal tentang Laravel, disini
[https://nusendra.com/post/cara-install-laravel-melalui-composer](https://nusendra.com/post/cara-install-laravel-melalui-composer)
Cara instalasi nya sangat mudah
```
$ composer create-project --prefer-dist laravel/lumen blog
```
untuk running server nya kita ga bisa pakai php artisan serve, tapi pake built-in php dev server nya
```
$ php -S localhost:8000 -t public
```
## CONFIG DASAR
pada lumen fresh install, dia bener bener ringan. tapi jika kita pengen pake kekuatan yang ada di laravel (seperti eloquent, facades, middleware, dll) untuk dipakai di lumen, kita harus mengaktifkan nya di file `bootstrap/app.php`.
Uncomment baris kode dibawah ini
```php
$app->withFacades(); //untuk mengaktifkan fitur facade (sangat disarankan)
$app->withEloquent(); //untuk mengaktifkan fitur eloquent (optional)
$app->routeMiddleware([
'auth' => App\Http\Middleware\Authenticate::class,
]); //untuk mengaktifkan middleware di route (untuk auth)
$app->register(App\Providers\AppServiceProvider::class); //untuk memakai service provider
$app->register(App\Providers\AuthServiceProvider::class); //untuk auth
```
## COMPOSER : LARAVEL VS LUMEN
Ketika kalian mengetik php artisan di terminal, pada laravel akan muncul banyak opsi, sebaliknya di lumen kalian hanya akan menemukan sedikit. karena lumen ini lebih banyak menggunakan teknik manual daripada otomatisasi seperti di laravel. Jika di laravel kita bisa bikin model dan controller lewat artisan, di lumen kita ga bisa melakukan hal tersebut. So, di lumen kita harus create file nya manual.
## ROUTE DI LUMEN
Di Laravel, kita bisa mengetikkan route seperti ini
```php
Route::get('post','PostController@index');
```
atau dengan resource
```php
Route::resource('post','PostController');
```
tapi di Lumen 5.5 berbeda, seperti dibawah ini
```php
$router->get('post','PostController@index');
```
dan satu lagi, di lumen kita ga bisa pakai fitur resource..
## API VERSIONING DI LUMEN
Saya dulu gak paham dengan api versioning ini. Kebingungan ini merasuk ke dalam jiwa #lol ketika mencari perbedaan antara URI localhost/api/v1/post dengan localhost/post. Karena keduanya sama aja di response nya, gak ada perbedaan sama sekali. Lantas apa gunanya api version? akhirnya googling sendiri dan nemu artikel ini
[https://dzone.com/articles/rest-api-versioning-is-there-a-right-answer](https://dzone.com/articles/rest-api-versioning-is-there-a-right-answer)
Jadi ada 2 kondisi :
Jika api yang dibangun hanya untuk kebutuhan internal, maka kita tidak perlu api versioning Jika api kita merupakan public API yang mana kita gak bisa mengontroll di sisi client, maka kita perlu melakukan api versioning.
Silakan kunjungi artikel tersebut, baca di awal awal postingan saja. insyallah paham.
<hr/>
Nah segini dulu pembukaan untuk pembahasan dasar lumen. Semoga berguna bagi temen - temen yang mungkin mau coba nerapin RESTful API pakai Lumen..
|
Python
|
UTF-8
| 10,208 | 2.546875 | 3 |
[
"Apache-2.0"
] |
permissive
|
# Copyright 2021 Canonical Ltd.
#
# 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.
import os
import typing
from io import BytesIO, StringIO
from pathlib import Path
from tempfile import NamedTemporaryFile
class MockFilesystem:
def __init__(self):
self.root = Directory(Path('/'))
def create_dir(
self,
path: str,
make_parents: bool = False,
permissions: typing.Optional[int] = None,
user_id: typing.Optional[int] = None,
user: typing.Optional[str] = None,
group_id: typing.Optional[int] = None,
group: typing.Optional[str] = None,
) -> 'Directory':
if not path.startswith('/'):
raise ValueError('Path must start with slash')
current_dir = self.root
tokens = Path(path).parts[1:]
for token in tokens[:-1]:
if token in current_dir:
current_dir = current_dir[token]
else:
if make_parents:
current_dir = current_dir.create_dir(
token,
permissions=permissions,
user_id=user_id,
user=user,
group_id=group_id,
group=group)
else:
raise FileNotFoundError(str(current_dir.path / token))
# Current backend will always raise an error if the final directory component
# already exists.
token = tokens[-1]
if token not in current_dir:
current_dir = current_dir.create_dir(
token,
permissions=permissions,
user_id=user_id,
user=user,
group_id=group_id,
group=group)
else:
raise FileExistsError(str(current_dir.path / token))
return current_dir
def create_file(
self,
path: typing.Union[str, Path],
data: typing.Union[bytes, str, typing.BinaryIO, typing.TextIO],
permissions: typing.Optional[int] = None,
user_id: typing.Optional[int] = None,
user: typing.Optional[str] = None,
group_id: typing.Optional[int] = None,
group: typing.Optional[str] = None,
) -> 'File':
path = Path(path)
dir_ = self[path.parent]
return dir_.create_file(
path.name,
data,
permissions=permissions,
user_id=user_id,
user=user,
group_id=group_id,
group=group)
def list_dir(self, path) -> typing.List[str]:
current_dir = self.root
tokens = Path(path).parts[1:]
for token in tokens:
try:
current_dir = current_dir[token]
except KeyError:
raise FileNotFoundError(str(current_dir.path / token))
if isinstance(current_dir, File):
raise NotADirectoryError(str(current_dir.path))
if not isinstance(current_dir, Directory):
# For now, ignoring other possible cases besides File and Directory (e.g. Symlink).
raise NotImplementedError()
return [str(child.path) for child in current_dir]
def open(
self,
path: typing.Union[str, Path],
encoding: typing.Optional[str] = 'utf-8',
) -> typing.Union[typing.BinaryIO, typing.TextIO]:
path = Path(path)
file = self[path] # warning: no check re: directories
if isinstance(file, Directory):
raise IsADirectoryError(str(file.path))
return file.open(encoding=encoding)
def __getitem__(self, path: typing.Union[str, Path]) -> typing.Union['Directory', 'File']:
path = Path(path)
tokens = path.parts[1:]
current_object = self.root
for token in tokens:
# ASSUMPTION / TESTME: object might be file
if token in current_object:
current_object = current_object[token]
else:
raise FileNotFoundError(str(current_object.path / token))
return current_object
def __delitem__(self, path: typing.Union[str, Path]) -> None:
parent_dir: Directory = self[path.parent]
del parent_dir[path.name]
class Directory:
def __init__(
self,
path: Path,
permissions: typing.Optional[int] = None,
user_id: typing.Optional[int] = None,
user: typing.Optional[str] = None,
group_id: typing.Optional[int] = None,
group: typing.Optional[str] = None):
self.path = path
self._children: typing.Dict[str, typing.Union[Directory, File]] = {}
self.permissions = permissions
self.user = user
self.user_id = user_id
self.group = group
self.group_id = group_id
@property
def name(self) -> str:
return self.path.name
def __contains__(self, child: str) -> bool:
return child in self._children
def __iter__(self) -> typing.Iterator[typing.Union['File', 'Directory']]:
return (value for value in self._children.values())
def __getitem__(self, key: str) -> typing.Union['File', 'Directory']:
return self._children[key]
def __delitem__(self, key: str) -> None:
try:
del self._children[key]
except KeyError:
raise FileNotFoundError(str(self.path / key))
def create_dir(
self,
name: str,
permissions: typing.Optional[int] = None,
user_id: typing.Optional[int] = None,
user: typing.Optional[str] = None,
group_id: typing.Optional[int] = None,
group: typing.Optional[str] = None,
) -> 'Directory':
self._children[name] = Directory(
self.path / name,
permissions=permissions,
user_id=user_id,
user=user,
group_id=group_id,
group=group)
return self._children[name]
def create_file(
self,
name: str,
data: typing.Union[bytes, str, StringIO, BytesIO],
permissions: typing.Optional[int] = None,
user_id: typing.Optional[int] = None,
user: typing.Optional[str] = None,
group_id: typing.Optional[int] = None,
group: typing.Optional[str] = None,
) -> 'File':
self._children[name] = File(
self.path / name,
data,
permissions=permissions,
user_id=user_id,
user=user,
group_id=group_id,
group=group)
return self._children[name]
class File:
MAX_MEM_LENGTH = 102400
READ_BLOCK_SIZE = 102400
def __init__(
self,
path: Path,
data: typing.Union[str, bytes, StringIO, BytesIO],
permissions: typing.Optional[int] = None,
user_id: typing.Optional[int] = None,
user: typing.Optional[str] = None,
group_id: typing.Optional[int] = None,
group: typing.Optional[str] = None):
self.path = path
if isinstance(data, (StringIO, BytesIO)):
data = self._get_data_from_filelike_object(data)
else:
# Farm out to file if too large
if len(data) > File.MAX_MEM_LENGTH:
tf = NamedTemporaryFile(delete=False)
with tf:
if isinstance(data, str):
data = data.encode()
tf.write(data)
data = tf
self.data = data
self.permissions = permissions
self.user = user
self.user_id = user_id
self.group = group
self.group_id = group_id
def _get_data_from_filelike_object(self, data):
blocks = []
total_read = 0
temp: typing.Optional[NamedTemporaryFile] = None
while True:
block = data.read(File.READ_BLOCK_SIZE)
if len(block) == 0:
break
if isinstance(block, str):
block = block.encode()
if temp is not None:
temp.write(block)
else:
blocks.append(block)
total_read += len(block)
if total_read > File.MAX_MEM_LENGTH:
temp = NamedTemporaryFile(delete=False)
for queued_block in blocks:
temp.write(queued_block)
if temp:
# Tempfile not automatically closed; close it
temp.close()
data = temp
else:
data = b''.join(blocks)
return data
def open(
self,
encoding: typing.Optional[str] = 'utf-8',
) -> typing.Union[typing.TextIO, typing.BinaryIO]:
if hasattr(self.data, 'name'): # tempfile case
return open(self.data.name, encoding=encoding)
if encoding is None:
# binary mode; coerce string to utf-8 bytes if needed
return BytesIO(self.data if isinstance(self.data, bytes) else self.data.encode())
else:
# string mode; coerce bytes to string if needed. encoding ignored if already a string.
return StringIO(
self.data if isinstance(self.data, str)
else self.data.decode(encoding))
def __del__(self, unlink=os.unlink) -> None:
if hasattr(self.data, 'name'):
# This is a file-like object returned from NamedTemporaryFile; remove the tempfile.
unlink(self.data.name)
|
C++
|
UTF-8
| 1,484 | 3.765625 | 4 |
[] |
no_license
|
/*
1.6 Действительные числа. Шаг 11
Даны действительные коэффициенты a, b, c, при этом a ≠ 0 .
Решите квадратное уравнение ax2 + bx + c = 0 и выведите все его корни.
Формат входных данных:
Вводятся три действительных числа.
Формат выходных данных:
Если уравнение имеет два корня, выведите два корня в порядке возрастания,
если один корень — выведите одно число, если нет корней — не выводите ничего.
Sample Input: 1 -1 -2
Sample Output: -1 2
*/
#include <iostream>
#include <cmath>
int main() {
while (true) {
double a, b, c, D, x1, x2;
std::cin >> a >> b >> c;
D = b * b - 4 * a * c;
if (D >= 0) {
x1 = (-b + sqrt(D)) / (2 * a);
x2 = (-b - sqrt(D)) / (2 * a);
if (x2 < x1)
std::cout << x2 << " " << x1;
if (x1 < x2)
std::cout << x1 << " " << x2;
if (x1 == x2)
std::cout << x1;
}
/*при a≠0, уравнение можно привести к виду x^2+px+q=0. Его корни имеют вид −p/2±sqrt((p/2)^2−q)
b /= 2 * a;
c = b * b - c / a;
if (c == 0) {
cout << -b;
}
else if (c > 0) {
cout << -b - sqrt(c) << " " << -b + sqrt(c);*/
}
return 0;
}
|
Java
|
UTF-8
| 11,565 | 1.671875 | 2 |
[] |
no_license
|
package com.reconinstruments.connectdevice.ios;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LevelListDrawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.SystemClock;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.TextView;
import com.reconinstruments.connectdevice.BTPropertyReader;
import com.reconinstruments.connectdevice.ChooseDeviceActivity;
import com.reconinstruments.connectdevice.ConnectionActivity;
import com.reconinstruments.connectdevice.DisconnectDeviceActivity;
import com.reconinstruments.connectdevice.ConnectionActivity.DeviceType;
import com.reconinstruments.connectdevice.PreferencesUtils;
import com.reconinstruments.connectdevice.R;
import com.reconinstruments.connectdevice.ios.BtNotificationThirdActivity;
import com.reconinstruments.connectdevice.ios.FirstConnectActivity;
import com.reconinstruments.modlivemobile.bluetooth.BTCommon;
import com.reconinstruments.commonwidgets.TwoOptionsJumpFixer;
import com.reconinstruments.utils.DeviceUtils;
public class MfiReconnectActivity extends ConnectionActivity {
protected static final String TAG = "MfiReconnectActivity";
private boolean fails = false;
private ProgressDialog progressDialog;
private TextView titleTV;
private TextView textTV;
private View cancelItem;
private TwoOptionsJumpFixer twoOptionsJumpFixer;
private int tryAgainTimes = 0;
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.activity_reconnect_jet);
titleTV = (TextView) findViewById(R.id.title);
textTV = (TextView) findViewById(R.id.activity_disconnected_text);
Bundle extras = getIntent().getExtras();
fails = false;
if (extras != null) {
fails = extras.getBoolean("fails");
}
if(fails){
titleTV.setText("FAILED TO RECONNECT");
if(PreferencesUtils.getLastPairedDeviceType(MfiReconnectActivity.this) == 0){
textTV.setText(Html
.fromHtml("Open the Engage app on your Android phone and try again.\n"));
}else{
textTV
.setText
(Html
.fromHtml(
"Go to <b>Settings > Bluetooth</b> on your phone and ensure Bluetooth is  <img src=\"on_switch.png\" align=\"middle\"> Then try again.",
new ImageGetter() {
@Override
public Drawable getDrawable(String source) {
int id;
if (source
.equals("on_switch.png")) {
id = R.drawable.on_switch;
} else {
return null;
}
LevelListDrawable d = new LevelListDrawable();
Drawable empty = getResources()
.getDrawable(id);
d.addLevel(0, 0, empty);
d.setBounds(0, 0,
empty.getIntrinsicWidth(),
empty.getIntrinsicHeight());
return d;
}
}, null));
}
}else{
if(DeviceUtils.isLimo()){
textTV.setText(Html
.fromHtml("Your MOD Live was previously connected to <b>"
+ PreferencesUtils.getLastPairedDeviceName(this)
+ "</b>, Would you like to connect to this device again?"));
}else{
textTV.setText(Html
.fromHtml("Your Snow2 was previously connected to <b>"
+ PreferencesUtils.getLastPairedDeviceName(this)
+ "</b>, Would you like to connect to this device again?"));
}
}
final View disconnectItem = findViewById(R.id.disconnect);
cancelItem = findViewById(R.id.cancel);
if(fails){
((TextView)cancelItem).setText("TRY AGAIN");
}
disconnectItem.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
disconnectItem.setFocusable(false);
cancelItem.setFocusable(false);
progressDialog = new ProgressDialog(MfiReconnectActivity.this);
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
progressDialog.setContentView(com.reconinstruments.commonwidgets.R.layout.recon_progress);
TextView textTv = (TextView) progressDialog.findViewById(R.id.text);
textTv.setText("Unpairing, please wait...");
int deviceType = BTPropertyReader.getBTConnectedDeviceType(MfiReconnectActivity.this);
if(deviceType == 0){ // android device
if(hudService != null){
MfiReconnectActivity.this.disconnect(DeviceType.ANDROID);
}
}else{
//TODO do something extra for ios
if(hudService != null){
MfiReconnectActivity.this.disconnect(DeviceType.IOS);
}
}
new CountDownTimer(3 * 1000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
if(progressDialog != null && progressDialog.isShowing()){
progressDialog.dismiss();
}
unpairDevice();
PreferencesUtils.setLastPairedDeviceName(MfiReconnectActivity.this, "");
PreferencesUtils.setBTDeviceName(MfiReconnectActivity.this, "");
PreferencesUtils.setDeviceAddress(MfiReconnectActivity.this, "");
PreferencesUtils.setDeviceName(MfiReconnectActivity.this, "");
PreferencesUtils.setLastPairedDeviceAddress(MfiReconnectActivity.this, "");
PreferencesUtils.setLastPairedDeviceType(MfiReconnectActivity.this, 0);
PreferencesUtils.setReconnect(MfiReconnectActivity.this, false);
startActivity(new Intent(MfiReconnectActivity.this,ChooseDeviceActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_HISTORY));
finish();
}
}.start();
}
});
disconnectItem.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
TransitionDrawable transition = (TransitionDrawable) v
.getBackground();
if (hasFocus) {
transition.startTransition(300);
} else {
transition.resetTransition();
}
}
});
cancelItem.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
disconnectItem.setFocusable(false);
cancelItem.setFocusable(false);
// int deviceType = BTPropertyReader.getBTConnectedDeviceType(MfiReconnectActivity.this);
// if(deviceType == 0){ // android device
// }else{
if(hudService != null){
if(!DeviceUtils.isLimo()){
progressDialog = new ProgressDialog(MfiReconnectActivity.this);
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
progressDialog.setContentView(com.reconinstruments.commonwidgets.R.layout.recon_progress);
TextView textTv = (TextView) progressDialog.findViewById(R.id.text);
textTv.setText("Reconnecting, please wait...");
}
PreferencesUtils.setReconnect(MfiReconnectActivity.this, true);
if(PreferencesUtils.getLastPairedDeviceType(MfiReconnectActivity.this) == 1){
if(DeviceUtils.isLimo()){
Intent intent = new Intent(MfiReconnectActivity.this,
WaitingActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}else{
MfiReconnectActivity.this.connect(PreferencesUtils.getLastPairedDeviceAddress(MfiReconnectActivity.this), DeviceType.IOS);
}
}else{
// the following tryAgainTimes logic is to prevent the system from bad bluetooth state.
// BluetoothSocket.connect() will block until a connection is made or the connection fails according to SDK document.
// but sometimes it returns neither a connection nor an IOException and just block it on this method call
// the other components can't release the bluetooth resource any more unless restarting the bluetooth module or rebooting the device.
// thus we need an option to kill the HUDService and restart it completely. We think here is the better place.
if(tryAgainTimes > 1){
Log.d(TAG, "resarting hud service and then try to reconnect to the phone.");
tryAgainTimes = 0;
MfiReconnectActivity.this.killHUDService();
new CountDownTimer(1000, 1000) {
@Override
public void onFinish() {
MfiReconnectActivity.this.getApplicationContext().startService(new Intent("RECON_HUD_SERVICE"));
}
@Override
public void onTick(long millisUntilFinished) {
}
}.start();
new CountDownTimer(5000, 1000) {
@Override
public void onFinish() {
MfiReconnectActivity.this.connect(PreferencesUtils.getLastPairedDeviceAddress(MfiReconnectActivity.this), DeviceType.ANDROID);
}
@Override
public void onTick(long millisUntilFinished) {
}
}.start();
}else{
MfiReconnectActivity.this.connect(PreferencesUtils.getLastPairedDeviceAddress(MfiReconnectActivity.this), DeviceType.ANDROID);
}
}
new CountDownTimer(15 * 1000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
if(progressDialog != null){
progressDialog.dismiss();
}
fails = true;
if(PreferencesUtils.getLastPairedDeviceType(MfiReconnectActivity.this) == 1){
textTV.setText(Html
.fromHtml(
"Go to <b>Settings > Bluetooth</b> on your phone and ensure Bluetooth is  <img src=\"on_switch.png\" align=\"middle\"> Then try again.",
new ImageGetter() {
@Override
public Drawable getDrawable(String source) {
int id;
if (source
.equals("on_switch.png")) {
id = R.drawable.on_switch;
} else {
return null;
}
LevelListDrawable d = new LevelListDrawable();
Drawable empty = getResources()
.getDrawable(id);
d.addLevel(0, 0, empty);
d.setBounds(0, 0,
empty.getIntrinsicWidth(),
empty.getIntrinsicHeight());
return d;
}
}, null));
}else{
textTV.setText(Html
.fromHtml("Open the Engage app on your Android phone and try again.\n"));
}
((TextView)cancelItem).setText("TRY AGAIN");
twoOptionsJumpFixer = new TwoOptionsJumpFixer(disconnectItem, cancelItem);
twoOptionsJumpFixer.start();
tryAgainTimes ++;
}
}.start();
}
// }
// MfiReconnectActivity.this.finish();
}
});
cancelItem.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
TransitionDrawable transition = (TransitionDrawable) v
.getBackground();
if (hasFocus) {
transition.startTransition(300);
} else {
transition.resetTransition();
}
}
});
twoOptionsJumpFixer = new TwoOptionsJumpFixer(disconnectItem, cancelItem);
twoOptionsJumpFixer.start();
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
@Override
protected void onDestroy() {
if(progressDialog != null && progressDialog.isShowing()){
progressDialog.dismiss();
progressDialog = null;
}
super.onDestroy();
}
}
|
SQL
|
UTF-8
| 971 | 3.515625 | 4 |
[] |
no_license
|
create database escola;
use escola;
CREATE TABLE alunos (
id_aluno INT PRIMARY KEY AUTO_INCREMENT,
matricula INT NOT NULL,
nome VARCHAR(35),
turma VARCHAR(5),
ano date
);
alter table alunos
drop ano;
alter table alunos
add nota float;
SELECT
*
FROM
alunos;
insert into alunos values(1, 67364, 'Scott Summers', '3A', 7.2),
(2, 67567, 'Jean Grey', '3A', 9.5),
(3, 68904, 'Kurt Wagner', '1B', 6.5),
(4, 78905, 'Kitty Pride', '1B', 6.8),
(5, 67365, 'Hank Maccoy', '3C', 10.0),
(6, 69093, 'Alex Summers', '2C', 5.6);
insert into alunos values (7, 66096, 'Raven Darkholme', '3B', 10.0);
select* from alunos;
#Faça um select que retorne o/as alunos/a com a nota maior do que 7.
select * from alunos
where nota > 7
order by nota, nome, turma;
#Faça um select que retorne o/as alunos/a com a nota menor do que 7.
select * from alunos
where nota < 7
order by nota, nome, turma;
|
C#
|
UTF-8
| 1,103 | 3.078125 | 3 |
[] |
no_license
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Module6.ObjectOrientedTypes;
namespace Module6.UnitTests
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var expected = "Max Kritzinger";
var me = new PersonFromInterface("Max", "Kritzinger");
var mePerson = me as IPerson;
Assert.AreEqual(expected, mePerson.Fullname);
}
[TestMethod]
public void TestMethod2()
{
var expectedCode = "01277";
var expectedNumber = "345678";
var contactDetails = Contact.NewPhoneNumber(expectedCode, expectedNumber);
var me = new ContactPerson("Max", "Kritzinger", contactDetails);
var prefContact = me.PreferredContact as Contact.PhoneNumber;
var actualCode = prefContact.AreaCode;
var actualNumber = prefContact.Number;
Assert.AreEqual(expectedCode, prefContact.AreaCode);
Assert.AreEqual(expectedNumber, prefContact.Number);
}
}
}
|
C++
|
UTF-8
| 481 | 2.90625 | 3 |
[] |
no_license
|
#include "UniformRS.h"
#include <random>
std::vector<std::pair<size_t, double>> UniformRS::sample(size_t sample_size)
{
std::random_device rd;
std::mt19937 generator(rd());
std::uniform_int_distribution<size_t> uid(0, dataset_size - 1);
std::vector<std::pair<size_t, double>> sample_IDs(sample_size);
for (size_t i = 0; i < sample_size; i++)
{
size_t ID = uid(generator);
sample_IDs[i].first = ID;
sample_IDs[i].second = 1.0 / sample_size;
}
return sample_IDs;
}
|
Markdown
|
UTF-8
| 1,624 | 2.703125 | 3 |
[
"Unlicense"
] |
permissive
|
# Solange Knowles Has Separated From Her Husband
Published at: **2019-11-02T16:27:41+00:00**
Author: **Bridget Read**
Original: [VULTURE](https://www.vulture.com/2019/11/solange-knowles-separated-from-her-husband-alan-ferguson.html)
Solange Knowles, sister of Bey, has taken to Instagram to announce in an all-lowercase caption (with one emoji) that she has split with her husband of nearly five years, Alan Ferguson. She did not give much detail, but said only that they had separated earlier this year. In a very spiritual, Solange-y way, and along with three stunning, dressed-down photos, the singer referred to changes in her life that had led to the breakup: “the past 2 years have brought me more physical and spiritual transition and evolution than ever before,” she wrote. “ive lived my best and worst moments in front of the lens and gaze of the world since i was a teenager. ive always tried to live in my truth no matter how ugly or full of love it is.” As of Ferguson, she said, “11 years ago i met a phenomenal man who changed every existence of my life. early this year we separated and parted ways, (and tho it ain’t nan no body business) i find it necessary to protect the sacredness of my personal truth and to live in it fully just as I have before and will continue to do.”
The exes do not share any children; Solange has a 15-year-old son with her first husband, Daniel Smith, whom she married in 2004. Knowles and Ferguson had an incredibly beautiful wedding ceremony in 2014 in New Orleans, Instagram posts from which remain enshrined in our collective memory. If you recall, she pioneered the wedding cape.
|
Java
|
UTF-8
| 1,455 | 2.15625 | 2 |
[] |
no_license
|
package com.yami.internet;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class BlankFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
RecyclerView inboxRecycler = (RecyclerView)inflater.inflate(
R.layout.fragment_inbox, container, false);
String[] inboxTitle = new String[messages.mess.length];
for (int i = 0; i < inboxTitle.length; i++) {
inboxTitle[i] = messages.mess[i].getTitle();
}
String[] inboxContent = new String[messages.mess.length];
for (int i = 0; i < inboxContent.length; i++) {
inboxContent[i] = messages.mess[i].getContent();
}
inboxAdapter adapter = new inboxAdapter(inboxTitle, inboxContent);
inboxRecycler.setAdapter(adapter);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
inboxRecycler.setLayoutManager(layoutManager);
return inboxRecycler;
}
}
|
PHP
|
UTF-8
| 4,376 | 2.6875 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
<?php
/**
*
* @package Gems
* @subpackage Clover
* @author Matijs de Jong <mjong@magnafacta.nl>
* @copyright Copyright (c) 2019, Erasmus MC and MagnaFacta B.V.
* @license New BSD License
*/
namespace Gems\Clover;
use Zalt\Loader\Target\TargetInterface;
use Zalt\Loader\Target\TargetTrait;
/**
*
* @package Gems
* @subpackage Clover
* @copyright Copyright (c) 2019, Erasmus MC and MagnaFacta B.V.
* @license New BSD License
* @since Class available since version 1.8.6 13-Sep-2019 14:03:39
*/
class Cleaner implements ApplicationInterface, TargetInterface
{
use MessageTableTrait;
use QueueTableTrait;
use TargetTrait;
// use InvokableCommandTrait;
/**
*
* @param int $days
*/
protected $_days;
/**
*
* @param int $days
*/
protected $_daysDefault = 14;
/**
* @var Stream
*/
protected $logging = null;
/**
* Cleaner constructor.
*
* @param null $days
*/
public function __construct($days = null, array $config)
{
if (intval($days) > 0) {
$this->_days = intval($days);
} else {
$this->_days = $this->_daysDefault;
if (strlen($days)) {
echo sprintf(
"Invalid cleanup parameter %s, default value %d used instead.\n",
$days,
$this->_daysDefault
);
}
}
if (isset($config['logfile'])) {
$this->logging = fopen($config['logfile'], 'a');
fwrite($this->logging, sprintf(
"Starting cleanup run at %s for %d days." . PHP_EOL,
date('c'),
$this->_days
));
}
}
/**
* Called after the check that all required registry values
* have been set correctly has run.
*
* @return void
*/
public function afterRegistry()
{
$this->_initMessageTable();
$this->_initQueueTable();
}
/**
* Should be called after answering the request to allow the Target
* to check if all required registry values have been set correctly.
*
* @return boolean False if required values are missing.
*/
public function checkRegistryRequestsAnswers()
{
return $this->db instanceof DbBridge;
}
/**
* Start the main application
*
* @return void
*/
public function run()
{
$startDate = new \DateTime('today');
$interval = new \DateInterval(sprintf("P%dD", $this->_days));
$startDate->sub($interval);
$queueWhere = sprintf(
"hq_created < '%s' AND hq_execution_count > 0",
$startDate->format('Y-m-d H:i:s'));
$messageWhere = sprintf(
"hm_created < '%s' AND hm_id NOT IN (SELECT hq_message_id FROM hl7_queue)",
$startDate->format('Y-m-d H:i:s'));
try {
$queueDel = $this->_queueTable->delete($queueWhere);
} catch (\Exception $e) {
$message = sprintf(
"Cleanup error at %s on queue %s: %s" . PHP_EOL . $e->getTraceAsString() . PHP_EOL,
date('c'),
$queueWhere,
$e->getMessage());
if ($this->logging) {
fwrite($this->logging, $message);
}
echo $message;
return 1;
}
try {
$messageDel = $this->_messageTable->delete($messageWhere);
} catch (\Exception $e) {
$message = sprintf(
"Cleanup error at %s on messages %s: %s" . PHP_EOL . $e->getTraceAsString() . PHP_EOL,
date('c'),
$messageWhere,
$e->getMessage());
if ($this->logging) {
fwrite($this->logging, $message);
}
echo $message;
return 1;
}
$message = sprintf(
"Cleanup log %d queue items and %d message items created before %s deleted." . PHP_EOL,
$queueDel,
$messageDel,
$startDate->format('Y-m-d H:i:s')
);
if ($this->logging) {
fwrite($this->logging, $message);
}
// echo $message;
}
}
|
Markdown
|
UTF-8
| 757 | 2.828125 | 3 |
[] |
no_license
|

## Eh?
Your phone is _fabulous_, and it knows it. But do you?
## I have no idea what's going on.
Do you promise to love your phone no matter what? Good. Because it just told you it doesn't want to be a phone anymore. It wants to be a mouse. It's been a _goddamned trackpad inside a phone's body_ this whole time.
## But what will the neighbors say?
Fuck em! In the meantime:
* Run `npm install` for the dependencies
* Create a local network on your machine
* Connect to this network on your phone
* Run `ifconfig en0` to get the IP address
* Fire up `node app.js`
* Navigate to the aforementioned IP on your phone (on port 8080)
## Zomg! My phone is a mouse!
I know! It can click and shit!
|
JavaScript
|
UTF-8
| 1,825 | 2.75 | 3 |
[] |
no_license
|
/* eslint-disable no-loop-func, prefer-spread */
// require('babel-register')
const r = require('ramda')
const noOfGames = (games, player) => {
return gamesForPlayer(games, player).length
}
const gamesForPlayer = r.curry((games, player) => {
return r.filter(g => {
return r.contains(player, r.flatten(g))
}, games)
})
const scoreForGame = ({ settings, game }) => {
if (!game[2]) return [0, 0]
return r.reduce(
(score, set) => {
const winner = set[0] > set[1] ? 0 : 1
score[winner] = score[winner] + settings.winBonus
if (settings.onlyCountOwnPoints) {
score[0] = score[0] + set[0]
score[1] = score[1] + set[1]
} else {
score[0] = score[0] + set[0] - set[1]
score[1] = score[1] + set[1] - set[0]
}
// console.log('score', score)
return score
},
[0, 0],
game[2]
)
}
const scoreForPlayer = ({ settings, games, player }) => {
let gameCount = noOfGames(games, player)
return gameCount
? r.reduce(
(sum, game) => {
// console.log(game, 'game')
const team = r.contains(player, game[0]) ? 0 : 1
const score = scoreForGame({ settings, game })
// console.log(sum + score[team])
return sum + score[team]
},
0,
gamesForPlayer(games, player)
) / gameCount
: 0
}
const sortPlayersByScore = ({ settings, games, players }) => {
let scoredPlayers = players.map(player => [player, scoreForPlayer({ settings, games, player })])
return r.sort(([, s1], [, s2]) => s2 - s1, scoredPlayers)
}
export const getMatchesPlayed = ({ players, playedGames }) =>
players.map(p => noOfGames(playedGames, p))
export const getScore = ({ settings, playedGames, players }) =>
sortPlayersByScore({ settings, games: playedGames, players })
|
Python
|
UTF-8
| 338 | 3.390625 | 3 |
[] |
no_license
|
def cigar_party(cigars, is_weekend):
if is_weekend:
if cigars >= 40:
return True
else:
return False
else:
if 40 <= cigars <= 60:
return True
else:
return False
print(cigar_party(30, False))
print(cigar_party(50, False))
print(cigar_party(70, True))
|
C++
|
UTF-8
| 429 | 3.125 | 3 |
[] |
no_license
|
class Solution {
public:
int maxProfit(vector<int> &prices) {
if (prices.size() < 2)
return 0;
int max_profit = 0;
int min_price_ahead = prices[0];
for (int i = 1; i < prices.size(); ++i) {
if (max_profit < prices[i] - min_price_ahead)
max_profit = prices[i] - min_price_ahead;
if (min_price_ahead > prices[i])
min_price_ahead = prices[i];
}
return max_profit;
}
};
|
Python
|
UTF-8
| 164 | 3.296875 | 3 |
[] |
no_license
|
#!/usr/bin/python3
def divisible_by_2(my_list=[]):
new_list = []
for i in my_list:
new_list.append(False if i % 2 else True)
return(new_list)
|
C++
|
UTF-8
| 600 | 2.8125 | 3 |
[] |
no_license
|
//
// main.cpp
// Uri 1257 - Array Hash
//
// Created by S M HEMEL on 12/21/16.
// Copyright © 2016 S M HEMEL. All rights reserved.
//
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
int n,l;
char linha[51];
int total;
cin >> n;
while(n--)
{
cin >> l;
total = 0;
for(int j=0;j<l; j++)
{
cin >> linha;
for(int k=0; linha[k]!='\0'; k++)
total += linha[k]-65 + j + k;
memset(linha,NULL,sizeof(linha));
}
printf("%d\n", total);
}
return 0;
}
|
C
|
UTF-8
| 1,681 | 2.703125 | 3 |
[] |
no_license
|
/**
@brief software pwm implementation source file.
This source file provides implementation for a software PWM.
@file soft_pwm.c
@author Joao P Bino
*/
#include "soft_pwm.h"
#include "mcc_generated_files/pin_manager.h"
static volatile uint16_t dutycycle [PWM_CHANNEL_MAX] = {0};
static volatile uint8_t pwm_channel[PWM_CHANNEL_MAX] = {0};
static volatile uint8_t gpio_channel[PWM_CHANNEL_MAX] =
{
_LATA_LATA4_POSITION,
_LATA_LATA5_POSITION,
};
void GPIO_Channel_Write ( uint8_t channel, uint8_t state )
{
if ( state )
{
LATA = LATA | (1 << channel);
}
else
{
LATA = LATA & (0xff & (0 << channel));
}
}
void ISR_PWM_Callback (void)
{
static volatile uint16_t interrupt_counter = 0;
for (uint8_t i = 0; i < 2; i++)
{
if ( interrupt_counter < dutycycle[i] )
{
GPIO_Channel_Write(pwm_channel[i],1 );
}
else
{
GPIO_Channel_Write(pwm_channel[i],0 );
}
}
++interrupt_counter;
if ( interrupt_counter >= PWM_RESOLUTION)
{
interrupt_counter = 0;
}
}
void Soft_PWM_Init ( void )
{
for (uint8_t i = 0; i < PWM_CHANNEL_MAX; i++)
{
pwm_channel[i] = gpio_channel[i];
}
Soft_PWM_Set_Duty(PWM_CHANNEL1, 0);
Soft_PWM_Set_Duty(PWM_CHANNEL2, 0);
}
void Soft_PWM_Set_Duty ( pwm_channel_t channel, uint8_t duty )
{
if ( channel >= PWM_CHANNEL_MAX)
{
return;
}
if (duty > PWM_RESOLUTION)
{
return;
}
for (uint8_t i = 0; i < PWM_CHANNEL_MAX; i++)
{
if ( channel == i)
{
dutycycle[i] = duty;
}
}
}
|
Java
|
UTF-8
| 289 | 2.3125 | 2 |
[] |
no_license
|
package designPattern.AbstractFactory;
/**
* @author sby
* @Title: SpringTextField
* @Description: TODO
* @date 2019/1/22 14:03
*/
public class SpringTextField extends TextField {
@Override
public void display() {
System.out.println("春天样式文本框");
}
}
|
Markdown
|
UTF-8
| 13,276 | 3.1875 | 3 |
[] |
no_license
|
# lamp on ubuntu - Keith - CSDN博客
2014年11月13日 22:09:17[ke1th](https://me.csdn.net/u012436149)阅读数:539
个人分类:[web develop](https://blog.csdn.net/u012436149/article/category/2709623)
### How To Install Linux, Apache, MySQL, PHP (LAMP) stack on Ubuntu 14.04
### Introduction
A "LAMP" stack is a group of open source software that is typically installed together to enable a server to host dynamic websites and web apps. This term is actually an acronym which represents the Linux operating system,
with the Apache web server. The site data is stored in a MySQL database, and dynamic content is processed by PHP.
In this guide, we'll get a LAMP stack installed on an Ubuntu 14.04 Droplet. Ubuntu will fulfill our first requirement: a Linux operating system.
## Prerequisites
Before you begin with this guide, you should have a separate, non-root user account set up on your server. You can learn how to do this by completing steps 1-4 in the [initial
server setup for Ubuntu 14.04](https://www.digitalocean.com/community/articles/initial-server-setup-with-ubuntu-14-04).
## Step One — Install Apache
The Apache web server is currently the most popular web server in the world, which makes it a great default choice for hosting a website.
We can install Apache easily using Ubuntu's package manager, `apt`. A package manager allows us to install most
software pain-free from a repository maintained by Ubuntu. You can learn more about [how
to use `apt`](https://www.digitalocean.com/community/articles/how-to-manage-packages-in-ubuntu-and-debian-with-apt-get-apt-cache) here.
For our purposes, we can get started by typing these commands:
```
sudo apt-get update
sudo apt-get install apache2
```
Since we are using a `sudo` command, these operations get executed with root privileges. It will ask you for
your regular user's password to verify your intentions.
Afterwards, your web server is installed.
You can do a spot check right away to verify that everything went as planned by visiting your server's public IP address in your web browser (see the note under the next heading to find out what your public IP address is if you do not have this information
already):
http://your_server_IP_address
You will see the default Ubuntu 14.04 Apache web page, which is there for informational and testing purposes. It should look something like this:

If you see this page, then your web server is now correctly installed.
### How To Find your Server's Public IP Address
If you do not know what your server's public IP address is, there are a number of ways you can find it. Usually, this is the address you use to connect to your server through SSH.
From the command line, you can find this a few ways. First, you can use the `iproute2` tools to get your address
by typing this:
```
ip addr show eth0 | grep inet | awk '{ print $2; }' | sed 's/\/.*$//'
```
This will give you one or two lines back. They are both correct addresses, but your computer may only be able to use one of them, so feel free to try each one.
An alternative method is to use an outside party to tell you how *it* sees your server. You can do this by asking a specific server what your IP address is:
```
curl http://icanhazip.com
```
Regardless of the method you use to get your IP address, you can type it into your web browser's address bar to get to your server.
## Step Two — Install MySQL
Now that we have our web server up and running, it is time to install MySQL. MySQL is a database management system. Basically, it will organize and provide access to databases where our site can store information.
Again, we can use `apt` to acquire and install our software. This time, we'll also install some other "helper"
packages that will assist us in getting our components to communicate with each other:
```
sudo apt-get install mysql-server libapache2-mod-auth-mysql php5-mysql
```
Note: In this case, you do not have to run `sudo apt-get update` prior to
the command. This is because we recently ran it in the commands above to install Apache. The package index on our computer should already be up-to-date.
During the installation, your server will ask you to select and confirm a password for the MySQL "root" user. This is an administrative account in MySQL that has increased privileges. Think of it as being similar to the root account for the server itself (the
one you are configuring now is a MySQL-specific account however).
When the installation is complete, we need to run some additional commands to get our MySQL environment set up securely.
First, we need to tell MySQL to create its database directory structure where it will store its information. You can do this by typing:
```
sudo mysql_install_db
```
Afterwards, we want to run a simple security script that will remove some dangerous defaults and lock down access to our database system a little bit. Start the interactive script by running:
```
sudo mysql_secure_installation
```
You will be asked to enter the password you set for the MySQL root account. Next, it will ask you if you want to change that password. If you are happy with your current password, type "n" for "no" at the prompt.
For the rest of the questions, you should simply hit the "ENTER" key through each prompt to accept the default values. This will remove some sample users and databases, disable remote root logins, and load these new rules so that MySQL immediately respects
the changes we have made.
At this point, your database system is now set up and we can move on.
## Step Three — Install PHP
PHP is the component of our setup that will process code to display dynamic content. It can run scripts, connect to our MySQL databases to get information, and hand the processed content over to our web server to display.
We can once again leverage the `apt` system to install our components. We're going to include some helper packages
as well:
```
sudo apt-get install php5 libapache2-mod-php5 php5-mcrypt
```
This should install PHP without any problems. We'll test this in a moment.
In most cases, we'll want to modify the way that Apache serves files when a directory is requested. Currently, if a user requests a directory from the server, Apache will first look for a file called `index.html`.
We want to tell our web server to prefer PHP files, so we'll make Apache look for an `index.php` file first.
To do this, type this command to open the `dir.conf` file in a text editor with root privileges:
```
sudo nano /etc/apache2/mods-enabled/dir.conf
```
It will look like this:
<IfModule mod_dir.c>
DirectoryIndex index.html index.cgi index.pl index.php index.xhtml index.htm
</IfModule>
We want to move the PHP index file highlighted above to the first position after the`DirectoryIndex` specification,
like this:
<IfModule mod_dir.c>
DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm
</IfModule>
When you are finished, save and close the file by pressing "CTRL-X". You'll have to confirm the save by typing "Y" and then hit "ENTER" to confirm the file save location.
After this, we need to restart the Apache web server in order for our changes to be recognized. You can do this by typing this:
```
sudo service apache2 restart
```
### Install PHP Modules
To enhance the functionality of PHP, we can optionally install some additional modules.
To see the available options for PHP modules and libraries, you can type this into your system:
```
apt-cache search php5-
```
The results are all optional components that you can install. It will give you a short description for each:
```
php5-cgi - server-side, HTML-embedded scripting language (CGI binary)
php5-cli - command-line interpreter for the php5 scripting language
php5-common - Common files for packages built from the php5 source
php5-curl - CURL module for php5
php5-dbg - Debug symbols for PHP5
php5-dev - Files for PHP5 module development
php5-gd - GD module for php5
. . .
```
To get more information about what each module does, you can either search the internet, or you can look at the long description in the package by typing:
apt-cache show package_name
There will be a lot of output, with one field called `Description-en` which will have a longer explanation of
the functionality that the module provides.
For example, to find out what the `php5-cli` module does, we could type this:
```
apt-cache show php5-cli
```
Along with a large amount of other information, you'll find something that looks like this:
```
. . .
SHA256: 91cfdbda65df65c9a4a5bd3478d6e7d3e92c53efcddf3436bbe9bbe27eca409d
Description-en: command-line interpreter for the php5 scripting language
This package provides the /usr/bin/php5 command interpreter, useful for
testing PHP scripts from a shell or performing general shell scripting tasks.
.
The following extensions are built in: bcmath bz2 calendar Core ctype date
dba dom ereg exif fileinfo filter ftp gettext hash iconv libxml mbstring
mhash openssl pcntl pcre Phar posix Reflection session shmop SimpleXML soap
sockets SPL standard sysvmsg sysvsem sysvshm tokenizer wddx xml xmlreader
xmlwriter zip zlib.
.
PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used
open source general-purpose scripting language that is especially suited
for web development and can be embedded into HTML.
Description-md5: f8450d3b28653dcf1a4615f3b1d4e347
Homepage: http://www.php.net/
. . .
```
If, after researching, you decide you would like to install a package, you can do so by using the `apt-get install` command
like we have been doing for our other software.
If we decided that `php5-cli` is something that we need, we could type:
```
sudo apt-get install php5-cli
```
If you want to install more than one module, you can do that by listing each one, separated by a space, following the
```
apt-get
install
```
command, like this:
sudo apt-get install package1package2...
At this point, your LAMP stack is installed and configured. We should still test out our PHP though.
## Step Four — Test PHP Processing on your Web Server
In order to test that our system is configured properly for PHP, we can create a very basic PHP script.
We will call this script `info.php`. In order for Apache to find the file and serve it correctly, it must be
saved to a very specific directory, which is called the "web root".
In Ubuntu 14.04, this directory is located at `/var/www/html/`. We can create the file at that location by typing:
```
sudo nano /var/www/html/info.php
```
This will open a blank file. We want to put the following text, which is valid PHP code, inside the file:
```
<?php
phpinfo();
?>
```
When you are finished, save and close the file.
Now we can test whether our web server can correctly display content generated by a PHP script. To try this out, we just have to visit this page in our web browser. You'll need your server's public IP address again.
The address you want to visit will be:
http://your_server_IP_address/info.php
The page that you come to should look something like this:

This page basically gives you information about your server from the perspective of PHP. It is useful for debugging and to ensure that your settings are being applied correctly.
If this was successful, then your PHP is working as expected.
You probably want to remove this file after this test because it could actually give information about your server to unauthorized users. To do this, you can type this:
```
sudo rm /var/www/html/info.php
```
You can always recreate this page if you need to access the information again later.
## Conclusion
Now that you have a LAMP stack installed, you have many choices for what to do next. Basically, you've installed a platform that will allow you to install most kinds of websites and web software on your server.
Some popular options are:
- [Install
Wordpress](https://www.digitalocean.com/community/articles/how-to-install-wordpress-on-ubuntu-12-04) the most popular content management system on the internet
- [Set
Up PHPMyAdmin](https://www.digitalocean.com/community/articles/how-to-install-and-secure-phpmyadmin-on-ubuntu-12-04) to help manage your MySQL databases from web browser.
- [Learn
more about MySQL](https://www.digitalocean.com/community/articles/a-basic-mysql-tutorial) to manage your databases.
- [Learn
how to create an SSL Certificate](https://www.digitalocean.com/community/articles/how-to-create-a-ssl-certificate-on-apache-for-ubuntu-12-04) to secure traffic to your web server.
- [Learn
how to use SFTP](https://www.digitalocean.com/community/articles/how-to-use-sftp-to-securely-transfer-files-with-a-remote-server) to transfer files to and from your server.
Note: We will be updating the links above to our 14.04 documentation as it is written.
[点击打开链接](http://gushedaoren.blog.163.com/blog/static/17366340520146654938871/)
|
Markdown
|
UTF-8
| 4,448 | 3.71875 | 4 |
[] |
no_license
|
# Graphical Editor
Write a program which simulates a simple interactive graphical editor.
### Usage
'''
npm run
'''
### Notes
The original command S write to a file. In this example the command was replaced by show in console.
## Original Problem
Graphical editors such as Photoshop allow us to alter bit-mapped images in the same way that text editors allow us to modify documents. Images are represented as an M × N array of pixels, where each pixel has a given color.
Your task is to write a program which simulates a simple interactive graphical editor.
### Input
The input consists of a sequence of editor commands, one per line. Each command is represented by one capital letter placed as the first character of the line. If the command needs parameters, they will be given on the same line separated by spaces.
Pixel coordinates are represented by two integers, a column number between 1 ... M and a row number between 1 ... N, where 1 ≤ M, N ≤ 250. The origin sits in the upper-left corner of the table.
Colors are specified by capital letters.
The editor accepts the following commands:
| Command | Result |
|-----------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| I M N | Create a new M × N image with all pixels initially colored white (O). |
| C | Clear the table by setting all pixels white (O). The size remains unchanged. |
| L X Y C | Colors the pixel (X, Y ) in color (C). |
| V X Y1 Y2 C | Draw a vertical segment of color (C) in column X,between the rows Y 1 and Y 2 inclusive. |
| V X Y1 Y2 C | Draw a horizontal segment of color (C) in the row Y ,between the columns X1 and X2 inclusive. |
| K X1 Y1 X2 Y2 C | Draw a filled rectangle of color C, where (X1, Y 1) isthe upper-left and (X2, Y 2) the lower right corner. |
| F X Y C | Fill the region R with the color C, where R is defined as follows. Pixel (X, Y ) belongs to R. Any other pixel which is the same color as pixel (X, Y ) and shares a common side with any pixel in R also belongs to this region. |
| S Name | Write the file name in MSDOS 8.3 format followed by the contents of the current image. |
| X | Terminate the session. |
### Output
On every command S NAME, print the filename NAME and contents of the current image. Each row is represented by the color contents of each pixel. See the sample output.
Ignore the entire line of any command defined by a character other than I, C, L, V, H, K, F, S, or X, and pass on to the next command. In case of other errors, the program behavior is unpredictable.
### Sample Input
```
I 5 6
L 2 3 A
S one.bmp
G 2 3 J
F 3 3 J
V 2 3 4 W
H 3 4 2 Z
S two.bmp
X
```
### Sample Output
one.bmp
```text
OOOOO
OOOOO
OAOOO
OOOOO
OOOOO
OOOOO
```
two.bmp
```text
JJJJJ
JJZZJ
JWJJJ
JWJJJ
JJJJJ
JJJJJ
```
|
Java
|
UTF-8
| 1,491 | 2.40625 | 2 |
[] |
no_license
|
package buySell;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.surf.dsasm.Rework.client.RestClientInteractor;
import MetricApplier.SymbolVsMetricSortedList;
import model.BoughtInfo;
import model.GradientCandleClassifier;
import model.Metric;
@Component
public class CandlestickGradientSellConsiderer implements SellConsiderer{
private RestClientInteractor clientInteractor;
private Logger logger = LoggerFactory.getLogger(CandlestickGradientSellConsiderer.class);
@Autowired
public CandlestickGradientSellConsiderer(RestClientInteractor clientInteractor) {
this.clientInteractor = clientInteractor;
}
@Override
public BoughtInfo shouldSellNow(BoughtInfo boughtInfo, int holdingIndex) {
//work out the difference between the original price and the price now
Double priceDiff = clientInteractor.getLatestPrice(boughtInfo.getSymbol());
BoughtInfo currentInfo = boughtInfo;//BoughtCoinsHolder.getBought(holdingIndex);
Metric metric = (Metric) SymbolVsMetricSortedList.get(boughtInfo.getSymbol()).getMetric();
boolean shouldSell = metric.shouldSell(priceDiff, currentInfo);
if (priceDiff > boughtInfo.getHighestProfit()) boughtInfo.setHighestProfit(priceDiff);
logger.info("Should Sell? "+shouldSell);
boughtInfo.setShouldSell(shouldSell);
return boughtInfo;
}
}
|
SQL
|
UTF-8
| 463 | 3.25 | 3 |
[] |
no_license
|
CREATE TABLE SUBSCR_RQST (
SUBSCR_RQST_ID INT(11) NOT NULL AUTO_INCREMENT,
USER_ID INT(11) UNSIGNED DEFAULT NULL,
PROJ_ID INT(11) NOT NULL,
RQST_TM DATETIME NOT NULL,
PRIMARY KEY (SUBSCR_RQST_ID),
INDEX IX__SUBSCR_RQST__PROJ_ID (PROJ_ID),
INDEX IX__SUBSCR_RQST__USER_ID (USER_ID),
UNIQUE INDEX IX__SUBSCR_RQST__PROJ_ID__USER_ID (PROJ_ID, USER_ID)
)
ENGINE = INNODB
|
Java
|
UTF-8
| 204 | 1.648438 | 2 |
[
"MIT"
] |
permissive
|
package io.blacknode.adx;
import android.location.Location;
/**
* Created by Arshit on 2/22/18.
*/
public interface OnLocationChangedListener {
void onLocationChanged(Location currentLocation);
}
|
Java
|
UTF-8
| 1,144 | 2.4375 | 2 |
[] |
no_license
|
/* CSI4124/SYS5110 – Foundations of Modeling and Simulation
* SM Market - Simulation Project
* Fall 2016
*
* Team Members:
* Paul Laplante
* Saman Daneshvar
* Matthew Gordon Yaraskavitch
* Toluwalase Olufowobi
* Ekomabasi Ukpong
* Qufei Chen
*/
package smmSimModel;
import simulationModelling.ScheduledAction;
class Initialise extends ScheduledAction
{
SMMarket model;
// Constructor
protected Initialise(SMMarket model) { this.model = model; }
double [] ts = { 0.0, -1.0 }; // -1.0 ends scheduling
int tsix = 0; // set index to first entry.
protected double timeSequence()
{
return ts[tsix++]; // only invoked at t=0
}
protected void actionEvent()
{
// System Initialization
model.rgCounters.get(Constants.MNF).list.clear(); // empties the list
model.rgCounters.get(Constants.DELI).list.clear(); // empties the list
model.qCustomerLines.get(Constants.MNF).clear(); // empties the line
model.qCustomerLines.get(Constants.DELI).clear(); // empties the line
// Initialize the output variables
model.output.numServed = 0;
model.output.numDissatisfied = 0;
model.udp.initializeUTotalEmp();
}
}
|
C
|
UTF-8
| 1,366 | 2.703125 | 3 |
[] |
no_license
|
#include <store.h>
#include <store/object.h>
#include <stdlib.h>
#include <string.h>
#include "_impl.h"
static object *_ob_new_unmanaged(object prototype)
{
object* ret = malloc(sizeof(object));
memcpy(ret, &prototype, sizeof(object));
if(ret->constructor!=NULL)
ret->constructor(ret);
return ret;
}
/*static void _ob_free_unmanaged(object* obj)
{
if(obj->destructor!=NULL)
obj->destructor(obj);
free(obj);
}*/
object* obj_new(store_t* store, object prototype)
{
object* obj = _ob_new_unmanaged(prototype);
store_t* s = _store_ptr(store, obj);
s->is_obj = 1;
return obj;
}
object* obj_copy(object* from, object* to)
{
to->constructor = from->constructor;
to->destructor = from->destructor;
to->copy_to(from, to);
return to;
}
object* obj_clone(store_t* store, object *from)
{
object* new = malloc(sizeof(object));
from->constructor(new);
obj_copy(from, new);
if(store)
{
store_t* s = _store_ptr(store, new);
s->is_obj = 1;
}
return new;
}
void obj_free(store_t *store,object *obj)
{
if(store->ptr == obj)
{
if(obj->destructor!=NULL)
obj->destructor(obj);
free(obj);
store->ptr = NULL;
store->is_obj=0;
} else if (store->next) {
obj_free(store->next,obj);
}
}
static void _obj_copy_default(object* f, object* t)
{
t->state = f->state;
}
const object OBJ_PROTO = {NULL,NULL,NULL, &_obj_copy_default};
|
Java
|
UTF-8
| 6,577 | 2.1875 | 2 |
[] |
no_license
|
package com.renny.simplebrowser.globe.image.impl.glide;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.widget.ImageView;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.renny.simplebrowser.globe.helper.BitmapUtils;
import com.renny.simplebrowser.globe.helper.ThreadHelper;
import com.renny.simplebrowser.globe.image.DisplayOption;
import com.renny.simplebrowser.globe.image.ImageDisplayLoader;
import com.renny.simplebrowser.globe.image.ImageLoadListener;
import java.io.File;
import java.util.concurrent.ExecutionException;
public class GlideImageLoaderNew implements ImageDisplayLoader {
private Context appContext;
private DisplayOption defaultDisplayOption;
public GlideImageLoaderNew(Context appContext) {
this.appContext = appContext;
}
public void setDefaultDisplayOption(DisplayOption defaultDisplayOption) {
this.defaultDisplayOption = defaultDisplayOption;
}
@Override
public void display(final ImageView imageView, final String url, final ImageLoadListener listener, DisplayOption opts) {
if (imageView != null && !TextUtils.isEmpty(url)) {
GlideRequest<Drawable> requestBuilder = GlideApp.with(appContext).load(url);
opts = opts == null ? defaultDisplayOption : opts;
if (opts != null) {
if (opts.cacheInMemory != null) {
requestBuilder.skipMemoryCache(!opts.cacheInMemory);
}
if (opts.cacheOnDisk != null) {
if (opts.cacheOnDisk) {
requestBuilder.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC);
} else {
requestBuilder.diskCacheStrategy(DiskCacheStrategy.NONE);
}
}
if (opts.maxHeight != null && opts.maxWidth != null) {
requestBuilder.override(opts.maxWidth, opts.maxHeight);
}
if (opts.errorResId > 0) {
requestBuilder.error(opts.errorResId);
}
if (opts.defaultResId > 0) {
requestBuilder.placeholder(opts.defaultResId);
}
if (opts.loadingResId > 0) {
requestBuilder.placeholder(opts.loadingResId);
}
}
if (listener != null) {
requestBuilder.listener(new RequestListener<Drawable>() {
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
listener.onLoadFail(url, imageView, e);
return false;
}
@Override
public boolean onResourceReady(Drawable resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) {
if (resource != null) {
listener.onLoadSuccess(imageView, BitmapUtils.drawableToBitmap(resource));
} else {
listener.onLoadSuccess(imageView, null);
}
return false;
}
});
}
requestBuilder.thumbnail(0.4f).into(imageView);
}
}
@Override
public void display(ImageView imageView, int bitmap) {
GlideApp.with(appContext).load(bitmap).diskCacheStrategy(DiskCacheStrategy.NONE).into(imageView);
}
@Override
public Bitmap syncLoad(File file) {
try {
return GlideApp.with(appContext).asBitmap().load(file).submit().get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
return null;
}
@Override
public Bitmap syncLoad(String url) {
try {
return GlideApp.with(appContext).asBitmap().load(url).submit().get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
return null;
}
@Override
public File syncLoadFile(String url){
try {
return GlideApp.with(appContext).asFile().load(url).submit().get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
return null;
}
@Override
public void preLoad(final String url) {
if (!ThreadHelper.inMainThread()) {
ThreadHelper.postMain(new Runnable() {
@Override
public void run() {
GlideApp.with(appContext).asBitmap().load(url).preload();
}
});
} else {
GlideApp.with(appContext).asBitmap().load(url).preload();
}
}
@Override
public void clearCache(int... cachePlaces) {
if (cachePlaces != null) {
for (int cachePlace : cachePlaces) {
switch (cachePlace) {
case ImageDisplayLoader.CACHE_IN_DISK:
if (ThreadHelper.inMainThread()) {
new Thread(new Runnable() {
@Override
public void run() {
GlideApp.get(appContext).clearDiskCache();//清理磁盘缓存 需要在子线程中执行
}
}).start();
} else {
GlideApp.get(appContext).clearDiskCache();//清理磁盘缓存 需要在子线程中执行
}
break;
case ImageDisplayLoader.CACHE_IN_MEM:
GlideApp.get(appContext).clearMemory();//清理内存缓存 可以在UI主线程中进行
break;
default:
break;
}
}
}
}
@Override
public void pause() {
GlideApp.with(appContext).pauseRequests();
}
@Override
public void resume() {
GlideApp.with(appContext).resumeRequests();
}
}
|
Java
|
UTF-8
| 233 | 1.898438 | 2 |
[] |
no_license
|
package me.nic.cloud.mapper;
import me.nic.cloud.entities.Payment;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface PaymentMapper {
int create(Payment payment);
Payment selectPaymentById(Long id);
}
|
JavaScript
|
UTF-8
| 8,093 | 3.796875 | 4 |
[] |
no_license
|
/**
* @namespace
* @memberof L3D
*/
L3D.utils = (function() {
var utils = {};
/**
* @constructor
* @description Linked list in javascript
* @memberof L3D.utils
*/
var List = function() {
/**
* @private
* @type {Number}
* @description number of elements in the list
*/
this._size = 0;
/**
* @private
* @type {Object}
* @description first chain element of the list
*/
this._begin = null;
/**
* @private
* @type {Object}
* @description last chain element of the list
*/
this._end = null;
};
/**
* Size of the list
* Complexity O(1)
* @returns {Number} the number of elements in the list
*/
List.prototype.size = function() {
return this._size;
};
/**
* Push an element at the end of the list
* Complexity O(1)
* @param element {Object} object to push at the end of the list
*/
List.prototype.push = function(element) {
if (this._size === 0) {
this._begin = { data : element, next: null, prev: null };
this._end = this._begin;
this._size = 1;
} else {
var newObject = { data: element, next: null, prev: this._end };
this._end.next = newObject;
this._end = newObject;
this._size++;
}
};
/**
* Sorts the list by creating an array, sorting it, and recopying it to the list
* @param comparator {function} comparator between objects
* Complexity O(size() * log (size()))
*/
List.prototype.sort = function(comparator) {
if (comparator === undefined) {
comparator = priv.defaultComparator;
}
var array = [];
this.forEach(function(elt) {
array.push(elt);
});
array.sort(function(a, b) {
return comparator(a, b);
});
var size = this.size();
this.clear();
for (var i = 0; i < size; i++) {
this.push(array[i]);
}
};
/**
* Removes and returns the last element of the list
* Complexity O(1)
* @returns {Object} the last element of the list
*/
List.prototype.pop = function() {
var tmp = this._end;
this._end = null;
return tmp.data;
};
/**
* Apply a call back to each element of the list
* Complexity O(size())
* @param callback {function} callback to call on all elements of the list
*/
List.prototype.forEach = function(callback) {
var chain = this._begin;
while (chain !== null) {
callback(chain.data);
chain = chain.next;
}
};
/**
* Apply a call back to each element of the list in reverse order
* Complexity O(size())
* @param callback {function} callback to call on all elements of the list in reverse order
*/
List.prototype.forEachInverse = function(callback) {
var chain = this._end;
while (chain !== null) {
callback(chain.data);
chain = chain.prev;
}
};
/**
* Get the ith element of the list
* Complexity O(ith)
* @param ith {Number} index of the element to get
* @returns {Object} the ith element if it exists, null otherwise
*/
List.prototype.at = function(ith) {
if (ith < 0 || ith >= this.size()) {
return null;
}
var chain = this._begin;
for (var i = 0; i < ith; i++) {
chain = chain.next;
}
return chain.data;
};
/**
* Empty the list
*/
List.prototype.clear = function() {
this._begin = null;
this._end = null;
this._size = 0;
};
/**
* Insert an element at the right place in a sorted list
* Precondition : the list must be sorted
* Complexity : O(i) where i is the number of elements lower than elt
* @param elt {Object} element to add
* @param comparator {function} classic js comparator
*/
List.prototype.insertSorted = function(elt, comparator) {
var newElement;
if (comparator === undefined) {
comparator = priv.defaultComparator;
}
if (this._begin === null) {
// Inserted in front (empty list)
this.push(elt);
} else if (comparator(this._begin.data, elt) > 0) {
// Inserted in front (smallest element)
newElement = {prev: null, next: this._begin, data: elt};
this._begin.prev = newElement;
this._begin = newElement;
this._size ++;
} else if (comparator(this._end.data, elt) < 0) {
// Inserted in end
this.push(elt);
} else {
// Inserted in the middle
var chain = this._begin;
while (chain.next !== null) {
// If chain < elt < chain.next
if (comparator(chain.next.data, elt) > 0) {
newElement = {data: elt, next: chain.next, prev: chain};
if (chain.next) {
chain.next.prev = newElement;
}
chain.next = newElement;
this._size ++;
return;
}
// Next step
chain = chain.next;
}
}
};
/**
* Checks if a list is sorted
* Complexity : O(size()) if the list is sorted, O(i) where i is the first non-sorted element in the list
* @param comparator {function} classic js comparator
* @returns {Boolean} true if the list is sorted, false otherwise
*/
List.prototype.isSorted = function(comparator) {
var chain = this._begin;
if (comparator === undefined) {
comparator = priv.defaultComparator;
}
while (chain.next !== null) {
if (comparator(chain.data, chain.next.data) > 0) {
return false;
}
chain = chain.next;
}
return true;
};
/**
* Returns an iterator to the begin of the list
* @returns {Iterator} an interator to the first element
*/
List.prototype.begin = function() {
return new Iterator(this._begin, 0);
};
/**
* Returns an iterator to the end of the list
* @returns {Iterator} an interator to the first element
*/
List.prototype.end = function() {
return new Iterator(this._end, this.size() - 1);
};
/**
* @constructor
* @description Reprensents an iterator to an element of a list
* @param chain {Object} chain element of a list
* @param counter {Number} index of the current element
* @memberof L3D.utils
*/
var Iterator = function(chain, counter) {
this._chain = chain;
this._counter = counter;
};
/**
* Go to the next element
* @method
*/
Iterator.prototype.next = function() {
this._chain = this._chain.next;
this._counter ++;
};
/**
* Go to the previous element
* @method
*/
Iterator.prototype.prev = function() {
this._chain = this._chain.prev;
this._counter --;
};
/**
* Returns the current element
* @method
* @returns {Object} current element
*/
Iterator.prototype.get = function() {
return this._chain.data;
};
/**
* Checks if there is a element after the current element
* @method
* @returns {Boolean} true if the element exists, false otherwise
*/
Iterator.prototype.hasNext = function() {
return this._chain.next !== null;
};
/**
* Checks if there is a element before the current element
* @method
* @returns {Boolean} true if the element exists, false otherwise
*/
Iterator.prototype.hasPrev = function() {
return this._chain.prev !== null;
};
/**
* Compares two iterators of the same list
* @param it2 {Iterator} second iterator of the comparison
* @returns {Boolean} result of this < it2
*/
Iterator.prototype.lowerThan = function(it2) {
return distance(this, it2) > 0;
};
/**
* Compares two iterators of the same list
* @method
* @param it2 {Iterator} second iterator of the comparison
* @returns {Boolean} result of this > it2
*/
Iterator.prototype.greaterThan = function(it2) {
return distance(this, it2) < 0;
};
/**
* Compute the distance between two iterators
* @method
* @private
* @param it1 {Iterator} first iterator of the computation
* @param it2 {Iterator} second iterator of the computation
* @returns {Number} distance between it1 and it2
*/
var distance = function(it1, it2) {
return it2._counter - it1._counter;
};
priv = {};
priv.defaultComparator = function(a,b) {
if (a < b)
return -1;
if (a > b)
return 1;
return 0;
};
utils.List = List;
utils.Iterator = Iterator;
return utils;
})();
|
JavaScript
|
UTF-8
| 611 | 2.65625 | 3 |
[] |
no_license
|
(function() {
var LevelWalls = function(width, height, metal, floor, wood) {
this.initialize(width, height, metal, floor, wood);
}
var p = LevelWalls.prototype = new createjs.Container();
p.width;
p.height;
p.metal;
p.floor;
p.wood;
p.Container_initialize = p.initialize;
p.initialize = function(width, height, metal, floor, wood) {
this.Container_initialize();
this.width = width;
this.height = height;
this.metal = metal;
this.floor = floor;
this.wood = wood;
this.addChild(metal);
this.addChild(floor);
this.addChild(wood);
}
window.LevelWalls = LevelWalls;
}())
|
Java
|
UTF-8
| 1,496 | 2.46875 | 2 |
[] |
no_license
|
package de.dailab.oven.database;
import javax.annotation.Nonnull;
import org.junit.Assume;
import org.junit.Before;
import de.dailab.oven.database.configuration.DatabaseConfiguration;
import de.dailab.oven.database.configuration.Graph;
/**
* Provides a {@link Graph} instance that can be used for database tests. Credentials need to be set via environment variables otherwise tests will be skipped.
*
* @author Hendrik Motza
* @since 19.11
*/
public abstract class AbstractDatabaseTest {
@Nonnull
private static final String ENVKEY_URI = "oven_database_test_uri";
@Nonnull
private static final String ENVKEY_USER = "oven_database_test_user";
@Nonnull
private static final String ENVKEY_PW = "oven_database_test_pw";
private Graph testGraph;
@Before
public void init() throws Throwable {
String uri = System.getenv(ENVKEY_URI);
String user = System.getenv(ENVKEY_USER);
String pw = System.getenv(ENVKEY_PW);
if(uri == null || user == null || pw == null) {
uri = System.getProperty(ENVKEY_URI);
user = System.getProperty(ENVKEY_USER);
pw = System.getProperty(ENVKEY_PW);
}
Assume.assumeTrue(uri != null && user != null && pw != null);
this.testGraph = new Graph(new DatabaseConfiguration(uri, user, pw));
initialize();
}
public abstract void initialize() throws Throwable;
public Graph getGraph() {
return this.testGraph;
}
}
|
C++
|
UTF-8
| 1,710 | 3.140625 | 3 |
[] |
no_license
|
#include <iostream>
#include <fstream>
#include "Eigen/Dense"
#include "Eigen/Eigenvalues"
//using namespace std;
using namespace Eigen;
using namespace std;
//Die Funktion Federpendel gibt die Eigenwerte des Differentialgleichungssystems aus
VectorXd Federpendel(VectorXd &m, VectorXd &k, VectorXd &l, int N)
{
//aufstellen der zu diagonalisierenden Matrix
MatrixXd A(N, N);
//die erste und letzte Zeile werden separat implementiert
A(0, 0) = -k(0)/m(0);
A(0, 1) = k(0)/m(0);
A(N-1, N-1) = -k(N-2)/m(N-1);
A(N-1, N-2) = k(N-2)/m(N-1);
//Die Matrix wird mit den berechneten Elementen befüllt
for(int i = 1; i <= N-2; i++)
{
A(i, i) = (-k(i)-k(i-1))/m(i);
A(i, i-1) = k(i-1)/m(i);
A(i, i+1) = k(i)/m(i);
}
//Die Eigenwerte der Matrix werden mittels eigen Bibliothek bestimmt und ausgegeben
EigenSolver<MatrixXd> es(A);
VectorXd eigenwerte = es.eigenvalues().real(); //Die Eigenwerte sind eh alle real, aber wir wollen nur eine Spalte haben
return eigenwerte;
}
int main ()
{
//Initialisierung der Anzahl der Massen N, sowie der Federkonstanten k, Massen m und Startwerte j
const int N = 10;
VectorXd m(N);
VectorXd l(N-1);
VectorXd k(N-1);
for(int i = 0; i < N-1; i++)
{
m(i) = (i+1);
k(i) = N-(i+1);
l(i) = abs(5-(i+1))+1;
}
m(N-1) = N;
//Berechnung der Eigenfrequenzen aus den Eigenwerten w = sqrt(-lambda)
VectorXd eigenwerte = Federpendel(m, k, l, N);
VectorXd eigenfrequenzen(N);
for(int i = 0; i<N; i++)
{
eigenfrequenzen(i) = sqrt(abs(eigenwerte(i)));
}
ofstream f;
f.open("Aufgabe2.txt");
f << "Eigenfrequenzen" << "\n";
f << eigenfrequenzen << "\n" ;
f.flush();
f.close();
return 0;
}
|
Python
|
UTF-8
| 11,839 | 2.515625 | 3 |
[] |
no_license
|
# coding: utf-8
# In[1]:
import tensorflow as tf
import time,sys,os,math,random,itertools,glob,cv2
from datetime import timedelta
#from sklearn.utils import shuffle
import pandas as pd
import numpy as np
from datetime import timedelta
from sklearn.model_selection import train_test_split,ShuffleSplit
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
#Adding Seed so that random initialization is consistent
from numpy.random import seed
seed(1)
from tensorflow import set_random_seed
import matplotlib.pyplot as plt
#get_ipython().run_line_magic('matplotlib', 'inline')
set_random_seed(2)
final_project_path = r"C:\tmp\speech_dataset"
os.chdir(final_project_path)
# In[2]:
def drawProgressBar(percent, barLen = 50):
sys.stdout.write("\r")
progress = ""
for i in range(barLen):
if i<int(barLen * percent):
progress += "="
else:
progress += " "
sys.stdout.write("[ %s ] %.2f%%" % (progress, percent * 100))
sys.stdout.flush()
imp_labels = ['yes', 'no', 'up', 'down', 'left', 'right', 'on', 'off', 'stop', 'go', 'silence', 'unknown']
def load_train(train_path):
images = []
classes = []
path = train_path
file_names = os.listdir(os.path.join(os.getcwd(),train_path))
counter = 1
print("Creating Classes, reading images and breaking things ...\n")
for file in file_names:
drawProgressBar(counter/len(file_names))
#print(file)
classes.append(file.split("_")[0])
image = cv2.imread(os.path.join(os.getcwd(),train_path,file))
image = image.astype(np.float32)
image = np.multiply(image, 1.0/255.0) #normalizing the pixel intensities
images.append(image)
counter += 1
print("\nDone!")
images = np.array(images)
#classes now has all the labels. order preserved
#but we need the classes to be floats/ints so lets map the shit out of them
for i in range(len(classes)):
if classes[i] not in imp_labels:
classes[i] = 'unkown'
d = {ni:indi for indi, ni in enumerate(set(classes))}
classes = [d[ni] for ni in classes]
classes = np.array(classes)
n_values = np.max(classes)+1
classes = np.eye(n_values)[classes]
#classes = np.eye(n_values)[classes.reshape(-1)]
print("\nDone!")
print("\n images shape: {}, labels shape: {}".format(images.shape,classes.shape))
return (images,classes)#(train_x,train_y,test_x,test_y)
images,labels = load_train("im_train")
def split_data(images, labels,test_size = 0.2, random_state = 7, shuffle = False):
return(train_test_split(images,labels,test_size = test_size,random_state = random_state,shuffle = shuffle))
train_x,test_x,train_y,test_y = split_data(images,labels, test_size = 0.2, shuffle = True)
print(train_x.shape,test_x.shape,train_y.shape,test_y.shape)
#plt.imshow(train_x[12])
# In[36]:
num_classes = 12
def random_mini_batches(X, Y, mini_batch_size = 64, seed = 0):
"""
Creates a list of random minibatches from (X, Y)
Arguments:
X -- input data, of shape (input size, number of examples) (m, Hi, Wi, Ci)
Y -- true "label" vector (containing 0 if cat, 1 if non-cat), of shape (1, number of examples) (m, n_y)
mini_batch_size - size of the mini-batches, integer
seed -- this is only for the purpose of grading, so that you're "random minibatches are the same as ours.
Returns:
mini_batches -- list of synchronous (mini_batch_X, mini_batch_Y)
"""
m = X.shape[0] # number of training examples
mini_batches = []
np.random.seed(seed)
# Step 1: Shuffle (X, Y)
permutation = list(np.random.permutation(m))
shuffled_X = X[permutation,:,:,:]
shuffled_Y = Y[permutation,:]
# Step 2: Partition (shuffled_X, shuffled_Y). Minus the end case.
num_complete_minibatches = math.floor(m/mini_batch_size) # number of mini batches of size mini_batch_size in your partitionning
for k in range(0, num_complete_minibatches):
mini_batch_X = shuffled_X[k * mini_batch_size : k * mini_batch_size + mini_batch_size,:,:,:]
mini_batch_Y = shuffled_Y[k * mini_batch_size : k * mini_batch_size + mini_batch_size,:]
mini_batch = (mini_batch_X, mini_batch_Y)
mini_batches.append(mini_batch)
# Handling the end case (last mini-batch < mini_batch_size)
if m % mini_batch_size != 0:
mini_batch_X = shuffled_X[num_complete_minibatches * mini_batch_size : m,:,:,:]
mini_batch_Y = shuffled_Y[num_complete_minibatches * mini_batch_size : m,:]
mini_batch = (mini_batch_X, mini_batch_Y)
mini_batches.append(mini_batch)
return mini_batches
def create_placeholders(n_H0, n_W0, n_C0, n_y):
"""
Creates the placeholders for the tensorflow session.
Arguments:
n_H0 -- scalar, height of an input image
n_W0 -- scalar, width of an input image
n_C0 -- scalar, number of channels of the input
n_y -- scalar, number of classes
Returns:
X -- placeholder for the data input, of shape [None, n_H0, n_W0, n_C0] and dtype "float"
Y -- placeholder for the input labels, of shape [None, n_y] and dtype "float"
"""
X = tf.placeholder(shape = [None, n_H0, n_W0, n_C0],dtype = tf.float32)
Y = tf.placeholder(shape = [None, n_y],dtype = tf.float32)
return X, Y
# In[40]:
def initialize_parameters():
"""
Initializes weight parameters to build a neural network with tensorflow. The shapes are:
W1 : [4, 4, 3, 8]
W2 : [2, 2, 8, 16]
Returns:
parameters -- a dictionary of tensors containing W1, W2
"""
tf.set_random_seed(1) # so that your "random" numbers match ours
W1 = tf.get_variable("W1",[4, 4, 3, 8], initializer = tf.contrib.layers.xavier_initializer(seed = 0))
W2 = tf.get_variable("W2",[2, 2, 16,16], initializer = tf.contrib.layers.xavier_initializer(seed = 0))
parameters = {"W1": W1,
"W2": W2}
return parameters
# In[ ]:
def forward_propagation(X, parameters):
W1 = parameters['W1']
W2 = parameters['W2']
with tf.device('/device:CPU:0'):
Z1 = tf.nn.conv2d(X,W1,strides = [1,2,2,1], padding = 'SAME')
A1 = tf.nn.dropout(tf.nn.relu(Z1),keep_prob = 0.9)
P1 = tf.nn.max_pool(A1,ksize = [1,8,8,1], strides = [1,8,8,1],padding = 'SAME')
Z2 = tf.nn.conv2d(P1, W2, strides=[1, 1, 1, 1], padding='SAME')
A2 = tf.nn.dropout(tf.nn.relu(Z2),keep_prob = 0.8)#relu(Z2)
P2 = tf.nn.max_pool(A2, ksize = [1, 4,4, 1], strides = [1, 2,2, 1], padding='SAME')
Z3 = tf.nn.conv2d(P2, W2, strides=[1, 1, 1, 1], padding='SAME')
A3 = tf.nn.dropout(tf.nn.relu(Z3),keep_prob = 0.8)
P3 = tf.nn.max_pool(A3, ksize = [1, 4,4, 1], strides = [1, 2,2, 1], padding='SAME')
# FLATTEN
P = tf.contrib.layers.flatten(P3)
Z4 = tf.contrib.layers.fully_connected(P, 12, activation_fn=None)
Z5 = tf.nn.dropout(tf.contrib.layers.fully_connected(Z3, 12, activation_fn=None),keep_prob = 0.8)
return Z5,Z3
def compute_cost(Z5, Y):
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = Z5, labels = Y))
return cost
# In[57]:
from tensorflow.python.framework import ops
def model(X_train, Y_train, X_test, Y_test, learning_rate=0.009,
num_epochs=100, minibatch_size=64, print_cost=True):
"""
Implements a three-layer ConvNet in Tensorflow:
CONV2D -> RELU -> MAXPOOL -> CONV2D -> RELU -> MAXPOOL -> FLATTEN -> FULLYCONNECTED
Arguments:
X_train -- training set, of shape (None, 64, 64, 3)
Y_train -- test set, of shape (None, n_y = 6)
X_test -- training set, of shape (None, 64, 64, 3)
Y_test -- test set, of shape (None, n_y = 6)
learning_rate -- learning rate of the optimization
num_epochs -- number of epochs of the optimization loop
minibatch_size -- size of a minibatch
print_cost -- True to print the cost every 100 epochs
Returns:
train_accuracy -- real number, accuracy on the train set (X_train)
test_accuracy -- real number, testing accuracy on the test set (X_test)
parameters -- parameters learnt by the model. They can then be used to predict.
"""
ops.reset_default_graph() # to be able to rerun the model without overwriting tf variables
tf.set_random_seed(1) # to keep results consistent (tensorflow seed)
seed = 3 # to keep results consistent (numpy seed)
(m, n_H0, n_W0, n_C0) = X_train.shape
n_y = Y_train.shape[1]
costs = [] # To keep track of the cost
# Create Placeholders of the correct shape
X, Y = create_placeholders(n_H0, n_W0, n_C0, n_y)
# Initialize parameters
parameters = initialize_parameters()
# Forward propagation: Build the forward propagation in the tensorflow graph
Z5,Z3 = forward_propagation(X, parameters)
# Cost function: Add cost function to tensorflow graph
#cost = compute_cost(Z3, Y)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = Z3, labels = Y))
with tf.name_scope('Optimizer'):
# Backpropagation: Define the tensorflow optimizer. Use an AdamOptimizer that minimizes the cost.
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
#summary_op = tf.summary.merge_all()
config = tf.ConfigProto(log_device_placement=True)
config.gpu_options.allow_growth = True
sess = tf.Session(config = config)
init = tf.global_variables_initializer()
merged = tf.summary.merge([tf.summary.scalar('cross_entropy', cost)])
writer = tf.summary.FileWriter(os.path.join(os.getcwd(),"logs"), graph=sess.graph)
with sess.as_default():
sess.run(init)
# Do the training loop
for epoch in range(num_epochs):
start = time.time()
minibatch_cost = 0.
num_minibatches = int(m / minibatch_size) # number of minibatches of size minibatch_size in the train set
batch_count = int(m/minibatch_size)
seed = seed + 1
minibatches = random_mini_batches(X_train, Y_train, minibatch_size, seed)
#c = 0
for minibatch in minibatches:
(minibatch_X, minibatch_Y) = minibatch
_ , temp_cost,summary= sess.run([optimizer, cost,merged], feed_dict={X:minibatch_X, Y:minibatch_Y})
#c += 1
minibatch_cost += temp_cost / num_minibatches
#print(type(summary))
if minibatch_cost <= 0.4 and costs[-1] - minibatch_cost <= 0.001:
break;
writer.add_summary(summary, epoch)
if print_cost == False:
drawProgressBar(epoch/num_epochs,barLen = 50)
# Print the cost every epoch
if print_cost == True and num_epochs<100 and epoch % 2 == 0:
end = time.time()
print ("Cost after epoch {}: {}\t time taken:{}".format(epoch, minibatch_cost,(end-start)))
if print_cost == True and num_epochs>=100:
if epoch % 10 == 0:
end = time.time()
print ("Cost after epoch {}: {}\t time taken:{}".format(epoch, minibatch_cost,(end-start)))
if print_cost == True and epoch % 1 == 0:
costs.append(minibatch_cost)
# plot the cost
plt.figure(figsize = (5,5))
plt.plot(np.squeeze(costs))
plt.ylabel('cost')
plt.xlabel('iterations (per tens)')
plt.title("Learning rate =" + str(learning_rate))
#plt.savefig("asd.png")
plt.show()
with tf.device('/device:CPU:0'):
# Calculate the correct predictions
predict_op = tf.argmax(Z3, 1)
correct_prediction = tf.equal(predict_op, tf.argmax(Y, 1))
# Calculate accuracy on the test set
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
print(accuracy)
train_accuracy = accuracy.eval({X: X_train, Y: Y_train})
test_accuracy = accuracy.eval({X: X_test, Y: Y_test})
print("Train Accuracy:", train_accuracy)
print("Test Accuracy:", test_accuracy)
return train_accuracy, test_accuracy, parameters
print("\ndropout in non linear transformation layers, 3000 epochs, 1024 batch size\n")
start = time.time()
_, _, parameters = model(train_x, train_y, test_x, test_y,learning_rate=0.009,
num_epochs=3000, minibatch_size = 1024, print_cost=True)
end = time.time()
ttl = end-start
seconds = ttl%60
ttl//=60
if ttl > 60:
minutes = ttl//60
ttl//=60
hrs = ttl
print("Time take: {} hours, {} minutes and {} seconds".format(hrs,minutes,seconds))
|
TypeScript
|
UTF-8
| 287 | 2.71875 | 3 |
[] |
no_license
|
import Ajv from 'ajv'
interface Validation {
valid: boolean
error?: string
}
export default (schema: any, data: any): Validation => {
const ajv = new Ajv()
const valid = ajv.validate(schema, data)
if (valid) { return { valid } }
return { valid, error: ajv.errorsText() }
}
|
TypeScript
|
UTF-8
| 1,470 | 2.6875 | 3 |
[] |
no_license
|
import { testGraphQl } from '../../lib/testHelpers';
import { expect } from 'chai';
describe('GraphQL: species', () => {
it('queries without inputs', async (): Promise<void> => {
const query = `query {
species {
name
id
}
}`;
const res = await testGraphQl(query);
expect(res.data.species.length).to.equal(37);
expect(res.data.species[0]).to.eql({ name: 'Human', id: 1 });
});
it('queries with planetID input', async (): Promise<void> => {
const query = `query {
species(planetId: 23) {
name
id
}
}`;
const res = await testGraphQl(query);
expect(res.data.species.length).to.equal(1);
expect(res.data.species[0]).to.eql({ name: 'Rodian', id: 4 });
});
it('queries with movieId input', async (): Promise<void> => {
const query = `query {
species(movieId: 5) {
name
id
}
}`;
const res = await testGraphQl(query);
expect(res.data.species.length).to.equal(14);
expect(res.data.species[0]).to.eql({ name: 'Human', id: 1 });
});
it('queries combined input', async (): Promise<void> => {
const query = `query {
species(movieId: 1, planetId: 23) {
name
id
}
}`;
const res = await testGraphQl(query);
expect(res.data.species.length).to.equal(1);
expect(res.data.species[0]).to.eql({ name: 'Rodian', id: 4 });
});
});
|
PHP
|
UTF-8
| 199 | 2.65625 | 3 |
[] |
no_license
|
<?php
if (isset($_POST['ticket_type'])) {
require_once('../classes/Tickets.php');
$tick = new Tickets();
if ($tick->insertTicket($_POST)) {
echo "Success";
} else {
echo "Failure";
}
}
?>
|
Markdown
|
UTF-8
| 6,538 | 3.03125 | 3 |
[] |
no_license
|
+++
title = "Connection handshakes"
description = "How to handle initial steps in a protocol"
menu = "going_deeper"
weight = 104
+++
Some protocols require some setup before they can start accepting requests. For
example, PostgreSQL requires a [start-up
message](https://www.postgresql.org/docs/9.3/static/protocol-flow.html#AEN99290),
Transport Layer Security requires a
[handshake](https://en.wikipedia.org/wiki/Transport_Layer_Security#TLS_handshake),
and so does [HTTP/2.0](http://httpwg.org/specs/rfc7540.html#starting). This
section will show how to model that using Tokio.
This guide will build off of the [simple line-based
protocol]({{< relref "simple-server.md" >}}) we saw earlier. Let's look at the
protocol specification again:
```rust,ignore
use tokio_proto::pipeline::ServerProto;
struct LineProto;
impl<T: Io + 'static> ServerProto<T> for LineProto {
type Request = String;
type Response = String;
type Error = io::Error;
// `Framed<T, LineCodec>` is the return value of
// `io.framed(LineCodec)`
type Transport = Framed<T, LineCodec>;
type BindTransport = Result<Self::Transport, io::Error>;
fn bind_transport(&self, io: T) -> Self::BindTransport {
Ok(io.framed(LineCodec))
}
}
```
The [`BindTransport`] associated type, returned from the `bind_transport`
function is an [`IntoFuture`]. This means that all connection setup work
can be done before realizing the `BindTransport` future. So far, none of our
protocols needed any setup, so we just used `Result`. But now, we're going
to change that.
[`BindTransport`]: https://tokio-rs.github.io/tokio-proto/tokio_proto/pipeline/trait.ServerProto.html#associatedtype.BindTransport
[`IntoFuture`]: https://docs.rs/futures/0.1/futures/future/trait.IntoFuture.html
## [Implementing the handshake](#implementing-handshake) {#implementing-handshake}
We're going to modify our line-based protocol. When a client connects to a
server, it has to send the following line: `You ready?`. Once the server is
ready to accept requests, it responds with: `Bring it!`. If the server wants to
reject the client for some reason, it responds with: `No! Go away!`. The client
is then expected to close the socket.
The server implementation of the handshake looks like this:
```rust,ignore
// Construct the line-based transport
let transport = io.framed(LineCodec);
// The handshake requires that the client sends `You ready?`, so wait to
// receive that line. If anything else is sent, error out the connection
transport.into_future()
// If the transport errors out, we don't care about the transport
// anymore, so just keep the error
.map_err(|(e, _)| e)
.and_then(|(line, transport)| {
// A line has been received, check to see if it is the handshake
match line {
Some(ref msg) if msg == "You ready?" => {
println!("SERVER: received client handshake");
// Send back the acknowledgement
Box::new(transport.send("Bring it!".to_string()))
as Self::BindTransport
}
_ => {
// The client sent an unexpected handshake, error out
// the connection
println!("SERVER: client handshake INVALID");
let err = io::Error::new(io::ErrorKind::Other,
"invalid handshake");
Box::new(future::err(err)) as Self::BindTransport
}
}
})
```
The transport returned by `Io::framed` is a value implementing [`Stream`] +
[`Sink`] over the frame type. In our case, the frame type is `String`, so we can
use the transport directly in order to implement our handshake logic.
[`Stream`]: https://docs.rs/futures/0.1/futures/stream/trait.Stream.html
[`Sink`]: https://docs.rs/futures/0.1/futures/sink/trait.Sink.html
The above snippet returns a future that completes with the transport when the
handshake has been completed.
## [Updating the protocol](#updating-protocol) {#updating-protocol}
The next step is to update the `bind_transport` function in our protocol
specification. Instead of returning the transport directly, we will perform the
handshake shown above. Here's the full code:
```rust,ignore
impl<T: Io + 'static> ServerProto<T> for ServerLineProto {
type Request = String;
type Response = String;
type Error = io::Error;
// `Framed<T, LineCodec>` is the return value of
// `io.framed(LineCodec)`
type Transport = Framed<T, line::LineCodec>;
type BindTransport = Box<Future<Item = Self::Transport,
Error = io::Error>>;
fn bind_transport(&self, io: T) -> Self::BindTransport {
// Construct the line-based transport
let transport = io.framed(line::LineCodec);
// The handshake requires that the client sends `You ready?`, so
// wait to receive that line. If anything else is sent, error out
// the connection
let handshake = transport.into_future()
// If the transport errors out, we don't care about the
// transport anymore, so just keep the error
.map_err(|(e, _)| e)
.and_then(|(line, transport)| {
// A line has been received, check to see if it is the
// handshake
match line {
Some(ref msg) if msg == "You ready?" => {
println!("SERVER: received client handshake");
// Send back the acknowledgement
Box::new(transport.send("Bring it!".to_string()))
as Self::BindTransport
}
_ => {
// The client sent an unexpected handshake, error
// out the connection
println!("SERVER: client handshake INVALID");
let err = io::Error::new(io::ErrorKind::Other,
"invalid handshake");
Box::new(future::err(err)) as Self::BindTransport
}
}
});
Box::new(handshake)
}
}
```
Then, if we use `TcpServer` to start a server with our `ServerLineProto`, the
handshake will be performed before requests start being processed.
The full working code for both the client and server can be found
[here](https://github.com/tokio-rs/tokio-line/blob/master/simple/examples/handshake.rs).
|
Swift
|
UTF-8
| 891 | 2.546875 | 3 |
[] |
no_license
|
//
// ListViewModel.swift
// StarWarsCleanArch
//
// Created by Miguel Barone - MBA on 28/02/20.
// Copyright © 2020 Miguel Barone - MBA. All rights reserved.
//
import Foundation
import RxCocoa
import RxSwift
protocol ListViewModelContract {
var swList: Driver<[SWResponse]?> { get }
func showList()
}
class ListViewModel: ListViewModelContract {
private let swStateRelay: BehaviorRelay<[SWResponse]?> = BehaviorRelay(value: nil)
var swList: Driver<[SWResponse]?> { return swStateRelay.asDriver() }
let swListUseCase: SWListUseCase
let disposeBag = DisposeBag()
init(swListUseCase: SWListUseCase) {
self.swListUseCase = swListUseCase
}
func showList() {
swListUseCase.getSWList().subscribe(onSuccess: { (swPeoples) in
self.swStateRelay.accept(swPeoples)
}).disposed(by: disposeBag)
}
}
|
Java
|
UTF-8
| 863 | 2.203125 | 2 |
[
"Apache-2.0"
] |
permissive
|
package net.onrc.onos.apps.proxyarp.web;
import net.floodlightcontroller.restserver.RestletRoutable;
import org.restlet.Context;
import org.restlet.Restlet;
import org.restlet.routing.Router;
/**
* Routing class for ARP module REST URLs.
*/
public class ArpWebRoutable implements RestletRoutable {
/**
* Get a router configured with ARP module REST URLs.
*
* @param context the restlet context to build a router with
* @return the router
*/
@Override
public Restlet getRestlet(Context context) {
Router router = new Router(context);
router.attach("/cache/json", ArpCacheResource.class);
return router;
}
/**
* Get the base path of the ARP module URLs.
*
* @return the string base path
*/
@Override
public String basePath() {
return "/wm/arp";
}
}
|
Java
|
UTF-8
| 1,081 | 3.390625 | 3 |
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
/*
* Hackerrank Jobs Coding Challenge
* Hackerrank Software Engineer position
*/
public class CountingBinarySubstring {
public static void main(String[] args) {
System.out.println(counting("0000011110010110100110001"));
}
static int counting(String s) {
int counter = 0;
int i = 0;
boolean isZero = false;
int num_1 = 0;
int num_0 = 0;
// 00110
for(char c : s.toCharArray()) {
if(c == '0') {
if(!isZero) {
num_0 = 1;
} else {
num_0++;
}
if(num_1 >= num_0) {
counter++;
}
isZero = true;
} else {
if(isZero) {
num_1 = 1;
} else {
num_1++;
}
if(num_0 >= num_1) {
counter++;
}
isZero = false;
}
i++;
}
return counter;
}
}
|
JavaScript
|
UTF-8
| 1,567 | 2.5625 | 3 |
[] |
no_license
|
import React, { useState } from "react";
import axios from "axios";
import { BASE_URL } from "../Constant/Constant";
import GlobalStateContext from "./GlobalStateContext";
import useRequestData from "../Hooks/useRequestData";
const GlobalState = (props) => {
const [pokedexList, setPokedexList] = useState([]);
const [pokemonsHome, setPokemonsHome] = useState([]);
const pokemonsName = useRequestData(BASE_URL, []);
const [name, setName] = useState("");
const [image, setImage] = useState({});
const [stats, setStats] = useState([]);
const [types, setTypes] = useState([]);
const [moves, setMoves] = useState([]);
const [pokemon, setPokemon] = useState();
const getPokemons = async () => {
let detailsArray = [];
try {
for (const pokemon of pokemonsName) {
const response = await axios.get(`${BASE_URL}${pokemon.name}`);
detailsArray.push(response.data);
}
} catch (error) {}
if (pokemonsHome.length === 0 && pokedexList.length === 0) {
setPokemonsHome(detailsArray);
}
};
const states = {
pokemonsHome,
pokedexList,
name,
image,
stats,
types,
moves,
pokemon,
};
const setters = {
setPokemonsHome,
setPokedexList,
setName,
setImage,
setStats,
setTypes,
setMoves,
setPokemon,
};
const requests = { getPokemons };
const data = { states, setters, requests };
return (
<GlobalStateContext.Provider value={data}>
{props.children}
</GlobalStateContext.Provider>
);
};
export default GlobalState;
|
Markdown
|
UTF-8
| 1,836 | 2.515625 | 3 |
[
"CC-BY-4.0",
"MIT"
] |
permissive
|
---
title: コンパイラ エラー C2593
ms.date: 11/04/2016
f1_keywords:
- C2593
helpviewer_keywords:
- C2593
ms.assetid: 4a0fe9bb-2163-447d-91f6-1890ed8250f6
ms.openlocfilehash: c358553a36104b5c389076f5a5ce02f94f85e85a
ms.sourcegitcommit: 0ab61bc3d2b6cfbd52a16c6ab2b97a8ea1864f12
ms.translationtype: MT
ms.contentlocale: ja-JP
ms.lasthandoff: 04/23/2019
ms.locfileid: "62386916"
---
# <a name="compiler-error-c2593"></a>コンパイラ エラー C2593
'operator identifier' があいまいです。
オーバー ロードされた演算子の 1 つ以上の可能な演算子が定義されます。
1 つまたは複数の実際のパラメーターで明示的なキャストを使用する場合、このエラーを修正しました可能性があります。
次の例では、C2593 が生成されます。
```
// C2593.cpp
struct A {};
struct B : A {};
struct X {};
struct D : B, X {};
void operator+( X, X );
void operator+( A, B );
D d;
int main() {
d + d; // C2593, D has an A, B, and X
(X)d + (X)d; // OK, uses operator+( X, X )
}
```
このエラーは、浮動小数点変数を使用して、シリアル化によって発生することができます、`CArchive`オブジェクト。 コンパイラの識別、`<<`演算子。 プリミティブのみの C++ の種類を`CArchive`をシリアル化できるが固定サイズ型`BYTE`、 `WORD`、 `DWORD`、および`LONG`します。 すべての整数型は、シリアル化のこれらの型のいずれかにキャストする必要があります。 浮動小数点型を使用してアーカイブする必要があります、`CArchive::Write()`メンバー関数。
次の例では、浮動小数点変数をアーカイブする方法を示しています (`f`) アーカイブに`ar`:
```
ar.Write(&f, sizeof( float ));
```
|
Java
|
UTF-8
| 8,960 | 3.21875 | 3 |
[] |
no_license
|
import java.awt.Color;
import edu.princeton.cs.algs4.Bag;
import edu.princeton.cs.algs4.Point2D;
import edu.princeton.cs.algs4.Queue;
import edu.princeton.cs.algs4.RectHV;
import edu.princeton.cs.algs4.StdDraw;
/*
* A 2d-tree is a generalization of a BST to two-dimensional keys. The idea is
* to build a BST with points in the nodes, using the x- and y-coordinates of
* the points as keys in strictly alternating sequence.
*/
public class KdTree {
private Node root; // root of the 2dTree
private int n; // size of the 2dTree
private Point2D champion = null; // nearest neighbor
private double minDist = Double.MAX_VALUE; // minimum distance
// kDtree helper node data type
private class Node {
private Point2D point; // key
private boolean useX; // use x coordinate to insert
private RectHV rect; // node rectangle
private Node left, right; // links to left and right subtrees
public Node(Point2D point, boolean useX, RectHV rect) {
this.point = point;
this.useX = useX;
this.rect = rect;
this.left = null;
this.right = null;
}
}
/**
* Initializes an empty KdTree.
*/
public KdTree() {
n = 0;
root = null;
}
/**
* Returns true if this KdTree is empty.
*
* @return <tt>true</tt> if this KdTree is empty; <tt>false</tt> otherwise
*/
public boolean isEmpty() {
return (root == null);
}
/**
* Returns the number of points in this KdTree.
*
* @return the number of points in this KdTree
*/
public int size() {
return n;
}
// throws an exception if a point is null
private void checkPoint(Point2D p) {
if (p == null)
throw new java.lang.NullPointerException("Null point");
}
// throws an exception if a rectangle is null
private void checkRect(RectHV rect) {
if (rect == null)
throw new java.lang.NullPointerException("Null rectangle");
}
/**
* Inserts the specified point into the KdTree, overwriting the old if it is
* not already in the KdTree.
*
* @param p
* the point
* @throws NullPointerException
* if <tt>p</tt> is <tt>null</tt>
*/
public void insert(Point2D p) {
checkPoint(p);
root = put(root, p);
root.rect = new RectHV(0, 0, 1, 1);
}
// compares a point and a node based on useX
private int compareNP(Node node, Point2D p) {
double dx = node.point.x() - p.x();
double dy = node.point.y() - p.y();
if (dx == 0 && dy == 0)
return 0;
if (node.useX && dx > 0)
return 1;
if (!node.useX && dy > 0)
return 1;
return -1;
}
// recursively find position for point p
private Node put(Node x, Point2D p) {
if (x == null) {
n++;
return new Node(p, true, null);
}
int cmp = compareNP(x, p);
if (cmp == 0)
return x;
else if (cmp > 0) {
x.left = put(x.left, p);
x.left.useX = !x.useX;
if (x.useX)
x.left.rect = new RectHV(x.rect.xmin(), x.rect.ymin(),
x.point.x(), x.rect.ymax());
else
x.left.rect = new RectHV(x.rect.xmin(), x.rect.ymin(),
x.rect.xmax(), x.point.y());
} else {
x.right = put(x.right, p);
x.right.useX = !x.useX;
if (x.useX)
x.right.rect = new RectHV(x.point.x(), x.rect.ymin(), x.rect.xmax(),
x.rect.ymax());
else
x.right.rect = new RectHV(x.rect.xmin(), x.point.y(),
x.rect.xmax(), x.rect.ymax());
;
}
return x;
}
/**
* Returns true if this KdTree contains the point p.
*
* @param p
* the point
* @return <tt>true</tt> if this KdTree icontains the point p.y;
* <tt>false</tt> otherwise
*/
public boolean contains(Point2D p) {
checkPoint(p);
return search(root, p);
}
// search recursively for point p
private boolean search(Node x, Point2D p) {
if (x == null)
return false;
// compare new node created from p with root
int cmp = compareNP(x, p);
if (cmp > 0)
return search(x.left, p);
else if (cmp < 0)
return search(x.right, p);
else
return true;
}
private Iterable<Node> levelOrder() {
Queue<Node> nodes = new Queue<Node>();
Queue<Node> queue = new Queue<Node>();
queue.enqueue(root);
while (!queue.isEmpty()) {
Node x = queue.dequeue();
if (x == null)
continue;
nodes.enqueue(x);
queue.enqueue(x.left);
queue.enqueue(x.right);
}
return nodes;
}
/**
* Draws all points to standard draw
*
* @return void
*/
public void draw() {
for (Node node : levelOrder()) {
StdDraw.setPenColor(Color.BLACK);
StdDraw.setPenRadius(.01);
node.point.draw();
if (node.useX) {
StdDraw.setPenRadius(.005);
StdDraw.setPenColor(Color.RED);
StdDraw.line(node.point.x(), node.rect.ymin(), node.point.x(),
node.rect.ymax());
} else {
StdDraw.setPenRadius(.005);
StdDraw.setPenColor(Color.BLUE);
StdDraw.line(node.rect.xmin(), node.point.y(), node.rect.xmax(),
node.point.y());
}
}
}
/**
* Returns all points in the kDTree inside a query rectangle as an
* <tt>Iterable</tt>. To iterate over all of the points in the rectangle
* <tt>rect</tt>, use the foreach notation:
* <tt>for (Point2D p : kd.range(rect))</tt>.
*
* @param rect
* the rectangle query
* @return all keys in a rectangle
*/
public Iterable<Point2D> range(RectHV rect) {
checkRect(rect);
Bag<Point2D> nodes = new Bag<Point2D>();
Queue<Node> queue = new Queue<Node>();
queue.enqueue(root);
while (!queue.isEmpty()) {
Node x = queue.dequeue();
if (x == null)
continue;
if (rect.intersects(x.rect)) {
if (rect.contains(x.point))
nodes.add(x.point);
queue.enqueue(x.left);
queue.enqueue(x.right);
}
}
return nodes;
}
/**
* Returns the nearest point in the kDTree given a query point.
*
* @param query
* the point query
* @return all keys in a rectangle
*/
public Point2D nearest(Point2D query) {
checkPoint(query);
// set root as champion
if (root == null)
return null;
champion = root.point;
minDist = query.distanceSquaredTo(champion);
// find nearest recursively
nearest(root, query);
return champion;
}
// recursively searches for the nearest point
private void nearest(Node node, Point2D query) {
// check if node is a new champion
double dist = node.point.distanceSquaredTo(query);
if (dist < minDist) {
champion = node.point;
minDist = dist;
}
// both nodes exist
if (node.left != null && node.right != null) {
// compute distances to query point
double left = node.left.rect.distanceSquaredTo(query);
double right = node.right.rect.distanceSquaredTo(query);
// alternate searching based on smaller query distances
if (left < right) {
nearest(node.left, query);
// prune right node if distance is less than minimum
if (right < minDist)
nearest(node.right, query);
} else {
nearest(node.right, query);
// prune left node if distance is less than minimum
if (left < minDist)
nearest(node.left, query);
}
return;
}
// left node exists
if (node.left != null) {
// prune left node if distance is less than minimum
if (node.left.rect.distanceSquaredTo(query) < minDist) {
nearest(node.left, query);
}
}
// right node exists
if (node.right != null) {
// prune right node if distance is less than minimum
if (node.right.rect.distanceSquaredTo(query) < minDist) {
nearest(node.right, query);
}
}
return;
}
public static void main(String[] args) {
KdTree kd = new KdTree();
kd.insert(new Point2D(0.7, 0.2));
kd.insert(new Point2D(0.7, 0.2));
kd.insert(new Point2D(0.5, 0.4));
kd.insert(new Point2D(0.2, 0.3));
kd.insert(new Point2D(0.4, 0.7));
kd.insert(new Point2D(0.9, 0.6));
System.out.println("tree size = " + kd.size());
RectHV rect = new RectHV(0, 0, 0.5, 0.5);
// StdDraw.setPenColor(StdDraw.BLACK);
// StdDraw.setPenRadius();
// rect.draw();
System.out.println("\n Points in rectangle [0, 0, 0.5, 0.5]");
for (Point2D p : kd.range(rect))
System.out.println(p);
kd.draw();
StdDraw.show();
System.out.println("\n Nearest Point (1., 1.)");
System.out.println(kd.nearest(new Point2D(1., 1.)));
}
}
|
C++
|
UTF-8
| 529 | 2.953125 | 3 |
[] |
no_license
|
class Solution {
public:
int numberOfArithmeticSlices(vector<int>& a) {
if(a.size()<3)
return 0;
int ans = 0;
int ptr1 = 0, ptr2 = 2;
int curr_diff = a[ptr1+1] - a[ptr1];
while(ptr2<a.size())
{
if(a[ptr2]-a[ptr2-1] == curr_diff)
ans += ptr2-ptr1 - 1;
else
{
ptr1 = ptr2-1;
curr_diff = a[ptr2] - a[ptr2-1];
}
ptr2++;
}
return ans;
}
};
|
C
|
UTF-8
| 866 | 3.265625 | 3 |
[] |
no_license
|
// LIST THE CONTENTS OF A TEXT FILE ON THE TERMINAL OR A FILE
// USAGE: p3b <text file> [<destination>]
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#define LENGTH 1024
int main(int argc, char *argv[]) {
int src, dst, nr;
char *buffer[LENGTH];
if (!(argc == 2 || argc == 3)) {
printf("Usage: %s <text file> [<destination>]\n", argv[0]);
return 1;
}
if ((src = open(argv[1], O_RDONLY)) == -1) {
perror(argv[1]);
return 2;
}
if (argc == 3) {
if ((dst = open(argv[2], O_WRONLY|O_CREAT|O_TRUNC, 0600)) == -1) {
perror(argv[2]);
return 3;
}
dup2(dst, STDOUT_FILENO); // redirect STDOUT_FILENO to dst
}
while ((nr=read(src, buffer, LENGTH)) != 0)
write(STDOUT_FILENO, buffer, nr); // write the same nr of bytes on the terminal or file
close(src);
return 0;
}
|
C
|
UTF-8
| 721 | 3.984375 | 4 |
[] |
no_license
|
//normal function call using char and passing arguments using char.
// for single char use single quote', for many char(string) use double quote"
//diff representations:
//char a ='b';
//char b[13] = "abi is good";
//char c[4] = {'h','e','l'}; //size should be one more than the total string
#include<stdio.h>
char func(char a, char b) //called fucntion: arg are char type
{
char A = 'g'; //represent in single quote
printf("entered a: %c\n", a);
printf("entered b: %c\n", b);
return A; //returning the singe char A whose value is 'g'.
}
void main()
{
char x = 'i', y = 'T';
//x and y char arguments are passed with func
char h = func(x,y); //returned func is stored in char variable h.
printf("normal: %c\n", h);
}
|
Java
|
GB18030
| 2,227 | 1.765625 | 2 |
[] |
no_license
|
package org.wx;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.WxBeanFactoryImpl;
import org.springframework.transaction.annotation.Transactional;
import org.apache.log4j.Logger;
import org.dao.WxAssertDao;
import org.dao.WxPromotionGiftDao;
import org.dao.WxUserDao;
import org.entity.asserts.WxAssert;
import org.entity.WxPromotionGift;
import org.entity.WxUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;
import org.util.WxUtils;
@Component("promotionManager")
public class PromotionManager {
@Autowired
JdbcTemplate jdbcTemplate;
@Autowired
WxPromotionGiftDao wxPromotionGiftDao;
@Autowired
WxUserDao wxUserDao;
@Autowired
WxAssertDao wxAssertDao;
//TODO úҪ
public boolean ggkIncomeGift(long userId, String giftId,String ipAddress) {
//System.out.println("-----ipAddress=" + ipAddress);
WxUser wxUser = wxUserDao.findById(userId);
WxPromotionGift pg = wxPromotionGiftDao.findById(giftId);
{ //TODO ǷѾ
pg.setGainDate(new Date());
pg.setGainWay("ιο");
pg.setGainer(wxUser);
pg.setStatus(2);
pg.setIpAddress(ipAddress);
wxPromotionGiftDao.save(pg);
}
if (pg.getAssertType().getId().intValue() == 0 || pg.getAssertType() == null) {
return true;
}
BigDecimal id = WxUtils.getSeqencesValue();
WxAssert war = new WxAssert();
war.setId(id);
war.setAssertType(pg.getAssertType());
war.setWxUser(wxUser);
war.setFaceValue(pg.getFaceVaule());
war.setWxPromotionGift(pg);
war.setOccurDate(new Date());
war.setRemark("Թιο");
wxAssertDao.save(war);
return true;
}
}
|
C#
|
UTF-8
| 1,048 | 2.875 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Text;
namespace ConnectionsSquare
{
public static class FamilyManager
{
public static List<GenericLocalMap<Being>> families = new List<GenericLocalMap<Being>>();
public static void GenerateFamilies()
{
families.Add(TileSquareFamilyCreator.GenerateFamily(5));
PositionFamiles();
AddBeingsToManager();
}
//Obvi if we ever have multiple families we'll need to position better
public static void PositionFamiles() => families.ForEach(x => FamilyPositioner.PositionFamily(x, new Point(400, 400), 0));
static void AddBeingsToManager()
{
foreach(var family in families)
{
foreach(var beingRow in family.map)
{
foreach(var being in beingRow.Value)
{
AllBeings.RegisterBeing(being.Value);
}
}
}
}
}
}
|
C++
|
UTF-8
| 1,808 | 3.859375 | 4 |
[] |
no_license
|
#include <iostream>
using s = unsigned short;
int main(){
unsigned short number {16387};
std::cout << sizeof(number) << " bytes" << std::endl;
//shift left by 2 bit positions
auto result {static_cast<s> (number << 2)}; //without casting, it is treated as int
std::cout << result << std::endl;
// std::cout << std::to_binary(number) << std::endl;
unsigned short n {12345};
//modify the original number
n >>= 2; //shift right two positions
//AND operators
// unsigned short font {0x064C}; //style 6, italic, 12 point
//in c++14 onwards we can write like this
unsigned short font {0b00000110'0'10'01100}; //style 6, italic, 12 point
//to get the different parts use masks
unsigned short size_mask {0x1F}; //the first low-order bits represent its size like 01100 above
//extract
auto size {static_cast<s> (font & size_mask)};
std::cout << size << std::endl;
//we can extract the style but here we have to shift the value also
s style_mask {0xFF00}; // 1111 1111 0000 0000
auto style {static_cast<s> ((font & style_mask) >> 8)}; //pointing right means right shift
// OR operator
//italic bit is 7th bits
// bold bit is 6th bit
// turn it on, maeke it 1
auto italic {static_cast<unsigned short> (1u << 6)}; //7th bit from the right
auto bold {static_cast<unsigned short> (1u << 5)}; //6th bit from the right
//make bold bit on
font |= bold; //set bold
//efficient way to apply mask is to take complement
//or else you need to know exaclty which position to apply mask which lacks portability
font &= ~bold; //turn bold off
font &= ~bold & ~italic; //turn bold and italic off
//the above statement can be written as
// font &= ~(bold | italic); //some a' . b' = (a+b)'
std::cout<< std::hex << font << std::endl;
}
|
C#
|
UTF-8
| 9,898 | 2.65625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using X.PagedList;
using System.Collections;
using System.ComponentModel.DataAnnotations;
namespace RaceAnalysis.Models
{
public class TriathletesViewModel :BaseViewModel
{
public int TotalCount { get; set; }
public int SelectedAthleteId { get; set; }
public string SelectedAthleteName { get; set; }
public string SelectedAgeGroup { get; set; } //the age group of the selected athlete
public string SelectedGender { get; set; } //the gender of the selected athlete
public IEnumerable<ShallowTriathlete> Athletes { get; set; }
public GoogleVisualizationDataTable AthletesTable
{
get
{
var dataTable = new GoogleVisualizationDataTable();
dataTable.AddColumn("Race", "string", "domain");
dataTable.AddColumn("Athlete", "string", "data");
dataTable.AddColumn("Country", "string", "data");
dataTable.AddColumn("Div Rank", "string", "data");
dataTable.AddColumn("Gender Rank", "string", "data");
dataTable.AddColumn("Overall Rank", "string", "data");
dataTable.AddColumn("Swim", "timeofday", "data");
dataTable.AddColumn("Bike", "timeofday", "data");
dataTable.AddColumn("Run", "timeofday", "data");
dataTable.AddColumn("Finish", "timeofday", "data");
foreach (Triathlete athlete in base.Triathletes.OrderBy(t => t.Race.RaceDate))
{
var row = new List<object>();
row.Add(athlete.Race.DisplayName);
row.Add(athlete.Name);
row.Add(athlete.Country);
row.Add(athlete.DivRank);
row.Add(athlete.GenderRank);
row.Add(athlete.OverallRank);
row.Add(new int[] { athlete.Swim.Hours, athlete.Swim.Minutes, athlete.Swim.Seconds }); //each of these sub-arrays are to build the time for 1 thing we are measuring
row.Add(new int[] { athlete.Bike.Hours, athlete.Bike.Minutes, athlete.Bike.Seconds });
row.Add(new int[] { athlete.Run.Hours, athlete.Run.Minutes, athlete.Run.Seconds });
row.Add(new int[] { athlete.Finish.Hours, athlete.Finish.Minutes, athlete.Finish.Seconds });
dataTable.AddRow(row);
}
return dataTable;
}
}
public GoogleVisualizationDataTable SingleRaceChart
{
get
{
var dataTable = new GoogleVisualizationDataTable();
dataTable.AddColumn("Name", "string", "domain");
dataTable.AddColumn("Swim", "timeofday", "data");
dataTable.AddColumn("Bike", "timeofday", "data");
dataTable.AddColumn("Run", "timeofday", "data");
dataTable.AddColumn("T1 & T2", "timeofday", "data");
dataTable.AddColumn("", "string", "annotation");
//athlete stats:
foreach (Triathlete athlete in Triathletes)
{
var row = new List<object>();
row.Add(new object[] { athlete.Name });
row.Add(new object[]
{ athlete.Swim.Hours, athlete.Swim.Minutes, athlete.Swim.Seconds });
row.Add(new object[]
{ athlete.Bike.Hours, athlete.Bike.Minutes, athlete.Bike.Seconds });
row.Add(new object[]
{ athlete.Run.Hours, athlete.Run.Minutes, athlete.Run.Seconds });
if (athlete.Finish.TotalSeconds > 0)
{
TimeSpan finish = athlete.Finish;
TimeSpan total = (athlete.Swim + athlete.Bike + athlete.Run);
TimeSpan tTime;
if (finish > total)
tTime = finish - total;
else
tTime = total - finish;
row.Add(new object[]
{ tTime.Hours, tTime.Minutes, tTime.Seconds });
}
else
{
row.Add(new object[] { 0, 0, 0 });
}
row.Add(new object[] { "" });
dataTable.AddRow(row);
}
//race stats:
{
var row = new List<object>();
row.Add(new object[] { RaceStats.Race.DisplayName });
row.Add(new object[]
{ RaceStats.Swim.Median.Hours, RaceStats.Swim.Median.Minutes, RaceStats.Swim.Median.Seconds });
row.Add(new object[]
{ RaceStats.Bike.Median.Hours, RaceStats.Bike.Median.Minutes, RaceStats.Bike.Median.Seconds });
row.Add(new object[]
{ RaceStats.Run.Median.Hours, RaceStats.Run.Median.Minutes, RaceStats.Run.Median.Seconds });
if (RaceStats.Finish.Median.TotalSeconds > 0)
{
TimeSpan finish = RaceStats.Finish.Median;
TimeSpan total = (RaceStats.Swim.Median + RaceStats.Bike.Median + RaceStats.Run.Median);
TimeSpan tTime;
if (finish > total)
tTime = finish - total;
else
tTime = total - finish;
row.Add(new object[]
{ tTime.Hours, tTime.Minutes, tTime.Seconds });
//swim+bike+run=14:03:42 finish med=13:39:02
}
else
{
row.Add(new object[] { 0, 0, 0 });
}
row.Add(new object[] { "" });
dataTable.AddRow(row);
}
//division stats
{
var row = new List<object>();
row.Add(new object[] { SelectedAgeGroup + " " + SelectedGender });
row.Add(new object[]
{ RaceDivisionStats.Swim.Median.Hours, RaceDivisionStats.Swim.Median.Minutes, RaceDivisionStats.Swim.Median.Seconds });
row.Add(new object[]
{ RaceDivisionStats.Bike.Median.Hours, RaceDivisionStats.Bike.Median.Minutes, RaceDivisionStats.Bike.Median.Seconds });
row.Add(new object[]
{ RaceDivisionStats.Run.Median.Hours, RaceDivisionStats.Run.Median.Minutes, RaceDivisionStats.Run.Median.Seconds });
if (RaceDivisionStats.Finish.Median.TotalSeconds > 0)
{
TimeSpan finish = RaceDivisionStats.Finish.Median;
TimeSpan total = (RaceDivisionStats.Swim.Median + RaceDivisionStats.Bike.Median + RaceDivisionStats.Run.Median);
TimeSpan tTime;
if (finish > total)
tTime = finish - total;
else
tTime = total - finish;
row.Add(new object[]
{ tTime.Hours, tTime.Minutes, tTime.Seconds });
}
else
{
row.Add(new object[] { 0, 0, 0 });
}
row.Add(new object[] { "" });
dataTable.AddRow(row);
}
return dataTable;
}
}
public GoogleVisualizationDataTable ComparisonChart
{
get
{
var dataTable = new GoogleVisualizationDataTable();
dataTable.AddColumn("Name", "string", "domain");
dataTable.AddColumn("Swim", "timeofday", "data");
dataTable.AddColumn("Bike", "timeofday", "data");
dataTable.AddColumn("Run", "timeofday", "data");
dataTable.AddColumn("T1 & T2", "timeofday", "data");
dataTable.AddColumn("", "string", "annotation");
//assign values to each column.
foreach (Triathlete athlete in Triathletes.OrderBy(t => t.Race.RaceDate))
{
var row = new List<object>();
row.Add(new object[] { athlete.Race.DisplayName + Environment.NewLine + athlete.Name });
row.Add(new object[]
{ athlete.Swim.Hours, athlete.Swim.Minutes, athlete.Swim.Seconds });
row.Add(new object[]
{ athlete.Bike.Hours, athlete.Bike.Minutes, athlete.Bike.Seconds });
row.Add(new object[]
{ athlete.Run.Hours, athlete.Run.Minutes, athlete.Run.Seconds });
if (athlete.Finish.TotalSeconds > 0)
{
TimeSpan tTime = athlete.Finish - (athlete.Swim + athlete.Bike + athlete.Run);
row.Add(new object[]
{ tTime.Hours, tTime.Minutes, tTime.Seconds });
}
else
{
row.Add(new object[]{ 0,0,0});
}
row.Add(new object[] { "" });
dataTable.AddRow(row);
}
return dataTable;
}
}
}
}
|
Java
|
UTF-8
| 558 | 2.734375 | 3 |
[] |
no_license
|
package com.yu.structure.proxy.staticproxy;
import java.util.ArrayList;
/**
* @author yuchangying
* @date 2022-06-15 18:14:49
*
* 代理模式-静态代理:在不改变被代理类的情况下对被代理类加强,需要实现接口
* 1、需要被代理类实现的接口
* 2、需要被代理的类
* 3、代理工厂
*/
public class Client {
public static void main(String[] args) {
IteachDao iteachDao = new TeachDao();
ProxyFactory proxyFactory = new ProxyFactory(iteachDao);
proxyFactory.getProxy();
}
}
|
TypeScript
|
UTF-8
| 406 | 3.71875 | 4 |
[
"MIT"
] |
permissive
|
function aaa(a: string, b: string, c: string) {
const d = 123;
const e = b + 123;
return `1${a}2${e}3${c}4${d}`;
}
aaa('1', '2', '3');
const bbb = (x: string) => "222";
bbb("1");
const a = {
b() {
return "111";
}
};
const b = {
b: function () {
return "111";
}
};
const c = {
b: () => {
return "111";
}
};
c.b();
if (b) {
bbb('');
}
|
PHP
|
UTF-8
| 739 | 2.890625 | 3 |
[] |
no_license
|
<?php
namespace App\DTO;
use Symfony\Component\Validator\Constraints as Assert;
class ProfilePasswordDTO
{
/**
* @var string
* @Assert\NotBlank
* @Assert\Length(
* max="4096",
* min="6",
* minMessage = "Jūsų slaptažodis turi turėti mažiausiai {{ limit }} simbolius",
* )
*/
private $newPassword;
/**
* @return string
*/
public function getNewPassword(): ?string
{
return $this->newPassword;
}
/**
* @param string $newPassword
* @return ProfilePasswordDTO
*/
public function setNewPassword(?string $newPassword): ProfilePasswordDTO
{
$this->newPassword = $newPassword;
return $this;
}
}
|
C#
|
UTF-8
| 1,046 | 3.578125 | 4 |
[
"MIT"
] |
permissive
|
public class Solution {
public int EvalRPN(string[] tokens) {
// solution 1: from left to right
var st = new Stack();
int iout;
int right, left;
for(var i = 0; i < tokens.Length; i++){
if(int.TryParse(tokens[i], out iout))
st.Push(int.Parse(tokens[i]));
else{ // operator
right = (int)st.Pop();
left = (int)st.Pop();
switch(tokens[i]){
case "+":
st.Push(right + left);
break;
case "-":
st.Push(left - right);
break;
case "*":
st.Push(left * right);
break;
case "/":
st.Push((int)(left / right));
break;
default:
break;
}
}
}
return (int)st.Pop();
}
}
|
PHP
|
UTF-8
| 2,701 | 2.734375 | 3 |
[] |
no_license
|
<?php
$con = mysqli_connect("localhost", "root", "wearethebest", "hma2014");
//*************take out info from ANEW *********************************************
$sql1 = "SELECT description FROM ANEW";
$sql2 = "SELECT Valence_Mean FROM ANEW";
$sql3 = "SELECT Word_Frequency FROM ANEW";
$result1 = mysqli_query($con,$sql1);
$result2 = mysqli_query($con,$sql2);
$result3 = mysqli_query($con,$sql3);
$k1=0; $k2=0; $k3=0;
/// $test1 is all description work,
while($array1 = mysqli_fetch_array($result1)){
$test1[$k1] = $array1[0];
$k1++;
}
//// $test2 is all responding valence_mean
while($array2 = mysqli_fetch_array($result2)){
$test2[$k2] = $array2[0];
$k2++;
}
/// $test3 is all responding word_frequency
while($array3 = mysqli_fetch_array($result3)){
$test3[$k3] = $array3[0];
$k3++;
}
//***************************************************************
//***************************************************************
//***************************************************************
//***************************************************************
$tweet_num=0;
$sql4 = "SELECT tweets FROM testtweets";
$result4 = mysqli_query($con,$sql4);
while($array4 = mysqli_fetch_array($result4)){
$tweets[$tweet_num] = $array4[0];
$tweet_num++;
}
$mood_sum=0; $Effect_tweet=0;
for($i=0;$i<count($tweets);$i++){
/////test single tweet
$lable=0;
$match_lable=array();
//echo $tweets[$i]."<br>";
for($j=0;$j<count($test1);$j++){
// match single keyword in table 1
if(strpos(".$tweets[$i].",$test1[$j])){
$match_lable[$lable]= $j;
$lable++;
}
}
//test5中放入了匹配当前条的关键词标号
//echo "lable is :".$lable."<br>";
$s1=0; $s2=0;
//这里计算的是当前条目的评分数
if($lable>0){
$Effect_tweet++;
//echo "effect is:".$Effect_tweet."<br>";
for($t=0;$t<count($match_lable);$t++){
$s1 += $test2[$match_lable[$t]]* $test3[$match_lable[$t]];
$s2 += $test3[$match_lable[$t]];
}
$single_value = $s1 / $s2;
echo "<br>";
} else{
$single_value=0;
}
echo "mood value of tweet: ".$tweets[$i]." is ".$single_value."<br>";
//这里 $single_value is mood value of a single tweet
$mood_sum=$single_value+$mood_sum;
echo "mood sum is:".$mood_sum."<br>";
}
echo "effect is:".$Effect_tweet."<br>";
$final = $mood_sum/$Effect_tweet;
echo "the average mood value of test tweets is ".$final;
mysqli_close($con);
?>
|
Java
|
UTF-8
| 4,100 | 2.375 | 2 |
[] |
no_license
|
package com.freemindcafe.socket.ssl.sample5;
import static com.freemindcafe.utils.FileSystemUtils.currentDir;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.security.KeyStore;
import java.security.Principal;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509KeyManager;
import org.junit.Test;
public class EchoServerTest {
@Test
public void ssl_server_that_demands_client_auth_uses_custom_key_manager() throws Exception{
System.setProperty(
"javax.net.ssl.trustStore",currentDir()+"/src/com/freemindcafe/socket/ssl/sample5/serverkeystore.jks");
System.setProperty("javax.net.ssl.trustStorePassword", "password");
// System.setProperty(
// "javax.net.ssl.keyStore",
// currentDir()+"/src/com/freemindcafe/socket/ssl/sample5/serverkeystore.jks");
// System.setProperty("javax.net.ssl.keyStorePassword", "password");
System.setProperty("javax.net.debug", "ssl:handshake");
KeyStore ks = KeyStore.getInstance("JKS");
// KeyStore ts = KeyStore.getInstance("JKS");
//
char[] passphrase = "password".toCharArray();
//
ks.load(new FileInputStream(currentDir()+"/src/com/freemindcafe/socket/ssl/sample5/serverkeystore.jks"), passphrase);
// ts.load(new FileInputStream(currentDir()+"/src/com/freemindcafe/socket/ssl/sample5/serverkeystore.jks"), passphrase);
//
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, passphrase);
//
// TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
// tmf.init(ts);
final X509KeyManager origKm = (X509KeyManager)kmf.getKeyManagers()[0];
X509KeyManager km = new X509KeyManager() {
@Override
public String chooseClientAlias(String[] keyType,
Principal[] issuers, Socket socket) {
return origKm.chooseClientAlias(keyType, issuers, socket);
}
@Override
public String chooseServerAlias(String keyType,
Principal[] issuers, Socket socket) {
//InetAddress remoteAddress = socket.getInetAddress();
return "serverkey";
}
@Override
public X509Certificate[] getCertificateChain(String alias) {
return origKm.getCertificateChain(alias);
}
@Override
public String[] getClientAliases(String keyType, Principal[] issuers) {
return origKm.getClientAliases(keyType, issuers);
}
@Override
public PrivateKey getPrivateKey(String alias) {
return origKm.getPrivateKey(alias);
}
@Override
public String[] getServerAliases(String keyType, Principal[] issuers) {
return origKm.getServerAliases(keyType, issuers);
}
};
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
//sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
sslContext.init(new KeyManager[] { km }, null, null);
// SSLServerSocketFactory sslserversocketfactory = (SSLServerSocketFactory) SSLServerSocketFactory
// .getDefault();
SSLServerSocketFactory sslserversocketfactory = sslContext.getServerSocketFactory();
SSLServerSocket sslserversocket = (SSLServerSocket) sslserversocketfactory
.createServerSocket(9999);
sslserversocket.setNeedClientAuth(true);
SSLSocket sslsocket = (SSLSocket) sslserversocket.accept();
InputStream inputstream = sslsocket.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(
inputstream);
BufferedReader bufferedreader = new BufferedReader(
inputstreamreader);
String string = null;
while ((string = bufferedreader.readLine()) != null) {
System.out.println("server printing ################");
System.out.println(string);
System.out.flush();
}
}
}
|
Java
|
GB18030
| 3,037 | 2.859375 | 3 |
[] |
no_license
|
package lesson2;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Scanner;
import javax.swing.*;
import java.awt.color.*;
import lesson2.MainUI;
public class AdchangeUI extends JFrame implements ActionListener
{
JPanel jp1=new JPanel();
JPanel jp2=new JPanel();
JPanel jp3=new JPanel();
JButton j1,j2;
JLabel jl1;
public static void main(String[] args)
{
AdchangeUI ui=new AdchangeUI();
}
//****************************¼ж**********************
//캯
public AdchangeUI() //Ϊvoid!!!!!½
{
jl1=new JLabel ("ѡ");
j1=new JButton("ıûɫ");
j2=new JButton("ıû");
jp1.add(jl1);
jp2.add(j1) ;
jp3.add(j2);
this.add(jp1);
this.add(jp2);
this.add(jp3);
//òֹ
this.setLayout(new GridLayout(6,3,50,0));
this.setTitle("ıûϢ");
this.setSize(400,300);
this.setLocation(200, 200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
j1.addActionListener(this);
j2.addActionListener(this);
this.addWindowListener(new WindowAdapter()
{
@Override
public void windowClosing(WindowEvent e)
{
// TODO Auto-generated method stub
if(JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(AdchangeUI.this, "Ƿ˳", "ѯ", JOptionPane.YES_NO_OPTION))
{
//WindowsAndMenu.this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
AdchangeUI.this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
}
else
{
AdchangeUI.this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
}
});
//setExtendedState(JFrame.MAXIMIZED_BOTH);
//this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == j1){
//رյǰ
dispose();
new AdchangeroleUI();
}else if(e.getSource() == j2){
//رյǰ
dispose();
new AdchangepassUI();
}
}
}
|
PHP
|
UTF-8
| 1,204 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace Frontend\Modules\Addresses\Engine;
use Backend\Core\Engine\Model as BackendModel;
use Backend\Modules\Addresses\Entity\Address;
use Backend\Modules\Addresses\Repository\AddressRepository;
use Backend\Modules\Catalog\Entity\Product;
use Backend\Modules\Catalog\Repository\ProductRepository;
use Frontend\Core\Language\Locale;
/**
* Class Engine
*
* @package \Frontend\Modules\Addresses\Engine
*/
class Model
{
public static function search(array $ids)
{
/** @var AddressRepository $addressRepository */
$addressRepository = BackendModel::get('addresses.repository.address');
$addresses = $addressRepository->findByIds($ids);
$resultsArray = array();
/** @var Address $address */
foreach ($addresses as $address) {
$resultsArray[$address->getId()] = array(
'id' => $address->getId(),
'title' => $address->getTranslation(Locale::frontendLanguage())->getTitle(),
'introduction' => $address->getTranslation(Locale::frontendLanguage())->getDescription(),
'full_url' => $address->getWebUrl()
);
}
return $resultsArray;
}
}
|
JavaScript
|
UTF-8
| 1,694 | 2.84375 | 3 |
[] |
no_license
|
var articles = JSON.parse(localStorage.getItem('news')) || [];
function getArticles() {
return new Promise((resolve, reject) => {
setTimeout(()=> resolve(articles.reverse()), 200);
});
};
function addArticle({id, title, author, tags, publishDate, shortDescription, fullDescription}) {
return new Promise((resolve, reject) => {
setTimeout(()=> {
const article = {
id,
title,
author,
tags,
publishDate,
shortDescription,
fullDescription,
};
articles.push(article);
localStorage.setItem(
'news',
JSON.stringify(articles)
);
resolve(articles.reverse());
}, 400);
});
};
function editArticle(dataInfo) {
return new Promise((resolve, reject) => {
setTimeout(()=> {
let article = articles.find((item) => item.id == dataInfo.id);
article = Object.assign(article, dataInfo);
localStorage.setItem(
'news',
JSON.stringify(articles)
);
resolve(articles.reverse());
}, 400);
});
};
function deleteArticle(id) {
return new Promise((resolve, reject) => {
setTimeout(()=> {
const article = articles.find((item) => item.id == id);
const index = articles.indexOf(article);
articles.splice(index, 1);
localStorage.setItem(
'news',
JSON.stringify(articles)
);
resolve(articles.reverse());
}, 400);
});
}
const newId = (function getNewId() {
let id = localStorage.getItem('lastID') || 0;
return function() {
id++;
localStorage.setItem('lastID', id);
return id;
};
})();
export { getArticles, newId, addArticle, editArticle, deleteArticle };
|
Python
|
UTF-8
| 1,870 | 2.71875 | 3 |
[] |
no_license
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import time
import sys
import random
#need this to pad the animation
height = 48
width = 40
#the canvas we have to work with
screen1 = [['-']*width for i in range(height)]
screen2 = [['-']*width for i in range(height)]
a = '''
__ __ ___ __ __ __ __ __ ___
| T T / \ | T TT || T | / _]
| | |Y Y| | |l_ || | | / [_
| ~ || O || | | \l| | |Y _]
l___, || || : | l : !| [_
| !l !l | \ / | T
l____/ \___/ \__,_j \_/ l_____j
__ __ ___ ____ __ __ __
| T__T T / \ | \ | T| T| T
| | | |Y Y| _ Y| || || |
| | | || O || | ||__j|__j|__j
l ` ' !| || | | __ __ __
\ / l !| | || T| T| T
\_/\_/ \___/ l__j__jl__jl__jl__j
'''
b = a.strip('\n').split('\n')
for j in range(height):
for k in range(width):
if j%2 == 0:
if k%2 == 0:
screen1[j][k] = '+'
elif k%2 == 1:
screen1[j][k] = '+'
for j in range(height):
for k in range(width):
if j%2 == 1:
if k%2 == 0:
screen2[j][k] = '+'
elif k%2 == 1:
screen2[j][k] = '+'
def randomizer(a,line):
b = ['x'*40]
for i,k in enumerate(a):
if i > line:
print("".join(b))
else:
print("".join(k))
def checker_print(i):
if(i%2 == 0):
print("\n".join("".join(i) for i in screen1[:40-25]))
else:
print("\n".join("".join(i) for i in screen2[:40-25]))
randomizer(b,i)
if(i%2 == 0):
print("\n".join("".join(i) for i in screen1[25:]))
else:
print("\n".join("".join(i) for i in screen2[25:]))
sys.stdout.flush()
for i in range(40):
checker_print(i)
time.sleep(0.2)
|
JavaScript
|
UTF-8
| 1,119 | 3.4375 | 3 |
[] |
no_license
|
/**
* 2021/04/13 每日一题 783. 二叉搜索树节点最小距离
* 给你一个二叉搜索树的根节点 root ,返回 树中任意两不同节点值之间的最小差值 。
*
* 注意:本题与 530:https://leetcode-cn.com/problems/minimum-absolute-difference-in-bst/ 相同
* 示例 1:
*
*
* 输入:root = [4,2,6,1,3]
* 输出:1
* 示例 2:
*
*
* 输入:root = [1,0,48,null,null,12,49]
* 输出:1
*/
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var minDiffInBST = function(root) {
if(!root) return root
let min = Infinity
let stack = []
let cur = root
let pre = null
while(stack.length || cur){
while(cur){
stack.push(cur)
cur = cur.left
}
cur = stack.pop()
if (pre) min = Math.min(cur.val - pre.val, min)
pre = cur
cur = cur.right
}
return min
};
|
Markdown
|
UTF-8
| 1,613 | 3.78125 | 4 |
[] |
no_license
|
# C++
알고리즘을 풀때 썻던 라이브러리 정리
## String.find()

C++ 라이브러리중에 부분 문자열을 찾는 유용한 라이브러리가 있어서 정리해본다.<br>
2.find()는 s가 가키는 문자부터 count 개 만큼을 취한 부분 문자열을 원 문자열에서 찾는다. s 중간에 NULL 이 있어도 괜찮다.<br>
3.s 가 가리키는 문자열을 원 문자열에서 검색한다. 이 때 s는 NULL 종료 문자열로 간주 된다.<br>
만약 문자열을 찾는데 성공하였다면, 해당 문자열의 시작 위치를 반환하고, 찾지 못했다면 ```npos``` 를 리터한다. ```npos```는 ```string::npos```로 정의되는 상수이다. <br>
### 인자들
<li> str - 찾고자 하는 문자열</li>
<li> pos - 검색을 시작할 위치</li>
<li> count - 찾고자 하는 문자열의 길이</li>
<li> s - 찾고자 하는 문자열을 가리키는 포인턴</li>
<li> ch - 찾고자 하는 문자</li>
<li> t - 찾고자 하는 string_view 로 변환 가능한 객체</li>
### 예시
```
void print(std::string::size_type n, std::string const &s) {
if (n == std::string::npos) {
std::cout << "not found\n";
} else {
std::cout << "found: " << s.substr(n) << '\n';
}
}
int main() {
std::string::size_type n;
std::string const s = "This is a string";
// s 의 처음 부터 찾는다.
n = s.find("is");
print(n, s);
// s 의 5번째 문자부터 찾는다.
n = s.find("is", 5);
print(n, s);
}
```
|
C++
|
UTF-8
| 277 | 2.640625 | 3 |
[] |
no_license
|
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#define PI 3.141592654
long double A, B, C;
long double rad, alt;
int main() {
while (scanf("%Lf %Lf %Lf ", &A, &B, &C) != EOF) {
rad = A*PI/180;
alt = tan(rad)*B + C;
printf("%0.2Lf\n", 5*alt);
}
return 0;
}
|
JavaScript
|
UTF-8
| 1,266 | 2.953125 | 3 |
[] |
no_license
|
var DataService = function () {
var self = this;
let counter = 2;
let dvdList = [
{
dvdId: 1,
title: 'Crossroads',
releaseYear: '1986',
director: 'Walter Hill',
rating: 'R'
}
];
// //////////////////////////////////////////////////////////////////
// Data manipulation methods
self.getDvds = function() {
return dvdList;
}
self.addDvd = function(dvd){
dvd.dvdId = counter++;
dvdList.push(dvd);
}
self.removeDvd = function (dvdId) {
let tempList = [];
for (let i = 0; i < dvdList.length; i++) {
const dvd = dvdList[i];
if (dvd.dvdId != dvdId) {
tempList.push(dvd);
}
}
dvdList = tempList;
}
self.getDvdById = function (dvdId) {
for (let i = 0; i < dvdList.length; i++) {
const dvd = dvdList[i];
if (dvd.dvdId == dvdId) {
return dvd;
}
}
return null;
}
self.updateDvd = function (dvd) {
for (let i = 0; i < dvdList.length; i++) {
if (dvd.dvdId == dvdList[i].dvdId) {
dvdList[i] = dvd;
}
}
}
}
|
C++
|
UTF-8
| 3,560 | 3.8125 | 4 |
[] |
no_license
|
/*
GeeksForGeeks: Longest consecutive sequence in Binary tree
Link to Problem: https://practice.geeksforgeeks.org/problems/longest-consecutive-sequence-in-binary-tree/1
Difficulty: Easy
Given a Binary Tree find the length of the longest path which comprises of nodes with consecutive values in increasing order. Every node is considered as a path of length 1.longest-consecutive-sequence-in-Binary-tree-example
6
/ \
3 9
/ \
7 10
\
11
LCP: 9,10,11 Length:3
Input:
The first line of the input contains a single integer T denoting the number of test cases. For each test a root node is given to the longestConsecutive function. The only input to the function is the root of the binary Tree.
Output:
For each test case output in a single line, find the length of the longest path of the binary tree.
If no such sequence is possible return -1.
Constraints:
1<=T<=50
1<=N<=50
Example:
Input:
2
2
1 2 L 1 3 R
5
10 20 L 10 30 R 20 40 L 20 60 R 30 90 L
Output:
2
-1
Explanation:
Test case 1:
1
/ \
2 3
For the above test case the longest sequence is : 1 2
Test case 2:
10
/ \
20 30
/ \ /
40 60 90
For the above test case no sequence is possible: -1
*/
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
Node *left, *right;
};
Node* newNode(int data)
{
Node* temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
int longestConsecutive(Node* root);
int main()
{
int t;
struct Node *child;
scanf("%d
", &t);
while (t--)
{
map<int, Node*> m;
int n;
scanf("%d
",&n);
struct Node *root = NULL;
while (n--)
{
Node *parent;
char lr;
int n1, n2;
scanf("%d %d %c", &n1, &n2, &lr);
if (m.find(n1) == m.end())
{
parent = newNode(n1);
m[n1] = parent;
if (root == NULL)
root = parent;
}
else
parent = m[n1];
child = newNode(n2);
if (lr == 'L')
parent->left = child;
else
parent->right = child;
m[n2] = child;
}
cout<<longestConsecutive(root)<<endl;
}
return 0;
}
/*Please note that it's Function problem i.e.
you need to write your solution in the form of Function(s) only.
Driver Code to call/invoke your function is mentioned above.*/
/*
struct Node
{
int data;
Node *left, *right;
};
*/
// your task is tp complete this function
// function should return the length of the longestConsecutive
// sequence
int longestSequence(Node* root,int prev,int maxLen,int length){
// Null node
if(!root)return maxLen;
// Found match for sequence; length ==1 => new sequence found; length ==0 => function invoked first time
if(root->data == prev+1) length++;
else length=1;
if(maxLen<length)maxLen = length;
// Go left and right and return max value
return max(longestSequence(root->left,root->data,maxLen,length),
longestSequence(root->right,root->data,maxLen,length));
}
int longestConsecutive(Node* root)
{
// For root node of tree, set prev value as current value-1 so that it gets
// counted as part of sequence
int ans = longestSequence(root,root->data-1,0,0);
return (ans>1)?ans:-1;
}
|
Python
|
UTF-8
| 584 | 3.265625 | 3 |
[] |
no_license
|
def any_lowercase1(s):
for c in s:
if c.islower():
return True
else:
return False
any_lowercase1(k)
def any_lowercase2(s):
for c in s:
if 'c'.islower():
return 'True'
else:
return 'False'
def any_lowercase3(s):
for c in s:
flag = c.islower()
return flag
def any_lowercase4(s):
flag = False
for c in s:
flag = flag or c.islower()
return flag
def any_lowercase5(s):
for c in s:
if not c.islower():
return False
return True
|
C++
|
UTF-8
| 2,239 | 2.90625 | 3 |
[] |
no_license
|
#include "../header/myheader.h"
class LT1726
{
public:
// D D
// vector<int> v;
// for(int i=0; i < nums.size(); i++) {
// for(int j=i+1; j < nums.size(); j++) {
// v.push_back(nums[i]*nums[j]);
// }
// }
// sort(v.begin(), v.end());
//
// int cnt = 0, tmp;
//
// for(int i=1; i < v.size(); i++) {
// tmp = 1;
// while(v[i] == v[i-1] && i < v.size()) {
// tmp++;
// i++;
// }
// cnt += tmp * (tmp-1) * 4;
// }
//
// return cnt;
// for(int i = 0 ; i < n ; ++i){
// for(int j = 0 ; j < i ; ++j){
// int prod = nums[i] * nums[j];
// /*Every tuple has 8 permutations*/
// res += 8 * umap[prod];
// ++umap[prod];
// }
// }
// for (int i = 0, n = nums.length; i < n; ++i) {
// for (int j = i + 1; j < n; ++j) {
// // cnt += products.merge(nums[i] * nums[j], 8, (a, b) -> a + 8) - 8;
// cnt += products.merge(nums[i] * nums[j], 8, Integer::sum) - 8; // credit to @madno
// }
// }
// java.lang/util?.hashmap
//Runtime: 532 ms, faster than 68.27% of C++ online submissions for Tuple with Same Product.
//Memory Usage: 81.7 MB, less than 37.26% of C++ online submissions for Tuple with Same Product.
// [2] * [3] , [3] * [4] , no , distinct
int lt1726a(vector<int>& nums)
{
unordered_map<int, int> map2;
int sz1 = nums.size();
for (int i = 0; i < sz1; ++i)
{
int v = nums[i];
for (int j = i + 1; j < sz1; ++j)
{
map2[v * nums[j]]++;
}
}
int ans = 0;
for (unordered_map<int, int>::iterator it = map2.begin(); it != map2.end(); it++)
{
int v = it->second;
if (v > 1)
{
ans += v * (v - 1) * 4;
}
}
return ans;
}
};
int main()
{
// myvi v = {2,3,4,6};
// myvi v = {1,2,4,5,10};
// myvi v = {2,3,4,6,8,12};
myvi v = {2,3,5,7};
LT1726 lt;
cout<<lt.lt1726a(v)<<endl;
return 0;
}
|
Java
|
UTF-8
| 935 | 3.3125 | 3 |
[] |
no_license
|
package LinkedList;
import static LinkedList.LinkedList.makelist;
public class PalindromeList {
public static boolean ispalin(Node head)
{
// find the middle element in list
Node fast = head, slow = head;
while(fast != null && fast.next!=null)
{
fast = fast.next.next;
slow = slow.next;
}
if(fast != null) {
// means odd nodes
slow = slow.next;
}
slow = ReverseLinkedList.reverseList(slow, null, slow);
fast = head;
while(slow!=null)
{
if(slow.data != fast.data){
return false;
}
slow = slow.next;
fast = fast.next;
}
return true;
}
public static void main(String[] args) {
int arr[] = {1,4,4,1,4,4,1};
Node head = makelist(arr);
System.out.println(ispalin(head));
}
}
|
Python
|
UTF-8
| 802 | 3.234375 | 3 |
[
"MIT"
] |
permissive
|
def engineer(train, test, real_test=None, funclist=[]):
"""
Loop through all of the dataframes and apply each of the funclist functions on them, in order
funclist must be a list of functions that accept data as a single parameter.
"""
datasets = [train, test]
if real_test is not None:
datasets.append(real_test)
for data in datasets:
for func in funclist:
func(data)
return
def refresh(train, test, real_test=None):
"""
Returns deep copies of all of the provided DataFrames for easily refreshing or undoing feature engineering
"""
if real_test is not None:
return train.copy(deep = True), test.copy(deep = True), real_test.copy(deep = True)
else:
return train.copy(deep = True), test.copy(deep = True)
|
Markdown
|
UTF-8
| 2,772 | 2.640625 | 3 |
[
"Apache-2.0"
] |
permissive
|
# ijcnlp17_emo
Code to replicate experiments in the IJCNLP 2017 paper "Modelling Representation Noise in Emotion Analysis using Gaussian Processes" (to appear)
## Requirements
### Data and resources
Download the "Affective Text" dataset and put the gzipped file in the "data" folder:
https://web.eecs.umich.edu/~mihalcea/downloads.html
Download the datasets for the WASSA 2017 shared task. Make sure you download the version *with* intensity labels. Put all files in the "data" folder:
http://saifmohammad.com/WebPages/EmotionIntensity-SharedTask.html
Download GloVe word embeddings, the version trained on Wikipedia and Gigaword ("glove.6B.zip") and put it in the "data" folder:
https://nlp.stanford.edu/projects/glove/
### Tools
All code uses Python, we recommend you use virtualenv to define an isolate virtual environment for the experiments.
Install NLTK
> `pip install nltk`
Install scikit-learn
> `pip install scikit-learn`
Install GPy
> `pip install gpy`
## Configuration and Preprocessing
All code assume the repository is located in your home folder with its original name, so you can run the scripts from anywhere in your command line. If the repository is somewhere else and/or you cloned it with a different name, change the `MAIN_FOLDER` variable inside the `bin/config.sh` file.
Once you're set, you can run the preprocessing script:
> `bin/preprocess.sh`
This will unpack the dataset and the word embeddings, as well as formatting the dataset in a friendlier format for the experiment scripts. It will also generate the SemEval 2007 data splits for 10-fold cross-validation, in the `splits` folder.
## Running the experiments
The `bin/run_all.sh` script replicates all models in the paper with 10-fold cross-validation, saving predictions in the `preds` folder and final scores in the `results` folder. This can take a long time to finish though.
For the SemEval 2007 experiments a more fine-grained replication is available using the `bin/run.py` script, which should be tried first for testing purposes. A single run of this script will train a `RidgeCV` regression model on the first fold. Options for the remaining models are available, use the '--help' flag for a description.
For the WASSA 2017 experiments, replication is available using the `bin/run_wassa.py` script. This uses the official test set from the shared task.
## Collecting final results
Any instances of `bin/run.py` will save the scores (Pearson's r and NLPD) in the `results` folder. The `bin/collect_results.py` script will gather all the scores in that folder and summarise them in the output. If you ran all models and folds, this should give you the same numbers published in the paper. However, you can also run it if you have partial results as well.
|
Java
|
UTF-8
| 327 | 2.5625 | 3 |
[] |
no_license
|
package com.abstractionExample;
//parent class
public abstract class BMW {
public void commonFeatures(){
System.out.println("common features...");
}
public abstract void Enginepower();// Abstract method
public static void main(String[] args) {
System.out.println("Abstract class");
}
}
|
C++
|
UTF-8
| 5,968 | 2.640625 | 3 |
[] |
no_license
|
// HeapAllocations.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "pch.h"
#include <iostream>
#include <Windows.h>
#include <tchar.h>
#include <stdio.h>
#include <intsafe.h>
#include <thread>
#include <chrono>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <string>
#include "Arguments.h"
const DWORD c_defaultDwFlags = 0;
const size_t c_initialHeapSize = 1024 * 1024; // Initial size
const size_t c_maxHeapSize = 0; // unbound
class HeapAllocationRunner
{
private:
HANDLE hDefaultProcessHeap;
std::mutex mut;
std::vector<std::chrono::microseconds> mAllocationTimings;
std::vector<std::chrono::microseconds> mFreeTimings;
Arguments& mArgs;
void addAllocationTime(std::chrono::microseconds& microseconds)
{
std::lock_guard<std::mutex> lk(mut);
mAllocationTimings.push_back(microseconds);
}
void addFreeTime(std::chrono::microseconds& microseconds)
{
std::lock_guard<std::mutex> lk(mut);
mFreeTimings.push_back(microseconds);
}
void printResults(std::vector<std::chrono::microseconds>& list)
{
std::sort(list.begin(), list.end());
auto count = list.size() - 1;
std::cout << "Total " << count + 1 << std::endl;
std::cout << "Min " << list[0].count() << std::endl;
std::cout << "Max " << list[count-1].count() << std::endl;
std::cout << "P50 " << list[(int)(count * 0.500)].count() << " us" << std::endl;
std::cout << "P60 " << list[(int)(count * 0.600)].count() << " us" << std::endl;
std::cout << "P70 " << list[(int)(count * 0.700)].count() << " us" << std::endl;
std::cout << "P80 " << list[(int)(count * 0.800)].count() << " us" << std::endl;
std::cout << "P90 " << list[(int)(count * 0.900)].count() << " us" << std::endl;
std::cout << "P95 " << list[(int)(count * 0.950)].count() << " us" << std::endl;
std::cout << "P99 " << list[(int)(count * 0.990)].count() << " us" << std::endl;
std::cout << "P995 " << list[(int)(count * 0.995)].count() << " us" << std::endl;
std::cout << "P999 " << list[(int)(count * 0.999)].count() << " us" << std::endl;
}
void printResults()
{
std::cout << "Allocation Timings" << std::endl;
printResults(mAllocationTimings);
std::cout << "Deallocation Timings" << std::endl;
printResults(mFreeTimings);
}
public:
void DoRun()
{
SIZE_T bytesToAllocate = 64 * 1024;
HANDLE heapHandle = hDefaultProcessHeap;
if (mArgs.UsePrivateHeap)
heapHandle = HeapCreate(c_defaultDwFlags, c_initialHeapSize, c_maxHeapSize);
for (int j = 0; j < mArgs.BatchIteration; j++)
{
std::vector<PHANDLE> handles;
handles.reserve(mArgs.BatchSize);
for (int i = 0; i < mArgs.BatchSize; i++)
{
auto startTime = std::chrono::high_resolution_clock::now();
PHANDLE heap = (PHANDLE)HeapAlloc(heapHandle, 0, bytesToAllocate);
auto endTime = std::chrono::high_resolution_clock::now();
auto executionTimeInMs = std::chrono::duration_cast<std::chrono::microseconds>(endTime - startTime);
addAllocationTime(executionTimeInMs);
if (heap == NULL) {
_tprintf(TEXT("HeapAlloc failed to allocate %d bytes.\n"),
bytesToAllocate);
}
handles.push_back(heap);
}
std::this_thread::sleep_for(std::chrono::milliseconds(20));
for (int i = 0; i < mArgs.BatchSize; i++)
{
auto startTime = std::chrono::high_resolution_clock::now();
PHANDLE heap = handles[i];
if (HeapFree(heapHandle, 0, heap) == FALSE) {
_tprintf(TEXT("Failed to free allocation from default process heap.\n"));
}
auto endTime = std::chrono::high_resolution_clock::now();
auto executionTimeInMs = std::chrono::duration_cast<std::chrono::microseconds>(endTime - startTime);
addFreeTime(executionTimeInMs);
}
}
}
void PerformTest()
{
auto startTime = std::chrono::high_resolution_clock::now();
for (int i = 0; i < mArgs.MaxIterations; i++)
{
std::cout << "Iteration " << (i+1) << std::endl;
DWORD NumberOfHeaps;
NumberOfHeaps = GetProcessHeaps(0, NULL);
std::cout << "Number of heaps : " << NumberOfHeaps << std::endl;
std::vector<std::thread> threads;
threads.reserve(mArgs.MaxThreads);
for (int i = 0; i < mArgs.MaxThreads; i++)
{
threads.push_back(std::thread(&HeapAllocationRunner::DoRun, this));
}
for (int i = 0; i < mArgs.MaxThreads; i++)
{
threads[i].join();
}
NumberOfHeaps = GetProcessHeaps(0, NULL);
std::cout << "Number of heaps : " << NumberOfHeaps << std::endl;
}
auto endTime = std::chrono::high_resolution_clock::now();
auto executionTimeInMs = std::chrono::duration_cast<std::chrono::microseconds>(endTime - startTime);
printResults();
std::cout << "Total Time : " << executionTimeInMs.count() << "us" << std::endl;
}
HeapAllocationRunner(Arguments& args) : mArgs(args)
{
long long totalAllocations = mArgs.BatchIteration * mArgs.BatchSize * mArgs.MaxIterations * mArgs.MaxThreads;
mAllocationTimings.reserve(totalAllocations);
mFreeTimings.reserve(totalAllocations);
if (!mArgs.UsePrivateHeap)
hDefaultProcessHeap = HeapCreate(c_defaultDwFlags, c_initialHeapSize, c_maxHeapSize);
}
};
int main(int argc, char* argv[])
{
std::cout << "Scheduling Test!\n";
Arguments args;
args.parse(argc, argv);
HeapAllocationRunner runner(args);
runner.PerformTest();
return 0;
}
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu
// Tips for Getting Started:
// 1. Use the Solution Explorer window to add/manage files
// 2. Use the Team Explorer window to connect to source control
// 3. Use the Output window to see build output and other messages
// 4. Use the Error List window to view errors
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
|
Markdown
|
UTF-8
| 1,478 | 2.78125 | 3 |
[] |
no_license
|
> [Monsters, NPC and Animals](srd_monsters.md)
---
# Young White Dragon
- Alias: [Jeune dragon blanc](hd_monsters_jeune_dragon_blanc.md)
- Large dragon, chaotic evil
- **Armor Class** 17 (natural armor)
- **Hit Points** 133 (14d10 + 56)
- **Speed** 40 ft., burrow 20 ft., fly 80 ft., swim 40 ft.
|STR|DEX|CON|INT|WIS|CHA|
|---|---|---|---|---|---|
|18 (+4)|10 (+0)|18 (+4)| 6 (-2)|11 (+0)|12 (+1)|
- **Saving Throws** Dex +3, Con +7, Wis +3, Cha +4
- **Skills** Perception +6, Stealth +3
- **Senses** blindsight 30 ft., darkvision 120 ft., passive Perception 16
- **Languages** Common, Draconic
- **Challenge** 6 (2300 XP)
- **Damage Immunities** cold
## Special Features
**_Ice Walk_**. The dragon can move across and climb icy surfaces without needing to make an ability check. Additionally, difficult terrain composed of ice or snow doesn't cost it extra moment.
## Actions
**_Multiattack_**. The dragon makes three attacks: one with its bite and two with its claws.
**_Bite_**. Melee Weapon Attack: +7 to hit, reach 10 ft., one target.
_Hit_: 15 (2d10 + 4) piercing damage plus 4 (1d8) cold damage.
**_Claw_**. Melee Weapon Attack: +7 to hit, reach 5 ft., one target.
_Hit_: 11 (2d6 + 4) slashing damage.
**_Cold Breath (Recharge 5-6)_**. The dragon exhales an icy blast in a 30-foot cone. Each creature in that area must make a DC 15 Constitution saving throw, taking 45 (10d8) cold damage on a failed save, or half as much damage on a successful one.
|
PHP
|
UTF-8
| 602 | 2.921875 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace App\Models;
class Cart
{
public function centsToPrice($cents)
{
return number_format($cents / 100, 2);
}
public static function unitPrice($item)
{
$a = 3;
echo '<script>alert("hi" gettype($a))</script>';
// alert(gettype($a));
//return (new self)->centsToPrice($item['product']['price']) * $item['quantity'];
}
public static function totalAmount()
{
$total = 0;
foreach(session('cart') as $item)
{
$total += self::unitPrice($item);
}
return $total;
}
}
|
Markdown
|
UTF-8
| 959 | 2.984375 | 3 |
[] |
no_license
|
# California Public Schools: Cleaned Data Set
PURPOSE:
This repository is for cleaning the California Department of Education's database
of public schools. It can then be used as a lookup table or for making
interactive maps. The original dataset is available publicly from [CDE's
website](http://www.cde.ca.gov/ds/si/ds/pubschls.asp).
The RMD file documents the cleaning process and outputs the cleaned csv in the
`data` folder.
### Links
- For your convenience, you can download the cleaned csv by
right clicking and selecting `download linked file` [at this link](https://github.com/restrellado/california-public-schools/raw/master/data/cleaned_cde_schools.csv)
- You can view a [presentation and examples of how to use the data](https://restrellado.github.io/california-public-schools/cde_dir_presentation.html)
- You can review [documentation of the process](https://restrellado.github.io/california-public-schools/ca_ps.html)
on github
|
Python
|
UTF-8
| 8,440 | 2.859375 | 3 |
[] |
no_license
|
import wx, os
from ..textbox import LayoutDimensions
from .smart import SmartTextBox, SmartInputLayout
__author__ = 'Joeny'
class PathSmartBox(SmartTextBox):
"""
Path Smart Box.
"""
def __init__(self, parent, *args, **kwargs):
"""
:param parent:
:param args:
:param kwargs:
"""
SmartTextBox.__init__(self, parent, *args, **kwargs)
self.Bind(wx.EVT_KEY_DOWN, self.key_down)
def key_down(self, event=None):
"""
:param event:
"""
pass
def is_file_exists(self):
"""
Is file exists.
:return:
"""
filepath = self.get_value()
if filepath:
if os.path.exists(filepath):
return os.path.isfile(filepath)
return False
def is_dir_exists(self):
"""
Is path exists.
:return:
"""
path = self.get_value()
if path:
if os.path.exists(path):
return os.path.isdir(path)
return False
class PathInputLayout(SmartInputLayout):
"""
Path Input Layout.
"""
def __init__(self,
parent,
textbox=None,
postbox=None,
layout=None,
is_file=False,
is_save=False,
message=wx.FileSelectorPromptStr,
defaultDir=wx.EmptyString,
defaultFile=wx.EmptyString,
wildcard=wx.FileSelectorDefaultWildcardStr,
style=wx.FD_DEFAULT_STYLE,
*args,
**kwargs):
"""
Constructor
:param parent:
:param textbox:
:param postbox:
:param layout:
:param is_file:
:param is_save:
:param message:
:param defaultDir:
:param defaultFile:
:param wildcard:
:param style:
:param args:
:param kwargs:
:return:
"""
SmartInputLayout.__init__(self, parent, layout=layout, *args, **kwargs)
if textbox:
self.textbox = textbox
else:
self.textbox = PathSmartBox(parent)
if postbox:
self.postbox = postbox
else:
self.postbox = wx.Button(parent, id=wx.ID_ANY, size=(24, 24))
if self.postbox:
if is_file:
self.postbox.Bind(wx.EVT_BUTTON, self.pick_file_path)
self.postbox.SetToolTip(wx.ToolTip("Choose File"))
else:
self.postbox.Bind(wx.EVT_BUTTON, self.pick_folder_path)
self.postbox.SetToolTip(wx.ToolTip("Choose Path"))
self.is_file = is_file
self.is_save = is_save
self.message = message
self.defaultDir = defaultDir
self.defaultFile = defaultFile
self.wildcard = wildcard
self.style = style
if is_save and is_file:
self.style = wx.SAVE | wx.OVERWRITE_PROMPT
self.do_layout()
def pick_folder_path(self, event):
"""
Pick the folder path using a Directory Dialog.
:param event:
:return:
"""
path = self.textbox.Value
if os.path.isdir(path):
dlg = wx.DirDialog(self.parent, defaultPath=path)
else:
dlg = wx.DirDialog(self.parent)
if dlg.ShowModal() == wx.ID_OK:
# Change the path string..
self.textbox.SetValue(dlg.GetPath())
ret_val = wx.ID_OK
else:
ret_val = wx.ID_CANCEL
dlg.Destroy()
return ret_val
def pick_file_path(self, event):
"""
Pick file path
:param event:
:return:
"""
path = self.textbox.Value
if os.path.isfile(path):
dlg = wx.FileDialog(self.parent,
message=self.message,
defaultDir=self.defaultDir,
defaultFile=path,
wildcard=self.wildcard,
style=self.style)
else:
dlg = wx.FileDialog(self.parent,
message=self.message,
defaultDir=self.defaultDir,
defaultFile=self.defaultFile,
wildcard=self.wildcard,
style=self.style)
if dlg.ShowModal() == wx.ID_OK:
# Change the path string..
self.textbox.SetValue(dlg.GetPath())
ret_val = wx.ID_OK
else:
ret_val = wx.ID_CANCEL
dlg.Destroy()
return ret_val
def enable(self):
"""
Enable textbox and/or postbox.
:return:
"""
if self.textbox:
self.textbox.Enable(True)
if self.postbox:
self.postbox.Enable(True)
def disable(self):
"""
Disable textbox and/or postbox.
:return:
"""
if self.textbox:
self.textbox.Disable()
if self.postbox:
self.postbox.Disable()
def set_value(self, value):
# type: (object) -> object
"""
Set the file path
"""
self.textbox.set_value(value)
def get_value(self):
"""
Return the file path
"""
return self.textbox.get_value()
def is_valid_path(self):
"""
Is valid path
:return:
"""
if self.is_file:
return self.textbox.is_file_exists()
else:
return self.textbox.is_dir_exists()
class SmartPathInputLayout(PathInputLayout):
"""
Smart Path Input Layout
"""
def __init__(self, parent, name=None, textbox=None, postbox=None, layout=None, *args, **kwargs):
"""
Constructor
:param parent:
:param name:
:param textbox:
:param postbox:
:param layout:
:param is_file:
:param args:
:param kwargs:
:return:
"""
if textbox is None:
textbox = PathSmartBox(parent, disabled_messages=[name])
textbox.Disable()
if postbox is None:
postbox = wx.Button(parent, label='Browse', id=wx.ID_ANY)
if layout is None:
layout = LayoutDimensions(left=2, right=2, top=2, bottom=2, interior=2,
widths=(125, 75),
stretch_factor=(1, 0))
layout.calculate()
PathInputLayout.__init__(self,
parent,
label=None,
textbox=textbox,
postbox=postbox,
layout=layout,
*args,
**kwargs)
self.path = None
def pick_file_path(self, event):
"""
Pick file path
:param event:
:return:
"""
retval = PathInputLayout.pick_file_path(self, event)
if retval == wx.ID_CANCEL:
self.textbox.set_disable_message()
self.path = None
else:
self.path = self.textbox.get_value()
return retval
def pick_folder_path(self, event):
"""
Pick folder path
:param event:
:return:
"""
retval = PathInputLayout.pick_folder_path(self, event)
if retval == wx.ID_CANCEL:
self.textbox.set_disable_message()
self.path = None
else:
self.path = self.textbox.get_value()
return retval
def enable(self):
"""
Enable textbox and/or postbox.
:return:
"""
if self.postbox:
self.postbox.Enable(True)
def disable(self):
"""
Disable textbox and/or postbox.
:return:
"""
if self.postbox:
self.postbox.Disable()
def get_value(self):
"""
Get the value
:return:
"""
return self.path
def set_value(self, value):
# type: (object) -> object
"""
Set the file path
"""
self.path = value
self.textbox.set_value(value)
|
JavaScript
|
UTF-8
| 798 | 2.5625 | 3 |
[] |
no_license
|
import { FETCH_RSS_BEGIN, FETCH_RSS_SUCCESS, FETCH_RSS_FAILURE } from "./index";
export const fetchRSSBegin = () => ({
type: FETCH_RSS_BEGIN
})
export const fetchRSSSuccess = data => ({
type: FETCH_RSS_SUCCESS,
payload: { data }
})
export const fetchRSSFailure = error => ({
type: FETCH_RSS_FAILURE,
payload: { error }
})
export function RSSfetch(url) {
return dispatch => {
dispatch(fetchRSSBegin());
return fetch('https://api.rss2json.com/v1/api.json?rss_url=' + url, {
method: 'GET'
})
.then(response => {
return response.json()
})
.then(json => {
dispatch(fetchRSSSuccess(json));
return json;
})
.catch(error => dispatch(fetchRSSFailure(error)));
}
}
|
Java
|
UTF-8
| 88,872 | 1.84375 | 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 UI;
import javax.swing.JOptionPane;
import Class.Koneksi;
import java.sql.Connection;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.swing.DefaultCellEditor;
import javax.swing.JOptionPane;
import javax.swing.table.TableColumn;
import com.sun.glass.events.KeyEvent;
import java.awt.Window;
import java.awt.event.KeyListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Locale;
import javax.swing.DefaultComboBoxModel;
import javax.swing.InputMap;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.text.JTextComponent;
import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;
import org.jdesktop.swingx.autocomplete.ComboBoxCellEditor;
import org.jdesktop.swingx.autocomplete.ObjectToStringConverter;
/**
*
* @author USER
*/
public class Master_Mutasi_PermintaanMutasiAntarGudang_DetailNew extends javax.swing.JFrame {
/**
* Creates new form Penjualan_penjualan
*/
int lokasipeminta = 0, lokasipenyedia = 0, jumlah_item = 0, kodebarang = 1, peminta, penyedia;
double jumlah_qty = 0;
String lokasi_deactived, lokasi_tmp = "PUSAT", kodekonversi;
String[] barang;
ArrayList<String> kode_nama_arr = new ArrayList();
private static int item = 0;
private boolean tampil = true;
String status;
Master_Mutasi_PermintaanMutasiAntarGudang awal;
public Master_Mutasi_PermintaanMutasiAntarGudang_DetailNew() {
}
public Master_Mutasi_PermintaanMutasiAntarGudang_DetailNew(Master_Mutasi_PermintaanMutasiAntarGudang awal, String status) {
initComponents();
this.awal = awal;
this.status = status;
this.setLocationRelativeTo(null);
lebarKolom();
tanggal_jam_sekarang();
loadNumberTable();
autonumber();
autonumberPermintaan();
seleksilokasipeminta();
seleksilokasipenyedia();
System.out.println(lokasipeminta+" -------- "+lokasipenyedia);
peminta = comTableLokasiPeminta.getSelectedIndex();
penyedia = comTableLokasiPenyedia.getSelectedIndex();
//JCombobox kode barang
((JTextComponent) comTableKode.getEditor().getEditorComponent()).getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
System.out.println("insert");
if (item == 0) {
loadComboKode(((JTextComponent) comTableKode.getEditor().getEditorComponent()).getText());
} else {
item = 0;
}
Runnable doHighlight = new Runnable() {
@Override
public void run() {
if (tampil) {
tbl_Permintaan_MutasiAG_new.editCellAt(tbl_Permintaan_MutasiAG_new.getSelectedRow(), 1);
comTableKode.setPopupVisible(true);
}
}
};
SwingUtilities.invokeLater(doHighlight);
}
@Override
public void removeUpdate(DocumentEvent e) {
System.out.println("remove");
System.out.println(((JTextComponent) comTableKode.getEditor().getEditorComponent()).getText());
String key = ((JTextComponent) comTableKode.getEditor().getEditorComponent()).getText();
System.out.println(key);
//((JTextComponent) comKodeBarang.getEditor().getEditorComponent()).setText(key);
}
@Override
public void changedUpdate(DocumentEvent e) {
System.out.println("change");
}
});
((JTextComponent) comTableKode.getEditor().getEditorComponent()).addKeyListener(new KeyListener() {
@Override
public void keyTyped(java.awt.event.KeyEvent e) {
}
@Override
public void keyPressed(java.awt.event.KeyEvent e) {
tampil = true;
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
tampil = false;
} else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
tampil = true;
}
}
@Override
public void keyReleased(java.awt.event.KeyEvent e) {
}
});
//kode JCombobox sampai sini
//JCombobox Nama barang
((JTextComponent) comTableBarang.getEditor().getEditorComponent()).getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
System.out.println("insert");
if (item == 0) {
loadComboNama(((JTextComponent) comTableBarang.getEditor().getEditorComponent()).getText());
} else {
item = 0;
}
Runnable doHighlight = new Runnable() {
@Override
public void run() {
if (tampil) {
tbl_Permintaan_MutasiAG_new.editCellAt(tbl_Permintaan_MutasiAG_new.getSelectedRow(), 2);
comTableBarang.setPopupVisible(true);
}
}
};
SwingUtilities.invokeLater(doHighlight);
}
@Override
public void removeUpdate(DocumentEvent e) {
System.out.println("remove");
System.out.println(((JTextComponent) comTableBarang.getEditor().getEditorComponent()).getText());
String key = ((JTextComponent) comTableBarang.getEditor().getEditorComponent()).getText();
System.out.println(key);
//((JTextComponent) comTableBarang.getEditor().getEditorComponent()).setText(key);
}
@Override
public void changedUpdate(DocumentEvent e) {
System.out.println("change");
}
});
((JTextComponent) comTableBarang.getEditor().getEditorComponent()).addKeyListener(new KeyListener() {
@Override
public void keyTyped(java.awt.event.KeyEvent e) {
}
@Override
public void keyPressed(java.awt.event.KeyEvent e) {
tampil = true;
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
tampil = false;
} else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
tampil = true;
}
}
@Override
public void keyReleased(java.awt.event.KeyEvent e) {
}
});
}
void cmbSelectInput(JComboBox combo, String input) {
int cmb_count = combo.getItemCount() - 1;
int inputlen = combo.getSelectedItem().toString().length() - 1;
String combo_item = null;
for (int i = 0; i < cmb_count; i++) {
combo_item = combo.getItemAt(i).toString().substring(0, inputlen);
if (input.equals(combo_item)) {
combo.setSelectedIndex(i);
break;
}
}
}
void showQTY() {
try {
jumlah_item = tbl_Permintaan_MutasiAG_new.getRowCount();
int qty, jumqty = 0;
System.out.println("row count : " + jumlah_item);
for (int j = 0; j < tbl_Permintaan_MutasiAG_new.getRowCount();) {
if (tbl_Permintaan_MutasiAG_new.getValueAt(j, 4) != "") {
qty = Integer.parseInt(tbl_Permintaan_MutasiAG_new.getValueAt(j, 4).toString());
jumqty += qty;
}
j++;
}
jumlah_qty = jumqty;
txtJumItem.setText("Jumlah Item : " + jumlah_item);
txtJumQty.setText("Jumlah Qty : " + String.valueOf(jumlah_qty));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Data tidak boleh kosong" + e);
e.printStackTrace();
}
}
/*
void showQTY() {
try {
jumlah_item = tbl_Permintaan_MutasiAG_new.getRowCount();
int qty, jumqty = 0;
System.out.println("row count : " + jumlah_item);
for (int j = 0; j < jumlah_item;) {
if (tbl_Permintaan_MutasiAG_new.getValueAt(j, 4) != "") {
qty = Integer.parseInt(tbl_Permintaan_MutasiAG_new.getValueAt(j, 4).toString());
System.out.println("j adalah : " + j);
jumqty += qty;
}
j++;
}
jumlah_qty = jumqty;
txtJumItem.setText("Jumlah Item : " + jumlah_item);
txtJumQty.setText("Jumlah Qty : " + String.valueOf(jumqty));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Eror" + e);
e.printStackTrace();
}
}
*/
public void lebarKolom() {
TableColumn column;
tbl_Permintaan_MutasiAG_new.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
column = tbl_Permintaan_MutasiAG_new.getColumnModel().getColumn(0);
column.setPreferredWidth(50);
column = tbl_Permintaan_MutasiAG_new.getColumnModel().getColumn(1);
column.setPreferredWidth(280);
column = tbl_Permintaan_MutasiAG_new.getColumnModel().getColumn(2);
column.setPreferredWidth(280);
column = tbl_Permintaan_MutasiAG_new.getColumnModel().getColumn(3);
column.setPreferredWidth(80);
column = tbl_Permintaan_MutasiAG_new.getColumnModel().getColumn(4);
column.setPreferredWidth(80);
column = tbl_Permintaan_MutasiAG_new.getColumnModel().getColumn(5);
column.setPreferredWidth(80);
}
void seleksilokasipeminta() {
if (comTableLokasiPeminta.getSelectedItem() == "PUSAT") {
lokasipeminta = 1;
} else if (comTableLokasiPeminta.getSelectedItem() == "GUD63") {
lokasipeminta = 2;
} else if (comTableLokasiPeminta.getSelectedItem() == "TOKO") {
lokasipeminta = 4;
} else if (comTableLokasiPeminta.getSelectedItem() == "TENGAH") {
lokasipeminta = 5;
} else if (comTableLokasiPeminta.getSelectedItem() == "UTARA") {
lokasipeminta = 6;
}
}
void seleksilokasipenyedia() {
if (comTableLokasiPenyedia.getSelectedItem() == "PUSAT") {
lokasipenyedia = 1;
} else if (comTableLokasiPenyedia.getSelectedItem() == "GUD63") {
lokasipenyedia = 2;
} else if (comTableLokasiPenyedia.getSelectedItem() == "TOKO") {
lokasipenyedia = 4;
} else if (comTableLokasiPenyedia.getSelectedItem() == "TENGAH") {
lokasipenyedia = 5;
} else if (comTableLokasiPenyedia.getSelectedItem() == "UTARA") {
lokasipenyedia = 6;
}
}
private void tanggalsekarang() {
int i = 0;
Thread p = new Thread() {
public void run() {
for (;;) {
GregorianCalendar cal = new GregorianCalendar();
int hari = cal.get(Calendar.DAY_OF_MONTH);
int bulan = cal.get(Calendar.MONTH);
int tahun = cal.get(Calendar.YEAR);
txt_tgl.setText(tahun + "-" + (bulan + 1) + "-" + hari);
if (i > 0) {
txt_tgl.setText(tahun + "-" + (bulan + 1) + "-" + hari);
} else {
}
}
}
};
p.start();
}
public void tanggal_jam_sekarang() {
Thread p = new Thread() {
public void run() {
for (;;) {
String timeStamp = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(Calendar.getInstance().getTime());
txt_tgl.setText(timeStamp);
}
}
};
System.out.println(txt_tgl.getText());
p.start();
}
void loadNumberTable() {
int baris = tbl_Permintaan_MutasiAG_new.getRowCount();
for (int a = 0; a < baris; a++) {
String nomor = String.valueOf(a + 1);
tbl_Permintaan_MutasiAG_new.setValueAt(nomor + ".", a, 0);
}
}
void loadComTableBarang() {
try {
String sql = "select b.kode_barang, b.nama_barang from barang b, barang_lokasi bl "
+ "where b.kode_barang = bl.kode_barang "
+ "and bl.kode_lokasi = '" + lokasipenyedia
+ "' order by nama_barang asc";
java.sql.Connection conn = (Connection) Koneksi.configDB();
java.sql.Statement stm = conn.createStatement();
java.sql.ResultSet res = stm.executeQuery(sql);
String index = null;
int i = 0;
while (res.next()) {
String kode = res.getString(1);
String name = res.getString(2);
comTableBarang.addItem(kode + " -- " + name);
}
String kalimat = comTableKode.getItemAt(0).toString();
String[] kata = kalimat.split(" -- ");
tbl_Permintaan_MutasiAG_new.setValueAt(kata[1], 0, 2);
System.out.println("barang lokasi " + lokasipenyedia);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Eror" + e);
}
}
void loadComTableKode() {
try {
String sql = "select * from barang order by nama_barang asc";
java.sql.Connection conn = (Connection) Koneksi.configDB();
java.sql.Statement stm = conn.createStatement();
java.sql.ResultSet res = stm.executeQuery(sql);
String index1 = null;
while (res.next()) {
String kode = res.getString("kode_barang");
String name = res.getString("nama_barang");
comTableKode.addItem(kode + " -- " + name);
}
String kalimat = comTableKode.getItemAt(0).toString();
String[] kata = kalimat.split(" -- ");
System.out.println("index kode" + index1);
tbl_Permintaan_MutasiAG_new.setValueAt(kata[0], 0, 1);
System.out.println("kode barang" + lokasipenyedia);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Eror" + e);
}
}
void loadComTableSatuan() {
try {
/// identitas konversi tidak urut
String sql = "select * from konversi k, barang_konversi bk, barang b "
+ "where b.kode_barang = bk.kode_barang "
+ "and bk.kode_konversi = k.kode_konversi "
+ "and b.kode_barang = '" + kodebarang + "' order by bk.kode_barang_konversi asc";
System.out.println("sts: " + sql);
java.sql.Connection conn = (Connection) Koneksi.configDB();
java.sql.Statement stm = conn.createStatement();
java.sql.ResultSet res = stm.executeQuery(sql);
comTableKonv.removeAllItems();
int i = 1;
while (res.next()) {
String name = res.getString("nama_konversi");
// if (res.getString("identitas_konversi").toString().equalsIgnoreCase("1")) {
// System.out.println("ya: " + name);
// comTableKonv.setSelectedItem(name);
// }
System.out.println(name);
comTableKonv.addItem(name);
i++;
}
//comTableKonv.setSelectedIndex(0);
res.close();
conn.close();
// comKodeKonv.addItem(name);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Eror" + e);
e.printStackTrace();
}
}
void loadTxtTableQty() {
try {
String sql = "select sum(jumlah) from barang_lokasi bl "
+ "where bl.kode_lokasi = '" + lokasipenyedia
+ "' and bl.kode_barang = '" + comTableKode.getSelectedItem() + "'";
System.out.println("sts: " + sql);
java.sql.Connection conn = (Connection) Koneksi.configDB();
java.sql.Statement stm = conn.createStatement();
java.sql.ResultSet res = stm.executeQuery(sql);
txt_Qty.setText(sql);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Eror" + e);
e.printStackTrace();
}
}
void load_dari_nama_barang() {
int selectedRow = tbl_Permintaan_MutasiAG_new.getSelectedRow();
String nama_awal = String.valueOf(comTableBarang.getSelectedItem());
String[] split = new String[2];
System.out.println("nilai comTable barang adalah " + comTableBarang.getSelectedItem());
if (comTableBarang.getSelectedItem() != null) {
split = nama_awal.split("-");
}
try {
String sql = "select kode_barang,nama_barang from barang where kode_barang = '" + split[0] + "'";
java.sql.Connection conn = (Connection) Koneksi.configDB();
java.sql.Statement stm = conn.createStatement();
java.sql.ResultSet res = stm.executeQuery(sql);
while (res.next()) {
String kode = res.getString("kode_barang");
String nama = res.getString("nama_barang");
loadNumberTable();
if (selectedRow != -1) {
System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&");
this.kodebarang = Integer.parseInt(kode);
loadComTableSatuan();
tbl_Permintaan_MutasiAG_new.setValueAt(comTableKonv.getItemAt(0), selectedRow, 3);
tbl_Permintaan_MutasiAG_new.setValueAt(kode, selectedRow, 1);
tbl_Permintaan_MutasiAG_new.setValueAt(nama, selectedRow, 2);
tbl_Permintaan_MutasiAG_new.setValueAt(0, selectedRow, 4);
}
}
conn.close();
res.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Eror" + e);
e.printStackTrace();
}
}
private void removeSelectedRows(JTable table) {
int Hapus = 1;
Hapus = JOptionPane.showConfirmDialog(null, "Apakah anda yakin mau menghapus baris ?", "konfirmasi", JOptionPane.YES_NO_OPTION);
if (Hapus == 0) {
DefaultTableModel model = (DefaultTableModel) this.tbl_Permintaan_MutasiAG_new.getModel();
int[] rows = table.getSelectedRows();
for (int i = 0; i < rows.length; i++) {
model.removeRow(rows[i] - i);
}
}
}
public void autonumber() {
try {
String lastNo = "";
String sql = "select max(no_bukti) from mutasi_antar_gudang ORDER BY no_bukti DESC";
java.sql.Connection conn = (Connection) Koneksi.configDB();
java.sql.Statement stm = conn.createStatement();
java.sql.ResultSet res = stm.executeQuery(sql);
while (res.next() && res != null) {
if (res.first() == false) {
txt_noBukti.setText("MG");
} else {
res.last();
String auto_num = res.getString(1);
int noLama = Integer.parseInt(auto_num.substring(auto_num.length() - 4));
++noLama;
String no = String.valueOf(noLama);
no = Integer.toString(noLama);
if (no.length() == 1) {
lastNo = "0000" + no;
} else if (no.length() == 2) {
lastNo = "000" + no;
} else if (no.length() == 3) {
lastNo = "00" + no;
} else if (no.length() == 4) {
lastNo = "0" + no;
} else {
lastNo = "00001";
}
int num = Integer.parseInt(lastNo);
String huruf = String.valueOf(auto_num.substring(0, 5));
num = Integer.valueOf(auto_num.substring(5)) + 0;
String angkapad = rightPadZeros(String.valueOf(++num), 5);
txt_noBukti.setText(String.valueOf(huruf + "" + angkapad));
}
}
res.close();
} catch (NullPointerException ex) {
txt_noBukti.setText("MG18-00001");
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "ERROR: \n" + ex.toString(),
"Kesalahan", JOptionPane.WARNING_MESSAGE);
}
}
public void autonumberPermintaan() {
try {
String lastNo = "";
String sql = "select max(no_permintaan) from mutasi_antar_gudang where no_permintaan!='-'ORDER BY no_permintaan DESC";
java.sql.Connection conn = (Connection) Koneksi.configDB();
java.sql.Statement stm = conn.createStatement();
java.sql.ResultSet res = stm.executeQuery(sql);
while (res.next() && res != null) {
if (res.first() == false) {
txt_noPermintaan.setText("PM");
} else {
res.last();
String auto_num = res.getString(1);
int noLama = Integer.parseInt(auto_num.substring(auto_num.length() - 4));
++noLama;
String no = String.valueOf(noLama);
no = Integer.toString(noLama);
if (no.length() == 1) {
lastNo = "0000" + no;
} else if (no.length() == 2) {
lastNo = "000" + no;
} else if (no.length() == 3) {
lastNo = "00" + no;
} else if (no.length() == 4) {
lastNo = "0" + no;
} else {
lastNo = "00001";
}
int num = Integer.parseInt(lastNo);
String huruf = String.valueOf(auto_num.substring(0, 5));
num = Integer.valueOf(auto_num.substring(5)) + 0;
String angkapad = rightPadZeros(String.valueOf(++num), 5);
txt_noPermintaan.setText(String.valueOf(huruf + "" + angkapad));
}
}
res.close();
} catch (NullPointerException ex) {
txt_noPermintaan.setText("PM18-00001");
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "ERROR: \n" + ex.toString(),
"Kesalahan", JOptionPane.WARNING_MESSAGE);
}
}
void ClearData() {
DefaultTableModel dm = (DefaultTableModel) tbl_Permintaan_MutasiAG_new.getModel();
dm.getDataVector().removeAllElements();
dm.fireTableDataChanged();
dm.addRow(new Object[]{"", "", "", "", "", ""});
autonumber();
autonumberPermintaan();
}
public void SaveData() {
try {
Koneksi Koneksi = new Koneksi();
Connection con = Koneksi.configDB();
Statement st = con.createStatement();
int row = 0;
int jumlah_data = tbl_Permintaan_MutasiAG_new.getRowCount();
System.out.println(jumlah_data);
int jumlah_item = 0;
double jumlah_qty = 0;
boolean cukup = true;
String kode_barang = "";
String kode_konversi = "";
String status = null;
//Memasukkan data perbaris ke tabel mutasi detail
for (int i = 0; i < jumlah_data; i++) {
//Konversi satuan
String satuan = String.valueOf(tbl_Permintaan_MutasiAG_new.getValueAt(i, 3));
String sql1 = "select kode_konversi from barang_konversi where kode_konversi = (select kode_konversi from konversi where nama_konversi='" + satuan + "') and kode_barang = '" + tbl_Permintaan_MutasiAG_new.getValueAt(i, 1) + "'";
System.out.println(sql1);
Statement st1 = con.createStatement();
java.sql.ResultSet res1 = st1.executeQuery(sql1);
while (res1.next()) {
kode_konversi = res1.getString(1);
}
res1.close();
System.out.println("satuan" + satuan);
//Cek ketersediaan barang di gudang tertentu
if (i == 0) {
for (int j = 0; j < jumlah_data; j++) {
//Konversi lokasi cek
String sql3a = "select kode_lokasi from lokasi where nama_lokasi = '" + comTableLokasiPenyedia.getSelectedItem().toString() + "'";
System.out.println(sql3a);
Statement st3a = con.createStatement();
java.sql.ResultSet res3a = st3a.executeQuery(sql3a);
String lokasi_cek = "";
while (res3a.next()) {
lokasi_cek = res3a.getString(1);
}
res3a.close();
//Konversi satuan cek
String satuan_cek = String.valueOf(tbl_Permintaan_MutasiAG_new.getValueAt(j, 3));
String sql1a = "select kode_konversi from barang_konversi where kode_konversi = (select kode_konversi from konversi where nama_konversi='" + satuan_cek + "') and kode_barang = '" + tbl_Permintaan_MutasiAG_new.getValueAt(i, 1) + "'";
System.out.println(sql1a);
Statement st1a = con.createStatement();
java.sql.ResultSet res1a = st1a.executeQuery(sql1a);
String kode_konversi_cek = "";
while (res1a.next()) {
kode_konversi_cek = res1a.getString(1);
}
res1a.close();
double qty = Double.parseDouble(String.valueOf(tbl_Permintaan_MutasiAG_new.getValueAt(j, 4)));
//qty dikali jumlah_konversi
double qty_sesudah = qty_konversi(String.valueOf(tbl_Permintaan_MutasiAG_new.getValueAt(j, 1)), kode_konversi_cek, qty);
System.out.println("qty_sesudah : " + qty_sesudah +" - "+ kode_konversi_cek+" - "+qty);
String sql4 = "select * from barang_lokasi where kode_barang ='" + String.valueOf(tbl_Permintaan_MutasiAG_new.getValueAt(j, 1)) + "' and kode_lokasi = '" + lokasi_cek + "'";
System.out.println(sql4);
java.sql.Statement stm4 = con.createStatement();
java.sql.ResultSet res4 = stm4.executeQuery(sql4);
System.out.println("qty_sesduah " + qty_sesudah);
while (res4.next()) {
int stok = Integer.parseInt(res4.getString("jumlah"));
System.out.println("stok " + stok);
kode_barang = String.valueOf(tbl_Permintaan_MutasiAG_new.getValueAt(j, 1));
if (qty_sesudah > stok) {
cukup = false;
//keluar while
break;
}
}
if (!cukup) {
//keluar pengecekan stok
break;
}
res4.close();
}
}
if (!cukup) {
//keluar for untuk input semua baris
break;
} else {
//Input kode_konversi
int kode = 0;
String sqlkode = "select kode_konversi from konversi WHERE nama_konversi = '" + tbl_Permintaan_MutasiAG_new.getValueAt(i, 3) + "'";
System.out.println(sqlkode);
Statement statkode = con.createStatement();
java.sql.ResultSet reskode = statkode.executeQuery(sqlkode);
while (reskode.next()) {
kode = Integer.parseInt(reskode.getString("kode_konversi"));
}
reskode.close();
//Memasukkan baris ke-i
String kalimat = tbl_Permintaan_MutasiAG_new.getValueAt(i, 1).toString();
String[] kata = kalimat.split(" -- ");
double jumlah = Double.parseDouble(String.valueOf(tbl_Permintaan_MutasiAG_new.getValueAt(i, 4)));
double qty_sesudah = qty_konversi(String.valueOf(tbl_Permintaan_MutasiAG_new.getValueAt(i, 1)), kode_konversi, jumlah);
String sql = "insert into mutasi_antar_gudang_detail( no_bukti, kode_barang, nama_barang, kode_lokasi_asal, satuan, qty, dikirim, kode_lokasi_tujuan)"
+ "value('" + txt_noBukti.getText() + "','" + tbl_Permintaan_MutasiAG_new.getValueAt(i, 1) + "','" + tbl_Permintaan_MutasiAG_new.getValueAt(i, 2) + "','" + lokasipenyedia + "','" + kode + "','" + tbl_Permintaan_MutasiAG_new.getValueAt(i, 4) + "','" + tbl_Permintaan_MutasiAG_new.getValueAt(i, 5) + "','" + lokasipeminta + "');";
System.out.println("insert detail " + i);
System.out.println(sql);
row = st.executeUpdate(sql);
if (!tbl_Permintaan_MutasiAG_new.getValueAt(i, 4).toString().equals(tbl_Permintaan_MutasiAG_new.getValueAt(i, 5).toString())) {
status = "ON PROGRESS";
} else {
status = "OPEN";
}
System.out.println(status);
//mengupdate stok dimasing-masing gudang
String mengurangi = "update barang_lokasi set jumlah= jumlah - " + qty_sesudah + " where kode_barang = '" + tbl_Permintaan_MutasiAG_new.getValueAt(i, 1) + "' and kode_lokasi = '" + lokasipenyedia + "'";
System.out.println(mengurangi);
Statement st_kurang = con.createStatement();
row = st_kurang.executeUpdate(mengurangi);
String menambah = "update barang_lokasi set jumlah= jumlah + " + qty_sesudah + " where kode_barang = '" + tbl_Permintaan_MutasiAG_new.getValueAt(i, 1) + "' and kode_lokasi = '" + lokasipeminta + "'";
System.out.println(menambah);
Statement st_tambah = con.createStatement();
row = st_tambah.executeUpdate(menambah);
jumlah_item++;
jumlah_qty += jumlah; //jumlah qty pada form
}
}
//Memasukkan data ke mutasi gudang umum
if (cukup) {
//String date = txt_tgl.getText();
System.out.println("status = " + status);
SimpleDateFormat format_tanggal = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = format_tanggal.format(System.currentTimeMillis());
String sql = "insert into mutasi_antar_gudang( no_bukti, no_permintaan, user, keterangan, jumlah_item, jumlah_qty, status, tanggal)"
+ "value('" + txt_noBukti.getText() + "','" + txt_noPermintaan.getText() + "','" + 3 + "','" + txt_Keterangan.getText() + "','" + jumlah_item + "','" + jumlah_qty + "','" + status + "','" + date + "');";
System.out.println(sql);
row = st.executeUpdate(sql);
} else {
JOptionPane.showMessageDialog(null, "Stok barang " + kode_barang + " di gudang " + lokasipenyedia + " tidak cukup");
}
if (row >= 1) {
JOptionPane.showMessageDialog(null, "data sudah ditambahkan ke database", "informasi", JOptionPane.INFORMATION_MESSAGE);
con.close();
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "data tidak dimasukkan ke database" + e, "informasi", JOptionPane.INFORMATION_MESSAGE);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Tidak ada data yang dimasukkan");
}
}
double qty_konversi(String kode_barang, String kode_konversi, double qty) {
double hasil = 0;
try {
String sql = "select * from barang_konversi where kode_barang='" + kode_barang + "' and kode_konversi ='" + kode_konversi + "'";
System.out.println("Kode konversi " + kode_konversi);
java.sql.Connection conn = (Connection) Koneksi.configDB();
java.sql.Statement stm = conn.createStatement();
java.sql.ResultSet res = stm.executeQuery(sql);
double jumlah_konversi = 0;
while (res.next()) {
jumlah_konversi = Double.parseDouble(res.getString("jumlah_konversi"));
}
hasil = jumlah_konversi * qty;
conn.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Eror" + e);
}
return hasil;
}
public static String rightPadZeros(String str, int num) {
return String.format("%05d", Integer.parseInt(str));
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
comTableBarang = new javax.swing.JComboBox();
txt_Qty = new javax.swing.JTextField();
comTableKode = new javax.swing.JComboBox();
txt_noPermintaan = new javax.swing.JTextField();
comTableKonv = new javax.swing.JComboBox();
jSeparator2 = new javax.swing.JSeparator();
LabelSave = new javax.swing.JLabel();
label_Clear = new javax.swing.JLabel();
jLabel21 = new javax.swing.JLabel();
label_Exit = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
jLabel22 = new javax.swing.JLabel();
jLabel32 = new javax.swing.JLabel();
jSeparator3 = new javax.swing.JSeparator();
txtJumItem = new javax.swing.JTextField();
txtJumQty = new javax.swing.JTextField();
jSeparator4 = new javax.swing.JSeparator();
jSeparator7 = new javax.swing.JSeparator();
jSeparator9 = new javax.swing.JSeparator();
txt_Keterangan = new javax.swing.JTextField();
txt_tgl = new javax.swing.JTextField();
jLabel23 = new javax.swing.JLabel();
jLabel24 = new javax.swing.JLabel();
comTableLokasiPeminta = new javax.swing.JComboBox<>();
comTableLokasiPenyedia = new javax.swing.JComboBox<>();
jLabel25 = new javax.swing.JLabel();
jLabel27 = new javax.swing.JLabel();
jLabel28 = new javax.swing.JLabel();
txt_noBukti = new javax.swing.JTextField();
jScrollPane17 = new javax.swing.JScrollPane();
tbl_Permintaan_MutasiAG_new = new javax.swing.JTable();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
jMenuItem3 = new javax.swing.JMenuItem();
comTableBarang.setEditable(true);
comTableBarang.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
comTableBarangActionPerformed(evt);
}
});
comTableBarang.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
comTableBarangKeyPressed(evt);
}
});
txt_Qty.setText("0");
comTableKode.setEditable(true);
comTableKode.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
comTableKodeActionPerformed(evt);
}
});
txt_noPermintaan.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, java.awt.Color.lightGray, java.awt.Color.gray, java.awt.Color.lightGray, java.awt.Color.lightGray));
txt_noPermintaan.setEnabled(false);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowActivated(java.awt.event.WindowEvent evt) {
formWindowActivated(evt);
}
public void windowClosed(java.awt.event.WindowEvent evt) {
formWindowClosed(evt);
}
});
addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
formKeyPressed(evt);
}
public void keyReleased(java.awt.event.KeyEvent evt) {
formKeyReleased(evt);
}
});
jSeparator2.setForeground(new java.awt.Color(153, 153, 153));
LabelSave.setFont(new java.awt.Font("Tahoma", 0, 13)); // NOI18N
LabelSave.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Gambar/if_stock_save_20659.png"))); // NOI18N
LabelSave.setText("F12 - Save");
LabelSave.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
LabelSaveMouseClicked(evt);
}
});
label_Clear.setFont(new java.awt.Font("Tahoma", 0, 13)); // NOI18N
label_Clear.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Gambar/Clear-icon.png"))); // NOI18N
label_Clear.setText("F9 - Clear");
label_Clear.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
label_ClearMouseClicked(evt);
}
});
jLabel21.setFont(new java.awt.Font("Tahoma", 0, 13)); // NOI18N
jLabel21.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Gambar/if_yast_printer_30297.png"))); // NOI18N
jLabel21.setText("Print");
jLabel21.addAncestorListener(new javax.swing.event.AncestorListener() {
public void ancestorMoved(javax.swing.event.AncestorEvent evt) {
}
public void ancestorAdded(javax.swing.event.AncestorEvent evt) {
jLabel21AncestorAdded(evt);
}
public void ancestorRemoved(javax.swing.event.AncestorEvent evt) {
}
});
jLabel21.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel21MouseClicked(evt);
}
});
label_Exit.setFont(new java.awt.Font("Tahoma", 0, 13)); // NOI18N
label_Exit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Gambar/cancel (3).png"))); // NOI18N
label_Exit.setText("Esc - Exit");
label_Exit.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
label_ExitMouseClicked(evt);
}
});
jSeparator1.setForeground(new java.awt.Color(153, 153, 153));
jLabel22.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel22.setText("Kasir");
jLabel32.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel32.setText("Nama Kasir");
jSeparator3.setForeground(new java.awt.Color(153, 153, 153));
txtJumItem.setBackground(new java.awt.Color(0, 0, 0));
txtJumItem.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
txtJumItem.setForeground(new java.awt.Color(255, 204, 0));
txtJumItem.setText("Jumlah Item");
txtJumItem.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, java.awt.Color.lightGray, java.awt.Color.gray, java.awt.Color.lightGray, java.awt.Color.lightGray));
txtJumItem.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
txtJumItemMouseClicked(evt);
}
});
txtJumItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtJumItemActionPerformed(evt);
}
});
txtJumQty.setBackground(new java.awt.Color(0, 0, 0));
txtJumQty.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
txtJumQty.setForeground(new java.awt.Color(255, 204, 0));
txtJumQty.setText("Jumlah Qty");
txtJumQty.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, java.awt.Color.lightGray, java.awt.Color.gray, java.awt.Color.lightGray, java.awt.Color.lightGray));
txtJumQty.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
txtJumQtyMouseClicked(evt);
}
});
jSeparator4.setForeground(new java.awt.Color(153, 153, 153));
jSeparator4.setOrientation(javax.swing.SwingConstants.VERTICAL);
jSeparator7.setForeground(new java.awt.Color(153, 153, 153));
jSeparator7.setOrientation(javax.swing.SwingConstants.VERTICAL);
jSeparator9.setForeground(new java.awt.Color(153, 153, 153));
jSeparator9.setOrientation(javax.swing.SwingConstants.VERTICAL);
txt_Keterangan.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, java.awt.Color.lightGray, java.awt.Color.gray, java.awt.Color.lightGray, java.awt.Color.lightGray));
txt_tgl.setEditable(false);
txt_tgl.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, java.awt.Color.lightGray, java.awt.Color.gray, java.awt.Color.lightGray, java.awt.Color.lightGray));
jLabel23.setFont(new java.awt.Font("Tahoma", 0, 13)); // NOI18N
jLabel23.setText("Lokasi Peminta");
jLabel24.setFont(new java.awt.Font("Tahoma", 0, 13)); // NOI18N
jLabel24.setText("Lokasi Penyedia");
comTableLokasiPeminta.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "PUSAT", "GUD63", "TOKO", "TENGAH", "UTARA" }));
comTableLokasiPeminta.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
comTableLokasiPemintaActionPerformed(evt);
}
});
comTableLokasiPenyedia.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "PUSAT", "GUD63", "TOKO", "TENGAH", "UTARA" }));
comTableLokasiPenyedia.setSelectedIndex(1);
comTableLokasiPenyedia.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
comTableLokasiPenyediaActionPerformed(evt);
}
});
jLabel25.setFont(new java.awt.Font("Tahoma", 0, 13)); // NOI18N
jLabel25.setText("Tanggal");
jLabel27.setFont(new java.awt.Font("Tahoma", 0, 13)); // NOI18N
jLabel27.setText("Keterangan");
jLabel28.setFont(new java.awt.Font("Tahoma", 0, 13)); // NOI18N
jLabel28.setText("No.Bukti");
txt_noBukti.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, java.awt.Color.lightGray, java.awt.Color.gray, java.awt.Color.lightGray, java.awt.Color.lightGray));
txt_noBukti.setEnabled(false);
tbl_Permintaan_MutasiAG_new.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null, null}
},
new String [] {
"No", "Kode", "Nama", "Satuan", "Qty", "Dikirim"
}
) {
boolean[] canEdit = new boolean [] {
true, true, true, false, true, true
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
tbl_Permintaan_MutasiAG_new.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tbl_Permintaan_MutasiAG_newMouseClicked(evt);
}
});
tbl_Permintaan_MutasiAG_new.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
tbl_Permintaan_MutasiAG_newKeyPressed(evt);
}
public void keyReleased(java.awt.event.KeyEvent evt) {
tbl_Permintaan_MutasiAG_newKeyReleased(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
tbl_Permintaan_MutasiAG_newKeyTyped(evt);
}
});
jScrollPane17.setViewportView(tbl_Permintaan_MutasiAG_new);
if (tbl_Permintaan_MutasiAG_new.getColumnModel().getColumnCount() > 0) {
tbl_Permintaan_MutasiAG_new.getColumnModel().getColumn(1).setCellEditor(new ComboBoxCellEditor(comTableKode));
tbl_Permintaan_MutasiAG_new.getColumnModel().getColumn(2).setCellEditor(new ComboBoxCellEditor(comTableBarang));
tbl_Permintaan_MutasiAG_new.getColumnModel().getColumn(4).setCellEditor(new DefaultCellEditor(txt_Qty));
}
jMenuBar1.setPreferredSize(new java.awt.Dimension(0, 0));
jMenu1.setText("File");
jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F12, 0));
jMenuItem1.setText("Save");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem1);
jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F9, 0));
jMenuItem2.setText("Clear");
jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem2ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem2);
jMenuItem3.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE, 0));
jMenuItem3.setText("Exit");
jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem3ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem3);
jMenuBar1.add(jMenu1);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator1)
.addComponent(jSeparator2))
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel22)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel32))
.addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 257, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 145, Short.MAX_VALUE)
.addComponent(txtJumItem, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtJumQty, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(161, 161, 161))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jScrollPane17)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel23)
.addComponent(jLabel24)
.addComponent(jLabel25)
.addComponent(jLabel27))
.addGap(68, 68, 68)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txt_tgl, javax.swing.GroupLayout.DEFAULT_SIZE, 150, Short.MAX_VALUE)
.addComponent(comTableLokasiPeminta, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(comTableLokasiPenyedia, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addComponent(jLabel28)
.addGap(18, 18, 18)
.addComponent(txt_noBukti, javax.swing.GroupLayout.PREFERRED_SIZE, 161, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(txt_Keterangan, javax.swing.GroupLayout.PREFERRED_SIZE, 394, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addComponent(LabelSave)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jSeparator4, javax.swing.GroupLayout.PREFERRED_SIZE, 8, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(label_Clear)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator7, javax.swing.GroupLayout.PREFERRED_SIZE, 8, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel21)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jSeparator9, javax.swing.GroupLayout.PREFERRED_SIZE, 8, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(label_Exit)))
.addContainerGap(317, Short.MAX_VALUE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(LabelSave)
.addComponent(label_Exit)
.addComponent(jLabel21)
.addComponent(jSeparator4, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(label_Clear)
.addComponent(jSeparator7, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jSeparator9, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel23)
.addComponent(comTableLokasiPeminta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(9, 9, 9)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel24)
.addComponent(comTableLokasiPenyedia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(8, 8, 8)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txt_tgl, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel25)
.addComponent(txt_noBukti, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel28))
.addGap(2, 2, 2)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txt_Keterangan, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel27))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane17, javax.swing.GroupLayout.PREFERRED_SIZE, 271, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 3, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel22, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel32, javax.swing.GroupLayout.Alignment.TRAILING))
.addGap(0, 0, 0)
.addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtJumItem, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtJumQty, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE))))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void txtJumItemMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtJumItemMouseClicked
// TODO add your handling code here:
}//GEN-LAST:event_txtJumItemMouseClicked
private void txtJumQtyMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtJumQtyMouseClicked
// TODO add your handling code here:
}//GEN-LAST:event_txtJumQtyMouseClicked
private void jLabel21AncestorAdded(javax.swing.event.AncestorEvent evt) {//GEN-FIRST:event_jLabel21AncestorAdded
// TODO add your handling code here:
}//GEN-LAST:event_jLabel21AncestorAdded
private void jLabel21MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel21MouseClicked
}//GEN-LAST:event_jLabel21MouseClicked
private void txtJumItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtJumItemActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtJumItemActionPerformed
private void comTableBarangActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comTableBarangActionPerformed
load_dari_nama_barang();
// tbl_Permintaan_MutasiAG_new.setValueAt(kodekonversi, tbl_Permintaan_MutasiAG_new.getSelectedRow(), 3);
// int kode_barang = 0;
// int baris = tbl_Permintaan_MutasiAG_new.getRowCount();
// TableModel tabelModel;
// tabelModel = tbl_Permintaan_MutasiAG_new.getModel();
// int selectedRow = tbl_Permintaan_MutasiAG_new.getSelectedRow();
//
//
//
// try {
// /*
// String kalimat = comTableKode.getSelectedItem().toString();
// String[] kata = kalimat.split(" -- ");
// for (int i = 0; i < kata.length; i++) {
// System.out.println(kata[i]);
// }
// tbl_Permintaan_MutasiAG_new.setValueAt(kata[0], 0, 1);
// tbl_Permintaan_MutasiAG_new.setValueAt(kata[1], 0, 2);
// */
//
// String sql = "select * from barang where kode_barang = '" + comTableBarang.getSelectedItem().toString() + "'";
// System.out.println(comTableBarang.getSelectedItem());
// java.sql.Connection conn = (Connection) Koneksi.configDB();
// java.sql.Statement stm = conn.createStatement();
// java.sql.ResultSet res = stm.executeQuery(sql);
// while (res.next()) {
// String kode = res.getString(1);
// String brg = res.getString(4);
// // loadComTableSatuan();
// // String konv = comTableKonv.getSelectedItem().toString();
//
// if (selectedRow != -1) {
// tbl_Permintaan_MutasiAG_new.setValueAt(brg, selectedRow, 2);
// tbl_Permintaan_MutasiAG_new.setValueAt(kode , selectedRow, 1);
//
// }
// }
// } catch (Exception e) {
// JOptionPane.showMessageDialog(null, "Eror" + e);
// e.printStackTrace();
// }
//
// try {
// String sql = "select k.nama_konversi, k.kode_konversi from konversi k, barang_konversi bk where k.kode_konversi = bk.kode_konversi and bk.kode_barang = '" + kode_barang + "'";
// java.sql.Connection conn = (Connection) Koneksi.configDB();
// java.sql.Statement stm = conn.createStatement();
// java.sql.ResultSet res = stm.executeQuery(sql);
// String Konv = "";
// while (res.next()) {
// Konv = res.getString(1);
//// comTableKonv.addItem(Konv);
// System.out.println("Konv =" + Konv);
// // System.out.println("echo : " + tbl_Pembelian.getValueAt(selectedRow, 2).toString());
//// tbl_Permintaan_MutasiAG_new.setValueAt(comTableKonv.getSelectedItem(), selectedRow, 2);
//
// }
//
// } catch (Exception e) {
// JOptionPane.showMessageDialog(null, "Eror nyaaaaa: ");
// e.printStackTrace();
// }
}//GEN-LAST:event_comTableBarangActionPerformed
private void tbl_Permintaan_MutasiAG_newKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbl_Permintaan_MutasiAG_newKeyPressed
DefaultTableModel model = (DefaultTableModel) tbl_Permintaan_MutasiAG_new.getModel();
int selectedRow = tbl_Permintaan_MutasiAG_new.getSelectedRow();
System.out.println(selectedRow);
//int selectedRow = tbl_tambah_mutasi.getSelectedRow();
//int baris = tbl_tambah_mutasi.getRowCount();
TableModel tabelModel;
tabelModel = tbl_Permintaan_MutasiAG_new.getModel();
try {
if (evt.getKeyCode() == KeyEvent.VK_ENTER) { // Membuat Perintah Saat Menekan Enter
if (tabelModel.getValueAt(tbl_Permintaan_MutasiAG_new.getSelectedRow(), 4).toString().equals("")
|| tabelModel.getValueAt(tbl_Permintaan_MutasiAG_new.getSelectedRow(), 3).toString().equals("")
|| tabelModel.getValueAt(tbl_Permintaan_MutasiAG_new.getSelectedRow(), 2).toString().equals("")
|| tabelModel.getValueAt(tbl_Permintaan_MutasiAG_new.getSelectedRow(), 1).toString().equals("")) {
throw new NullPointerException();
} else {
if (tbl_Permintaan_MutasiAG_new.getSelectedColumn() == 5) {
/*
System.out.println("Jumlah item = " + jumlah_item);
jumlah_item++;
int qty = 0, jumqty = 0;
txtJumItem.setText("Jumlah Item : " + jumlah_item);
for (int j = 0; j < jumlah_item; j++) {
jumqty += Integer.parseInt(tbl_Permintaan_MutasiAG_new.getValueAt(j, 4).toString());
}
jumlah_qty = jumqty;
txtJumQty.setText("Jumlah Qty : " + String.valueOf(jumqty));
*/
model.addRow(new Object[]{"", "", "", "", "", ""});
}
}
} else if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
this.dispose();
awal.setVisible(true);
awal.setFocusable(true);
System.out.println("status = " + status);
awal.loadTable(status, "*");
} else if (evt.getKeyCode() == KeyEvent.VK_F5) {
if (tbl_Permintaan_MutasiAG_new.getRowCount() - 1 == -1) {
JOptionPane.showMessageDialog(null, "Data didalam tabel telah tiada.", "", 2);
} else {
removeSelectedRows(tbl_Permintaan_MutasiAG_new);
}
} else if (evt.getKeyCode() == KeyEvent.VK_DELETE) {
if (tbl_Permintaan_MutasiAG_new.getRowCount() - 1 == -1) {
JOptionPane.showMessageDialog(null, "Data didalam tabel telah tiada.", "", 2);
showQTY();
} else {
removeSelectedRows(tbl_Permintaan_MutasiAG_new);
}
} else if (evt.getKeyCode() == KeyEvent.VK_F12) {
int simpan_data = 1;
simpan_data = JOptionPane.showConfirmDialog(null, "Apakah anda yakin ingin menyimpan data ?", "konfirmasi", JOptionPane.YES_NO_OPTION);
if (simpan_data == 0) {
SaveData();
}
} else if (evt.getKeyCode() == KeyEvent.VK_F9) {
ClearData();
} else if (evt.getKeyCode() == KeyEvent.VK_INSERT) {
if (tbl_Permintaan_MutasiAG_new.getRowCount() - 1 == -1) {
model.addRow(new Object[]{"", "", "", "", "", ""});
}
} else if (evt.getKeyCode() == KeyEvent.VK_1 && tbl_Permintaan_MutasiAG_new.getSelectedColumn() == 3) {
System.out.println("ini alt");
String kode_barang = String.valueOf(tbl_Permintaan_MutasiAG_new.getValueAt(tbl_Permintaan_MutasiAG_new.getSelectedRow(), 1));
try {
String sql = "select k.kode_konversi, nama_konversi from konversi k join barang_konversi bk on bk.kode_konversi = k.kode_konversi where bk.identitas_konversi = '1' and bk.kode_barang = '" + kode_barang + "'";
java.sql.Connection conn = (Connection) Koneksi.configDB();
java.sql.Statement stm = conn.createStatement();
java.sql.ResultSet res = stm.executeQuery(sql);
int i = 0;
while (res.next()) {
String kode = res.getString("kode_konversi");
System.out.println("konversi " + kode);
String sat = res.getString("nama_konversi");
String sat2 = sat;
tbl_Permintaan_MutasiAG_new.setValueAt(sat2, tbl_Permintaan_MutasiAG_new.getSelectedRow(), 3);
System.out.println(sat2);
i++;
}
res.close();
conn.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Eror" + e);
}
} else if (evt.getKeyCode() == KeyEvent.VK_2 && tbl_Permintaan_MutasiAG_new.getSelectedColumn() == 3) {
System.out.println("ini alt");
String kode_barang = String.valueOf(tbl_Permintaan_MutasiAG_new.getValueAt(tbl_Permintaan_MutasiAG_new.getSelectedRow(), 1));
try {
String sql = "select k.kode_konversi, nama_konversi from konversi k join barang_konversi bk on bk.kode_konversi = k.kode_konversi where bk.identitas_konversi = '2' and bk.kode_barang = '" + kode_barang + "'";
java.sql.Connection conn = (Connection) Koneksi.configDB();
java.sql.Statement stm = conn.createStatement();
java.sql.ResultSet res = stm.executeQuery(sql);
while (res.next()) {
String kode = res.getString("kode_konversi");
System.out.println("konversi " + kode);
String sat = res.getString("nama_konversi");
String sat2 = sat;
tbl_Permintaan_MutasiAG_new.setValueAt(sat2, tbl_Permintaan_MutasiAG_new.getSelectedRow(), 3);
System.out.println(sat2);
}
res.close();
conn.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Eror" + e);
}
} else if (evt.getKeyCode() == KeyEvent.VK_3 && tbl_Permintaan_MutasiAG_new.getSelectedColumn() == 3) {
System.out.println("ini alt");
String kode_barang = String.valueOf(tbl_Permintaan_MutasiAG_new.getValueAt(tbl_Permintaan_MutasiAG_new.getSelectedRow(), 1));
try {
String sql = "select k.kode_konversi, nama_konversi from konversi k join barang_konversi bk on bk.kode_konversi = k.kode_konversi where bk.identitas_konversi = '3' and bk.kode_barang = '" + kode_barang + "'";
java.sql.Connection conn = (Connection) Koneksi.configDB();
java.sql.Statement stm = conn.createStatement();
java.sql.ResultSet res = stm.executeQuery(sql);
while (res.next()) {
String kode = res.getString("kode_konversi");
System.out.println("konversi " + kode);
String sat = res.getString("nama_konversi");
String sat2 = "2. " + sat;
tbl_Permintaan_MutasiAG_new.setValueAt(sat2, tbl_Permintaan_MutasiAG_new.getSelectedRow(), 3);
System.out.println(sat2);
}
res.close();
conn.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Eror" + e);
}
} else if (evt.getKeyCode() == KeyEvent.VK_DOWN && (tbl_Permintaan_MutasiAG_new.getSelectedColumn() == 1 || tbl_Permintaan_MutasiAG_new.getSelectedColumn() == 2 || tbl_Permintaan_MutasiAG_new.getSelectedColumn() == 3 || tbl_Permintaan_MutasiAG_new.getSelectedColumn() == 6)) {
InputMap im = tbl_Permintaan_MutasiAG_new.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
KeyStroke down = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0);
KeyStroke f2 = KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0);
im.put(down, im.get(f2));
System.out.println("asd");
} else if (evt.getKeyCode() == KeyEvent.VK_DOWN && (tbl_Permintaan_MutasiAG_new.getSelectedColumn() == 0 || tbl_Permintaan_MutasiAG_new.getSelectedColumn() == 4 || tbl_Permintaan_MutasiAG_new.getSelectedColumn() == 5)) {
InputMap im = tbl_Permintaan_MutasiAG_new.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
KeyStroke down = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0);
KeyStroke f2 = KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0);
im.put(f2, null);
im.put(down, null);
System.out.println("fgh");
}
} catch (NullPointerException e) {
JOptionPane.showMessageDialog(null, "Data harus lengkap");
}
loadNumberTable();
}//GEN-LAST:event_tbl_Permintaan_MutasiAG_newKeyPressed
private void tbl_Permintaan_MutasiAG_newKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbl_Permintaan_MutasiAG_newKeyReleased
DefaultTableModel model = (DefaultTableModel) tbl_Permintaan_MutasiAG_new.getModel();
int selectedRow = tbl_Permintaan_MutasiAG_new.getSelectedRow();
int baris = tbl_Permintaan_MutasiAG_new.getRowCount();
TableModel tabelModel;
tabelModel = tbl_Permintaan_MutasiAG_new.getModel();
loadNumberTable();
if ( (tbl_Permintaan_MutasiAG_new.getSelectedColumn() == 0
|| tbl_Permintaan_MutasiAG_new.getSelectedColumn() == 3
|| tbl_Permintaan_MutasiAG_new.getSelectedColumn() == 4
|| tbl_Permintaan_MutasiAG_new.getSelectedColumn() == 5)
&& tbl_Permintaan_MutasiAG_new.getValueAt(tbl_Permintaan_MutasiAG_new.getSelectedRow(), 4) != "") {
showQTY();
}
}//GEN-LAST:event_tbl_Permintaan_MutasiAG_newKeyReleased
private void LabelSaveMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_LabelSaveMouseClicked
SaveData();
}//GEN-LAST:event_LabelSaveMouseClicked
private void comTableLokasiPemintaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comTableLokasiPemintaActionPerformed
if (comTableLokasiPeminta.getSelectedItem() == comTableLokasiPenyedia.getSelectedItem()) {
JOptionPane.showMessageDialog(null, "Lokasi tidak boleh sama");
comTableLokasiPeminta.setSelectedIndex(peminta);
}
else{
seleksilokasipeminta();
System.out.println("seleksi peminta : " + lokasipeminta);
}
/*
lokasi_deactived = comTableLokasiPeminta.getSelectedItem().toString();
comTableLokasiPenyedia.removeItem(lokasi_deactived);
if (!comTableLokasiPeminta.getSelectedItem().toString().equals(lokasi_tmp)) {
comTableLokasiPenyedia.addItem(lokasi_deactived);
}
*/
}//GEN-LAST:event_comTableLokasiPemintaActionPerformed
private void comTableLokasiPenyediaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comTableLokasiPenyediaActionPerformed
if ( comTableLokasiPenyedia.getSelectedItem() == comTableLokasiPeminta.getSelectedItem()) {
JOptionPane.showMessageDialog(null, "Lokasi tidak boleh sama");
comTableLokasiPenyedia.setSelectedIndex(penyedia);
}else{
seleksilokasipenyedia();
System.out.println("seleksi penyedia : " + lokasipenyedia);
}
//loadComTableKode();
//loadComTableBarang();
}//GEN-LAST:event_comTableLokasiPenyediaActionPerformed
private void label_ExitMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_label_ExitMouseClicked
awal.setVisible(true);
awal.setFocusable(true);
awal.loadTable(status, "*");
this.dispose();
}//GEN-LAST:event_label_ExitMouseClicked
private void label_ClearMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_label_ClearMouseClicked
ClearData();
}//GEN-LAST:event_label_ClearMouseClicked
void load_dari_kode_barang() {
int selectedRow = tbl_Permintaan_MutasiAG_new.getSelectedRow();
String nama_awal = String.valueOf(comTableKode.getSelectedItem());
String[] split = new String[2];
System.out.println("nilai comTable barang adalah " + comTableKode.getSelectedItem());
if (comTableKode.getSelectedItem() != null) {
split = nama_awal.split("-");
}
try {
String sql = "select kode_barang,nama_barang from barang where kode_barang = '" + split[0] + "'";
java.sql.Connection conn = (Connection) Koneksi.configDB();
java.sql.Statement stm = conn.createStatement();
java.sql.ResultSet res = stm.executeQuery(sql);
while (res.next()) {
String kode = res.getString("kode_barang");
String nama = res.getString("nama_barang");
loadNumberTable();
if (selectedRow != -1) {
System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&");
this.kodebarang = Integer.parseInt(kode);
loadComTableSatuan();
tbl_Permintaan_MutasiAG_new.setValueAt(comTableKonv.getItemAt(0), selectedRow, 3);
tbl_Permintaan_MutasiAG_new.setValueAt(kode, selectedRow, 1);
tbl_Permintaan_MutasiAG_new.setValueAt(nama, selectedRow, 2);
tbl_Permintaan_MutasiAG_new.setValueAt(0, selectedRow, 4);
}
}
conn.close();
res.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Eror" + e);
e.printStackTrace();
}
}
private void comTableKodeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comTableKodeActionPerformed
load_dari_kode_barang();
//
// int kode_barang = 0;
// int baris = tbl_Permintaan_MutasiAG_new.getRowCount();
// TableModel tabelModel;
// tabelModel = tbl_Permintaan_MutasiAG_new.getModel();
// int selectedRow = tbl_Permintaan_MutasiAG_new.getSelectedRow();
//
// try {
// /*
// String kalimat = comTableKode.getSelectedItem().toString();
// String[] kata = kalimat.split(" -- ");
// for (int i = 0; i < kata.length; i++) {
// System.out.println(kata[i]);
// }
// tbl_Permintaan_MutasiAG_new.setValueAt(kata[0], 0, 1);
// tbl_Permintaan_MutasiAG_new.setValueAt(kata[1], 0, 2);
// */
//
// String sql = "select * from barang where kode_barang = '" + comTableKode.getSelectedItem().toString() + "'";
// System.out.println(comTableKode.getSelectedItem());
// java.sql.Connection conn = (Connection) Koneksi.configDB();
// java.sql.Statement stm = conn.createStatement();
// java.sql.ResultSet res = stm.executeQuery(sql);
// while (res.next()) {
// String kode = res.getString(1);
// String brg = res.getString(4);
// // loadComTableSatuan();
// // String konv = comTableKonv.getSelectedItem().toString();
//
// if (selectedRow != -1) {
// tbl_Permintaan_MutasiAG_new.setValueAt(brg, selectedRow, 2);
// tbl_Permintaan_MutasiAG_new.setValueAt(kode , selectedRow, 1);
//
// }
// }
// } catch (Exception e) {
// JOptionPane.showMessageDialog(null, "Eror" + e);
// e.printStackTrace();
// }
//
// try {
// String sql = "select k.nama_konversi, k.kode_konversi from konversi k, barang_konversi bk where k.kode_konversi = bk.kode_konversi and bk.kode_barang = '" + kode_barang + "'";
// java.sql.Connection conn = (Connection) Koneksi.configDB();
// java.sql.Statement stm = conn.createStatement();
// java.sql.ResultSet res = stm.executeQuery(sql);
// String Konv = "";
// while (res.next()) {
// Konv = res.getString(1);
//// comTableKonv.addItem(Konv);
// System.out.println("Konv =" + Konv);
// // System.out.println("echo : " + tbl_Pembelian.getValueAt(selectedRow, 2).toString());
//// tbl_Permintaan_MutasiAG_new.setValueAt(comTableKonv.getSelectedItem(), selectedRow, 2);
//
// }
//
// } catch (Exception e) {
// JOptionPane.showMessageDialog(null, "Eror nyaaaaa: ");
// e.printStackTrace();
// }
//
}//GEN-LAST:event_comTableKodeActionPerformed
void loadComboKode(String key) {
Runnable doHighlight = new Runnable() {
@Override
public void run() {
System.out.println("ini load combo nama");
try {
String sql = "select concat(kode_barang,\"-\",nama_barang) as gabung from barang where kode_barang ='" + key + "' OR nama_barang like '%" + key + "%'";
System.out.println(sql);
java.sql.Connection conn = (Connection) Koneksi.configDB();
java.sql.Statement stm = conn.createStatement();
java.sql.ResultSet res = stm.executeQuery(sql);
System.out.println("ini sql com kode nama " + sql);
kode_nama_arr.clear();
kode_nama_arr.add("");
while (res.next()) {
String gabung = res.getString("gabung");
kode_nama_arr.add(gabung);
item++;
}
if (item == 0) {
item = 1;
}
comTableKode.setModel(new DefaultComboBoxModel(kode_nama_arr.toArray()));
((JTextComponent) comTableKode.getEditor().getEditorComponent()).setText(key);
conn.close();
res.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Eror" + e);
e.printStackTrace();
}
}
};
SwingUtilities.invokeLater(doHighlight);
}
void loadComboNama(String key) {
Runnable doHighlight = new Runnable() {
@Override
public void run() {
System.out.println("ini load combo nama");
try {
String sql = "select concat(kode_barang,\"-\",nama_barang) as gabung from barang where kode_barang ='" + key + "' OR nama_barang like '%" + key + "%'";
System.out.println(sql);
java.sql.Connection conn = (Connection) Koneksi.configDB();
java.sql.Statement stm = conn.createStatement();
java.sql.ResultSet res = stm.executeQuery(sql);
System.out.println("ini sql com kode nama " + sql);
kode_nama_arr.clear();
kode_nama_arr.add("");
while (res.next()) {
String gabung = res.getString("gabung");
kode_nama_arr.add(gabung);
item++;
}
if (item == 0) {
item = 1;
}
comTableBarang.setModel(new DefaultComboBoxModel(kode_nama_arr.toArray()));
((JTextComponent) comTableBarang.getEditor().getEditorComponent()).setText(key);
conn.close();
res.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Eror" + e);
e.printStackTrace();
}
}
};
SwingUtilities.invokeLater(doHighlight);
}
private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
awal.setVisible(true);
awal.setFocusable(true);
awal.loadTable(status, "*");
this.dispose();
}
}//GEN-LAST:event_formKeyPressed
private void formKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyReleased
}//GEN-LAST:event_formKeyReleased
private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
}//GEN-LAST:event_formWindowActivated
private void comTableBarangKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_comTableBarangKeyPressed
}//GEN-LAST:event_comTableBarangKeyPressed
private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
awal.setVisible(true);
awal.setFocusable(true);
awal.loadTable(status, "*");
}//GEN-LAST:event_formWindowClosed
private void tbl_Permintaan_MutasiAG_newKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbl_Permintaan_MutasiAG_newKeyTyped
if (tbl_Permintaan_MutasiAG_new.getSelectedColumn() == 4
|| tbl_Permintaan_MutasiAG_new.getSelectedColumn() == 5) {
char vChar = evt.getKeyChar();
if (!(Character.isDigit(vChar)
|| (vChar == java.awt.event.KeyEvent.VK_BACK_SPACE)
|| (vChar == java.awt.event.KeyEvent.VK_DELETE))) {
evt.consume();
}
}
}//GEN-LAST:event_tbl_Permintaan_MutasiAG_newKeyTyped
private void tbl_Permintaan_MutasiAG_newMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbl_Permintaan_MutasiAG_newMouseClicked
}//GEN-LAST:event_tbl_Permintaan_MutasiAG_newMouseClicked
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
SaveData();
}//GEN-LAST:event_jMenuItem1ActionPerformed
private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
ClearData();
}//GEN-LAST:event_jMenuItem2ActionPerformed
private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed
this.dispose();
}//GEN-LAST:event_jMenuItem3ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Windows".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Master_Mutasi_PermintaanMutasiAntarGudang_DetailNew.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Master_Mutasi_PermintaanMutasiAntarGudang_DetailNew.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Master_Mutasi_PermintaanMutasiAntarGudang_DetailNew.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Master_Mutasi_PermintaanMutasiAntarGudang_DetailNew.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Master_Mutasi_PermintaanMutasiAntarGudang_DetailNew().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel LabelSave;
private javax.swing.JComboBox comTableBarang;
private javax.swing.JComboBox comTableKode;
private javax.swing.JComboBox comTableKonv;
private javax.swing.JComboBox<String> comTableLokasiPeminta;
private javax.swing.JComboBox<String> comTableLokasiPenyedia;
private javax.swing.JLabel jLabel21;
private javax.swing.JLabel jLabel22;
private javax.swing.JLabel jLabel23;
private javax.swing.JLabel jLabel24;
private javax.swing.JLabel jLabel25;
private javax.swing.JLabel jLabel27;
private javax.swing.JLabel jLabel28;
private javax.swing.JLabel jLabel32;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JMenuItem jMenuItem3;
private javax.swing.JScrollPane jScrollPane17;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JSeparator jSeparator3;
private javax.swing.JSeparator jSeparator4;
private javax.swing.JSeparator jSeparator7;
private javax.swing.JSeparator jSeparator9;
private javax.swing.JLabel label_Clear;
private javax.swing.JLabel label_Exit;
private javax.swing.JTable tbl_Permintaan_MutasiAG_new;
private javax.swing.JTextField txtJumItem;
private javax.swing.JTextField txtJumQty;
private javax.swing.JTextField txt_Keterangan;
private javax.swing.JTextField txt_Qty;
private javax.swing.JTextField txt_noBukti;
private javax.swing.JTextField txt_noPermintaan;
private javax.swing.JTextField txt_tgl;
// End of variables declaration//GEN-END:variables
}
|
PHP
|
UTF-8
| 4,120 | 2.828125 | 3 |
[] |
no_license
|
<?php ob_start(); ?>
<?php
function placeholder($image)
{
if(!isset($image))
{
return 'php.png';
}
else
{
return $image;
}
}
function redirect($location){
global $connection;
header("Location:" . $location);
// instead of returning you can use exit function
exit;
}
function ifItIsMethod($method)
{
if($_SERVER['REQUEST_METHOD'] == strtoupper($method))
{
return true;
}
else
{
return false;
}
}
function isLoggedIn()
{
if(isset($_SESSION['user_role']))
{
return true;
}
else
{
return false;
}
}
function checkIfUserIsLoggedInAndRedirect($redirectLocation = null)
{
if(isLoggedIn())
{
redirect($redirectLocation);
}
}
function escape($string)
{
global $connection;
return mysqli_real_escape_string($connection, trim($string));
}
// those users_role is set to admin that only can acces the users.php page
function is_admin($username)
{
global $connection;
$query="SELECT user_role FROM users WHERE username = '$username'";
$result=mysqli_query($connection,$query);
if(!$result)
{
die("query failed".mysqli_error($connection));
}
$row=mysqli_fetch_assoc($result);
if($row['user_role']=='admin')
{
return true;
}
else
{
return false;
}
}
function username_exist($username)
{
global $connection;
$query="SELECT username FROM users WHERE username = '$username'";
$result = mysqli_query($connection,$query);
if(!$result)
{
die("query failed".mysqli_error($connection));
}
if(mysqli_num_rows($result)>1)
{
return true;
}
else{
return false;
}
}
function email_exist($email)
{
global $connection;
$query="SELECT user_email FROM users WHERE user_email = '$email'";
$result = mysqli_query($connection,$query);
if(!$result)
{
die("query failed".mysqli_error($connection));
}
if(mysqli_num_rows($result)>0)
{
return true;
}
else{
return false;
}
}
function register_user($username,$email,$password)
{
global $connection;
$username=mysqli_real_escape_string($connection,$username);
$email=mysqli_real_escape_string($connection,$email);
$password=mysqli_real_escape_string($connection,$password);
$password = password_hash($password, PASSWORD_BCRYPT, array('cost' => 10));
$query = "INSERT INTO users (username, user_email, user_password, user_role) ";
$query .= "VALUES('$username', '$email', '$password', 'subscriber' )";
$register_user_query=mysqli_query($connection,$query);
if(!$register_user_query)
{
die("query failed".mysqli_error($connection));
}
// $message = "your registration has been submitted";
}
function login_users($username,$password)
{
global $connection;
$username = trim($username);
$password = trim($password);
$username=mysqli_real_escape_string($connection,$username);
$password=mysqli_real_escape_string($connection,$password);
$query="SELECT * FROM users WHERE username='$username' ";
$select_user_query=mysqli_query($connection,$query);
if(!$select_user_query)
{
die("Query failed".mysqli_error($connection));
}
while($row=mysqli_fetch_assoc($select_user_query))
{
$db_user_id=$row['user_id'];
$db_username=$row['username'];
$db_user_password=$row['user_password'];
$db_user_firstname=$row['user_firstname'];
$db_user_lastname=$row['user_lastname'];
$db_user_role=$row['user_role'];
if(password_verify($password,$db_user_password))
{
$_SESSION['username'] = $db_username;
$_SESSION['firstname'] = $db_user_firstname;
$_SESSION['lastname'] = $db_user_lastname;
$_SESSION['user_role'] = $db_user_role;
redirect("/cms/admin");
}
else
{
return false;
}
}
return true;
}
?>
|
Markdown
|
UTF-8
| 1,271 | 3.25 | 3 |
[] |
no_license
|
### **Orientation**
```
Del.» function Orientation(const poly: TPath): boolean;
C++ » bool Orientation(const Path &poly); // Function in the ClipperLib namespace.
C# » public static bool Orientation(Path poly); // Static method of the Clipper class in the ClipperLib namespace.
```
方向只有在封闭的曲线里面是重要的,方向的定义就是在给定的封闭曲线中给出点集是按照顺时针还是逆时针进行排列;
方向同样是跟轴的方向有关联的:
- 在Y轴向上显示模式中,方向变量为true对应的是为逆时针轮廓;
- 在Y轴向下显示模式中,方向变量为true对应的是为顺时针轮廓;

> **Note**:
> 自交多边形有着不确定的方向性,此时函数不会返回一个有意义的值;
> 大部分2D的图形显示库(例如GDI、GDI+)甚至SVG文件格式有其坐标原点(在左上角,y轴方向朝下)。但是,一部分显示库(OpenGL等)可以自定义坐标原点,或者自定义Y方向朝上;
> 对于None-Zero填充的多边形,内环(内孔)的方向必须和外环相反;
> 对于由CLipper库的Execute方法,他们的外孔结果永远为true,内孔结果永远为false;(除非ReverseSolution属性已经被启用)
|
C#
|
UTF-8
| 794 | 3.046875 | 3 |
[] |
no_license
|
namespace WeatherStation
{
public class WeatherData : Observable<WeatherInfo>
{
private double _humidity;
private double _pressure;
private double _temperature;
private void MeasurementsChanged()
{
NotifyObservers();
}
public void SetMeasurements(double temp, double humidity, double pressure)
{
_humidity = humidity;
_temperature = temp;
_pressure = pressure;
MeasurementsChanged();
}
protected override WeatherInfo GetChangedData()
{
WeatherInfo info;
info.Temperature = _temperature;
info.Humidity = _humidity;
info.Pressure = _pressure;
return info;
}
}
}
|
JavaScript
|
UTF-8
| 668 | 3.421875 | 3 |
[] |
no_license
|
const crypto = require ('crypto');
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let comparedStr = '0000';
for (let i = 0; i < 60; i++) {
comparedStr += 'f';
}
//console.log(comparedStr);
rl.question('Enter a string: ', str => {
const magicNumber = mine(str);
console.log(magicNumber);
rl.close();
});
function mine(str) {
let i = 0;
let str_new;
do {
i++;
str_new = str + i;
hashed = crypto.createHash('sha256').update(str_new).digest('hex');
} while (hashed >= comparedStr);
console.log(hashed)
return i;
}
|
Markdown
|
UTF-8
| 10,948 | 3.0625 | 3 |
[] |
no_license
|
# readme
### 目录
* [第10次作业新增内容(最新)](#new3)
* [设计文档更新](#设计文档更新)
* [新增出租车类型](#新增出租车类型)
* [新增测试接口](#新增测试接口2)
* [第9次作业新增内容](#new2)
* [bug修改说明](#bug修改说明)
* [设计文档](#设计文档)
* [道路交叉方式的输入](#道路交叉方式的输入)
* [新增内容(第8次作业)](#new)
* [新增测试接口](#新增测试接口)
* [过程规格](#过程规格)
* [上次内容(第7次作业)](#last)
* [输入](#输入)
* [本程序提供的测试接口](#本程序提供的测试接口)
* [测试](#测试)
---
> <h3 id="new3">第10次作业新增内容(最新)</h3>
> 请***务必***先按顺序阅读[第7次内容(点击跳转)](#last),[第8次内容(点击跳转)](#new)和[第9次内容(点击跳转)](#new2)再阅读[本次内容](#new3)
<h3 id="设计文档更新">设计文档更新</h3>
设计文档新增了以下内容:
* `pos` 类
* `car_mofa` 类
* `path` 类
<h3 id="新增出租车类型">新增出租车类型</h3>
现在100辆出租车中,序号在[0,29]范围内的为新型出租车,序号在[30,99]范围内的为旧出租车,测试的时候请注意
<h3 id="新增测试接口2">新增测试接口</h3>
* `_disp.watcher.get_ser_count(int x)`
* 作用:返回x号出租车(新型出租车)完成的请求数量
* x 的取值范围为[0,29]
* 返回类型:int
* `_disp.watcher.get_path(int x,int y)`
* 作用:返回x号出租车(新型出租车)第y次完成请求时经过的路径的迭代器
* x的取值范围为[0,29]
* y的取值范围为[0,get_ser_count(x)]
* 返回类型:Iterator
* 注意:
* 返回的路径为出租车从乘客位置到目的地的路径,如果因等红灯而停住则会包含多个连续的相同坐标。如果在请求尚未完成的时候调用该函数,返回的是不完整的路径(当前已经经过的路径)
* 虽然红灯经过300ms就会变绿,但出租车是有可能在一个点等超过300ms红灯的,现介绍其中两种情况:
* 1.出租车到达某点的时候向右是绿的,100ms后将要向右移动的时候,向右恰好变红,又要等300ms
* 2.出租车要从A点到B点,有两条最短路径,一条向上,一条向右。一开始向右行红灯,但向右的流量小,因此出租车选择向右的路径,等红灯。等路灯变为向右绿,向上红的时候,恰好流量变为向上走的流量小于向右走,这时出租车又会选择向上走的路线,第二次等红灯。因此理论上出租车可能在一个点等任意长时间的红灯,测试时请您注意。
* 关于新增测试接口的使用姿势:先调用`_disp.watcher.get_ser_count(int x)`获取x号出租车的完成的请求数,再调用`_disp.watcher.get_path(int x,int y)`获得相应的该出租车某次完成请求经过路径的迭代器iter,之后在iter的hasNext为true的前提下调用iter的next方法,则会返回一个Object类型的对象temp,将temp转化为pos类型的对象之后,调用temp的get_x()和get_y()就可以获得路径中的一个坐标啦~具体使用方法在`test_thread`类里面有示例代码可供参考
---
> <h3 id="new2">第9次作业新增内容</h3>
> 请***务必***先按顺序阅读[第7次内容(点击跳转)](#last)和[第8次内容(点击跳转)](#new)再阅读[本次内容](#new2)
<h3 id="bug修改说明">bug修改说明</h3>
上次作业,使用了javafx.util.Pair,我用的idea,没有问题,但那哥们用的eclipse说编译不了,其实把jre移除再重新添加就好了,但还是被他扣了一波,我也懒得向课代表申诉了,这次把所有用到的Pair都移除了
<h3 id="设计文档">设计文档</h3>
* 详见设计文档
* 包含以下内容:
* overview
* 表示对象
* 抽象函数
* 不变式
* 过程规格在代码中每个方法前的注释中
<h3 id="道路交叉方式的输入">道路交叉方式的输入</h3>
* 与前两次作业相比,增加了道路交叉方式的输入,在输入完地图之后,会在控制台输出* "请输入道路交叉方式信息所在的文件的绝对路径" *,此时请由***控制台***输入文件的***绝对路径***。如`F:\temp\新建文本文档.txt`
* 为保留原有地图的输入方法,程序应单独增加一文件输入,定义道路交叉情况。 文件内容为 80 行字符串,每行有 80 个字符,每个字符为 0 或 1。 0 表示立体交叉, 1 表示平面交叉。理论上,两者的数量应该各占一半。 该文件与地图文件一样, ***由测试者***保证输入文件的有效性。 交叉方式与结点的邻接关系无关,并不是十字路口才能设置立体交叉,直道也允许拥有立体交叉属性。(摘自基本法)
* 程序运行开始,先输入地图所在文件,再输入道路交叉方式信息所在文件
> [继续阅读第10次新增内容(点击跳转)](#new3)
---
> <h3 id="new">第8次作业新增内容</h3>
> 请***务必***先仔细阅读[上次内容(点击跳转)](#last)再阅读[本次作业新增内容](#new)
<h3 id="新增测试接口">新增测试接口</h3>
* `_disp.open_edge(int x,int y,String direct)`
* 作用:打开已有的边,边的位置是与坐标(x,y)相连的上、下、左、右四条中的一个,由参数direct决定
* x, y 的取值范围为[0,79]
* direct 可以取的值如下:
* `up`:表明创建的边连接坐标(x,y)与其上方的点(x-1,y)
* `down`:表明创建的边连接坐标(x,y)与其下方的点(x+1,y)
* `left`:表明创建的边连接坐标(x,y)与其左边的点(x,y-1)
* `right`:表明创建的边连接坐标(x,y)与其右边的点(x,y-1)
* 返回类型:void
* 注意事项:
* 支持在运行过程中动态关闭或打开一些地图上***已有的连接边***,受影响边的总数***由测试者***确保不能超过 5,任意时刻需要***由测试者***确保地图上的***所有的点都是连通***的。(摘自基本法)
* 对上一条注意事项中***“已有的连接边”*** 的理解:即打开的边必须为地图文件信息中存在的边,也就是说,不能创建边,只能打开关闭的边。
* 另外值得注意的是:坐标(x,y)中x代表行号,而y代表列号,因此(x,y)的上方是(x-1,y)
* `_disp.close_edge(int x,int y,String direct)`
* 作用:关闭已有的边,边的位置是与坐标(x,y)相连的上、下、左、右四条中的一个,由参数direct决定
* x, y 的取值范围为[0,79]
* direct 可以取的值如下:
* `up`:表明消除连接坐标(x,y)与其上方的点(x-1,y)的边
* `down`:表明消除连接坐标(x,y)与其下方的点(x+1,y)的边
* `left`:表明消除连接坐标(x,y)与其左边的点(x,y-1)的边
* `right`:表明消除连接坐标(x,y)与其右边的点(x,y-1)的边
* 返回类型:void
* 注意事项:同`_disp.open_edge(int x,int y,String direct)`中注意事项
<h3 id="过程规格">过程规格</h3>
* 在每个方法前的注释中
* 包括三项内容:
* requires: 定义了过程对输入的约束要求。
* modifies: 过程在执行过程中对Input的修改。
* effects: 定义了过程在所有未被Requires排除的输入下给出的执行效果。
> [继续阅读第9次新增内容(点击跳转)](#new2)
---
> <h3 id="last">第7次作业内容</h3>
<h3 id="输入">输入</h3>
* 城市地图通过文件输入,文件格式为文本文件。文件内容为 80 行字符串,
每行有 80 个字符,每个字符为 0 到 3 之间的整数。(摘自基本法)
* 文件需要***由测试者***确保地图上的所有的点都是连通的,即整个图是连通图,
但不能存在点与图外的点有连接,例如 (80,1) 不能是 2 或 3,(80,80) 只能是 0。(摘自基本法)
* 程序开始运行后,会在控制台输出 *"请输入地图数据所在的文件的绝对路径"* ,此时请在***控制台***中输入包含地图数据的文件的***绝对路径***,如`F:\temp\新建文本文档.txt`
<h3 id="本程序提供的测试接口">本程序提供的测试接口</h3>
* `_disp`为在`main`函数中创建的`disp类`的一个对象。
* 测试时,请调用`_disp`的如下方法:
* `_disp.watcher.get_reputation(int x)`
* 作用:获取x号出租车的信誉值
* 返回类型为int
* x的取值范围为[0,99]
* `_disp.watcher.get_status(int x)`
* 作用:获得x号出租车的运行状态
* 返回类型为String
* x的取值范围为[0,99]
* 车运行的状态有如下四种:
* `waiting`:等待服务
* `stopped`:停止运行
* `serving`:正在服务
* `to-passenger`:即将服务
* `_disp.watcher.get_x(int x)`
* 作用:获得x号出租车在地图中所处的行号
* 返回类型为int
* x的取值范围为[0,99]
* `_disp.watcher.get_y(int x)`
* 作用:获得x号出租车在地图中所处的列号
* 返回类型为int
* x的取值范围为[0,99]
* `_disp.watcher.get_time(int x)`
* 作用:获得当前时间(当前系统时间-`_disp`这个对象被创建时的系统时间)
* 返回类型为long
* x的取值范围为[0,99]
* `_disp.add_request(int x, int y, int dest_x, int dest_y)`
* 作用:添加新的乘客请求(从(x,y)前往(dest_x,dest_y)的请求)
* 返回类型为void
* x, y, dest_x, dest_y 的取值范围均为[0,79]
* 若请求无法响应,则会在控制台输出类似如下内容:
>请求 (22,5) => (43,27) 没有车能够响应
* 注意:由于指导书中要求请求队列容量只需不少于300,因此,一旦同时运行的请求数超过300,程序将从控制台输出提示信息。此后,虽然程序继续运行,但不对发生的错误负责
* ***注意:测试时请一定要调用_disp这个对象的测试接口,而不要创建disp类的其他对象。在main函数作用域以外测试的话需要将_disp作为参数传递过去***
<h3 id="测试">测试</h3>
* 工程中已经添加了测试代码的示例以供参考,包括`test_thread`类以及`main`函数中46~47行,建好工程直接运行就可以看到测试示例的结果。
* 建议直接修改`test_thread`类的`run`方法进行测试。(注释掉已有代码,添加新的测试代码)
* 当然,要是完全重写测试线程我也是兹词的,但要记得将`main`函数中46~47行注释掉,在相同位置启动测试线程。注意一定要像示例的测试代码那样先在`main`函数中将`_disp`作为参数传给测试线程,再在测试线程中调用`_disp`的相应方法进行测试,因为很重要所以又说了一遍。
> [继续阅读第8次新增内容(点击跳转)](#new)
|
Java
|
UTF-8
| 844 | 2.15625 | 2 |
[
"Apache-2.0"
] |
permissive
|
package lv.ctco.cukes.ldap.facade;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import lv.ctco.cukes.core.internal.context.GlobalWorldFacade;
import lv.ctco.cukes.ldap.internal.ConnectionService;
@Singleton
public class SetupFacade {
@Inject
GlobalWorldFacade world;
@Inject
ConnectionService connectionService;
public void initConfiguration() {
connectionService.close();
}
public void setUrl(String url) {
world.put(ConnectionService.URL, url);
connectionService.close();
}
public void setUserDn(String userDn) {
world.put(ConnectionService.USER, userDn);
connectionService.close();
}
public void setPassword(String password) {
world.put(ConnectionService.PASSWORD, password);
connectionService.close();
}
}
|
C#
|
UTF-8
| 1,907 | 3.515625 | 4 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lesson0102
{
class Program
{
static void Main(string[] args)
{
// Các toán tử
// Toán tử số học: +; -; *; /; %
// Toán tử so sánh: >; >=; <; <=; ==; !=
// Toán tử logic: && (and - và) ; || (or - hoặc); !
// Toán tử gán: =; +=; -=; *=; /=; %=
// Toán tử tăng/ giảm: ++; --
// Toán tử nối chuỗi: +
// Toán tử điều kiện: (Biểu thức điều kiện) ? <gt đúng> : <gt sai>;
//example
int x = 115, y = 255;
int z;
// Toán tử số học: +; -; *; /; %
z = x + y;
Console.WriteLine("{0} + {1} = {2}", x, y, z);
z = x - y;
Console.WriteLine("{0} - {1} = {2}", x, y, z);
z = x * y;
Console.WriteLine("{0} * {1} = {2}", x, y, z);
z = x / y;
Console.WriteLine("{0} / {1} = {2}", x, y, z);
z = x % y;
Console.WriteLine("{0} % {1} = {2}", x, y, z);
//So sánh
bool flag;
flag = x > y;
Console.WriteLine(flag);
flag = x < y;
Console.WriteLine(flag);
flag = (x >= y) && (x < y);
Console.WriteLine(flag);
flag = (x >= y) || (x < y);
Console.WriteLine(flag);
flag = !(x >= y);
Console.WriteLine(flag);
// gán:
x = 123;
Console.WriteLine("x++ = {0} ", x++);
Console.WriteLine("x++ = {0} ", x++);
y = 12;
Console.WriteLine("++y={0}", ++y);
z = 123;
z += 100; // z=z+100;
}
}
}
|
JavaScript
|
UTF-8
| 1,275 | 3.4375 | 3 |
[
"MIT"
] |
permissive
|
/**
* @param {number[][]} times
* @param {number} N
* @param {number} K
* @return {number}
*/
const networkDelayTime = function (times, N, K) {
const mins = new Array(N).fill(Infinity)
mins[K - 1] = 0
for (let i = 0; i < N; i++) {
for (let [u, v, t] of times) {
if (mins[u - 1] === Infinity) continue
if (mins[v - 1] > mins[u - 1] + t) {
mins[v - 1] = mins[u - 1] + t
}
}
}
return mins.includes(Infinity) ? -1 : Math.max(...mins)
}
// another
/**
* @param {number[][]} times
* @param {number} N
* @param {number} K
* @return {number}
*/
const networkDelayTime = function(times, N, K) {
const distances = new Array(N).fill(Infinity);
distances[K - 1] = 0;
for(let i = 0 ; i < N -1 ; i++){
let counter = 0;
for(let j = 0 ; j < times.length ; j++){
const source = times[j][0];
const target = times[j][1];
const weight = times[j][2];
if(distances[source - 1] + weight < distances[target - 1]){
distances[target - 1] = distances[source - 1] + weight;
counter++
}
}
if(counter === 0) break
}
const res = Math.max(...distances);
return res === Infinity ? -1 : res;
};
|
C++
|
UTF-8
| 1,142 | 2.65625 | 3 |
[] |
no_license
|
// matrix.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include "NxM_Matrix.h"
#include "Sqr_Matrix.h"
#include "Network.h"
using namespace std;
int main()
{
/// ----- new main ----- ///
string file = "in.txt";
Network *nnet = new Network(3, 3, file);
nnet->read_input_data(file);
nnet->init_biases();
nnet->init_weights();
for (int z = 0; z < 7; z++) {
column *il = new column();
il->col = nnet->inp[z];
il->height = il->col.size();
cout << "========== FORWARD PASS BELOW =========" << endl;
column *o1 = nnet->forward_pass(z);
column *t1 = nnet->target_col(il);
cout << "=======================================" << endl;
cout << "*** input ****" << endl;
nnet->h_layer_1->print_col(il);
cout << "**** target ****" << endl;
nnet->h_layer_1->print_col(t1);
cout << "**** actual ****" << endl;
nnet->h_layer_1->print_col(o1);
cout << "**** loss ****" << endl;
cout << nnet->euclid_distance(o1, t1) << endl;
}
int r;
cin >> r;
return r;
}
|
C++
|
UTF-8
| 1,973 | 3.15625 | 3 |
[] |
no_license
|
#include "Input.h"
#include <conio.h>
namespace Utils
{
Input::Input()
: mLastInput(Key::None)
{
// Empty
}
Input::~Input()
{
// Empty
}
void Input::Update()
{
if (_kbhit())
{
int character = _getch();
// Character could be ASCII
// Could also be a scan code (arrow keys, function keys, etc.)
// Check for Scan Code Input - 0xE0 is an escape code indicating scan code
if (character == 0xE0)
{
character = _getch();
// Process Scan Code
mLastInput = ProcessScanCodeInput(character);
}
else
{
// Process ASCII Code
mLastInput = ProcessAsciiInput(character);
}
}
}
void Input::ResetInput()
{
mLastInput = Key::None;
}
void Input::GetKeyString(Key key, std::string& str) const
{
switch (key)
{
case Key::W:
str = "W";
break;
case Key::A:
str = "A";
break;
case Key::S:
str = "S";
break;
case Key::D:
str = "D";
break;
case Key::Up:
str = "Up";
break;
case Key::Left:
str = "Left";
break;
case Key::Right:
str = "Right";
break;
case Key::Down:
str = "Down";
break;
case Key::Space:
str = "Space";
break;
case Key::Enter:
str = "Enter";
break;
case Key::None:
str = "None";
break;
default:
str = "Invalid";
break;
}
}
Input::Key Input::ProcessAsciiInput(int input) const
{
switch (input)
{
case 'w':
case 'W':
return Key::W;
case 'a':
case 'A':
return Key::A;
case 's':
case 'S':
return Key::S;
case 'd':
case 'D':
return Key::D;
case 32: // ASCII value for Space
return Key::Space;
case 13: // ASCII value for Return
return Key::Enter;
default:
return Key::None;
}
}
Input::Key Input::ProcessScanCodeInput(int input) const
{
switch (input)
{
case 72:
return Key::Up;
case 75:
return Key::Left;
case 77:
return Key::Right;
case 80:
return Key::Down;
default:
return Key::None;
}
}
}
|
C++
|
UTF-8
| 16,453 | 2.515625 | 3 |
[] |
no_license
|
// -*- lsst-c++ -*-
/*
* LSST Data Management System
* Copyright 2008-2014 LSST Corporation.
*
* This product includes software developed by the
* LSST Project (http://www.lsst.org/).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the LSST License Statement and
* the GNU General Public License along with this program. If not,
* see <http://www.lsstcorp.org/LegalNotices/>.
*/
#ifndef LSST_AFW_GEOM_BOX_H
#define LSST_AFW_GEOM_BOX_H
#include <vector>
#include "boost/format.hpp"
#include "lsst/afw/geom/Point.h"
#include "lsst/afw/geom/Extent.h"
#include "ndarray.h"
namespace lsst {
namespace afw {
namespace geom {
class Box2D;
/**
* An integer coordinate rectangle.
*
* Box2I is an inclusive box that represents a rectangular region of pixels. A box
* never has negative dimensions; the empty box is defined to have zero-size dimensions,
* and is treated as though it does not have a well-defined position (regardless of the
* return value of getMin() or getMax() for an empty box).
*
* @internal
*
* Box2I internally stores its minimum point and dimensions, because we expect
* these will be the most commonly accessed quantities.
*
* Box2I sets the minimum point to the origin for an empty box, and returns -1 for both
* elements of the maximum point in that case.
*/
class Box2I {
public:
typedef Point2I Point;
typedef Extent2I Extent;
typedef int Element;
enum EdgeHandlingEnum { EXPAND, SHRINK };
/// Construct an empty box.
Box2I() : _minimum(0), _dimensions(0) {}
/**
* Construct a box from its minimum and maximum points.
*
* @param[in] minimum Minimum (lower left) coordinate (inclusive).
* @param[in] maximum Maximum (upper right) coordinate (inclusive).
* @param[in] invert If true (default), swap the minimum and maximum coordinates if
* minimum > maximum instead of creating an empty box.
*/
Box2I(Point2I const& minimum, Point2I const& maximum, bool invert = true);
/**
* Construct a box from its minimum point and dimensions.
*
* @param[in] minimum Minimum (lower left) coordinate.
* @param[in] dimensions Box dimensions. If either dimension coordinate is 0, the box will be empty.
* @param[in] invert If true (default), invert any negative dimensions instead of creating
* an empty box.
*/
Box2I(Point2I const& minimum, Extent2I const& dimensions, bool invert = true);
/**
* Construct an integer box from a floating-point box.
*
* Floating-point to integer box conversion is based on the concept that a pixel
* is not an infinitesimal point but rather a square of unit size centered on
* integer-valued coordinates. Converting a floating-point box to an integer box
* thus requires a choice on how to handle pixels which are only partially contained
* by the input floating-point box.
*
* @param[in] other A floating-point box to convert.
* @param[in] edgeHandling If EXPAND, the integer box will contain any pixels that
* overlap the floating-point box. If SHRINK, the integer
* box will contain only pixels completely contained by
* the floating-point box.
*/
explicit Box2I(Box2D const& other, EdgeHandlingEnum edgeHandling = EXPAND);
/// Standard copy constructor.
Box2I(Box2I const&) = default;
Box2I(Box2I&&) = default;
~Box2I() = default;
void swap(Box2I& other) {
_minimum.swap(other._minimum);
_dimensions.swap(other._dimensions);
}
/// Standard assignment operator.
Box2I& operator=(Box2I const&) = default;
Box2I& operator=(Box2I&&) = default;
/**
* @name Min/Max Accessors
*
* Return the minimum and maximum coordinates of the box (inclusive).
*/
//@{
Point2I const getMin() const { return _minimum; }
int getMinX() const { return _minimum.getX(); }
int getMinY() const { return _minimum.getY(); }
Point2I const getMax() const { return _minimum + _dimensions - Extent2I(1); }
int getMaxX() const { return _minimum.getX() + _dimensions.getX() - 1; }
int getMaxY() const { return _minimum.getY() + _dimensions.getY() - 1; }
//@}
/**
* @name Begin/End Accessors
*
* Return STL-style begin (inclusive) and end (exclusive) coordinates for the box.
*/
//@{
Point2I const getBegin() const { return _minimum; }
int getBeginX() const { return _minimum.getX(); }
int getBeginY() const { return _minimum.getY(); }
Point2I const getEnd() const { return _minimum + _dimensions; }
int getEndX() const { return _minimum.getX() + _dimensions.getX(); }
int getEndY() const { return _minimum.getY() + _dimensions.getY(); }
//@}
/**
* @name Size Accessors
*
* Return the size of the box in pixels.
*/
//@{
Extent2I const getDimensions() const { return _dimensions; }
int getWidth() const { return _dimensions.getX(); }
int getHeight() const { return _dimensions.getY(); }
int getArea() const { return getWidth() * getHeight(); }
//@}
/// Return slices to extract the box's region from an ndarray::Array.
ndarray::View<boost::fusion::vector2<ndarray::index::Range, ndarray::index::Range> > getSlices() const;
/// Return true if the box contains no points.
bool isEmpty() const { return _dimensions.getX() == 0 && _dimensions.getY() == 0; }
/// Return true if the box contains the point.
bool contains(Point2I const& point) const;
/**
* Return true if all points contained by other are also contained by this.
*
* An empty box is contained by every other box, including other empty boxes.
*/
bool contains(Box2I const& other) const;
/**
* Return true if any points in other are also in this.
*
* Any overlap operation involving an empty box returns false.
*/
bool overlaps(Box2I const& other) const;
/**
* Increase the size of the box by the given buffer amount in all directions.
*
* If a negative buffer is passed and the final size of the box is less than or
* equal to zero, the box will be made empty.
*/
void grow(int buffer) { grow(Extent2I(buffer)); }
/**
* Increase the size of the box by the given buffer amount in each direction.
*
* If a negative buffer is passed and the final size of the box is less than or
* equal to zero, the box will be made empty.
*/
void grow(Extent2I const& buffer);
/// Shift the position of the box by the given offset.
void shift(Extent2I const& offset);
/// Flip a bounding box about the y-axis given a parent box of extent (xExtent).
void flipLR(int xExtent);
/// Flip a bounding box about the x-axis given a parent box of extent (yExtent).
void flipTB(int yExtent);
/// Expand this to ensure that this->contains(point).
void include(Point2I const& point);
/// Expand this to ensure that this->contains(other).
void include(Box2I const& other);
/// Shrink this to ensure that other.contains(*this).
void clip(Box2I const& other);
/**
* Compare two boxes for equality.
*
* All empty boxes are equal.
*/
bool operator==(Box2I const& other) const;
/**
* Compare two boxes for equality.
*
* All empty boxes are equal.
*/
bool operator!=(Box2I const& other) const;
/**
* Get the corner points
*
* The order is counterclockise, starting from the lower left corner, i.e.:
* (minX, minY), (maxX, maxY), (maxX, maxX), (minX, maxY)
*/
std::vector<Point2I> getCorners() const;
std::string toString() const {
return (boost::format("Box2I(%s,%s)") % _minimum.toString() % _dimensions.toString()).str();
}
private:
Point2I _minimum;
Extent2I _dimensions;
};
/**
* A floating-point coordinate rectangle geometry.
*
* Box2D is a half-open (minimum is inclusive, maximum is exclusive) box. A box
* never has negative dimensions; the empty box is defined to zero-size dimensions
* and its minimum and maximum values set to NaN. Only the empty box may have
* zero-size dimensions.
*
* @internal
*
* Box2D internally stores its minimum point and maximum point, instead of
* minimum point and dimensions, to ensure roundoff error does not affect
* whether points are contained by the box.
*
* Despite some recommendations to the contrary, Box2D sets the minimum and maximum
* points to NaN for an empty box. In almost every case, special checks for
* emptiness would have been necessary anyhow, so there was little to gain in
* using the minimum > maximum condition to denote an empty box, as was used in Box2I.
*/
class Box2D {
public:
typedef Point2D Point;
typedef Extent2D Extent;
typedef double Element;
/**
* Value the maximum coordinate is multiplied by to increase it by the smallest
* possible amount.
*/
static double const EPSILON;
/// Value used to specify undefined coordinate values.
static double const INVALID;
/// Construct an empty box.
Box2D();
/**
* Construct a box from its minimum and maximum points.
*
* If any(minimum == maximum), the box will always be empty (even if invert==true).
*
* @param[in] minimum Minimum (lower left) coordinate (inclusive).
* @param[in] maximum Maximum (upper right) coordinate (exclusive).
* @param[in] invert If true (default), swap the minimum and maximum coordinates if
* minimum > maximum instead of creating an empty box.
*/
Box2D(Point2D const& minimum, Point2D const& maximum, bool invert = true);
/**
* Construct a box from its minimum point and dimensions.
*
* @param[in] minimum Minimum (lower left) coordinate (inclusive).
* @param[in] dimensions Box dimensions. If either dimension coordinate is 0, the box will be empty.
* @param[in] invert If true (default), invert any negative dimensions instead of creating
* an empty box.
*/
Box2D(Point2D const& minimum, Extent2D const& dimensions, bool invert = true);
/**
* Construct a floating-point box from an integer box.
*
* Integer to floating-point box conversion is based on the concept that a pixel
* is not an infinitesimal point but rather a square of unit size centered on
* integer-valued coordinates. While the output floating-point box thus has
* the same dimensions as the input integer box, its minimum/maximum coordinates
* are 0.5 smaller/greater.
*/
explicit Box2D(Box2I const& other);
/// Standard copy constructor.
Box2D(Box2D const&) = default;
Box2D(Box2D&&) = default;
~Box2D() = default;
void swap(Box2D& other) {
_minimum.swap(other._minimum);
_maximum.swap(other._maximum);
}
/// Standard assignment operator.
Box2D& operator=(Box2D const&) = default;
Box2D& operator=(Box2D&&) = default;
/**
* @name Min/Max Accessors
*
* Return the minimum (inclusive) and maximum (exclusive) coordinates of the box.
*/
//@{
Point2D const getMin() const { return _minimum; }
double getMinX() const { return _minimum.getX(); }
double getMinY() const { return _minimum.getY(); }
Point2D const getMax() const { return _maximum; }
double getMaxX() const { return _maximum.getX(); }
double getMaxY() const { return _maximum.getY(); }
//@}
/**
* @name Size Accessors
*
* Return the size of the box.
*/
//@{
Extent2D const getDimensions() const { return isEmpty() ? Extent2D(0.0) : _maximum - _minimum; }
double getWidth() const { return isEmpty() ? 0 : _maximum.getX() - _minimum.getX(); }
double getHeight() const { return isEmpty() ? 0 : _maximum.getY() - _minimum.getY(); }
double getArea() const {
Extent2D dim(getDimensions());
return dim.getX() * dim.getY();
}
//@}
/**
* @name Center Accessors
*
* Return the center coordinate of the box.
*/
//@{
Point2D const getCenter() const { return Point2D((_minimum.asEigen() + _maximum.asEigen()) * 0.5); }
double getCenterX() const { return (_minimum.getX() + _maximum.getX()) * 0.5; }
double getCenterY() const { return (_minimum.getY() + _maximum.getY()) * 0.5; }
//@}
/// Return true if the box contains no points.
bool isEmpty() const { return _minimum.getX() != _minimum.getX(); }
/// Return true if the box contains the point.
bool contains(Point2D const& point) const;
/**
* Return true if all points contained by other are also contained by this.
*
* An empty box is contained by every other box, including other empty boxes.
*/
bool contains(Box2D const& other) const;
/**
* Return true if any points in other are also in this.
*
* Any overlap operation involving an empty box returns false.
*/
bool overlaps(Box2D const& other) const;
/**
* Increase the size of the box by the given buffer amount in all directions.
*
* If a negative buffer is passed and the final size of the box is less than or
* equal to zero, the box will be made empty.
*/
void grow(double buffer) { grow(Extent2D(buffer)); }
/**
* Increase the size of the box by the given buffer amount in each direction.
*
* If a negative buffer is passed and the final size of the box is less than or
* equal to zero, the box will be made empty.
*/
void grow(Extent2D const& buffer);
/// Shift the position of the box by the given offset.
void shift(Extent2D const& offset);
/// Flip a bounding box about the y-axis given a parent box of extent (xExtent).
void flipLR(float xExtent);
/// Flip a bounding box about the x-axis given a parent box of extent (yExtent).
void flipTB(float yExtent);
/**
* Expand this to ensure that this->contains(point).
*
* If the point sets a new maximum value for the box, the maximum coordinate will
* be adjusted to ensure the point is actually contained
* by the box instead of sitting on its exclusive upper edge.
*/
void include(Point2D const& point);
/// Expand this to ensure that this->contains(other).
void include(Box2D const& other);
/// Shrink this to ensure that other.contains(*this).
void clip(Box2D const& other);
/**
* Compare two boxes for equality.
*
* All empty boxes are equal.
*/
bool operator==(Box2D const& other) const;
/**
* Compare two boxes for equality.
*
* All empty boxes are equal.
*/
bool operator!=(Box2D const& other) const;
/**
* Get the corner points
*
* The order is counterclockise, starting from the lower left corner, i.e.:
* (minX, minY), (maxX, maxY), (maxX, maxX), (minX, maxY)
*/
std::vector<Point2D> getCorners() const;
std::string toString() const {
return (boost::format("Box2D(%s,%s)") % _minimum.toString() % _maximum.toString()).str();
}
private:
void _tweakMax(int n) {
if (_maximum[n] < 0.0) {
_maximum[n] *= (1.0 - EPSILON);
} else if (_maximum[n] > 0.0) {
_maximum[n] *= (1.0 + EPSILON);
} else {
_maximum[n] = EPSILON;
}
}
Point2D _minimum;
Point2D _maximum;
};
typedef Box2D BoxD;
typedef Box2I BoxI;
std::ostream& operator<<(std::ostream& os, Box2I const& box);
std::ostream& operator<<(std::ostream& os, Box2D const& box);
}
}
}
#endif
|
JavaScript
|
UTF-8
| 1,309 | 3.125 | 3 |
[] |
no_license
|
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('index', { title: 'Enter some shit' });
});
router.post('/', function(req, res, next){
var shuffle = arrShuffle(req.body.shuffleArr.split(','));
var chunks = arrChunk(shuffle, req.body.chunks);
console.log(chunks);
var output = '';
for (var i = 0; i < chunks.length; i++) {
output += 'Chunk #'+ (i+1) + ': ' + chunks[i] + ' \n';
}
res.render('index', {title: 'Shuffled and Chunked!', shuffleChunk: output});
});
function arrShuffle(shuffleArr){
var length = shuffleArr.length;
var newShuffleArr = [];
for (var i = length; i > 0; i--) {
var rand = Math.floor(Math.random() * i);
var transfer = shuffleArr.splice(rand,1);
newShuffleArr.push(transfer[0]);
}
return newShuffleArr;
}
function arrChunk(arr, chunks){
var chunkArr = arr.slice(0);
var newChunkArr = [];
var size = Math.floor(chunkArr.length / chunks);
var leftOvers = chunkArr.length % chunks;
for (var i = 0; i < chunks; i++) {
newChunkArr.push(chunkArr.splice(0,size));
}
for (var i = 0; i < leftOvers; i++) {
if(newChunkArr[i].length === size){
newChunkArr[i].push(chunkArr.splice(0,1)[0]);
}
}
return newChunkArr;
}
module.exports = router;
|
C#
|
UTF-8
| 810 | 3.515625 | 4 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MergableStack
{
class Program
{
static void Main(string[] args)
{
Stack s = new Stack();
s.Push(3);
s.Push(4);
s.Push(5);
Console.WriteLine("Pop from S (Expected 5): " + s.Pop().Value);
Stack s1 = new Stack();
s1.Push(7);
s1.Push(8);
s1.Push(9);
s1.Push(10);
Console.WriteLine("Pop from S1 (Expected 10): " + s1.Pop().Value);
Stack s2 = s1.MergeStacks(s, s1);
Console.WriteLine("Merging Stacks (Expected 3 4 9 8 7) : ");
s2.Display();
Console.ReadKey();
}
}
}
|
TypeScript
|
UTF-8
| 2,292 | 2.5625 | 3 |
[] |
no_license
|
import { mount, MountingOptions } from "@vue/test-utils";
import ContentList from "@/components/Parts/CategoryContent/ContentList.vue";
import ChildComponent from "@/components/Base/Input/BaseInputRadio.vue";
import crafterJSON from "@/assets/FFXIV.json";
const testData: Crafter = crafterJSON.crafter[0];
interface Crafter {
type: string;
name: string;
order: number;
image: string;
}
interface Props {
content: Crafter;
value: string;
}
const ContentListFactory = (propsData: object) => {
return mount(ContentList, {
propsData: {
content: {},
selectRadioValue: "",
...propsData,
},
} as MountingOptions<{}>);
};
const props: Props = {
content: testData,
value: "TEST",
};
describe("ContentList", () => {
test("propsを受け取れいているか", (): void => {
const wrapper = ContentListFactory(props);
expect(wrapper.props().content).toStrictEqual(testData);
});
it("子からのemitイベントで親へemitを発火するか", () => {
const wrapper = ContentListFactory(props);
wrapper.findComponent(ChildComponent).vm.$emit("change-radio");
expect(wrapper.emitted().change).not.toBeUndefined();
});
});
import CategoryContent from "@/components/Parts/CategoryContent/CategoryContent.vue";
const categoryContentFactory = (propsData: object) => {
return mount(CategoryContent, {
propsData: {
categories: [],
...propsData,
},
} as MountingOptions<{}>);
};
interface CategoryContentProps {
categories: Crafter[];
}
const categoryContentProps: CategoryContentProps = {
categories: crafterJSON.crafter,
};
describe("CategoryContent", () => {
test("Componentを配列分描画できているか", (): void => {
const wrapper = categoryContentFactory(categoryContentProps);
const findconpoments = wrapper.findAllComponents(ContentList);
expect(findconpoments.length).toBe(crafterJSON.crafter.length);
});
test("小からのEmitで、stateが更新されているか", (): void => {
const wrapper = categoryContentFactory(categoryContentProps);
expect(wrapper.vm.selectRadioValue).toBe("Expansion2");
wrapper.findComponent(ContentList).vm.$emit("change", { name: "TEST" });
expect(wrapper.vm.selectRadioValue).not.toBe("Expansion2");
});
});
|
C#
|
UTF-8
| 6,025 | 2.578125 | 3 |
[] |
no_license
|
// ------------------------------------------------------------
// © 2010 Masaaki Kishi
// ------------------------------------------------------------
namespace AbookTest
{
using Abook;
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using EX = Abook.AbException.EX;
using TYPE = Abook.AbConstants.TYPE;
/// <summary>
/// 秘密収支情報管理テスト
/// </summary>
public class AbTestPrivateManager
{
/// <summary>引数:支出情報リスト</summary>
private List<AbExpense> argExpenses;
/// <summary>対象:秘密収支情報管理</summary>
private AbPrivateManager abPrivateManager;
/// <summary>
/// SetUp
/// </summary>
[SetUp]
public void SetUp()
{
argExpenses = GenerateExpenses();
abPrivateManager = new AbPrivateManager(argExpenses);
}
/// <summary>
/// 支出情報リスト生成
/// </summary>
/// <returns>支出情報リスト</returns>
private List<AbExpense> GenerateExpenses()
{
var expenses = new List<AbExpense>();
expenses.Add(new AbExpense("2011-01-01", "name1", TYPE.PRVI, "10000"));
expenses.Add(new AbExpense("2011-02-28", "name0", TYPE.FOOD, "11000"));
expenses.Add(new AbExpense("2011-03-15", "name2", TYPE.PRVO, "10000"));
expenses.Add(new AbExpense("2011-04-20", "name0", TYPE.FOOD, "22000"));
expenses.Add(new AbExpense("2011-05-08", "name3", TYPE.PRVI, "15000"));
expenses.Add(new AbExpense("2011-07-31", "name0", TYPE.FOOD, "33000"));
expenses.Add(new AbExpense("2011-09-28", "name4", TYPE.PRVI, "30000"));
expenses.Add(new AbExpense("2011-10-11", "name0", TYPE.FOOD, "44000"));
expenses.Add(new AbExpense("2011-11-03", "name5", TYPE.PRVO, "25000"));
expenses.Add(new AbExpense("2011-12-12", "name0", TYPE.FOOD, "55000"));
expenses.Add(new AbExpense("2011-12-30", "name6", TYPE.PRVI, "20000"));
return expenses;
}
/// <summary>
/// コンストラクタ
/// 要素数のテスト
/// </summary>
[Test]
public void AbPrivateManagerWithPrivatesCount()
{
Assert.AreEqual(6, abPrivateManager.Privates().Count());
}
/// <summary>
/// コンストラクタ
/// 1行目のテスト
/// </summary>
[Test]
public void AbPrivateManagerWith1st()
{
var prv = abPrivateManager.Privates().ElementAt(0);
Assert.AreEqual("2011-01", prv.Date);
Assert.AreEqual("name1" , prv.Name);
Assert.AreEqual( 10000, prv.Cost);
Assert.AreEqual( 10000, prv.Blnc);
}
/// <summary>
/// コンストラクタ
/// 2行目のテスト
/// </summary>
[Test]
public void AbPrivateManagerWith2nd()
{
var prv = abPrivateManager.Privates().ElementAt(1);
Assert.AreEqual("2011-03", prv.Date);
Assert.AreEqual("name2" , prv.Name);
Assert.AreEqual( -10000, prv.Cost);
Assert.AreEqual( 0, prv.Blnc);
}
/// <summary>
/// コンストラクタ
/// 3行目のテスト
/// </summary>
[Test]
public void AbPrivateManagerWith3rd()
{
var prv = abPrivateManager.Privates().ElementAt(2);
Assert.AreEqual("2011-05", prv.Date);
Assert.AreEqual("name3" , prv.Name);
Assert.AreEqual( 15000, prv.Cost);
Assert.AreEqual( 15000, prv.Blnc);
}
/// <summary>
/// コンストラクタ
/// 4行目のテスト
/// </summary>
[Test]
public void AbPrivateManagerWith4th()
{
var prv = abPrivateManager.Privates().ElementAt(3);
Assert.AreEqual("2011-09", prv.Date);
Assert.AreEqual("name4" , prv.Name);
Assert.AreEqual( 30000, prv.Cost);
Assert.AreEqual( 45000, prv.Blnc);
}
/// <summary>
/// コンストラクタ
/// 5行目のテスト
/// </summary>
[Test]
public void AbPrivateManagerWith5th()
{
var prv = abPrivateManager.Privates().ElementAt(4);
Assert.AreEqual("2011-11", prv.Date);
Assert.AreEqual("name5" , prv.Name);
Assert.AreEqual( -25000, prv.Cost);
Assert.AreEqual( 20000, prv.Blnc);
}
/// <summary>
/// コンストラクタ
/// 6行目のテスト
/// </summary>
[Test]
public void AbPrivateManagerWith6th()
{
var prv = abPrivateManager.Privates().ElementAt(5);
Assert.AreEqual("2011-12", prv.Date);
Assert.AreEqual("name6" , prv.Name);
Assert.AreEqual( 20000, prv.Cost);
Assert.AreEqual( 40000, prv.Blnc);
}
/// <summary>
/// コンストラクタ
/// 引数:支出情報リストがNULL
/// </summary>
[Test]
public void AbPrivateManagerWithNullExpenses()
{
argExpenses = null;
var ex = Assert.Throws<AbException>(() =>
new AbPrivateManager(argExpenses)
);
Assert.AreEqual(EX.EXPENSES_NULL, ex.Message);
}
/// <summary>
/// コンストラクタ
/// 引数:支出情報リストが空
/// </summary>
[Test]
public void AbPrivateManagerWithEmptyExpenses()
{
argExpenses = new List<AbExpense>();
abPrivateManager = new AbPrivateManager(argExpenses);
Assert.AreEqual(0, abPrivateManager.Privates().Count());
}
}
}
|
Java
|
UTF-8
| 865 | 2.421875 | 2 |
[] |
no_license
|
package com.murray.financial.adapter.converter;
import com.murray.financial.domain.entity.BankAccount;
import com.murray.financial.dtos.BankAccountDTO;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
/**
* Converts a {@link BankAccount} to a {@link BankAccountDTO}
*/
@Component
public class BankAccountDomainToDTO implements Converter<BankAccount, BankAccountDTO> {
@Override
public BankAccountDTO convert(BankAccount bankAccount) {
BankAccountDTO dto = new BankAccountDTO();
dto.setBalance(bankAccount.getBalance());
dto.setIbanNumber(bankAccount.getIbanNumber());
dto.setCurrency(bankAccount.getCurrency().name());
dto.setOpenedOn(bankAccount.getOpenedOn());
dto.setStatus(bankAccount.getStatus().name());
return dto;
}
}
|
Java
|
UTF-8
| 8,674 | 1.710938 | 2 |
[] |
no_license
|
package com.mobdeve.s11.manuel.tang.strayhaven.home;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
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 com.mobdeve.s11.manuel.tang.strayhaven.misc.Collections;
import com.mobdeve.s11.manuel.tang.strayhaven.post.PostActivity;
import com.mobdeve.s11.manuel.tang.strayhaven.profile.ProfileActivity;
import com.mobdeve.s11.manuel.tang.strayhaven.R;
import com.mobdeve.s11.manuel.tang.strayhaven.settings.SettingsActivity;
import com.mobdeve.s11.manuel.tang.strayhaven.feed.Feed;
import com.mobdeve.s11.manuel.tang.strayhaven.feed.FeedAdapter;
import com.mobdeve.s11.manuel.tang.strayhaven.message.MessagesActivity;
import com.mobdeve.s11.manuel.tang.strayhaven.notification.NotificationActivity;
import com.mobdeve.s11.manuel.tang.strayhaven.tracker.TrackerActivity;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class HomeRequestActivity extends AppCompatActivity {
private ImageView ivProfile;
private TextView tvUpdates;
private FloatingActionButton fabPost;
private ImageButton ibSettings,ibTracker, ibNotifications, ibMessages;
private RecyclerView rvFeed;
private ArrayList<Feed> dataFeed;
private FirebaseDatabase database;
private FirebaseAuth mAuth;
private FirebaseUser user;
private String userId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_request);
this.initComponents();
this.initProfilePic();
this.initRequest();
if (!"activity_main".equals(getIntent().getStringExtra("from"))) {
overridePendingTransition(0, 0);
getIntent().addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
}
}
private void initProfilePic(){
this.database = FirebaseDatabase.getInstance();
this.mAuth = FirebaseAuth.getInstance();
this.user = this.mAuth.getCurrentUser();
this.userId = this.user.getUid();
DatabaseReference reference = database.getReference(Collections.users.name());
reference.child(this.userId).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
String imageUrl = snapshot.child("profilepicUrl").getValue().toString();
if (imageUrl.equals(" ")){
ivProfile.setImageResource(R.drawable.icon_default_user);
} else {
Picasso.get().load(imageUrl).into(ivProfile);
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
private void initRequest(){
this.database = FirebaseDatabase.getInstance();
this.dataFeed = new ArrayList<Feed>();
DatabaseReference userReference = database.getReference(Collections.users.name());
database.getReference().child(Collections.request.name()).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for(DataSnapshot dss:snapshot.getChildren()){
String type = dss.child("type").getValue(String.class);
String posterkey = dss.child("posterKey").getValue(String.class);
String caption = dss.child("caption").getValue(String.class);
String location = dss.child("location").getValue(String.class);
String date = dss.child("date").getValue(String.class);
String imageUrl = dss.child("postUrl").getValue(String.class);
String postername = dss.child("username").getValue(String.class);
//String profileUrl = dss.child("profileUrl").getValue(String.class);
String postKey = dss.getKey();
userReference.child(posterkey).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
String profileUrl = snapshot.child("profilepicUrl").getValue().toString();
Feed request = new Feed(posterkey, postername, profileUrl, imageUrl, type, location, caption, date);
request.setPostKey(postKey);
dataFeed.add(request);
rvFeed = findViewById(R.id.rv_home_req_feed);
rvFeed.setLayoutManager(new LinearLayoutManager(HomeRequestActivity.this, LinearLayoutManager.VERTICAL, true));
rvFeed.setAdapter(new FeedAdapter(dataFeed));
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
@Override
protected void onPause() {
super.onPause();
overridePendingTransition(0, 0);
}
//Initialize objects
private void initComponents(){
this.ivProfile = findViewById(R.id.iv_home_req_user_pic);
this.tvUpdates = findViewById(R.id.tv_home_req_update_tab);
this.ibSettings = findViewById(R.id.ib_home_req_settings);
this.fabPost = findViewById(R.id.fab_home_req_create_post);
this.ibTracker = findViewById(R.id.ib_home_req_tracker);
this.ibNotifications = findViewById(R.id.ib_home_req_notifications);
this.ibMessages = findViewById(R.id.ib_home_req_messages);
ivProfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(HomeRequestActivity.this, ProfileActivity.class);
startActivity(intent);
}
});
tvUpdates.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(HomeRequestActivity.this, HomeUpdateActivity.class);
startActivity(intent);
}
});
ibSettings.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(HomeRequestActivity.this, SettingsActivity.class);
startActivity(intent);
}
});
fabPost.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(HomeRequestActivity.this, PostActivity.class);
startActivity(intent);
}
});
ibTracker.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(HomeRequestActivity.this, TrackerActivity.class);
startActivity(intent);
}
});
ibNotifications.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(HomeRequestActivity.this, NotificationActivity.class);
startActivity(intent);
}
});
ibMessages.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(HomeRequestActivity.this, MessagesActivity.class);
startActivity(intent);
}
});
}
}
|
Java
|
UTF-8
| 1,740 | 2.359375 | 2 |
[] |
no_license
|
package com.example.thadaninilesh.approvalchain;
/**
* Created by thadaninilesh on 17-02-2016.
*/
public class ManagerForApprovalList {
private String employeeName, employeeEmail, taskName, taskDescription, taskAmount;
private boolean approvalSelect = false;
public ManagerForApprovalList(String employeeEmail, String employeeName, String taskAmount, String taskDescription, String taskName) {
this.employeeEmail = employeeEmail;
this.employeeName = employeeName;
this.taskAmount = taskAmount;
this.taskDescription = taskDescription;
this.taskName = taskName;
this.approvalSelect = approvalSelect;
}
public boolean isApprovalSelect() {
return approvalSelect;
}
public void setApprovalSelect(boolean approvalSelect) {
this.approvalSelect = approvalSelect;
}
public String getEmployeeEmail() {
return employeeEmail;
}
public void setEmployeeEmail(String employeeEmail) {
this.employeeEmail = employeeEmail;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public String getTaskAmount() {
return taskAmount;
}
public void setTaskAmount(String taskAmount) {
this.taskAmount = taskAmount;
}
public String getTaskDescription() {
return taskDescription;
}
public void setTaskDescription(String taskDescription) {
this.taskDescription = taskDescription;
}
public String getTaskName() {
return taskName;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
}
|
Python
|
UTF-8
| 441 | 4.21875 | 4 |
[] |
no_license
|
# Given mixed array of numbers, strings, booleans and nulls.
# Filter array and get all the numbers in a separate array.
# Arrange them such as from the beginning are the odds and from the ending the evens.
arr = [8, 0, 1, 'hey', 12, 5 , True, '2', None, 7, 3]
ar = []
ar1 = []
for i in arr:
if type(i) == int or type(i) == float:
if i % 2 == 1:
ar.append(i)
else:
ar1.append(i)
print(ar + ar1)
|
Markdown
|
UTF-8
| 1,261 | 2.515625 | 3 |
[
"0BSD"
] |
permissive
|
---
category: 'blog'
title: "[GatsbyJS] Making Blog Website with Gatsby for Beginners"
date: "2020-03-11"
---
## CSS
- viewport meta tag 는 이미 개츠비가 설정해두었기에 따로 import 필요 없음
- css 에 calc() 이용해서 바로 적용
## 마크다운 이미지
- [gatsby-source-filesystem](https://www.gatsbyjs.com/plugins/gatsby-source-filesystem/?=gatsby-source-filesystem)
-
## GraphQL
- 포스팅 리스트 순서 : 날짜, 제목 순서
- https://www.gatsbyjs.com/docs/graphql-reference/
## 플러그인
- 마크다운의 코드 블럭 꾸미기
- https://www.gatsbyjs.com/plugins/gatsby-remark-prismjs/
- css 충돌은 styles/global.css 로 직접 수정
- 참고 이슈: https://github.com/PrismJS/prism/issues/1237
```css
pre{
width: 100%;
background: beige;
border-radius: 1px;
}
pre code {
white-space: break-spaces !important;
}
````
fonts
- https://www.gatsbyjs.com/plugins/gatsby-plugin-web-font-loader/?=google-fonts
- https://github.com/KyleAMathews/typefaces
- different font-family for different languages
- https://www.gatsbyjs.com/docs/how-to/styling/using-local-fonts/
## 리스트에 썸네일 이미지 넣는 방법
- https://www.gatsbyjs.com/docs/working-with-images-in-markdown/
|
Java
|
UTF-8
| 4,989 | 2.890625 | 3 |
[] |
no_license
|
package com.II.readFiles;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Out_Bib_Generation
{
public static void main(String[] args)
{
int startYear=0;
int endYear=0;
try
{
FileWriter writer = new FileWriter("BibGenereation.bib");
// JDBC driver name and database URL
// Database credentials
Connection conn = null;
java.sql.Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("oracle.jdbc.driver.OracleDriver");
//STEP 3: Open a connection
conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","II_project","II_project");
//STEP 4: Execute a query
stmt = conn.createStatement();
//user query where he/she can specify constrains with values for startYear and endYear
String sql = "";
if(startYear==0 && endYear==0){
sql = "SELECT * from MERGER";
}else if(startYear!=0 && endYear!=0){
sql = "SELECT * from MERGER where YEAR>="+startYear+"and YEAR <="+endYear;
}else if(startYear!=0 && endYear==0){
sql = "SELECT * from MERGER where YEAR>="+startYear;
}else if(startYear==0 && endYear!=0){
sql = "SELECT * from MERGER where YEAR<="+endYear;
}
ResultSet rs = stmt.executeQuery(sql);
int count=0;
//STEP 5: Extract data from result set
while(rs.next()){
++count;
//Retrieve by column name
String Article_id = rs.getString("ARTICLE_ID");
String Author = rs.getString("AUTHOR");
String Title = rs.getString("TITLE");
String Publisher = rs.getString("PUBLISHER");
String Year = rs.getString("YEAR");
String Volume = rs.getString("VOLUME");
String Pages = rs.getString("PAGES");
String isbn = rs.getString("ISBN");
String Biburl = rs.getString("BIBURL");
//Display values in BibTex format
if (Article_id!=null)
{
writer.write("@article{" + Article_id + ",");
if (Author!=null)
{
writer.write("\n AUTHOR\t= {" + Author + "},");
}
if (Title!=null)
{
writer.write("\n TITLE\t= {" + Title + "},");
}
if (Publisher!=null)
{
writer.write("\n PUBLISHER\t= {" + Publisher + "},");
}
if (Year!=null)
{
writer.write("\n YEAR\t= {" + Year + "},");
}
if (Volume!=null)
{
writer.write("\n VOLUME\t= {" + Volume + "},");
}
if (Pages!=null)
{
writer.write("\n PAGES\t= {" + Pages + "},");
}
if (isbn!=null)
{
writer.write("\n ISBN\t= {" + isbn + "},");
}
if (Biburl!=null)
{
writer.write("\n BIBURL\t= {" + Biburl + "},");
}
}
writer.write("\n");
if (Article_id!=null)
{
writer.write("}");
}
writer.write("\n");
writer.write("\n");
}
System.out.println(count);
//Displays number of rows
rs.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
C++
|
UTF-8
| 531 | 3.71875 | 4 |
[] |
no_license
|
#include <iostream>
// Given a string, compute recursively a new string where all the
// adjacent chars are now separated by a '*'.
std::string insertRecursively(std::string x, unsigned int length)
{
if (length == 0) {
return x;
} else {
x.insert(length - 1, 1, '*');
return insertRecursively(x, length - 1);
}
}
int main() {
std::string stringx = "xer xor or xer and xl osssx";
unsigned int size = stringx.length();
std::cout << insertRecursively(stringx, size);
return 0;
}
|
C++
|
UTF-8
| 693 | 2.65625 | 3 |
[] |
no_license
|
#include <iostream>
#include <cassert>
#include "utility/type/ll.hpp"
#include "utility/range.hpp"
using namespace std;
ll reverse(ll x) {
ll y = 0;
while (x) {
y *= 10;
y += x % 10;
x /= 10;
}
return y;
}
int main() {
ios_base::sync_with_stdio(false);
constexpr ll l = 1000001;
ll dp[l] = {};
dp[0] = 0;
for (int i : range(1,l)) {
dp[i] = dp[i-1]+1;
if (reverse(i) < i and reverse(reverse(i)) == i) dp[i] = min(dp[i], dp[reverse(i)]+1);
}
for (int testcase : range(cin)) {
ll n; cin >> n;
assert (n < l);
cout << "Case #" << testcase+1 << ": " << dp[n] << endl;
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.