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
|
|---|---|---|---|---|---|---|---|
Python
|
UTF-8
| 625
| 3.671875
| 4
|
[] |
no_license
|
# This is a comment
# this is some high level code
2 + 2 == 4
4 - 1 == 3
print("quick maths")
def func1():
""" docstring and some code later """
print("Hello, World!")
def func2():
" docstring and some code later "
print("Hello, World!2")
def func3(k):
" docstring and some code later "
print("Hello, World!2")
def func4():
" docstring and some code later "
print("Hello, World!2")
def func5(k):
" docstring and some code later "
print("Hello, World!2")
func4()
def func6():
" docstring and some code later "
k = func1()
func2()
k = (func3(k))
func5()
|
Java
|
UTF-8
| 8,038
| 1.820313
| 2
|
[] |
no_license
|
package com.appvirality.appviralityui.custom;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.text.Html;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import com.appvirality.AppVirality;
import com.appvirality.CampaignDetail;
import com.appvirality.appviralityui.R;
import com.appvirality.appviralityui.Utils;
import com.appvirality.appviralityui.activities.GrowthHackActivity;
import java.util.ArrayList;
/**
* Created by AppVirality on 3/21/2016.
*/
public class CustomPopUp {
Activity activity;
private PopupWindow miniNotification;
private Dialog popUp;
Utils utils;
AppVirality appVirality;
public CustomPopUp(Activity activity) {
this.activity = activity;
utils = new Utils(activity);
appVirality = AppVirality.getInstance(activity);
}
public void showPopUp(ArrayList<CampaignDetail> campaignDetails, final CampaignDetail womCampaignDetail){
showLaunchPopUp(campaignDetails, womCampaignDetail, false);
}
public void showMiniNotification(ArrayList<CampaignDetail> campaignDetails, final CampaignDetail womCampaignDetail){
showLaunchPopUp(campaignDetails, womCampaignDetail, true);
}
private void showLaunchPopUp(final ArrayList<CampaignDetail> campaignDetails, final CampaignDetail womCampaignDetail, boolean isMiniNotification) {
try {
if ((popUp != null && popUp.isShowing()) || (miniNotification != null && miniNotification.isShowing()))
return;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View launchBarLayout;
if (isMiniNotification)
launchBarLayout = inflater.inflate(R.layout.lauch_mini_notification, null);
else
launchBarLayout = inflater.inflate(R.layout.launch_popup, null);
Button btnLaunchPopup = (Button) launchBarLayout.findViewById(R.id.appvirality_btnlaunchbar);
Button btnRemindLater = (Button) launchBarLayout.findViewById(R.id.appvirality_btnremindlater);
ImageView launchIcon = (ImageView) launchBarLayout.findViewById(R.id.appvirality_launchimage);
launchIcon.setImageResource(getLaunchIcon(womCampaignDetail.launchIconId));
TextView txtLaunchMessage = (TextView) launchBarLayout.findViewById(R.id.appvirality_txtlaunchmessage);
txtLaunchMessage.setText(Html.fromHtml(TextUtils.isEmpty(womCampaignDetail.launchMessage) ? womCampaignDetail.campaignTitle : womCampaignDetail.launchMessage));
if (womCampaignDetail.launchMsgColor != null)
txtLaunchMessage.setTextColor(Color.parseColor(womCampaignDetail.launchMsgColor));
if (!TextUtils.isEmpty(womCampaignDetail.remindBtnTxt))
btnRemindLater.setText(womCampaignDetail.remindBtnTxt);
if (!TextUtils.isEmpty(womCampaignDetail.launchBtnTxt))
btnLaunchPopup.setText(womCampaignDetail.launchBtnTxt);
GradientDrawable shape = new GradientDrawable();
shape.setCornerRadii(new float[]{1, 1, 0, 0, 1, 1, 0, 0});
shape.setStroke(1, Color.parseColor("#FFFFFF"));
shape.setBounds(0, 1, 1, 0);
if (womCampaignDetail.launchBtnTxtColor != null) {
btnLaunchPopup.setTextColor(Color.parseColor(womCampaignDetail.launchBtnTxtColor));
btnRemindLater.setTextColor(Color.parseColor(womCampaignDetail.launchBtnTxtColor));
}
if (womCampaignDetail.launchBtnBgColor != null) {
shape.setColor(Color.parseColor(womCampaignDetail.launchBtnBgColor));
if (android.os.Build.VERSION.SDK_INT >= 16) {
btnLaunchPopup.setBackground(shape);
btnRemindLater.setBackground(shape);
} else {
btnLaunchPopup.setBackgroundDrawable(shape);
btnRemindLater.setBackgroundDrawable(shape);
}
}
launchBarLayout.setBackgroundColor(Color.parseColor(womCampaignDetail.launchBgColor));
if (isMiniNotification) {
DisplayMetrics metrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
int popupWidth = metrics.widthPixels;
int popupHeight = utils.isScreenPortrait() ? (int) (metrics.heightPixels * 0.2) : (int) (metrics.widthPixels * 0.2);
if (miniNotification == null ? true : !miniNotification.isShowing()) {
miniNotification = new PopupWindow(launchBarLayout, popupWidth, popupHeight, false);
miniNotification.setAnimationStyle(R.style.appvirality_slide_activity);
miniNotification.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
miniNotification.showAtLocation(launchBarLayout, Gravity.BOTTOM, 0, 0);
appVirality.popUpShown(womCampaignDetail.campaignId);
}
} else {
if (popUp == null ? true : !popUp.isShowing()) {
popUp = new Dialog(activity);
popUp.requestWindowFeature(Window.FEATURE_NO_TITLE);
popUp.setCancelable(false);
popUp.setContentView(launchBarLayout);
popUp.show();
appVirality.popUpShown(womCampaignDetail.campaignId);
}
}
btnLaunchPopup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
Intent growthHackIntent = new Intent(activity, GrowthHackActivity.class);
growthHackIntent.putExtra("campaign_details", campaignDetails);
growthHackIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(growthHackIntent);
appVirality.recordImpressionsClicks(womCampaignDetail.campaignId, false, true);
dismissLaunchBar();
} catch (Exception e) {
}
}
});
btnRemindLater.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
appVirality.saveRemindLater(womCampaignDetail);
dismissLaunchBar();
} catch (Exception e) {
}
}
});
appVirality.recordImpressionsClicks(womCampaignDetail.campaignId, true, false);
} catch (Exception e) {
e.printStackTrace();
}
}
private void dismissLaunchBar() {
try {
if (miniNotification != null && miniNotification.isShowing())
miniNotification.dismiss();
if (popUp != null && popUp.isShowing())
popUp.dismiss();
} catch (Exception e) {
}
}
private int getLaunchIcon(int launchId) {
switch (launchId) {
case 1:
return R.drawable.megaphone;
case 2:
return R.drawable.alert;
case 3:
return R.drawable.bell;
case 4:
return R.drawable.flag;
case 5:
return R.drawable.trophy;
default:
return R.drawable.megaphone;
}
}
}
|
Java
|
UTF-8
| 551
| 1.976563
| 2
|
[] |
no_license
|
package com.kgignatyev.workflow.fileprocessing;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.TestWatcher;
import static com.kgignatyev.workflow.fileprocessing.WFContext.testEnv;
public class WFTestWatcher implements TestWatcher {
public void testFailed(ExtensionContext context, Throwable cause) {
System.out.println("WFTestWatcher.testFailed");
if (testEnv != null) {
System.err.println(testEnv.getDiagnostics());
testEnv.close();
}
}
}
|
Python
|
UTF-8
| 3,159
| 2.640625
| 3
|
[] |
no_license
|
import numpy as np
import pandas as pd
from keras.layers import Embedding, Dropout, Dense, Input, Flatten, Concatenate, Dot, Add
from keras.models import load_model, Model
from keras.optimizers import Adam, Adamax
from keras.callbacks import Callback, EarlyStopping, ModelCheckpoint
from keras.preprocessing.sequence import pad_sequences
from keras.layers.normalization import BatchNormalization
from keras import backend as K
epochs = 1000
batch_size = 4096
embedding_dim = 200
RNG_SEED = 1446557
def rmse(y_true,y_pred):
return K.sqrt(K.mean((y_pred - y_true)**2))
#read users info
train_user = open('users.csv', 'r')
next(train_user, None)
age_dict = {}
occ_dict = {}
for line in train_user.readlines():
line_spilt = line.split("::")
age_dict[line_spilt[0]] = line_spilt[2]
occ_dict[line_spilt[0]] = line_spilt[3]
#read train
train = pd.read_csv('train.csv')
max_userid = train['UserID'].drop_duplicates().max()+1
max_movieid = train['MovieID'].drop_duplicates().max()+1
shuffled_ratings = train.sample(frac=1.0, random_state=RNG_SEED)
user = shuffled_ratings['UserID'].values
movie = shuffled_ratings['MovieID'].values
rating = shuffled_ratings['Rating'].values
#add feature (age and occ)
age = []
occ = []
for i in range(len(user)):
age.append([int(age_dict[str(user[i])])])
occ.append([int(occ_dict[str(user[i])])])
age = pad_sequences(age)
occ = pad_sequences(occ)
max_age = age.max()+1
max_occ = occ.max()+1
'''
#normalization
mean = np.mean(rating)
std = np.std(rating)
rating = (rating-mean)/std
print(mean)
print(std)
'''
#model
user_input = Input(shape=[1])
user_vec = Embedding(max_userid, embedding_dim, embeddings_initializer='random_normal')(user_input)
user_vec = Flatten()(user_vec)
movie_input = Input(shape=[1])
movie_vec = Embedding(max_movieid, embedding_dim, embeddings_initializer='random_normal')(movie_input)
movie_vec = Flatten()(movie_vec)
age_input = Input(shape=[1])
age_vec = Embedding(max_age, embedding_dim, embeddings_initializer='random_normal')(age_input)
age_vec = Flatten()(age_vec)
occ_input = Input(shape=[1])
occ_vec = Embedding(max_occ, embedding_dim, embeddings_initializer='random_normal')(occ_input)
occ_vec = Flatten()(occ_vec)
concat_vec = Concatenate()([user_vec, movie_vec, age_vec, occ_vec])
dnn = Dense(256, activation='relu')(concat_vec)
dnn = Dropout(0.5)(dnn)
dnn = Dense(128, activation='relu')(dnn)
dnn = Dropout(0.5)(dnn)
dnn = Dense(64, activation='relu')(dnn)
dnn = Dropout(0.5)(dnn)
result = Dense(1, activation='linear')(dnn)
model = Model(inputs=[user_input, movie_input, age_input, occ_input], outputs=result)
model.summary()
model.compile(loss='mse', optimizer='adam', metrics=[rmse])
callbacks = [EarlyStopping(monitor='val_rmse',
patience=10,
verbose=1,
mode='min'),
ModelCheckpoint(filepath='DNN.h5',
verbose=1,
save_best_only=True,
monitor='val_rmse',
mode='min')]
model.fit([user, movie, age, occ], rating,
epochs=epochs,
batch_size=batch_size,
validation_split=0.1,
callbacks=callbacks)
|
Ruby
|
UTF-8
| 649
| 2.578125
| 3
|
[] |
no_license
|
class ApiKey < ActiveRecord::Base
attr_accessible :key, :user_id, :active, :application_url
belongs_to :user
before_create :generate_api_key
before_save :prevent_reactivating
validates_presence_of :application_url
def prevent_reactivating
return false if (self.active_was == false && self.active == true)
end
def generate_api_key
begin
key = new_key
end while !ApiKey.where(key: key).count == 0
self.key = new_key
end
def whitelisted_sites
self.application_url.split(",").map(&:strip)
end
private
def new_key
Array.new(14){[*'0'..'9', *'a'..'z', *'A'..'Z'].sample}.join
end
end
|
SQL
|
UTF-8
| 1,394
| 3.640625
| 4
|
[
"BSD-3-Clause"
] |
permissive
|
-- we don't know how to generate schema sandbox (class Schema) :(
create table mail_types
(
id int auto_increment
primary key,
name varchar(32) not null,
code varchar(128) not null,
sender json not null,
subject varchar(64) null,
attachments json null,
bcc_recipients json null,
charset varchar(16) default 'utf-8' not null,
priority smallint(2) default '0' not null,
constraint mail_types_code_uindex
unique (code)
)
;
create table mails
(
id int auto_increment
primary key,
mail_type_id int not null,
recipient json not null,
sender json not null,
subject varchar(64) null,
attachments json null,
bcc_recipients json null,
charset varchar(16) default 'utf-8' not null,
date_created datetime default CURRENT_TIMESTAMP not null,
data json null,
hashcode varchar(32) not null,
date_sent datetime null,
constraint fk_mails_mail_types
foreign key (mail_type_id) references mail_types (id)
)
;
create table mail_queue
(
mail_id int not null
primary key,
priority smallint(2) default '0' not null,
attempts_count smallint(2) default '0' not null,
job_id char(36) null,
constraint mail_queue_mails_id_fk
foreign key (mail_id) references mails (id)
on update cascade on delete cascade
)
;
create index mail_queue_job_id_index
on mail_queue (job_id)
;
create index fk_mails_mail_types_idx
on mails (mail_type_id)
;
|
C++
|
UTF-8
| 1,189
| 2.859375
| 3
|
[] |
no_license
|
#include <iostream>
#include <algorithm>
#include <string.h>
#include <string>
using namespace std;
#define max_n 10000
#define max_m 100
struct Tuple {
int p, a;
} arr[max_n + 5][4]
int prime[max_m + 5] = {0};
void get_num(int a, int b, Tuple *temp) {
int len = 0;
while (a != 1) {
int p_num = 0, pre = prime[a];
while (a % pre == 0) p_num++, a /= pre;
temp[len].p = pre, temp[len].a = p_num * b;
len++;
}
return ;
}
int main() {
for (int i = 2; i <= max_n; i++) {
if (prime[i]) continue;
for (int j = i; j <= max_m; j += i) {
if (prime[j]) continue;
prime[j] = i;
}
}
int cnt = 0;
for (int a = 2; a <= max_m; a++) {
for (int n = 2; b <= max_m; b++) {
Tuple temp[4] = {0};
get_num(a, b, temp);
int flag = 1;
for (int i = 0; i < cnt && flag; i++) {
flag = memcmp(arr[i], temp, sizeof(temp));
}
if (!flag) continue;
memcpy(arr[cnt++], temp, sizeof(temp));
}
}
cout << cnt << endl;
return 0;
}
|
Markdown
|
UTF-8
| 1,113
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
# pythonStudy
Code studying python<br>
help(*\<function/class\>*) # to list doc_here<br>
dir(*\<function/class\>*) # to list members/attributes<br>
<br>
\>\>\> import this<br>
The Zen of Python, by Tim Peters<br>
<br>
Beautiful is better than ugly.<br>
Explicit is better than implicit.<br>
Simple is better than complex.<br>
Complex is better than complicated.<br>
Flat is better than nested.<br>
Sparse is better than dense.<br>
Readability counts.<br>
Special cases aren't special enough to break the rules.<br>
Although practicality beats purity.<br>
Errors should never pass silently.<br>
Unless explicitly silenced.<br>
In the face of ambiguity, refuse the temptation to guess.<br>
There should be one-- and preferably only one --obvious way to do it.<br>
Although that way may not be obvious at first unless you're Dutch.<br>
Now is better than never.<br>
Although never is often better than *right* now.<br>
If the implementation is hard to explain, it's a bad idea.<br>
If the implementation is easy to explain, it may be a good idea.<br>
Namespaces are one honking great idea -- let's do more of those!<br>
|
JavaScript
|
UTF-8
| 2,350
| 2.53125
| 3
|
[] |
no_license
|
import React, {Component} from 'react';
import { getLongLat, reverseGeocoding, switcher} from '../actions';
import { connect } from 'react-redux'
import AutoComplete from './googleMapWrapper/autoComplete'
class Header extends(Component){
constructor(props){
super();
this.switchToAutofill=this.switchToAutofill.bind(this);
}
componentWillMount(){
//when our application is about to mount we want to run this action to get current longitude and latidude
//from the user's device
this.props.getLongLat();
}
componentWillReceiveProps(nextProps){
//whenever our component wants to receive another property
//if we have a position(long and lang) and we haven't resolve the cityName and we don't have any errors
if(nextProps.allRestaurants.position && !nextProps.allRestaurants.cityName && nextProps.allRestaurants.error ==='') {
//then we want to resolve our Geocode / postion coordinate to a city name
nextProps.reverseGeocoding(nextProps.allRestaurants.position)
}
}
//if we want to manually switch to autofill
switchToAutofill(event){
event.preventDefault()
this.props.switcher()
}
render(){
const { allRestaurants } = this.props
return(
<div className="App-header">
{
allRestaurants.cityName ?
<div>
<h2>Find a Restaurant Near <br />
{allRestaurants.cityName[0].formatted_address}
</h2>
<a href="#" onClick={this.switchToAutofill}> Not Your Location ? use the city finder </a>
</div>
:
<div className="searchBar">
<h2>Sorry we could not locate you automatically, please use the form below</h2>
<form>
<AutoComplete />
</form>
</div>
}
</div>
)
}
}
//to connet to our this component's prop to our state
function mapStateToProps(state){
return{
allRestaurants:state.allRestaurants
}
}
//wrapping our connect with the component
export default connect(mapStateToProps, {getLongLat, reverseGeocoding, switcher})(Header)
|
C#
|
UTF-8
| 398
| 2.59375
| 3
|
[] |
no_license
|
using factory.PizzaStaff;
namespace factory.PizzaStoreStaff
{
public abstract class PizzaStore
{
public Pizza OrderPizza(string order)
{
var pizza = CreatePizza(order);
pizza.Bake();
pizza.Cut();
pizza.Box();
return pizza;
}
protected abstract Pizza CreatePizza(string order);
}
}
|
Java
|
UTF-8
| 329
| 2.078125
| 2
|
[
"MIT"
] |
permissive
|
package net.serenitybdd.screenplay.jenkins.targets;
import net.serenitybdd.screenplay.targets.Target;
public class Label {
public static Target called(String text) {
return Target.the(String.format("the '%s' label", text))
.locatedBy("//label[contains(.,'{0}')]")
.of(text);
}
}
|
Rust
|
UTF-8
| 34,572
| 2.921875
| 3
|
[
"Apache-2.0",
"BSD-3-Clause",
"bzip2-1.0.6",
"LicenseRef-scancode-other-permissive",
"NCSA",
"MIT",
"ISC",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"Unlicense"
] |
permissive
|
use chalk_integration::query::LoweringDatabase;
#[test]
fn well_formed_trait_decl() {
lowering_success! {
program {
trait Clone { }
trait Copy where Self: Clone { }
struct Foo { }
impl Clone for Foo { }
impl Copy for Foo { }
}
}
}
#[test]
fn ill_formed_trait_decl() {
lowering_error! {
program {
trait Clone { }
trait Copy where Self: Clone { }
struct Foo { }
impl Copy for Foo { }
} error_msg {
"trait impl for `Copy` does not meet well-formedness requirements"
}
}
}
#[test]
fn cyclic_traits() {
lowering_success! {
program {
trait A where Self: B { }
trait B where Self: A { }
impl<T> B for T { }
impl<T> A for T { }
}
}
lowering_error! {
program {
trait Copy { }
trait A where Self: B, Self: Copy {}
trait B where Self: A { }
// This impl won't be able to prove that `T: Copy` holds.
impl<T> B for T {}
impl<T> A for T where T: B {}
} error_msg {
"trait impl for `B` does not meet well-formedness requirements"
}
}
lowering_success! {
program {
trait Copy { }
trait A where Self: B, Self: Copy {}
trait B where Self: A { }
impl<T> B for T where T: Copy {}
impl<T> A for T where T: B {}
}
}
}
#[test]
fn cyclic_wf_requirements() {
lowering_success! {
program {
trait Foo where <Self as Foo>::Value: Foo {
type Value;
}
struct Unit { }
impl Foo for Unit {
type Value = Unit;
}
}
}
}
#[test]
fn ill_formed_assoc_ty() {
lowering_error! {
program {
trait Foo { }
struct OnlyFoo<T> where T: Foo { }
struct MyType { }
trait Bar {
type Value;
}
impl Bar for MyType {
// `OnlyFoo<MyType>` is ill-formed because `MyType: Foo` does not hold.
type Value = OnlyFoo<MyType>;
}
} error_msg {
"trait impl for `Bar` does not meet well-formedness requirements"
}
}
}
#[test]
fn implied_bounds() {
lowering_success! {
program {
trait Eq { }
trait Hash where Self: Eq { }
struct Set<K> where K: Hash { }
struct OnlyEq<T> where T: Eq { }
trait Foo {
type Value;
}
impl<K> Foo for Set<K> {
// Here, `WF(Set<K>)` implies `K: Hash` and hence `OnlyEq<K>` is WF.
type Value = OnlyEq<K>;
}
}
}
}
#[test]
fn ill_formed_ty_decl() {
lowering_error! {
program {
trait Hash { }
struct Set<K> where K: Hash { }
struct MyType<K> {
value: Set<K>
}
} error_msg {
"type declaration `MyType` does not meet well-formedness requirements"
}
}
}
#[test]
fn implied_bounds_on_ty_decl() {
lowering_success! {
program {
trait Eq { }
trait Hash where Self: Eq { }
struct OnlyEq<T> where T: Eq { }
struct MyType<K> where K: Hash {
value: OnlyEq<K>
}
}
}
}
#[test]
fn wf_requiremements_for_projection() {
lowering_error! {
program {
trait Foo {
type Value;
}
trait Iterator {
type Item;
}
impl<T> Foo for T {
// The projection is well-formed if `T: Iterator` holds, which cannot
// be proved here.
type Value = <T as Iterator>::Item;
}
} error_msg {
"trait impl for `Foo` does not meet well-formedness requirements"
}
}
lowering_success! {
program {
trait Foo {
type Value;
}
trait Iterator {
type Item;
}
impl<T> Foo for T where T: Iterator {
type Value = <T as Iterator>::Item;
}
}
}
}
#[test]
fn ill_formed_type_in_header() {
lowering_error! {
program {
trait Foo {
type Value;
}
trait Bar { }
// Types in where clauses are not assumed to be well-formed,
// an explicit where clause would be needed (see below).
impl<T> Bar for T where <T as Foo>::Value: Bar { }
} error_msg {
"trait impl for `Bar` does not meet well-formedness requirements"
}
}
lowering_success! {
program {
trait Foo {
type Value;
}
trait Bar { }
impl<T> Bar for T where T: Foo, <T as Foo>::Value: Bar { }
}
}
}
#[test]
fn bound_in_header_from_env() {
lowering_success! {
program {
trait Foo { }
trait Bar {
type Item: Foo;
}
struct Stuff<T> { }
impl<T> Bar for Stuff<T> where T: Foo {
// Should have FromEnv(T: Foo) here.
type Item = T;
}
}
}
lowering_error! {
program {
trait Foo { }
trait Baz { }
trait Bar {
type Item: Baz;
}
struct Stuff<T> { }
impl<T> Bar for Stuff<T> where T: Foo {
// No T: Baz here.
type Item = T;
}
} error_msg {
"trait impl for `Bar` does not meet well-formedness requirements"
}
}
}
#[test]
fn mixed_indices_check_projection_bounds() {
lowering_success! {
program {
trait Foo<T> { }
trait Bar<T> {
type Item: Foo<T>;
}
struct Stuff<T, U> { }
impl<T, U> Bar<T> for Stuff<T, U> where U: Foo<T> {
type Item = U;
}
}
}
lowering_error! {
program {
trait Foo<T> { }
trait Baz<T> { }
trait Bar<T> {
type Item: Baz<T>;
}
struct Stuff<T, U> { }
impl<T, U> Bar<T> for Stuff<T, U> where U: Foo<T> {
type Item = U;
}
} error_msg {
"trait impl for `Bar` does not meet well-formedness requirements"
}
}
}
#[test]
fn mixed_indices_check_generic_projection_bounds() {
lowering_success! {
program {
struct Stuff<T, U> { }
trait Foo<T> { }
// A type that impls Foo<T> as long as U: Foo<T>.
struct Fooey<U, V> { }
impl<T, U, V> Foo<T> for Fooey<U, V> where U: Foo<T> { }
trait Bar<T> {
type Item<V>: Foo<T> where V: Foo<T>;
}
impl<T, U> Bar<T> for Stuff<T, U> where U: Foo<T> {
type Item<V> = Fooey<U, V>;
}
}
}
lowering_error! {
program {
struct Stuff<T, U> { }
trait Foo<T> { }
trait Baz<T> { }
// A type that impls Foo<T> as long as U: Foo<T>.
struct Fooey<U, V> { }
impl<T, U, V> Foo<T> for Fooey<U, V> where U: Foo<T> { }
trait Bar<T> {
type Item<V>: Baz<T> where V: Foo<T>;
}
impl<T, U> Bar<T> for Stuff<T, U> where U: Foo<T> {
type Item<V> = Fooey<U, V>;
}
} error_msg {
"trait impl for `Bar` does not meet well-formedness requirements"
}
}
}
#[test]
fn generic_projection_where_clause() {
lowering_success! {
program {
trait PointerFamily { type Pointer<T>; }
struct Cow<T> { }
struct CowFamily { }
impl PointerFamily for CowFamily { type Pointer<T> = Cow<T>; }
struct String { }
struct Foo<P> where P: PointerFamily {
bar: <P as PointerFamily>::Pointer<String>
}
}
}
lowering_error! {
program {
trait Copy { }
trait PointerFamily { type Pointer<T> where T: Copy; }
struct Cow<T> { }
struct CowFamily { }
impl PointerFamily for CowFamily { type Pointer<T> = Cow<T>; }
struct String { }
struct Foo<P> where P: PointerFamily {
// No impl Copy for String, so this will fail.
bar: <P as PointerFamily>::Pointer<String>
}
} error_msg {
"type declaration `Foo` does not meet well-formedness requirements"
}
}
}
#[test]
fn generic_projection_bound() {
lowering_success! {
program {
trait Clone { }
trait PointerFamily { type Pointer<T>: Clone where T: Clone; }
struct Cow<T> { }
impl<T> Clone for Cow<T> where T: Clone { }
struct CowFamily { }
// impl is WF due because of:
// - `where T: Clone` clause on PointerFamily::Pointer<T>
// - impl<T> Clone for Cow<T> where T: Clone
impl PointerFamily for CowFamily { type Pointer<T> = Cow<T>; }
struct String { }
impl Clone for String { }
struct Foo<P> where P: PointerFamily {
bar: <P as PointerFamily>::Pointer<String>
}
}
}
lowering_error! {
program {
trait Clone { }
trait PointerFamily { type Pointer<T>: Clone where T: Clone; }
struct Cow<T> { }
struct CowFamily { }
// No impl Clone for Cow<T>, so this will fail.
impl PointerFamily for CowFamily { type Pointer<T> = Cow<T>; }
} error_msg {
"trait impl for `PointerFamily` does not meet well-formedness requirements"
}
}
}
#[test]
fn higher_ranked_trait_bounds() {
lowering_error! {
program {
trait Foo<'a> { }
trait Bar where forall<'a> Self: Foo<'a> { }
struct Baz { }
impl Bar for Baz { }
} error_msg {
"trait impl for `Bar` does not meet well-formedness requirements"
}
}
lowering_success! {
program {
trait Foo<'a> { }
trait Bar where forall<'a> Self: Foo<'a> { }
struct Baz { }
impl<'a> Foo<'a> for Baz { }
impl Bar for Baz { }
}
}
}
#[test]
fn higher_ranked_trait_bound_on_gat() {
lowering_success! {
program {
trait Foo<'a> { }
struct Baz { }
trait Bar<'a> {
type Item<V>: Foo<'a> where forall<'b> V: Foo<'b>;
}
impl<'a> Bar<'a> for Baz {
type Item<V> = V;
}
}
}
}
// See `cyclic_traits`, this is essentially the same but with higher-ranked co-inductive WF goals.
#[test]
fn higher_ranked_cyclic_requirements() {
lowering_success! {
program {
trait Foo<T> where forall<U> Self: Bar<U> { }
trait Bar<T> where forall<U> Self: Foo<T> { }
impl<T, U> Foo<T> for U { }
impl<T, U> Bar<T> for U { }
}
}
lowering_error! {
program {
trait Copy { }
trait Foo<T> where forall<U> Self: Bar<U>, Self: Copy { }
trait Bar<T> where forall<U> Self: Foo<T> { }
impl<T, U> Foo<T> for U { }
impl<T, U> Bar<T> for U where U: Foo<T> { }
} error_msg {
"trait impl for `Foo` does not meet well-formedness requirements"
}
}
lowering_success! {
program {
trait Copy { }
trait Foo<T> where forall<U> Self: Bar<U>, Self: Copy { }
trait Bar<T> where forall<U> Self: Foo<T> { }
impl<T, U> Foo<T> for U where U: Copy { }
impl<T, U> Bar<T> for U where U: Foo<T> { }
}
}
}
#[test]
fn higher_ranked_inline_bound_on_gat() {
lowering_success! {
program {
trait Fn<T> { }
struct Ref<'a, T> { }
struct Val {}
struct fun<T> { }
impl<'a, T> Fn<Ref<'a, T>> for for<'b> fn(fun<Ref<'b, T>>) { }
trait Bar {
type Item<T>: forall<'a> Fn<Ref<'a, T>>;
}
impl Bar for Val {
type Item<T> = for<'a> fn(fun<Ref<'a, T>>);
}
}
}
lowering_error! {
program {
trait Fn<T, U> { }
struct Val {}
struct fun<T, U> { }
impl<T, U> Fn<T, U> for fun<T, U> { }
trait Bar {
type Item<T>: forall<U> Fn<T, U>;
}
impl Bar for Val {
type Item<T> = fun<T, Val>;
}
} error_msg {
"trait impl for `Bar` does not meet well-formedness requirements"
}
}
}
#[test]
fn assoc_type_recursive_bound() {
lowering_error! {
program {
trait Sized { }
trait Print {
// fn print();
}
trait Foo {
type Item: Sized where <Self as Foo>::Item: Sized;
}
struct Number { }
impl Foo for Number {
// Well-formedness checks require that the following
// goal is true:
// ```
// if (str: Sized) { # if the where clauses hold
// str: Sized # then the bound on the associated type hold
// }
// ```
// which it is :)
type Item = str;
}
struct OnlySized<T> where T: Sized { }
impl<T> Print for OnlySized<T> {
// fn print() {
// println!("{}", std::mem::size_of::<T>());
// }
}
trait Bar {
type Assoc: Print;
}
impl<T> Bar for T where T: Foo {
type Assoc = OnlySized<<T as Foo>::Item>;
}
// Above, we used to incorrectly assume that `OnlySized<<T as Foo>::Item>`
// is well-formed because of the `FromEnv(T: Foo)`, hence making the `T: Bar`
// impl pass the well-formedness check. But the following query will
// (and should) always succeed, as there is no where clauses on `Assoc`:
// ```
// forall<T> { if (T: Bar) { WellFormed(<T as Bar>::Assoc) } }
// ```
//
// This may lead to the following code to compile:
// ```
// fn foo<T: Print>() {
// T::print() // oops, in fact `T = OnlySized<str>` which is ill-formed
// }
// fn bar<T: Bar> {
// // ok, we have `FromEnv(T: Bar)` hence
// // `<T as Bar>::Assoc` is well-formed and
// // `Implemented(<T as Bar>::Assoc: Print)` hold
// foo<<T as Bar>::Assoc>(
// }
// fn main() {
// bar::<Number>() // ok, `Implemented(Number: Bar)` hold
// }
// ```
} error_msg {
"trait impl for `Bar` does not meet well-formedness requirements"
}
}
}
#[test]
fn struct_sized_constraints() {
lowering_error! {
program {
#[lang(sized)]
trait Sized { }
struct S<T> {
t1: T,
t2: T
}
} error_msg {
"type declaration `S` does not meet well-formedness requirements"
}
}
lowering_success! {
program {
#[lang(sized)]
trait Sized { }
struct Foo { }
struct S<T> {
t1: Foo,
t2: T
}
}
}
lowering_success! {
program {
#[lang(sized)]
trait Sized { }
struct S<T> where T: Sized {
t1: T,
t2: T
}
}
}
lowering_success! {
program {
#[lang(sized)]
trait Sized { }
struct Foo {}
struct G<T> {
foo: S<S<Foo>>,
s: S<S<S<T>>>
}
struct S<T> {
t1: T
}
}
}
lowering_error! {
program {
#[lang(sized)]
trait Sized { }
struct Foo {}
impl Sized for Foo {}
} error_msg {
"trait impl for `Sized` does not meet well-formedness requirements"
}
}
}
#[test]
fn enum_sized_constraints() {
// All fields must be sized
lowering_error! {
program {
#[lang(sized)]
trait Sized { }
enum E<T> {
A {
t1: T,
t2: T,
},
B,
C,
}
} error_msg {
"type declaration `E` does not meet well-formedness requirements"
}
}
// Even the last field must be sized
lowering_error! {
program {
#[lang(sized)]
trait Sized { }
struct Foo { }
enum E<T> {
A {
t1: Foo,
t2: T,
},
B,
C,
}
} error_msg {
"type declaration `E` does not meet well-formedness requirements"
}
}
// Sized bound
lowering_success! {
program {
#[lang(sized)]
trait Sized { }
enum S<T> where T: Sized {
A {
t1: T,
t2: T,
},
B,
C,
}
}
}
// No manual impls
lowering_error! {
program {
#[lang(sized)]
trait Sized { }
enum Foo {}
impl Sized for Foo {}
} error_msg {
"trait impl for `Sized` does not meet well-formedness requirements"
}
}
}
#[test]
fn copy_constraints() {
lowering_success! {
program {
#[lang(copy)]
trait Copy { }
#[lang(drop)]
trait Drop { }
struct S<T1, T2> { t1: T1, t2: T2 }
impl<T1, T2> Copy for S<T1, T2> where T1: Copy, T2: Copy { }
}
}
lowering_success! {
program {
#[lang(copy)]
trait Copy { }
#[lang(drop)]
trait Drop { }
trait MyTrait where Self: Copy { }
struct S<T> where T: MyTrait { t: T }
impl<T> Copy for S<T> { }
}
}
// Copy implementations for a struct with non-copy field
lowering_error! {
program {
#[lang(copy)]
trait Copy { }
struct S<T> { t: T }
impl<T> Copy for S<T> { }
} error_msg {
"trait impl for `Copy` does not meet well-formedness requirements"
}
}
lowering_error! {
program {
#[lang(copy)]
trait Copy { }
struct S<T1, T2> { t1: T1, t2: T2 }
impl<T1, T2> Copy for S<T1, T2> where T2: Copy { }
} error_msg {
"trait impl for `Copy` does not meet well-formedness requirements"
}
}
// Copy implemenation for a Drop type
lowering_error! {
program {
#[lang(copy)]
trait Copy { }
#[lang(drop)]
trait Drop { }
struct S<T> where T: Copy { t: T }
impl<T> Copy for S<T> { }
impl<T> Drop for S<T> { }
} error_msg {
"trait impl for `Copy` does not meet well-formedness requirements"
}
}
// Enums
// Copy types on enum
lowering_success! {
program {
#[lang(copy)]
trait Copy { }
#[lang(drop)]
trait Drop { }
enum E<T1, T2> { Foo(T1), Bar { t2: T2 } }
impl<T1, T2> Copy for E<T1, T2> where T1: Copy, T2: Copy { }
}
}
// Types with with copy bound
lowering_success! {
program {
#[lang(copy)]
trait Copy { }
#[lang(drop)]
trait Drop { }
trait MyTrait where Self: Copy { }
enum E<T> where T: MyTrait { Foo(T) }
impl<T> Copy for E<T> { }
}
}
// Copy implementations for a adt with non-copy field
lowering_error! {
program {
#[lang(copy)]
trait Copy { }
enum E<T> { Foo(T) }
impl<T> Copy for E<T> { }
} error_msg {
"trait impl for `Copy` does not meet well-formedness requirements"
}
}
// Only one copy field
lowering_error! {
program {
#[lang(copy)]
trait Copy { }
enum E<T1, T2> { Foo(T1), Bar { t2: T2 } }
impl<T1, T2> Copy for E<T1, T2> where T2: Copy { }
} error_msg {
"trait impl for `Copy` does not meet well-formedness requirements"
}
}
// Copy implemenation for a Drop type
lowering_error! {
program {
#[lang(copy)]
trait Copy { }
#[lang(drop)]
trait Drop { }
enum E<T> where T: Copy { Foo { t: T } }
impl<T> Copy for E<T> { }
impl<T> Drop for E<T> { }
} error_msg {
"trait impl for `Copy` does not meet well-formedness requirements"
}
}
// Tests for Copy impls for builtin types
lowering_success! {
program {
#[lang(copy)]
trait Copy { }
#[lang(drop)]
trait Drop { }
impl Copy for u8 {}
impl Copy for f32 {}
impl Copy for char {}
impl Copy for bool {}
impl<T> Copy for *const T {}
impl<T> Copy for *mut T {}
impl<'a, T> Copy for &'a T {}
impl Copy for ! {}
}
}
lowering_error! {
program {
#[lang(copy)]
trait Copy { }
impl<'a, T> Copy for &'a mut T {}
} error_msg {
"trait impl for `Copy` does not meet well-formedness requirements"
}
}
lowering_error! {
program {
#[lang(copy)]
trait Copy { }
#[object_safe]
trait Trait {}
impl<'a> Copy for dyn Trait + 'a {}
} error_msg {
"trait impl for `Copy` does not meet well-formedness requirements"
}
}
lowering_error! {
program {
#[lang(copy)]
trait Copy { }
impl Copy for fn(u32) {}
} error_msg {
"trait impl for `Copy` does not meet well-formedness requirements"
}
}
lowering_error! {
program {
#[lang(copy)]
trait Copy { }
impl Copy for str {}
} error_msg {
"trait impl for `Copy` does not meet well-formedness requirements"
}
}
lowering_error! {
program {
#[lang(copy)]
trait Copy { }
impl Copy for [u32; 4] {}
} error_msg {
"trait impl for `Copy` does not meet well-formedness requirements"
}
}
lowering_error! {
program {
#[lang(copy)]
trait Copy { }
impl Copy for [u32] {}
} error_msg {
"trait impl for `Copy` does not meet well-formedness requirements"
}
}
}
#[test]
fn drop_constraints() {
lowering_error! {
program {
#[lang(drop)]
trait Drop { }
struct Foo { }
struct S<T> { }
impl Drop for S<Foo> { }
} error_msg {
"trait impl for `Drop` does not meet well-formedness requirements"
}
}
lowering_success! {
program {
trait Trait where Self: SuperTrait { }
trait SuperTrait {}
#[lang(drop)]
trait Drop { }
struct S<T> where T: Trait { }
impl<T> Drop for S<T> where T: SuperTrait { }
}
}
lowering_success! {
program {
#[lang(drop)]
trait Drop { }
struct S<T1, T2> { }
impl<T1, T2> Drop for S<T2, T1> { }
}
}
lowering_error! {
program {
trait MyTrait { }
#[lang(drop)]
trait Drop { }
struct S<T>{ }
impl<T> Drop for S<T> where T: MyTrait { }
} error_msg {
"trait impl for `Drop` does not meet well-formedness requirements"
}
}
}
#[test]
fn no_unsize_impls() {
lowering_error! {
program {
#[lang(unsize)]
trait Unsize<T> {}
impl Unsize<u32> for u32 {}
} error_msg {
"trait impl for `Unsize` does not meet well-formedness requirements"
}
}
}
#[test]
fn ill_formed_opaque_ty() {
lowering_error! {
program {
trait Foo {}
struct Bar {}
opaque type T: Foo = Bar;
} error_msg {
"opaque type declaration `T` does not meet well-formedness requirements"
}
}
lowering_error! {
program {
trait Foo { }
struct NotFoo { }
struct IsFoo { }
impl Foo for IsFoo { }
opaque type T: Foo = NotFoo;
} error_msg {
"opaque type declaration `T` does not meet well-formedness requirements"
}
}
}
#[test]
fn coerce_unsized_pointer() {
lowering_success! {
program {
#[lang(unsize)]
trait Unsize<T> {}
#[lang(coerce_unsized)]
trait CoerceUnsized<T> {}
impl<'a, T, U> CoerceUnsized<*mut U> for &'a mut T where T: Unsize<U> {}
impl<T, U> CoerceUnsized<*mut U> for *mut T where T: Unsize<U> {}
}
}
// T: Unsize<U> is not in the environment
lowering_error! {
program {
#[lang(unsize)]
trait Unsize<T> {}
#[lang(coerce_unsized)]
trait CoerceUnsized<T> {}
impl<'a, T, U> CoerceUnsized<*mut U> for &'a mut T {}
} error_msg {
"trait impl for `CoerceUnsized` does not meet well-formedness requirements"
}
}
// Test with builtin Unsize impl
lowering_success! {
program {
#[lang(unsize)]
trait Unsize<T> {}
#[lang(coerce_unsized)]
trait CoerceUnsized<T> {}
#[object_safe]
trait Foo {}
#[auto]
#[object_safe]
trait Auto {}
impl<'a> CoerceUnsized<&'a (dyn Foo + 'a)> for &'a (dyn Foo + Auto + 'a) {}
}
}
// Test with builtin Unsize impl
lowering_error! {
program {
#[lang(unsize)]
trait Unsize<T> {}
#[lang(coerce_unsized)]
trait CoerceUnsized<T> {}
#[object_safe]
trait Foo {}
#[auto]
#[object_safe]
trait Auto {}
impl<'a> CoerceUnsized<&'a (dyn Foo + Auto + 'a)> for &'a (dyn Foo + 'a) {}
} error_msg {
"trait impl for `CoerceUnsized` does not meet well-formedness requirements"
}
}
// Test with builtin Unsize impl
lowering_success! {
program {
#[lang(unsize)]
trait Unsize<T> {}
#[lang(coerce_unsized)]
trait CoerceUnsized<T> {}
impl<'a> CoerceUnsized<&'a [f32]> for &'a [f32; 3] {}
}
}
// Coercing from shared to mut
lowering_error! {
program {
#[lang(unsize)]
trait Unsize<T> {}
#[lang(coerce_unsized)]
trait CoerceUnsized<T> {}
impl<'a, T, U> CoerceUnsized<*mut U> for &'a T where T: Unsize<U> {}
} error_msg {
"trait impl for `CoerceUnsized` does not meet well-formedness requirements"
}
}
// Coercing from shared to mut
lowering_error! {
program {
#[lang(unsize)]
trait Unsize<T> {}
#[lang(coerce_unsized)]
trait CoerceUnsized<T> {}
impl<'a, T, U> CoerceUnsized<&'a mut U> for &'a T where T: Unsize<U> {}
} error_msg {
"trait impl for `CoerceUnsized` does not meet well-formedness requirements"
}
}
// Coercing from shared to mut
lowering_error! {
program {
#[lang(unsize)]
trait Unsize<T> {}
#[lang(coerce_unsized)]
trait CoerceUnsized<T> {}
impl<T, U> CoerceUnsized<*mut U> for *const T where T: Unsize<U> {}
} error_msg {
"trait impl for `CoerceUnsized` does not meet well-formedness requirements"
}
}
// Coercing from raw pointer to ref
lowering_error! {
program {
#[lang(unsize)]
trait Unsize<T> {}
#[lang(coerce_unsized)]
trait CoerceUnsized<T> {}
impl<'a, T, U> CoerceUnsized<&'a U> for *const T where T: Unsize<U> {}
} error_msg {
"trait impl for `CoerceUnsized` does not meet well-formedness requirements"
}
}
}
#[test]
fn coerce_unsized_struct() {
lowering_success! {
program {
#[lang(unsize)]
trait Unsize<T> {}
#[lang(coerce_unsized)]
trait CoerceUnsized<T> {}
struct Foo<'a, T> where T: 'a {
t: &'a T
}
struct Bar<T, U> {
extra: T,
ptr: *mut U,
}
impl<'a, T, U> CoerceUnsized<&'a U> for &'a T where T: Unsize<U> {}
impl<T, U> CoerceUnsized<*mut U> for *mut T where T: Unsize<U> {}
impl<'a> CoerceUnsized<Foo<'a, [u32]>> for Foo<'a, [u32; 3]> {}
impl<T, U, V> CoerceUnsized<Bar<T, V>> for Bar<T, U> where U: Unsize<V> {}
}
}
// Unsizing different structs
lowering_error! {
program {
#[lang(unsize)]
trait Unsize<T> {}
#[lang(coerce_unsized)]
trait CoerceUnsized<T> {}
struct S1<T> {
t: T,
}
struct S2<T> {
t: T,
}
impl<T, U> CoerceUnsized<S2<U>> for S1<T> where T: CoerceUnsized<U> {}
} error_msg {
"trait impl for `CoerceUnsized` does not meet well-formedness requirements"
}
}
// Unsizing enums
lowering_error! {
program {
#[lang(unsize)]
trait Unsize<T> {}
#[lang(coerce_unsized)]
trait CoerceUnsized<T> {}
enum Foo<T> {
A {
t: T
}
}
impl<T, U> CoerceUnsized<Foo<U>> for Foo<T> where T: CoerceUnsized<U> {}
} error_msg {
"trait impl for `CoerceUnsized` does not meet well-formedness requirements"
}
}
// Unsizing two fields
lowering_error! {
program {
#[lang(unsize)]
trait Unsize<T> {}
#[lang(coerce_unsized)]
trait CoerceUnsized<T> {}
struct Bar<T, U> {
ptr1: *mut T,
ptr2: *mut U,
}
impl<T, U> CoerceUnsized<*mut U> for *mut T where T: Unsize<U> {}
impl<T, S, U, V> CoerceUnsized<Bar<T, V>> for Bar<S, U> where U: Unsize<V>, T: Unsize<S> {}
} error_msg {
"trait impl for `CoerceUnsized` does not meet well-formedness requirements"
}
}
// Unsizing no fields
lowering_error! {
program {
#[lang(unsize)]
trait Unsize<T> {}
#[lang(coerce_unsized)]
trait CoerceUnsized<T> {}
struct Bar<T, U> {
ptr1: *mut T,
ptr2: *mut U,
}
impl<T, U> CoerceUnsized<*mut U> for *mut T where T: Unsize<U> {}
impl<T> CoerceUnsized<Bar<T, T>> for Bar<T, T> where T: Unsize<T> {}
} error_msg {
"trait impl for `CoerceUnsized` does not meet well-formedness requirements"
}
}
// No unsize in the environment
lowering_error! {
program {
#[lang(unsize)]
trait Unsize<T> {}
#[lang(coerce_unsized)]
trait CoerceUnsized<T> {}
struct Bar<T, U> {
extra: T,
ptr: *mut U,
}
impl<T, U> CoerceUnsized<*mut U> for *mut T where T: Unsize<U> {}
impl<T, U, V> CoerceUnsized<Bar<T, V>> for Bar<T, U> {}
} error_msg {
"trait impl for `CoerceUnsized` does not meet well-formedness requirements"
}
}
// Phantom data test & CoerceUnsized in the environment test
lowering_success! {
program {
#[lang(unsize)]
trait Unsize<T> {}
#[lang(coerce_unsized)]
trait CoerceUnsized<T> {}
#[phantom_data]
struct PhantomData<T> {}
struct Foo<T, V> {
coerce: T,
phantom: PhantomData<V>,
}
struct Bar<T, U, V> {
extra: T,
phantom: PhantomData<V>,
ptr: *mut U,
}
impl<T, U> CoerceUnsized<*mut U> for *mut T where T: Unsize<U> {}
impl<T, U, V, N, M> CoerceUnsized<Bar<T, V, N>> for Bar<T, U, M> where U: Unsize<V> {}
impl<T, U, V> CoerceUnsized<Foo<U, V>> for Foo<T, V> where T: CoerceUnsized<U> {}
}
}
}
|
TypeScript
|
UTF-8
| 7,782
| 2.984375
| 3
|
[] |
no_license
|
import { Coords, PolarCoordinate } from '@/Types/types';
export class Mouse {
private canvas : HTMLCanvasElement;
private offsetX = 0;
private offsetY = 0;
private mouseX = 0;
private mouseY = 0;
constructor(e: MouseEvent, canvas: HTMLCanvasElement) {
this.canvas = canvas;
const canvasBounding = this.canvas.getBoundingClientRect();
this.offsetX = canvasBounding.left;
this.offsetY = canvasBounding.top;
this.mouseX = e.clientX - this.offsetX;
this.mouseY = e.clientY - this.offsetY;
}
public get mousePosition(): Coords {
return {
x: this.mouseX,
y: this.mouseY
}
}
}
export class ResizeHandle {
private handleSize = 9;
public x = 0;
public y = 0;
constructor(public position: PolarCoordinate, private coords: Coords, private shapeWidth: number, private shapeHeight: number, private ctx: CanvasRenderingContext2D) {
this.createHandle();
}
private draw(x: number, y: number) {
this.x = x;
this.y = y;
this.ctx.fillRect(x, y, this.handleSize, this.handleSize);
this.ctx.strokeRect(x, y, this.handleSize, this.handleSize);
}
private createHandle() {
this.ctx.fillStyle = '#ffffff';
this.ctx.strokeStyle = '#00a7f9';
const N = {
x: this.coords.x + this.shapeWidth / 2 - this.handleSize / 2,
y: this.coords.y - this.handleSize / 2
}
const S = {
x: this.coords.x + this.shapeWidth / 2 - this.handleSize / 2,
y: this.coords.y + this.shapeHeight - this.handleSize / 2
}
const W = {
x: this.coords.x - this.handleSize / 2,
y: this.coords.y + this.shapeHeight / 2 - this.handleSize / 2
}
const E = {
x: this.coords.x + this.shapeWidth - this.handleSize / 2,
y: this.coords.y + this.shapeHeight / 2 - this.handleSize / 2
}
const NW = {
x: this.coords.x - this.handleSize / 2,
y: this.coords.y - this.handleSize / 2
}
const NE = {
x: this.coords.x + this.shapeWidth - this.handleSize / 2,
y: NW.y,
}
const SW = {
x: NW.x,
y: this.coords.y + this.shapeHeight - this.handleSize / 2
}
const SE = {
x: NE.x,
y: SW.y
}
switch (this.position) {
case 'N':
this.draw(N.x, N.y);
break;
case 'S':
this.draw(S.x, S.y);
break;
case 'W':
this.draw(W.x, W.y);
break;
case 'E':
this.draw(E.x, E.y);
break;
case 'NW':
this.draw(NW.x, NW.y);
break;
case 'NE':
this.draw(NE.x, NE.y);
break;
case 'SW':
this.draw(SW.x, SW.y);
break;
case 'SE':
this.draw(SE.x, SE.y);
break;
}
}
public mouseIsOver(mouseX: number, mouseY: number): boolean {
const hotSpotN = mouseX >= this.x - this.shapeWidth / 2 + 20 && mouseX <= this.x + this.shapeWidth / 2 - 20 && mouseY >= this.y - this.handleSize && mouseY <= this.y + this.handleSize / 2;
const hotSpotS = mouseX >= this.x - this.shapeWidth / 2 + 20 && mouseX <= this.x + this.shapeWidth / 2 - 20 && mouseY <= this.y + this.handleSize + this.handleSize / 2 && mouseY >= this.y ;
const hotSpotW = mouseX >= this.x - this.handleSize && mouseX <= this.x + this.handleSize / 2 && mouseY >= this.y - this.shapeHeight / 2 + 20 && mouseY <= this.y + this.shapeHeight / 2 - 20;
const hotSpotE = mouseX >= this.x && mouseX <= this.x + this.handleSize + this.handleSize / 2 && mouseY >= this.y - this.shapeHeight / 2 + 20 && mouseY <= this.y + this.shapeHeight / 2 - 20;
const hotSpotNW = mouseX >= this.x - 15 && mouseX <= this.x + 2.5 && mouseY >= this.y - 15 && mouseY <= this.y + 2.5;
const hotSpotNE = mouseX >= this.x && mouseX <= this.x + 15 && mouseY >= this.y - 15 && mouseY <= this.y + 15;
const hotSpotSE = mouseX >= this.x && mouseX <= this.x + 15 && mouseY >= this.y - 15 && mouseY <= this.y + 15;
const hotSpotSW = mouseX >= this.x - 15 && mouseX <= this.x + 2.5 && mouseY >= this.y - 15 && mouseY <= this.y + 15;
switch (this.position) {
case 'N':
return hotSpotN;
case 'S':
return hotSpotS;
case 'W':
return hotSpotW;
case 'E':
return hotSpotE;
case 'NW':
return hotSpotNW;
case 'NE':
return hotSpotNE;
case 'SE':
return hotSpotSE;
case 'SW':
return hotSpotSW;
}
}
}
export class RadiusHandle {
private handleRadius = 5;
private x = 0;
private y = 0;
private hotSpot = 15;
constructor(public position: PolarCoordinate, public coords: Coords, private shapeWidth: number, private shapeHeight: number, private ctx: CanvasRenderingContext2D, private radius: number) {
this.createHandle();
}
private draw(x: number, y: number) {
this.x = x;
this.y = y;
this.ctx.lineWidth = 1;
this.ctx.strokeStyle = '#00a7f9';
this.ctx.beginPath();
this.ctx.arc(x, y, this.handleRadius, 0, 2 * Math.PI);
this.ctx.fill();
this.ctx.beginPath();
this.ctx.arc(x, y, this.handleRadius, 0, 2 * Math.PI);
this.ctx.stroke();
}
private createHandle() {
this.ctx.fillStyle = '#ffffff';
this.ctx.strokeStyle = '#000000';
const NW = {
x: this.coords.x + 15 + this.radius/Math.PI,
y: this.coords.y + 15 + this.radius/Math.PI
}
const NE = {
x: this.coords.x + this.shapeWidth - 15 - this.radius/Math.PI,
y: NW.y,
}
const SW = {
x: NW.x,
y: this.coords.y + this.shapeHeight - 15 - this.radius/Math.PI
}
const SE = {
x: NE.x,
y: SW.y
}
switch (this.position) {
case 'NW':
this.draw(NW.x, NW.y);
break;
case 'NE':
this.draw(NE.x, NE.y);
break;
case 'SW':
this.draw(SW.x, SW.y);
break;
case 'SE':
this.draw(SE.x, SE.y);
break;
case 'W':
break;
case 'E':
break;
}
}
public mouseIsOver(mouseX: number, mouseY: number): boolean {
const hotSpotNW = mouseX >= this.x - 3 && mouseX <= this.x + this.hotSpot && mouseY >= this.y - 3 && mouseY <= this.y + this.hotSpot;
const hotSpotNE = mouseX >= this.x - this.hotSpot && mouseX <= this.x + 3 && mouseY >= this.y - 3 && mouseY <= this.y + this.hotSpot;
const hotSpotSE = mouseX >= this.x - this.hotSpot && mouseX <= this.x + 3 && mouseY >= this.y - this.hotSpot && mouseY <= this.y + 3;
const hotSpotSW = mouseX >= this.x - 3 && mouseX <= this.x + this.hotSpot && mouseY >= this.y - this.hotSpot && mouseY <= this.y + 3;
switch (this.position) {
case 'NW':
return hotSpotNW;
case 'NE':
return hotSpotNE;
case 'SE':
return hotSpotSE;
case 'SW':
return hotSpotSW;
}
return false;
}
}
|
Java
|
UTF-8
| 1,367
| 2.109375
| 2
|
[] |
no_license
|
package com.accp.service;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.accp.domain.Shop;
import com.accp.domain.User;
import com.accp.mapper.ShopMapper;
import com.accp.mapper.UserMapper;
@Service
@Transactional
public class ShopService {
@Autowired
ShopMapper sm;
@Autowired
UserMapper um;
public List<Shop> queryShop(Integer userid){
List<Shop> list=sm.queryShop(userid);
return list;
}
public String addShop(Shop shop,HttpSession session) {
User user=new User();
User us=(User)session.getAttribute("user");
user=um.selectByPrimaryKey(us.getUserid());
shop.setUserid(user.getUserid());
sm.insertSelective(shop);
return "success";
}
public Shop byShopId(Integer shopid) {
return sm.selectByPrimaryKey(shopid);
}
public int removeShop(Integer shopid) {
return sm.deleteByPrimaryKey(shopid);
}
public int updateShop(Shop shop) {
return sm.updateByPrimaryKeySelective(shop);
}
public Shop queryShopName(String shopname) {
return sm.queryShopName(shopname);
}
}
|
Python
|
UTF-8
| 223
| 3
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 29 11:03:09 2020
@author: Ayush
"""
def printDict():
x=int(input())
d={}
for i in range (1,x+1):
d[i]=i**2
print(d,end="")
printDict()
printDict()
|
Java
|
UTF-8
| 4,770
| 2.78125
| 3
|
[] |
no_license
|
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import model.User;
public class UserDAO {
private Connection con;
private int lastUserAutoKey;
public UserDAO() throws NamingException, SQLException {
// initialize lastAutoKeys here
lastUserAutoKey = -1;
Context cxt = new InitialContext();
DataSource ds = (DataSource) cxt.lookup("java:/comp/env/jdbc/CartDB");
con = ds.getConnection();
}
public void closeConnection() throws SQLException {
con.close();
}
// CREATE
public int createUser(User newUser) throws SQLException {
String sql = "INSERT INTO cart_comp461_db.User (idUser, name,"
+ "address, city, state, zip, phone) VALUES"
+ "(?, ?, ?, ?, ?, ?, ?)";
ResultSet rs = null;
PreparedStatement ps = con.prepareStatement(sql,
Statement.RETURN_GENERATED_KEYS);
ps.setNull(1, java.sql.Types.INTEGER);
ps.setString(2, newUser.getName());
ps.setString(3, newUser.getAddress());
ps.setString(4, newUser.getCity());
ps.setString(5, newUser.getState());
ps.setString(6, newUser.getZip());
ps.setString(7, newUser.getPhone());
ps.executeUpdate();
rs = ps.getGeneratedKeys();
rs.last();
lastUserAutoKey = rs.getInt(1);
return lastUserAutoKey;
}
// RETRIEVE
/**
* Returns a User object when searching via the user's ID.
*
* @param userID
* the ID of the user to lookup
* @return the User Model object, or null if not found
* @throws SQLException
* when SQL error occurs
*/
public User getUserByUserID(int userID) throws SQLException {
User record = null;
String sql = "SELECT * FROM cart_comp461_db.User " + "WHERE idUser = "
+ userID;
// prepared statement
Statement s = con.createStatement();
ResultSet rs = s.executeQuery(sql);
int id;
String name, address, city, state, zip, phone;
while (rs.next()) {
id = rs.getInt("idUser");
name = rs.getString("name");
address = rs.getString("address");
city = rs.getString("city");
state = rs.getString("state");
zip = rs.getString("zip");
phone = rs.getString("phone");
record = new User(id, name, address, city, state, zip, phone);
}
s.close();
rs.close();
return record;
}
public User getUserByName(String userName) throws SQLException {
User record = null;
String sql = "SELECT idUser FROM cart_comp461_db.User "
+ "WHERE name = '" + userName + "'";
// prepared statement
Statement s = con.createStatement();
ResultSet rs = s.executeQuery(sql);
while (rs.next()) {
record = getUserByUserID(rs.getInt("idUser"));
}
s.close();
rs.close();
return record;
}
// UPDATE
public void updateUser(int userId, User theUser) throws SQLException {
// UPDATE <table> SET <column>=<value> WHERE ID=<id>
String sql = "UPDATE cart_comp461_db.User SET "
+ "name = ?, address = ?, city = ?, state = ?, zip = ?,"
+ "phone = ? WHERE idUser = ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, theUser.getName());
ps.setString(2, theUser.getAddress());
ps.setString(3, theUser.getCity());
ps.setString(4, theUser.getState());
ps.setString(5, theUser.getZip());
ps.setString(6, theUser.getPhone());
ps.setInt(7, userId);
ps.executeUpdate();
ps.close();
}
// DELETE
public void removeUser(User theUser) throws SQLException {
// DELETE FROM cart_comp461_db.User WHERE ID = <id>
String sql = "DELETE FROM cart_comp461_db.User WHERE idUser = ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, theUser.getUserID());
ps.execute();
ps.close();
}
public void removeUserByUserID(int userID) throws SQLException {
// DELETE FROM cart_comp461_db.User WHERE ID = <id>
String sql = "DELETE FROM cart_comp461_db.User WHERE idUser = ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, userID);
ps.execute();
ps.close();
}
}
|
Java
|
UTF-8
| 1,940
| 2.34375
| 2
|
[] |
no_license
|
package com.devfest.musicstore.activity;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import com.devfest.musicstore.R;
import com.devfest.musicstore.adapters.ViewPagerAdapter;
import com.devfest.musicstore.custom.NonSwipeableViewPager;
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
TabLayout tabLayout;
ViewPager viewPager;
String[] titles = {"Home", "Radio"};
private int[] tabIcons = {
R.drawable.ic_home,
R.drawable.ic_radio
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Setting Up ViewPager and Toolbar
tabLayout = (TabLayout) findViewById(R.id.tabs);
viewPager = (NonSwipeableViewPager) findViewById(R.id.pager);
renderLayout();
}
void renderLayout() {
final ViewPager pager = (ViewPager) findViewById(R.id.pager);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager(), titles);
pager.setAdapter(adapter);
tabLayout.setupWithViewPager(pager);
pager.setOnPageChangeListener(new NonSwipeableViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
setupTabIcons();
}
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(R.drawable.ic_home);
tabLayout.getTabAt(1).setIcon(R.drawable.ic_radio);
}
}
|
Java
|
UTF-8
| 285
| 2.671875
| 3
|
[] |
no_license
|
package org.westos.设计模式;
//懒汉式的更加实现
public class Singleton4 {
private Singleton4() {
}
private static class Holder{
static Singleton4 ME=new Singleton4();
}
public static Singleton4 getInstance(){
return Holder.ME;
}
}
|
Python
|
UTF-8
| 717
| 3.421875
| 3
|
[] |
no_license
|
def count_n_dig(num):
# "12345678"
s_num = str(num)
dig_num = len(s_num)
bottom_half = int(s_num[dig_num/2:])
top_half = int(s_num[:dig_num/2][::-1])
if top_half == 1:
return bottom_half
return top_half + bottom_half
def count(num):
if num < 10:
return num
if num % 10 == 0:
return count(num-1) + 1
ret = 10
p = 10
while p*10 <= num:
ret += count_n_dig(p*10 - 1) + 1
p *= 10
ret += count_n_dig(num)
return ret
def parse(filename):
output = open("output.txt", "w")
with open(filename, "rb") as f:
T = int(f.readline())
for i in xrange(T):
num = int(f.readline())
res = count(num)
output.write("Case #%d: %d\n" % (i+1, res))
parse("input.txt")
|
Python
|
UTF-8
| 8,690
| 2.625
| 3
|
[] |
no_license
|
import numpy as np
import matplotlib.pylab as plt
from scipy.interpolate import griddata
import time
import pickle
from functools import reduce
from matplotlib import animation
def PointFocalLaw(f,F,p,N,x,y,c):
xn = np.linspace(-0.5*(N-1)*p,0.5*p*(N-1),N)
Fn = [F*np.exp(-2j*f*np.pi*np.sqrt((x-xn[n])**2 + y**2)/c) for n in range(N)]
return Fn
def SweepFocalLaw(f,F,p,N,angle,c):
xn = np.linspace(-0.5*(N-1)*p,0.5*p*(N-1),N)
Fn = [F*np.exp(2j*f*np.pi*np.sin(angle*np.pi/180.)*xn[n]/c) for n in range(N)]
return Fn
def GetCenterline(x,y,I,angle,dr=0.1):
x,y = np.meshgrid(x,y)
r = np.arange(0,np.amax(y)/np.cos(angle*np.pi/180.),dr)
X = r*np.sin(angle*np.pi/180.)
Y = r*np.cos(angle*np.pi/180.)
s = griddata((x.flatten(),y.flatten()), I.flatten(), (X.flatten(),Y.flatten()), method='linear')
return s
def ToPolarField(x,y,I,res=(0.1,5),isongrid=True):
if isongrid:
x,y = np.meshgrid(x,y)
x = x.flatten()
y = y.flatten()
r = np.sqrt(x**2+y**2)
th = np.arctan2(x,y)*180./np.pi
rr,tth = np.arange(np.amin(r),np.amax(r),res[0]), np.arange(np.amin(th),np.amax(th),res[1])
R,Th = np.meshgrid(rr,tth)
s = R.shape
R = R.flatten()
Th = Th.flatten()
II = griddata((r,th), (I.flatten()), (R,Th), fill_value=0.).reshape(s)
return np.arange(0.,np.amax(r),res[0]), np.arange(np.amin(th),np.amax(th),res[1]), II
def GetScatteringDistribution(x,y,scatterparams,c=5.92):
if scatterparams['Type']=='SDH':
xc,yc = scatterparams['Center']
R = scatterparams['Radius']
x,y=np.meshgrid(x,y)
I = ((y-yc)**2)<=(R**2 - (x-xc)**2)
I = (I.astype(np.float).reshape(x.shape))*(1/(0.33)**2 - 1/c**2)
return I
def GetNormalline(x,y,I,angle,r,dr=0.1):
x,y = np.meshgrid(x,y)
x0 = r*np.sin(angle*np.pi/180.)
y0 = r*np.cos(angle*np.pi/180.)
# y0 = np.amax(y)
#
# x0 = y0*np.tan(angle*np.pi/180.)
#
xx = (np.amax(y) - y0)/np.cos(angle*np.pi/180.)
yy = (np.amax(x) - x0)/np.sin(angle*np.pi/180.)
#
# yy = (xx - x0)/np.tan(np.pi/2 - angle*np.pi/180.)
#
# print(yy)
# r = np.arange(0.,np.sqrt((xx-x0)**2 + yy**2),dr)
r = np.arange(-np.sqrt((xx-x0)**2 + (np.amax(y)-y0)**2),np.sqrt((np.amax(x)-x0)**2 + (np.amax(yy)-y0)**2),dr)
X = r*np.sin(np.pi/2 - angle*np.pi/180.) + x0
Y = r*np.cos(np.pi/2 - angle*np.pi/180.) + y0
s = griddata((x.flatten(),y.flatten()), I.flatten(), (X.flatten(),Y.flatten()), method='linear')
return r,s
def CompressionElementField3d(L,W,f,F,resolution,Lx,Lz,rho=7.8,cp=5.92,cs=3.24,Nkz = 10,bc='displacement',eta=1e-4):
# cp = cp*(1-eta*1j)
dx = resolution
Nx = int(Lx/dx)
Nz = int(Lz/dx)
kx,ky,z,w = np.meshgrid(2*np.pi*np.linspace(-1/L,1/L,Nkz), 2*np.pi*np.linspace(-1/(2*dx),1/(2*dx),Nx),np.linspace(0,Lz,Nz), 2*np.pi*f)
F = F.reshape((1,1,1,w.shape[-1]))
kz = np.sqrt((w/cp)**2 - kx**2 - ky**2 + 0j)
if bc == 'stress':
P = L*W*F*np.sinc(0.5*L*ky/np.pi)*np.sinc(0.5*W*kx/np.pi)*np.exp(1j*kz*z)/(rho*(w**2 - 2*(kx**2 + ky**2)*cs**2))
P = P/np.amax(np.abs(P))
n = P.shape
P[np.abs(np.imag(kz))>0.] = 0.+0j
P[np.abs((w**2 - 2*(kx**2 + ky**2)*cs**2))<eta] = 0.+0j
elif bc == 'displacement':
P = L*W*F*np.sinc(0.5*L*ky/np.pi)*np.sinc(0.5*W*kx/np.pi)*np.exp(1j*kz*z)/(1j*kz)
P = P/np.amax(np.abs(P))
n = P.shape
P[np.abs(np.imag(kz))>0.] = 0.+0j
P[np.abs(kz)<eta] = 0.+0j
elif bc == 'potential':
P = L*W*F*np.sinc(0.5*L*ky/np.pi)*np.sinc(0.5*W*kx/np.pi)*np.exp(1j*kz*z)
P = P/np.amax(np.abs(P))
n = P.shape
P[np.abs(np.imag(kz))>0.] = 0.+0j
P = P.reshape(n)
# Field averaged over passive aperture
p = (np.fft.fftshift(np.sum(np.abs(np.sum(np.fft.ifft(P,axis=0),axis=1)),axis=2),axes=(0))).transpose()
return p
def SteeringAmplitude(f,F,angles,wedgeangle,p,N,h,c=(2.33,3.24)):
pangles = np.rad2deg(np.arcsin(np.real(c[0])*np.sin(np.deg2rad(angles))/c[1])) - wedgeangle
Fn = [SweepFocalLaw(f,F,p,N,pang,np.real(c[0])) for pang in pangles]
dx = p/5.
Nx = int(5*N*p/dx)
kx,w = np.meshgrid(np.pi*2*f+0j,np.pi*2*np.linspace(-1/(2*dx),1/(2*dx),Nx)+0j)
print(w.shape)
print(len(f))
xn = np.linspace(-(N-1)*p/2, (N-1)*p/2, N) + 0j
ky = np.sqrt((w/c[0])**2 - kx**2)
ky[np.abs(np.imag(ky))>0] = 0. + 0j
A = np.array([reduce(lambda x,y: x+y, (FF[n].reshape((1,len(f)))*np.exp(-1j*kx*xn[n]) for n in range(len(FF)))) for FF in Fn])
A = (p+0j)*A*np.sinc(0.5*p*kx/(np.pi+0j))
print(A.shape)
x = -np.linspace(-dx*Nx*0.5,dx*Nx*0.5,Nx)
a = np.array([np.sum(np.abs(np.sum(A*np.exp(1j*ky*(np.sin(np.deg2rad(wedgeangle))*x + h/np.cos(np.deg2rad(wedgeangle))))*np.exp(1j*kx*np.cos(np.deg2rad(wedgeangle))*x),axis=1)),axis=1) for x in x])
# a = np.array([A*np.exp(1j*ky*(np.sin(np.deg2rad(wedgeangle))*xx + h/np.cos(np.deg2rad(wedgeangle))))*np.exp(1j*kx*np.cos(np.deg2rad(wedgeangle))*xx) for xx in x])
return a
def ContactArray2d(f,F,p,resolution,Lx,Ly,rho=7.8,cL=5.91,cT=3.24,bc='stress',eta=1e-4,output='averagefield'):
N = len(F)
Nx = int(Lx/resolution)
kx,y,w = np.meshgrid(2*np.pi*np.linspace(-1/(2*resolution),1/(2*resolution),Nx)+0j,np.arange(0.,Ly,resolution)+0j,2*np.pi*f + 0j)
xn = np.linspace(-(N-1)*p/2, (N-1)*p/2, N) + 0j
ky = np.sqrt((w/cL)**2 - kx**2)
A = reduce(lambda x,y: x+y, (F[n].reshape((1,1,len(f)))*np.exp(-1j*kx*xn[n]) for n in range(len(F))))
# A = F[8].reshape((1,1,len(f)))
if bc == 'stress':
A = (p+0j)*A*np.sinc(0.5*p*kx/(np.pi+0j))*np.exp(1j*ky*y)/(rho*(2*(cT*kx)**2 - w**2))
# A = np.sqrt((rho*(2*(cT/cL)**2 - 1)*w**2 - 2*cT**2*kx**2)**2 + 1)*(p+0j)*A*np.sinc(0.5*p*kx/(np.pi+0j))*np.exp(1j*ky*y)
# A = (p+0j)*A*np.sinc(0.5*p*kx/(np.pi+0j))*np.exp(1j*ky*y)
# A = (p+0j)*A*np.sinc(0.5*p*kx/(np.pi+0j))*np.exp(1j*ky*y)/(rho*ky**2)
A = A/np.amax(np.abs(A))
s = A.shape
# A[np.abs(np.imag(ky))>0.] = 0. + 0j
A[np.abs(kx**2 - 0.5*(w/cT)**2)<eta] = np.nan
# A[np.abs(2*(cT*kx)**2 - w**2)<eta] = 0. +0j
# elif bc == 'potential':
#
# A = (p+0j)*A*np.sinc(0.5*p*kx/(np.pi+0j))*np.exp(1j*ky*y)
#
# s = A.shape
#
# A[np.abs(np.imag(ky))>0.] = 0. + 0j
#
#
# # elif bc == 'stressdisplacement':
# #
# # A = (p+0j)*A*np.sinc(0.5*p*kx/(np.pi+0j))*np.exp(1j*ky*y)/((1j*ky)*(rho*(2*(cT*kx)**2 - w**2)))
# #
# # s = A.shape
# #
# # A[np.abs(np.imag(ky))>0.] = 0. + 0j
# #
# # A[np.abs(ky)<0.] = 0. +0j
# #
# # A[np.abs(rho*(2*(cT*kx)**2 - w**2))<0.] = 0. +0j
#
#
# A = A.reshape(s)
np.nan_to_num(A,False)
if output == 'averagefield':
return np.fft.fftshift(np.sum(np.abs(np.fft.ifft(A,axis=1)),axis=2),axes = (1))
elif output == 'timefield':
return np.fft.fftshift(np.fft.fft(np.fft.ifft(A,axis=1),axis=2,n=int(2*len(f)+1)),axes = (1))
elif output == 'frequencyfield':
return np.fft.fftshift(np.fft.ifft(A,axis=1),axes = (1))
def BornScatteredFieldContact(f,A,I,resolution,Lx,Ly,c=5.92):
from numpy.fft import ifft, fftn, ifftn, fft
""" Takes incident field, A, and computes field scattered by scattering
distribution I. Incident field is assumed to be generated by a contact array
and should be computed over the same domain as is requested here.
f - frequency vector, resolution spacing of x and y points, Lx is length of x domain (y E [-Lx/2, Lx/2])
Ly is length of y domain, y E [-Ly/2, Ly/2]. Returns time domain scattered field (analytic signal thereof)"""
# w = (2*np.pi*f).reshape((1,1,len(f)))
Nx = int(np.round(Lx/resolution))
Ny = int(np.round(Ly/resolution))
Zx = np.zeros((Ny,int(Nx/2),len(f)))
Zy = np.zeros((int(Ny/2),2*Nx,len(f)))
x,y,w = np.meshgrid(np.linspace(-Lx*resolution,Lx*resolution,2*Nx), np.linspace(-Ly*resolution, Ly*resolution, 2*Ny), 2*np.pi*f)
r = np.sqrt(x**2 + y**2).reshape((x.shape[0],x.shape[1],len(f)))
g = np.exp(-1j*w*r/c)/r
G = fftn(g,axes=(0,1))
# I =
I = fftn(np.vstack((Zy[:,:,0],np.hstack((Zx[:,:,0],I,Zx[:,:,0])),Zy[:,:,0])),axes=(0,1))
S = -I*(w**2)
A = fftn(np.vstack((Zy,np.hstack((Zx,A,Zx)),Zy)),axes=(0,1))
P = S*A*G
p = ifftn(P,axes=(0,1))
p = fft(p[int(np.round(0.5*Ny)):int(np.round(1.5*Ny)),int(np.round(0.5*Nx)):int(np.round(1.5*Ny)),:],n=2*len(f) - 1,axis=2)
return p
|
Java
|
ISO-8859-1
| 1,454
| 2.734375
| 3
|
[] |
no_license
|
package com.Aluguel.repositorios;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import com.Aluguel.Basicas.Aluguel;
public class RepositorioAluguel {
private static RepositorioAluguel instanciaAluguel;
public static RepositorioAluguel getInstancia() {
if(instanciaAluguel == null) {
instanciaAluguel = new RepositorioAluguel();
}else {
System.out.println("Erro no foi possivel criar instancia de Aluguel");
}
return instanciaAluguel;
}
public void novoAluguel(Aluguel alg) throws Exception {
//carregar driver
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
System.out.println("Driver ok, no Aluguel");
//abrir Conexao
Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/projeto_Aluguel;create=true;user=root;password=root");
System.out.println("conexao ok, no Aluguel");
// realizando consultas
PreparedStatement stmt = conn.prepareStatement("INSERT INTO ALUGUEL(cpf_Cliente, placa_Veiculo, valor, forma_Pagamento) VALUES(?,?,?,?)");
stmt.setString(1, alg.getCpfCliente());
stmt.setString(2, alg.getPlacaVeiculo());
stmt.setFloat(3, alg.getValor());
stmt.setString(4, alg.getFormadePagamento());
stmt.execute();
//fechar conexao
conn.commit();
conn.close();
System.out.println("Aluguel realizado com Sucesso!");
}
}
|
Python
|
UTF-8
| 1,406
| 3.78125
| 4
|
[] |
no_license
|
#A media access control address (MAC address) is a unique identifier assigned to network interfaces for communications on the physical network segment.
#The standard (IEEE 802) format for printing MAC-48 addresses in human-friendly form is six groups of two hexadecimal digits (0 to 9 or A to F), separated by hyphens (e.g. 01-23-45-67-89-AB).
#Example
#For inputString = "00-1B-63-84-45-E6", the output should be
#isMAC48Address(inputString) = true;
#For inputString = "Z1-1B-63-84-45-E6", the output should be
#isMAC48Address(inputString) = false;
#For inputString = "not a MAC-48 address", the output should be
#isMAC48Address(inputString) = false.
#Input/Output
#[time limit] 4000ms (py)
#[input] string inputString
#Constraints:
#15 ≤ inputString.length ≤ 20.
#[output] boolean
#true if inputString corresponds to MAC-48 address naming rules, false otherwise.
def isMAC48Address(inputString):
if len(inputString)!=17:
return False
inputStringSplit = inputString.split('-')
if len(inputStringSplit)!=6:
return False
for i in range(0,len(inputStringSplit)):
if len(inputStringSplit[i])!=2:
return False
if (("0"<=inputStringSplit[i][0]<="9" or "A"<=inputStringSplit[i][0]<="F") and ("0"<=inputStringSplit[i][1]<="9" or "A"<=inputStringSplit[i][1]<="F")):
return True
else:
return False
|
Rust
|
UTF-8
| 32,586
| 2.921875
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
// Copyright 2017 Daniel P. Clark & other digits Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
//
#![deny(missing_docs,trivial_casts,trivial_numeric_casts,
missing_debug_implementations, missing_copy_implementations,
unsafe_code,unused_import_braces,unused_qualifications)
]
//! # digits
//!
//! The digits crate is a linked list implementation of a score card flipper. But
//! in this case it's with any characters you want and you can enumerate through
//! possibilities beyond the numeric limits intrinsic in basic numerc types like `u64`.
//!
//! Primary use case would be brute forcing character sequences.
#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]
extern crate base_custom;
#[doc(no_inline)]
pub use base_custom::BaseCustom;
use std::fmt;
use std::ops::{
Add,AddAssign,Mul,MulAssign,BitXor,BitXorAssign
};
use std::cmp::{PartialOrd,Ordering};
extern crate array_tool;
mod internal;
use internal::step_map::StepMap;
use internal::carry_add::{CappedAdd,SignNum,Sign};
/// This struct acts similar to a full number with a custom numeric character base
/// which is provided and mapped via a `BaseCustom` instance.
///
/// The underlying implementation for Digits is a linked list where all the methods recurse
/// as far as need to to implement the operations.
#[derive(Clone)]
pub struct Digits {
mapping: BaseCustom<char>,
digit: u64,
left: Option<Box<Digits>>,
}
impl Digits {
/// Add two Digits instances together.
///
/// # Example
///
/// ```
/// use digits::prelude::*;
///
/// let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
///
/// let eleven = Digits::new(base10.clone(), "11".to_string());
/// let two = Digits::new(base10, "2".to_string());
///
/// assert_eq!(eleven.add(two).to_s(), "13");
/// ```
///
/// # Output
///
/// ```text
/// "13"
/// ```
///
/// _This will panic if numeric bases are not the same._
pub fn add(&self, other: Self) -> Self {
assert!(self.base() == other.base());
let mut result: Vec<u64> = vec![];
let mut carry: u64 = 0;
let mut c_self: Option<Box<Digits>> = Some(Box::new(self.clone()));
let mut o_self: Option<Box<Digits>> = Some(Box::new(other));
let mut remainder: Option<SignNum<u64>>;
loop {
if carry == 0 && c_self == None && o_self == None { break }
let cs = c_self.clone();
let os = o_self.clone();
result.push(
{
let cr = carry.capped_add({
cs.unwrap_or_else(|| Box::new(self.zero())).digit +
os.unwrap_or_else(|| Box::new(self.zero())).digit},
(0, self.base() as u64)
);
remainder = cr.carry;
cr.sign_num.num
}
);
let guard = remainder.unwrap_or_else(|| SignNum::new(0));
match guard.sign {
Sign::Plus => {
carry = guard.num;
},
Sign::Minus => unimplemented!()
}
c_self = c_self.unwrap_or_else(|| Box::new(self.zero())).left;
o_self = o_self.unwrap_or_else(|| Box::new(self.zero())).left;
}
result.reverse();
self.new_mapped(&result).unwrap()
}
/// Returns a vector of each characters position mapping
pub fn as_mapping_vec(&self) -> Vec<u64> {
match self.left {
Some(ref l) => {
let mut result = l.as_mapping_vec();
result.extend(vec![self.digit]);
result
},
None => vec![self.digit],
}
}
/// Make numeric base size publicly available on Digits
pub fn base(&self) -> usize {
self.mapping.base as usize
}
/// Allows you to generate/encode a Digits from a `u64` or other `Digits` even if they are of a
/// different numeric base.
///
/// # Example
///
/// ```
/// use digits::prelude::*;
///
/// let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
///
/// let two = Digits::new(base10, "2".to_string());
/// let three = two.gen(3_u64);
///
/// assert_eq!(three.to_s(), "3");
/// ```
pub fn gen<T>(&self, other: T) -> Self
where Self: From<(BaseCustom<char>, T)> {
Digits::from((self.mapping.clone(), other))
}
// the way to recurse and process Digits
fn head_tail(self) -> (u64, Option<Box<Self>>) {
match self.left {
Some(bx) => (self.digit, Some(bx)),
None => (self.digit, None),
}
}
/// Returns true of false based on whether the limit of allowed adjacents is not exceeded.
/// Early termination result when false.
///
/// Same as being a more efficient `self.max_adjacent <= allowed_adjacent`.
pub fn is_valid_adjacent(&self, adjacent: usize) -> bool {
let mut ptr = self;
let mut last_num = self.digit;
let mut last_num_count = 0;
while let Some(ref item) = ptr.left {
if item.digit == last_num {
last_num_count += 1;
} else {
last_num_count = 0;
}
if last_num_count > adjacent { return false; }
last_num = item.digit;
ptr = item;
}
true
}
/// Returns whether the two Digits instances have the same numeric base and
/// character mapping.
///
/// # Example
///
/// ```
/// use digits::prelude::*;
///
/// let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
///
/// let two = Digits::new(base10.clone(), "2".to_string());
/// let three = Digits::new(base10, "3".to_string());
///
/// assert!(two.is_compat(&three));
/// ```
pub fn is_compat(&self, other: &Self) -> bool {
self.mapping == other.mapping
}
// A non-consuming quick end check.
// More efficient than calling `is_zero` when this applies.
fn is_end(&self) -> bool {
self.digit == 0 && match self.left { None => true, _ => false }
}
/// Returns bool value of if the number is one.
pub fn is_one(&self) -> bool {
if self.digit != 1 { return false }
match self.left {
None => { true },
Some(ref bx) => { bx.is_zero() },
}
}
/// Returns bool value of if the number is zero.
pub fn is_zero(&self) -> bool {
if self.digit != 0 { return false }
match self.left {
None => { true },
Some(ref bx) => { bx.is_zero() },
}
}
/// Returns a `usize` of the total linked list length.
pub fn length(&self) -> usize {
match self.left {
None => 1,
Some(ref l) => { l.length() + 1 }
}
}
/// Give the count for the maximum of the same adjacent characters for this digit.
///
/// Note that adjacent is a non-inclusive count. So for 7 numbers it's 1 adjacent
/// to 6 which will return 6.
///
/// # Example
///
/// ```
/// use digits::prelude::*;
///
/// let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
/// let num = Digits::new(base10, "557771".to_string());
///
/// assert_eq!(num.max_adjacent(), 2);
/// ```
///
/// The above example demonstrates that there are 2 adjacent 7s next to a 7
/// and that is the biggest adjacent set of numbers.
pub fn max_adjacent(&self) -> usize {
self.max_adj(self.digit, 0, 1) - 1
}
fn max_adj(&self, last_num: u64, last_num_count: usize, max_count: usize) -> usize {
let mut lnc = last_num_count;
if self.digit == last_num { lnc += 1; } else { lnc = 1; }
let max_count = std::cmp::max(lnc, max_count);
match self.left {
None => max_count,
Some(ref l) => { l.max_adj(self.digit, lnc, max_count) },
}
}
/// Multiply two Digits instances together.
///
/// # Example
///
/// ```
/// use digits::prelude::*;
///
/// let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
///
/// let eleven = Digits::new(base10.clone(), "11".to_string());
/// let two = Digits::new(base10, "2".to_string());
///
/// assert_eq!(eleven.mul(two).to_s(), "22");
/// ```
///
/// # Output
///
/// ```text
/// "22"
/// ```
///
/// _This will panic if numeric bases are not the same._
pub fn mul(&self, other: Self) -> Self {
self.multiply(other, 0)
}
// Internal implementation for multiply. Needs the recursive
// value of powers of ten for addition.
fn multiply(&self, other: Digits, power_of_ten: usize) -> Self {
assert!(self.base() == other.base());
let mut position: usize = power_of_ten;
let mut o = Some(Box::new(other));
let mut result = self.zero();
while let Some(thing) = o.clone() {
let (dgt, tail) = thing.head_tail();
o = tail;
let mltply = self.propagate((self.digit * dgt).to_string()).pow_ten(position);
let current_digit = self.propagate(self.mapping.gen(dgt).to_string());
if let Some(ref bx) = self.left {
result.mut_add_internal(bx.clone().multiply(current_digit, position + 1), true);
};
result.mut_add_internal( mltply, true );
position += 1;
}
result
}
/// Add two Digits instances together.
///
/// # Example
///
/// ```
/// use digits::prelude::*;
///
/// let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
///
/// let mut eleven = Digits::new(base10.clone(), "11".to_string());
/// let two = Digits::new(base10, "2".to_string());
///
/// assert_eq!(eleven.mut_add(two).to_s(), "13");
/// ```
///
/// # Output
///
/// ```text
/// "13"
/// ```
///
/// _This will panic if numeric bases are not the same._
pub fn mut_add(&mut self, other: Self) -> Self {
self.mut_add_internal(other, false)
}
fn mut_add_internal(&mut self, other: Digits, trim: bool) -> Self {
assert!(self.base() == other.base());
if other.is_end() { return self.clone(); };
let (last, rest) = other.head_tail();
// sums current single digit
let added = self.propagate(self.mapping.gen(last + self.digit));
let (l, r) = added.head_tail();
self.digit = l;
// sums for left
let mut intermediate = Digits::new_zero(self.mapping.clone());
if let Some(dg) = r { intermediate.mut_add_internal(dg.replicate(), trim); }
if let Some(dg) = rest { intermediate.mut_add_internal(dg.replicate(), trim); }
match self.left.clone() {
Some(bx) => {
self.set_left( bx.replicate().mut_add_internal(intermediate, trim).clone(), trim );
},
None => {
if !intermediate.is_zero() {
self.set_left( intermediate, trim );
}
}
};
self.clone()
}
/// Multiply two Digits instances together.
///
/// # Example
///
/// ```
/// use digits::prelude::*;
///
/// let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
///
/// let mut eleven = Digits::new(base10.clone(), "11".to_string());
/// let two = Digits::new(base10, "2".to_string());
///
/// assert_eq!(eleven.mut_mul(two).to_s(), "22");
/// ```
///
/// # Output
///
/// ```text
/// "22"
/// ```
///
/// _This will panic if numeric bases are not the same._
pub fn mut_mul(&mut self, other: Self) -> Self {
let (d, r) = self.multiply(other, 0).head_tail();
self.digit = d;
if let Some(rest) = r { self.set_left(rest.replicate(), true); }
self.clone()
}
/// Creates a new Digits instance with the provided character set and value.
///
/// The first parameter must be a BaseCustom object which defines and maps all values.
/// The second parameter is a string value with all valid characters from the BaseCustom set.
///
/// # Example
///
/// ```
/// use digits::prelude::*;
///
/// let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
/// let nine = Digits::new(base10, "9".to_string());
///
/// assert_eq!(nine.to_s(), "9");
/// ```
pub fn new<S>(mapping: BaseCustom<char>, number: S) -> Digits
where S: Into<String> {
let number = number.into();
if number.is_empty() { return Digits { mapping: mapping, digit: 0, left: None }; };
let (last, rest) = {
let mut n = number.chars().rev();
(n.next().unwrap(), n.rev().collect::<String>())
};
let continuation = {
if rest.is_empty() {
None
} else {
Some(Box::new(Digits::new(mapping.clone(), rest)))
}
};
Digits {
mapping: mapping.clone(),
digit: mapping.decimal(last.to_string()),
left: continuation,
}
}
/// Create a Digits from a Vector of from zero positional mappings for custom Digits numeric
/// base.
///
/// # Example
///
/// ```
/// use digits::prelude::*;
///
/// let base16 = BaseCustom::<char>::new("0123456789abcdef".chars().collect());
/// let builder = Digits::new(base16, "".to_string());
/// let num = builder.new_mapped(&vec![1,0,2,1]).ok().unwrap();
///
/// assert_eq!(num.to_s(), "1021");
/// ```
///
/// If zero had been Z in the example above the same vector `vec![1,0,2,1]` would have
/// produced a Digits instance of a Hex value of "1Z21". The vector is the litteral positional
/// map of the character(s) via an index from zero regardless of numeric base.
///
/// If a number provided within the vector is higher than the numeric base size then the method
/// will return an `Err(&'static str)` Result.
pub fn new_mapped(&self, places: &[u64]) -> Result<Self, &'static str> {
if places.iter().any(|&x| x >= self.mapping.base) {
return Err("Character mapping out of range!");
}
let num = places.iter().fold("".to_string(), |mut acc, &x| {
acc.push(*self.mapping.nth(x as usize).unwrap());
acc
}
);
Ok(Digits::new(self.mapping.clone(), num))
}
/// Creates a new Digits instance with value of one and the provided character mapping.
///
/// # Example
///
/// ```
/// use digits::prelude::*;
///
/// let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
/// let one = Digits::new_one(base10);
///
/// assert_eq!(one.to_s(), "1");
/// ```
pub fn new_one(mapping: BaseCustom<char>) -> Self {
Digits { mapping: mapping, digit: 1, left: None }
}
/// Creates a new Digits instance with value of zero and uses the provided character mapping.
///
/// # Example
///
/// ```
/// use digits::prelude::*;
///
/// let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
/// let zero = Digits::new_zero(base10);
///
/// assert_eq!(zero.to_s(), "0");
/// ```
pub fn new_zero(mapping: BaseCustom<char>) -> Self {
Digits { mapping: mapping, digit: 0, left: None }
}
/// Returns the next Digits in incrementing that only allows the given number of
/// adjacent number duplicates.
///
/// _This will panic! if numeric base is less than 4._
///
/// # Example
///
/// ```
/// use digits::prelude::*;
///
/// let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
/// let mut num = Digits::new(base10, "98".to_string());
///
/// assert_eq!(num.next_non_adjacent(0).to_s(), "101");
/// ```
pub fn next_non_adjacent(&mut self, adjacent: usize) -> Self {
self.prep_non_adjacent(adjacent);
self.step_non_adjacent(adjacent)
}
/// Creates a new Digits instance with value of one and uses the current character mapping.
///
/// # Example
///
/// ```
/// use digits::prelude::*;
///
/// let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
/// let nine = Digits::new(base10, "9".to_string());
/// let one = nine.one();
///
/// assert_eq!(one.to_s(), "1");
/// ```
pub fn one(&self) -> Self {
Digits::new_one(self.mapping.clone())
}
/// The “pinky” is the smallest digit
/// a.k.a. current digit in the linked list
/// a.k.a. the right most digit.
/// This will be a `char` value for that digit.
pub fn pinky(&self) -> char {
self.mapping.char(self.digit as usize).unwrap()
}
/// Multiplies self times the power-of given Digits parameter.
///
/// # Example
///
/// ```
/// use digits::prelude::*;
///
/// let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
///
/// let mut eleven = Digits::new(base10.clone(), "11".to_string());
/// let two = Digits::new(base10, "2".to_string());
///
/// assert_eq!(eleven.pow(two).to_s(), "121");
/// ```
///
/// # Output
///
/// ```text
/// "121"
/// ```
pub fn pow(&mut self, mut pwr: Self) -> Self {
if pwr.is_zero() { return self.one(); }
let copy = self.clone();
loop {
if pwr.is_one() {
break
} else {
self.mut_mul(copy.clone());
}
pwr.pred_till_zero();
}
self.clone()
}
// multiply self by 10ⁿ without using typical multiplication
fn pow_ten(&self, positions: usize) -> Self {
let mut result: Digits = self.clone();
for _ in 0..positions {
let original = result;
result = Digits::new_zero(self.mapping.clone());
result.set_left(original, true);
}
result
}
/// Minuses one unless it's zero, then it just returns a Digits instance of zero.
pub fn pred_till_zero(&mut self) -> Self {
if self.is_zero() { return self.clone(); }
if self.digit == 0 {
self.digit = self.mapping.base - 1;
match self.left.clone() {
Some(ref mut bx) => self.set_left(bx.pred_till_zero(), false),
None => self.left = None
}
} else {
self.digit -= 1;
}
self.clone()
}
/// Sometimes given starting Digits have more adjacent characters than is desired
/// when proceeding with non-adjacent steps. This method provides a valid initial
/// state for `step_non_adjacent`'s algorithm to not miss any initial steps.
///
/// _This method is used internally for `next_non_adjacent`.
///
/// _This will panic! if numeric base is less than 4._
///
/// # Example
///
/// ```
/// use digits::prelude::*;
///
/// let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
/// let mut num = Digits::new(base10, "0003".to_string());
///
/// assert_eq!(num.prep_non_adjacent(1).to_s(), "0009");
/// ```
///
/// In the example above the prep moves to a valid state of "0010" and then
/// minuses one to "0009" so that `step_non_adjacent` will add 1 and return to the
/// valid state of "0010" for this one-adjacent scenario.
///
/// For performance in your own applications use this method once and continue iterating
/// with `step_non_adjacent`.
///
/// For convenience you may just use `next_non_adjacent` instead of prep and step.
pub fn prep_non_adjacent(&mut self, adjacent: usize) -> Self {
assert!(self.mapping.base > 3, "\n\n WARNING!\n\n \"You may not use non-adjacent stepping with numeric bases of less than 4!\"\n\n");
if self.is_valid_adjacent(adjacent) {
return self.clone();
}
let mut v = self.as_mapping_vec();
'outer: loop {
let mut last_num: Option<u64> = None;
let mut last_num_count = 0;
let w = v.clone();
let itr = w.iter().enumerate();
for (i, item) in itr {
if last_num == None {
last_num = Some(*item);
continue;
}
if let Some(val) = last_num {
if item == &val {
last_num_count += 1;
} else {
last_num_count = 0;
}
if last_num_count > adjacent {
let i = i + 1;
let mut d = self.new_mapped(&v[0..i].to_vec()).ok().unwrap();
d.succ();
let mut new_v = d.as_mapping_vec();
for _ in v[i..v.len()].iter() {
new_v.push(0)
}
v = new_v;
continue 'outer;
}
}
last_num = Some(*item);
}
break;
}
let result = self.new_mapped(&v).ok().unwrap().pred_till_zero();
self.digit = result.digit;
self.left = result.left.clone();
result
}
/// Creates a new Digits instance with the internal character set and given value.
///
/// The parameter is a string value with all valid characters from the BaseCustom set.
///
/// # Example
///
/// ```
/// use digits::prelude::*;
///
/// let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
/// let nine = Digits::new(base10, "9".to_string());
/// let forty_two = nine.propagate("42".to_string());
///
/// assert_eq!(forty_two.to_s(), "42");
/// ```
pub fn propagate<S>(&self, number: S) -> Self
where S: Into<String> {
Digits::new(self.mapping.clone(), number)
}
/// Right count of digits character index.
///
/// Returns a `usize` of how many Digits values from the right
/// match the BaseCustom index given for number.
///
/// # Example
///
/// ```
/// use digits::prelude::*;
///
/// let base10 = BaseCustom::<char>::new("ABC3456789".chars().collect());
/// let num = Digits::new(base10, "34BBB".to_string());
///
/// assert_eq!(num.rcount(1), 3);
/// ```
///
/// # Output
///
/// ```text
/// 3
/// ```
pub fn rcount(&self, character_index: u8) -> usize {
if let Some(ref d) = self.left {
if self.digit == u64::from(character_index) {
return d.rcount(character_index) + 1;
}
} else if self.digit == u64::from(character_index) {
return 1;
}
0
}
/// An alias for `clone`. _Useful for unboxing._
pub fn replicate(self) -> Self { self.clone() }
// logic for setting left linked list continuation
fn set_left(&mut self, d: Digits, trim: bool) {
if trim && d.is_end() {
self.left = None;
} else {
self.left = Some(Box::new(d));
}
}
/// Returns the next Digits in incrementing that only allows the given number of
/// adjacent number duplicates.
///
/// _This will panic! if numeric base is less than 4._
///
/// **NOTE:** _This assumes the starting state is valid for given non adjacent characters.
/// If you want to ensure this please use prep_adjacent before this, or just use
/// `next_non_adjacent` to handle them both._
///
/// # Example
///
/// ```
/// use digits::prelude::*;
///
/// let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
/// let mut num = Digits::new(base10, "98".to_string());
///
/// assert_eq!(num.step_non_adjacent(0).to_s(), "101");
/// ```
pub fn step_non_adjacent(&mut self, adjacent: usize) -> Self {
let mut step_map = StepMap::new(self.zero(), adjacent as u8);
let mut v: Self;
loop {
let mut builder = self.clone();
v = builder.mut_add(step_map.next().unwrap());
if v.is_valid_adjacent(adjacent) {
break;
}
}
self.digit = v.digit;
self.left = v.left;
self.clone()
}
/// Plus one.
pub fn succ(&mut self) -> Self {
let one = self.one();
self.mut_add_internal(one, false)
}
/// Gives the full value of all digits within the linked list as a String.
pub fn to_s(&self) -> String {
let num = self.mapping.gen(self.digit);
match self.left {
None => num.to_owned(),
Some(ref bx) => format!("{}{}", bx.to_s(), num),
}
}
/// Gives the full value of all digits within the linked list as a String.
pub fn to_string(&self) -> String {
self.to_s()
}
/// Creates a new Digits instance with value of zero and the current character mapping.
///
/// # Example
///
/// ```
/// use digits::prelude::*;
///
/// let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
/// let nine = Digits::new(base10, "9".to_string());
/// let zero = nine.zero();
///
/// assert_eq!(zero.to_s(), "0");
/// ```
pub fn zero(&self) -> Self {
Digits::new_zero(self.mapping.clone())
}
/// Zero fills the left of the current number up to a total character length.
///
/// # Example
///
/// ```
/// use digits::prelude::*;
///
/// let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
/// let mut nine = Digits::new(base10, "9".to_string());
/// nine.zero_fill(4);
///
/// assert_eq!(nine.to_s(), "0009");
/// ```
pub fn zero_fill(&mut self, length: usize) {
if self.length() >= length { return; }
if length == 0 { return; }
match self.left.clone() {
None => {
let mut l = self.zero();
l.zero_fill(length - 1);
self.left = Some(Box::new(l));
}
Some(v) => {
self.set_left(
{
let mut l = v.replicate();
l.zero_fill(length -1 );
l
},
false
)
}
}
}
/// Zero trims the left of the current number.
///
/// # Example
///
/// ```
/// use digits::prelude::*;
///
/// let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
/// let mut nine = Digits::new(base10, "0009".to_string());
/// nine.zero_trim();
///
/// assert_eq!(nine.to_s(), "9");
/// ```
pub fn zero_trim(&mut self) {
let mut lnum: String = "".to_string();
if let Some(ref v) = self.left {
lnum = v.to_s();
}
lnum = lnum.trim_start_matches(*self.mapping.zero()).to_string();
let lval = self.propagate(lnum);
self.set_left(lval, true);
}
}
/// Reverse mutates self into a reversed self.
pub trait Reverse {
/// # Example
///
/// ```
/// use digits::{BaseCustom,Digits,Reverse};
///
/// let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
/// let mut nine = Digits::new(base10, "0009".to_string());
///
/// nine.reverse();
///
/// assert_eq!(nine.to_s(), "9000");
/// ```
fn reverse(&mut self);
}
impl Reverse for Digits {
fn reverse(&mut self) {
let mut curr_node: Option<Digits> = Some(self.clone());
let mut prev_node: Option<Digits> = None;
while curr_node != None {
let cn = curr_node.unwrap();
let next_node = if let Some(n) = cn.clone().left {
Some(n.replicate())
} else { None };
let mut c = cn;
if let Some(prev) = prev_node {
c.set_left(prev, false);
} else {
c.left = None;
}
prev_node = Some(c);
curr_node = next_node;
}
let p = prev_node.unwrap();
self.digit = p.digit;
self.left = p.left;
}
}
#[allow(missing_docs)]
pub trait Into<String> {
fn into(self) -> String;
}
impl From<(BaseCustom<char>, u64)> for Digits {
fn from(d: (BaseCustom<char>, u64)) -> Digits {
let mapping = d.0;
let value = d.1;
Digits::new(mapping.clone(), mapping.gen(value))
}
}
impl From<(BaseCustom<char>, Digits)> for Digits {
fn from(d: (BaseCustom<char>, Digits)) -> Digits {
let mapping = d.0;
let source = d.1;
let from_base = source.mapping.base;
let mut result = Digits::new_zero(mapping.clone());
let mut pointer: Option<Box<Digits>> = Some(Box::new(source.clone()));
let mut position = 0;
// Down-Casting
if from_base >= mapping.base {
while let Some(bx) = pointer {
let (h, t) = bx.head_tail();
if h != 0 { // speed optimization
result.mut_add_internal(
Digits::new(mapping.clone(), mapping.gen(h)).mul(
Digits::new(mapping.clone(), mapping.gen(from_base)).
pow(source.gen(position))
),
true
);
}
position += 1;
pointer = t;
}
} else { // Up-Casting
while let Some(bx) = pointer {
let (h, t) = bx.head_tail();
if h != 0 { // speed optimization
result.mut_add_internal(
// This implementation is limited by the max of usize
Digits::new(mapping.clone(), mapping.gen(h * from_base.pow(position as u32))),
true
);
}
position += 1;
pointer = t;
}
}
result
}
}
impl From<(Digits, Digits)> for Digits {
fn from(d: (Digits, Digits)) -> Digits {
if d.0.base() == d.1.base() { return d.1; }
Digits::from((d.0.mapping, d.1))
}
}
impl From<Digits> for String {
fn from(d: Digits) -> String {
d.to_s()
}
}
impl Into<String> for Digits {
fn into(self) -> String {
self.to_s()
}
}
impl Into<String> for String {
fn into(self) -> String {
self.clone()
}
}
impl fmt::Display for Digits {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Digits — (Character: '{}', Decimal Value: {}{})",
self.mapping.gen(self.digit), self.digit, {
match self.left {
None => "".to_string(),
Some(ref l) => format!(", With Preceeding: '{}'", l.to_s()),
}
}
)
}
}
impl fmt::Debug for Digits {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} with base: {:?}", self, self.mapping)
}
}
impl PartialEq for Digits {
fn eq(&self, other: &Digits) -> bool {
self.mapping == other.mapping &&
self.digit == other.digit &&
self.left == other.left
}
}
impl Add for Digits {
type Output = Self;
fn add(self, other: Self) -> Self {
self.clone().mut_add(other)
}
}
impl AddAssign for Digits {
fn add_assign(&mut self, other: Self) {
self.mut_add(other);
}
}
impl Mul for Digits {
type Output = Self;
fn mul(self, other: Self) -> Self {
self.multiply(other, 0)
}
}
impl MulAssign for Digits {
fn mul_assign(&mut self, other: Self) {
self.mut_mul(other);
}
}
impl BitXor for Digits {
type Output = Self;
fn bitxor(self, other: Self) -> Self {
self.clone().pow(other)
}
}
impl BitXorAssign for Digits {
fn bitxor_assign(&mut self, other: Self) {
self.pow(other);
}
}
impl PartialOrd for Digits {
fn partial_cmp(&self, other: &Digits) -> Option<Ordering> {
assert!(self.mapping == other.mapping);
let mut result: Option<Ordering>;
let mut a: Self = self.clone();
let mut b: Self = other.clone();
result = a.digit.partial_cmp(&b.digit);
while let (Some(x),Some(y)) = (a.left.clone(), b.left.clone()) {
a = x.replicate();
b = y.replicate();
match a.digit.partial_cmp(&b.digit) {
Some(Ordering::Equal) | None => (),
Some(change) => { result = Some(change); },
}
}
if a.left.is_some() && !b.left.is_some() && !a.left.clone().unwrap().is_zero() {
result = Some(Ordering::Greater);
}
if !a.left.is_some() && b.left.is_some() && !b.left.unwrap().is_zero() {
result = Some(Ordering::Less);
}
result
}
}
#[allow(missing_docs)]
pub mod prelude {
#[doc(inline)]
pub use super::Digits;
#[doc(inline)]
pub use base_custom::BaseCustom;
}
impl Default for Digits {
fn default() -> Digits {
let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
Digits::new_zero(base10)
}
}
/// A default Radix modules including most common numeric bases.
pub mod radices {
use super::*;
/// Binary implementation of `BaseCustom`
pub fn binary_base() -> BaseCustom<char> {
BaseCustom::<char>::new("01".chars().collect())
}
/// Octal implementation of `BaseCustom`
pub fn octal_base() -> BaseCustom<char> {
BaseCustom::<char>::new("01234567".chars().collect())
}
/// Decimal implementation of `BaseCustom`
pub fn decimal_base() -> BaseCustom<char> {
BaseCustom::<char>::new("0123456789".chars().collect())
}
/// Hexadecimal implementation of `BaseCustom`
pub fn hex_base() -> BaseCustom<char> {
BaseCustom::<char>::new("0123456789ABCDEF".chars().collect())
}
/// Lowercase hexadecimal implementation of `BaseCustom`
pub fn hexl_base() -> BaseCustom<char> {
BaseCustom::<char>::new("0123456789abcdef".chars().collect())
}
}
/// Default Radix type conversion for `Digits`
pub trait Radix {
/// Convert current `Digits` to binary
fn binary(&self) -> Self;
/// Convert current `Digits` to octal
fn octal(&self) -> Self;
/// Convert current `Digits` to decimal
fn decimal(&self) -> Self;
/// Convert current `Digits` to hexadecimal
fn hex(&self) -> Self;
/// Convert current `Digits` to lowercase hexadecimal
fn hexl(&self) -> Self;
}
impl Radix for Digits {
fn binary(&self) -> Digits {
Digits::from((radices::binary_base(), self.clone()))
}
fn octal(&self) -> Digits {
Digits::from((radices::octal_base(), self.clone()))
}
fn decimal(&self) -> Digits {
Digits::from((radices::decimal_base(), self.clone()))
}
fn hex(&self) -> Digits {
Digits::from((radices::hex_base(), self.clone()))
}
fn hexl(&self) -> Digits {
Digits::from((radices::hexl_base(), self.clone()))
}
}
|
JavaScript
|
UTF-8
| 653
| 2.734375
| 3
|
[] |
no_license
|
const theme = (() => {
const init = () => {
let hour = new Date().getHours();
const body = document.getElementsByTagName("body")[0];
if (hour >= 18 || hour < 6) {
body.setAttribute("class", "theme--dark");
} else {
body.setAttribute("class", "theme--default");
}
};
const handleThemeToggle = () => {
const body = document.getElementsByTagName("body")[0];
if (body.classList.contains("theme--default")) {
body.setAttribute("class", "theme--dark");
} else {
body.setAttribute("class", "theme--default");
}
};
return {
init,
handleThemeToggle,
};
})();
export default theme;
|
Python
|
UTF-8
| 5,351
| 2.890625
| 3
|
[] |
no_license
|
import torch
from torch import nn
import numpy as np
import math
import torch.nn.functional as F
from Resnet_demo import ResNet18
class SincConv_fast(nn.Module):
"""Sinc-based convolution
Parameters
----------
in_channels : `int`
Number of input channels. Must be 1.
out_channels : `int`
Number of filters.
kernel_size : `int`
Filter length.
sample_rate : `int`, optional
Sample rate. Defaults to 16000.
Usage
-----
See `torch.nn.Conv1d`
Reference
---------
Mirco Ravanelli, Yoshua Bengio,
"Speaker Recognition from raw waveform with SincNet".
https://arxiv.org/abs/1808.00158
"""
@staticmethod
def to_mel(hz):
return 2595 * np.log10(1 + hz / 700)
@staticmethod
def to_hz(mel):
return 700 * (10 ** (mel / 2595) - 1)
def __init__(self, out_channels, kernel_size, sample_rate=16000, in_channels=1,
stride=1, padding=0, dilation=1, bias=False, groups=1, min_low_hz=50, min_band_hz=50):
super(SincConv_fast, self).__init__()
if in_channels != 1:
# msg = (f'SincConv only support one input channel '
# f'(here, in_channels = {in_channels:d}).')
msg = "SincConv only support one input channel (here, in_channels = {%i})" % (in_channels)
raise ValueError(msg)
self.out_channels = out_channels
self.kernel_size = kernel_size
# Forcing the filters to be odd (i.e, perfectly symmetrics)
if kernel_size % 2 == 0:
self.kernel_size = self.kernel_size + 1
self.stride = stride
self.padding = padding
self.dilation = dilation
if bias:
raise ValueError('SincConv does not support bias.')
if groups > 1:
raise ValueError('SincConv does not support groups.')
self.sample_rate = sample_rate
self.min_low_hz = min_low_hz
self.min_band_hz = min_band_hz
# initialize filterbanks such that they are equally spaced in Mel scale
low_hz = 30
high_hz = self.sample_rate / 2 - (self.min_low_hz + self.min_band_hz)
mel = np.linspace(self.to_mel(low_hz),
self.to_mel(high_hz),
self.out_channels + 1)
hz = self.to_hz(mel)
# filter lower frequency (out_channels, 1)
self.low_hz_ = nn.Parameter(torch.Tensor(hz[:-1]).view(-1, 1))
# filter frequency band (out_channels, 1)
self.band_hz_ = nn.Parameter(torch.Tensor(np.diff(hz)).view(-1, 1))
# Hamming window
# self.window_ = torch.hamming_window(self.kernel_size)
n_lin = torch.linspace(0, (self.kernel_size / 2) - 1,
steps=int((self.kernel_size / 2))) # computing only half of the window
self.window_ = 0.54 - 0.46 * torch.cos(2 * math.pi * n_lin / self.kernel_size);
# (1, kernel_size/2)
n = (self.kernel_size - 1) / 2.0
self.n_ = 2 * math.pi * torch.arange(-n, 0).view(1,
-1) / self.sample_rate # Due to symmetry, I only need half of the time axes
def forward(self, waveforms):
"""
Parameters
----------
waveforms : `torch.Tensor` (batch_size, 1, n_samples)
Batch of waveforms.
Returns
-------
features : `torch.Tensor` (batch_size, out_channels, n_samples_out)
Batch of sinc filters activations.
"""
self.n_ = self.n_.to(waveforms.device)
self.window_ = self.window_.to(waveforms.device)
low = self.min_low_hz + torch.abs(self.low_hz_)
high = torch.clamp(low + self.min_band_hz + torch.abs(self.band_hz_), self.min_low_hz,
self.sample_rate / 2) # clamp约束函数将input约束到min_low_hz至sample_rate/2内
band = (high - low)[:, 0]
f_times_t_low = torch.matmul(low, self.n_)
f_times_t_high = torch.matmul(high, self.n_)
band_pass_left = ((torch.sin(f_times_t_high) - torch.sin(f_times_t_low)) / (
self.n_ / 2)) * self.window_ # Equivalent of Eq.4 of the reference paper (SPEAKER RECOGNITION FROM RAW WAVEFORM WITH SINCNET). I just have expanded the sinc and simplified the terms. This way I avoid several useless computations.
band_pass_center = 2 * band.view(-1, 1)
band_pass_right = torch.flip(band_pass_left, dims=[1])
band_pass = torch.cat([band_pass_left, band_pass_center, band_pass_right], dim=1)
band_pass = band_pass / (2 * band[:, None]) # 此处依然为[80,251]
self.filters = (band_pass).view(
self.out_channels, 1, self.kernel_size) # 此处输出size为[80,1,251]
return F.conv1d(waveforms, self.filters, stride=self.stride, padding=self.padding, dilation=self.dilation,
bias=None, groups=1)
def tes():
net = SincConv_fast(out_channels=80,kernel_size=251,sample_rate=16000,in_channels=1)
resnet = ResNet18()
dat = torch.randn([2,1,3200])
sincoutput= net.forward(dat)
a = F.max_pool1d(abs(sincoutput),3)
a_Resnet = resnet(a.unsqueeze(1))
# MLP = nn.Linear(983,257)
# MLPoutput = MLP(a)
# MLPoutput = MLPoutput.squeeze()
return a_Resnet
tes()
|
Java
|
UTF-8
| 10,535
| 1.617188
| 2
|
[
"BSD-3-Clause",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-unknown"
] |
permissive
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.internal.cache;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.apache.logging.log4j.Logger;
import org.apache.geode.DataSerializer;
import org.apache.geode.SystemFailure;
import org.apache.geode.cache.Cache;
import org.apache.geode.distributed.internal.ClusterDistributionManager;
import org.apache.geode.distributed.internal.DistributionManager;
import org.apache.geode.distributed.internal.DistributionMessage;
import org.apache.geode.distributed.internal.HighPriorityDistributionMessage;
import org.apache.geode.distributed.internal.InternalDistributedSystem;
import org.apache.geode.distributed.internal.MessageWithReply;
import org.apache.geode.distributed.internal.ReplyException;
import org.apache.geode.distributed.internal.ReplyMessage;
import org.apache.geode.distributed.internal.ReplyProcessor21;
import org.apache.geode.distributed.internal.ReplySender;
import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
import org.apache.geode.internal.InternalDataSerializer;
import org.apache.geode.internal.cache.partitioned.PartitionMessage;
import org.apache.geode.internal.serialization.DeserializationContext;
import org.apache.geode.internal.serialization.SerializationContext;
import org.apache.geode.logging.internal.log4j.api.LogService;
/**
* Message to all the peers to ask which member hosts the transaction for the given transaction id
*/
public class FindRemoteTXMessage extends HighPriorityDistributionMessage
implements MessageWithReply {
private static final Logger logger = LogService.getLogger();
private TXId txId;
private int processorId;
public FindRemoteTXMessage() {
// do nothing
}
public FindRemoteTXMessage(TXId txid, int processorId, Set recipients) {
super();
setRecipients(recipients);
txId = txid;
this.processorId = processorId;
}
/**
* Asks all the peers if they host a transaction for the given txId
*
* @param txId the transaction id
* @return reply processor containing memberId of the member that hosts the transaction and a
* recently committed transactionMessage if any
*/
public static FindRemoteTXMessageReplyProcessor send(Cache cache, TXId txId) {
final InternalDistributedSystem system =
(InternalDistributedSystem) cache.getDistributedSystem();
DistributionManager dm = system.getDistributionManager();
Set recipients = dm.getOtherDistributionManagerIds();
FindRemoteTXMessageReplyProcessor processor =
new FindRemoteTXMessageReplyProcessor(dm, recipients, txId);
FindRemoteTXMessage msg = new FindRemoteTXMessage(txId, processor.getProcessorId(), recipients);
dm.putOutgoing(msg);
return processor;
}
@Override
public int getDSFID() {
return FIND_REMOTE_TX_MESSAGE;
}
@Override
protected void process(ClusterDistributionManager dm) {
boolean sendReply = true;
Throwable thr = null;
try {
if (logger.isDebugEnabled()) {
logger.debug("processing {}", this);
}
FindRemoteTXMessageReply reply = new FindRemoteTXMessageReply();
InternalCache cache = dm.getCache();
if (cache != null) {
TXManagerImpl mgr = (TXManagerImpl) cache.getCacheTransactionManager();
mgr.waitForCompletingTransaction(txId); // in case there is a lost commit going on
reply.isHostingTx = mgr.isHostedTxInProgress(txId) || mgr.isHostedTxRecentlyCompleted(txId);
if (!reply.isHostingTx) {
// lookup in CMTTracker if a partial commit message exists
TXCommitMessage partialMessage = TXCommitMessage.getTracker().getTXCommitMessage(txId);
if (partialMessage != null) {
reply.txCommitMessage = partialMessage;
reply.isPartialCommitMessage = true;
}
// cleanup the local txStateProxy fixes bug 43069
mgr.removeHostedTXState(txId, true);
}
}
reply.setRecipient(getSender());
reply.setProcessorId(processorId);
getReplySender(dm).putOutgoing(reply);
sendReply = false;
if (logger.isDebugEnabled()) {
logger.debug("TX: FoundRemoteTXMessage: isHostingTx for txid:{}? {} isPartialCommit? {}",
txId, reply.isHostingTx, reply.isPartialCommitMessage);
}
} catch (VirtualMachineError err) {
SystemFailure.initiateFailure(err);
// If this ever returns, rethrow the error. We're poisoned
// now, so don't let this thread continue.
throw err;
} catch (Throwable t) {
// Whenever you catch Error or Throwable, you must also
// catch VirtualMachineError (see above). However, there is
// _still_ a possibility that you are dealing with a cascading
// error condition, so you also need to check to see if the JVM
// is still usable:
SystemFailure.checkFailure();
if (sendReply) {
thr = t;
}
} finally {
ReplySender rs = getReplySender(dm);
if (sendReply && (processorId != 0 || (rs != dm))) {
ReplyException rex = null;
if (thr != null) {
rex = new ReplyException(thr);
}
ReplyMessage.send(getSender(), processorId, rex, getReplySender(dm));
}
}
}
@Override
public String toString() {
StringBuilder buff = new StringBuilder();
String className = getClass().getName();
buff.append(className.substring(
className.indexOf(PartitionMessage.PN_TOKEN) + PartitionMessage.PN_TOKEN.length())); // partition.<foo>
buff.append("(txId=").append(txId).append("; sender=").append(getSender())
.append("; processorId=").append(processorId);
buff.append(")");
return buff.toString();
}
@Override
public void toData(DataOutput out,
SerializationContext context) throws IOException {
super.toData(out, context);
DataSerializer.writeObject(txId, out);
out.writeInt(processorId);
}
@Override
public void fromData(DataInput in,
DeserializationContext context) throws IOException, ClassNotFoundException {
super.fromData(in, context);
txId = DataSerializer.readObject(in);
processorId = in.readInt();
}
public static class FindRemoteTXMessageReplyProcessor extends ReplyProcessor21 {
private InternalDistributedMember hostingMember;
private TXCommitMessage txCommit;
private final TXId txId;
private final Set<TXCommitMessage> partialCommitMessages = new HashSet<>();
public FindRemoteTXMessageReplyProcessor(DistributionManager dm, Collection initMembers,
TXId txId) {
super(dm, initMembers);
this.txId = txId;
}
@Override
public void process(DistributionMessage msg) {
if (msg instanceof FindRemoteTXMessageReply) {
FindRemoteTXMessageReply reply = (FindRemoteTXMessageReply) msg;
if (reply.isHostingTx) {
hostingMember = msg.getSender();
} else if (reply.isPartialCommitMessage) {
partialCommitMessages.add(reply.txCommitMessage);
}
}
super.process(msg);
}
/**
* @return the member that is hosting the tx
*/
public InternalDistributedMember getHostingMember() {
return hostingMember;
}
@Override
public boolean stillWaiting() {
return hostingMember == null && super.stillWaiting();
}
/**
* @return if hosting member is null, the rebuilt TXCommitMessage from partial TXCommitMessages
* distributed to peers during commit processing
*/
public TXCommitMessage getTxCommitMessage() {
if (txCommit != null) {
return txCommit;
}
if (!partialCommitMessages.isEmpty()) {
TXCommitMessage localTXMessage = TXCommitMessage.getTracker().getTXCommitMessage(txId);
if (localTXMessage != null) {
partialCommitMessages.add(localTXMessage);
}
txCommit = TXCommitMessage.combine(partialCommitMessages);
}
return txCommit;
}
}
@Override
public boolean sendViaUDP() {
return true;
}
/**
* Reply message for {@link FindRemoteTXMessage}. Reply is a boolean to indicate if the recipient
* hosts or has recently hosted the tx state. If the member did host the txState previously, reply
* contains the complete TXCommitMessage representing the tx.
*/
public static class FindRemoteTXMessageReply extends ReplyMessage {
protected boolean isHostingTx;
protected boolean isPartialCommitMessage;
protected TXCommitMessage txCommitMessage;
public FindRemoteTXMessageReply() {}
@Override
public int getDSFID() {
return FIND_REMOTE_TX_REPLY;
}
@Override
public void toData(DataOutput out,
SerializationContext context) throws IOException {
super.toData(out, context);
out.writeBoolean(isHostingTx);
boolean sendTXCommitMessage = txCommitMessage != null;
out.writeBoolean(sendTXCommitMessage);
if (sendTXCommitMessage) {
out.writeBoolean(isPartialCommitMessage);
// since this message is going to a peer, reset client version
txCommitMessage.setClientVersion(null); // fixes bug 46529
InternalDataSerializer.writeDSFID(txCommitMessage, out);
}
}
@Override
public void fromData(DataInput in,
DeserializationContext context) throws IOException, ClassNotFoundException {
super.fromData(in, context);
isHostingTx = in.readBoolean();
if (in.readBoolean()) {
isPartialCommitMessage = in.readBoolean();
txCommitMessage = (TXCommitMessage) InternalDataSerializer.readDSFID(in);
}
}
}
}
|
Java
|
UTF-8
| 148
| 2.078125
| 2
|
[] |
no_license
|
package a3adept;
public class Rice extends IngredientImpl {
public Rice(double amount) {
super(amount, 0.25, "rice", true, false, true);
}
}
|
Markdown
|
UTF-8
| 3,035
| 2.65625
| 3
|
[] |
no_license
|
# Growth Hackers Test Frontend
## Table of contents
- [General info](#general-info)
- [Technologies](#technologies)
- [Quality assurance](#quality-assurance)
- [Setup](#setup)
## General info
The project is a mercado livre clone, that has just some features related with
the e-commerce:
- It list products of diferents graphql sources;
- Has some filters that can be applied by the user, ex: like select which category (source) the user want;
- Can order the products ascending or descending by title;
- Can search for keywords;
- Can paginate throught the selected products (or by all if no filter is applied);
- Has a login/signup system that is stored on the localStorage of the browser;
- The user can select favorites products and can see the list on another page of the project;
P.S: Because of the limitation of the free graphql API's, I load all the data inside the redux, and I do all the process's of pagination on the client-side.
## Technologies
Project is created with:
- @ant-design/icons version 4.0.2
- Ant Design version 4.0.2
- Commitizen version 4.0.3
- Commitlint version 8.3.5
- Cross-env version 7.0.0
- Eslint version 5.16.0
- Faker version 4.1.0
- Husky version 4.2.1
- Lint-staged version 10.0.8
- Jest version 24.9.0
- Prettier version 1.19.1
- Puppeteer version 2.1.1
- React version: 16.13.0
- React-router-dom version 5.1.2
- Reactotron version 0.9
- Redux version: 7.2.0
- Redux-saga version 1.1.3
- Styled-components version 5.0.1
- Stylelint version 13.2.0
## Quality assurance
To assure the quality of the project, some measures have been taken:
- Clean code;
- Eslint & prettier monitoring, alert and fix the code pattern of javascript related files following the airbnb styleguide;
- Directory structure design to be easy to find specific components & features;
- EditorConfig configure to force a code pattern independent of the editor;
- End-to-End test coveraging the "happy path" of a user;
- Git-hooks and automated tools (husky, lint-staged, commitizen, commitlint to padronize commit messages and test procedures before pushing the code on the online repository to avoid sending bug code to it;
- Git-flow to padronize the git structure of branchs and release;
- Unit/Integration test coverage;
- Reactotron to debug the redux & redux-saga middleware more efficiently;
- Stylelint to monitore, alert and fix de code pattern of style related files;
## Setup
To run this project on development mode, install it locally using yarn:
```
$ cd ~/directory-where-the-project-was-cloned/growth-test
$ yarn
$ yarn start
```
To run tests, execute the following command `$ yarn test`
To run the depuration with reactotron, install it locally following those [instructions](https://github.com/infinitered/reactotron/blob/master/docs/installing.md). After the installation of reactotron locally execute reactotron and start the application on development mode.
To run this project on production mode build it using yarn `$ yarn build` then deploy the builded bundle to the desired host.
|
C
|
UTF-8
| 978
| 3.15625
| 3
|
[] |
no_license
|
#include <assert.h>
#include <string.h>
#include "brainfuck.c"
void test_gen_bracket_table(){
assert(gen_bracket_table("[]", 3)[0] == 1);
assert(gen_bracket_table("[[]]", 5)[0] == 3);
assert(gen_bracket_table("[[]]", 5)[1] == 2);
assert(gen_bracket_table("[[[]]][]", 9)[0] == 5);
assert(gen_bracket_table("[[[]]][]", 9)[1] == 4);
assert(gen_bracket_table("[[[]]][]", 9)[2] == 3);
assert(gen_bracket_table("[[[]]][]", 9)[6] == 7);
}
void test_hello_world(){
FILE* out = popen("./brainfuck helloworld.bf 2 >&1", "r");
char output[100];
fgets(output, 100, out);
assert(strcmp(output, "Hello World!\n") == 0);
}
void test_rot13(){
FILE* out = popen("./brainfuck rot13.bf abcdefghijklmnopqrstuvwxyz 2 >&1", "r");
char output[100];
fgets(output, 100, out);
assert(strcmp(output, "nopqrstuvwxyzabcdefghijklm\n") == 0);
}
int main(){
test_gen_bracket_table();
test_hello_world();
test_rot13();
return 0;
}
|
Python
|
UTF-8
| 1,211
| 2.515625
| 3
|
[] |
no_license
|
'''Classes for standard handler responses.'''
"""This file is part of PyF.
PyF 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.
PyF 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 GNU General Public License
along with PyF. If not, see <http://www.gnu.org/licenses/>.
"""
class Responses:
'''Container class for handler responses.'''
def XMLSetup(self, node):
for n in node.children:
if n.node.nodeName == 'response':
if n.node.hasAttribute('id'):
s = n.getValue()
self[n.node.getAttribute('id')] = s
def __init__(self, parent, dict):
self.parent = parent
self.dict = dict
def __getitem__(self, name):
'''Try retrieving value from owner handler's ScriptNode before looking up the dict.'''
return self.dict[name]
def __setitem__(self, name, value):
self.dict[name] = value
|
TypeScript
|
UTF-8
| 968
| 3.46875
| 3
|
[
"Apache-2.0"
] |
permissive
|
import { readFileSync } from 'fs';
type Input = number[][];
type Output = number;
function main() {
const input = readInput();
const output = solve(input);
writeOutput(output);
}
function readInput(): Input {
const raw = readFileSync(0).toString();
const ans: number[][] = [];
let current: number[] = [];
raw.trim().split('\n').forEach((raw) => {
const line = raw.trim();
if (!line) {
ans.push(current);
current = [];
} else {
const value = Number(line);
current.push(value);
}
});
if (current) {
ans.push(current);
}
return ans;
}
function solve(input: Input): Output {
const sumCalories = input.map((elf) => elf.reduce((a, b) => a + b));
const maxCalories = Math.max.apply(null, sumCalories);
return maxCalories;
}
function writeOutput(output: Output): void {
const raw = output;
console.log(raw);
}
main();
|
Markdown
|
UTF-8
| 8,998
| 2.9375
| 3
|
[] |
no_license
|
---
title: Compile SASS with npm
metaDescription: Use npm package.json scripts, node-sass npm package cli and clean-css npm package cli to compile SCSS and minify the css output with Node.js
guid: 99bf307e-00e5-4226-b919-a8a08f8301b6
author: James Edwards
tags:
- Node.js
- SASS
image: npm-compile-sass.png
imageAlt: Compile SCSS into CSS
---
There are many different ways to compile [SCSS](https://stackoverflow.com/questions/5654447/whats-the-difference-between-scss-and-sass), one of the [two syntaxes supported by SASS](https://sass-lang.com/documentation/syntax). In this post we will explore the utilization of the [node-sass](https://www.npmjs.com/package/node-sass?activeTab=readme) npm package. We'll also look at how we can use the [clean-css](https://www.npmjs.com/package/clean-css) npm package to minify and optimize the generated output after compiling SCSS into CSS. Both of these techniques are similar to how Bootstrap handles the [compilation](https://github.com/twbs/bootstrap/blob/622c914a3acc1ab933b3e89d8abfdd63feeb4016/package.json#L25) and [minification](https://github.com/twbs/bootstrap/blob/622c914a3acc1ab933b3e89d8abfdd63feeb4016/package.json#L29) of its SCSS files. Please make sure you have [Node.js](https://nodejs.org/en/) and [npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) installed first.
### SCSS
First an SCSS file is needed, and it can be placed in the root of the project folder. To illustrate the preprocessing of our SCSS file into CSS let's add some style rules that are intentionally utilizing the SCSS syntax. We'll look to the [Sass Basics guide](https://sass-lang.com/guide) for some code snippets.
```scss
// some variables
$font-stack: Helvetica, sans-serif;
$primary-color: #333;
body {
font: 100% $font-stack;
color: $primary-color;
}
// some nesting
nav {
ul {
margin: 0;
padding: 0;
list-style: none;
}
li {
display: inline-block;
}
a {
display: block;
padding: 6px 12px;
text-decoration: none;
}
}
// a mixin
@mixin transform($property) {
-webkit-transform: $property;
-ms-transform: $property;
transform: $property;
}
.box {
@include transform(rotate(30deg));
}
```
Now that we have an SCSS file to process, the next step involves configuring the package.json to install the necessary dependencies and provide a way to compile SCSS with Node.js by adding custom scripts.
### package.json
Using the scripts section of an [npm package.json](https://docs.npmjs.com/files/package.json) file we can execute a series of commands to carry out the compilation of SCSS and optimize the resulting CSS output. A package.json file is required, and can be created running the command <kbd>npm init</kbd> in the project folder and following the prompts, or copying below.
```json
{
"name": "npmcompilesass",
"scripts": {}
}
```
Next we'll need to add two packages into the devDependencies of our project. To do so run the following command <kbd>npm install node-sass clean-css-cli --save-dev</kbd>. What will occur is that the node-sass and clean-css npm packages will be installed to the devDependencies of the project. You should also see a node modules folder appear in the root of the project, and there should also be a [package-lock.json](https://docs.npmjs.com/files/package-lock.json) file that was created.
Your package.json file should look like this:
```json
{
"name": "npmcompilesass",
"scripts": {},
"devDependencies": {
"clean-css-cli": "^4.3.0",
"node-sass": "^4.12.0"
}
}
```
If for some reason your file looks different, you can copy the above and run the command <kbd>npm install</kbd>. This will reinstall both packages.
### Compile Sass to CSS using node-sass
With the dependencies available we can add a script to compile the SCSS file created earlier with the node-sass npm package.
```json
{
"name": "npmcompilesass",
"scripts": {
"compile-styles": "node-sass --output-style expanded --source-map true --source-map-contents true --precision 6 styles.scss dist/styles.css"
},
"devDependencies": {
"clean-css-cli": "^4.3.0",
"node-sass": "^4.12.0"
}
}
```
Unfortunately, [multi-line npm scripts are not supported](https://stackoverflow.com/questions/36258456/how-can-i-write-multiline-scripts-in-npm-scripts) so the script is quite long, and there are quite a few parameters passed. Luckily the [node-sass command line documentation](https://github.com/sass/node-sass#command-line-interface) can provided detailed info on all of the possible parameters that are supported.
In this case parameters are used to indicate source maps should be generated (for debugging purposes), the amount of decimal precision is capped at 6, and the scss source file to process is styles.scss, which will be processed and output to a file named styles.css in a new folder named dist, located in the root of the project. The name of the dist folder can be changed if needed, and it will be created when the script runs if it does not already exist.
At this point we can run the compile styles script by running the command <kbd>npm run compile-styles</kbd>. However, this is only running node-sass and isn't minifying the css output, so we need to add another script to carry out the css optimization.
### Minify CSS with clean-css
Like the node-sass package, we installed the clean-css package in the first step. To utilize it we'll add an additional script to the package.json file.
```json
{
"name": "npmcompilesass",
"scripts": {
"compile-styles": "node-sass --output-style expanded --source-map true --source-map-contents true --precision 6 styles.scss dist/styles.css",
"css-minify": "cleancss --level 1 --format breaksWith=lf --source-map --source-map-inline-sources --output dist/styles.min.css dist/styles.css"
},
"devDependencies": {
"clean-css-cli": "^4.3.0",
"node-sass": "^4.12.0"
}
}
```
Similar to the compile-styles script, the css-minify script is also quite long and contains many parameters. More info on all the parameters can be found at the [clean-css-cli GitHub repo](https://github.com/jakubpawlowicz/clean-css-cli#cli-options). The parameters being passed in indicate to run clean-css with a certain level of optimization, line break formatting, and to include source maps with the optimized output. The file to optimize is the styles.css file located in the dist folder that was generated by the compile-styles command, and the optimized output will be written to styles.min.css in the same folder. Now that all the required scripts have been added to the package.json file we can first compile, and then minify the scss source, by running the command <kbd>npm run compile-styles</kbd> followed by the command <kbd>npm run css-minify</kbd>. Then looking in the dist folder that was created there should be four files:
- styles.css
- styles.css.map
- styles.min.css
- styles.min.css.map
The two files we are most interested in are styles.css and styles.min.css. These are the browser compatible style sheets that can now be linked in any HTML file.
### CSS
To make sure everything worked correctly your styles.css file should look like this:
```css
body {
font: 100% Helvetica, sans-serif;
color: #333;
}
nav ul {
margin: 0;
padding: 0;
list-style: none;
}
nav li {
display: inline-block;
}
nav a {
display: block;
padding: 6px 12px;
text-decoration: none;
}
.box {
-webkit-transform: rotate(30deg);
-ms-transform: rotate(30deg);
transform: rotate(30deg);
}
/*# sourceMappingURL=styles.css.map */
```
You can also verify the styles.min.css file because it should have identical content with all of the whitespace removed. Also take note that a comment is included at the bottom for the source map file. This can be left as is and allows for seeing the style rules in the original SCSS file from the browser's dev tools.
### Run npm Scripts Sequentially
With the output being generated correctly, there is one additional step we can do to simplify the SCSS processing into one command. Looking back to the scripts section of the package.json file, let's add one more script to combine the other two.
```json
{
"name": "npmcompilesass",
"scripts": {
"compile-styles": "node-sass --output-style expanded --source-map true --source-map-contents true --precision 6 styles.scss dist/styles.css",
"css-minify": "cleancss --level 1 --format breaksWith=lf --source-map --source-map-inline-sources --output dist/styles.min.css dist/styles.css",
"process-styles": "npm run compile-styles && npm run css-minify"
},
"devDependencies": {
"clean-css-cli": "^4.3.0",
"node-sass": "^4.12.0"
}
}
```
Now by running the command <kbd>npm run process-styles</kbd>, the compile-styles and css-minify scripts will run in series, and it is no longer necessary to execute both scripts separately. The process-styles script is responsible for both compiling the SCSS into css output and minifying it for optimal use.
|
JavaScript
|
UTF-8
| 2,804
| 2.65625
| 3
|
[] |
no_license
|
function Particle (particleTemplate, paramPosition, paramMoveDirection, paramVelocity) {
this.id = particleIdCounter++;
this.type = "particle";
this.template = ParticlesTemplateRooster.getTemplate(particleTemplate);
this.curAnimStep = 0;
this.position = paramPosition;
this.moveDirection = paramMoveDirection;
this.speed = paramVelocity;
this.rotation = 0;
this.rotationSpeed = 0;
this.ttl = this.template.getStepCount();
this.timeLastFrame = 0;
this.isActive = true;
this.update = function(timeSinceLastFrame)
{
//Moves forward in the direction of the Vector moveDirection multiplied by the speed
this.position.Add(this.moveDirection.MultiplyNoChanges((this.speed * timeSinceLastFrame / 1000)));
this.rotation += this.rotationSpeed * timeSinceLastFrame / 1000;
if(this.rotation > (Math.PI * 2))
this.rotation = this.rotation % (Math.PI * 2);
else if(this.rotation < 0)
this.rotation = (Math.PI * 2) - (this.rotation % (Math.PI * -2));
}
this.paint = function (ctx, viewportOffset, viewportSize, timeSinceLastFrame)
{
if((Viewport.curTime - this.timeLastFrame) >= this.template.minStepDuration)
{
this.curAnimStep ++ ;
this.ttl -- ;
this.timeLastFrame = Viewport.curTime;
}
if( 0 < this.ttl)
{
this.update(timeSinceLastFrame);
var tileSource = this.template.getAnimStep(this.curAnimStep);
var tileDest = [Viewport.paintOffset[0] + (this.position.x - viewportOffset.x) * Viewport.pixelsPerThousand / 1000, Viewport.paintOffset[1] + (Viewport.viewportSize.y - this.position.y + viewportOffset.y) * Viewport.pixelsPerThousand / 1000, tileSource[2], tileSource[3]];
var origPoints = [tileDest[0], tileDest[1]];
if(this.rotation != 0) {
tileDest[0] = Math.round(0 - tileSource[2] / 2);
tileDest[1] = Math.round(0 - tileSource[3] / 2);
ctx.save();
ctx.translate(origPoints[0], origPoints[1]);
ctx.rotate(this.rotation);
ctx.drawImage(this.template.img.src, tileSource[0], tileSource[1], tileSource[2], tileSource[3], tileDest[0], tileDest[1], tileDest[2], tileDest[3]);
ctx.restore();
} else
{
tileDest[0] = Math.round(tileDest[0] - tileSource[2] / 2);
tileDest[1] = Math.round(tileDest[1] - tileSource[3] / 2);
ctx.drawImage(this.template.img.src, tileSource[0], tileSource[1], tileSource[2], tileSource[3], tileDest[0], tileDest[1], tileDest[2], tileDest[3]);
}
} else
{
this.isActive = false;
}
}
}
|
JavaScript
|
UTF-8
| 1,061
| 2.53125
| 3
|
[] |
no_license
|
import {ADD_ORDER, DELETE_ORDER} from '../constants'
export default ( tableForCheck = setDefaultTableForCheck(), action ) => {
console.log(action);
const { type, payload } = action;
switch (type) {
case ADD_ORDER:
let {order} = payload;
if (order.bill_id) {
tableForCheck[order.bill_id] = order;
}
localStorage.setItem('tableForCheck', JSON.stringify(tableForCheck));
return {...tableForCheck};
case DELETE_ORDER:
let {id} = payload;
delete tableForCheck[id];
localStorage.setItem('tableForCheck', JSON.stringify(tableForCheck));
return {...tableForCheck};
}
return tableForCheck;
}
const setDefaultTableForCheck = () => {
let result = {};
if (localStorage.getItem('tableForCheck')) {
//localStorage.setItem('tableForCheck', JSON.stringify({}));
result = JSON.parse(localStorage.getItem('tableForCheck'));
console.log("defaultData ->" ,result);
return result;
}
return result;
}
|
JavaScript
|
UTF-8
| 451
| 2.59375
| 3
|
[] |
no_license
|
import R from 'ramda'
export default function changeAt(key, val, obj) {
if (R.isNil(val)) {
// Remove
return R.ifElse(
Array.isArray,
R.remove(key, 1),
R.assoc(key, val)
)(obj)
}
else {
// Replace
return R.ifElse(
Array.isArray,
R.ifElse(
R.propEq('length', key),
R.append(val), // Append if past last index
R.update(key, val) // Otherwise replace the item at the index
),
R.assoc(key, val)
)(obj)
}
}
|
C#
|
UTF-8
| 461
| 2.703125
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OOP_InitClasses
{
class Hummer
{
public string firm = null;
public string Material { get; set; }
public int Weight { get; set; }
public int price;
public Hummer()
{
}
public Hummer(int price)
{
this.price = price;
}
}
}
|
Python
|
UTF-8
| 3,708
| 3.140625
| 3
|
[] |
no_license
|
# This file will serve to create a CSV that contains all lotto results since Draw #1.
import requests
from bs4 import BeautifulSoup
from datetime import date, datetime
import csv
import os
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36'}
# The number of draws must firstly be calculated.
# A draw occurs every Wednesday and Saturday; 2 times a week.
# The first draw occurred on July 4th, 2001.
# To account for anomalies or specific events where draws could not happen, a variable is assigned for margin of error.
# This can be changed as required.
error = 31
def getTotalDraws():
d1 = date(2001, 7, 4)
d2 = date.today()
return (((d2-d1).days // 7)*2)-error
# Having gotten approximately the number of draws, the data must now be compiled to a CSV, for further data processing.
# The core link to query draws is stored in the query variable. This may need to be updated if the URL is every changed in the future.
# For every draw, the data is pulled, using bs4, and written into the CSV.
# Additional data may also be pulled, to assist the ML model later on (TODO).
# The createCSV() makes the following assumptions:
# - The webpage remains as it is on 3/5/2021.
# - The class names are as programmed, and are in the appropriate element (div).
# - The draw consists of 6 numbers, the last of which is considered the PowerBall.
# - The PowerBall has a different class than the other elements
# - The date for each draw is found within a <strong> elements.
classForDraws = "ball lotto-balls"
classForPowerBall = "ball lotto-balls yellow-ball"
def createCSV():
maxQueries = getTotalDraws()
query = "http://www.nlcbplaywhelotto.com/nlcb-lotto-plus-results/?drawnumber="
cls = lambda: os.system('cls')
with open('draws.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Draw Number', 'Date', 'Jackpot', '1', '2', '3', '4','5', 'PB'])
for i in range(1, maxQueries+1):
# In case any error occurs, it just skips that iteration.
# It was discovered that some of the webpages do not contain the jackpot amount. Ignoring these would result in a smaller dataset,
# but I am trying to have as much features to use, with one being the jackpot amount.
try:
print(i, "/", maxQueries)
nums = []
pb = ""
drawDate = ""
drawAmt = ""
queryTemp = query + str(i)
r = requests.get(queryTemp, headers=headers)
soup = BeautifulSoup(r.text, 'lxml')
result1 = soup.find_all('div', class_= classForDraws)
for num in result1:
if num is None:
nums.append('None')
else:
nums.append(num.text)
result2 = soup.find('div', class_= classForPowerBall)
if result2 is None:
pb = 'None'
else:
pb = result2.text
result3 = soup.find_all('strong')[3].text.split(' ')[1]
drawDate = result3
result4 = float(soup.find('div', class_="drawDetails").text.split()[9].rstrip('Number\n').lstrip('\n$').replace(',',''))
drawAmt = result4
# Write into to CSV
writer.writerow([str(i), drawDate, drawAmt, nums[0], nums[1], nums[2], nums[3], nums[4], pb])
cls()
except:
print("Skipping...")
continue
createCSV()
|
Markdown
|
UTF-8
| 4,465
| 3.078125
| 3
|
[] |
no_license
|
三五
这并不是他们窝囊,而是九玄洞的攻击力量,远远超乎他们意料之外。
因为这里并非只有九玄洞的人,还有丐帮、长鲸帮、华山派和天台派的高手,也汇合在一起。
这些武林人物,本各处于天南地北,不知如何,此刻竟然齐聚此地,而且还表现得相当团结。
团结,永远是一种最强大的力量。
倘若只有九玄洞的人,说不定早已溃不成军。
这九十六个青衣大汉,确是一支精锐雄师。
但除了九玄洞之外,再加上这数大门派帮会的力量,情况就绝不相同。
激战之下,神血盟伤亡惨重。
只有极少数人冲开二条血路,得以幸免。
铁凤师的伤势其实只是痊愈的八成左右。
但在这一役,他的表现却是令人吃惊的。
他把凤凰神剑的威力,发挥得淋漓尽致,最少有十几个青衣大汉,在他的剑下伤亡。
倒是那灰衣人,遇上了劲敌。
那曾经易容的青衣汉武功高得出奇。
他也是用剑,但剑法却比毒木郎费西园还更厉害。
苦战良久,灰衣人才总算一枪刺穿他的咽喉,获得最后胜利。
这时候,大局己定。
神血盟这一役,损兵折将,碰得头焦额烂。
然而,那个曾经易容的青衣汉子,原来也不是濮阳玉。
濮阳玉已经杀出重围,逃之夭夭了。
濮阳玉的真正身份已被揭破。
他是五龙上人的弟子。
然而他学的武功,却并非只是五龙上人的武功。
他还有另外一个师父。
这师父赫然竟是血公爵卫天禅。
传言他杀了卫宝官,其实这只是掩护的手法。
卫宝官没有死,只是隐藏起来。
濮阳玉却可以藉着这一个传言,与抗拒神血盟的人混在一起。
他们在制造机会,来使濮阳玉可以混水摸鱼。
然而,司马纵横却揭穿了这年青高手的假面具。
濮阳玉不能再耽下去,只好放弃原来的计划。
但现在,司马纵横不见了,濮阳玉也不见了。
局势演变下去将会变成怎样。
第三节
正午,晴。
在一座竹林后,有几间很雅致的石屋子。
竹林很静。
石屋子四周更静。
穿过这几间石屋子,后面有一条可容马车驶过的石路。
石路蜿蜒曲折,路旁相隔不远就有一间茅屋,或者是一座亭阁。
石路尽头,距离那座竹林已最少有一里。那座竹林本已地处偏僻,这里更是宁静得出奇。
这里有一间很宽宏的屋子。
在这屋子的厅院里,一个赤发老人,正捧着一杯酒,不断的在叹气。
在他的背后,一个自衣人笔直地站立着。
这白衣人赫然正是濮阳玉。
濮阳玉的神情,看来相当难过。
因为他偷袭九玄洞的计划,已彻底失败。
赤发老人正是血公爵卫天禅。
他忽然把酒泼在地上,然后转过脸,瞪着濮阳玉。
“玉儿,你可知道,这一次本盟的损失有多大?”
“弟子知道,弟子愿负全责。”
“唉,这是死罪。”
“弟子连累数十兄弟,死不足惜。”
“但你若死了,又怎能戴罪立功?”
濮阳玉跪了下来:“盟主能给予弟子机会,弟子感激万分。”
卫天禅道:“你现在先退下去,也不必太担心,这几天之内,多点休息,多吃点丰富的食物,倘若需要女人,向花堂主说一声便是。”
“谢谢盟主。”濮阳玉退下。
卫天禅又是轻轻的叹了口气。
这时候,一辆马车缓缓地驶到大屋子门外停下。
“诸葛总护法求见盟主。”一个家仆匆匆走了进来。
卫天禅点点头。
不久,一个头戴高冠,身穿黄袍的老人进入大厅。
这人就是神血盟中,地位极高的总护法,“血手罗刹”诸葛超凡。
诸葛超凡与卫天禅谈了一会,长孙倚凤也来了。
卫天禅也召见他。
长孙倚凤已在诸葛超凡推荐之下,加入了神血盟。
卫天禅盯着他看,过了很久,才忽然说道:“果然是名不虚传,我们正需要你这种能担当大任的人材。”
长孙倚凤神态恭谨:“属下愿听从盟主调度,鞠躬尽瘁,死而后己。”
卫天禅陡地纵声大笑。
|
PHP
|
UTF-8
| 956
| 3.234375
| 3
|
[] |
no_license
|
<?php
namespace Botchka\Command;
use \Botchka\Command;
/**
* Class Who
* @author Joost Mul <joost@jmul.net>
*
* Returns a list of users who match <name>.[54] If the flag "o" is given, the server will only return information about IRC Operators.
*
* Defined in RFC 1459
*/
final class Who extends Command
{
/**
* @var string
*/
protected $name = '';
/**
* @param $name
*/
public function __construct($name)
{
$this->setName($name);
}
/**
* @return string
*/
public function getSyntax()
{
return "WHO [<name>]";
}
/**
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @return string
*/
public function __toString()
{
return "WHO {$this->getName()}";
}
}
|
TypeScript
|
UTF-8
| 328
| 2.84375
| 3
|
[] |
no_license
|
(() => {
enum Sizes {
Small = 'small',
Medium = 'medium',
Large = 'large'
}
enum Sizes {
ExtraLarge = 'xtraLarge'
}
let selectedSize: Sizes = Sizes.Small;
function updateSizes(size: Sizes): void {
selectedSize = size;
}
updateSizes(Sizes.ExtraLarge);
console.log(selectedSize);
})();
|
Java
|
UTF-8
| 797
| 2.8125
| 3
|
[] |
no_license
|
package com.mycompany.commands;
import com.codename1.ui.Command;
import com.codename1.ui.Dialog;
import com.codename1.ui.events.ActionEvent;
import com.mycompany.a3.GameWorld;
public class AboutCmd extends Command {
/**
* Constructor for the Command object.
* @param gw = GameWorld from which the commands are going to run from
*/
public AboutCmd(GameWorld gw) {
super("About"); //name the command block
}
/**
* actionPerformed is overridden to run the specified command
* from the GameWorld.
*/
public void actionPerformed(ActionEvent evt) { //Override the actionPerformed method in Command
String info = "Name: Emran Tokhi\nCourse: CSC 133 Section 02"
+ "\nVersion: 1.0.0";
Dialog.show("Sili-Challenge:", info, "Back", null);
}
}
|
Markdown
|
UTF-8
| 1,607
| 2.8125
| 3
|
[] |
no_license
|
学习笔记
# HTML
* symbol
* ` `: 空格
* no-break space
* 会破坏语义,不建议使用
* `"`: `"`
* `&`: `&`
* `<`: `<`
* `>`: `>`
* 语义化
* 定义
* 语义指的是一段代码的含义
* 例如: 这个 HTML 的元素有什么作用,扮演了什么样的角色
* 在恰当的需求下使用恰当的 HTML 元素
* 好处
* `<h1>`它的语义会被在很多地方以不同的方式被使用到, 例如搜索引擎会把它包含的内容作为一个重要的关键词,从而影响这个页面在搜索结果中的排序(SEO),而且屏幕阅读器会使用它来帮助视障用户更好的使用这个页面。
* 语义化元素
* `<article>`
* `<aside>`
* `<details>`
* `<figcaption>`
* `<figure>`
* `<footer>`
* `<header>`
* `<main>`
* `<mark>`
* `<nav>`
* `<section>`
* `<summary>`
* `<time>`
* [more...](https://developer.mozilla.org/en-US/docs/Web/HTML/Element#Inline_text_semantics)
## CSSOM
* window.getComputedStyle(element [, pseudoElt]);
* element 要获取其计算样式的元素
* pseudoElt 可选,伪元素
* 返回 一个包含元素的所有 CSS 属性值的对象
* window
* innerHeight,innerWidth
* outerHeight,outerWidth
* devicePixelRatio
* scroll
* element
* scrollTop
* scrollLeft
* scrollWidth
* scrollHeight
* scroll(x, y)
* scrollBy(x, y)
* scrollIntoView()
* window
* scrollX
* scrollY
* scroll(x, y)
* scrollBy(x, y)
* layout
* getClientRects()
* __getBoundingClientRect()__
|
Rust
|
UTF-8
| 9,110
| 2.765625
| 3
|
[
"Apache-2.0"
] |
permissive
|
use std::collections::HashMap;
use std::sync::Arc;
use grpcio::{Channel, ChannelBuilder, ChannelCredentialsBuilder, Environment};
#[cfg(feature = "serialize")]
use serde::{Deserialize, Serialize};
use crate::exporter::Compression;
use crate::ExportConfig;
use super::default_headers;
#[cfg(feature = "logs")]
mod logs;
#[cfg(feature = "trace")]
mod trace;
#[cfg(feature = "metrics")]
mod metrics;
/// Configuration of grpcio
#[derive(Debug)]
#[non_exhaustive]
pub struct GrpcioConfig {
/// The credentials to use when communicating with the collector.
pub credentials: Option<Credentials>,
/// Additional headers to send to the collector.
pub headers: Option<HashMap<String, String>>,
/// The compression algorithm to use when communicating with the collector.
pub compression: Option<Compression>,
/// Use TLS without any specific certificate pinning.
pub use_tls: Option<bool>,
/// The number of GRPC worker threads to poll queues.
pub completion_queue_count: usize,
}
impl Default for GrpcioConfig {
fn default() -> Self {
GrpcioConfig {
credentials: None,
headers: Some(default_headers()),
compression: None,
use_tls: None,
completion_queue_count: 2,
}
}
}
/// Credential configuration for authenticated requests.
#[cfg_attr(feature = "serialize", derive(Deserialize, Serialize))]
#[derive(Clone, Debug)]
pub struct Credentials {
/// Credential cert
pub cert: String,
/// Credential key
pub key: String,
}
impl From<Compression> for grpcio::CompressionAlgorithms {
fn from(compression: Compression) -> Self {
match compression {
Compression::Gzip => grpcio::CompressionAlgorithms::GRPC_COMPRESS_GZIP,
}
}
}
/// Configuration for the [grpcio] OTLP GRPC exporter.
///
/// It allows you to
/// - setup credentials
/// - add additional headers
/// - config compression
/// - select whether to use TLS
/// - set the number of GRPC worker threads to poll queues
///
/// [grpcio]: https://github.com/tikv/grpc-rs
///
/// ## Examples
///
/// ```no_run
/// # #[cfg(feature="metrics")]
/// use opentelemetry_sdk::metrics::reader::{
/// DefaultAggregationSelector, DefaultTemporalitySelector,
/// };
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // Create a span exporter you can use to when configuring tracer providers
/// # #[cfg(feature="trace")]
/// let span_exporter = opentelemetry_otlp::new_exporter().grpcio().build_span_exporter()?;
///
/// // Create a metrics exporter you can use when configuring meter providers
/// # #[cfg(feature="metrics")]
/// let metrics_exporter = opentelemetry_otlp::new_exporter()
/// .grpcio()
/// .build_metrics_exporter(
/// Box::new(DefaultAggregationSelector::new()),
/// Box::new(DefaultTemporalitySelector::new()),
/// )?;
///
/// // Create a log exporter you can use when configuring logger providers
/// # #[cfg(feature="logs")]
/// let log_exporter = opentelemetry_otlp::new_exporter().grpcio().build_log_exporter()?;
/// # Ok(())
/// # }
/// ```
#[derive(Default, Debug)]
pub struct GrpcioExporterBuilder {
pub(crate) exporter_config: ExportConfig,
pub(crate) grpcio_config: GrpcioConfig,
}
impl GrpcioExporterBuilder {
/// Set the credentials to use when communicating with the collector.
pub fn with_credentials(mut self, credentials: Credentials) -> Self {
self.grpcio_config.credentials = Some(credentials);
self
}
/// Set additional headers to send to the collector.
pub fn with_headers(mut self, headers: HashMap<String, String>) -> Self {
let mut inst_headers = self.grpcio_config.headers.unwrap_or_default();
inst_headers.extend(headers);
self.grpcio_config.headers = Some(inst_headers);
self
}
/// Set the compression algorithm to use when communicating with the collector.
pub fn with_compression(mut self, compression: Compression) -> Self {
self.grpcio_config.compression = Some(compression);
self
}
/// Enable TLS without any certificate pinning.
pub fn with_tls(mut self, use_tls: bool) -> Self {
self.grpcio_config.use_tls = Some(use_tls);
self
}
/// Set the number of GRPC worker threads to poll queues.
pub fn with_completion_queue_count(mut self, count: usize) -> Self {
self.grpcio_config.completion_queue_count = count;
self
}
fn build_channel(&mut self) -> Result<Channel, crate::Error> {
let mut builder: ChannelBuilder = ChannelBuilder::new(Arc::new(Environment::new(
self.grpcio_config.completion_queue_count,
)));
if let Some(compression) = self.grpcio_config.compression {
builder = builder.default_compression_algorithm(compression.into());
}
let channel = match (
self.grpcio_config.credentials.take(),
self.grpcio_config.use_tls.take(),
) {
(None, Some(true)) => builder
.set_credentials(ChannelCredentialsBuilder::new().build())
.connect(self.exporter_config.endpoint.as_str()),
(None, _) => builder.connect(self.exporter_config.endpoint.as_str()),
(Some(credentials), _) => builder
.set_credentials(
ChannelCredentialsBuilder::new()
.cert(credentials.cert.into(), credentials.key.into())
.build(),
)
.connect(self.exporter_config.endpoint.as_str()),
};
Ok(channel)
}
/// Create a new span exporter with the current configuration
#[cfg(feature = "trace")]
pub fn build_span_exporter(
mut self,
) -> Result<crate::SpanExporter, opentelemetry::trace::TraceError> {
use opentelemetry_proto::grpcio::collector::trace::v1::TraceServiceClient;
use self::trace::GrpcioTraceClient;
let channel = self.build_channel()?;
let client = GrpcioTraceClient::new(
TraceServiceClient::new(channel),
self.exporter_config.timeout,
self.grpcio_config.headers.unwrap_or_default(),
);
Ok(crate::SpanExporter::new(client))
}
#[cfg(feature = "logs")]
/// Builds a new log exporter with the given configuration
pub fn build_log_exporter(
mut self,
) -> Result<crate::logs::LogExporter, opentelemetry::logs::LogError> {
use self::logs::GrpcioLogsClient;
use opentelemetry_proto::grpcio::collector::logs::v1::LogsServiceClient;
let channel = self.build_channel()?;
let client = GrpcioLogsClient::new(
LogsServiceClient::new(channel),
self.exporter_config.timeout,
self.grpcio_config.headers.unwrap_or_default(),
);
Ok(crate::logs::LogExporter::new(client))
}
#[cfg(feature = "metrics")]
/// Builds a new metrics exporter with the given configuration
pub fn build_metrics_exporter(
mut self,
aggregation_selector: Box<dyn opentelemetry_sdk::metrics::reader::AggregationSelector>,
temporality_selector: Box<dyn opentelemetry_sdk::metrics::reader::TemporalitySelector>,
) -> opentelemetry::metrics::Result<crate::MetricsExporter> {
use self::metrics::GrpcioMetricsClient;
use opentelemetry_proto::grpcio::collector::metrics::v1::MetricsServiceClient;
let channel = self.build_channel()?;
let client = GrpcioMetricsClient::new(
MetricsServiceClient::new(channel),
self.exporter_config.timeout,
self.grpcio_config.headers.unwrap_or_default(),
);
Ok(crate::MetricsExporter::new(
client,
temporality_selector,
aggregation_selector,
))
}
}
#[cfg(test)]
mod tests {
use crate::GrpcioExporterBuilder;
use std::collections::HashMap;
#[test]
fn test_with_headers() {
// metadata should merge with the current one with priority instead of just replacing it
let mut headers = HashMap::new();
headers.insert("key".to_string(), "value".to_string());
let builder = GrpcioExporterBuilder::default().with_headers(headers);
let result = builder.grpcio_config.headers.unwrap();
assert_eq!(result.get("key").unwrap(), "value");
assert!(result.get("User-Agent").is_some());
// metadata should override entries with the same key in the default one
let mut headers = HashMap::new();
headers.insert("User-Agent".to_string(), "baz".to_string());
let builder = GrpcioExporterBuilder::default().with_headers(headers);
let result = builder.grpcio_config.headers.unwrap();
assert_eq!(result.get("User-Agent").unwrap(), "baz");
assert_eq!(
result.len(),
GrpcioExporterBuilder::default()
.grpcio_config
.headers
.unwrap()
.len()
);
}
}
|
C#
|
UTF-8
| 761
| 2.578125
| 3
|
[] |
no_license
|
using UnityEngine;
using UnityEngine.UI;
public class HPSlider : MonoBehaviour
{
public Slider HPslider;
public Text HPText;
private float HP;
public float HP1 { get => HP; set => HP = value; }
void Start()
{
HPslider.minValue = 0;
HPslider.maxValue = 100;
HP1 = HPslider.value;
}
// Update is called once per frame
void Update()
{
// 判斷目前滑桿血量
HP1 = HPslider.value;
HPControl(HP1);
}
void HPControl(float HP)
{
if(HP >= 70)
{
HPText.text = "安全";
}else if(HP >= 30)
{
HPText.text = "警告";
}else
{
HPText.text = "危險";
}
}
}
|
Java
|
UTF-8
| 3,690
| 2.546875
| 3
|
[] |
no_license
|
package com.sfmap.api.maps.offlinemap;
import android.os.Parcel;
import android.os.Parcelable;
/**
* 下载城市属性的相关类。
*/
public class OfflineMapCity
extends City
{
/**
* 下载城市的数据地址。
*/
private String url = "";
/**
* 返回下载城市数据的大小,单位字节。
*/
private long size = 0L;
/**
* 城市下载状态。
*/
private int state = OfflineMapStatus.CHECKUPDATES;
private String version = "";
/**
* 下载百分比。
*/
private int code = 0;
/**
* 地图数据md5值
*/
private String md5="";
/**
* 构造一个OfflineMapCity对象。
*/
public OfflineMapCity() {}
/**
* 返回所下载城市的数据地址。
* @return 所下载城市的数据地址。
*/
public String getUrl()
{
return this.url;
}
/**
* 设置所下载城市的数据地址。
* @param url - 所下载城市的数据地址。
*/
public void setUrl(String url)
{
this.url = url;
}
/**
*返回下载城市数据的大小,单位字节。
* @return 下载城市数据的大小,单位字节。
*/
public long getSize()
{
return this.size;
}
/**
* 设置下载城市数据的大小,单位字节。
* @param size - 下载城市数据的大小,单位字节。
*/
public void setSize(long size)
{
this.size = size;
}
/**
* 返回城市下载状态。
* @return 城市下载状态。
*/
public int getState()
{
return this.state;
}
/**
* 设置返回城市下载状态。
* @param state - 城市下载状态。
*/
public void setState(int state)
{
this.state = state;
}
/**
* 返回下载城市的数据版本。
* @return 下载城市的数据版本。
*/
public String getVersion()
{
return this.version;
}
/**
* 设置下载城市的数据版本。
* @param version - 下载城市的数据版本。
*/
public void setVersion(String version)
{
this.version = version;
}
/**
* 返回城市下载完成的百分比,100表示下载完成。
* @return 城市下载完成的百分比,100表示下载完成。
*/
public int getcompleteCode()
{
return this.code;
}
/**
* 获取城市数据的MD5值。
* @return 城市数据的MD5值
*/
public String getMd5() {
return md5;
}
/**
* 设置城市数据的MD5值。
* @param md5 城市数据的MD5值。
*/
public void setMd5(String md5) {
this.md5 = md5;
}
/**
*设置下载完成的百分比,100表示下载完成。
* @param code - 下载完成的百分比,100表示下载完成。
*/
public void setCompleteCode(int code)
{
this.code = code;
}
public int describeContents()
{
return 0;
}
public void writeToParcel(Parcel paramParcel, int paramInt)
{
super.writeToParcel(paramParcel, paramInt);
paramParcel.writeString(this.url);
paramParcel.writeLong(this.size);
paramParcel.writeInt(this.state);
paramParcel.writeString(this.version);
paramParcel.writeInt(this.code);
paramParcel.writeString(md5);
}
public OfflineMapCity(Parcel paramParcel)
{
super(paramParcel);
this.url = paramParcel.readString();
this.size = paramParcel.readLong();
this.state = paramParcel.readInt();
this.version = paramParcel.readString();
this.code = paramParcel.readInt();
this.md5 = paramParcel.readString();
}
public static final Parcelable.Creator<OfflineMapCity> CREATOR = new OfflineMapCityCreator();
}
|
JavaScript
|
UTF-8
| 1,271
| 2.546875
| 3
|
[] |
no_license
|
import {
ADD_TODO,
CLEAR_COMPLETED_TASKS,
UPDATE_TASK_DESCRIPTION,
TOGGLE_COMPLETE
} from '../data/constants';
import moment from 'moment';
import uuid from 'uuid';
export default function reducer(state, action) {
switch (action.type) {
case UPDATE_TASK_DESCRIPTION:
return {
...state,
taskDescription: action.payload
};
case ADD_TODO:
return {
todos: [...state.todos, {
id: uuid(),
description: state.taskDescription,
isComplete: false,
completedDate: '' } ],
taskDescription: '',
};
case CLEAR_COMPLETED_TASKS:
return {
...state,
todos: state.todos.filter(todo => todo.isComplete === false),
};
case TOGGLE_COMPLETE:
return {
...state,
todos: state.todos.map(todo => {
return todo.id === action.payload.id
? {...todo,
isComplete: !todo.isComplete,
completedDate: todo.isComplete ? '' : moment().format("dddd, MMMM Do YYYY, h:mm:ss a")
}
: todo
})
};
default:
return state;
}
}
|
Java
|
UTF-8
| 752
| 3.78125
| 4
|
[] |
no_license
|
package sort;
/**
* 冒泡算法
* 实现思路:数向上慢慢爬
* @author xuguowei
*
*/
public class BubbleSort {
/**
* 时间复杂度:o(n2)
* @param sortArray
* @return
*/
public int[] BubbleSort_1(int[] sortArray){
for(int i = 0;i<sortArray.length;i++){
for(int j=sortArray.length-1;j>i;j--){
if(sortArray[j-1]>=sortArray[j]){
int temp = sortArray[j];
sortArray[j] = sortArray[j-1];
sortArray[j-1] = temp;
}
}
}
return sortArray;
}
public static void main(String[] args) {
BubbleSort sort = new BubbleSort();
int[] sortArray = {5,3,7,4,1,6,2};
int[] result = sort.BubbleSort_1(sortArray);
for(int m = 0;m<sortArray.length;m++){
System.out.println(result[m]);
}
}
}
|
Python
|
UTF-8
| 9,710
| 3
| 3
|
[] |
no_license
|
import argparse
import nd2reader
import os
import numpy as np
from os import listdir
import shutil
from skimage.feature import register_translation
from scipy.ndimage import fourier_shift
from skimage import exposure
def read_data(reader, data_path):
"""
Reads data from .nd2 files.
:param reader: nd2 reader to use
:param data_path: path to files to read
:return: list of samples (content of file) and list of filenames.
"""
samples = []
filenames = []
for filename in sorted(listdir(data_path)):
if filename.endswith('.nd2'):
samples.append(reader(data_path + "/" + filename))
filenames.append(filename)
return samples, filenames
def get_volume(sample, channel, frame):
"""
Loads particular volume from sample.
:param sample: sample from which load volume.
:param channel: which channel to read.
:param frame: which frame to read.
:return: volume which is np.array containing images of all levels.
"""
if channel in range(sample.sizes["c"]) and frame in range(sample.sizes["t"]):
sample.iter_axes = 'z'
sample.default_coords['c'] = channel
sample.default_coords['t'] = frame
volume = np.array([np.array(level) for level in sample])
return volume
def align_images(img_1, img_2):
"""
Aligns first image to second one using cross-correlation in Fourier space to find shift.
:param img_1: first image.
:param img_2: second image.
:return: pair of images: (shifted version of image1 and image2.
"""
shift, error, diffphase = register_translation(img_1, img_2, 100)
shift = -1 * shift
img_1_shifted = fourier_shift(np.fft.fftn(img_1), shift)
img_1_shifted = np.fft.ifftn(img_1_shifted).real
return img_1_shifted, img_2
def align_volumes(volume_1, volume_2):
"""
Aligns volumes by aligning each pair of images from two volumes.
Pair contains one image per volume with the same level.
:param volume_1: first volume.
:param volume_2: second volume.
:return: pair of volumes: (shifted version of volume1 and volume2).
"""
volume_1_shifted = []
for img_1, img_2 in zip(volume_1, volume_2):
img_1_shifted, img_2 = align_images(img_1, img_2)
volume_1_shifted.append(img_1_shifted)
return volume_1_shifted, volume_2
def augment_image(img):
"""
Augments image by using flipping image across both axes.
:param img: image to augment.
:return: list of 4 images (first image is original).
"""
return [img, np.fliplr(img), np.flipud(img), np.fliplr(np.flipud(img))]
def augment_volumes(volume_1, volume_2):
"""
Augments pair of volumes by flipping each image across both axes.
:param volume_1: first volume.
:param volume_2: second volume.
:return: pair of augmented volumes.
"""
volume_1_augmented = []
volume_2_augmented = []
for img_1, img_2 in zip(volume_1, volume_2):
volume_1_augmented.extend(augment_image(img_1))
volume_2_augmented.extend(augment_image(img_2))
return volume_1_augmented, volume_2_augmented
def is_overnoised(img, bright_pixel_percent=0.05):
"""
Checks whether image is overnoised.
Uses simple heuristic: overnoised images have big percentage of "bright" pixels.
:param img: image to check.
:param bright_pixel_percent: threshold (max percentage of "bright" pixels in not overnoised image
:return: 'True' if image is overnoised, 'False' otherwise.
"""
hist = exposure.histogram(img, nbins=2)[0]
value = hist[1] # Number of bright points. (The less value, the less noise)
n_pixels = img.shape[0] * img.shape[1]
return value > n_pixels * bright_pixel_percent
def clean_volumes(volume_1, volume_2):
"""
Delete pair of images from both volumes if one of images from pair is overnoised.
:param volume_1: first volume.
:param volume_2: second volume.
:return: pair of cleaned volumes.
"""
volume_1_cleaned = []
volume_2_cleaned = []
for img_1, img_2 in zip(volume_1, volume_2):
if is_overnoised(img_1) | is_overnoised(img_2):
continue
else:
volume_1_cleaned.append(img_1)
volume_2_cleaned.append(img_2)
return volume_1_cleaned, volume_2_cleaned
def save_img_grayscale(img, filename):
"""
Save image in grayscale format.
:param img: pixel matrix of image. Must be grayscale.
:param filename: filename for file to save.
:return: 'True' if image is successfully saved.
"""
np.save(filename, img)
return True
def save_volume(volume, path):
"""
Save images form volume in grayscale format.
:param volume: volume to save.
:param path: path where save volume in.
:return: 'True' if volume is successfully saved.
"""
for ind, image in enumerate(volume):
filename = f"{path}_image_{ind}"
save_img_grayscale(image, filename)
return True
def create_folders(dataset_path):
"""
Create folders for dataset.
:param dataset_path: dataset's path where the folders will be created.
:return: 'True' if folders are successfully created.
"""
os.mkdir(dataset_path)
for channel in ["green", "red"]:
os.mkdir(f"{dataset_path}/{channel}")
for train_or_val in ["train", "val"]:
os.mkdir(f"{dataset_path}/{channel}/{train_or_val}", )
for src_or_trg in ["src", "trg"]:
os.mkdir(f"{dataset_path}/{channel}/{train_or_val}/{src_or_trg}")
return True
def generate_dataset(samples, param, dataset_path):
"""
Generate dataset.
:param samples: samples from which take images for dataset.
:param param: dictionary which contains set of preprocessing steps to be done.
Possible pre-processing steps: 'clean', 'align', 'augment'.
:param dataset_path: path where save dataset in.
:return: 'True' if dataset is successfully generated.
"""
create_folders(dataset_path)
for sample_ind, sample in enumerate(samples):
print("Sample №{}".format(sample_ind))
for channel_ind, channel_name in enumerate(["green", "red"]):
for pair_ind, pair in enumerate([[0, 2], [1, 3]]): # Frame pairs
is_test = (pair_ind == 1 and sample_ind == len(samples) - 1)
volume_1 = get_volume(sample, channel=channel_ind, frame=pair[0])
volume_2 = get_volume(sample, channel=channel_ind, frame=pair[1])
if param.get('align'):
volume_1, volume_2 = align_volumes(volume_1, volume_2)
if not is_test: # We don't need to do this steps for test set
if param.get('clean'):
volume_1, volume_2 = clean_volumes(volume_1, volume_2)
if param.get('augment'):
volume_1, volume_2 = augment_volumes(volume_1, volume_2)
assert (len(volume_1) == len(volume_2))
train_or_val = "val" if is_test else "train"
path_src = f"{dataset_path}/{channel_name}/{train_or_val}/src/sample_{sample_ind}_pair{pair_ind}"
path_trg = f"{dataset_path}/{channel_name}/{train_or_val}/trg/sample_{sample_ind}_pair{pair_ind}"
save_volume(volume_1, path_src)
save_volume(volume_2, path_trg)
print(f"Channel: {channel_name}, "
f"Frames: {pair}, "
f"Number of samples: {len(volume_1)}, "
f"{train_or_val} set")
return True
def delete_dataset(dataset_folder):
"""
Delete folder and all it's content.
:param dataset_folder: folder to delete
:return: 'True' if dataset is successfully deleted.
"""
if os.path.isdir(dataset_folder):
shutil.rmtree(dataset_folder, ignore_errors=True)
def get_args():
parser = argparse.ArgumentParser(description="preprocess .nd2 images",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--data_dir", type=str, required=True,
help="samples files dir (.nd2 format)")
parser.add_argument("--data_type", type=str, default="",
help="defines which type of images to use. Can be '30ms', '5ms'. "
"If arg is not provided all data is used")
args = parser.parse_args()
return args
def main():
"""
Generates dataset with pre-processing steps done from sample files
:return:
"""
args = get_args()
data_dir = args.data_dir
data_type = args.data_type
reader = nd2reader.ND2Reader
samples, filenames = read_data(reader, data_dir)
if data_type: # Filter only needed samples
file_indices = [ind for ind, filename in enumerate(filenames) if data_type in filename]
samples = [samples[ind] for ind in file_indices]
print(f"Found in total {len(samples)} files:")
# Experiment params
params = [
{'clean': False, 'align': True, 'augment': False},
{'clean': True, 'align': True, 'augment': False},
{'clean': False, 'align': True, 'augment': True},
{'clean': True, 'align': True, 'augment': True}
]
for experiment_ind, param in enumerate(params):
experiment_name = "_".join([key for key, el in param.items() if el])
print(f"Generating the dataset for experiment {experiment_name}")
dataset_path = f"{experiment_name}_data_{data_type}"
delete_dataset(dataset_path)
generate_dataset(samples, param, dataset_path)
if __name__ == '__main__':
main()
|
JavaScript
|
UTF-8
| 2,436
| 2.640625
| 3
|
[
"Apache-2.0"
] |
permissive
|
/*jslint sloppy:true*/
/*globals console,freedom*/
function FileServer(inSocial) {
this.social = inSocial;
this.files = {};
}
FileServer.prototype.serve = function (myClientState, key, value, name) {
console.log('serve-data: now serving ' + key);
this.files[key] = {
data: value,
stats: {}
};
if (myClientState.status === this.social.STATUS.ONLINE) {
freedom().emit('serve-descriptor', {
targetId: myClientState.clientId,
key: key,
name: name
});
} else {
freedom().emit('serve-error', "Error connecting to server.");
}
this.updateStats(key, 0, 0);
};
FileServer.prototype.updateStats = function (key, inprogress, done) {
if (!this.files[key].stats.hasOwnProperty('inprogress')) {
this.files[key].stats.inprogress = 0;
}
if (!this.files[key].stats.hasOwnProperty('done')) {
this.files[key].stats.done = 0;
}
this.files[key].stats.key = key;
this.files[key].stats.inprogress += inprogress;
this.files[key].stats.done += done;
freedom().emit('stats', this.files[key].stats);
};
FileServer.prototype.onMessage = function (val) {
// Try parsing message
try {
val.msgStr = this.social.ab2str(val.data);
val.msg = JSON.parse(val.msgStr);
} catch (e) {
console.log("Error parsing message: " + JSON.stringify(val));
return;
}
if (val.from.clientId && val.msg.cmd && val.msg.data && val.msg.cmd === 'fetch') {
var key = val.msg.data,
targetId = val.from.clientId;
this.updateStats(key, 1, 0);
console.log("social.onMessage: Received request for " + key + " from " + targetId);
if (this.files[key] && this.files[key].data) {
console.log("social.onMessage: Sending " + key + " to " + targetId);
this.social.sendMessage(targetId, key, this.files[key].data).then(function () {
}, function (err) {
console.error(JSON.stringify(err));
});
} else {
console.log("social.onMessage: I don't have key: " + key);
this.social.sendMessage(targetId, 's2f', JSON.stringify({
cmd: 'error',
data: 'File missing!'
})).then(function () {
}, function (err) {
console.error(JSON.stringify(err));
});
}
} else if (val.from.clientId && val.msg.cmd && val.msg.data && val.msg.cmd === 'done') {
this.updateStats(val.msg.data, -1, 1);
} else {
console.log("social.onMessage: Unrecognized message: " + JSON.stringify(val));
}
};
|
Python
|
UTF-8
| 202
| 2.6875
| 3
|
[] |
no_license
|
import math
#=input()
#=int(input())
a,b,c=map(int,input().split())
#=map(str,input().split())
#=list(map(int,input().split()))
if 4*a*b < (-a-b+c)**2 and a+b<=c:
print("Yes")
else:
print("No")
|
C++
|
UTF-8
| 1,818
| 3.15625
| 3
|
[] |
no_license
|
#include <iostream>
#include <fstream>
using namespace std;
#define SIZE 10
struct Choice{
int order[SIZE];
Choice *next;
};
class CombanitonAndArrangement{
private:
int *ChosenNumberInit(int how_many_need){
int *chosen_number_group = new int[how_many_need +1];
chosen_number_group[0] = -1;
return(chosen_number_group + 1);
}
Choice *ChoiceInit(){
Choice *head = new Choice;
head->next = NULL;
return(head);
}
void copy(int to[], int from[], int how_many_to_copy){
for(int i = 0; i < how_many_to_copy; to[i] = from[i], ++i);
}
Choice *Save_choice(int chosen_number_group[], int how_many_need, Choice *p){
p->next = new Choice;
p = p->next;
copy(p->order, chosen_number_group, how_many_need);
p->next = NULL;
return(p);
}
public:
Choice *Combination(int how_many_provide, int how_many_need, int which_number_choose_now = 0){
static Choice *head = ChoiceInit(), *p = head;
if(!how_many_need)
return(head);
static int *chosen_number_group = ChosenNumberInit(how_many_need);
int min_choice_now = chosen_number_group[which_number_choose_now - 1] + 1, max_choice_now = how_many_provide + which_number_choose_now - how_many_need;
for(int i = min_choice_now; i <= max_choice_now; ++i){
chosen_number_group[which_number_choose_now] = i;
if(which_number_choose_now == how_many_need - 1)
p = Save_choice(chosen_number_group, how_many_need, p);
else
Combination(how_many_provide, how_many_need, which_number_choose_now + 1);
}
return(head);
}
};
main(){
Choice *head, *p;
int a = 20, b = 10, count = 0;
CombanitonAndArrangement c;
head = c.Combination(a, b);
for(p = head->next; p; p = p->next){
// for(int i = 0; i < b; ++i)
// cout << p->order[i] << ' ';
// cout << '\n';
++count;
}
cout << count;
}
|
Java
|
UTF-8
| 388
| 2
| 2
|
[] |
no_license
|
package codingcareers.webapp.client.PageComponents;
import codingcareers.webapp.client.Constants;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.RootPanel;
public abstract class PageFooter extends HorizontalPanel implements PageComponent {
// TODO PageFooter load()
public void load(){
RootPanel.get(Constants.FOOTER_ID).add(this);
};
}
|
JavaScript
|
UTF-8
| 942
| 2.625
| 3
|
[] |
no_license
|
const Engine = Matter.Engine;
const World = Matter.World;
const Bodies = Matter.Bodies;
const Body = Matter.Body;
var paper;
var ground;
var dustbin1,dustbin2,dustbin3;
function preload()
{
}
function setup() {
createCanvas(1350, 700);
engine = Engine.create();
world = engine.world;
//Create the Bodies Here.
ground=createSprite(600,600,1490,20)
paper=createSprite (50,550,50,50);
dustbin1=createSprite(1250,540,20,90);
dustbin2=createSprite(1000,540,20,90);
dustbin3=createSprite(1125,580,280,20);
Engine.run(engine);
}
function draw() {
rectMode(CENTER);
background(0);
ground.shapeColor=("green")
dustbin1.shapeColor=("yellow");
dustbin2.shapeColor=("yellow");
dustbin3.shapeColor=("yellow");
paper.shapeColor=("red");
keyPressed();
drawSprites();
}
function keyPressed(){
if (keyDown === UP_ARROW) {
Matter.Body.applyForce(paper.body,paper.body.position,
{
x:12,
y:-13
})
}
}
|
Markdown
|
UTF-8
| 1,654
| 3.859375
| 4
|
[
"MIT"
] |
permissive
|
### [Possible Bipartition](https://leetcode.com/problems/possible-bipartition)
<p>We want to split a group of <code>n</code> people (labeled from <code>1</code> to <code>n</code>) into two groups of <strong>any size</strong>. Each person may dislike some other people, and they should not go into the same group.</p>
<p>Given the integer <code>n</code> and the array <code>dislikes</code> where <code>dislikes[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that the person labeled <code>a<sub>i</sub></code> does not like the person labeled <code>b<sub>i</sub></code>, return <code>true</code> <em>if it is possible to split everyone into two groups in this way</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 4, dislikes = [[1,2],[1,3],[2,4]]
<strong>Output:</strong> true
<strong>Explanation:</strong> group1 [1,4] and group2 [2,3].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, dislikes = [[1,2],[1,3],[2,3]]
<strong>Output:</strong> false
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> n = 5, dislikes = [[1,2],[2,3],[3,4],[4,5],[1,5]]
<strong>Output:</strong> false
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 2000</code></li>
<li><code>0 <= dislikes.length <= 10<sup>4</sup></code></li>
<li><code>dislikes[i].length == 2</code></li>
<li><code>1 <= dislikes[i][j] <= n</code></li>
<li><code>a<sub>i</sub> < b<sub>i</sub></code></li>
<li>All the pairs of <code>dislikes</code> are <strong>unique</strong>.</li>
</ul>
|
C#
|
UTF-8
| 485
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class fasttest : MonoBehaviour {
// Use this for initialization
int tr;
int fal;
void Start () {
tr = 0;
fal = 0;
}
// Update is called once per frame
void Update () {
int temp = Random.Range(0, 2);
if (temp == 1)
tr++;
else
fal++;
Debug.Log(string.Format("random test: {0}_{1}_{2}",temp,tr,fal));
}
}
|
Shell
|
UTF-8
| 2,146
| 4.09375
| 4
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env bash
# -----------------------------------------------------------------------------
# bat-extras | Copyright (C) 2019 eth-p | MIT License
#
# Repository: https://github.com/eth-p/bat-extras
# Issues: https://github.com/eth-p/bat-extras/issues
# -----------------------------------------------------------------------------
# Returns 0 (true) if the current pager is less, otherwise 1 (false).
is_pager_less() {
[[ "$(pager_name)" = "less" ]]
return $?
}
# Returns 0 (true) if the current pager is disabled, otherwise 1 (false).
is_pager_disabled() {
[[ -z "$(pager_name)" ]]
return $?
}
# Gets the name of the pager command.
pager_name() {
if [[ -z "${SCRIPT_PAGER_CMD[0]}" ]]; then return; fi
if [[ -z "$_SCRIPT_PAGER_NAME" ]]; then
local output
output="$("${SCRIPT_PAGER_CMD[0]}" --version 2>&1)"
if head -n 1 <<<"$output" | grep '^less \d' &>/dev/null; then
_SCRIPT_PAGER_NAME="less"
else
_SCRIPT_PAGER_NAME="$(basename "${SCRIPT_PAGER_CMD[0]}")"
fi
fi
echo "$_SCRIPT_PAGER_NAME"
}
# Executes a command or function, and pipes its output to the pager (if it exists).
#
# Returns: The exit code of the command.
# Example:
# pager_exec echo hi
pager_exec() {
if [[ -n "$1" ]]; then
if [[ -n "$SCRIPT_PAGER_CMD" ]]; then
"$@" | "${SCRIPT_PAGER_CMD[@]}" "${SCRIPT_PAGER_ARGS[@]}"
return $?
else
"$@"
return $?
fi
fi
}
# Displays the output of a command or function inside the pager (if it exists).
#
# Example:
# bat | pager_display
pager_display() {
if [[ -n "$SCRIPT_PAGER_CMD" ]]; then
"${SCRIPT_PAGER_CMD[@]}" "${SCRIPT_PAGER_ARGS[@]}"
else
cat
fi
}
# -----------------------------------------------------------------------------
# Defaults.
SCRIPT_PAGER_CMD=("$PAGER")
SCRIPT_PAGER_ARGS=()
# Add arguments for the less pager.
if is_pager_less; then
SCRIPT_PAGER_ARGS=(-R)
fi
# Prefer the bat pager.
if [[ -n "${BAT_PAGER+x}" ]]; then
# [note]: This is intentional.
# shellcheck disable=SC2206
SCRIPT_PAGER_CMD=($BAT_PAGER)
SCRIPT_PAGER_ARGS=()
fi
# Prefer no pager if not a tty.
if ! [[ -t 1 ]]; then
SCRIPT_PAGER_CMD=()
SCRIPT_PAGER_ARGS=()
fi
|
Java
|
UTF-8
| 1,442
| 1.890625
| 2
|
[] |
no_license
|
package com.pfa.AppRecrutement;
import com.pfa.AppRecrutement.dao.UserRepository;
import com.pfa.AppRecrutement.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@SpringBootApplication
public class RecrutmentAppApplication {
public static void main(String[] args) {
SpringApplication.run(RecrutmentAppApplication.class, args);
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(final CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("*")
.allowedHeaders("*")
.allowCredentials(true).maxAge(3600);
}
};
}
}
|
Shell
|
UTF-8
| 362
| 3.203125
| 3
|
[] |
no_license
|
#!/bin/bash -eu
. `dirname $0`/../library/script
initd_path=/etc/init.d/virtualbox-guest-utils
# install VirtualBox guest packages
install virtualbox-guest-{dkms,utils,x11}
# disable warnings for VirtualBox Guest init.d script
name=log_warning_msg
sudo perl -pe "s/(\s*)($name .+)/\1# \2/" -i $initd_path
[[ `pcregrep -c "\s*# $name .+" $initd_path` == 1 ]]
|
PHP
|
UTF-8
| 530
| 3.234375
| 3
|
[
"MIT"
] |
permissive
|
<?php
/**
* Created by PhpStorm.
* User: shiwenyuan
* Date: 2019/12/31 13341007105@163.com
* Time: 15:37
*/
/*
* Class Solution
*/
class Solution
{
/**
* @param String[] $s
* @return NULL
*/
function reverseString(&$s)
{
// krsort($s);
$len = count($s);
for ($i=0; $i < $len/2; $i++) {
$tmp = $s[$i] ;
$s[$i] = $s[$len-$i-1];
$s[$len-$i-1] = $tmp;
}
}
}
$s = ["h","e","l","l","o"];
(new Solution())->reverseString($s);
var_export($s);
|
Java
|
UTF-8
| 1,595
| 2.5
| 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 InventApp;
import java.util.*;
/**
*
* @author master
*/
public class Sesion {
private Date fechaInicializacion;
private Date fechaFinalizacion;
private Double cashInSession;
private Cajero cajeroEnSesion;
public Sesion(Date fechaInicializacion, Date fechaFinalizacion, Double cashInSession, Cajero cajeroEnSesion) {
this.fechaInicializacion = fechaInicializacion;
this.fechaFinalizacion = fechaFinalizacion;
this.cashInSession = cashInSession;
this.cajeroEnSesion = cajeroEnSesion;
}
public Date getFechaInicializacion() {
return fechaInicializacion;
}
public void setFechaInicializacion(Date fechaInicializacion) {
this.fechaInicializacion = fechaInicializacion;
}
public Date getFechaFinalizacion() {
return fechaFinalizacion;
}
public void setFechaFinalizacion(Date fechaFinalizacion) {
this.fechaFinalizacion = fechaFinalizacion;
}
public Double getCashInSession() {
return cashInSession;
}
public void setCashInSession(Double cashInSession) {
this.cashInSession = cashInSession;
}
public Cajero getCajeroEnSesion() {
return cajeroEnSesion;
}
public void setCajeroEnSesion(Cajero cajeroEnSesion) {
this.cajeroEnSesion = cajeroEnSesion;
}
public void guardarSesionDB(){
}
}
|
SQL
|
UTF-8
| 22,927
| 3.234375
| 3
|
[] |
no_license
|
-- phpMyAdmin SQL Dump
-- version 4.8.5
-- https://www.phpmyadmin.net/
--
-- Hôte : localhost
-- Généré le : Dim 05 mai 2019 à 20:44
-- Version du serveur : 8.0.13-4
-- Version de PHP : 7.2.17-0ubuntu0.18.04.1
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de données : `mVklwn0hfR`
--
-- --------------------------------------------------------
--
-- Structure de la table `competence`
--
CREATE TABLE `competence` (
`id` int(11) NOT NULL,
`sujet` varchar(255) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Déchargement des données de la table `competence`
--
INSERT INTO `competence` (`id`, `sujet`) VALUES
(9, 'AMAZON AWS'),
(10, 'ANDROID'),
(11, 'APACHE'),
(12, 'API'),
(13, 'AS400'),
(14, 'BI'),
(15, 'BIG DATA'),
(16, 'C'),
(17, 'Cloud AWS'),
(18, 'DATASTAGE'),
(1, 'HTML'),
(19, 'JAVA'),
(39, 'JAVASCRIPT'),
(40, 'JBOSS'),
(38, 'JMS'),
(37, 'JQUERY'),
(2, 'JSP'),
(36, 'JUNIPER'),
(35, 'Kubernetes'),
(34, 'LAMP'),
(7, 'LINUX'),
(33, 'MAC OS'),
(32, 'MS-DOS'),
(3, 'MySQL'),
(31, 'ORACLE'),
(8, 'PHP'),
(4, 'Tomcat'),
(5, 'Weblogic'),
(6, 'WebSphere');
-- --------------------------------------------------------
--
-- Structure de la table `parcours`
--
CREATE TABLE `parcours` (
`id` int(11) NOT NULL,
`score` int(11) DEFAULT NULL,
`duree` int(11) DEFAULT NULL,
`id_utilisateur` int(11) DEFAULT NULL,
`id_questionnaire` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Déchargement des données de la table `parcours`
--
INSERT INTO `parcours` (`id`, `score`, `duree`, `id_utilisateur`, `id_questionnaire`) VALUES
(1, 0, 0, 92, 2),
(2, 0, 0, 92, 1);
-- --------------------------------------------------------
--
-- Structure de la table `parcours_reponse`
--
CREATE TABLE `parcours_reponse` (
`id_parcours` int(11) NOT NULL,
`id_reponse` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- --------------------------------------------------------
--
-- Structure de la table `question`
--
CREATE TABLE `question` (
`id` int(11) NOT NULL,
`valeur` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`statut` tinyint(1) DEFAULT NULL,
`id_questionnaire` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Déchargement des données de la table `question`
--
INSERT INTO `question` (`id`, `valeur`, `statut`, `id_questionnaire`) VALUES
(1, 'Que signifie HTML?', 1, 1),
(2, 'Quand le langage HTML a-t-il été créé ?', 1, 1),
(3, 'Qui est l\'inventeur du langage HTML ?', 1, 1),
(4, 'Avec quelles balises pouvez changer le texte en gras ?', 1, 1),
(5, 'Si j\'utilise la balise <blink> que va-t-il se passer ?', 1, 1),
(6, 'Si je tape é, quelle lettre vais-je obtenir ?', 1, 1),
(7, 'Quel est le code hexadécimal de la couleur rouge ?', 1, 1),
(8, 'Comment puis-je transformer une image en zône cliquable ?', 1, 1),
(9, 'A quoi sert l\'option VLINK dans la balise BODY ?', 1, 1),
(10, 'Quelle est la couleur par défaut de l\'option ALINK dans la balise BODY ?', 1, 1),
(11, 'Lequel des éléments suivants n’est pas un concept POO en Java?', 1, 2),
(12, 'Quand la surcharge de méthode est-elle déterminée?', 1, 2),
(13, 'Quand la surcharge ne se produit pas?', 1, 2),
(14, 'Quel concept de Java est un moyen de convertir des objets du monde réel en termes de classe?', 1, 2),
(15, 'Quel concept de Java est utilisé en combinant des méthodes et des attributs dans une classe?', 1, 2),
(16, 'Comment ça s’appelle si un objet a son propre cycle de vie?', 1, 2),
(17, 'Comment s’appelle-t-on dans le cas où l’objet d’une classe mère est détruit donc l’objet d’une classe fille sera détruit également?', 1, 2),
(18, 'Comment s’appelle-t-on l’objet a son propre cycle de vie et l’objet d’une classe fille ne dépend pas à un autre objet d’une classe mère?', 1, 2),
(19, 'La surcharge d’une méthode peut remplacer l’héritage et le polymorphisme?', 1, 2),
(20, 'Quels keywords sont utilisés pour spécifier la visibilité des propriétés et des méthodes ?', 1, 2);
-- --------------------------------------------------------
--
-- Structure de la table `questionnaire`
--
CREATE TABLE `questionnaire` (
`id` int(11) NOT NULL,
`valeur` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`statut` tinyint(1) DEFAULT NULL,
`id_competence` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Déchargement des données de la table `questionnaire`
--
INSERT INTO `questionnaire` (`id`, `valeur`, `statut`, `id_competence`) VALUES
(1, 'QCM HTML', 1, 1),
(2, 'QCM Java – Programmation Orientée Objet', 1, 19);
-- --------------------------------------------------------
--
-- Structure de la table `reponse`
--
CREATE TABLE `reponse` (
`id` int(11) NOT NULL,
`valeur` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`statut` tinyint(1) DEFAULT NULL,
`bonne` tinyint(1) DEFAULT NULL,
`id_question` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Déchargement des données de la table `reponse`
--
INSERT INTO `reponse` (`id`, `valeur`, `statut`, `bonne`, `id_question`) VALUES
(55, 'Hyper Technology Mixed Language', 1, 0, 1),
(56, 'HyperText Markup Language', 1, 1, 1),
(57, 'Hot Text Mapping Language', 1, 0, 1),
(58, '1970', 1, 0, 2),
(59, '1986', 1, 0, 2),
(60, '1990', 1, 1, 2),
(61, 'Bill Gates', 1, 0, 3),
(62, 'Tim Berners-Lee', 1, 1, 3),
(63, 'Emmanuel Gérard', 1, 0, 3),
(64, '<br></br>', 1, 0, 4),
(65, '<b></b>', 1, 1, 4),
(66, '<p></p>', 1, 0, 4),
(67, 'le texte sera rayé', 1, 0, 5),
(68, 'le texte sera en surbrillance', 1, 1, 5),
(69, 'le texte clignotera', 1, 0, 5),
(70, 'è', 1, 1, 6),
(71, 'é', 1, 0, 6),
(72, 'ê', 1, 0, 6),
(73, '#00FF00', 1, 0, 7),
(74, '#0000FF', 1, 0, 7),
(75, '#FF0000', 1, 1, 7),
(76, 'à positionner la couleur d\'un lien qui n\'a pas encore été visité', 1, 0, 9),
(77, 'à positionner la couleur d\'un lien au moment où l\'on clique dessus', 1, 0, 9),
(78, 'à positionner la couleur d\'un lien qui a déjà été visité', 1, 1, 9),
(79, 'rouge', 1, 0, 10),
(80, 'violet', 1, 0, 10),
(81, 'bleu', 1, 1, 10),
(82, 'Je ne sais pas', 1, 0, 1),
(83, '2000', 1, 0, 2),
(84, 'Emmanuel Macron', 1, 0, 3),
(85, '<gras></gras>', 1, 0, 4),
(86, 'le texte sera invisible', 1, 0, 5),
(87, 'e', 1, 0, 6),
(88, '#000000', 1, 0, 7),
(89, 'Je ne sais pas', 1, 1, 9),
(90, 'noire', 1, 0, 10),
(91, 'Héritage', 1, 0, 11),
(92, 'Encapsulation', 1, 0, 11),
(93, 'Polymorphisme', 1, 0, 11),
(94, 'Compilation', 1, 1, 11),
(95, 'Au moment de l’exécution', 1, 0, 12),
(96, 'Au moment de la compilation', 1, 0, 12),
(97, 'Au moment du codage', 1, 1, 12),
(98, 'Au moment de l’exécution', 1, 0, 12),
(99, 'Quand il y a plusieurs méthodes avec le même nom mais avec une signature de méthode différente et un nombre ou un type de paramètres différent', 1, 0, 13),
(100, 'Quand il y a plusieurs méthodes avec le même nom, le même nombre de paramètres et le type mais une signature différente', 1, 1, 13),
(101, 'Quand il y a plusieurs méthodes avec le même nom, la même signature, le même nombre de paramètres mais un type différent', 1, 0, 13),
(102, 'Quand il y a plusieurs méthodes avec le même nom, la même signature mais avec différente signature', 1, 0, 13),
(103, 'Polymorphisme', 1, 0, 14),
(104, 'Encapsulation', 1, 0, 14),
(105, 'Abstraction', 1, 1, 14),
(106, 'Héritage', 1, 0, 14),
(107, 'Agrégation', 1, 0, 15),
(108, 'Composition', 1, 1, 15),
(109, 'Encapsulation', 1, 0, 15),
(110, 'Association', 1, 0, 15),
(111, 'Agrégation', 1, 0, 16),
(112, 'Composition', 1, 0, 16),
(113, 'Encapsulation', 0, 1, 16),
(114, 'Association', 1, 1, 16),
(115, 'Agrégation', 1, 0, 17),
(116, 'Composition', 1, 1, 17),
(117, 'Encapsulation', 0, 1, 17),
(118, 'Association', 1, 0, 17),
(119, 'Agrégation', 1, 1, 18),
(120, 'Composition', 1, 0, 18),
(121, 'Encapsulation', 1, 0, 18),
(122, 'Association', 1, 0, 18),
(123, 'Vrai', 1, 1, 19),
(124, 'Faux', 1, 0, 19),
(125, 'final', 1, 0, 20),
(126, 'Composition', 1, 0, 20),
(127, 'private', 1, 1, 20),
(128, '<IMG SRC=\"...\"></IMG>', 1, 0, 8);
-- --------------------------------------------------------
--
-- Structure de la table `utilisateur`
--
CREATE TABLE `utilisateur` (
`id` int(11) NOT NULL,
`nom` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`prenom` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`pwd` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`statut` tinyint(1) NOT NULL,
`telephone` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`dateCreation` timestamp NULL DEFAULT NULL,
`ROLE` varchar(255) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Déchargement des données de la table `utilisateur`
--
INSERT INTO `utilisateur` (`id`, `nom`, `prenom`, `email`, `pwd`, `statut`, `telephone`, `dateCreation`, `ROLE`) VALUES
(1, 'Chapman', 'Velma', 'ligula.elit@magnaDuis.co.uk', 'SRL31PJA9YG', 0, '08 44 76 62 69', '2018-10-28 20:44:27', 'administrateur'),
(2, 'Mosley', 'Jaden', 'mi.Aliquam@loremvitae.org', 'SOY82MHX7IB', 1, '05 82 18 57 91', '2019-06-14 02:25:54', 'administrateur'),
(3, 'Head', 'Hakeem', 'egestas.a.scelerisque@lectus.net', 'TOP70CQB8CO', 0, '03 51 69 79 81', '2019-03-24 01:07:59', 'stagiaire'),
(4, 'Graham', 'Silas', 'metus.In.lorem@dolorvitaedolor.com', 'CPE64LRP6EL', 0, '02 06 92 37 54', '2018-10-05 20:33:21', 'administrateur'),
(5, 'Sutton', 'Quin', 'cursus@nascetur.ca', 'MSB66RXV9VO', 0, '08 20 43 90 91', '2019-12-07 10:39:08', 'administrateur'),
(6, 'Ingram', 'Clark', 'cursus@CuraePhasellusornare.org', 'FPF27PHM2FY', 0, '03 89 38 09 96', '2020-02-17 19:10:59', 'stagiaire'),
(7, 'Forbes', 'Kyra', 'mollis.Phasellus@Donecat.net', 'RYC40WVI8EN', 0, '01 45 72 64 01', '2019-04-04 04:13:06', 'stagiaire'),
(8, 'Vincent', 'Armando', 'Cras@sagittisaugue.ca', 'BLS41RUO6GL', 1, '09 11 32 31 46', '2020-03-14 07:25:49', 'administrateur'),
(9, 'Mcbride', 'Anjolie', 'elementum.at.egestas@semegestasblandit.com', 'AAO31EKJ3FL', 0, '02 18 62 38 10', '2018-09-17 08:10:29', 'administrateur'),
(10, 'Willis', 'Jack', 'sagittis@seddolor.ca', 'RBL31XDK2JI', 1, '01 36 49 62 38', '2020-02-07 09:44:12', 'administrateur'),
(11, 'Watts', 'Deborah', 'dolor.Fusce@estmollisnon.edu', 'MPH10SJX1KG', 1, '05 80 95 91 94', '2019-03-24 23:31:32', 'stagiaire'),
(12, 'White', 'Jolie', 'dui.Cum.sociis@ut.ca', 'RUI31BPN3HI', 1, '05 40 48 97 99', '2019-06-03 08:30:09', 'stagiaire'),
(13, 'Holman', 'Buffy', 'Vivamus.euismod.urna@diamdictum.net', 'PCB93YFT4FX', 0, '05 33 45 59 51', '2019-01-20 19:26:45', 'administrateur'),
(14, 'Hale', 'Dalton', 'egestas.Aliquam.nec@nectellusNunc.ca', 'YLN29BEC5EU', 0, '06 99 57 42 05', '2018-09-25 12:23:20', 'administrateur'),
(15, 'Avila', 'Unity', 'neque.venenatis.lacus@quisaccumsan.edu', 'WBT29HUE3WS', 0, '04 20 72 46 38', '2020-01-21 04:16:19', 'stagiaire'),
(16, 'Fisher', 'Alea', 'massa.rutrum.magna@pharetrasedhendrerit.org', 'XQB22CJA0UI', 1, '06 50 01 22 36', '2020-03-29 01:44:37', 'administrateur'),
(17, 'Gallegos', 'Sigourney', 'vel.arcu.Curabitur@augueut.com', 'ZGN26AFP1DO', 1, '02 89 97 23 99', '2018-10-06 02:22:22', 'administrateur'),
(18, 'Ward', 'Dylan', 'viverra@pedeetrisus.net', 'IZE23DYT0MP', 1, '05 24 30 21 08', '2019-01-17 02:22:57', 'administrateur'),
(19, 'Campbell', 'Mary', 'risus.Nulla.eget@montes.org', 'CWI29QHG8LF', 0, '05 69 32 19 79', '2019-04-26 16:05:52', 'administrateur'),
(20, 'Ruiz', 'Gloria', 'vitae@id.com', 'LXQ40QVV1GF', 1, '07 45 11 16 81', '2020-01-25 06:34:33', 'stagiaire'),
(21, 'Stevens', 'Adam', 'Aliquam@interdumSed.edu', 'UHS61RTP0PI', 0, '04 24 97 28 16', '2019-08-13 10:04:33', 'administrateur'),
(22, 'Christian', 'Alfreda', 'taciti.sociosqu@penatibus.co.uk', 'VOB72BKD9PO', 0, '02 38 23 37 24', '2019-08-22 18:39:02', 'stagiaire'),
(23, 'Schmidt', 'Jordan', 'dolor.dapibus@nequeInornare.net', 'UAQ03NKT0VY', 0, '06 51 76 61 40', '2018-09-25 00:04:05', 'stagiaire'),
(24, 'Massey', 'Brent', 'morbi@rutrumeuultrices.co.uk', 'EMQ46YLF3FE', 1, '05 24 26 99 03', '2018-07-19 03:40:16', 'administrateur'),
(25, 'Baker', 'Iliana', 'quis.pede@tinciduntorci.net', 'VTR59ZUP0MX', 0, '04 24 68 35 58', '2019-10-01 08:20:27', 'administrateur'),
(26, 'Calderon', 'Patricia', 'diam.at.pretium@Loremipsumdolor.net', 'IJS63WDA1LR', 1, '02 51 42 08 27', '2018-07-15 04:53:16', 'administrateur'),
(27, 'Espinoza', 'Jerry', 'mauris@ligulaNullamenim.com', 'RLH07RLZ8CU', 1, '03 60 36 38 09', '2018-05-11 08:35:21', 'stagiaire'),
(28, 'Morrow', 'Ebony', 'id@nisi.ca', 'IHH65XOO0ZS', 0, '06 54 16 29 57', '2018-09-30 01:44:29', 'administrateur'),
(29, 'Edwards', 'Halla', 'Nunc.ullamcorper@Phasellusliberomauris.edu', 'YOS47KAM2AO', 0, '08 49 91 99 25', '2018-07-20 18:55:10', 'administrateur'),
(30, 'Riley', 'Leroy', 'dui.semper@et.edu', 'YSV57NNR7LL', 1, '02 72 61 11 43', '2018-10-05 01:33:07', 'stagiaire'),
(31, 'Gill', 'Victor', 'tellus@lectus.com', 'GRT16DDB6OC', 1, '01 95 35 31 07', '2019-07-30 00:24:24', 'stagiaire'),
(32, 'Colon', 'Tara', 'elit.pellentesque.a@nislelementum.ca', 'PHB83NXO4OE', 1, '06 42 55 24 87', '2018-10-09 14:48:02', 'stagiaire'),
(33, 'Thompson', 'Rose', 'urna.Ut.tincidunt@posuerevulputate.ca', 'ATW18OXX7XN', 1, '01 54 93 89 87', '2018-07-07 15:35:13', 'stagiaire'),
(34, 'Palmer', 'Aaron', 'velit.egestas@posuerevulputatelacus.net', 'HCM05MHW4FP', 0, '08 65 11 21 78', '2019-04-29 03:36:24', 'administrateur'),
(35, 'Barker', 'Mira', 'sapien@nascetur.org', 'TCR19GSA3WX', 1, '04 35 68 94 38', '2019-03-09 07:37:02', 'stagiaire'),
(36, 'Stone', 'Jarrod', 'amet@nequevitaesemper.com', 'MKL82OIO0RY', 1, '06 62 11 22 24', '2019-10-10 15:07:47', 'administrateur'),
(37, 'Williams', 'Yuri', 'Cum@ante.net', 'EAB43DTU5XP', 0, '03 56 60 03 26', '2018-09-15 19:05:36', 'stagiaire'),
(38, 'Park', 'Dahlia', 'egestas@varius.org', 'JXN01OTC2RQ', 1, '06 45 56 71 78', '2019-09-08 09:55:30', 'stagiaire'),
(39, 'Farmer', 'Vernon', 'lacus.vestibulum@enimcommodohendrerit.net', 'JGF91OIK3TE', 1, '07 84 70 60 28', '2020-03-07 00:55:27', 'administrateur'),
(40, 'Phillips', 'Myles', 'ante.Maecenas@facilisis.ca', 'YFE96LTU0OY', 1, '08 25 10 87 48', '2019-07-15 23:28:33', 'stagiaire'),
(41, 'Gregory', 'Lars', 'sem@sem.co.uk', 'GWV39JTW5LA', 0, '07 87 17 05 56', '2019-07-16 02:09:53', 'stagiaire'),
(42, 'Hammond', 'Ainsley', 'Vivamus.euismod@id.co.uk', 'QXY81PSE1FY', 1, '09 85 10 96 23', '2018-07-20 19:34:43', 'administrateur'),
(43, 'Valentine', 'Gemma', 'nisl.arcu@dapibusligulaAliquam.com', 'MCF56IGY9GY', 0, '09 56 41 37 70', '2019-10-29 11:39:34', 'stagiaire'),
(44, 'Hogan', 'Cheryl', 'Lorem.ipsum@eleifendegestasSed.co.uk', 'JSI09VOC5KZ', 1, '05 01 53 83 17', '2018-09-29 06:10:52', 'stagiaire'),
(45, 'Mack', 'Leandra', 'urna.Ut.tincidunt@Nullamscelerisque.ca', 'YCW17BYR7BH', 1, '07 87 59 19 27', '2019-08-02 02:53:34', 'stagiaire'),
(46, 'Evans', 'Bethany', 'quam.Curabitur@feugiatplaceratvelit.com', 'MSX99UET8LA', 1, '04 48 30 17 96', '2019-12-01 00:03:55', 'stagiaire'),
(47, 'Cox', 'Lenore', 'ornare@Duismienim.org', 'TJS51TFH2DV', 0, '03 68 89 75 35', '2019-10-11 20:55:44', 'administrateur'),
(48, 'Montgomery', 'Ahmed', 'sociis@facilisisloremtristique.ca', 'LAS02JBF0YZ', 0, '06 67 15 24 85', '2019-03-19 20:39:28', 'stagiaire'),
(49, 'Landry', 'Cailin', 'a@Vestibulumut.org', 'HXY00DPI8QC', 0, '01 45 79 34 61', '2020-03-25 04:28:22', 'administrateur'),
(50, 'Lynch', 'Kim', 'aliquet.metus.urna@nec.co.uk', 'MXJ22JNB8LT', 0, '06 99 23 16 45', '2018-11-06 14:53:18', 'administrateur'),
(51, 'Roman', 'Dominique', 'erat.Sed@montesnasceturridiculus.edu', 'UCF04CBD5FN', 1, '06 20 69 85 55', '2019-09-27 06:10:15', 'stagiaire'),
(52, 'Vargas', 'Briar', 'vel@Suspendissealiquet.org', 'DCG29PTS5FL', 1, '04 01 79 20 81', '2018-05-10 00:02:41', 'administrateur'),
(53, 'Acevedo', 'Imelda', 'velit@Phasellus.com', 'ENL47DFY3KZ', 0, '04 33 56 84 05', '2019-04-05 07:12:08', 'stagiaire'),
(54, 'Benton', 'Hashim', 'scelerisque@risusQuisquelibero.net', 'LYK05MLB4SM', 0, '08 86 57 27 00', '2019-10-27 00:23:01', 'administrateur'),
(55, 'Erickson', 'Bethany', 'sem.ut.dolor@Nullamsuscipitest.net', 'MVG26JEY6WU', 0, '07 41 07 15 29', '2020-02-27 10:51:05', 'administrateur'),
(56, 'Chen', 'Ina', 'Ut@liberoInteger.edu', 'QNQ48MWY8LR', 0, '05 34 99 08 44', '2018-12-05 03:16:03', 'administrateur'),
(57, 'Noel', 'Veronica', 'magna.malesuada.vel@in.org', 'ZXL44DTF6AR', 1, '09 86 40 12 89', '2019-09-16 18:28:34', 'stagiaire'),
(58, 'Vaughn', 'Kai', 'metus.In@egestasadui.edu', 'ICB54IYC3DC', 0, '02 76 44 12 15', '2019-08-03 17:33:57', 'administrateur'),
(59, 'Rodriguez', 'Lesley', 'justo.eu@massaMaurisvestibulum.ca', 'JMT75NZA9ZK', 1, '08 73 91 05 29', '2019-08-28 03:44:44', 'stagiaire'),
(60, 'Stevens', 'Gloria', 'Morbi@blandit.co.uk', 'QSI43BOC0HH', 1, '01 75 63 93 66', '2019-09-22 15:39:04', 'administrateur'),
(61, 'Gardner', 'Ivana', 'magna@ultricesiaculis.org', 'WNN32MRE7FR', 1, '07 00 22 45 39', '2019-09-01 08:00:16', 'stagiaire'),
(62, 'Charles', 'Sage', 'luctus.vulputate@elementumdui.ca', 'WOP96QDA2YU', 0, '05 54 27 33 38', '2020-02-13 02:29:05', 'administrateur'),
(63, 'Dixon', 'Helen', 'sem.Pellentesque.ut@tellusPhaselluselit.edu', 'FBR08NRN5TM', 0, '04 07 92 87 19', '2018-07-30 05:02:49', 'stagiaire'),
(64, 'French', 'Chase', 'facilisis.facilisis.magna@auguescelerisque.com', 'OUQ12NAC0QA', 1, '02 10 46 10 99', '2019-03-12 07:00:47', 'stagiaire'),
(65, 'Ortega', 'Desiree', 'placerat@cursusnon.edu', 'AFS89FEU0TM', 0, '02 86 10 66 53', '2019-05-12 03:35:01', 'administrateur'),
(66, 'Kinney', 'Margaret', 'erat.Sed@quis.co.uk', 'RIQ02LHZ3JS', 0, '05 15 08 69 36', '2018-11-27 16:53:34', 'stagiaire'),
(67, 'Lyons', 'Larissa', 'Mauris@faucibusorci.ca', 'CSH20MJY4IP', 1, '04 45 33 99 14', '2019-10-04 12:53:40', 'administrateur'),
(68, 'Patton', 'Jarrod', 'sit@ultricesposuerecubilia.org', 'OHD99YYX6VP', 1, '09 69 61 97 33', '2019-06-20 19:54:53', 'administrateur'),
(69, 'Pitts', 'Kane', 'Integer.vitae.nibh@velitQuisque.co.uk', 'LEO90UYX6MT', 1, '05 23 52 77 23', '2019-08-25 20:03:06', 'administrateur'),
(70, 'Hansen', 'Raja', 'Suspendisse.tristique.neque@sedpedeCum.com', 'CCZ27CDH7IR', 0, '05 68 30 74 74', '2019-08-31 02:56:17', 'administrateur'),
(71, 'Vasquez', 'Sasha', 'nec@ornarefacilisiseget.net', 'TIB78TSX1FB', 1, '09 76 60 14 87', '2019-12-06 17:58:58', 'administrateur'),
(72, 'Caldwell', 'Magee', 'dictum@mauris.org', 'RFC47ELN4YH', 0, '05 89 76 80 08', '2018-06-01 03:57:19', 'stagiaire'),
(73, 'Ware', 'Hilel', 'vulputate@risusa.edu', 'HBM84STT5ZJ', 0, '08 11 16 53 50', '2018-07-27 16:01:39', 'stagiaire'),
(74, 'Hopkins', 'Tatyana', 'Donec.est@montesnasceturridiculus.edu', 'TCB28NPQ6SK', 0, '06 34 01 38 22', '2018-06-26 14:07:09', 'administrateur'),
(75, 'Sloan', 'Cody', 'fringilla.cursus.purus@ametnullaDonec.org', 'DSO34JUD8EJ', 0, '08 82 90 54 02', '2019-12-21 02:45:29', 'stagiaire'),
(76, 'Gordon', 'Ruby', 'adipiscing@sociisnatoquepenatibus.com', 'XZL51AUZ2IA', 1, '02 35 22 88 52', '2019-08-08 09:11:54', 'administrateur'),
(77, 'Cohen', 'Tobias', 'magna.et.ipsum@sit.co.uk', 'UOW10QNS0GS', 0, '02 40 36 57 60', '2020-01-09 22:11:16', 'stagiaire'),
(78, 'Hutchinson', 'Matthew', 'Nullam.vitae@In.org', 'ISF08GAK5LM', 1, '01 60 87 27 62', '2018-12-16 00:50:01', 'stagiaire'),
(79, 'Nichols', 'Lee', 'dictum.Phasellus@consequatlectussit.ca', 'DNS50CBF9JC', 0, '02 58 56 93 36', '2018-04-30 15:31:30', 'stagiaire'),
(80, 'Mcclure', 'Basia', 'a.felis@magnaPhasellus.ca', 'UKR48WUE8MG', 0, '04 73 00 89 20', '2019-11-21 09:16:03', 'stagiaire'),
(81, 'Cooley', 'Karleigh', 'Praesent.eu@ante.co.uk', 'VJR51GFP3JW', 0, '03 55 32 20 32', '2019-03-30 08:16:49', 'stagiaire'),
(82, 'Mcclure', 'Alisa', 'non.magna.Nam@ipsum.net', 'LMG26NDF9DX', 1, '01 92 97 22 13', '2018-10-29 15:27:04', 'stagiaire'),
(83, 'Simpson', 'Berk', 'euismod@magnisdisparturient.net', 'BCZ50MLD7GW', 0, '02 72 27 14 39', '2019-03-28 22:35:16', 'administrateur'),
(84, 'Ballard', 'Jermaine', 'facilisis.Suspendisse.commodo@Nullamlobortis.com', 'DZV82GQV3KN', 1, '02 36 73 97 33', '2018-12-26 20:54:06', 'stagiaire'),
(85, 'Foreman', 'Lydia', 'orci.tincidunt@Cras.ca', 'ZYJ29HEE1XL', 1, '03 10 22 88 35', '2020-01-25 11:31:11', 'stagiaire'),
(86, 'Rivers', 'Chastity', 'pharetra.felis@sociosquad.com', 'JPS12MEA5OT', 1, '04 55 95 86 83', '2019-03-27 13:42:54', 'stagiaire'),
(87, 'Chapman', 'Joshua', 'ornare.placerat.orci@Suspendissesed.edu', 'PUN90BHX6OO', 0, '05 50 63 38 64', '2018-05-10 22:23:29', 'stagiaire'),
(88, 'Fuentes', 'Yael', 'sapien.Cras.dolor@felisadipiscing.com', 'KUE19NHJ0YA', 1, '04 04 57 00 15', '2018-10-30 20:17:15', 'stagiaire'),
(89, 'Hayden', 'MacKenzie', 'libero.Proin.sed@ullamcorpereu.org', 'KLE53SGG9QD', 0, '04 02 82 45 77', '2018-08-15 15:34:03', 'stagiaire'),
(90, 'Weaver', 'Amery', 'ultrices@erat.net', 'ZVZ09AQV7DZ', 0, '04 13 16 90 20', '2019-08-11 00:28:06', 'administrateur'),
(91, 'Admin', 'Admin', 'admin@admin.com', 'admin1234', 1, '04 98 52 16 84', '2018-09-21 21:10:47', 'administrateur'),
(92, 'Test', 'Test', 'test@test.com', 'test1234', 1, '08 65 33 00 89', '2018-09-21 09:50:51', 'stagiaire'),
(93, 'Stagiaire', 'Stagiaire', 'stagiaire@stagiaire.com', 'stagiaire1234', 1, '08 65 33 00 89', '2018-09-21 09:50:51', 'stagiaire');
--
-- Index pour les tables déchargées
--
--
-- Index pour la table `competence`
--
ALTER TABLE `competence`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `sujet` (`sujet`);
--
-- Index pour la table `parcours`
--
ALTER TABLE `parcours`
ADD PRIMARY KEY (`id`),
ADD KEY `id_utilisateur` (`id_utilisateur`),
ADD KEY `id_questionnaire` (`id_questionnaire`);
--
-- Index pour la table `parcours_reponse`
--
ALTER TABLE `parcours_reponse`
ADD PRIMARY KEY (`id_parcours`,`id_reponse`),
ADD KEY `id_reponse` (`id_reponse`);
--
-- Index pour la table `question`
--
ALTER TABLE `question`
ADD PRIMARY KEY (`id`),
ADD KEY `id_questionnaire` (`id_questionnaire`);
--
-- Index pour la table `questionnaire`
--
ALTER TABLE `questionnaire`
ADD PRIMARY KEY (`id`),
ADD KEY `id_competence` (`id_competence`);
--
-- Index pour la table `reponse`
--
ALTER TABLE `reponse`
ADD PRIMARY KEY (`id`),
ADD KEY `id_question` (`id_question`);
--
-- Index pour la table `utilisateur`
--
ALTER TABLE `utilisateur`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT pour les tables déchargées
--
--
-- AUTO_INCREMENT pour la table `competence`
--
ALTER TABLE `competence`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=41;
--
-- AUTO_INCREMENT pour la table `parcours`
--
ALTER TABLE `parcours`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT pour la table `question`
--
ALTER TABLE `question`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=21;
--
-- AUTO_INCREMENT pour la table `questionnaire`
--
ALTER TABLE `questionnaire`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT pour la table `reponse`
--
ALTER TABLE `reponse`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=129;
--
-- AUTO_INCREMENT pour la table `utilisateur`
--
ALTER TABLE `utilisateur`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=94;
--
-- Contraintes pour les tables déchargées
--
--
-- Contraintes pour la table `parcours`
--
ALTER TABLE `parcours`
ADD CONSTRAINT `parcours_ibfk_1` FOREIGN KEY (`id_utilisateur`) REFERENCES `utilisateur` (`id`),
ADD CONSTRAINT `parcours_ibfk_2` FOREIGN KEY (`id_questionnaire`) REFERENCES `questionnaire` (`id`);
--
-- Contraintes pour la table `parcours_reponse`
--
ALTER TABLE `parcours_reponse`
ADD CONSTRAINT `parcours_reponse_ibfk_1` FOREIGN KEY (`id_parcours`) REFERENCES `parcours` (`id`),
ADD CONSTRAINT `parcours_reponse_ibfk_2` FOREIGN KEY (`id_reponse`) REFERENCES `reponse` (`id`);
--
-- Contraintes pour la table `question`
--
ALTER TABLE `question`
ADD CONSTRAINT `question_ibfk_1` FOREIGN KEY (`id_questionnaire`) REFERENCES `questionnaire` (`id`);
--
-- Contraintes pour la table `questionnaire`
--
ALTER TABLE `questionnaire`
ADD CONSTRAINT `questionnaire_ibfk_1` FOREIGN KEY (`id_competence`) REFERENCES `competence` (`id`);
--
-- Contraintes pour la table `reponse`
--
ALTER TABLE `reponse`
ADD CONSTRAINT `reponse_ibfk_1` FOREIGN KEY (`id_question`) REFERENCES `question` (`id`);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
Markdown
|
UTF-8
| 2,171
| 2.78125
| 3
|
[] |
no_license
|
# Article 1
Les appellations autorisées pour les établissements de soins vétérinaires sont le « cabinet vétérinaire », la « clinique vétérinaire », le « centre hospitalier vétérinaire » et le « centre de vétérinaires spécialistes ».
Pour se prévaloir d'une de ces appellations, l'établissement de soins doit répondre aux exigences minimales en termes de locaux, de matériels, de modules d'activité, de personnel et d'horaires d'ouverture telles que précisées dans le présent arrêté ainsi que, le cas échéant, aux exigences spécifiques en termes de compétences, de locaux et de matériels précisées dans le cahier des charges établi pour chacune des catégories d'établissements de soins vétérinaires et en fonction des espèces soignées. Ce cahier des charges est établi et tenu à jour par le Conseil supérieur de l'ordre des vétérinaires et publié sur son site internet.
Un module d'activité est un ensemble de prestations et de matériels concernant une activité revendiquée au sein d'un établissement de soins vétérinaires. Il constitue la norme minimale pour que l'établissement de soins vétérinaires puisse faire état de l'activité revendiquée dans sa communication auprès du public. Les modules peuvent être complétés par le cahier des charges susmentionné.
Indépendamment de la communication relative aux modules, une information du public sur les activités développées dans l'établissement de soins est possible.
Les appellations précisant les espèces soignées sont autorisées.
Dès lors que l'activité d'un établissement de soins vétérinaires est mixte, les conditions générales de fonctionnement de l'établissement de soins précisent explicitement au public les espèces soignées concernées par l'appellation.
Les précautions nécessaires pour isoler les animaux contagieux sont prises.
Pour l'application du présent arrêté, on retient pour la définition du temps plein pour un docteur vétérinaire :
- celle en vigueur en droit du travail s'il est salarié ;
- la même durée hebdomadaire de présence au sein de l'établissement s'il est de statut libéral.
|
Markdown
|
UTF-8
| 1,203
| 2.53125
| 3
|
[] |
no_license
|
## Bookmarks tagged [[runtime]](https://www.bookmarks.dev/search?q=[runtime])
_<sup><sup>[www.bookmarks.dev/tagged/runtime](https://www.bookmarks.dev/tagged/runtime)</sup></sup>_
---
#### [Byte Buddy - runtime code generation for the Java virtual machine](https://bytebuddy.net/#/)
_<sup>https://bytebuddy.net/#/</sup>_
Byte Buddy is a code generation and manipulation library for creating and modifying Java classes during the runtime of a Java application and without the help of a compiler. Other than the code genera...
* **tags**: [java](../tagged/java.md), [virtual-machine](../tagged/virtual-machine.md), [jvm](../tagged/jvm.md), [runtime](../tagged/runtime.md)
* :octocat: **[source code](https://github.com/raphw/byte-buddy)**
---
#### [Tokio home page](https://tokio.rs/)
_<sup>https://tokio.rs/</sup>_
Tokio is an asynchronous runtime for the Rust programming language. It provides the building blocks needed for writing network applications. It gives the flexibility to target a wide range of systems,...
* **tags**: [rust](../tagged/rust.md), [asynchronous](../tagged/asynchronous.md), [runtime](../tagged/runtime.md)
* :octocat: **[source code](https://github.com/tokio-rs/tokio)**
---
|
Python
|
UTF-8
| 1,738
| 4.15625
| 4
|
[] |
no_license
|
#Ref:
#https://github.com/williamfiset/Algorithms/blob/master/src/main/java/com/williamfiset/algorithms/search/InterpolationSearch.java
#https://www.geeksforgeeks.org/interpolation-search/
#For uniform distrubtion list.
#Worst Case O(n)
#Avearge Case O(log(log(n)))
#When element to be search si closer to data[hi]
# mid value ideally is higher opposite if element is closer to data[lo]
#Formula for mid:
# Let's assume that the elements of the array are linearly distributed.
# General equation of line : y = m*x + c.
# y is the value in the array and x is its index.
# Now putting value of lo,hi and x in the equation
# arr[hi] = m*hi+c ----(1)
# arr[lo] = m*lo+c ----(2)
# x = m*pos + c ----(3)
# m = (arr[hi] - arr[lo] )/ (hi - lo)
# subtracting eqxn (2) from (3)
# x - arr[lo] = m * (pos - lo)
# lo + (x - arr[lo])/m = pos
# pos = lo + (x - arr[lo]) *(hi - lo)/(arr[hi] - arr[lo])
class interpolationSearch:
def __init__(self, sortedData, value):
self.data = sortedData
self.value = value
def search(self):
lo = 0
mid = 0
hi = len(self.data) - 1
while (self.data[lo] <= self.value and self.data[hi] >= self.value):
mid = lo + ((self.value - self.data[lo]) *(hi - lo)) / (self.data[hi] - self.data[lo])
mid = int(mid)
if(self.data[mid] < self.value):
lo = mid + 1
elif (self.data[mid] > self.value):
hi = mid - 1
else:
return mid
if (self.data[lo]==self.value):
return lo
return None
data = ["10", "20", "25", "35", '50', '70', '85', '100', '110', '120', '125']
test = interpolationSearch(data,'25')
print(test.search())
|
C#
|
UTF-8
| 504
| 3.15625
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_Euler___C_Sharp {
static class RandomSequence {
public static int[] RandomList(int length) {
List<int> numbers = new List<int>(length);
Random rand = new Random();
for (int i = 0; i < length; i++) {
numbers.Add(rand.Next(-20, 20));
}
return numbers.ToArray();
}
}
}
|
C++
|
UTF-8
| 2,980
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
#pragma once
#include <SFML/Graphics.hpp>
#include "engine/physics/physics.hpp"
#include "engine/common/utils.hpp"
struct Renderer
{
const CIVector<PhysicObject>& objects;
sf::RenderTarget& target;
sf::VertexArray objects_va;
sf::Texture circle_texture;
sf::RenderStates render_states;
Renderer(sf::RenderTarget& target_, CIVector<PhysicObject>& objects_)
: objects(objects_)
, target(target_)
, objects_va(sf::Quads)
{
// Load texture
circle_texture.loadFromFile("res/circle.png");
render_states.texture = &circle_texture;
// Initialize vertex array
const uint64_t objects_count = objects.size();
objects_va.resize(4 * objects_count);
for (uint64_t i(0); i < objects_count; ++i) {
objects_va[4 * i + 0].texCoords = { 0.0f , 0.0f };
objects_va[4 * i + 1].texCoords = { 512.0f, 0.0f };
objects_va[4 * i + 2].texCoords = { 512.0f, 512.0f };
objects_va[4 * i + 3].texCoords = { 0.0f , 512.0f };
}
}
void updateVA()
{
const uint64_t objects_count = objects.size();
objects_va.resize(4 * objects_count);
for (uint64_t i(0); i < objects_count; ++i) {
const PhysicObject& o = objects[i];
const sf::Vector2f vel = o.getVelocity();
const float speed = 1.0f * getLength(vel);
const float pressure = 1.0f * o.pressure;
const float base = 5.0f;
const float intensity = base + pressure + speed;
const float r = 100.0f * (pressure + speed);
const float g = 10.0f * pressure;
const float b = 1500.0f * speed;
const sf::Color color(
std::max(std::min(255.0f, r), 0.0f),
std::max(std::min(255.0f, g), 0.0f),
std::max(std::min(255.0f, b), 0.0f),
100
);
//sf::Color color = sf::Color::White;
const sf::Vector2f vel_v = vel / speed;
const sf::Vector2f vel_n = { -vel_v.y, vel_v.x };
const float width = 1.0f + 3.0f * speed;
objects_va[4 * i + 0].position = o.position + width * vel_v + 0.35f * width * vel_n;
objects_va[4 * i + 1].position = o.position + width * vel_v - 0.35f * width * vel_n;
objects_va[4 * i + 2].position = o.position - width * vel_v - 0.35f * width * vel_n;
objects_va[4 * i + 3].position = o.position - width * vel_v + 0.35f * width * vel_n;
objects_va[4 * i + 0].color = color;
objects_va[4 * i + 1].color = color;
objects_va[4 * i + 2].color = color;
objects_va[4 * i + 3].color = color;
}
}
void render(const sf::RenderStates& states)
{
updateVA();
render_states.transform = states.transform;
target.draw(objects_va, render_states);
}
};
|
Python
|
UTF-8
| 1,782
| 3.578125
| 4
|
[] |
no_license
|
class Ingredient:
"""A liquid ingredient of a mixed drink"""
def __init__(self, name, flavs = {}):
"""Returns a new Ingredient instance.
Keyword arguments:
flavs -- dictionary of string keys, the flavors, and number values:
name -- string, name of ingredient
sweetness -- scale of 0 to 1 (default 0)
proof -- 0 to 200 (default 0)
bitterness -- scale of 0 to 1 (default 0)
sourness -- scale of 0 to 1 (default 0)
flavor_strength -- how flavorful in general, scale of 0 to 1 (default 0)
carbonation -- scale of 0 to 1 (default 0)
creaminess -- scale of 0 to 1 (default 0)
"""
self.name = name
self.flavors = flavs
def add(self, amnt):
"""Print the adding of an ingredient
Keyword arguments:
amnt -- amount to add, in mL
"""
print "Adding", amnt, "mL of", self.name
def get_flavor(self, flavor):
"""Returns the value of the flavor, 0 if no value
Keyword arguments:
flavor -- string, flavor name
"""
if(self.flavors.has_key(flavor)):
return self.flavors[flavor]
return 0
def proof(self):
return self.getFlavor("proof")
def sweetness(self):
return self.getFlavor("sweetness")
def bitterness(self):
return self.getFlavor("bitterness")
def sourness(self):
return self.getFlavor("sourness")
def flavor_strength(self):
return self.getFlavor("flavor_strength")
def carbonation(self):
return self.getFlavor("carbonation")
def creaminess(self):
return self.getFlavor("creaminess")
|
TypeScript
|
UTF-8
| 261
| 2.875
| 3
|
[] |
no_license
|
export class CourseService{
static courses: string[]= ["C1", "C2", "C3"];
getCourses():string[]{
return CourseService.courses;
}
static setCourse(course:string){
CourseService.courses[CourseService.courses.length]=course;
}
}
|
Markdown
|
UTF-8
| 3,889
| 2.609375
| 3
|
[] |
no_license
|
---
layout: post
author: Hiroto Kaneko
title: Tello EDU 4台を使ったドローン編隊飛行に挑戦(第1回:ざっくり全体像)
tags:
---
今回から Tello EDU 4台を使ってドローン編隊飛行に挑戦していきます!
Tello EDU([Tello EDU 公式サイト](https://www.ryzerobotics.com/jp/tello-edu))は、香港のとなりのIT産業の盛んな町、深圳のベンチャー企業 Ryze Technology 社から発売されている小さなちいさなドローンです。同じ会社から発売されている無印の Tello との最大の違いは、なんと複数台で編隊飛行ができること!
今回から4回に分けて、プログラミング言語 Python を使った Tello EDU の編隊飛行までの道のりを紹介していきたいと思います。
[第2回](https://ku-macs-com.github.io/2020/03/25/MultiTelloPart2.html) - [第3回](https://ku-macs-com.github.io/2020/03/25/MultiTelloPart3.html) - [第4回](https://ku-macs-com.github.io/2020/03/25/MultiTelloPart4.html)
### ゴールを確認!
まずは目指すゴールを動画で確認しましょう! これは実際に京大 MACS のメンバーで編隊飛行を試みて、成功した様子を撮ったものです。このシリーズでは、これを目指していきます。
{% include youtube.html id="l33BURhMC2A" %}
{% include youtube.html id="ts2wrf0xiUg" %}
### 用意するもの
次の3つが必要になります。
1. パソコン( Windows でも Mac でもどちらでも OK )
2. Tello EDU 4台(4台でなくとも2台以上あれば OK です)
3. 無線ルータ( SSID とパスワードがわかれば既設のものでも OK )
それから、Tello EDU を飛ばせる広めのスペースも重要です!8畳ぐらいのスペースがあれば大丈夫だと思います。注意点としては、カーペット敷きなど光を散乱する床の場合、Tello EDU の能動型赤外線センサが作動しなくなり、失敗します。光を反射する床のスペースを選びましょう。
### ざっくり全体像
次のステップで編隊飛行の準備をしていきます。
1. Python 環境の構築( Anaconda のインストールと仮想環境の作成)
2. Tello EDU 編隊飛行用レポジトリ [Multi-Tello-Formation](https://github.com/TelloSDK/Multi-Tello-Formation) の導入
3. Tello EDU の設定を変更し無線ルータに接続
4. 無線ルータ経由で Tello SDK コマンドを Tello EDU に送信し編隊飛行を実行
1と2を[第2回](https://ku-macs-com.github.io/2020/03/25/MultiTelloPart2.html)、3と4を[第3回](https://ku-macs-com.github.io/2020/03/25/MultiTelloPart3.html)で詳しく紹介していきたいと思います。3と4において Tello EDU に Tello SDK コマンドを送信する際には、ソケット通信を使います。今回は Python の機能([公式ドキュメント](https://docs.python.org/ja/3/library/socket.html))を使ってソケット通信を行っていますが、node.js など別の言語を使ってもソケット通信は可能です。今回はわかりやすくするために、言語は Python に絞って説明していきます。
最終的に構築されるシステムは、図のようになります。
<img src="/images/kaneko/tello_multi_system.png" width="300">
初期設定ではドローンとパソコンが直接接続されるために1台のみしか制御できませんが、Tello EDU と無線ルータ、無線ルータとパソコン、というように無線ルータを間に挟んで接続することで、複数台(今回は4台)の編隊飛行が可能になります。
### 次回
[次回](https://ku-macs-com.github.io/2020/03/25/MultiTelloPart2.html)は、Tello EDU 編隊飛行のための Python 環境の構築について詳しく紹介していく予定です!
|
Markdown
|
UTF-8
| 3,286
| 3.234375
| 3
|
[
"MIT"
] |
permissive
|
# Matchers and Conditions (Draft)
Here we will learn how to execute Matchers depending on some given Conditions.
In complex forms use-cases, some controls directly depend on the value or status of some other form control. Then we implement custom behaviors, like `hiding` a field when another control has some value, or `disabling` it depending on a complex condition, etc.
## Definition
A `Matcher` is a task that is executed when a given set of `Conditions` are fulfilled. They are able to manipulate the form hierarchy via the `DynTreeNode`.
## Conditions
To match a special requirement, we need to define one or more conditions, so when all (AND) or one (OR) of them are fulfilled we run a particular task. The Condition Function type consists of:
```typescript
interface DynControlConditionFn {
(node: DynTreeNode): Observable<boolean>;
}
```
it streams a boolean whenever the condition is fulfilled or not, for example, we could check if a specific control has the expected value:
```typescript
(node: DynTreeNode) => {
return node.query('some.control').valueChanges.pipe(
map(controlValue => controlValue === 'xValue'),
);
}
```
we can join these conditions with the required operator (`AND | OR`) for our use-case, and then execute a specific `Matcher`.
## Matchers
We define our requirement with the Matchers that we want to run when all or a single condition is satisfied:
```typescript
match: [
{
matchers: ['DISABLE'], // one or more matchers
when: [{
// the library provides a DEFAULT condition handler to process path, value and negate
path: 'other.field',
value: 'expectedValue'
}]
}
]
```
the `DISABLE` matcher is included in the library with `ENABLE`, `SHOW`, `HIDE` (display: none), `INVISIBLE` (visibility: hidden) and `VALIDATE`.
One matcher consists of a function which performs a task in the form hierarchy; to do so, it receives the `DynTreeNode` instance:
```typescript
interface DynControlMatcherFn {
(node: DynTreeNode, hasMatch: boolean): void;
}
```
For example the `DISABLE` matcher operates into the form control when the specified conditions are fulfilled (has match):
```typescript
{
id: 'DISABLE',
fn: (): DynControlMatcherFn => {
return (node: DynTreeNode, hasMatch: boolean) => {
hasMatch ? node.control.disable() : node.control.enable();
}
}
},
```
## Conditional Validators
We have a AsyncValidator ready to be configured to conditionally validate a field depending on other control: `RELATED`. The [config-builder demo](https://mynd.dev/demos/dyn-forms/builder) uses it like this:
```typescript
name: 'serial',
asyncValidators: {
RELATED: [{ path: 'accessType', value: MyndAccessType.SmartLock }],
},
```
And the `serial` control will be required when the `accessType` field is equal to `SmartLock`. We can pass a custom `ValidatorFn` to be used too:
```typescript
asyncValidators: {
RELATED: [{ path: 'accessType', value: MyndAccessType.SmartLock }, Validators.min(3)],
},
```
## Next
- Check the article about [Conditional Matchers](https://dev.to/myndpm/conditional-tasks-in-dynamic-forms-h8) at DEV.to
- What else can we implement to support business-logic? join [this discussion](https://github.com/myndpm/open-source/discussions/4).
|
JavaScript
|
UTF-8
| 988
| 2.734375
| 3
|
[] |
no_license
|
"use strict";
export default function songChooser(settings) {
function randomItem(items) {
return items[Math.floor(Math.random() * items.length)];
}
const SPARTAK = [300, 200, 300, 200, 150, 100, 150, 100, 150, 300, 100, 100, 100, 100, 150, 100, 200, 300, 120, 130, 120, 300];
const MORTAL = [100, 200, 100, 200, 100, 200, 100, 200, 100, 100, 100, 100, 100, 200, 100, 200, 100, 200, 100, 200, 100, 100, 100, 100, 100, 200, 100, 200, 100, 200, 100, 200, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 50, 50, 100, 800];
const IMPERIAL = [500, 110, 500, 110, 450, 110, 200, 110, 170, 40, 450, 110, 200, 110, 170, 40, 500];
const songs = [SPARTAK, MORTAL, IMPERIAL];
const getRandomSong = function () {
return randomItem(songs);
};
const getSong = function () {
if (settings.useRandomSong) {
return getRandomSong();
}
return SPARTAK;
};
return {getSong: getSong};
}
|
Ruby
|
UTF-8
| 595
| 3.78125
| 4
|
[] |
no_license
|
# write a ruby script to accept a filename from the user print the extension of that
#file = "H:/3-2 subjects/SL Lab/program3.rb" #here we are explicitly taking the file name
#Reading filename
puts "Enter the file name: "
file = gets.chomp
#filename
fname = File.basename file
puts "File name: " + fname
#basename
bname = File.basename file,".rb" #to print file name without it's extension we have included .rb
puts "Base name : " + bname
#file extension
fextn = File.extname file
puts "Entension: "+ fextn
#path of the file
fpath = File.dirname file
puts "File path is: "+ fpath
|
Java
|
UTF-8
| 991
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
public class w
{
public char n;
public int w;
}
package <missing>;
public class GlobalMembers
{
public static w[] a = tangible.Arrays.initializeWithDefaultwInstances(4);
public static void Main()
{
int z;
int q;
int s;
int l;
int i;
int j;
int t;
char x;
for (z = 1;z < 60;z++)
{
for (q = 1;q < 60;q++)
{
for (s = 1;s < 60;s++)
{
for (l = 1;l < 60;l++)
{
if (z % 10 == 0 && q % 10 == 0 && s % 10 == 0 && l % 10 == 0 && z + q == s + l && z + l > s + q && z + s < q)
{
a[0].n = 'z';
a[0].w = z;
a[1].n = 'q';
a[1].w = q;
a[2].n = 's';
a[2].w = s;
a[3].n = 'l';
a[3].w = l;
}
}
}
}
}
for (i = 0;i < 3;i++)
{
for (j = 0;j < 3 - i;j++)
{
if (a[j].w < a[j + 1].w)
{
t = a[j].w;
a[j].w = a[j + 1].w;
a[j + 1].w = t;
x = a[j].n;
a[j].n = a[j + 1].n;
a[j + 1].n = x;
}
}
}
for (i = 0;i < 4;i++)
{
System.out.printf("%c %d\n",a[i].n,a[i].w);
}
}
}
|
Markdown
|
UTF-8
| 933
| 3.1875
| 3
|
[] |
no_license
|
# Game.TicTacToe
TicTacToe game problem
Tic-Tac-Toe
Tic tac toe console game in C#
What?
Tic-tac-toe (also known as noughts and crosses or Xs and Os) is a game for two players, X and O,
who take turns marking the spaces in a 3×3 grid. The player who succeeds in placing three of their marks in a horizontal, vertical
or diagonal row wins the game. This is a simple console game with either two players for playing or user playing with computer
To run the application you need to install .NET Core runtime on your system.
To run the application first traverse to the folder that has .csproj available. In this casse it would be ..\Game.TicTacToe\Game.TicTacToe
Now run the following command : dotnet run
To run the tests traverse to the following location : ..\Game.TicTacToe\Game.TicTacToe.Tests
Now run the following command : dotnet test /p:CollectCoverage=true /p:CoverletOutput=TestResults/ /p:CoverletOutputFormat=lcov
|
JavaScript
|
UTF-8
| 2,162
| 4
| 4
|
[] |
no_license
|
// Assignment Code
var generateBtn = document.querySelector("#generate");
// Write password to the #password input
function writePassword() {
var password = generatePassword();
var passwordText = document.querySelector("#password");
passwordText.value = password;
}
// Add event listener to generate button
generateBtn.addEventListener("click", writePassword);
// Prompt user and generate PW based on parameters
function generatePassword() {
var pwLength = prompt("How long would you like your password to be?");
console.log("Length: " + pwLength);
// Ensure proper validation
if ((isNaN(pwLength)) || (pwLength < 8 || pwLength > 128)) {
alert('Invalid entry. Must enter a number between 8 and 128.');
return "";
}
// Prompt for user PW requirements
var sc = confirm('Would you like to use $peci@l characters?');
var lc = confirm('Would you like to use lower case letters?');
var uc = confirm('Would you like to use Upper Case Letters?');
var nc = confirm('Would you like to use numb3rs?');
// Strings for character types
var scString = '!@#$%^&*()_+/?[]{}\|';
var lcString = 'abcdefghijklmnopqrstuvwxyz';
var ucString = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var ncString = '0123456789';
// Create the final library of characters based on user choices
var finalString = '';
function finalStringConcat() {
if (sc === true) {
finalString = finalString.concat(scString);
console.log("Include Special Characters");
}
if (lc === true) {
finalString = finalString.concat(lcString);
console.log("Include lower case characters");
}
if (uc === true) {
finalString = finalString.concat(ucString);
console.log("Include upper case characters");
}
if (nc === true) {
finalString = finalString.concat(ncString);
console.log("Include numbers");
}
}
finalStringConcat();
// Generate a random PW based on user requirements
var pwResult = '';
function makePW() {
for (i=0 ; i < pwLength; i++) {
pwResult += finalString.charAt(Math.floor(Math.random() * finalString.length));
}
}
makePW();
return pwResult;
}
|
Java
|
UTF-8
| 1,749
| 2.078125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package it.cnr.isti.labsedc.bpmls;
import org.springframework.web.bind.annotation.RequestBody;
public interface LearningProcessEngineController {
public String registerNewUser(@RequestBody String responseJSON);
public String authenticateUser(@RequestBody String responseJSON);
/**
* {status:error,errortype: ,htmlform:dynamic
* content} 1. Status is error and errortype is 'lpnonexistant',if the given
* Learning Path if not running, in which case the client app needs to
* redirect the page <br>
* 2. No Learning scenario in progress but next in line present, status is
* success with a form to start the next Learning Scenario <br>
* 3. No Learning scenario in progress and no next in line present, status
* is error and errortype is 'nonextls' because this state shouldnt be
* reached <br>
* 4. Learning Scenario present and no task present, status is error and
* errortype is 'notask' because this state shouldnt be reached <br>
* 5. Learning Scenario task and task present, status is success and the
* htmlform is the task form
*/
public String getCurrentLPStatus(String lpid, String responseJSON);
public String getAvailableLearningPaths(String responseJSON);
public String getRunningPaths(String responseJSON);
public String startalearningpath( String lpid, String responseJSON);
public String startalearningscenario(String lpid,String lpinst, String responseJSON);
public String completeCurrentLearningTask(String lpid, String responseJSON)throws Exception;
public String getLearningPathFlowDiagram(String lpid, String responseJSON);
public String getProcessDiagramDetails(String lpid, String responseJSON);
public String gerOracleValues(String lpid, String responseJSON);
}
|
Python
|
UTF-8
| 1,727
| 2.671875
| 3
|
[] |
no_license
|
from sqlparser.parser.parser import parser
from sqlparser.parser.lex import lexer
from sqlparser.output.csv_output import CsvOutput
from sqlparser.parser.boxes import QueryBox
from sqlparser.tables.abstract import AbstractTable
from sys import stdout
from typing import Dict, Type
class TableManager(object):
def __init__(self):
self.table_classes = {} # type: Dict[str, Type[AbstractTable]]
def register(self, name: str, cls=None):
def inner(cls):
self.table_classes[name] = cls
return cls
return inner if cls is None else inner(cls)
def prepare_table(self, query_box: QueryBox) -> AbstractTable:
table_name = query_box.froms[0].value
table_class = self.table_classes[table_name]
table = table_class()
table.set_columns(query_box.exprs)
if query_box.where is not None:
table.set_where(query_box.where)
if query_box.limit is not None:
table.set_limit(query_box.limit)
if query_box.offset is not None:
table.set_offset(query_box.offset)
if query_box.group_by is not None:
table.set_group_by(query_box.group_by)
return table
def execute_query(self, query: str, stream=None, output_cls=None):
output_cls = output_cls or CsvOutput
output = output_cls()
query_box = parser.parse(lexer.lex(query)) # type: QueryBox
table = self.prepare_table(query_box)
stream = stream or stdout
generator = table.generate_data()
first_row = next(generator)
stream.write(output.parse_first_row(first_row))
for row in generator:
stream.write(output.parse_row(row))
|
JavaScript
|
UTF-8
| 5,657
| 2.578125
| 3
|
[] |
no_license
|
// Generated by CoffeeScript 1.9.1
(function() {
var board, dirs, draw, fs, gameOver, hasToPass, http, idCounter, invertibles, io, player, port, put, reset, sendMessage, server, size, socketio, switchTurn, turn;
http = require("http");
fs = require("fs");
socketio = require("socket.io");
port = process.env.PORT || 5000;
server = http.createServer(function(request, response) {
switch (request.url) {
case "/":
case "/index.html":
response.writeHead(200, {
"Content-Type": "text/html"
});
response.write(fs.readFileSync("index.html"));
break;
case "/script.js":
response.writeHead(200, {
"Content-Type": "text/javascript"
});
response.write(fs.readFileSync("client.js"));
}
response.end();
}).listen(port, function() {
console.log("Listening on %d.", port);
});
io = socketio.listen(server);
idCounter = 0;
player = size = board = turn = null;
setTimeout(function() {
reset();
});
io.on("connection", function(socket) {
socket.on("login", function(name) {
var id;
id = idCounter++;
if (name === "") {
name = "Anonymous" + String(id);
socket.emit("set name", name);
}
draw();
sendMessage("[ " + name + " log in ]");
socket.on("disconnect", function() {
var color;
sendMessage("[ " + name + " log out ]");
if (player != null) {
for (color in player) {
if (player[color] === id) {
delete player[color];
}
}
}
});
socket.on("click", function(x, y) {
if ((turn != null) && player[turn] === id && (0 <= x && x < size) && (0 <= y && y < size)) {
put(x, y);
}
});
socket.on("entry", function() {
if (player.black == null) {
player.black = id;
sendMessage("[ " + name + " play as black ]");
} else if (player.white == null) {
player.white = id;
sendMessage("[ " + name + " play as white ]");
}
});
socket.on("reset", function() {
reset();
draw();
sendMessage("[ " + name + " reset ]");
});
socket.on("chat", function(text) {
sendMessage(name + ": " + text);
});
});
});
sendMessage = function(text) {
io.sockets.emit("message", text);
};
draw = function() {
io.sockets.emit("draw", size, board);
};
reset = function() {
var i, j, ref, ref1, x, y;
player = {};
size = 8;
board = [];
for (x = i = 0, ref = size; 0 <= ref ? i < ref : i > ref; x = 0 <= ref ? ++i : --i) {
board[x] = [];
for (y = j = 0, ref1 = size; 0 <= ref1 ? j < ref1 : j > ref1; y = 0 <= ref1 ? ++j : --j) {
board[x][y] = "blank";
}
}
board[3][3] = "black";
board[3][4] = "white";
board[4][3] = "white";
board[4][4] = "black";
turn = "black";
};
gameOver = function() {
var blackCnt, i, j, ref, ref1, whiteCnt, x, y;
turn = null;
blackCnt = 0;
whiteCnt = 0;
for (x = i = 0, ref = size; 0 <= ref ? i < ref : i > ref; x = 0 <= ref ? ++i : --i) {
for (y = j = 0, ref1 = size; 0 <= ref1 ? j < ref1 : j > ref1; y = 0 <= ref1 ? ++j : --j) {
switch (board[x][y]) {
case "black":
blackCnt++;
break;
case "white":
whiteCnt++;
}
}
}
sendMessage("[ black " + String(blackCnt) + "-" + String(whiteCnt) + " white ]");
};
switchTurn = function() {
switch (turn) {
case "black":
turn = "white";
break;
case "white":
turn = "black";
}
};
put = function(x, y) {
var i, invs, len, p;
invs = invertibles(x, y);
if (invs.length === 0) {
return;
}
board[x][y] = turn;
for (i = 0, len = invs.length; i < len; i++) {
p = invs[i];
board[p.x][p.y] = turn;
}
draw();
sendMessage("[ " + turn + " " + String(x) + " " + String(y) + " ]");
switchTurn();
if (hasToPass()) {
sendMessage("[ " + turn + " pass ]");
switchTurn();
if (hasToPass()) {
sendMessage("[ " + turn + " pass ]");
gameOver();
}
}
};
hasToPass = function() {
var i, j, ref, ref1, x, y;
for (x = i = 0, ref = size; 0 <= ref ? i < ref : i > ref; x = 0 <= ref ? ++i : --i) {
for (y = j = 0, ref1 = size; 0 <= ref1 ? j < ref1 : j > ref1; y = 0 <= ref1 ? ++j : --j) {
if (invertibles(x, y).length > 0) {
return false;
}
}
}
return true;
};
invertibles = function(x, y) {
var accum, d, i, len, temp, xx, yy;
if (board[x][y] !== "blank") {
return [];
}
accum = [];
for (i = 0, len = dirs.length; i < len; i++) {
d = dirs[i];
temp = [];
xx = x;
yy = y;
while (true) {
xx += d.x;
yy += d.y;
if (!((0 <= xx && xx < size) && (0 <= yy && yy < size))) {
break;
} else if (board[xx][yy] === "blank") {
break;
} else if (board[xx][yy] === turn) {
accum = accum.concat(temp);
break;
} else {
temp.push({
x: xx,
y: yy
});
}
}
}
return accum;
};
dirs = [
{
x: -1,
y: -1
}, {
x: -1,
y: 0
}, {
x: -1,
y: +1
}, {
x: 0,
y: -1
}, {
x: 0,
y: +1
}, {
x: +1,
y: -1
}, {
x: +1,
y: 0
}, {
x: +1,
y: +1
}
];
}).call(this);
|
C++
|
UTF-8
| 830
| 2.515625
| 3
|
[] |
no_license
|
#include "roomdto.h"
QString RoomDto::getName() const
{
return name;
}
void RoomDto::setName(const QString &value)
{
name = value;
}
int RoomDto::getRoomTypeId() const
{
return roomTypeId;
}
void RoomDto::setRoomTypeId(int value)
{
roomTypeId = value;
}
bool RoomDto::getNeedClean() const
{
return needClean;
}
void RoomDto::setNeedClean(bool value)
{
needClean = value;
}
bool RoomDto::getLocked() const
{
return locked;
}
void RoomDto::setLocked(bool value)
{
locked = value;
}
QString RoomDto::getDescription() const
{
return description;
}
void RoomDto::setDescription(const QString &value)
{
description = value;
}
int RoomDto::getId() const
{
return id;
}
void RoomDto::setId(int value)
{
id = value;
}
RoomDto::RoomDto(QObject *parent): QObject(parent)
{
}
|
PHP
|
UTF-8
| 4,486
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
<?php
/**
* Generated by Protobuf protoc plugin.
*
* File descriptor : Documents/Document.proto
*/
namespace AgentSIB\Diadoc\Api\Proto\Documents;
/**
* Protobuf enum : AgentSIB.Diadoc.Api.Proto.Documents.RevocationStatus
*/
class RevocationStatus extends \Protobuf\Enum
{
/**
* UnknownRevocationStatus = 0
*/
const UnknownRevocationStatus_VALUE = 0;
/**
* RevocationStatusNone = 1
*/
const RevocationStatusNone_VALUE = 1;
/**
* RevocationIsRequestedByMe = 2
*/
const RevocationIsRequestedByMe_VALUE = 2;
/**
* RequestsMyRevocation = 3
*/
const RequestsMyRevocation_VALUE = 3;
/**
* RevocationAccepted = 4
*/
const RevocationAccepted_VALUE = 4;
/**
* RevocationRejected = 5
*/
const RevocationRejected_VALUE = 5;
/**
* @var \AgentSIB\Diadoc\Api\Proto\Documents\RevocationStatus
*/
protected static $UnknownRevocationStatus = null;
/**
* @var \AgentSIB\Diadoc\Api\Proto\Documents\RevocationStatus
*/
protected static $RevocationStatusNone = null;
/**
* @var \AgentSIB\Diadoc\Api\Proto\Documents\RevocationStatus
*/
protected static $RevocationIsRequestedByMe = null;
/**
* @var \AgentSIB\Diadoc\Api\Proto\Documents\RevocationStatus
*/
protected static $RequestsMyRevocation = null;
/**
* @var \AgentSIB\Diadoc\Api\Proto\Documents\RevocationStatus
*/
protected static $RevocationAccepted = null;
/**
* @var \AgentSIB\Diadoc\Api\Proto\Documents\RevocationStatus
*/
protected static $RevocationRejected = null;
/**
* @return \AgentSIB\Diadoc\Api\Proto\Documents\RevocationStatus
*/
public static function UnknownRevocationStatus()
{
if (self::$UnknownRevocationStatus !== null) {
return self::$UnknownRevocationStatus;
}
return self::$UnknownRevocationStatus = new self('UnknownRevocationStatus', self::UnknownRevocationStatus_VALUE);
}
/**
* @return \AgentSIB\Diadoc\Api\Proto\Documents\RevocationStatus
*/
public static function RevocationStatusNone()
{
if (self::$RevocationStatusNone !== null) {
return self::$RevocationStatusNone;
}
return self::$RevocationStatusNone = new self('RevocationStatusNone', self::RevocationStatusNone_VALUE);
}
/**
* @return \AgentSIB\Diadoc\Api\Proto\Documents\RevocationStatus
*/
public static function RevocationIsRequestedByMe()
{
if (self::$RevocationIsRequestedByMe !== null) {
return self::$RevocationIsRequestedByMe;
}
return self::$RevocationIsRequestedByMe = new self('RevocationIsRequestedByMe', self::RevocationIsRequestedByMe_VALUE);
}
/**
* @return \AgentSIB\Diadoc\Api\Proto\Documents\RevocationStatus
*/
public static function RequestsMyRevocation()
{
if (self::$RequestsMyRevocation !== null) {
return self::$RequestsMyRevocation;
}
return self::$RequestsMyRevocation = new self('RequestsMyRevocation', self::RequestsMyRevocation_VALUE);
}
/**
* @return \AgentSIB\Diadoc\Api\Proto\Documents\RevocationStatus
*/
public static function RevocationAccepted()
{
if (self::$RevocationAccepted !== null) {
return self::$RevocationAccepted;
}
return self::$RevocationAccepted = new self('RevocationAccepted', self::RevocationAccepted_VALUE);
}
/**
* @return \AgentSIB\Diadoc\Api\Proto\Documents\RevocationStatus
*/
public static function RevocationRejected()
{
if (self::$RevocationRejected !== null) {
return self::$RevocationRejected;
}
return self::$RevocationRejected = new self('RevocationRejected', self::RevocationRejected_VALUE);
}
/**
* @param int $value
* @return \AgentSIB\Diadoc\Api\Proto\Documents\RevocationStatus
*/
public static function valueOf($value)
{
switch ($value) {
case 0: return self::UnknownRevocationStatus();
case 1: return self::RevocationStatusNone();
case 2: return self::RevocationIsRequestedByMe();
case 3: return self::RequestsMyRevocation();
case 4: return self::RevocationAccepted();
case 5: return self::RevocationRejected();
default: return null;
}
}
}
|
Swift
|
UTF-8
| 467
| 2.640625
| 3
|
[] |
no_license
|
//
// DisplayableDetailContainer.swift
// AlienGo
//
// Created by Richmond Watkins on 10/5/16.
// Copyright © 2016 Nashville Native. All rights reserved.
//
import UIKit
struct DetailTextContainer: DetailTextItem {
var title: String
var content: String
init?(title: String?, content: String?) {
guard let content = content else {
return nil
}
self.title = title ?? ""
self.content = content
}
}
|
Markdown
|
UTF-8
| 410
| 3.296875
| 3
|
[
"MIT"
] |
permissive
|
### 566. 重塑矩阵
### 代码
```
func matrixReshape(nums [][]int, r int, c int) [][]int {
l1:=len(nums)
l2:=len(nums[0])
res:=make([][]int, r)
for i, _:=range res{
res[i]=make([]int, c)
}
if r*c!=l1*l2{
return nums
}
for i:=0;i<r;i++{
for j:=0;j<c;j++{
k:=i*c+j
res[i][j]=nums[k/l2][k%l2]
}
}
return res
}
```
|
Python
|
UTF-8
| 3,935
| 3.078125
| 3
|
[] |
no_license
|
# exercise 11.4.1
import numpy as np
from matplotlib.pyplot import (figure, imshow, bar, title, xticks, yticks, cm,
subplot, show)
from scipy.io import loadmat
from toolbox_02450 import gausKernelDensity
from sklearn.neighbors import NearestNeighbors
def Outlier(input_data, index_to_check):
X, y = split_train_test(input_data, index_to_check)
N, M = np.shape(X)
# Restrict the data to images of "2"
### Gausian Kernel density estimator
# cross-validate kernel width by leave-one-out-cross-validation
# (efficient implementation in gausKernelDensity function)
# evaluate for range of kernel widths
widths = X.var(axis=0).max() * (2.0 ** np.arange(-10, 3))
logP = np.zeros(np.size(widths))
for i, w in enumerate(widths):
print('Fold {:2d}, w={:f}'.format(i, w))
density, log_density = gausKernelDensity(X, w)
logP[i] = log_density.sum()
val = logP.max()
ind = logP.argmax()
width = widths[ind]
print('Optimal estimated width is: {0}'.format(width))
# evaluate density for estimated width
density, log_density = gausKernelDensity(X, width)
# Sort the densities
i = (density.argsort(axis=0)).ravel()
density = density[i].reshape(-1, )
print('The index of the lowest GKD estimator object: {0}'.format(i[0:5]))
print('The value of the lowest GKD estimator object: {0}'.format(density[0:5]))
# Plot density estimate of outlier score
figure(1)
bar(range(20), density[:20])
title('Density estimate')
# Plot possible outliers
### K-neighbors density estimator
# Neighbor to use:
K = 5
# Find the k nearest neighbors
knn = NearestNeighbors(n_neighbors=K).fit(X)
D, i = knn.kneighbors(X)
density = 1. / (D.sum(axis=1) / K)
# Sort the scores
i = density.argsort()
density = density[i]
print('The index of the lowest KNN 5 neighbours density object: {0}'.format(i[0:5]))
print('The value of the lowest KNN 5 neighbours density object: {0}'.format(density[0:5]))
# Plot k-neighbor estimate of outlier score (distances)
figure(3)
bar(range(20), density[:20])
title('KNN density: Outlier score')
# Plot possible outliers
### K-nearest neigbor average relative density
# Compute the average relative density
knn = NearestNeighbors(n_neighbors=K).fit(X)
D, i = knn.kneighbors(X)
density = 1. / (D.sum(axis=1) / K)
avg_rel_density = density / (density[i[:, 1:]].sum(axis=1) / K)
# Sort the avg.rel.densities
i_avg_rel = avg_rel_density.argsort()
avg_rel_density = avg_rel_density[i_avg_rel]
print('The index of the lowest KNN average relative density object: {0}'.format(i_avg_rel[0:5]))
print('The value of the lowest KNN average relative density object: {0}'.format(avg_rel_density[0:5]))
# Plot k-neighbor estimate of outlier score (distances)
figure(5)
bar(range(20), avg_rel_density[:20])
title('KNN average relative density: Outlier score')
# Plot possible outliers
### Distance to 5'th nearest neighbor outlier score
K = 5
# Find the k nearest neighbors
knn = NearestNeighbors(n_neighbors=K).fit(X)
D, i = knn.kneighbors(X)
# Outlier score
score = D[:, K - 1]
# Sort the scores
i = score.argsort()
score = score[i[::-1]]
print('The index of the highest KNN 5 neighbours outlier score: {0}'.format(i[0:5]))
print('The value of the highest KNN 5 neighbours outlier score: {0}'.format(score[0:5]))
# Plot k-neighbor estimate of outlier score (distances)
figure(7)
bar(range(20), score[:20])
title('5th neighbor distance: Outlier score')
# Plot possible outliers
show()
print('Ran Exercise 11.4.1')
def split_train_test(input_matrix, index):
y = input_matrix[:, index]
X = np.delete(input_matrix, index, axis=1)
print(X.shape)
return X, y
|
Python
|
UTF-8
| 3,506
| 2.65625
| 3
|
[] |
no_license
|
class User:
def __init__(self, name, pasw):
self.name = name
self.pasw = pasw
USERS.append(self)
def newContent(self):
mes = list(filter(lambda m: m.userNoticed == self and not m.revised, MESSAGES))
pub = list(filter(lambda p: p.userNoticed == self and not p.revised, PUBLICATIONS))
for c in mes + pub:
c.revised = 1
return mes,pub
def send(self, name, text, date):
for u in USERS:
if u.name == name:
Message(self, u, text, date)
return True
return False
def post(self, text, date):
Publication(self, text, date)
def like(self, name, date):
for p in PUBLICATIONS:
if p.userNoticed.name == name and p.date == date:
p.likes += 1
p.revised = 0
return 1
return 0
class Content:
def __init__(self, user, text, date):
self.userNoticed = user
self.text = text
self.date = date
self.revised = 0
class Message(Content):
def __init__(self, userFrom, userTo, text, date):
Content.__init__(self, userTo, text, date)
self.origin = userFrom
MESSAGES.append(self)
class Publication(Content):
def __init__(self, user, text, date):
Content.__init__(self, user, text, date)
self.likes = 0
self.revised = 1
PUBLICATIONS.append(self)
# LOAD
def loadData(nf):
KV_USERS = dict()
with open(nf) as f:
for l in f:
# COMENTS & EMPTY
if l[0] == '#' or len(l) < 2: continue
l = l.strip()
# SECCION
if l[0] == '*':
cur = l[1:]
continue
# LOAD USERS
if cur == "user":
u = User(*l.split(';'))
KV_USERS[u.name] = u
# LOAD MESSAGES
if cur == "mess":
usfr,usto,text,date,revs = l.split(';')
m = Message(KV_USERS[usfr], KV_USERS[usto], text, int(date))
m.revised = int(revs)
# LOAD PUBLICATIONS
if cur == "publ":
us,text,date,likes,revs = l.split(';')
p = Publication(KV_USERS[us], text, int(date))
p.revised = int(revs)
p.likes = int(likes)
return USERS,MESSAGES,PUBLICATIONS
# SAVE
def saveData(nf):
with open(nf, 'w') as f:
f.write("*user\n")
for u in USERS:
l = ';'.join((u.name,u.pasw))
f.write(l + '\n')
f.write("\n*mess\n")
for m in MESSAGES:
l = ';'.join((m.origin.name, m.userNoticed.name, m.text, str(m.date), str(m.revised)))
f.write(l + '\n')
f.write("\n*publ\n")
for p in PUBLICATIONS:
l = ';'.join((p.userNoticed.name, p.text, str(p.date), str(p.likes), str(p.revised)))
f.write(l + '\n')
def LogIn(name, pasw):
for u in USERS:
if u.name == name:
if pasw == u.pasw: return u
else: return None
return None
def SignUp(name, pasw):
for u in USERS:
if u.name == name: return None
return User(name, pasw)
def LastContent(n):
PUBLICATIONS.sort(key=lambda p: -p.date)
return PUBLICATIONS[:min(n,len(PUBLICATIONS))]
# INIT DATA
USERS = list()
MESSAGES = list()
PUBLICATIONS = list()
|
Markdown
|
UTF-8
| 1,183
| 2.59375
| 3
|
[
"CC-BY-4.0",
"MIT"
] |
permissive
|
---
uid: Microsoft.Quantum.Math.ArcTan
title: ArcTan 関数
ms.date: 1/23/2021 12:00:00 AM
ms.topic: article
qsharp.kind: function
qsharp.namespace: Microsoft.Quantum.Math
qsharp.name: ArcTan
qsharp.summary: Returns the angle whose tangent is the specified number.
ms.openlocfilehash: 6c7b22ce1278c2cb45f16330b0c2276ac15296cf
ms.sourcegitcommit: 71605ea9cc630e84e7ef29027e1f0ea06299747e
ms.translationtype: MT
ms.contentlocale: ja-JP
ms.lasthandoff: 01/26/2021
ms.locfileid: "98847371"
---
# <a name="arctan-function"></a>ArcTan 関数
名前空間: [Microsoft. Quantum. Math](xref:Microsoft.Quantum.Math)
Package: [Microsoft.](https://nuget.org/packages/Microsoft.Quantum.QSharp.Core) ....... コア
タンジェントが指定数となる角度を返します。
```qsharp
function ArcTan (d : Double) : Double
```
## <a name="input"></a>入力
### <a name="d--double"></a>d: [Double](xref:microsoft.quantum.lang-ref.double)
## <a name="output--double"></a>出力: [Double](xref:microsoft.quantum.lang-ref.double)
## <a name="remarks"></a>解説
詳細については、 [Atan](https://docs.microsoft.com/dotnet/api/system.math.atan) を参照してください。
|
PHP
|
UTF-8
| 8,381
| 2.765625
| 3
|
[] |
no_license
|
<?php
require_once(__DIR__ . "/../businessobjects/AbstractBaseDataClass.php");
require_once(__DIR__ . "/../businessobjects/PageClass.php");
/**
* @table "pagenavigation"
*/
class PageNavigationClass extends AbstractBaseDataClass {
const PAGENAVIGATIONTYPE_MOBILE = "X";
const PAGENAVIGATIONTYPE_PAGE = "P";
const PAGENAVIGATIONTYPE_MENU = "M";
const PAGENAVIGATIONTYPE_HIDDEN = "L";
/* Properties. */
private $pagenavigationid = null;
private $pageid = null;
private $childpageid = null;
private $sequence = null;
private $pagetype = null;
private $title = null;
private $divider = null;
private $target = null;
private $color = null;
/** One to one **/
private $page = null;
private $childpage = null;
/**
* Load by child page ID
* @param int $childpageid
* @return PageNavigationClass
* @throws Exception
*/
public function loadByChildPageId($childpageid) {
$sql = "SELECT *
FROM {$_SESSION['DB_PREFIX']}pagenavigation
WHERE childpageid = ?";
$stmt = SessionControllerClass::getDB()->prepare($sql);
$stmt->bindValue(1, $childpageid, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows AS $row) {
$this->loadRecordFromResultset($row);
}
}
/**
* Load by child page ID
* @param int $pageid
* @param int $childpageid
* @return PageNavigationClass
* @throws Exception
*/
public function loadByParentAndChildPageId($pageid, $childpageid) {
$sql = "SELECT *
FROM {$_SESSION['DB_PREFIX']}pagenavigation
WHERE pageid = ?
AND childpageid = ?";
$stmt = SessionControllerClass::getDB()->prepare($sql);
$stmt->bindValue(1, $pageid, PDO::PARAM_INT);
$stmt->bindValue(2, $childpageid, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows AS $row) {
$this->loadRecordFromResultset($row);
}
}
/**
* Load previous sibling
* @return PageNavigationClass
* @throws Exception
*/
public function loadPreviousSibling() {
$sibling = null;
$sql = "SELECT *
FROM {$_SESSION['DB_PREFIX']}pagenavigation A
WHERE A.pageid = ? AND
A.sequence < ?
ORDER BY A.sequence DESC
LIMIT 1";
$stmt = SessionControllerClass::getDB()->prepare($sql);
$stmt->bindValue(1, $this->pageid, PDO::PARAM_INT);
$stmt->bindValue(2, $this->sequence, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows AS $row) {
$sibling = new PageNavigationClass();
$sibling->loadRecordFromResultset($row);
}
return $sibling;
}
/**
* Load next sibling
* @return PageNavigationClass
* @throws Exception
*/
public function loadNextSibling() {
$sibling = null;
$sql = "SELECT *
FROM {$_SESSION['DB_PREFIX']}pagenavigation A
WHERE A.pageid = ? AND
A.sequence > ?
ORDER BY A.sequence
LIMIT 1";
$stmt = SessionControllerClass::getDB()->prepare($sql);
$stmt->bindValue(1, $this->pageid, PDO::PARAM_INT);
$stmt->bindValue(2, $this->sequence, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows AS $row) {
$sibling = new PageNavigationClass();
$sibling->loadRecordFromResultset($row);
}
return $sibling;
}
/**
* {@inheritDoc}
* @see AbstractBaseDataClass::updateRecord()
*/
public function updateRecord() {
parent::updateRecord();
$cache = new Cache(array(
'name' => 'page-cache',
'path' => __DIR__ . "/../tmp/",
'extension' => '.cache'
));
$cache->eraseAll();
}
/**
* {@inheritDoc}
* @see AbstractBaseDataClass::insertRecord()
*/
public function insertRecord() {
parent::insertRecord();
$cache = new Cache(array(
'name' => 'page-cache',
'path' => __DIR__ . "/../tmp/",
'extension' => '.cache'
));
$cache->eraseAll();
}
/**
* Move up.
*/
public function moveUp() {
$sibling = $this->loadPreviousSibling();
if ($sibling != null) {
$siblingSequence = $sibling->getSequence();
$sibling->setSequence($this->getSequence());
$sibling->updateRecord();
$this->setSequence($siblingSequence);
$this->updateRecord();
}
}
/**
* Move down.
*/
public function moveDown() {
$sibling = $this->loadNextSibling();
if ($sibling != null) {
$siblingSequence = $sibling->getSequence();
$sibling->setSequence($this->getSequence());
$sibling->updateRecord();
$this->setSequence($siblingSequence);
$this->updateRecord();
}
}
/**
* pagenavigationid
* @param int $pagenavigationid
* @return int
*/
public function setPagenavigationid($pagenavigationid){
$this->pagenavigationid = $pagenavigationid;
return $this;
}
/**
* @primarykey true
* @column "pagenavigationid"
* @property
* pagenavigationid
* @return int
*/
public function getPagenavigationid(){
return $this->pagenavigationid;
}
/**
* pageid
* @param int $pageid
* @return int
*/
public function setPageid($pageid){
$this->pageid = $pageid;
return $this;
}
/**
* @column "pageid"
* @property
* pageid
* @return int
*/
public function getPageid(){
return $this->pageid;
}
/**
* childpageid
* @param int $childpageid
* @return int
*/
public function setChildpageid($childpageid){
$this->childpageid = $childpageid;
return $this;
}
/**
* @column "childpageid"
* @property
* childpageid
* @return int
*/
public function getChildpageid(){
return $this->childpageid;
}
/**
* sequence
* @param int $sequence
* @return int
*/
public function setSequence($sequence){
$this->sequence = $sequence;
return $this;
}
/**
* @column "sequence"
* @property
* sequence
* @return int
*/
public function getSequence(){
return $this->sequence;
}
/**
* pagetype
* @param string $pagetype
* @return string
*/
public function setPagetype($pagetype){
$this->pagetype = $pagetype;
return $this;
}
/**
* @column "pagetype"
* @property
* pagetype
* @return string
*/
public function getPagetype(){
return $this->pagetype;
}
/**
* title
* @param string $title
* @return string
*/
public function setTitle($title){
$this->title = $title;
return $this;
}
/**
* @column "title"
* @property
* title
* @return string
*/
public function getTitle(){
return $this->title;
}
/**
* divider
* @param int $divider
* @return int
*/
public function setDivider($divider){
$this->divider = $divider;
return $this;
}
/**
* @column "divider"
* @property
* divider
* @return int
*/
public function getDivider(){
return $this->divider;
}
/**
* target
* @param string $target
* @return string
*/
public function setTarget($target){
$this->target = $target;
return $this;
}
/**
* @column "target"
* @property
* target
* @return string
*/
public function getTarget(){
return $this->target;
}
/**
* color
* @param string $color
* @return string
*/
public function setColor($color){
$this->color = $color;
return $this;
}
/**
* @column "color"
* @property
* color
* @return string
*/
public function getColor(){
return $this->color;
}
/**
* @onetoone
* page
* @return PageClass
*/
public function getPage($load = true){
if ($this->page == null && $load) {
$this->page = new PageClass();
if ($this->getPageid() != null) {
$this->page->loadRecord($this->getPageid());
}
}
return $this->page;
}
/**
* @onetoone
* Child page
* @return PageClass
*/
public function getChildPage($load = true){
if ($this->childpage == null && $load) {
$this->childpage = new PageClass();
if ($this->getChildpageid() != null) {
$this->childpage->loadRecord($this->getChildpageid());
}
}
return $this->childpage;
}
}
?>
|
Swift
|
UTF-8
| 1,719
| 3.328125
| 3
|
[] |
no_license
|
//
// Date+Ext.swift
// ShortsReportBeta
//
// Created by Aidan Pendlebury on 24/06/2020.
//
import Foundation
extension Date {
func minutesBetweenDates() -> Double {
//get both times sinces refrenced date and divide by 60 to get minutes
let newDateMinutes = Date().timeIntervalSinceReferenceDate/60
let oldDateMinutes = self.timeIntervalSinceReferenceDate/60
//then return the difference
return newDateMinutes - oldDateMinutes
}
func shortTimeString() -> String {
let formatter = DateFormatter()
formatter.timeStyle = .short
return formatter.string(from: self)
}
func shortDateAndTimeString() -> String {
let formatter = DateFormatter()
formatter.dateStyle = .short
formatter.timeStyle = .short
return formatter.string(from: self)
}
func dayOfWeekString() -> String {
let number = Calendar.current.dateComponents([.weekday], from: self).weekday
switch number {
case 1:
return "Sun"
case 2:
return "Mon"
case 3:
return "Tue"
case 4:
return "Wed"
case 5:
return "Thu"
case 6:
return "Fri"
default:
return "Sat"
}
}
func hourOfDay() -> Int { Calendar.current.component(.hour, from: self) }
func timeOfDay() -> TimeOfDay {
let hour = self.hourOfDay()
if hour <= 12 {
return .morning
} else if hour > 12 && hour <= 18 {
return .afternoon
}
return .night
}
}
|
Java
|
UTF-8
| 1,538
| 2.09375
| 2
|
[] |
no_license
|
package com.cw.stu.internet.tech.stu.audit.webservice.test.client;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="client_code" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"clientCode"
})
@XmlRootElement(name = "Getstdcode")
public class Getstdcode {
@XmlElement(name = "client_code")
protected String clientCode;
/**
* Gets the value of the clientCode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getClientCode() {
return clientCode;
}
/**
* Sets the value of the clientCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setClientCode(String value) {
this.clientCode = value;
}
}
|
PHP
|
UTF-8
| 7,771
| 2.625
| 3
|
[] |
no_license
|
<?php
class Functions
{
public function logoHeader() {
$result = mysql_query("SELECT * FROM settings");
$row = mysql_fetch_object($result);
if ($row->logoexist === 'true') {
echo '<img id="logoimg" src="' . $row->logo . '" alt="' . $row->servername . ' - ' . $row->slogan . '">';
echo '<hr class="noscreen" />';
}
else {
echo '<h1 id="logo">';
echo $row->servername;
echo '</h1>';
echo '<h2 id="slogan">';
echo $row->slogan;
echo '</h2>';
}
}
public function newsHeader() {
$result = mysql_query("SELECT * FROM settings");
$row = mysql_fetch_object($result);
if ($row->newsexist === 'true') {
echo '<h2 id="content-title">' . $row->servername . ' > ' . $currentpage . '</h2>';
echo '<div id="perex" class="box">';
echo '<img src="./design/minecraft_icon.png" width="100px" height="95px" alt="news thumbnail" class="f-left" /><h2 id="news-top-title">' . $row->newstitle . '</h2><p id="news-top-body">' . $row->newsbody . '</p>';
echo '</div>';
echo '<hr class="noscreen" />';
}
else {
echo '<h2 id="content-title">' . $row->servername . $currentpage . '</h2>';
echo '<hr class="noscreen" />';
}
}
public function news() {
$sql="SELECT * FROM news ORDER BY id DESC";
$result=mysql_query($sql);
$nb = 10;
$n = 0;
while(($data = mysql_fetch_assoc($result)) and $n < $nb){
echo '<h2 id="news-title">' . $data["title"] . '</h2>';
echo '<div id="date">' . date("F j, Y \a\t g:i A",strtotime($data["date"])) . '</div>';
echo $data["content"];
echo '<p>Posted by ' . $data["poster"] . '</p><br />';
$n = $n + 1;
}
}
public function loginWidget() {
if ((isset($_SESSION['username'])) && (!empty($_SESSION['username'])))
{
//Already logged in
$susername = $_SESSION['username'];
$sql = "SELECT * FROM users WHERE user_name='$susername'";
$result = mysql_query($sql);
$data = mysql_fetch_assoc($result);
echo '<h4 id="aside-title">Hello, ' . $data["user_name"] . '</h4>';
echo '<div class="aside-in">';
echo '<div class="aside-box">';
echo '<p>';
echo '<div align="center"><img id="avatar" width="100px" height="100px" src="' . $data["user_avatar"] . '" /></div><br />';
echo '<a href="settings.php">Change Settings</a><br />';
echo '<a href="index.php?action=logout">Log out</a></p>';
echo '</div> <!-- /aside-box -->';
echo '</div> <!-- /aside-in -->';
}
else
{
//Login or register
echo '<h4 id="aside-title">Login/Register</h4>';
echo '<div class="aside-in">';
echo '<div class="aside-box">';
echo '<form action="login.php" method="post">';
echo '<div>';
echo '<label for="username" id="cufon">Username: </label><br />';
echo '<input type="text" name="login" /><br />';
echo '<label for="password"" id="cufon2">Password: </label><br />';
echo '<input type="password" name="password" /><br />';
echo '<input type="submit" VALUE="Login">';
echo '</div>';
echo '</form>';
echo '<br />';
echo '<p>Not registered? <a href="register.php">Register here!</a></p>';
echo '</div> <!-- /aside-box -->';
echo '</div> <!-- /aside-in -->';
}
}
public function statusWidget() {
$result = mysql_query("SELECT * FROM settings");
$row = mysql_fetch_object($result);
$config['server']['ip'] = $row->serverip;
$config['server']['port'] = $row->serverport;
include './inc/mc.inc.php';
$info = fetch_server_info($config['server']['ip'], "25566");
if ($info === false){
echo '<p id="serverstatus">' . $row->servername . '<br /><br />';
echo 'Status: <font color="red">Offline</font>';
echo '</p>';
}else{
echo '<p id="serverstatus">' . $row->servername . '<br />';
echo '<br />';
echo 'Status: <font color="green">Online</font><br />';
echo "Slots: " . $info['playerCount'] . "/" . $info['maxPlayers'] . "<br />";
echo 'Server IP: ' . $row->serverip . ':' . $row->serverport . '<br />';
echo 'Player List:';
echo '<div id="mypanel" class="ddpanel">';
echo '<div id="mypanelcontent" class="ddpanelcontent">';
echo '<p style="padding:10px" id="playerlist">';
echo implode('<br />', $info['playerList']);
echo '</p>';
echo '</div>';
echo '<div id="mypaneltab" class="ddpaneltab">';
echo '<a href="#"><span id="toggle">Toggle</span></a>';
echo '</div>';
echo '</div>';
echo '</p>';
}
}
public function forumIndex() {
$sql = "SELECT categories.cat_id, categories.cat_name, categories.cat_description, COUNT(topics.topic_id) AS topics FROM categories LEFT JOIN topics ON topics.topic_id = categories.cat_id GROUP BY categories.cat_name, categories.cat_description, categories.cat_id ORDER BY cat_id ASC";
$result = mysql_query($sql);
if(!$result)
{
echo 'The categories could not be displayed, please try again later.';
}
else
{
if(mysql_num_rows($result) == 0)
{
echo 'No categories defined yet.';
}
else
{
//prepare the table
echo '<table border="1px">
<tr>
<th> Category</th>
<th> Last topic</th>
</tr>';
while($row = mysql_fetch_assoc($result))
{
echo '<tr>';
echo '<td class="leftpart">';
echo '<h3 id="nocufon"><a href="category.php?id=' . $row['cat_id'] . '">' . $row['cat_name'] . '</a></h3>' . $row['cat_description'];
echo '</td>';
echo '<td class="rightpart">';
//fetch last topic for each cat
$topicsql = "SELECT topic_id, topic_subject, topic_date, topic_cat FROM topics WHERE topic_cat = " . $row['cat_id'] . " ORDER BY topic_date DESC LIMIT 1";
$topicsresult = mysql_query($topicsql);
if(!$topicsresult)
{
echo 'Last topic could not be displayed.';
}
else
{
if(mysql_num_rows($topicsresult) == 0)
{
echo 'no topics';
}
else
{
while($topicrow = mysql_fetch_assoc($topicsresult))
echo '<a href="topic.php?id=' . $topicrow['topic_id'] . '">' . $topicrow['topic_subject'] . '</a> at ' . date('d-m-Y', strtotime($topicrow['topic_date']));
}
}
echo '</td>';
echo '</tr>';
}
}
}
}
public function forumCategory() {
//first select the category based on $_GET['cat_id']
$sql = "SELECT cat_id, cat_name, cat_description FROM categories WHERE cat_id = " . mysql_real_escape_string($_GET['id']);
$result = mysql_query($sql);
if(!$result)
{
echo 'The category could not be displayed, please try again later.' . mysql_error();
}
else
{
if(mysql_num_rows($result) == 0)
{
echo 'This category does not exist.';
}
else
{
//display category data
while($row = mysql_fetch_assoc($result))
{
echo '<h2>Topics in ′' . $row['cat_name'] . '′ category</h2><br />';
}
//do a query for the topics
$sql = "SELECT topic_id, topic_subject, topic_date, topic_cat FROM topics WHERE topic_cat = " . mysql_real_escape_string($_GET['id']);
$result = mysql_query($sql);
if(!$result)
{
echo 'The topics could not be displayed, please try again later.';
}
else
{
if(mysql_num_rows($result) == 0)
{
echo 'There are no topics in this category yet.';
}
else
{
//prepare the table
echo '<table border="1">
<tr>
<th>Topic</th>
<th>Created at</th>
</tr>';
while($row = mysql_fetch_assoc($result))
{
echo '<tr>';
echo '<td class="leftpart">';
echo '<h3><a href="topic.php?id=' . $row['topic_id'] . '">' . $row['topic_subject'] . '</a><br /><h3>';
echo '</td>';
echo '<td class="rightpart">';
echo date('d-m-Y', strtotime($row['topic_date']));
echo '</td>';
echo '</tr>';
}
}
}
}
}
}
}
|
Java
|
UTF-8
| 527
| 2.0625
| 2
|
[] |
no_license
|
package com.example.tung.gituser.ui.main;
import com.example.tung.gituser.BasePresenter;
import com.example.tung.gituser.BaseView;
import com.example.tung.gituser.data.model.User;
import java.util.List;
public interface MainContract {
interface Presenter extends BasePresenter {
void getUsers();
void searchUsers(String s);
}
interface View extends BaseView<Presenter> {
void displayUsers(List<User> users);
void showEmptyUsers();
void showError(Exception e);
}
}
|
Markdown
|
UTF-8
| 9,430
| 2.78125
| 3
|
[] |
no_license
|
# Projeto XY
Projeto sobre novo sistema em nuvem para a XY Brasil
## Objetivo
O Objetivo deste documento é facilitar a tomada de decisão sobre a implantação de um sistema em núvem para o novo sistema de gestão integrada para a empresa XY Brasil.
## On-Premisses VS SaaS
O uso de sistemas on-premisses é a forma mais tradicional de trabalhar com sistemas de gestão, já que o software acaba estando integrando ao patrimônio da empresa, quando um bug ou problema aparece muitas vezes a equipe sabe em qual linha de código está o erro, por ser tudo criando "em casa".
Com o crescimento das compras on-line o mercado logistico tem um papel fundamental e indispensável na entrega dos produtos físicos. Mas conforme o mercado avança, os outros players tem setado a barra cada vez mais alto, a própria complexidade das operações tem aumentado, conforme a cada dia que passa uma nova solução disruptiva é adicionada, criando um cenário onde quem não escala é deixado para trás.
Escalar a solução usando sistemas on-premisses é possível, mas o tamanho e nível de especialização da equipe seria tão alto que poderia tirar o foco da empresa, que é a gestão das operações logisticas e não cuidar de data-centers e criar algoritmos computacionais.
Com soluções SaaS é possível ampliar o produtividade da equipe de TI da empresa efetuar novas contratações, e sem precisar aumentar os custos com Hardware e Licenças, na verdade existem uma grande chance dos custos baixarem ou pelo menos se estabilizarem sem impactar o crescimento da empresa.
Quando se trata de segurança o SaaS apresenta uma vantagem muita grande, uma delas é que mesmo em caso de ataque a equipe de segurança do fornecedor, consegue isolar o problema em um determinado cluster e manter outro datacenter funcionando como se nada tivesse acontecido. Outra grande vantagem é que em casos extremos as empresas SaaS se responsabilizam por possíveis danos e perdas, já __quando acontece algum incidente com um sistema _in-house_ empresa acaba levando todo prejuizo financeiro e jurídico sozinha__.
## Tatica de implantação
Como a empresa já tem vários sistemas rodando on-premisses a primeira opção seria buscar uma solução que já englobasse todos os sistemas em um só, a segunda opção seria um sistema que faz a maior parte das operações sendo necessário adicionar algumas customizações menores e a terceira opção seria a integração de vários sistemas SaaS, por exemplo, o setor de vendas vai usar o ECM Fluig juntamente com o SugarCRM(SaaS) enquanto a equipe de Marketing vai usar uma solução SalesForce para as campanhas B2B e SharpSping para as campanhas B2C, nada impede que a equipe de TI trabalhe com maior foco no tratamento de dados relevantes e alimente em fluxo contínuo [chartio.com](//chartio.com) para que os gestores da empresa possam ver os dados mais relevantes em um só lugar.
__Assim temos:__
* Tatica #1: SaaS Monolítico
* Tatica #2: SaaS com extensões
* Tatica #3: Vários sistemas SaaS inteligados
## Processo de implantação
### Análise de cenário
É muito difícil que a empresa esteja 100% com sistemas On-promisses, possivelemte boa parte da documentação dessa empresa já esteja no Google Docs, por exemplo. Outros pontos a se analisar são:
* ROI: É preciso analisar qual fornecedor vai entregar as features que a empresa usa no SLA que a empresa precisa, levando em consideração as vantagens de segurança que o SaaS de uma empresa conceituada traz.
* Cultura da empresa: nenhuma empresa fica grande sem desenvolver uma cultura, é necessário analisar e calcular quanto tempo levaria para os times absorverem novas ferramentas sem gerar buzz negativo, tourn-over desnecessário e medo de ser substituido pelos novos sistemas.
* Estimativa de tempo de implantação: Considerando motivos humanos (treinamento, cultura) e processuais (Levantamento de dados, migração do TI, jurídico).
### Migração Setorizada
Ainda que a empresa tenha encontrado um SaaS monolitico que vai cobrir todas as suas necessidades ou irá usar vários serviços integrados, a forma mais eficiente e menos dolorosa é realizar a migração seria setor-por-setor, cada um dos sistemas on-promisses para SaaS, migrando primeiro os sistemas periféricos e finalizando com a migração dos sistemas core, assim diminuido possíveis impáctos negativos ao funcionamento da empresa.
#### Migração de sistemas-periféricos
Sistemas perifericos são sistemas que não vão impactar diretamente na função principal da empresa durante a sua migração.
Vamos supor que a empresa use um _sisteminha_ que o pessoal do TI desenvolveu há muito tempo usando ASP e VB para cuidar do processo de recrutamento e seleção, isso pode ser subistituido pelo [MS Dynamics 365](https://dynamics.microsoft.com)
#### Migração de sistemas-core
Sistemas _core_ são sistemas que impactam diretamente no dia-a-dia da empresa.
Se o sistema que recebe as solicitações de transporte falha a empresa para, então esses sistemas seriam migrados por último.
### Treinamentos
Os treinamentos são parte fundamental da implantação do sistema, deve ficar claro que o sistema irá facilitar o trabalho do funcinário e não subistituilo. O desejo da empresa é crescer com a equipe e que os novos sistemas e metodologias poderão viabilizar formas mais confortáveis de se trabalhar, incluindo horários flexíveis, trabalho remoto.
Os gestores poderão melhorar a performance de seus setores assim melhorando os seus resultados e relatórios sem perder a hora da janta.
Se as pessoas virem o projeto como uma forma de fazer cortes na folha de pagamentos, a resistência pode retardar ou até inviabilizar toda a implantação do sistema o que aumenta o custo de implantação.
Treinamentos em empresas grandes são custosos porque param os funcionários de suas atividades por horas e as vezes por dias.
Todo setor tem aquele usuário que é mais familiarizado com a tecnologia e que entende as atividades do dia-a-dia do setor, mas conversa bem com a equipe de TI, esses seriam os usuários _focal-point_.
Ao invés de treinar a empresa inteira é melhor designar usuários _focal-point_ em cada setor, porque eles aprendem mais rápido e já estão habituados a auxiliar os seus colegas.
#### Treinamento da equipe de TI
A equipe de TI deve ser treinada para usar os novos sistemas e poder treinar e dar suporte para os _focal-points_ de cada setor. Dessa forma não consumindo as horas do cunsultor técnico da fornecedora, uma vez que sua hora/cunsultoria costuma ter valor elevado.
#### Treinamento dos usuários focal-point
Uma vez treinada, a equipe de TI deve treinar os usuários _focal-point_.
Ao invés de gastar 3 dias no autitório ou sala de reunião da empresa, com coffee-break, pausa para dúvidas. Pode-se investir 4 horas fazendo uma boa apresentação para o _focal-point_ do setor, é uma economia imensa para a empresa.
### Monitoria e Analytics
Uma vez implantado o sistema uma das tarefas da equipe de TI é monitorar e gerar relatórios sobre a performance do sistema.
## Atividades e rotinas
* __Weekly Meeting__: Uma reunião rápida de até 30 minutos no inicio da semana para revisão das tarefas do semana anterior e objetivação de metas da semana.
* __Daily Meetings__: Uma reunião rápida de até 30 minutos no início do dia para revisão das tarefas do dia anterior e objetivação de metas do dia, verificando sempre se não há um desvio desnecessário das metas objetivadas na _Weelky Meeting_
* __Rotina__:
* Verificação e levantamento de warnings do sistema;
* Check dos chamados dos usuários _Focal Point_;
* Follow-up das respostas do suporte do fornecedor;
* Investigação de novas práticas, melhorias e fornecedores;
* fechamento de turno usando o documento padrão para report do dia.
## Métricas
### Cumprimento de SLA
* Verificar quanto tempo o fornecedor leva para adicionar as features, solucionar bugs e responder dúvidas
* Verificar o nível de entrega de seviço
### Resoluções em primeira chamada
* Manter um controle interno de quantas chamadas são resolvidas na primeira chamada de acordo com o SLA acertado.
### Tempo médio para atender
* Estar atento se em média o fornecedor atende em tempos condizentes com o SLA de cada chamado.
### Uptime
* Uptime de suporte: Tempo que o suporte leva para respondes às urgências.
* Uptime de infra: Tempo que o sistema funciona sem dar problemas.
### Tempo médio fora do ar
* Quando ocorre algum problema no sistema, em quanto tempo ele volta a operar integralmente.
### Tempo de resposta
* Tempo de resposta dos endpoints(REST/SOAP) e dos Scripts, observando o cumprimento de SLA.
### Tempo médio de atendimento
* Tempo que o suporte leva para chegar a solução em cada etapa do atendimento.
### Porcentagem de entregas com atraso
* Qual é a proporção dos atrasos do fornecedor e da equipe interna com as operações que rodam em SaaS.
### Comparação de dados
* Comparar todos os resultados da métricas SaaS com os resultados das métricas dos sistemas On-Premisses para fazer uma análise constante da viabilidade e ROI
## Conclusão
A menos que a empresa tenha a necessidade de poder colocar fogo no datacenter a qualquer momento para apagar os dados e torrar um bom dinheiro, SaaS é certamente a opção mais viável para empresas que querem crescer.
|
PHP
|
UTF-8
| 350
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
<?php namespace Quince\Pelastic\Contracts\Config;
interface PelasticConfigInterface {
/**
* Bootstrap from array
*
* @param array $params
* @return $this
*/
public function setClientConfig(array $params);
/**
* Get client config
*
* @return array
*/
public function getClientConfig();
}
|
Ruby
|
UTF-8
| 1,001
| 3.921875
| 4
|
[] |
no_license
|
class Product
attr_reader :red
def initialize(name,blue,red,green)
@name = name #ocup variables de instancia para que sean en sadas en otro momento.
@blue = blue.to_i
@red = red.to_i
@green = green.to_i
end
def total
@blue+@red+@green
end
end
products = []
file = File.open('products.txt', 'r') #que abro y para qué r de reader.
data = file.readlines #leer por lineas
file.close #cierro archivo ya leido
data.each do |line|
name,blue,red,green = line.split(', ') #por cada linea separo por criterio, en este caso la "," y lo guardo en el array vacío "products"
products << Product.new(name,blue,red,green)
end
data.each do |product|
puts product.red #puedo acceder al stock de red siempre que tenga un attr reader ya que sino queda como indefinido para esta instancia
end
puts products.inject(0){|sum, product|sum + product.red}
puts products.inject(0){|sum, product|sum + product.total}
# ruby arreglo_productos.rb
|
Python
|
UTF-8
| 1,261
| 3.65625
| 4
|
[] |
no_license
|
from linked_list import _Node, LinkedList
from typing import List, Any, Optional
class Queue:
"""
This is a queue implemented using linked list
"""
def __init__(self):
self.item = LinkedList([])
def is_empty(self) -> bool:
"""
Return whether this queue contains no items
"""
return self.item.is_empty()
def enqueue(self, item: Any):
"""Add <item> to the back of this queue.
"""
tmp = None
if not self.is_empty():
tmp = self.item._first
self.item._first = _Node(item)
if tmp is not None:
self.item._first.next = tmp
def dequeue(self) -> Optional[Any]:
"""Remove and return the item at the front of this queue.
Return None if this Queue is empty.
(We illustrate a different mechanism for handling an erroneous case.)
>>> q = Queue()
>>> q.enqueue('hello')
>>> q.enqueue('goodbye')
>>> q.dequeue()
'hello'
"""
curr = self.item._first
while curr.next is not None:
curr = curr.next
tmp = curr.item
curr.item = None
return tmp
if __name__ == '__main__':
import doctest
doctest.testmod()
|
Python
|
UTF-8
| 1,308
| 2.671875
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 13 10:46:03 2018
@author: Manjit
This function contains the density calibration shots for each day
"""
def calshot(day):
if day == '101718':
return '101718r2'
if day =='101618':
return '101618r3'
if day == '100218':
return '100218r5'
if day == '081518':
return '081518r2'
if day == '083018':
return '083018r4'
if day == '082118':
return '082118r5'
if day == '081418':
return '081418r4'
if day == '081717':
return '081717r2'
if day == '101917':
return '101917r5'
if day == '070918':
return '070918r5'
if day == '071218':
return '071218r1'
if day == '101917':
return '101917r5'
if day == '030118':
return '030118r1'
if day == '101317':
return '101317r5'
if day == '101117':
return '101117r4'
if day == '091818':
return '091818r4'
if day == '061219':
return '061219r19'
if day == '062619':
return '062619r3'
if day == '071019':
return '071019r2'
if day == '071819':
return '071819r2'
if day == '072419':
return '072419r3'
if day == '073019':
return '073019r5'
else:
print('Day/shot not found')
|
Java
|
UTF-8
| 307
| 1.851563
| 2
|
[] |
no_license
|
package springMongo.MovieStore.service;
import java.util.List;
import springMongo.MovieStore.bean.Result;
import springMongo.MovieStore.bean.Users;
public interface UserService {
public Users save(Users users);
public Users getUser(String name);
public List<Result> getAvgrating(Integer id);
}
|
Swift
|
UTF-8
| 1,103
| 3.265625
| 3
|
[] |
no_license
|
import Foundation
func solution(_ expression:String) -> Int64 {
let priors: [[Character]] = [["+", "-", "*"], ["+", "*", "-"],
["-", "+", "*"], ["-", "*", "+"],
["*", "-", "+"], ["*", "+", "-"]]
let operands = expression.components(separatedBy: ["+", "-", "*"]).map { Int($0)! }
let operators = Array(expression.filter { !$0.isNumber })
var result = 0
func calc(_ a: Int, _ b: Int, _ op: Character) -> Int {
switch op {
case "+": return a + b
case "-": return a - b
case "*": return a * b
default: return 0
}
}
for prior in priors {
var (opds, opts) = (operands, operators)
for op in prior {
while let index = opts.firstIndex(of: op) {
opds[index] = calc(opds[index], opds[index+1], opts[index])
opds.remove(at: index+1)
opts.remove(at: index)
}
}
result = max(result, abs(opds[0]))
}
return Int64(result)
}
|
C++
|
UTF-8
| 908
| 3.9375
| 4
|
[] |
no_license
|
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
/*
Write a program that prompts the user to enter the number of students, the students’ names,
and their scores, and prints student names in decreasing order of their scores.
*/
struct Student {
string name;
int score;
};
bool sortByScoreDesc(const Student &lhs, const Student &rhs) {return lhs.score > rhs.score;}
int main() {
int size = 0;
cout << "Enter number of students: ";
cin >> size;
vector<Student> list(size);
for(int i = 0; i < size; i++) {
cout << "Enter student name: " << endl;
cin >> list[i].name;
cout << "Enter student score: " << endl;
cin >> list[i].score;
}
//using std:sort because it's easiest
sort(list.begin(), list.end(), sortByScoreDesc);
for(int k = 0; k < size; k++) {
cout << list[k].name << " - " << list[k].score << endl;
}
}
|
Markdown
|
UTF-8
| 10,040
| 2.59375
| 3
|
[
"Apache-2.0"
] |
permissive
|
# :blush:JPTabBar:blush:
[](https://bintray.com/peng83508440/maven/JPTabBar)
<br>[](http://android-arsenal.com/details/1/4685)
###
# 效果图
<br>
# 主要功能以及特色:
- [x] 多种Tab切换的动画效果
- [x] 实现底部导航中间按钮凸出的效果
- [x] 实现WeChat那种滑动导航的底部渐变效果,随着滑动的距离变化而变化
- [x] 实现TabBar上的红色标记,并且可以拖动
- [x] 强大的BadgeView功能,智能判断数字隐藏与越界显示,两种显示模式。
- [x] 提供监听Tab的点击事件,中间点击以及badge被拖拉消失的接口
- [x] 引用注解方式,免去自己手动构造TabBarItem
# 用法:
1.引入Gradle依赖
```Java
repositories {
jcenter()
}
dependencies{
compile 'com.jpeng:JPTabBar:1.1.4'
}
```
2.添加JPTabBar到你的主界面布局
```JAVA
<com.jpeng.jptabbar.JPTabBar
android:id="@+id/tabbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff"
jp:TabHeight="56dp"
jp:BadgeDraggable="true"
jp:TabAnimate="Jump"
jp:BadgePadding="4dp"
jp:BadgeMargin="5dp"
jp:BadgeTextSize="10dp"
/>
```
3.在你的主界面使用注解声明数组变量,内部通过反射来生成TabItem,注意的是:NorIcons和Titles是必须的,每个数组长度要保持一致
```JAVA
@Titles
private static final String[] mTitles = {"页面一","页面二","页面三","页面四"};
@SeleIcons
private static final int[] mSeleIcons = {R.mipmap.tab1_selected,R.mipmap.tab2_selected,R.mipmap.tab3_selected,R.mipmap.tab4_selected};
@NorIcons
private static final int[] mNormalIcons = {R.mipmap.tab1_normal, R.mipmap.tab2_normal, R.mipmap.tab3_normal, R.mipmap.tab4_normal};
```
或者,你可以在oncreate方法里面初始化导航的item
```JAVA
mTabbar = (JPTabBar) findViewById(tabbar);
mTabbar.setTitles(R.string.tab1, R.string.tab2, R.string.tab3, R.string.tab4)
.setNormalIcons(R.mipmap.tab1_normal, R.mipmap.tab2_normal, R.mipmap.tab3_normal, R.mipmap.tab4_normal)
.setSelectedIcons(R.mipmap.tab1_selected, R.mipmap.tab2_selected, R.mipmap.tab3_selected, R.mipmap.tab4_selected)
.generate();
```
4.经过上面,TabBar的布局基本上已经搭建好了。如果要实现Wechat那种渐变还有自动让ViewPager改变页面的功能的话,只需要在Activity oncreate方法里面,添加一行代码:
```JAVA
//传入一定要集成继承ViewPager
mTabbar.setContainer(mPager);
```
5.本项目中已经提供了部分动画,如果你要使用自己定义的动画,可以setCustomAnimate,传入内部提供的Animatable接口,参考下面的例子
```
mTabbar.setCustomAnimate(new Animatable() {
/**
* 这个方法当你点击Tab切换页面的时候会调用
* @param target TabBar里面的IconView
* @param Duration 是你自定义的动画时间
*/
@Override
public void playAnimate(View target, int Duration) {
ViewHelper.setPivotX(target,target.getLayoutParams().width/2);
ViewHelper.setPivotY(target,target.getLayoutParams().height/2);
AnimatorSet set = new AnimatorSet();
set.playTogether(
ObjectAnimator.ofFloat(target,"scaleX",0.2f,1f).setDuration(Duration),
ObjectAnimator.ofFloat(target,"scaleY",0.2f,1f).setDuration(Duration),
ObjectAnimator.ofFloat(target,"alpha",0.3f,1f).setDuration(Duration)
);
set.start();
}
/**
* 这个方法的解析
* 当你切换用手势滑动ViewPager,这个方法就会回调
* 这个方法生效的条件是下面要return true
* @param target 同上
* @param offset 这个参数代表偏差,范围 0-1
*/
@Override
public void onPageAnimate(View target, float offset) {
ViewHelper.setScaleX(target,1+offset*0.2f);
ViewHelper.setScaleY(target,1+offset*0.2f);
}
/**
* 代表是否需要滑动中,调用Icon动画
* @return
*/
@Override
public boolean isNeedPageAnimate() {
return true;
}
});
```
# 方法和节点说明:
#### JPTabBar主要方法:
```JAVA
/**
* 设置自定义Tab切换动画
*/
public void setCustomAnimate(Animatable customAnimate);
/**
* 显示BadgeView ,传入字符串
* 当然还有一个重载方法,第二个参数为int,设置消息数量
* 传入""字符串显示圆点
*/
public void ShowBadge(int position,String text);
/**
* 隐藏BadgeView
*/
public void HideBadge(int position);
/**
* 切换Tab页面,是否带动画
*/
public void setSelectTab(int index, boolean animated);
/**
* 设置点击TabBar事件的观察者
*/
public void setTabListener(OnTabSelectListener listener);
/**
* 设置badgeView消失的回调事件
*/
public void setDismissListener(BadgeDismissListener listener);
```
### 结点说明:
| 结点名字 | 结点说明 | 参数类型 | 默认值 |
|-------------|:-------------|:----------:|:-----:|
| TabHeight |TabBar的高度,将会覆盖layout_height的设置 |dimension| 56dp |
| TabNormalColor |字体和图标的未选中颜色 |color | 0xffAEAEAE(灰色) |
| TabSelectColor |字体和图标的选中的颜色 |color | 0xff59D9B9(青色) |
| TabTextSize |Tab底部文件大小 |dimension | 14sp |
| TabIconSize |Tab图标的大小 |dimension| 24dp |
| TabIconFilter | 设置图标是否随着字体颜色而改变|boolean | true |
| TabMargin |设置图标距离上面和文字距离下面的距离 |dimension | 8dp |
| TabSelectBg |设置TabBarItem选中的背景颜色 |color | 透明 |
| TabAnimate |Tab切换的动画类型 |enum | Scale |
| TabMiddleIcon |Tab中间的图标 |drawable | 无 |
| BadgeColor |徽章的背景颜色 |color | #f00(红色) |
| BadgeDraggable |徽章是否可以拖动 |boolean | false |
| BadgePadding |徽章的背景扩展距离 |dimension | 4dp |
| BadgeTextSize |徽章显示的字体大小 |dimension | 11dp |
| BadgeMargin | 徽章距离右边边缘的间隔 |dimension | 9dp |
# 注意事项
1.假如你已经给TabBar setContainer,不要setOnPageChangeListener给ViewPager
```JAVA
/**
*如果你前面已经给TabBar设置了容器,然后调用这个方法的话,类似WeChat那种拖动渐变效果以及自动切换页面将会失效
*假如你要监听页面改变事件,可以使用TabListener
*/
mPager.setOnPageChangeListener(this);
```
2.假如你要实现中间凸出的按钮,必须要在主界面最外围的父结点设置 android:clipChildren="false",否则会遮盖
```JAVA
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:jp="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipChildren="false"
android:gravity="bottom"
android:orientation="vertical"
>
```
3.如果你想让ViewPager禁止滑动,你可以使用我demo中的NoScrollViewPager
# 更新日志
### V1.0.4
- 修复BadgeView显示位置随着字体位置偏差问题
- 修复背景被TabItem背景覆盖问题
- 修改高度默认56dp,徽章Margin为9dp
### V1.0.5
- 解决徽章BadgeMargin不能往左上角移动
- Titles注解可支持int[]数组
- 干掉徽章BadgeModes注解,提高徽章使用的灵活性,修改了TabBar调用徽章的方法
- 添加TabSelectBg结点,用来设置选中的背景
### V1.1.0
- 解决XML布局中渲染报错问题
- 修复点击Tab回调两次的BUG
- 新增切换对动画的回调接口方法,提高TabBar动画灵活性
### V1.1.2
- 给动画添加了弹性
- 修复当pager没有数据时无法点击问题
### V1.1.4
- 修复这个BUG当页面数量大于或者小于TabItem数量的问题
- 添加点击ITEM颜色渐变(有selectedicon)的效果
- 增加另一套初始化TabBarItems的方法
- 解决因为drawable共用内存,每次finish后,没有图标的问题。
# 希望
</p>如果你觉得这个项目快速和有用,有帮助,别忘记点一下右上角的星星,因为我要在下下年挑战BAT校招。
<br><br>
</p>世界上再强的程序员写代码过程中难免会出现BUG,如果使用者发现BUG,可联系我或者直接issue,谢谢!
# 关于我
一名在校大学生,目前还在专研学习各种技术中...<br>
QQ:83508440<br>
邮箱:83508440@qq.com
# License
```
Copyright 2016 [JPeng]
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.
```
|
Markdown
|
UTF-8
| 6,315
| 3.53125
| 4
|
[
"MIT"
] |
permissive
|
---
title: Segunda clase
date: '2019-03-25'
description: 'Introducción a Funcional. Composición, Precedencia de Operadores, primera parte de Tipado.'
tags: [funcional, composicion, tipado, precedencia-de-operadores, inmutabilidad]
---
## Tarea para la clase que viene
- **Hacer parejas para los trabajos practicos que ya se vienen!**
- **Hacer las lecciones 1 a 4 (inclusive) del capítulo 1 de [mumuki](https://mumuki.io/pdep-utn)**
## Qué empezamos viendo hoy?
Repasamos lo que vimos la clase pasada (los conceptos de **declaratividad** y **expresividad**, **abstraccion**, **delegacion**), y arrancamos con el paradigma **Funcional** y Haskell.
## Y qué es el paradigma funcional?
En el paradigma funcional veremos y trabajaremos, justamente, con el concepto de **_funciones_**. Y como las funciones de análisis matemático, las funciones tienen dos propiedades importantes: **existencia** y **unicidad**. Estas propiedades también se respetan en Haskell.
## Valores y Funciones
En Haskell, nosotros podemos definir valores, como tambien funciones:
```haskell
billetera = 100
-- Los valores pueden ser booleanos, enteros, strings, etc.
comprarAgua unaBilletera = unaBilletera - 30
```
Las funciones van a ser nuestra herramienta para poder operar sobre los valores. Si yo en la consola de Haskell escribo:
```
> comprarAgua billetera
=> 70
```
Y algo muy importante: **En Haskell no hay efecto**. Esto quiere decir que, los valores igualados no van a mutar luego de ser operados por las funciones (Este concepto se llama **_inmutabilidad_**).
Por ejemplo, si aplicamos `comprarAgua` a `billetera`, podemos ver que `billetera` no cambia su valor:
```
> billetera
=> 100
> comprarAgua billetera
=> 70
> billetera
=> 100
```
Por esto, es que en haskell logramos tener lo que se llama **Transparencia Referencial**.
## Composición
Supongamos que, como vimos en clase, tenemos esta otra funcion:
```haskell
ganarLoteria unaBilletera = unaBilletera + 1000
```
Ahora, quiero que en la billetera se vea que haya ganado la loteria y que me compré un agua. Como se hace?
Pues podemos utilizar la **Composicion** de funciones:
```
> (comprarAgua.ganarLoteria) billetera
=> 1070
```
Lo que está ocurriendo acá es lo mismo que con la composición de funciones matemáticas ( FoG(x) ). Primero se aplica la función de la derecha con el valor, y luego se aplica la de la izquierda con el valor que nos devolvió la función anterior.
Recordemos que, como en matemática, el valor que retorne la función de la derecha, tiene que ser **un valor que la función de la izquierda pueda operar**.
Por ejemplo, si tenemos esta nueva función:
```Haskell
esRico unaBilletera = unaBilletera > 1000
```
y la intento componer así:
```
> (ganarLoteria.esRico) billetera
```
Haskell nos va a decir que esta mal, ya que ganarLoteria tiene que recibir un numero, y esta recibiendo un booleano.
La version correcta seria asi:
```
> (esRico.ganarLoteria) billetera
```
Lo que nos queda después de componer dos funciones es una **nueva funcion**
tambien las podemos definir:
```haskell
ganarLoteriaYComprarAgua = comprarAgua.ganarLoteria
-- Notacion Point-Free, podemos ignorar parametros cuando las funciones
-- esperan ese mismo parametro (En este caso, la billetera).
```
## Precedencia de Operadores
En matemática, cuando tenemos una expresión como 2 \* 3 + 4, solemos operarla dependiendo de la precedencia de cada operador. Como el \* es de mayor precedencia que el +, operamos primero 2 \* 3 y luego le sumamos 4.
En haskell también se respeta esto. Les dejamos una tabla para que puedan ver la precedencia que utiliza Haskell:
| Precedencia (Mayor numero, mayor precedencia) | "Operador" |
| --------------------------------------------- | :------------------------------: |
| 10 | Aplicacion Normal de una Funcion |
| 9 | . |
| 8 | ^ |
| 7 | \*,/ |
| 6 | +,- |
| 5 | : |
| 4 | ==, /=, <, <=, >, >= |
| 3 | && |
| 2 | \|\| |
| 1 | \$ |
## Tipado
un **tipo** es un conjunto de valores, a los cuales uno puede operar con un conjunto de funciones (Que entienden esos valores). Se puede pensar como en las funciones matemáticas y los dominios de una función.
por ejemplo, los tipos de las funciones que utilizamos anteriormente serían:
```haskell
billetera :: Int
comprarAgua :: Int -> Int
ganarLoteria :: Int -> Int
esRico :: Int -> Bool
```
Ahora, **Para qué nos sirve tipar?**
Nos sirve para que, solo mirando el tipado de una función y el nombre de ésta (Y con una buena expresividad), podamos inferir que es lo que la función hace. También, es una gran forma de validar que lo que estamos pensando está bien. (Aparte, en el examen vamos a pedir que tipen las funciones, asi que ojo con esto!)
## Algunas funciones que vimos en clase
- even: Dado un numero, devuelve si este es par
```haskell
> even 2
=> True
```
- odd: Dado un numero, devuelve si este es impar
```haskell
> odd 2
=> False
```
- id: Dado un valor, devuelve ese mismo valor
```haskell
> id "Hola!"
=> "Hola!"
```
- (\$): Dada una funcion y un valor, devuelve el valor que es la aplicacion de la funcion al valor
```haskell
> even $ 2
=> True
```
Sirve mucho para deshacernos de paréntesis. por ejemplo, para las composiciones:
```haskell
> (comprarAgua.ganarLoteria) billetera
-- es equivalente hacer
> comprarAgua.ganarLoteria $ billetera
```
Esto ocurre gracias a la precedencia del \$.
## Links Útiles
- [Concepto de función](http://wiki.uqbar.org/wiki/articles/concepto-de-funcion.html)
- [Composición](http://wiki.uqbar.org/wiki/articles/composicion.html)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.