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
|
|---|---|---|---|---|---|---|---|
JavaScript
|
UTF-8
| 2,611
| 2.609375
| 3
|
[] |
no_license
|
function goto () {
this.closest('form').style.display = 'none' ;
document.querySelector(this.getAttribute('href')).style.display = '';
}
function submitForm(evt) {
evt.stopPropagation();
evt.preventDefault();
let els = this.querySelectorAll('input, select, textarea') ;
let datas = {} ;
for (var i in els) {
if(!els[i].type ||!els[i].name)
continue ;
if(els[i].type && ['radio', 'checkbox'].indexOf(els[i].type) !=-1) {
if(!els[i].checked) {
continue ;
}
}
if (!!els[i].value)
datas[els[i].name] = els[i].value ;
}
fetch(this.action, {
method : this.getAttribute('method'),
headers: {
'Content-Type': 'application/json',
},
body:JSON.stringify(datas) })
.then(r => r.text())
.then(response => {
if(response === 'user.login') {
document.getElementById('loginArea').style.display = 'none' ;
document.getElementById('tweetArea').style.display = '' ;
document.getElementById('logout').style.display = '' ;
document.getElementById('userWrapper').style.display = '' ;
document.getElementById('username').innerText = document.cookie.replace(/(?:(?:^|.*;\s*)loggedIn\s*\=\s*([^;]*).*$)|^.*$/, "$1");
return loadTweets();
}
if(response === 'tweet.sent') {
return this.reset();
}
alert('Veuillez vérifier le formulaire');
})
}
function loadTweets () {
fetch('/tweets', {credentials:'same-origin'}).then(r => r.json()).then(response => {
document.getElementById('tweets').innerHTML = response.response;
});
}
var socket ;
document.body.onload = evt => {
let userName = document.cookie.replace(/(?:(?:^|.*;\s*)loggedIn\s*\=\s*([^;]*).*$)|^.*$/, "$1");
if(userName) {
loadTweets () ;
}
socket = io('http://localhost:8000');
socket.on('tweet', function (data) {
if(data)
fetch('/tweets/'+data, {credentials:'same-origin'}).then(r => r.json()).then(response => {
document.getElementById('tweets').innerHTML = response.response + document.getElementById('tweets').innerHTML;
});
});
}
function logout (event) {
event.stopPropagation();
event.preventDefault();
fetch(event.target.href, {method:'DELETE'})
.then(r=>r.text())
.then(r=>{
document.getElementById('loginArea').style.display = '' ;
document.getElementById('tweetArea').style.display = 'none' ;
document.getElementById('logout').style.display = 'none' ;
document.getElementById('userWrapper').style.display = 'none' ;
document.getElementById('username').innerText = 'userName' ;
})
} ;
|
Java
|
UTF-8
| 10,282
| 2.140625
| 2
|
[] |
no_license
|
package my.aws.java.sandbox.application.aws.iam;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClientBuilder;
import com.amazonaws.services.identitymanagement.model.AddUserToGroupRequest;
import com.amazonaws.services.identitymanagement.model.AttachGroupPolicyRequest;
import com.amazonaws.services.identitymanagement.model.AttachRolePolicyRequest;
import com.amazonaws.services.identitymanagement.model.CreateGroupRequest;
import com.amazonaws.services.identitymanagement.model.CreateGroupResult;
import com.amazonaws.services.identitymanagement.model.CreateRoleRequest;
import com.amazonaws.services.identitymanagement.model.CreateRoleResult;
import com.amazonaws.services.identitymanagement.model.CreateUserRequest;
import com.amazonaws.services.identitymanagement.model.CreateUserResult;
import com.amazonaws.services.identitymanagement.model.DeleteGroupRequest;
import com.amazonaws.services.identitymanagement.model.DeleteRoleRequest;
import com.amazonaws.services.identitymanagement.model.DeleteUserRequest;
import com.amazonaws.services.identitymanagement.model.DetachGroupPolicyRequest;
import com.amazonaws.services.identitymanagement.model.DetachRolePolicyRequest;
import com.amazonaws.services.identitymanagement.model.Group;
import com.amazonaws.services.identitymanagement.model.ListAttachedRolePoliciesRequest;
import com.amazonaws.services.identitymanagement.model.ListAttachedRolePoliciesResult;
import com.amazonaws.services.identitymanagement.model.ListGroupsRequest;
import com.amazonaws.services.identitymanagement.model.ListGroupsResult;
import com.amazonaws.services.identitymanagement.model.ListRolePoliciesRequest;
import com.amazonaws.services.identitymanagement.model.ListRolePoliciesResult;
import com.amazonaws.services.identitymanagement.model.ListRolesRequest;
import com.amazonaws.services.identitymanagement.model.ListRolesResult;
import com.amazonaws.services.identitymanagement.model.ListUsersRequest;
import com.amazonaws.services.identitymanagement.model.ListUsersResult;
import com.amazonaws.services.identitymanagement.model.RemoveUserFromGroupRequest;
import com.amazonaws.services.identitymanagement.model.Role;
import com.amazonaws.services.identitymanagement.model.User;
public class AmazonIAMService {
private final AmazonIdentityManagement amazonIdentityManagement;
public AmazonIAMService(AWSCredentials awsCredentials) {
AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(awsCredentials);
amazonIdentityManagement = AmazonIdentityManagementClientBuilder
.standard()
.withCredentials(credentialsProvider)
.withRegion(Regions.EU_WEST_1)
.build();
}
public void createGroup(String groupName) {
System.out.println("Start create group with name: " + groupName);
CreateGroupRequest createGroupRequest = new CreateGroupRequest()
.withGroupName(groupName);
CreateGroupResult createGroupResult = amazonIdentityManagement.createGroup(createGroupRequest);
System.out.println("Created group: " + createGroupResult.getGroup());
}
public void deleteGroup(String groupName) {
DeleteGroupRequest deleteGroupRequest = new DeleteGroupRequest()
.withGroupName(groupName);
amazonIdentityManagement.deleteGroup(deleteGroupRequest);
System.out.println("Group deleted.");
}
public void createUser(String userName) {
CreateUserRequest createUserRequest = new CreateUserRequest()
.withUserName(userName);
CreateUserResult createUserResult = amazonIdentityManagement.createUser(createUserRequest);
System.out.println("Created user: " + createUserResult.getUser());
}
public void deleteUser(String userName) {
DeleteUserRequest deleteUserRequest = new DeleteUserRequest()
.withUserName(userName);
amazonIdentityManagement.deleteUser(deleteUserRequest);
System.out.println("User deleted.");
}
public void createRole(String roleName) {
CreateRoleRequest createRoleRequest = new CreateRoleRequest()
.withRoleName(roleName)
.withDescription("From sandbox: Allows EC2 instances to call AWS services on your behalf.")
.withAssumeRolePolicyDocument("{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"ec2.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}");
CreateRoleResult createRoleResult = amazonIdentityManagement.createRole(createRoleRequest);
System.out.println("Created role: " + createRoleResult.getRole());
}
public void deleteRole(String roleName) {
DeleteRoleRequest deleteRoleRequest = new DeleteRoleRequest()
.withRoleName(roleName);
amazonIdentityManagement.deleteRole(deleteRoleRequest);
System.out.println("Role deleted.");
}
public void listGroups() {
System.out.println("List of groups: ");
ListGroupsRequest listGroupsRequest = new ListGroupsRequest();
while (true) {
ListGroupsResult listGroupsResult = amazonIdentityManagement.listGroups(listGroupsRequest);
for (Group group : listGroupsResult.getGroups()) {
System.out.format("Retrieved group %s\n", group.getGroupName());
}
listGroupsRequest.setMarker(listGroupsResult.getMarker());
if (!listGroupsResult.getIsTruncated()) {
break;
}
}
}
public void listUsers() {
System.out.println("List of users: ");
ListUsersRequest listUsersRequest = new ListUsersRequest();
while (true) {
ListUsersResult listUsersResult = amazonIdentityManagement.listUsers(listUsersRequest);
for (User user : listUsersResult.getUsers()) {
System.out.format("Retrieved user %s\n", user.getUserName());
}
listUsersRequest.setMarker(listUsersResult.getMarker());
if (!listUsersResult.getIsTruncated()) {
break;
}
}
}
public void listRoles() {
System.out.println("List of roles: ");
ListRolesRequest listRolesRequest = new ListRolesRequest();
while (true) {
ListRolesResult listRolesResult = amazonIdentityManagement.listRoles(listRolesRequest);
for (Role role : listRolesResult.getRoles()) {
System.out.println("Retrieved role: " + role.getRoleName());
System.out.println(" - assumeRolePolicyDocument: " + role.getAssumeRolePolicyDocument());
System.out.println(" - description: " + role.getDescription());
System.out.println(" - arn: " + role.getArn());
listRolePolicies(role.getRoleName());
System.out.println();
}
listRolesRequest.setMarker(listRolesResult.getMarker());
if (!listRolesResult.getIsTruncated()) {
break;
}
}
}
private void listRolePolicies(String roleName) {
ListRolePoliciesRequest listRolePoliciesRequest = new ListRolePoliciesRequest()
.withRoleName(roleName);
ListRolePoliciesResult listRolePoliciesResult = amazonIdentityManagement.listRolePolicies(listRolePoliciesRequest);
System.out.println(listRolePoliciesResult);
ListAttachedRolePoliciesRequest listAttachedRolePoliciesRequest = new ListAttachedRolePoliciesRequest()
.withRoleName(roleName);
ListAttachedRolePoliciesResult listAttachedRolePoliciesResult = amazonIdentityManagement.listAttachedRolePolicies(listAttachedRolePoliciesRequest);
System.out.println(listAttachedRolePoliciesResult);
}
public void addUserToGroup(String groupName, String userName) {
AddUserToGroupRequest addUserToGroupRequest = new AddUserToGroupRequest()
.withGroupName(groupName)
.withUserName(userName);
amazonIdentityManagement.addUserToGroup(addUserToGroupRequest);
}
public void removeUserFromGroup(String groupName, String userName) {
RemoveUserFromGroupRequest removeUserFromGroupRequest = new RemoveUserFromGroupRequest()
.withGroupName(groupName)
.withUserName(userName);
amazonIdentityManagement.removeUserFromGroup(removeUserFromGroupRequest);
System.out.println("User removed from group.");
}
public void attachPolicyToGroup(String groupName, String policyArn) {
AttachGroupPolicyRequest attachGroupPolicyRequest = new AttachGroupPolicyRequest()
.withGroupName(groupName)
.withPolicyArn(policyArn);
amazonIdentityManagement.attachGroupPolicy(attachGroupPolicyRequest);
}
public void detachPolicyFromGroup(String groupName, String policyArn) {
DetachGroupPolicyRequest detachGroupPolicyRequest = new DetachGroupPolicyRequest()
.withGroupName(groupName)
.withPolicyArn(policyArn);
amazonIdentityManagement.detachGroupPolicy(detachGroupPolicyRequest);
System.out.println("Policy detached from group.");
}
public void attachPolicyToRole(String roleName, String policyArn) {
AttachRolePolicyRequest attachRolePolicyRequest = new AttachRolePolicyRequest()
.withRoleName(roleName)
.withPolicyArn(policyArn);
amazonIdentityManagement.attachRolePolicy(attachRolePolicyRequest);
}
public void detachPolicyFromRole(String roleName, String policyArn) {
DetachRolePolicyRequest detachRolePolicyRequest = new DetachRolePolicyRequest()
.withRoleName(roleName)
.withPolicyArn(policyArn);
amazonIdentityManagement.detachRolePolicy(detachRolePolicyRequest);
System.out.println("Policy detached from role.");
}
}
|
Java
|
UTF-8
| 2,628
| 1.945313
| 2
|
[] |
no_license
|
package com.ryj.yuyue.bean;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
/**
* 查询用户评分
* @author Thor
*
*/
public class ScoreResult {
private Integer id;
private Integer uId;
private String uName;
private Integer claId;
private String classKName;
private Integer claKId;
private Integer pId;
private String pName;
private Float score;
private String comment;
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date scoreTime;
private Integer orderId;
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date orderTime;
private Integer age;
private String gender;
private String picUrl;
public String getPicUrl() {
return picUrl;
}
public void setPicUrl(String picUrl) {
this.picUrl = picUrl;
}
public String getuName() {
return uName;
}
public void setuName(String uName) {
this.uName = uName;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getuId() {
return uId;
}
public void setuId(Integer uId) {
this.uId = uId;
}
public Integer getClaId() {
return claId;
}
public void setClaId(Integer claId) {
this.claId = claId;
}
public String getClassKName() {
return classKName;
}
public void setClassKName(String classKName) {
this.classKName = classKName;
}
public Integer getClaKId() {
return claKId;
}
public void setClaKId(Integer claKId) {
this.claKId = claKId;
}
public Integer getpId() {
return pId;
}
public void setpId(Integer pId) {
this.pId = pId;
}
public String getpName() {
return pName;
}
public void setpName(String pName) {
this.pName = pName;
}
public Float getScore() {
return score;
}
public void setScore(Float score) {
this.score = score;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public Date getScoreTime() {
return scoreTime;
}
public void setScoreTime(Date scoreTime) {
this.scoreTime = scoreTime;
}
public Integer getOrderId() {
return orderId;
}
public void setOrderId(Integer orderId) {
this.orderId = orderId;
}
public Date getOrderTime() {
return orderTime;
}
public void setOrderTime(Date orderTime) {
this.orderTime = orderTime;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
|
Rust
|
UTF-8
| 2,303
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
// Backup configuration structs
//
// Copyright (c) 2016 by William R. Fraser
//
use std::collections::btree_map::{BTreeMap, Entry, IterMut};
#[derive(Debug)]
pub struct Backup {
pub filename_base: String,
pub volume: String,
pub start_snapshot: Option<String>,
pub end_snapshot: Option<String>,
}
pub struct Backups {
backups_by_volume: BTreeMap<String, Backup>,
}
pub struct BackupsIterMut<'a> {
iter_mut: IterMut<'a, String, Backup>,
}
impl<'a> Iterator for BackupsIterMut<'a> {
type Item = &'a mut Backup;
fn next(&mut self) -> Option<&'a mut Backup> {
match self.iter_mut.next() {
Some((_, backup)) => Some(backup),
None => None,
}
}
}
impl Backups {
pub fn new() -> Backups {
Backups { backups_by_volume: BTreeMap::new() }
}
pub fn insert(&mut self,
filename_base: String,
volume: String,
start_snapshot: Option<String>) {
match self.backups_by_volume.entry(volume.clone()) {
Entry::Occupied(ref mut entry) => {
let backup = entry.get_mut();
if let Some(new_snapshot) = start_snapshot {
if backup.start_snapshot.is_none()
|| &new_snapshot > backup.start_snapshot.as_ref().unwrap()
{
backup.start_snapshot = Some(new_snapshot);
backup.filename_base = filename_base;
}
}
}
Entry::Vacant(entry) => {
entry.insert(Backup {
filename_base,
volume,
start_snapshot,
end_snapshot: None,
});
}
}
}
//#[allow(clippy::for_kv_map)]
pub fn into_values(self) -> Vec<Backup> {
let mut vec: Vec<Backup> = Vec::new();
for (_k, v) in self.backups_by_volume {
if v.end_snapshot.is_some() {
vec.push(v);
}
}
vec
}
pub fn iter_mut(&mut self) -> BackupsIterMut {
BackupsIterMut { iter_mut: self.backups_by_volume.iter_mut() }
}
}
|
Python
|
UTF-8
| 911
| 2.53125
| 3
|
[] |
no_license
|
from flask import Flask,render_template,request, make_response, redirect, url_for
app = Flask(__name__)
@app.route('/')
def user_login():
return render_template('login.html')
@app.route('/set', methods = ['POST','GET'])
def set_user_cookie():
if request.method == 'POST':
username = request.form['username']
from_cookie = request.cookies.get('username')
if username==from_cookie:
return redirect(url_for('welcome_user'))
else:
res = make_response(render_template('welcome.html', user=username))
res.set_cookie('username',username)
return res
@app.route('/welcome', methods = ['POST','GET'])
def welcome_user():
username = request.cookies.get('username')
#return '<h1>Welcome '+username+'</h1>'
return render_template('display.html',username=username)
if __name__ == '__main__':
app.run(debug = True)
|
Java
|
UTF-8
| 3,581
| 2.109375
| 2
|
[] |
no_license
|
package com.google.android.gms.measurement.internal;
import android.os.Parcel;
import android.os.Parcelable.Creator;
import com.google.android.gms.common.internal.Preconditions;
import com.google.android.gms.common.internal.safeparcel.AbstractSafeParcelable;
import com.google.android.gms.common.internal.safeparcel.SafeParcelWriter;
public final class zzfh extends AbstractSafeParcelable {
public static final Creator<zzfh> CREATOR = new zzfi();
public final String name;
public final String origin;
private final int versionCode;
private final String zzamp;
public final long zzaue;
private final Long zzauf;
private final Float zzaug;
private final Double zzauh;
zzfh(zzfj com_google_android_gms_measurement_internal_zzfj) {
this(com_google_android_gms_measurement_internal_zzfj.name, com_google_android_gms_measurement_internal_zzfj.zzaue, com_google_android_gms_measurement_internal_zzfj.value, com_google_android_gms_measurement_internal_zzfj.origin);
}
zzfh(String str, long j, Object obj, String str2) {
Preconditions.checkNotEmpty(str);
this.versionCode = 2;
this.name = str;
this.zzaue = j;
this.origin = str2;
if (obj == null) {
this.zzauf = null;
this.zzaug = null;
this.zzauh = null;
this.zzamp = null;
} else if (obj instanceof Long) {
this.zzauf = (Long) obj;
this.zzaug = null;
this.zzauh = null;
this.zzamp = null;
} else if (obj instanceof String) {
this.zzauf = null;
this.zzaug = null;
this.zzauh = null;
this.zzamp = (String) obj;
} else if (obj instanceof Double) {
this.zzauf = null;
this.zzaug = null;
this.zzauh = (Double) obj;
this.zzamp = null;
} else {
throw new IllegalArgumentException("User attribute given of un-supported type");
}
}
zzfh(int i, String str, long j, Long l, Float f, String str2, String str3, Double d) {
Double d2 = null;
this.versionCode = i;
this.name = str;
this.zzaue = j;
this.zzauf = l;
this.zzaug = null;
if (i == 1) {
if (f != null) {
d2 = Double.valueOf(f.doubleValue());
}
this.zzauh = d2;
} else {
this.zzauh = d;
}
this.zzamp = str2;
this.origin = str3;
}
public final Object getValue() {
if (this.zzauf != null) {
return this.zzauf;
}
if (this.zzauh != null) {
return this.zzauh;
}
if (this.zzamp != null) {
return this.zzamp;
}
return null;
}
public final void writeToParcel(Parcel parcel, int i) {
int beginObjectHeader = SafeParcelWriter.beginObjectHeader(parcel);
SafeParcelWriter.writeInt(parcel, 1, this.versionCode);
SafeParcelWriter.writeString(parcel, 2, this.name, false);
SafeParcelWriter.writeLong(parcel, 3, this.zzaue);
SafeParcelWriter.writeLongObject(parcel, 4, this.zzauf, false);
SafeParcelWriter.writeFloatObject(parcel, 5, null, false);
SafeParcelWriter.writeString(parcel, 6, this.zzamp, false);
SafeParcelWriter.writeString(parcel, 7, this.origin, false);
SafeParcelWriter.writeDoubleObject(parcel, 8, this.zzauh, false);
SafeParcelWriter.finishObjectHeader(parcel, beginObjectHeader);
}
}
|
Java
|
UTF-8
| 11,234
| 3.359375
| 3
|
[] |
no_license
|
package controller.inventory;
import controller.itemsAndPuzzle.Weapon;
import controller.itemsAndPuzzle.Armor;
import controller.itemsAndPuzzle.Elixir;
import view.View;
/**
* author: JJ Lindsay
* version: 2.0
* Course: ITEC 3860 Fall 2014
* Written: 11/16/2014
*
* This class represents an inventory.
*
* Purpose: Allows storing, retrieval, and removal of items.
*/
public class Inventory
{
//instances variables
private final int SIZELIMIT = 10;
private String[][] ruckSack;
char[] itemType; //A, E, W for armor, elixir, or weapon
private int itemCount;
private Weapon[] weapons;
private Elixir[] elixirs;
private Armor[] armors;
/**No argument constructor
*/
public Inventory()
{
ruckSack = new String[SIZELIMIT][2]; //contains 10 rows and 2 columns for item name and itemType
itemType = new char[SIZELIMIT];
itemCount = 0;
weapons = new Weapon[SIZELIMIT];
armors = new Armor[SIZELIMIT];
elixirs = new Elixir[SIZELIMIT];
}
/**Adds a weapon to the ruckSack/inventory and weapons array
* @param weapon a weapon object
* @return true or false for successfully adding a weapon to inventory
*/
public boolean add(Weapon weapon)
{
if (itemCount < SIZELIMIT)
{
for (int x = 0; x < SIZELIMIT; x++)
{
if (weapons[x] == null)
{
for(int p = 0; p < SIZELIMIT; p++)
{
if (ruckSack[p][0] == null)
{
weapons[x] = weapon;
ruckSack[p][0] = weapons[x].getItemName();
ruckSack[p][1] = "w";
itemCount++;
return true;
}
}
}
}
}
new View().setControllerDisplay("You are unable to carry any more items.");
return false;
}
/**Adds an armor to the ruckSack/inventory and armors array
* @param armor An armor object
* @return true or false for successfully adding an armor to inventory
*/
public boolean add(Armor armor)
{
if (itemCount < SIZELIMIT)
{
for (int x = 0; x < SIZELIMIT; x++)
{
if (armors[x] == null)
{
for(int p = 0; p < SIZELIMIT; p++)
{
if (ruckSack[p][0] == null)
{
armors[x] = armor;
ruckSack[p][0] = armors[x].getItemName();
ruckSack[p][1] = "a";
itemCount++;
return true;
}
}
}
}
}
new View().setControllerDisplay("You are unable to carry any more items.");
return false;
}
/**Adds an elixir to the ruckSack/inventory and elixirs array
* @param elixir An elixir object
* @return true or false for successfully adding a weapon to inventory
*/
public boolean add(Elixir elixir)
{
if (itemCount < SIZELIMIT)
{
for (int x = 0; x < SIZELIMIT; x++)
{
if (elixirs[x] == null)
{
for(int p = 0; p < SIZELIMIT; p++)
{
if (ruckSack[p][0] == null)
{
elixirs[x] = elixir;
ruckSack[p][0] = elixirs[x].getItemName();
ruckSack[p][1] = "e";
itemCount++;
return true;
}
}
}
}
}
new View().setControllerDisplay("You are unable to carry any more items.");
return false;
}
/**Locates and removes an item given its name from the ruckSack/inventory and either weapons[],
* armors[], or elixirs[]
* @param weaponArmElixName The nme of the item to be removed
* @return true or false for successfully removing an item from inventory
*/
public Boolean remove(String weaponArmElixName)
{
for(int p = 0; p < SIZELIMIT; p++)
{
//locate the item name
if (ruckSack[p][0] != null && ruckSack[p][0].equalsIgnoreCase(weaponArmElixName))
{
//identify the item
if (ruckSack[p][1].equalsIgnoreCase("w"))
{
for (int x = 0; x < SIZELIMIT; x++)
{
if (weapons[x] != null && weapons[x].getItemName().equalsIgnoreCase(weaponArmElixName))
{
weapons[x] = null;
ruckSack[p][0] = null;
ruckSack[p][1] = null;
itemCount--;
return true;
}
}
}
else if (ruckSack[p][1].equalsIgnoreCase("e"))
{
int x = 0;
while (x < SIZELIMIT)
{
if (elixirs[x] != null && elixirs[x].getItemName().equalsIgnoreCase(weaponArmElixName))
{
elixirs[x] = null;
ruckSack[p][0] = null;
ruckSack[p][1] = null;
itemCount--;
return true;
}
x++;
}
}
else //armor
{
for (int x = 0; x < SIZELIMIT; x++)
{
if (armors[x] != null && armors[x].getItemName().equalsIgnoreCase(weaponArmElixName))
{
armors[x] = null;
ruckSack[p][0] = null;
ruckSack[p][1] = null;
itemCount--;
return true;
}
}
}
}
}
new View().setControllerDisplay(weaponArmElixName + " could not be found in your inventory.");
return false;
}
/**Displays a detailed view of the ruckSack/inventory contents by
* also displaying the stats on each item
*/
public String view()
{
String inInventory = "";
if (itemCount > 0)
{
for (int i = 0; i < ruckSack.length; i++)
{
if (ruckSack[i][0] != null)
{
inInventory += "Item type: " + ruckSack[i][1];
inInventory += "\tItem: " + ruckSack[i][0];
if (ruckSack[i][1].equalsIgnoreCase("w"))
{
inInventory += "\tAttack boost: " + getWeapon(ruckSack[i][0]).getStrength() + "\n";
}
else if (ruckSack[i][1].equalsIgnoreCase("a"))
{
inInventory += "\tDefensive boost: " + getArmor( ruckSack[i][0]).getArmorDefense() + "\n";
}
else //elixir
{
inInventory += "\tHealth boost: " + getElixir(ruckSack[i][0]).getHealthBoost() + "\n";
}
}
}
}
else
{
inInventory = "Your inventory appears to be empty.";
}
return inInventory;
}
/**Finds an weapon in the ruckSack/inventory and retrieves the weapon from the weapons array
* @param weaponName The name of a weapon
* @return weapons[s] Gets the weapon object
*/
public Weapon getWeapon(String weaponName)
{
for (int s = 0; s < SIZELIMIT; s++)
{
if (weapons[s] != null && weapons[s].getItemName().equalsIgnoreCase(weaponName))
{
return weapons[s];
}
}
new View().setControllerDisplay("Your inventory appears to be empty.");
return null;
}
/**Finds an elixir in the ruckSack/inventory and retrieves the elixir from the elixirs array
* @param elixirName The name of an elixir
* @return elixirs[s] Gets the elixir object
*/
public Elixir getElixir(String elixirName)
{
for (int s = 0; s < SIZELIMIT; s++)
{
if (elixirs[s] != null && elixirs[s].getItemName().equalsIgnoreCase(elixirName))
{
return elixirs[s];
}
}
new View().setControllerDisplay("Your inventory appears to be empty.");
return null;
}
/**Finds an armor in the ruckSack/inventory and retrieves the armor from the armors array
* @param armorName The name of an armor
* @return armors[s] Gets the armor object
*/
public Armor getArmor(String armorName)
{
for (int s = 0; s < SIZELIMIT; s++)
{
if (armors[s] != null && armors[s].getItemName().equalsIgnoreCase(armorName))
{
return armors[s];
}
}
new View().setControllerDisplay("Your inventory appears to be empty.");
return null;
}
/**Confirms an item exist in the ruckSack/inventory
* @param weaponArmElixName The name of an item
* @return true or false Gets the existence of an item
*/
public Boolean confirmItem(String weaponArmElixName)
{
int h = 0;
if (itemCount > 0 && weaponArmElixName != null)
{
while (h <= itemCount)
{
if (ruckSack[h][0] != null && weaponArmElixName.equalsIgnoreCase(ruckSack[h][0]))
{
return true;
}
h++;
}
new View().setControllerDisplay("No item with the name: " + weaponArmElixName + " could be found in your inventory. Check your spelling and try again.");
}
else
{
new View().setControllerDisplay("Your inventory appears to be empty.");
}
return false;
}
/**Identifies the item type based on the item's name
* @param weaponArmElixName The name of an item
* @return ruckSack[s][1] Gets the item type a, e or w
*/
public String getItemType(String weaponArmElixName)
{
for (int s = 0; s < SIZELIMIT; s++)
{
if (ruckSack[s][0] != null && ruckSack[s][0].equalsIgnoreCase(weaponArmElixName))
{
return ruckSack[s][1];
}
}
new View().setControllerDisplay("No item type for " + weaponArmElixName + " could not be found in your inventory.");
return null;
}
/**
* @return ruckSack Gets the ruckSack/inventory
*/
public String[][] getRuckSack()
{
return ruckSack;
}
}
|
Java
|
UTF-8
| 1,061
| 2.03125
| 2
|
[] |
no_license
|
package com.talend.components.source.details;
import java.io.Serializable;
import com.talend.components.source.TCompStore;
import org.talend.sdk.component.api.configuration.Option;
import org.talend.sdk.component.api.configuration.type.DataSet;
import org.talend.sdk.component.api.configuration.ui.layout.GridLayout;
import org.talend.sdk.component.api.meta.Documentation;
@GridLayout({
// the generated layout put one configuration entry per line,
// customize it as much as needed
@GridLayout.Row({ "dataStore" }),
})
@Documentation("TODO fill the documentation for this configuration")
public class ComponentDetailsProcessorConfiguration implements Serializable {
@Option
@Documentation("Base url of TCOMP server.")
private TCompStore dataStore;
public TCompStore getDataStore() {
return dataStore;
}
public ComponentDetailsProcessorConfiguration setDataStore(TCompStore dataStore) {
this.dataStore = dataStore;
return this;
}
}
|
JavaScript
|
UTF-8
| 1,307
| 2.65625
| 3
|
[] |
no_license
|
const fs = require('fs');
const path = require('path');
// 模拟浏览器向网站发送请求
const superagent = require("superagent");
// 服务器端的 jQuery,相当于 html中的 jQuery
const cheerio = require("cheerio");
// 1.爬取的请求地址:丁香园
const url = 'https://ncov.dxy.cn/ncovh5/view/pneumonia';
superagent.get(url)
.then(res => {
// console.log(res.text); // 相应的内容
// 2. 去解析 html字符串从里面提取对应的疫情数据
const $ = cheerio.load(res.text);
var $getAreaStat = $('#getAreaStat').html();
var $getListByCountryTypeService2true = $('#getListByCountryTypeService2true').html();
// console.log($getAreaStat);
// 3. 使用正则表达式,unescape()函数转编码,字符串切割或 eval函数将代码运行
var dataObj = {}; // 定义对象换掉源码的 window
eval($getAreaStat.replace(/window/g,'dataObj'));
eval($getListByCountryTypeService2true.replace(/window/g,'dataObj'));
// console.log(dataObj); // 此时该对象就有我们添加的属性了
// 4. 用 fs模块写入数据到本地
fs.writeFile(path.join(__dirname,'data.json'),JSON.stringify(dataObj),err=>{
if(err) throw err;
console.log('数据写入成功');
})
})
.catch(err=>{
throw err
});
|
Ruby
|
UTF-8
| 1,981
| 2.796875
| 3
|
[] |
no_license
|
require('minitest/autorun')
require('minitest/reporters')
require_relative('../sport_team.rb')
Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new()
class TestTeam < Minitest::Test
def test_team_name
new_team = Team.new("The Wildcats", ["Ross", "Bob", "Jess", "Lucy"], "Arnold Palmer")
assert_equal("The Wildcats", new_team.team_name())
end
def test_players
new_team = Team.new("The Penguins", ["Smith", "Will", "Rob", "Emma"], "Will Smith")
assert_equal(["Smith", "Will", "Rob", "Emma"], new_team.players())
end
def test_coach
new_team = Team.new("The Penguins", ["Smith", "Will", "Rob", "Emma"], "Will Smith")
assert_equal("Will Smith", new_team.coach())
end
def test_set_coach
new_team = Team.new("The Penguins", ["Smith", "Will", "Rob", "Emma"], "Will Smith")
new_team.coach = "Rob Ross"
assert_equal("Rob Ross", new_team.coach())
end
def test_add_new_player()
new_team = Team.new("The Rovers", ["Smith", "Will", "Rob", "Emma"], "Will Smith")
new_team.add_new_player("Jane")
assert_equal(["Smith", "Will", "Rob", "Emma", "Jane"], new_team.players())
end
def test_check_for_player__found()
new_team = Team.new("The Rovers", ["Jane", "Bob", "Rob", "Emma"], "Will Smith")
assert_equal(true, new_team.check_for_player("Jane"))
end
def test_check_for_player__not_found()
new_team = Team.new("The Rovers", ["Jane", "Bob", "Rob", "Emma"], "Will Smith")
assert_equal(false, new_team.check_for_player("Bill"))
end
def test_points_update__win()
new_team = Team.new("Tigers", ["Jane", "Bob", "Rob", "Emma"], "John")
new_team.points_update("win")
assert_equal(1, new_team.points)
end
def test_points_update__lose()
new_team = Team.new("Tigers", ["Jane", "Bob", "Rob", "Emma"], "John")
new_team.points_update("lose")
assert_equal(-1, new_team.points)
end
end
|
JavaScript
|
UTF-8
| 2,670
| 3.359375
| 3
|
[] |
no_license
|
document.addEventListener('DOMContentLoaded', () => {
})
const BASEURL = `http://localhost:3000/dogs/`;
//get all the dogs
function getDogs(){
debugger
return fetch(BASEURL)
.then(resp => resp.json())
}
//edit a dog
function updateDog (dog) {
return fetch(BASEURL + `/${dog.id}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(dog)
}).then(resp => resp.json())
}
//get HTML elements
const tableBody = document.getElementById("table-body")
const dogForm = document.getElementById("dog-form")
// add a single dog to the page
function addDog(dog){
let dogtr = document.createElement('tr')
let editBtn = document.querySelector('button')
let dogNameTd = document.createElement('td')
dogNameTd.innerText = dog.name
let dogBreedTd = document.createElement('td')
dogBreedTd.innerText = dog.breed
let dogSexTd = document.createElement('td')
dogSexTd.innerText = dog.sex
let dogEditTd = document.createElement('td')
let dogEditButton = document.createElement('button')
dogEditButton.dataset.id = dog.id
dogEditButton.className = 'button'
dogEditButton.innerText = "Edit"
dogEditButton.addEventListener('click', () => editDog(dog))
dogEditTd.append(dogEditButton)
dogtr.append(dogNameTd, dogBreedTd, dogSexTd, dogEditTd)
tableBody.appendChild(dogtr);
}
function editDog(dog){
dogForm.name.value = dog.name
dogForm.breed.value = dog.breed
dogForm.sex.value = dog.sex
dogForm.dataset.id = dog.id
}
// function addEventListenerToBtn(){
// let editBtn = document.querySelector('.button')
// editBtn.addEventListener("click", function(event){
// console.log(event.target.dataset.id);
// })
// }
//add multiple dogs to page
function addAllDogs(dogs){
tableBody.innerHTML = ""
dogs.forEach(dog => addDog(dog))
}
function updateDogToServer(event){
event.preventDefault()
return fetch(BASEURL + dogForm.dataset.id,{
method: "PATCH",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(
{
name: dogForm.name.value,
breed: dogForm.breed.value,
sex: dogForm.sex.value
}
)
})
.then(() => {
dogForm.reset()
init()
})
}
dogForm.addEventListener('submit', updateDogToServer)
function init(){
fetch(BASEURL)
.then(data => data.json())
.then(dogs => addAllDogs(dogs));
}
init()
|
C#
|
UTF-8
| 207
| 2.796875
| 3
|
[] |
no_license
|
WorkOrder w = new WorkOrder();
Type t = typeof(WorkOrder);
foreach (XmlNode xl in myXML)
{
PropertyInfo pi = t.GetProperty(xl.Name);
pi.SetValue(w, xl.InnerText, null);
}
|
Python
|
UTF-8
| 24,501
| 2.5625
| 3
|
[] |
no_license
|
# Import generic packages
import time
import configparser
# Import multi-threading capacity
from multiprocessing import Queue
from threading import Thread, Event
# Import GUI packages
import tkinter as tk
import tkinter.font as tkFont
import tkinter.ttk as ttk
font_collection = {}
class gui_manager(Thread):
def __init__(self, master_thread, outbound_queue, inbound_queue):
# Class name
self.__name = 'gui'
print(self.__name + ' thread - Initializing ... ', end='')
# Master thread
self.master_thread = master_thread
# Class variables
self.settings_grid = self.master_thread.settings_grid
self.status_grid = self.master_thread.status_grid
self.selection_grid = self.master_thread.selection_grid
self.data_grid = self.master_thread.data_grid
self.loop_timer = 0.05
# Class queues
self.inbound_q = inbound_queue
self.outbound_q = outbound_queue
# Class events
self._stopped = Event()
# Class command handlers
self.command_handlers = {
}
# Load configuration from last open
user_config = configparser.ConfigParser()
user_config.read('user_settings.ini')
self.master_thread.update_thread_selection('target_coin', user_config['SELECTION']['target_coin'])
self.master_thread.update_thread_selection('target_notional',
float(user_config['SELECTION']['target_notional']))
print('Done.')
super(gui_manager, self).__init__()
def run(self):
print(self.__name + ' thread - Started.')
# Generate tkinter master window
self.gui_root = tk.Tk()
# Font Dictionary
font_collection['button1'] = tkFont.Font(family='arial', size=10, weight='bold')
font_collection['header1'] = tkFont.Font(family='arial', size=10, weight='bold')
font_collection['body1'] = tkFont.Font(family='arial', size=10)
# Instantiate window classes
self.main_window = main_window(self.gui_root, self.inbound_q, self.outbound_q, self)
self.gui_root.after(0, self.run_gui)
self.gui_root.mainloop()
def run_gui(self):
# Gui main loop
if not self._stopped.is_set():
if not self.inbound_q.empty():
src_name, tgt_name, command, payload = self.inbound_q.get()
if command not in self.command_handlers:
print(self.__name + ' thread - No handler for ' + command)
else:
self.command_handlers[command](src_name, tgt_name, command, payload)
self.gui_root.update()
self.main_window.update_data_grid()
time.sleep(self.loop_timer)
self.gui_root.after(0, self.run_gui)
else:
# Todo: set all tkinter varaibles to None on exit
self.gui_root.destroy()
self.gui_root.quit()
def stop(self):
# Save last selection for next startup
config = configparser.ConfigParser()
config['SELECTION'] = self.selection_grid
with open('user_settings.ini', 'w') as configfile:
config.write(configfile)
# Set Stop event
print(self.__name + ' thread - Shutting down.')
self._stopped.set()
def update_status_grid(self):
self.main_window.update_status_grid()
class main_window:
def __init__(self, gui_root, inbound_q, outbound_q, parent):
# Class internal variables
self.__name = 'gui'
self.gui_root = gui_root
self.parent = parent
self.gui_root.title('Program')
self.frame = tk.Frame(self.gui_root)
self.inbound_q = inbound_q
self.outbound_q = outbound_q
# Status grid mappings to GUI dynamic variables
self.status_map = {
'master': (2, 0), 'tfx_ws': (2, 1), 'qcx_ws': (2, 2), 'bfx_ws': (2, 4)
}
# Data grid mappings to GUI dynamic variables
self.data_map = {
'fx_pair': (3, 3), 'fx_rate': (3, 5), 'qcx_cad': (6, 0), 'qcx_usd': (6, 1), 'qcx_usd_to_cad': (6, 2),
'qcx_implied_fx_rate': (6, 4), 'qcx_internal_fx_coin_spread': (7, 1), 'qcx_internal_fx_spread': (7, 4),
'bfx_cad': (9, 0), 'bfx_usd': (9, 1), 'arb_spread': (9, 2), 'arb_return': (9, 4)
}
self.data_logic_map = {
'qcx_usd': self.__check_if_multi_fiat_active,
'qcx_usd_to_cad': self.__check_if_multi_fiat_active,
'qcx_implied_fx_rate': self.__check_if_multi_fiat_active,
'qcx_internal_fx_coin_spread': self.__check_if_multi_fiat_active,
'qcx_internal_fx_spread': self.__check_if_multi_fiat_active
}
self.data_format_map = {
'qcx_cad': '$ {0:.2f}', 'qcx_usd': '$ {0:.2f}', 'qcx_usd_to_cad': '$ {0:.2f}',
'qcx_implied_fx_rate': '{0:.6}', 'qcx_internal_fx_coin_spread': '$ {0:.2f}',
'qcx_internal_fx_spread': '{} BPS',
'bfx_cad': '$ {0:.2f}', 'bfx_usd': '$ {0:.2f}',
'arb_spread': '$ {0:.2f}', 'arb_return': '{0:.2f} %'
}
# Window grid objects
self._tk_grid_obj = {
0: {0: None},
1: {0: None, 1: None, 2: None, 4: None},
2: {0: None, 1: None, 2: None, 4: None},
3: {0: None, 1: None, 2: None, 3: None, 4: None, 5: None},
4: {0: None, 1: None, 2: None, 4: None, 5: None},
5: {0: None, 1: None, 2: None, 4: None},
6: {0: None, 1: None, 2: None, 4: None},
7: {0: None, 1: None, 2: None, 4: None},
8: {0: None, 1: None, 2: None, 4: None},
9: {0: None, 1: None, 2: None, 4: None},
10: {0: None}
}
# Window grid variables
self._tk_var_obj = {
0: {0: 'Stop Main Program'},
1: {0: 'Master Thread', 1: 'TrueFX Thread', 2: 'Quadriga Thread', 4: 'BitFinex Thread'},
2: {0: tk.StringVar(), 1: tk.StringVar(), 2: tk.StringVar(), 4: tk.StringVar()},
3: {0: 'Coin to Arb:', 1: tk.StringVar(), 2: 'FX Pair:', 3: tk.StringVar(),
4: 'FX Rate:', 5: tk.DoubleVar()},
4: {0: 'Notional Target (CAD):', 1: tk.DoubleVar(), 2: 'Set Notional Target',
4: 'Target (CAD):', 5: tk.StringVar()},
5: {0: 'Quadriga CAD Price', 1: 'Quadriga USD Price', 2: 'QCX Implied CAD Price',
4: 'QCX Implied FX Rate'},
6: {0: tk.StringVar(), 1: tk.StringVar(), 2: tk.StringVar(), 4: tk.StringVar()},
7: {0: 'QCX Internal FX Spread:', 1: tk.StringVar(), 2: 'QCX FX BPS Spread:', 4: tk.StringVar()},
8: {0: 'BFX CAD Price', 1: 'BFX USD Price', 2: 'Arbitrage P&L (CAD)', 4: 'Arbitrage % Return'},
9: {0: tk.StringVar(), 1: tk.StringVar(), 2: tk.StringVar(), 4: tk.StringVar()},
10: {0: ''}
}
# Window width settings
self._column_width = {0: 250, 1: 250, 2: 250, 3: 250, 4: 250, 5: 150}
# ========================================== GRID OBJECTS ========================================== #
# ============================================== ROW 0 ============================================= #
self._tk_grid_obj[0][0] = tk.Button(
self.gui_root,
text=self._tk_var_obj[0][0], font=font_collection['header1'], background='light grey',
command=self.__button_stop_main
)
self._tk_grid_obj[0][0].grid(row=0, column=0, padx=5, pady=5, sticky=('N', 'W', 'E', 'S'), columnspan=2)
# ============================================== ROW 1 ============================================= #
self._tk_grid_obj[1][0] = tk.Message(
self.gui_root, width=self._column_width[0],
text=self._tk_var_obj[1][0], font=font_collection['header1'], relief='ridge'
)
self._tk_grid_obj[1][0].grid(row=1, column=0, padx=5, sticky=('N', 'W', 'E', 'S'), columnspan=1)
self._tk_grid_obj[1][1] = tk.Message(
self.gui_root, width=self._column_width[1],
text=self._tk_var_obj[1][1], font=font_collection['header1'], relief='ridge'
)
self._tk_grid_obj[1][1].grid(row=1, column=1, padx=5, sticky=('N', 'W', 'E', 'S'), columnspan=1)
self._tk_grid_obj[1][2] = tk.Message(
self.gui_root, width=self._column_width[2],
text=self._tk_var_obj[1][2], font=font_collection['header1'], relief='ridge'
)
self._tk_grid_obj[1][2].grid(row=1, column=2, padx=5, sticky=('N', 'W', 'E', 'S'), columnspan=2)
self._tk_grid_obj[1][4] = tk.Message(
self.gui_root, width=self._column_width[4],
text=self._tk_var_obj[1][4], font=font_collection['header1'], relief='ridge'
)
self._tk_grid_obj[1][4].grid(row=1, column=4, padx=5, sticky=('N', 'W', 'E', 'S'), columnspan=2)
# ============================================== ROW 2 ============================================= #
self._tk_grid_obj[2][0] = tk.Message(
self.gui_root, width=self._column_width[0],
textvariable=self._tk_var_obj[2][0], font=font_collection['header1'], relief='ridge'
)
self._tk_grid_obj[2][0].grid(row=2, column=0, padx=5, sticky=('N', 'W', 'E', 'S'), columnspan=1)
self._tk_grid_obj[2][1] = tk.Message(
self.gui_root, width=self._column_width[1],
textvariable=self._tk_var_obj[2][1], font=font_collection['header1'], relief='ridge'
)
self._tk_grid_obj[2][1].grid(row=2, column=1, padx=5, sticky=('N', 'W', 'E', 'S'), columnspan=1)
self._tk_grid_obj[2][2] = tk.Message(
self.gui_root, width=self._column_width[2],
textvariable=self._tk_var_obj[2][2], font=font_collection['header1'], relief='ridge'
)
self._tk_grid_obj[2][2].grid(row=2, column=2, padx=5, sticky=('N', 'W', 'E', 'S'), columnspan=2)
self._tk_grid_obj[2][4] = tk.Message(
self.gui_root, width=self._column_width[4],
textvariable=self._tk_var_obj[2][4], font=font_collection['header1'], relief='ridge'
)
self._tk_grid_obj[2][4].grid(row=2, column=4, padx=5, sticky=('N', 'W', 'E' 'S'), columnspan=2)
# ============================================== ROW 3 ============================================= #
self._tk_grid_obj[3][0] = tk.Message(
self.gui_root, width=self._column_width[0],
text=self._tk_var_obj[3][0], font=font_collection['header1']
)
self._tk_grid_obj[3][0].grid(row=3, column=0, padx=5, pady=5, sticky=('N', 'W', 'E', 'S'),columnspan=1)
self._tk_var_obj[3][1].set(self.parent.selection_grid['target_coin'])
self._tk_var_obj[3][1].trace('w', self.__trace_option_menu_change_r3_c1)
self._tk_grid_obj[3][1] = tk.OptionMenu(
self.gui_root, self._tk_var_obj[3][1], *self.parent.settings_grid['TARGET_ARB_COINS']
)
self._tk_grid_obj[3][1].config(font=font_collection['body1'], width=10)
self._tk_grid_obj[3][1].grid(row=3, column=1, padx=5, pady=5, sticky=('N', 'W', 'E', 'S'), columnspan=1)
self._tk_grid_obj[3][2] = tk.Message(
self.gui_root, width=self._column_width[2],
text=self._tk_var_obj[3][2], font=font_collection['header1']
)
self._tk_grid_obj[3][2].grid(row=3, column=2, padx=5, pady=5, sticky=('N', 'W', 'E', 'S'), columnspan=1)
self._tk_var_obj[3][3].set('')
self._tk_grid_obj[3][3] = tk.Message(
self.gui_root, width=self._column_width[3],
textvariable=self._tk_var_obj[3][3], font=font_collection['body1']
)
self._tk_grid_obj[3][3].grid(row=3, column=3, padx=5, pady=5, sticky=('N', 'W', 'E', 'S'), columnspan=1)
self._tk_grid_obj[3][4] = tk.Message(
self.gui_root, width=self._column_width[4],
text=self._tk_var_obj[3][4], font=font_collection['header1']
)
self._tk_grid_obj[3][4].grid(row=3, column=4, padx=5, pady=5, sticky=('N', 'W', 'E', 'S'), columnspan=1)
self._tk_var_obj[3][5].set('')
self._tk_grid_obj[3][5] = tk.Message(
self.gui_root, width=self._column_width[5],
textvariable=self._tk_var_obj[3][5], font=font_collection['body1']
)
self._tk_grid_obj[3][5].grid(row=3, column=5, padx=5, pady=5, sticky=('N', 'W', 'E', 'S'), columnspan=1)
# ============================================== ROW 4 ============================================= #
self._tk_grid_obj[4][0] = tk.Message(
self.gui_root, width=self._column_width[0],
text=self._tk_var_obj[4][0], font=font_collection['header1']
)
self._tk_grid_obj[4][0].grid(row=4, column=0, padx=5, pady=5, sticky=('N', 'W', 'E', 'S'), columnspan=1)
self._tk_grid_obj[4][1] = tk.Entry(
self.gui_root,
textvariable=self._tk_var_obj[4][1], font=font_collection['body1'], justify='right'
)
self._tk_grid_obj[4][1].grid(row=4, column=1, padx=5, pady=5, sticky=('N', 'W', 'E', 'S'), columnspan=1)
self._tk_grid_obj[4][2] = tk.Button(
self.gui_root,
text=self._tk_var_obj[4][2], font=font_collection['header1'], background='light grey',
command=self.__button_set_notional
)
self._tk_grid_obj[4][2].grid(row=4, column=2, padx=5, pady=5, sticky=('N', 'W', 'E', 'S'), columnspan=2)
self._tk_grid_obj[4][4] = tk.Message(
self.gui_root, width=self._column_width[4],
text=self._tk_var_obj[4][4], font=font_collection['header1']
)
self._tk_grid_obj[4][4].grid(row=4, column=4, padx=5, pady=5, sticky=('N', 'W', 'E', 'S'), columnspan=1)
self._tk_var_obj[4][5].set('$ {0:.2f}'.format(self.parent.selection_grid['target_notional']))
self._tk_grid_obj[4][5] = tk.Message(
self.gui_root, width=self._column_width[5],
textvariable=self._tk_var_obj[4][5], font=font_collection['body1'], justify='right'
)
self._tk_grid_obj[4][5].grid(row=4, column=5, padx=5, pady=5, sticky=('N', 'W', 'E', 'S'), columnspan=1)
# ============================================== ROW 5 ============================================= #
self._tk_grid_obj[5][0] = tk.Message(
self.gui_root, width=self._column_width[0],
text=self._tk_var_obj[5][0], font=font_collection['header1'], relief='ridge'
)
self._tk_grid_obj[5][0].grid(row=5, column=0, padx=5, sticky=('N', 'W', 'E', 'S'), columnspan=1)
self._tk_grid_obj[5][1] = tk.Message(
self.gui_root, width=self._column_width[1],
text=self._tk_var_obj[5][1], font=font_collection['header1'], relief='ridge'
)
self._tk_grid_obj[5][1].grid(row=5, column=1, padx=5, sticky=('N', 'W', 'E', 'S'), columnspan=1)
self._tk_grid_obj[5][2] = tk.Message(
self.gui_root, width=self._column_width[2],
text=self._tk_var_obj[5][2], font=font_collection['header1'], relief='ridge'
)
self._tk_grid_obj[5][2].grid(row=5, column=2, padx=5, sticky=('N', 'W', 'E', 'S'), columnspan=2)
self._tk_grid_obj[5][4] = tk.Message(
self.gui_root, width=self._column_width[4],
text=self._tk_var_obj[5][4], font=font_collection['header1'], relief='ridge'
)
self._tk_grid_obj[5][4].grid(row=5, column=4, padx=5, sticky=('N', 'W', 'E', 'S'), columnspan=2)
# ============================================== ROW 6 ============================================= #
self._tk_grid_obj[6][0] = tk.Message(
self.gui_root, width=self._column_width[0],
textvariable=self._tk_var_obj[6][0], font=font_collection['header1'], relief='ridge'
)
self._tk_grid_obj[6][0].grid(row=6, column=0, padx=5, sticky=('N', 'W', 'E', 'S'), columnspan=1)
self._tk_grid_obj[6][1] = tk.Message(
self.gui_root, width=self._column_width[1],
textvariable=self._tk_var_obj[6][1], font=font_collection['header1'], relief='ridge'
)
self._tk_grid_obj[6][1].grid(row=6, column=1, padx=5, sticky=('N', 'W', 'E', 'S'), columnspan=1)
self._tk_grid_obj[6][2] = tk.Message(
self.gui_root, width=self._column_width[2],
textvariable=self._tk_var_obj[6][2], font=font_collection['header1'], relief='ridge'
)
self._tk_grid_obj[6][2].grid(row=6, column=2, padx=5, sticky=('N', 'W', 'E', 'S'), columnspan=2)
self._tk_grid_obj[6][4] = tk.Message(
self.gui_root, width=self._column_width[4],
textvariable=self._tk_var_obj[6][4], font=font_collection['header1'], relief='ridge'
)
self._tk_grid_obj[6][4].grid(row=6, column=4, padx=5, sticky=('N', 'W', 'E', 'S'), columnspan=2)
# ============================================== ROW 7 ============================================= #
self._tk_grid_obj[7][0] = tk.Message(
self.gui_root, width=self._column_width[0],
text=self._tk_var_obj[7][0], font=font_collection['header1']
)
self._tk_grid_obj[7][0].grid(row=7, column=0, padx=5, pady=5, sticky=('N', 'W', 'E', 'S'), columnspan=1)
self._tk_grid_obj[7][1] = tk.Message(
self.gui_root, width=self._column_width[1],
textvariable=self._tk_var_obj[7][1], font=font_collection['header1']
)
self._tk_grid_obj[7][1].grid(row=7, column=1, padx=5, pady=5, sticky=('N', 'W', 'E', 'S'), columnspan=1)
self._tk_grid_obj[7][2] = tk.Message(
self.gui_root, width=self._column_width[2],
text=self._tk_var_obj[7][2], font=font_collection['header1']
)
self._tk_grid_obj[7][2].grid(row=7, column=2, padx=5, pady=5, sticky=('N', 'W', 'E', 'S'), columnspan=2)
self._tk_grid_obj[7][4] = tk.Message(
self.gui_root, width=self._column_width[4],
textvariable=self._tk_var_obj[7][4], font=font_collection['header1']
)
self._tk_grid_obj[7][4].grid(row=7, column=4, padx=5, pady=5, sticky=('N', 'W', 'E', 'S'), columnspan=2)
# ============================================== ROW 8 ============================================= #
self._tk_grid_obj[8][0] = tk.Message(
self.gui_root, width=self._column_width[0],
text=self._tk_var_obj[8][0], font=font_collection['header1'], relief='ridge'
)
self._tk_grid_obj[8][0].grid(row=8, column=0, padx=5, sticky=('N', 'W', 'E', 'S'), columnspan=1)
self._tk_grid_obj[8][1] = tk.Message(
self.gui_root, width=self._column_width[1],
text=self._tk_var_obj[8][1], font=font_collection['header1'], relief='ridge'
)
self._tk_grid_obj[8][1].grid(row=8, column=1, padx=5, sticky=('N', 'W', 'E', 'S'), columnspan=1)
self._tk_grid_obj[8][2] = tk.Message(
self.gui_root, width=self._column_width[2],
text=self._tk_var_obj[8][2], font=font_collection['header1'], relief='ridge'
)
self._tk_grid_obj[8][2].grid(row=8, column=2, padx=5, sticky=('N','W','E', 'S'), columnspan=2)
self._tk_grid_obj[8][4] = tk.Message(
self.gui_root, width=self._column_width[4],
text=self._tk_var_obj[8][4], font=font_collection['header1'], relief='ridge'
)
self._tk_grid_obj[8][4].grid(row=8, column=4, padx=5, sticky=('N','W','E','S'), columnspan=4)
# ============================================== ROW 9 ============================================= #
self._tk_grid_obj[9][0] = tk.Message(
self.gui_root, width=self._column_width[0],
textvariable=self._tk_var_obj[9][0], font=font_collection['header1'], relief='ridge'
)
self._tk_grid_obj[9][0].grid(row=9, column=0, padx=5, sticky=('N', 'W', 'E', 'S'), columnspan=1)
self._tk_grid_obj[9][1] = tk.Message(
self.gui_root, width=self._column_width[1],
textvariable=self._tk_var_obj[9][1], font=font_collection['header1'], relief='ridge'
)
self._tk_grid_obj[9][1].grid(row=9, column=1, padx=5, sticky=('N', 'W', 'E', 'S'), columnspan=1)
self._tk_grid_obj[9][2] = tk.Message(
self.gui_root, width=self._column_width[2],
textvariable=self._tk_var_obj[9][2], font=font_collection['header1'], relief='ridge'
)
self._tk_grid_obj[9][2].grid(row=9, column=2, padx=5, sticky=('N', 'W', 'E', 'S'), columnspan=2)
self._tk_grid_obj[9][4] = tk.Message(
self.gui_root, width=self._column_width[4],
textvariable=self._tk_var_obj[9][4], font=font_collection['header1'], relief='ridge'
)
self._tk_grid_obj[9][4].grid(row=9, column=4, padx=5, sticky=('N', 'W', 'E', 'S'), columnspan=2)
# ========================================== Button Commands ========================================== #
def __button_stop_main(self):
self.outbound_q.put((self.__name, 'master', 'stop_all', None))
def __button_set_notional(self):
try:
selected_notional = self._tk_var_obj[4][1].get()
if selected_notional > 0:
self.parent.master_thread.update_thread_selection('target_notional', selected_notional)
self._tk_var_obj[4][5].set('$ {0:.2f}'.format(selected_notional))
else:
self._tk_var_obj[4][1].set(0.0)
except Exception as e:
print(self.__name + ' thread - Exception! Notional Entry is not float type!')
self._tk_var_obj[4][1].set(0.0)
# ========================================== Trace Callback commands========================================== #
def __trace_option_menu_change_r3_c1(self, *args):
selected_coin = self._tk_var_obj[3][1].get()
self.parent.master_thread.update_thread_selection('target_coin', selected_coin)
# ========================================== External facing commands========================================== #
def update_status_grid(self):
for name in self.parent.status_grid:
if name in self.status_map:
position = self.status_map[name]
status = self.parent.status_grid[name]
self._tk_var_obj[position[0]][position[1]].set(self.parent.status_grid[name])
if status in ['Active', 'Online']:
self._tk_grid_obj[position[0]][position[1]].config(background='lime green')
elif status in ['Inactive', 'Offline']:
self._tk_grid_obj[position[0]][position[1]].config(background='red2')
else:
print(self.__name + ' thread - Warning! No tkinter grid variable for status: "' + str(name) + '".')
def update_data_grid(self):
# for item in self.parent.data_grid:
for item in self.parent.data_grid:
if item in self.data_map:
position = self.data_map[item]
if item in self.data_format_map:
if item in self.data_logic_map:
if self.data_logic_map[item](position[0], position[1]):
self._tk_var_obj[position[0]][position[1]].set(
self.data_format_map[item].format(self.parent.data_grid[item]))
else:
self._tk_var_obj[position[0]][position[1]].set(
self.data_format_map[item].format(self.parent.data_grid[item]))
else:
self._tk_var_obj[position[0]][position[1]].set(self.parent.data_grid[item])
# else:
# print(self.__name + ' thread - Warning! No tkinter grid variable for data object: "' + str(item) + '".')
# ========================================== Internal facing commands========================================== #
def __check_if_multi_fiat_active(self, x_pos, y_pos):
if self.parent.selection_grid['target_coin_multi_fiat'] == True:
return True
else:
self._tk_var_obj[x_pos][y_pos].set('Not Available')
|
PHP
|
UTF-8
| 1,348
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddUnderlyingDisease extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('patient', function(Blueprint $table)
{
$table->boolean('ards');
$table->boolean('arf');
$table->boolean('hap');
$table->boolean('vap');
$table->boolean('pneumonia');
$table->boolean('sepsis');
$table->boolean('decubitus');
$table->boolean('metabolic');
$table->boolean('hiv');
$table->boolean('neuromuscular');
$table->boolean('circulatory');
$table->boolean('liver');
$table->boolean('injury');
$table->boolean('morbidity');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('patient', function(Blueprint $table)
{
$table->dropColumn('ards');
$table->dropColumn('arf');
$table->dropColumn('hap');
$table->dropColumn('vap');
$table->dropColumn('pneumonia');
$table->dropColumn('sepsis');
$table->dropColumn('decubitus');
$table->dropColumn('metabolic');
$table->dropColumn('hiv');
$table->dropColumn('neuromuscular');
$table->dropColumn('circulatory');
$table->dropColumn('liver');
$table->dropColumn('injury');
$table->dropColumn('morbidity');
});
}
}
|
C#
|
UTF-8
| 2,913
| 2.78125
| 3
|
[] |
no_license
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WeaponModel {
public int Id { get; set; }//武器编号
public string Name { get; set; }//武器名字
public WeaponType Type { get; set; }//武器类型
public string Description { get; set; }
public int Atk { get; set; }//武器攻击力加成
public int Def { get; set; }//防御力加成
public int AtkRadius { get; set; }//攻击距离半径
public int AtkSpeed { get; set; }//攻击速度加成
public int MoveSpeed { get; set; }//移动速度加成
public int SkillId { get; set; }//附加技能
public float CoolingTime { get; set; } //冷却时间
public int BuyPrice { get; set; }//买入价格
public int SellPrice { get; set; }//卖出价格
public string SpritePath { get; set; } //图片存储位置
public enum WeaponType
{
MainHand = 0, //主手武器
OffHand = 1, //副手武器
Head = 2,//头戴的
Foot = 3,//鞋
}
///// <summary>
///// 构造函数
///// </summary>
///// <param name="id"></param>
///// <param name="name"></param>
///// <param name="atk"></param>
///// <param name="atkradius"></param>
///// <param name="atkspeed"></param>
///// <param name="skill"></param>
//public WeaponModel(int id, string name,int atk,int atkradius,int atkspeed,List<SkillModel> skill) {
// this.Id = id;
// this.Name = name;
// this.Atk = atk;
// this.AtkRadius = atkradius;
// this.AtkSpeed = atkspeed;
// this.Skill = skill;
//}
//得到显示面板应该显示的内容
public string GetToolTipText()
{
SkillModel skill = InventoryManager.Instance.GetSkillById(SkillId);
string skillText = string.Format("<size=16><color=red>武器附加技能:{0}</color></size>\n技能冷却:{4}\n技能范围:{1}\n技能消耗:{2}\n<color=yellow>技能描述:{3}</color>",skill.Name,skill.Range,skill.UseMp,skill.Description,CoolingTime);
string color = "";
switch (Type)
{
case WeaponType.MainHand:
color = "red";
break;
case WeaponType.OffHand:
color = "blue";
break;
case WeaponType.Foot:
color = "green";
break;
case WeaponType.Head:
color = "yellow";
break;
}
string weaponText = string.Format("<size=16>{0}</size>\n<color={7}>{1}</color>\n攻击力:{2}\n攻击范围:{3}\n攻击速度:{4}\n移动速度:{9}\n<color=yellow>描述:{8}</color>\n<color=green>购买价格:{5} 出售价格:{6}</color>",Name,Type.ToString(),Atk,AtkRadius,AtkSpeed,BuyPrice,SellPrice,color,Description,MoveSpeed);
return weaponText+"\n"+skillText;
}
}
|
Rust
|
UTF-8
| 559
| 2.8125
| 3
|
[] |
no_license
|
extern crate num;
use self::num::bigint::{ToBigInt, BigInt};
use self::num::One;
fn dig_sum(n: BigInt) -> u64 {
n.to_string().into_bytes().iter().fold(0, |acc, &x| acc + (x - 48) as u64)
}
pub fn go() -> String {
let mut max = 0u64;
for a in 95..100 {
let mut q = BigInt::one();
let p = a.to_bigint().unwrap();
for _ in 1..100 {
q = q * &p;
let t: u64 = dig_sum(q.clone());
if t > max {
max = t;
}
}
}
max.to_string()
}
problem!(go, 972);
|
Java
|
UTF-8
| 1,637
| 2.40625
| 2
|
[] |
no_license
|
package com.res.sqlite;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import static android.database.sqlite.SQLiteDatabase.CursorFactory;
/**
* Class Descriptions.
* User: Riemannh
* Date: 13-1-5
* Time: 上午6:55
* version:[]
*/
public class SQLiteHelper extends SQLiteOpenHelper {
public SQLiteHelper(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
Log.v("SQLiteHelper onCreate", "Creating all the tables");
try {
sqLiteDatabase.execSQL(SQLConstant.CREATE_TABLE_DISH_INFO);
sqLiteDatabase.execSQL(SQLConstant.CREATE_TABLE_DISH_TYPE);
sqLiteDatabase.execSQL(SQLConstant.CREATE_TABLE_TABLE_INFO);
} catch (SQLException e) {
Log.v("Create table exeception ", e.getMessage());
}
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
String updateLog = "Upgrading from version " + oldVersion + " to " + newVersion + " , which will destory all old data";
Log.w("TaskDBAdapter", updateLog);
sqLiteDatabase.execSQL(SQLConstant.DROP_TABLE_DISH_INFO);
sqLiteDatabase.execSQL(SQLConstant.DROP_TABLE_DISH_TYPE);
sqLiteDatabase.execSQL(SQLConstant.DROP_TABLE_TABLE_INFO);
onCreate(sqLiteDatabase);
}
}
|
Python
|
UTF-8
| 46,255
| 3
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
# ==============================================================================
# implementations.py
# ------------------------------------------------------------------------------
# authors: Patrick Ley, Joel Fischer
# date: 10.10.2018
# ==============================================================================
# This code collection contains the functions required for the submission of
# ptoject 1 of the 2018 machine learning course at EPFL as well as some other
# utility functions used to complete the task at hand.
# The functions required for the submission can be found in the first section
# "Required Functions".
# ==============================================================================
# -Required Functions
# -> least_squares_GD(y, tx, initial_w, max_iters, gamma)
# -> least_squares_SGD(y, tx, initial_w, max_iters, gamma)
# -> least_squares(y, tx)
# -> ridge_regression(y, tx, lambda_)
# -> logistic_regression(y, tx, initial_w, max_iters, gamma)
# -> reg_logistic_regression(y, tx, lambda_ ,initial_w, max_iters, gamma)
# -Trainers
# -> my_least_squares_GD(y, tx, initial_w, max_iters=1000, gamma=0.2, lambda_=0, eps=1e-5)
# -> my_least_squares_SGD(y, tx, initial_w, max_iters=1000, gamma=0.2, batch_size=1, lambda_=0, eps=1e-1)
# -> my_least_squares(y, tx, lambda_=0)
# -> my_ridge_regression(y, tx, lambda_, mode = "ls", max_iters=100, gamma=0.2, batch_size=1, eps=1e-5)
# -> my_logistic_regression(y, tx, initial_w, max_iters=100, gamma=0.2, mode="log", lambda_=0, eps=1e-5)
# -> my_reg_logistic_regression(y, tx, lambda_ ,initial_w, max_iters=100, gamma=0.2, mode="log", eps=1e-5)
# -> my_stoch_logistic_regression(y, tx, initial_w, max_iters=100, gamma=0.2, batch_size=4, mode="log", lambda_=0, eps=1e-5)
# -Utility functions for trainers
# -> compute_gradient(y, tx, w, mode="mse", lambda_=0)
# -> compute_sigma(tx,w,lim=100.0)
# -> batch_iter(y, tx, batch_size=1, num_batches=1, shuffle=True, seed=1)
# -Loss functions
# -> compute_loss(y, tx, w, mode="mse", lambda_=0)
# -Preprocessing
# -> standardize(tx,mean_=0,std_=1)
# -> split_data(y, tx, ratio, seed=1)
# -> eq_split_data(y, tx, nparts, shuffle=True, seed=1)
# -> add_constant(x)
# -> poly_expansion(x, degree, add_constant=True, mix_features=False)
# -Utility
# -> generate_data(nsamples,nfeatures,seed=1,std)
# -> generate_bin_data(nsamples,nfeatures,seed=1,std=0.1)
# -> column_array(y)
# -> compute_y(tx,w)
# -> nCr(n,k)
# ==============================================================================
# TODO:
# - nobody ain't got time for that!
# ==============================================================================
import numpy as np
# ==============================================================================
# Required Functions
# ==============================================================================
# This section contains the training functions required for the submission
# without optional arguments thus acts as an interface between the actual
# implementations and the automated test programm.
# The training functions are used to compute the optimal weights for a given
# model from a training dataset.
# For the respective source code, see the functions in the section "Trainers"
# (same names but with prefix "my_").
# ------------------------------------------------------------------------------
def least_squares_GD(y, tx, initial_w, max_iters, gamma):
"""
----------------------------------------------------------------------------
Iteratively compute the model weights "w" from "y" and "tx" using the
gradient descent algorithm starting at "initial_w" with a maximum of
"max_iters" steps and step size "gamma".
The function also returns the loss computed as the mean square error (mse).
----------------------------------------------------------------------------
Input:
- y "measured" objective function, (nsamples,1) np.array
- tx features, (nsamples,nfeatures) np.array
- initial_w initial guess of model weights, (nfeatures,1) np.array
- max_iters # of iterations after which the procedure will stop, int>0
- gamma step size, scalar in ]0,1[
Output:
- w obtained weights, (nfeatures,1) np.array
- loss loss computed as the mean square error, scalar
----------------------------------------------------------------------------
"""
return my_least_squares_GD(y, tx, initial_w, max_iters, gamma)
# ------------------------------------------------------------------------------
def least_squares_SGD(y, tx, initial_w, max_iters, gamma):
"""
----------------------------------------------------------------------------
Iteratively compute the model parameters "w" from "y" and "tx" using the
stochastic gradient descent algorithm starting at "initial_w" with a
maximum of "max_iters" steps and step size "gamma".
The function also returns the loss computed as the mean square error.
----------------------------------------------------------------------------
Input:
- y "measured" objective function, (nsamples,1) np.array
- tx features, (nsamples,nfeatures) np.array
- initial_w initial guess of model weights, (nfeatures,1) np.array
- max_iters # of iterations after which the procedure will stop, int>0
- gamma step size, scalar in ]0,1[
Output:
- w obtained weights, (nfeatures,1) np.array
- loss loss computed as the mean square error, scalar
----------------------------------------------------------------------------
"""
return my_least_squares_SGD(y, tx, initial_w, max_iters, gamma)
# ------------------------------------------------------------------------------
def least_squares(y, tx):
"""
----------------------------------------------------------------------------
Compute the model weights "w" from "y" and "tx" using the
normal equations.
The function also returns the loss computed as the mean square error (mse).
----------------------------------------------------------------------------
Input:
- y "measured" objective function, (nsamples,1) np.array
- tx features, (nsamples,nfeatures) np.array
Output:
- w obtained weights, (nfeatures,1) np.array
- loss loss computed as the mean square error, scalar
----------------------------------------------------------------------------
"""
return my_least_squares(y, tx)
# ------------------------------------------------------------------------------
def ridge_regression(y, tx, lambda_):
"""
----------------------------------------------------------------------------
Compute the model weights "w" from "y" and "tx" using the
normal equations with reagularization parameter "lambda_".
The function also returns the loss computed as the mean square error (mse).
----------------------------------------------------------------------------
Input:
- y "measured" objective function, (nsamples,1) np.array
- tx features, (nsamples,nfeatures) np.array
- lambda_ regularization parameter, scalar>0
Output:
- w obtained weights, (nfeatures,1) np.array
- loss loss computed as the mean square error, scalar
----------------------------------------------------------------------------
"""
return my_ridge_regression(y, tx, lambda_)
# ------------------------------------------------------------------------------
def logistic_regression(y, tx, initial_w, max_iters, gamma):
"""
----------------------------------------------------------------------------
Iteratively computes the model weights "w" from "y" and "tx" using
logistic regression with an optional reagularization parameter "lambda_"
in up "max_iters" iterations.
The function also returns the loss computed according to the logistic
regression loss function.
----------------------------------------------------------------------------
Input:
- y "measured" objective function, (nsamples,1) np.array
- tx features, (nsamples,nfeatures) np.array
- initial_w initial guess of model weights, (nfeatures,1) np.array
- max_iters # of iterations after which the procedure will stop, int>0
- gamma step size, scalar in ]0,1[
Output:
- w obtained weights, (nfeatures,1) np.array
- loss loss computed as the mean square error, scalar
----------------------------------------------------------------------------
"""
return my_logistic_regression(y, tx, initial_w, max_iters, gamma)
# ------------------------------------------------------------------------------
def reg_logistic_regression(y, tx, lambda_ ,initial_w, max_iters, gamma):
"""
----------------------------------------------------------------------------
Iteratively computes the model weights "w" from "y" and "tx" using
regularized logistic regression with reagularization parameter "lambda_"
in up "max_iters" iterations.
The function also returns the loss computed according to the logistic
regression loss function.
----------------------------------------------------------------------------
Input:
- y "measured" objective function, (nsamples,1) np.array
- tx features, (nsamples,nfeatures) np.array
- lambda_ regularization parameter, scalar>0
- initial_w initial guess of model weights, (nfeatures,1) np.array
- max_iters # of iterations after which the procedure will stop, int>0
- gamma step size, scalar in ]0,1[
Output:
- w obtained weights, (nfeatures,1) np.array
- loss loss computed as the mean square error, scalar
----------------------------------------------------------------------------
"""
return my_reg_logistic_regression(y, tx, lambda_ ,initial_w, max_iters, gamma)
# ==============================================================================
# Trainers
# ==============================================================================
# This section contains the training functions required for the submission with
# optional arguments.
# The training functions are used to compute the optimal weights for a given
# model from a training dataset.
# ------------------------------------------------------------------------------
def my_least_squares_GD(y, tx, initial_w, max_iters=100, gamma=0.2, lambda_=0, eps=1e-3):
"""
----------------------------------------------------------------------------
Iteratively compute the model weights "w" from "y" and "tx" using the
gradient descent algorithm starting at "initial_w" with a maximum of
"max_iters" steps and step size "gamma".
The function also returns the loss computed as the mean square error (mse).
----------------------------------------------------------------------------
Input:
- y "measured" objective function, (nsamples,1) np.array
- tx features, (nsamples,nfeatures) np.array
- initial_w initial guess of model weights, (nfeatures,1) np.array
- max_iters # of iterations after which the procedure will stop, int>0
(default=100)
- gamma step size, scalar in ]0,1[ (default=0.5)
- lambda_ regularization parameter, scalar>0 (default = 0)
- eps end condition, scalar>0 (default=1e-5)
Output:
- w obtained weights, (nfeatures,1) np.array
- loss loss computed as the mean square error, scalar
----------------------------------------------------------------------------
"""
y = column_array(y)
nsamples = tx.shape[0]
nfeatures = tx.shape[1]
w = initial_w
err = 1
for n_iter in range(max_iters):
grad = compute_gradient(y, tx, w,"mse",lambda_)
w = w -gamma*grad
if ((n_iter+1)%10 == 0):
err = np.sum(np.abs(grad))/nfeatures
if err < eps :
print("Terminated least_squares_GD after ",n_iter," iterations.")
break
loss = compute_loss(y,tx,w)
return w, loss
# ------------------------------------------------------------------------------
def my_least_squares_SGD(y, tx, initial_w, max_iters=1000, gamma=0.2, batch_size=10, lambda_=0, eps=1e-1):
"""
----------------------------------------------------------------------------
Iteratively compute the model parameters "w" from "y" and "tx" using the
stochastic gradient descent algorithm starting at "initial_w" with a
maximum of "max_iters" steps and step size "gamma" and sample size batch_size.
The function also returns the loss computed as the mean square error.
----------------------------------------------------------------------------
Input:
- y "measured" objective function, (nsamples,1) np.array
- tx features, (nsamples,nfeatures) np.array
- initial_w initial guess of model weights, (nfeatures,1) np.array
- batch_size size of the subsamples, positive integer (default=4)
( setting to 0 or >=nsamples will result in using standard sg)
- max_iters # of iterations after which the procedure will stop, int>0
(default=1000)
- gamma step size, scalar in ]0,1[ (default=0.5)
- lambda_ regularization parameter, scalar>0 (default = 0)
- eps end condition, scalar>0 (default=1e-1)
Output:
- w obtained weights, (nfeatures,1) np.array
- loss loss computed as the mean square error, scalar
----------------------------------------------------------------------------
"""
y = column_array(y)
nsamples = tx.shape[0]
nfeatures = tx.shape[1]
if ( batch_size==0 ) | ( batch_size>=nsamples ):
w, loss = my_least_squares_GD(y, tx, initial_w, max_iters, gamma, lambda_,eps)
else:
w = initial_w
batches = batch_iter(y, tx, batch_size, max_iters)
err = 0
nerr = min(max((nsamples/50),20),100)
n_iter = 0
for batch in batches:
yb = batch[0]
txb = batch[1]
grad = compute_gradient(yb, txb, w)
err = err + np.sum(np.abs(grad))
w = w -gamma*grad
if ((n_iter+1)%nerr == 0):
if err/(nerr*batch_size*nfeatures) < eps:
print("Terminated least_squares_SGD after ",n_iter," iterations.")
break
err = 0
n_iter = n_iter+1
loss = compute_loss(y,tx,w)
return w, loss
# ------------------------------------------------------------------------------
def my_least_squares(y, tx, lambda_=0):
"""
----------------------------------------------------------------------------
Compute the model weights "w" from "y" and "tx" using the
normal equations.
The function also returns the loss computed as the mean square error (mse).
----------------------------------------------------------------------------
Input:
- y "measured" objective function, (nsamples,1) np.array
- tx features, (nsamples,nfeatures) np.array
- lambda_ regularization parameter, scalar>0 (default = 0)
Output:
- w obtained weights, (nfeatures,1) np.array
- loss loss computed as the mean square error, scalar
----------------------------------------------------------------------------
"""
if lambda_ == 0:
a = 0
else:
a = 2*tx.shape[0]*lambda_*np.eye(tx.shape[1])
y = column_array(y)
w = tx.transpose().dot(tx) + a
w = np.linalg.inv(w)
w = w.dot(tx.transpose().dot(y))
loss = compute_loss(y, tx, w)
return w, loss
# ------------------------------------------------------------------------------
def my_ridge_regression(y, tx, lambda_, mode = "ls", max_iters=1000, gamma=0.2, batch_size=4, eps=1e-3):
"""
----------------------------------------------------------------------------
Compute the model weights "w" from "y" and "tx" using the
normal equations with reagularization parameter "lambda_".
The function also returns the loss computed as the mean square error (mse).
----------------------------------------------------------------------------
Input:
- y "measured" objective function, (nsamples,1) np.array
- tx features, (nsamples,nfeatures) np.array
- lambda_ regularization parameter, scalar>0
- mode choice of algorithm (0/"ls",1/"gd",2/"sgd"), string/integer
(default "ls")
- max_iters # of iterations after which the procedure will stop, int>0
(default=100)
- gamma step size, scalar in ]0,1[ (default=0.5)
- batch_size size of the subsamples, positive integer (default=4)
( setting to 0 or >=nsamples will result in using standard sg)
- eps end condition, scalar>0 (default=1e-5)
Output:
- w obtained weights, (nfeatures,1) np.array
- loss loss computed as the mean square error, scalar
----------------------------------------------------------------------------
"""
if( mode=="gd" ) | ( mode==1 ): # gradient_descent
w, loss = my_least_squares_GD(y, tx, initial_w, max_iters, gamma, lambda_,eps)
elif ( mode=="sgd" ) | ( mode==2 ): # stochastic_gradient_descent
eps = 1e-1
w, loss = my_least_squares_SGD(y,tx,initial_w,max_iters,gamma,batch_size,lambda_,eps)
else: # least_squares
w, loss = my_least_squares(y, tx, lambda_)
return w, loss
# ------------------------------------------------------------------------------
def my_logistic_regression(y, tx, initial_w, max_iters=100, gamma=0.2, mode="log", lambda_=0, eps=1e-3):
"""
----------------------------------------------------------------------------
Iteratively computes the model weights "w" from "y" and "tx" using
logistic regression with an optional reagularization parameter "lambda_"
in up "max_iters" iterations.
The function also returns the loss computed according to the logistic
regression loss function.
----------------------------------------------------------------------------
Input:
- y "measured" objective function, (nsamples,1) np.array
- tx features, (nsamples,nfeatures) np.array
- initial_w initial guess of model weights, (nfeatures,1) np.array
- max_iters # of iterations after which the procedure will stop,
int>0 (default=100)
- gamma step size, scalar in ]0,1[ (default=0.5)
- mode choice of algorithm (1/"log",2/"newton"), string/integer
(default=1/"log")
- lambda_ regularization parameter, scalar>0
- eps end condition, scalar>0 (default=1e-5)
Output:
- w obtained weights, (nfeatures,1) np.array
- loss loss computed as the mean square error, scalar
----------------------------------------------------------------------------
"""
if (mode != "newton") & (mode != 2 ):
mode = "log"
y = column_array(y)
w = initial_w
nfeatures = tx.shape[1]
for n_iter in range(max_iters):
grad = compute_gradient(y, tx, w, mode, lambda_)
w = w -gamma*grad
if ((n_iter+1)%10 == 0):
err = np.sum(np.abs(grad))
if err/nfeatures < eps:
break
loss = compute_loss(y,tx,w,"log")
return w, loss
# ------------------------------------------------------------------------------
def my_stoch_logistic_regression(y, tx, initial_w, max_iters=100, gamma=0.2, batch_size=4, mode="log", lambda_=0, eps=1e-1):
"""
----------------------------------------------------------------------------
Iteratively computes the model weights "w" from "y" and "tx" using stochastic
logistic regression with an optional reagularization parameter "lambda_"
in up "max_iters" iterations.
The function also returns the loss computed according to the logistic
regression loss function.
----------------------------------------------------------------------------
Input:
- y "measured" objective function, (nsamples,1) np.array
- tx features, (nsamples,nfeatures) np.array
- initial_w initial guess of model weights, (nfeatures,1) np.array
- max_iters # of iterations after which the procedure will stop,
int>0 (default=100)
- gamma step size, scalar in ]0,1[ (default=0.5)
- batch_size size of the subsamples, positive integer (default=4)
( setting to 0 or >nsamples will result in using standard sg)
- mode choice of algorithm (1/"log",2/"newton"), string/integer
(default=1/"log")
- lambda_ regularization parameter, scalar>0
- eps end condition, scalar>0 (default=1e-5)
Output:
- w obtained weights, (nfeatures,1) np.array
- loss loss computed as the mean square error, scalar
----------------------------------------------------------------------------
"""
if (mode != "newton") & (mode != 2 ):
mode = "log"
y = column_array(y)
w = initial_w
nsamples = tx.shape[0]
nfeatures = tx.shape[1]
if ( batch_size==0 ) | ( batch_size>=nsamples ):
w, loss = my_logistic_regression(y, tx, initial_w, max_iters, gamma, mode, lambda_, eps)
else:
w = initial_w
batches = batch_iter(y, tx, batch_size, max_iters)
err = 0
nerr = min(max((nsamples/50),20),100)
n_iter = 0
for batch in batches:
grad = compute_gradient(y, tx, w, mode, lambda_)
w = w -gamma*grad
err = err + np.sum(np.abs(grad))
if ((n_iter+1)%nerr == 0):
if err/(nerr*batch_size*nfeatures) < eps:
break
err = 0
if( np.abs(w).any()>1e+20):
break
n_iter = n_iter+1
loss = compute_loss(y,tx,w,"log")
return w, loss
# ------------------------------------------------------------------------------
def my_reg_logistic_regression(y, tx, lambda_ ,initial_w, max_iters=100, gamma=0.2, mode="log", eps=1e-5):
"""
----------------------------------------------------------------------------
Iteratively computes the model weights "w" from "y" and "tx" using
regularized logistic regression with reagularization parameter "lambda_"
in up "max_iters" iterations.
The function also returns the loss computed according to the logistic
regression loss function.
----------------------------------------------------------------------------
Input:
- y "measured" objective function, (nsamples,1) np.array
- tx features, (nsamples,nfeatures) np.array
- lambda_ regularization parameter, scalar>0
- initial_w initial guess of model weights, (nfeatures,1) np.array
- max_iters # of iterations after which the procedure will stop,
int>0 (default=100)
- gamma step size, scalar in ]0,1[ (default=0.5)
- mode choice of algorithm (1/"log",2/"newton"), string/integer
(default=1/"log")
- eps end condition, scalar>0 (default=1e-5)
Output:
- w obtained weights, (nfeatures,1) np.array
- loss loss computed as the mean square error, scalar
----------------------------------------------------------------------------
"""
w, loss = my_logistic_regression(y,tx,initial_w,max_iters,gamma,mode,lambda_,eps)
return w, loss
# ==============================================================================
# Utility functions for trainers
# ==============================================================================
# Accesory function required for the different training functions.
# ------------------------------------------------------------------------------
def compute_gradient(y, tx, w, mode="mse", lambda_=0):
"""
----------------------------------------------------------------------------
Compute the gradient of the mean square error loss function evaluated at
(y,tx,w) with respect to the weights "w" with or without taking into account
the regularization parameter "lambda_".
Optionally this function can also be used to compute the gradient with
respect to the loss function used for logistic regression or even to compute
one step of the second order logistic regression algorithm (Newton method).
----------------------------------------------------------------------------
Input:
- y "measured" objective function, (nsamples,1) np.array
- tx features, (nsamples,nfeatures) np.array
- w current weights, (nfeatures,1) np.array
- mode choice of regression type for which the gradient is used
(0/"mse",1/"log",2/"newton"), int/string (default=0/"mse")
- lambda_ regularization parameter, scalar>0 (default = 0)
Output:
- grad gradient, (tx.shape[0],1) np.array
----------------------------------------------------------------------------
MSE Gradient: L(w) = (y-x*w)^2/(2*N) + lambda_*w^2
grad = -(y-x*w)^t*x/N + 2*lambda_*w
= -(y-x*w-N*lambda_/2)^t*w
Log Gradient: L(w) = lambda_/2*w^2 + sum_n^N ln[1+exp(x_n*w)]-y_n*x_n*w
grad = lambda_*w + x^t*[sigma(x*w)-y]
Newton (Log): H = x^t*S*x, S_nn = sigma(x_n*w)*[1-sigma(x_n^t*w)]
grad2= H^-1*grad
----------------------------------------------------------------------------
"""
if (lambda_ == 0 ):
a = 0
else:
a = lambda_*w
if (( mode=="log" ) | ( mode=="1" )) | (( mode=="newton" ) | ( mode=="2" )):
sigma = compute_sigma(tx,w)
grad = sigma-y
grad = tx.transpose().dot(grad)+a
if ( mode=="newton" ) | ( mode=="2" ):
S = sigma*(1-sigma)
H = tx.transpose().dot(tx*S)
grad = np.linalg.inv(H).dot(grad)
else:
grad = -tx.transpose().dot(y-tx.dot(w))/tx.shape[0] + 2*a
return grad
# ------------------------------------------------------------------------------
def compute_sigma(tx,w,lim=100.0):
"""
----------------------------------------------------------------------------
Computes sigma=exp(tx*w)/(1+exp(tx*w)) as needed for logistic regression.
----------------------------------------------------------------------------
Input:
- tx features, (nsamples,nfeatures) np.array
- w current weights, (nfeatures,1) np.array
- lim limit of the exponent after which sigma isn't computed
explicitly anymore (instead it will be simply set to 0 or 1)
, scalar>0 (default=100.0)
Output:
- sigma sigma=exp(tx*w)/(1+exp(tx*w)), (tx.shape[0],1) np.array
----------------------------------------------------------------------------
"""
x = tx.dot(w)
large = x>lim
small = x<-lim
neither = np.logical_not(large)*np.logical_not(small)
x[neither] = np.exp(x[neither])
sigma = np.divide(x,1+x)
sigma[large] = 1
sigma[small] = 0
return sigma
# ------------------------------------------------------------------------------
def batch_iter(y, tx, batch_size=1, num_batches=1, shuffle=True, seed=1):
"""
----------------------------------------------------------------------------
Generate a minibatch iterator for a dataset.
Takes as input two iterables (here the output desired values 'y' and the
input data 'tx') and outputs an iterator which gives mini-batches of
`batch_size` matching elements from `y` and `tx`.
Data can be randomly shuffled to avoid ordering in the original data messing
with the randomness of the minibatches.
Example of use :
for minibatch_y, minibatch_tx in batch_iter(y, tx, 32):
<DO-SOMETHING>
Note: this implementation was provided by the teachers/TAs and has since
been slightly modified to allow for more iterations. However iterations that
exceed the batch_num*batch_size>data_size will reuse the same batches (i.e
without additional shuffeling).
----------------------------------------------------------------------------
Input:
- y "measured" objective function, (nsamples,1) np.array
- tx features, (nsamples,nfeatures) np.array
- batch_size subsample size, integer>0 (default=1)
- num_batches number of batches, integer>0 (default=1)
- shuffle random order if True, retains order otherwise, boolean
- seed seed for np.random, integer
Output:
- batches subsamples,
generator num_batches*[(batch_size,1),(batch_size,nfeatures)]
----------------------------------------------------------------------------
"""
nsamples = tx.shape[0]
if shuffle:
np.random.seed(seed)
shuffle_indices = np.random.permutation(np.arange(nsamples))
shuffled_y = y[shuffle_indices]
shuffled_tx = tx[shuffle_indices]
else:
shuffled_y = y
shuffled_tx = tx
for batch_num in range(num_batches):
start_index = (batch_num*batch_size)%nsamples
end_index = min(start_index+batch_size, nsamples)
if start_index != end_index:
yield shuffled_y[start_index:end_index], shuffled_tx[start_index:end_index]
# ==============================================================================
# Loss functions
# ==============================================================================
# Functions used to compute the loss of between the prediction created by a
# model and the actual "measurements"/reality.
# ------------------------------------------------------------------------------
def compute_loss(y, tx, w, mode="mse", lambda_=0):
"""
----------------------------------------------------------------------------
Computes the loss according to the specified loss function. The available
loss functions are mean square error (mse), root mean square error (rmse),
mean absolute error (mae) and the loss function used for logistic regression
(log). Furthermore the regularization parameter "lambda_" can be taken
account of if desired.
----------------------------------------------------------------------------
Input:
- y "measured" objective function, (nsamples,1) np.array
- tx features, (nsamples,nfeatures) np.array
- mode choice of loss function (0/"mse",1/"rmse",2/"msa",3/"log"),
string/integer (default = 0/"mse")
- lambda_ regularization parameter, scalar>0, (default=0)
Output:
- loss loss computed using the loss function of choice, scalar
----------------------------------------------------------------------------
"""
y = column_array(y)
# compute error
if (mode == "msa") | (mode == 2):
e = y-tx.dot(w)
e = np.absolute(e).sum()/e.shape[0]/2
elif (mode == "log") | (mode == 3):
e = compute_y(tx,w)
e = np.abs(y - e)/(2*len(e))
# e = tx.dot(w)
#
# lim = 100.0
# large = e>lim
# small = e<-lim
# neither = np.logical_not(large)*np.logical_not(small)
#
# x = e
# x[neither] = np.log(1+np.exp(e[neither]))
# x[large] = e[large]
# x[small] = 0
#
# e = (x - y*e)/(2*len(e))
else: # mse or rmse loss
e = y-tx.dot(w)
e = (np.transpose(e).dot(e)/(2*e.shape[0]))
if (mode == "rmse") | (mode == 1):
e = np.sqrt(2*e)
loss = np.sum(e)
# compute regularization contribution
if lambda_ == 0:
a = 0
else:
a = lambda_*np.sum(w*w)
return loss + a
# ==============================================================================
# Preprocessing
# ==============================================================================
# Preprocessing functions to prepare data for training and/or prediction.
# ------------------------------------------------------------------------------
def standardize(tx, mean_=0, std_=1):
"""
----------------------------------------------------------------------------
Standardize data (i.e substract mean and divide by standard deviation). If
non-zero mean and non unitary standard deviation are passed as arguments the
passed values will be used instead of the mean value and standrad deviation
of the sample "tx".
----------------------------------------------------------------------------
Input:
- tx features, (nsamples,nfeatures) np.array
- mean_ mean value of features, (1,nfeatures) np.array, (default=0)
- std_ standrad deviation of features, (1,nfeatures) np.array,
(default=1)
Output:
- tx_std features standardized to mean 0 and std 1,
(nsamples,nfeatures) np.array
- mean mean value of features, (1,nfeatures) np.array
- std standrad deviation of features, (1,nfeatures) np.array
----------------------------------------------------------------------------
"""
if (np.sum(mean_==0)) | (np.sum(std_==1)):
# does not work if there is an actual feature with mean 0 or std 1
mean = np.mean(tx,0)
std = np.std(tx,0)
else:
mean = mean_
std = std_
tx_std = np.divide(tx-mean,std)
return tx_std, mean, std
# ------------------------------------------------------------------------------
def split_data(y, tx, ratio, seed=1):
"""
----------------------------------------------------------------------------
Randomly split the dataset "(y,tx)" based on the passed split ratio.
----------------------------------------------------------------------------
Input:
- y "measured" objective function, (nsamples,1) np.array
- tx features, (nsamples,nfeatures) np.array
- ratio split ratio, scalar in [0,1]
- seed seed for np.random, integer
Output:
- y1 "measured" objective function, (nsamples*ratio,1) np.array
- x1 features, (nsamples*ratio,nfeatures) np.array
- y2 "measured" objective function,
(nsamples*(1-ratio),nfeatures) np.array
- x2 features, (nsamples*(1-ratio),nfeatures) np.array
----------------------------------------------------------------------------
"""
np.random.seed(seed)
nsamples = tx.shape[0]
indices = np.indices([nsamples])[0]
np.random.shuffle(indices)
split1 = indices[0:int(np.floor(nsamples*ratio))]
split2 = indices[int(np.floor(nsamples*ratio)):nsamples]
return y[split1],tx[split1,:],y[split2],tx[split2,:]
# ------------------------------------------------------------------------------
def eq_split_data(y, tx, nparts, shuffle=True, seed=1):
"""
----------------------------------------------------------------------------
Randomly split the dataset "(y,tx)" into "nparts" equally sized portions.
----------------------------------------------------------------------------
Input:
- y "measured" objective function, (nsamples,1) np.array
- tx features, (nsamples,nfeatures) np.array
- nparts number of parts, integer>0
- shuffle wheter or not to shuffle the data before splitting, logical
(default=True)
- seed seed for np.random, integer
Output:
- ys "measured" objective function, (nsamples//nparts,1,nparts) np.array
- txs features, (nsamples//nparts,nfeatures,nparts) np.array
- inds indices included in each split, (nsamples//nparts,nparts) int np.array
- boolind indices included in each split, (nsamples,nparts) logical np.array
----------------------------------------------------------------------------
"""
np.random.seed(seed)
y = column_array(y)
nsamples = tx.shape[0]
nfeatures = tx.shape[1]
indices = np.indices([nsamples])[0]
np.random.shuffle(indices)
nspp = nsamples//nparts #number of samples per part
ys = np.zeros([nspp,nparts])
txs = np.zeros([nspp,nfeatures,nparts])
inds = np.zeros([nspp,nparts],"int")
boolind = np.zeros([nsamples,nparts],"bool")
for part in range(nparts):
inds[:,part] = indices[part*nspp:(part+1)*nspp]
ys[:,part] = y[inds[:,part],0]
txs[:,:,part] = tx[inds[:,part]]
boolind[inds[:,part],part] = True
return ys, txs, inds, boolind
# ------------------------------------------------------------------------------
def add_constant(x):
"""
----------------------------------------------------------------------------
Adds a constant feature to the features present in the data array "x".
----------------------------------------------------------------------------
Input:
- x features, (nsamples,nfeatures) np.array
Output:
- tx features, (nsamples,nfeatures+1) np.array
----------------------------------------------------------------------------
"""
tx = np.column_stack((np.ones([x.shape[0],1]),x))
return tx
# ------------------------------------------------------------------------------
# mix_features is WIP
def poly_expansion(x, degree, add_constant=True, mix_features=False):
"""
----------------------------------------------------------------------------
Performs a polynomial feature expansion of "x" up to the degree "degree",
assuming that each column of "x" represents a feature. Note that to avoid
undesired side effects the array "x" should not contain a constant feature
since it would carry over in the expansion.
This function also allows to directly add a constant feature if
desired.
In the future this function will be extended to also allow for feature
mixing (fe) in the polynomial expansion. However caution is adviced since the
size of the expansion will grow as O(nfeatures^degree) instead of
O(nfeatures*degree) if feature mixing is enabled.
----------------------------------------------------------------------------
Input:
- x features, (nsamples,nfeatures) np.array
- degree degree of the polynomial, integer>0
- add_constant if enabled a constant feature will be added, boolean
(default=True)
- mix_features if enabled features will be mixed up to the second degree,
boolean (default=False)
Output:
- tx the polynomial expansion of "x",
(nsamples,nfeatures*degree+add_constant) np.array (w/o fm)
(nsamples,?) np.array (w fm)
----------------------------------------------------------------------------
"""
nfeatures = x.shape[1]
nsamples = x.shape[0]
# if mix_features:
# nftot = nCr(nfeatures+degree,degree)
# tx = np.ones([nsamples,nftot])
#
# for d in range(1,degree):
# for i in range(nfeatures):
# tx(:,1+i*d*(nfeatures):1+(1+i*d)*(nfeatures)) = tx(:,1:1+nfeatures)*x(:,i)
#
# else:
tx = np.ones([nsamples,degree*nfeatures+1])
for n in range(0,nfeatures):
tx[:,n*degree+1] = x[:,n]
for d in range(2,degree+1):
tx[:,n*(degree)+d] = tx[:,n*(degree)+d-1]*x[:,n]
if mix_features:
tx_add = np.zeros([nsamples,int(nfeatures*(nfeatures-1)/2)])
ind = 0
for i in range(nfeatures):
for j in range(i+1,nfeatures):
tx_add[:,ind] = x[:,i]*x[:,j]
ind = ind+1
tx = np.column_stack([tx,tx_add])
if not add_constant:
tx = tx[:,1:]
#TODO : improve this, fix mix_features
return tx
# ==============================================================================
# Utility
# ==============================================================================
# Collection of other functions of use.
# ------------------------------------------------------------------------------
def generate_data(nsamples,nfeatures,seed=1,std=0.1):
"""
----------------------------------------------------------------------------
This procedure generates a random data set following a linear model
with random coefficients. Additionally normal distributed error is then
added to the dataset.
----------------------------------------------------------------------------
Input:
- nsamples number of samples, integer>0
- nfeatures number of features, integer>0
- seed seed for np.random, integer (default=1)
- std standrad deviation of normal distrubted noise, scalar>0,
(default=0.1)
Output:
- y objective function, (nsamples,1) np.array
- x features, (nsamples,nfeatures+1) np.array
- w actual weights, (nfeatures+1,1) np.array
----------------------------------------------------------------------------
"""
np.random.seed(seed)
w = np.random.random([nfeatures+1,1])*2-1
x = np.random.random([nsamples,nfeatures])
tx = np.ones([nsamples,1])
tx = np.column_stack((tx,x))
y = tx.dot(w)
y = y + np.random.normal(0,std,[nsamples,1])
return y, tx, w
# ------------------------------------------------------------------------------
def generate_bin_data(nsamples,nfeatures,seed=1,std=0.1):
"""
----------------------------------------------------------------------------
This procedure generates a random data set following a linear model
with random coefficients and a binary objective function.
----------------------------------------------------------------------------
Input:
- nsamples number of samples, integer>0
- nfeatures number of features, integer>0
- seed seed for np.random, integer (default=1)
- std standrad deviation of normal distrubted noise, scalar>0,
(default=0.1)
Output:
- y binary objective function, (nsamples,1) np.array
- x features, (nsamples,nfeatures+1) np.array
- w actual weights, (nfeatures+1,1) np.array
----------------------------------------------------------------------------
"""
z,x,w = generate_data(nsamples,nfeatures,seed,std)
y = compute_y(z,1)
return y, x, w
# ------------------------------------------------------------------------------
def column_array(y):
"""
----------------------------------------------------------------------------
Reshape y to a (len,1) np.array.
----------------------------------------------------------------------------
Input:
- y y, (nelem,) np.array
Output:
- yr yr, (nelem,1) np.array
----------------------------------------------------------------------------
"""
if len(y.shape) != 2:
nelem = len(y)
yr = np.zeros([nelem,1])
yr[:,0] = y
else:
yr = y
return yr
# ------------------------------------------------------------------------------
def compute_y(tx,w):
"""
----------------------------------------------------------------------------
Convert {0,1} array to {-1,1} array
----------------------------------------------------------------------------
Input:
- tx features, (nsamples,nfeatures) np.array
- w current weights, (nfeatures,1) np.array
Output:
- y predicted objective function, (nelem,1) np.array {-1,1}
----------------------------------------------------------------------------
"""
y = np.where(tx.dot(w)<0,-1,1)
return y
# ------------------------------------------------------------------------------
def nCr(n, k):
"""
----------------------------------------------------------------------------
Compute binomial coefficients.
----------------------------------------------------------------------------
Input:
- n integer > 0
- k integer > 0
Output:
- ncr nCR(n,k)
----------------------------------------------------------------------------
"""
if 0 <= k <= n:
ncr = 1
n_ = n
for i in range(1,k+1):
ncr *= n_/i
n_ = n_-1
else:
ncr = 0
return ncr
# ==============================================================================
# WIP
# ==============================================================================
# Other functions that are still work in progress and not guaranteed to work.
# ------------------------------------------------------------------------------
# def example(arg1, arg2):
# """
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Input:
# - arg1 argument 1, type (default=?)
# - arg2 argument 2, type (default=?)
# Output:
# - rv return value, type
# ----------------------------------------------------------------------------
# """
#
# y = x
#
# return y
|
Java
|
UTF-8
| 1,082
| 2.515625
| 3
|
[] |
no_license
|
package VirtualFileSystem;
import junit.framework.Assert;
import org.junit.Test;
/**
* Created with IntelliJ IDEA.
* User: Serv
* Date: 01.07.13
* Time: 14:27
* To change this template use File | Settings | File Templates.
*/
public class FileTest {
@Test
public void createFile () {
File file= new File ("test.test", FileSystemSingleton.getInstance().ROOT_FOLDER) ;
Assert.assertTrue(file.exist);
File file2= new File ("test.test\\test", FileSystemSingleton.getInstance().ROOT_FOLDER) ;
Assert.assertFalse(file2.exist);
Folder folder = new Folder("fileTest", FileSystemSingleton.getInstance().ROOT_FOLDER);
File file3 = new File("test.test", FileSystemSingleton.getInstance().ROOT_FOLDER);
Assert.assertFalse(file3.exist);
File file4 = new File("test.test", folder);
Assert.assertTrue(file4.exist);
File file5 = new File("C:\\test.test\\test.test", FileSystemSingleton.getInstance().ROOT_FOLDER);
Assert.assertFalse(file5.exist) ;
}
}
|
Java
|
GB18030
| 812
| 3.09375
| 3
|
[] |
no_license
|
package com.xms.javase.day12.p;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class Thread2 {
public static void main(String[] args) throws InterruptedException, ExecutionException {
Test t=new Test();
FutureTask<Integer> ft= new FutureTask<Integer>(t);
Thread t2=new Thread(ft);
t2.start();
//ȡֵ
System.out.println(ft.isDone());
Integer integer = ft.get();
System.out.println(integer);
//ȡֵ߳̽
System.out.println(ft.isDone());
}
}
class Test implements Callable<Integer>{
@Override
public Integer call() throws Exception {
// TODO Auto-generated method stub
return new Random().nextInt(10);
}
}
|
JavaScript
|
UTF-8
| 6,872
| 2.5625
| 3
|
[] |
no_license
|
import React, {useState} from 'react';
const ContactForm = ({ displayContactForm }) => {
const [companyEmail, setCompanyEmail] = useState("");
const [typeOfOrg, setTypeOfOrg] = useState("");
const [orgLocation, setOrgLocation] = useState("");
const [error, setError] = useState({});
const [success, setSuccess] = useState(false);
const handleCancel=() => {
displayContactForm( false )
}
const handleSubmit= (event) => {
event.preventDefault();
let sError ={};
let errorText = {
blank: 'This field is required',
notSelected: 'Please make a selection',
invalid: 'Please enter a valid value',
};
// validate:
if (companyEmail.length === 0) sError.companyEmail = errorText.blank;
if (typeOfOrg.length === 0) sError.typeOfOrg = errorText.blank;
if (orgLocation.length === 0) sError.orgLocation = errorText.notSelected;
setError(sError);
// console.log("orgLocation: ", orgLocation);
if (Object.keys(sError).length === 0) {
setSuccess(true);
setTimeout(function() {
displayContactForm( false );
}, 2500);
}
}
console.log("error: ", error);
return (
<div className="rowFlex rowCenterContent">
<form className="row">
<div className="rowFlex">
<input placeholder="Company email" type="email"
name="companyEmail"
required
error={error.companyEmail}
onChange={(event) => {
setCompanyEmail(event.target.value);
}}
/>
</div>
{error.companyEmail &&
<div className="errorMsg redFont">{error.companyEmail}
</div> }
<div className="rowFlex">
<input placeholder="Type of organization" type="text" name="organizationType"
error={error.typeOfOrg}
onChange={(event) => {
setTypeOfOrg(event.target.value);
}}
/>
</div>
{error.typeOfOrg &&
<div className="errorMsg redFont">{error.typeOfOrg}
</div> }
<div className="rowFlex rowSpaceBetweenContent">
<label >Organization location: </label>
<select name="states" required
error={error.orgLocation}
defaultValue={0}
onChange={(event) => {
setOrgLocation(event.target.value);
}}
>
<option value="0" disabled>Please select</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="CT">Connecticut</option>
<option value="DE">Delaware</option>
<option value="DC">District Of Columbia</option>
<option value="FL">Florida</option>
<option value="GA">Georgia</option>
<option value="HI">Hawaii</option>
<option value="ID">Idaho</option>
<option value="IL">Illinois</option>
<option value="IN">Indiana</option>
<option value="IA">Iowa</option>
<option value="KS">Kansas</option>
<option value="KY">Kentucky</option>
<option value="LA">Louisiana</option>
<option value="ME">Maine</option>
<option value="MD">Maryland</option>
<option value="MA">Massachusetts</option>
<option value="MI">Michigan</option>
<option value="MN">Minnesota</option>
<option value="MS">Mississippi</option>
<option value="MO">Missouri</option>
<option value="MT">Montana</option>
<option value="NE">Nebraska</option>
<option value="NV">Nevada</option>
<option value="NH">New Hampshire</option>
<option value="NJ">New Jersey</option>
<option value="NM">New Mexico</option>
<option value="NY">New York</option>
<option value="NC">North Carolina</option>
<option value="ND">North Dakota</option>
<option value="OH">Ohio</option>
<option value="OK">Oklahoma</option>
<option value="OR">Oregon</option>
<option value="PA">Pennsylvania</option>
<option value="RI">Rhode Island</option>
<option value="SC">South Carolina</option>
<option value="SD">South Dakota</option>
<option value="TN">Tennessee</option>
<option value="TX">Texas</option>
<option value="UT">Utah</option>
<option value="VT">Vermont</option>
<option value="VA">Virginia</option>
<option value="WA">Washington</option>
<option value="WV">West Virginia</option>
<option value="WI">Wisconsin</option>
<option value="WY">Wyoming</option>
</select>
</div>
{error.orgLocation &&
<div className="errorMsg redFont">{error.orgLocation}
</div> }
<div className="rowFlex rowCenterContent">
<button className="demoButton"
onClick={(event) => handleSubmit(event)}
>Request a Demo</button>
<button type="reset"
onClick={() => handleCancel()}
className="cancelButton">Cancel</button>
</div>
{success &&
<div className="successMsg">Thanks for your request! A member of our team will reach out to you soon!
</div> }
</form>
</div>
);
};
export default ContactForm;
|
Java
|
UTF-8
| 273
| 1.976563
| 2
|
[] |
no_license
|
package one;
public class NimingTest {
public static void main(String[] args){
Thread th=new Thread(){
@Override
public void run() {
System.out.println("匿名类");
}
};
th.start();
}
}
|
Python
|
UTF-8
| 4,507
| 3
| 3
|
[
"MIT"
] |
permissive
|
"""
Example code for reproducing some of the results
from the accompanying paper.
For a particular RGG ensemble we pick a set of parameters.
We then draw some samples from the algebraic connectivity
distriution and:
1) display the mean and Coefficient of Variation.
2) Plot a histogram (see figure 4).
"""
#Standard python modules:
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
import math
#Modules from RGG ensemble analysis:
import rgg_ensemble_analysis
import rgg_ensemble_analysis.Analytic_Functions as Analytic
import rgg_ensemble_analysis.RGG as RGG
import rgg_ensemble_analysis.Statistics_Computation as StatComp
import rgg_ensemble_analysis.get_connection_radii_estimate as connection
#Choose parameters for the ensemble:
Samples = 50
N = 10000
d = 5
boundary = 'P'
#Se the expected mean degree parameter:
C = 1.5
Kappa = C*math.log(N)
#Create a dictionary for the input.
Input_Param_Dict = {}
Input_Param_Dict['N'] = N
Input_Param_Dict['d'] = d
Input_Param_Dict['boundary'] = boundary
#Should in fact derive radius from the scaling param:
Input_Param_Dict['degree_scaling_parameter'] = Kappa
#Number of samples for estimating the connection radius:
radii_samps = 10
#Perform several radius estimates and take the mean:
radii_estimates = [ connection.Get_Required_Kappa(Kappa , N, 1000 , d , Boundaries = boundary , positions = None , pattern="uniform") for k in range(radii_samps) ]
r = np.mean(radii_estimates)
Input_Param_Dict['r'] = r
database_name = "example_database.db"
graph_data_table_name = "graph_properties"
#Choose the properties to sample:
pattern = "uniform"
methods_to_call = [ "Algebraic_Connectivity" ,'LCC_Min_Degree' , 'Mean_Degree' ]
### Sample RGGs ###
RGG.Sample_RGGs(N, r, d, boundary,Kappa,Samples, methods_to_call, database_name,graph_data_table_name,pattern,Save_Positions=False,connect_to_server=False)
### DATA READING IN ###
ensemble = RGG.Graph_Ensemble(database_name,graph_data_table_name,Input_Param_Dict)
mu2_array = ensemble.get_prop_array('algebraic_connectivity')
kmin_array = ensemble.get_prop_array('LCC_Min_Degree')
Mean_Mu2 = np.mean(mu2_array)
CV_Mu2 = StatComp.CV(mu2_array)
CV_ER_Mu2 = StatComp.CV_Error(mu2_array)
#Compute the coefficient of variation and its error:
print("Number of samples = {}".format(len(mu2_array)) )
print("Mean Mu2 = {}".format(Mean_Mu2) )
if boundary =='P' :
print("Theoretical Mean Mu2 (periodic) = {}".format( Analytic.Theory_Algebraic(N,Kappa,d) ) )
print("CV = {} +/- {}".format(CV_Mu2 ,CV_ER_Mu2 ) )
#Compute the correlation between algebraic connectivity and min degree:
correlation_mu2_kmin, pval = stats.spearmanr(mu2_array, kmin_array)
print("correlation = {} (P val = {})\n\n".format(correlation_mu2_kmin,pval) )
###Plot the histogram ####
file_path = "hist_example"
d = ensemble.d
#Code below bins mu2 values according to the corresponding
#values of the minimim degree (kmin).
#Zip mu2 and kmin together:
combined_array = zip(mu2_array,kmin_array)
#get the set of different kmin values:
distinct_kmin_vals = set([ int(k) for k in set(kmin_array) ] )
#Make a dictionary where keys are the values:
kmin_mu2_dict = { }
for k in distinct_kmin_vals :
kmin_mu2_dict[k] = [ ]
for i in range(len(mu2_array)) :
kmin_mu2_dict[kmin_array[i]].append(mu2_array[i])
#Make histogram bins:
num_of_bins = 20
BIN_POINTS = np.linspace(0.9*min(mu2_array), 1.1*max(mu2_array), num = num_of_bins)
plt.clf()
plt.figure(1)
ax = plt.gca()
colors = [ 'k' , 'b' , 'r' , 'g' , 'm']
line_styles = [ '-', '--', '-.', ':']
col_index = 0
all_counts = [ ]
for k in kmin_mu2_dict.keys() :
counts , bins = np.histogram(kmin_mu2_dict[k] , bins= BIN_POINTS )
#bins is len(counts)+1 so need to take the mid points:
mid_points = [ (bins[i+1]+bins[i])/2.0 for i in range(len(bins)-1) ]
#normalize by dividing by the total # of counts:
counts = [ i/float(len(mu2_array)) for i in counts ]
#Make the plot:
ax.plot(mid_points, counts, c = colors[col_index] , linestyle= line_styles[col_index] , linewidth=2,label = "$\kappa_{min}$ = " + str(k))
col_index +=1
all_counts = np.concatenate((all_counts,counts))
#Set axis labels etc.. and save plot.
plt.title("$E(\mu_2)$ = {} , $CV(\mu_2)$ = {} +\- {}".format( round(Mean_Mu2,3), round(CV_Mu2,3), round(CV_ER_Mu2,3) ) )
plt.legend(loc=2)
plt.xlabel("$\mu_2$", fontsize=20)
plt.ylabel("$P(\mu_2)$", fontsize=20)
plt.ylim(0.0, 1.1*max(all_counts))
plt.savefig(file_path + ".png" , bbox_inches="tight",format="png")
|
C#
|
UTF-8
| 5,759
| 3.328125
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
namespace textGame
{
class Program
{
static int width = 100;
static int height = 50;
static int count = 5;
static string search = "Hospital";
static List<CrossPoint> points = new List<CrossPoint>();
static List<Road> roads = new List<Road>();
static void Main(string[] args)
{
Console.WriteLine("Карта размером " + width + "x" + height);
// 4 начальные точки
points.AddRange(CrossPoint.AddRectPoints(width, height));
// дороги
roads.AddRange(Road.AddRoadsRect(points));
// центральные дороги
roads = Road.AddNewRoads(count, width, height, roads, points, out List<CrossPoint> list);
points = list;
Console.WriteLine("\nДобавлено центральных дорог: " + count);
// новые точки на пересечениях центральных дорог
List<CrossPoint> newCrossPoints = new List<CrossPoint>();
roads = Road.CheckCrossRoads(roads, width, height, out newCrossPoints);
points.AddRange(newCrossPoints);
Console.WriteLine("\nВсе доступные пункты: ");
// все созданные точки
List<CrossPoint> show = new List<CrossPoint>();
foreach (var item in roads)
foreach (var item2 in item.GetCrossPoints())
if (!show.Contains(item2))
show.Add(item2);
foreach (var item in show)
Console.WriteLine(item.X + ";" + item.Y + " \t\t" + item.Type);
// отдельный граф для вычисления путей по алгоритму Дейкстры
var g = new Graph();
// добпаление аершин
foreach (var item in points)
{
g.AddVertex(item.X + "_" + item.Y);
}
// перебор дорог
foreach (var item in roads)
{
// список точек на дороге
var cp = item.GetCrossPoints();
for (int i = 0; i < cp.Count - 1; i++)
{
var from = cp[i];
var to = cp[i + 1];
int distance = (int)CrossPoint.Distance(from, to);
// добавление связи в одну и другую сторону
g.AddEdge(from.X + "_" + from.Y, to.X + "_" + to.Y, distance);
g.AddEdge(to.X + "_" + to.Y, from.X + "_" + from.Y, distance);
}
}
Console.WriteLine("\nИщем путь к " + search);
var dijkstra = new Dijkstra(g);
List<string> shortPaths = new List<string>();
// перебирая все точки
foreach (var point in points)
{
// берём нужный тип
if (point.Type == search)
{
// получаем имя-координаты
string search = point.X + "_" + point.Y;
var path = dijkstra.FindShortestPath("0_0", search);
shortPaths.Add(path);
}
}
Console.WriteLine("\nКороткие пути: ");
if (shortPaths.Count > 0)
foreach (var item in shortPaths)
Console.WriteLine(item);
else
Console.WriteLine("Коротких путей нету, так как нету нужного пункта назначения!");
string[] str = { " -> " };
double length;
double minAnswer = double.MaxValue;
string pathAnswer = "Отсутствует.";
if (shortPaths.Count > 0)
{
foreach (var item in shortPaths)
{
length = 0;
string[] coords = item.Split(str, StringSplitOptions.None);
// если в пути больше 1 точки (своей)
if (coords.Length > 1)
{
// перебор точек пути для суммирования длины пути
for (int i = 0; i < coords.Length - 1; i++)
{
string[] xy1 = coords[i].Split('_');
string[] xy2 = coords[i + 1].Split('_');
length += CrossPoint.Distance(new CrossPoint(int.Parse(xy1[0]), int.Parse(xy1[1])), new CrossPoint(int.Parse(xy2[0]), int.Parse(xy2[1])));
}
}
else
{
length = 0;
}
// если текущий путь меньше текущего минимального сохраняем ответ
if (length < minAnswer)
{
minAnswer = length;
pathAnswer = item;
}
}
Console.WriteLine("\nОптимальный маршрут: " + pathAnswer + "\nДлина: " + minAnswer);
}
Console.ReadKey();
}
}
}
/*
* A-------B
* | |
* D-------C
*
* A--E----B
* | \ |
* D----F--C
*
* короткий путь от A до C
* AE - EF - FC
*/
|
PHP
|
UTF-8
| 4,199
| 2.703125
| 3
|
[] |
no_license
|
<?php
require_once '../../connection.php';
require_once '../../function.php';
require_once '../backend.php';
require_once 'header_login.php';
if (isset($_POST['daftar'])) {
$pdo->beginTransaction();
try {
$username = $userData['username'];
$fullname = $userData['full_name'];
$usia = calculate_age($userData['birth_date']);
$keluhan = filter_input(INPUT_POST, 'keluhan', FILTER_SANITIZE_STRING);
$poliklinik = filter_input(INPUT_POST, 'poliklinik', FILTER_SANITIZE_STRING);
$data = [$username, $fullname, $poliklinik, $usia, $keluhan];
$query = "INSERT INTO antrian_pasien (username, name, poliklinik, age, symptom, date) VALUES (?, ?, ?, ?, ?, now())";
$pdo->prepare($query)->execute($data);
$pdo->commit();
$validation = $pdo->prepare("SELECT * FROM antrian_pasien WHERE name = ? AND poliklinik = ? AND age = ? LIMIT 1");
$validation->execute([$fullname, $poliklinik, $usia]);
if ($validation->rowCount() < 0) {
$_SESSION['error'] = "Gagal Mendaftarkan Data!";
} else {
$data = $validation->fetchAll(PDO::FETCH_ASSOC);
$_SESSION['success'] = "Terima Kasih telah mendaftar! Data anda telah berhasil masuk ke sistem\nDengan nomor pendaftaran: <b>". $data[0]['id'] . "</b>";
// header("Location: ../navigation/dashboard.php");
echo "<script>window.location.href = '../navigation/dashboard.php'; </script>";
}
} catch (Exception $e) {
die($e->getMessage());
$pdo->rollback();
}
} elseif (isset($_POST['back'])) {
// header("Location: ../navigation/dashboard.php");
echo "<script>window.location.href = '../navigation/dashboard.php'; </script>";
}
?>
<!-- Register form -->
<section class="signup">
<div class="container">
<div class="card-header bg-transparent">
<?php if(isset($_SESSION['error'])) { ?>
<div class="alert alert-danger"><?= $_SESSION['error'] ?></div>
<?php
unset($_SESSION['error']);
}
?>
<h2 class="form-title">Pendaftaran Pasien</h2>
<form method="POST" class="register-form" id="register-form">
<hr class="my-4" />
<!-- Description -->
<h6 class="heading-small text-muted mb-4">Keluhan Anda</h6>
<div class="form-group">
<textarea rows="4" id="keluhan" class="form-control" name="keluhan" placeholder="Ketikan Keluhan Anda ..." required></textarea>
</div>
<hr class="my-4" />
<h6 class="heading-small text-muted mb-4">Pilih Poliklinik</h6>
<div class="form-group">
<div class="input-select">
<select required name="poliklinik" style="width: 100%; padding: 4px" class="form-select" aria-label="Pilih Poliklinik">
<option selected value="Umum">Umum</option>
<option value="Gigi">Gigi</option>
<option value="KIA">KIA</option>
<option value="Gizi">Gizi</option>
<option value="Sanitasi">Sanitasi</option>
<option value="Batra">Batra</option>
<option value="Psikologi">Psikologi</option>
<option value="Lansia">Lansia</option>
</select>
</div>
</div>
<div class="form-group form-button">
<input type="submit" name="daftar" id="daftar" class="form-submit"/>
<input type="submit" name="back" value="Kembali" formnovalidate class="form-submit"/>
</div>
</form>
<hr class="my-4" />
</div>
</section>
<?php require_once 'footer_login.php'; ?>
|
Python
|
UTF-8
| 1,465
| 2.625
| 3
|
[
"AFL-3.0"
] |
permissive
|
from flask import Flask,render_template,request,redirect,session
app = Flask(__name__) # 一个Flask类的对象
app.secret_key = 'u2jksidjflsduwerjl'
app.debug = True
USER_DICT = {
'1': {'name':'志军','age':18},
'2': {'name':'大伟','age':48},
'3': {'name':'梅凯','age':38},
}
@app.route('/login',methods=['GET',"POST"])
def login():
if request.method == 'GET':
return render_template('login.html')
user = request.form.get('user') # 获取POST传过来的值
pwd = request.form.get('pwd') # 获取POST传过来的值
if user == 'alex' and pwd == '123':
# 用户信息放入session
session['user_info'] = user
return redirect('/index')
else:
return render_template('login.html',msg ='用户名或密码错误')
# return render_template('login.html',**{'msg':'用户名或密码错误'})
@app.route('/index',endpoint='n1')
def index():
user_info = session.get('user_info')
if not user_info:
return redirect('/login')
return render_template('index.html',user_dict = USER_DICT)
@app.route('/detail')
def detail():
user_info = session.get('user_info')
if not user_info:
return redirect('/login')
uid = request.args.get('uid')
info = USER_DICT.get(uid)
return render_template('detail.html',info = info)
@app.route('/logout')
def logout():
del session['user_info']
return redirect('/login')
if __name__ == '__main__':
app.run()
|
Markdown
|
UTF-8
| 1,886
| 2.8125
| 3
|
[] |
no_license
|
# Sollevamento e trasporto
Il tuo punteggio di forza determina la quantità di peso che puoi sopportare. I seguenti termini definiscono ciò che puoi sollevare o trasportare.
### Capacità di carico.
La tua capacità di carico massimo è il tuo punteggio di Forza moltiplicato per 15. Questo è il peso (in libbre) che puoi portare.
### Spingi, trascina o solleva.
Puoi spingere, trascinare o sollevare un peso in libbre fino al doppio della tua capacità di carico (o 30 volte il tuo punteggio di Forza). Mentre si spinge o si trascina un peso in eccesso rispetto alla propria capacità di carico, la velocità scende a 1,5 metri.
### Dimensioni e forza.
Le creature più grandi possono sopportare più peso, mentre le creature minuscole possono portare meno. Per ogni categoria di taglia superiore a Media, raddoppia la capacità di carico della creatura e la quantità che può spingere, trascinare o sollevare. Per una creatura minuscola, dimezza questi pesi.
## Ingombro
Le regole per il sollevamento e il trasporto sono volutamente semplici. Ecco una variante se stai cercando regole più dettagliate per determinare come un personaggio è ostacolato dal peso dell'equipaggiamento. Quando usi questa variante, ignora la colonna Forza della tabella Armatura.
Se porti un peso superiore a 5 volte il tuo punteggio di Forza, sei ingombrato, il che significa che la tua velocità diminuisce di 3 metri.
Se porti un peso superiore a 10 volte il tuo punteggio di Forza, fino alla tua massima capacità di carico, sei invece pesantemente ingombrato, il che significa che la tua velocità diminuisce di 6 metri e hai uno svantaggio sulle prove di caratteristica, sui tiri per colpire e sui tiri salvezza che usano Forza, destrezza o costituzione.
## <b> Credits </b>
Il credito per queste informazioni va a [Legend of Avalon](https://legendofavalon.forumfree.it/?t=77886755)
|
Python
|
UTF-8
| 81
| 3.8125
| 4
|
[] |
no_license
|
a = int(input('enter A: '))
b = int(input('Enter B: '))
print('Sum is: ', a + b)
|
Java
|
UTF-8
| 972
| 2.234375
| 2
|
[] |
no_license
|
package com.example.kailashsaravanan.projectfalconofficial;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
public class DisplayImageActivity extends Activity{
private static final String TAG = "DisplayImageActivity";
public DisplayImageActivity(){
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_image);
ImageView pic = findViewById(R.id.pic);
// Get the Intent that started this activity and extract the string
Intent intent = getIntent();
String url = intent.getStringExtra(ImageAdapter.EXTRA_MESSAGE);
Picasso.get()
.load(url)
.fit()
.centerInside()
.into(pic);
}
}
|
Markdown
|
UTF-8
| 4,190
| 3.53125
| 4
|
[] |
no_license
|
---
title: 二级索引与联合索引
date: 2020-06-15
categories: mysql
---
> 上周在公司内部分享了关于索引的一些相关概念,在会议最后,有两位同事想我提出了若干问题,这里就单独抽出来聊一聊
> 原问题:二级高效还是联合高效,还是根据场景来定?
谈到索引,主要分几大类,**聚簇索引**、**二级索引**、**联合索引**,先回顾一下这三种索引对应的概念
### 聚簇索引
聚簇索引就是以主键值作为索引而建立的一颗 b+ 树,子节点包含**记录完整的数据**,举例说明
```
- 创建表 issues
CREATE TABLE `issues`(
`id` INT UNSIGNED AUTO_INCREMENT,
`title` varchar(255),
`author_id` int,
PRIMARY KEY ( `id` )
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into issues(`title`, `author_id`) values('test_01', 3)
insert into issues(`title`, `author_id`) values('test_02', 10)
insert into issues(`title`, `author_id`) values('test_03', 20)
insert into issues(`title`, `author_id`) values('test_04', 5)
```
画成 mysql 结构的**聚簇索引 (由id建立起来的索引)** b+ 树后,结构是如此的,底下的`页10`、`页22`、`页8`都称为树的子节点,他们内部存储的都是数据表记录,注意,它是**按主键顺序或者rowid(当没有显式定义主键或唯一索引就会默认用 rowid 作为主键,当然了这个是隐藏列,平时我们是看不到的) 的大小顺序组成的..**,而页 10086 也即是我们平时所说的索引页,一颗树中可能有许许多多的索引页,简单画了下大概结构如下:

所以,总结如下:聚簇索引就是由 id 作为索引建立起来的 b+ 树,它是默认就存在的,换言之,不需要你手动创建,innodb引擎会自动帮你创建,如果觉得这棵树有点别扭,可以参考下这句话 **数据即索引,索引即数据**
### 二级索引
在聚簇索引之上创建的索引称之为辅助索引,辅助索引访问数据总是需要二次查找。**辅助索引叶子节点存储的不再是行所有内容,而是主键值 + 你建立的索引**。通过辅助索引首先找到的是主键值,再通过主键值找到数据行的数据叶,再通过数据叶中的Page Directory找到数据行。
对比上面的图,我们可以试着创建一个二级索引
```
alter table issues add index index_by_author_id(author_id);
```
然后b+树的索引结构就会转变为,如图所示
不同点在于**子节点不再存储完成的列记录**,对比可见 title 字段已经没有记录在这些子节点出现了

所以就会有如下区别
```
- 1. 此 sql 会首先在二级索引(index_by_author_id)中先找到对应记录,找到后发现子节点竟然没有 title 字段
- 2. 找到对应记录后,再次到聚簇索引进行查找 title 记录
select title from issues where author_id = 2;
- 此 sql 会首先在二级索引(index_by_author_id)中先找到对应记录,找到后发现子节点有 id 和 title 字段,直接返回
select id, author_id from issues where author_id = 2;
```
### 联合索引
联合索引最为常用,比如我要为**author_id 和 title**建立联合索引,字段有先后次序之分哦,联合索引(author_id, title) 和 (title, author_id) 是不同滴,(语法省略..),比如建立 (author_id, title),此索引包含两层含义:
1. 先把各个记录和页按照 author_id 列进行排序。
2. 在记录的 author_id 列相同的情况下,采用 title 列的大小进行排序

在查找过程中,其实主要区别也是和二级索引的类似,**如果 select 的字段没有命中索引,那么也是要到聚簇索引进行二次查找的**,所以回到最开始的问题,哪个高效?其实硬要选出一个的话,那么当然是二级索引较为高效,因为它的建立索引的字段列少,对比联合索引可以减少循环判断,但是最主要的还是取决于**是否需要回表**,即 select 语句是否有查询非索引的列...
|
Java
|
UTF-8
| 719
| 2.109375
| 2
|
[] |
no_license
|
package cn.app.smartbook;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
public class LoginActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
/**
* 登录函数
*/
public void login(View view) {
}
/**
* 注册函数
* 说明:注册用户数据,存储在sql数据库里面,每个用户数据包括:ID、用户名、密码
*/
public void register(View view) {
Intent intent = new Intent();
intent.setClass(this, RegisterActivity.class);
startActivity(intent);
}
}
|
JavaScript
|
UTF-8
| 4,605
| 3.046875
| 3
|
[
"MIT"
] |
permissive
|
import {getRandomIntInclusive} from "./_utilities";
if (document.getElementById("services")) {
(function () {
// cards variables
const cards = document.querySelectorAll(".services-intro__card");
const numberOfCards = cards.length;
// carousel variables
const carousel = document.querySelector(".services-opinions__carousel");
const carouselItems = document.querySelectorAll(".carousel__item");
const previous = document.querySelector(".services-opinions__carousel-control--prev");
const next = document.querySelector(".services-opinions__carousel-control--next");
const numberOfItems = carouselItems.length;
let currentItemIndex = 0;
/**
* @name flipCardOnClick
* @desc Flips services card when it is clicked. It utilizes adding and removing services-intro__card--flip css class.
*/
const flipCardOnClick = () => {
for (let card of cards) {
card.addEventListener("click", function (e) {
const target = e.target;
const targetCard = target.closest(".services-intro__card");
if (targetCard.classList.contains("services-intro__card--flip")) {
targetCard.classList.remove("services-intro__card--flip");
} else {
for (let card of cards) {
card.classList.remove("services-intro__card--flip");
}
targetCard.classList.add("services-intro__card--flip");
}
});
}
};
/**
* @name flipCardTimeout
* @desc Flips card every 10 seconds by adding services-intro__card--flip css class.
* If there is already a flipped card, this card is flipped back and a new card is not flipped.
*/
const flipCardTimeout = () => {
setTimeout(function () {
let isAnyCardFlipped = false;
for (let card of cards) {
if (card.classList.contains("services-intro__card--flip")) {
isAnyCardFlipped = true;
card.classList.remove("services-intro__card--flip");
break;
}
}
if(!isAnyCardFlipped) {
const cardToFlipIndex = getRandomIntInclusive(0, numberOfCards - 1);
const cardToFlip = cards[cardToFlipIndex];
cardToFlip.classList.add("services-intro__card--flip");
}
flipCardTimeout();
}, 10000);
};
/**
* @name showCarouselItem
* @param selectedIndex {int} index of the item to be shown
* @param currentIndex {int} index of the currently shown item
* @desc Switches between carousel items by changing left property of the carousel DOM element.
*/
const showCarouselItem = (selectedIndex, currentIndex) => {
carousel.style.left = `-${100 * selectedIndex}%`;
carouselItems[currentIndex].classList.remove("carousel__item--selected");
carouselItems[selectedIndex].classList.add("carousel__item--selected");
};
/**
* @name bindCarouselControls
* @desc Binds next and previous buttons for clients opinion carousel.
* It verifies the index of the carousel item to be shown and invokes showCarouselItem function.
*/
const bindCarouselControls = () => {
next.addEventListener("click", function () {
const selectedItemIndex = currentItemIndex < numberOfItems - 1 ? currentItemIndex + 1 : 0;
showCarouselItem(selectedItemIndex, currentItemIndex);
currentItemIndex = selectedItemIndex;
});
previous.addEventListener("click", function () {
const selectedItemIndex = currentItemIndex > 0 ? currentItemIndex - 1 : numberOfItems - 1;
showCarouselItem(selectedItemIndex, currentItemIndex);
currentItemIndex = selectedItemIndex;
})
};
const init = () => {
flipCardOnClick();
flipCardTimeout();
bindCarouselControls();
};
window.addEventListener("load", init)
})();
}
|
Markdown
|
UTF-8
| 1,566
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
#### Travis CI: [](https://travis-ci.com/CkCreative/fff) Better Code: [](https://bettercodehub.com/) Coveralls: [](https://coveralls.io/github/CkCreative/fff?branch=dev)
## Features
- Return a list of all orders on **GET** `https://fast-food-fast-api.herokuapp.com/api/v1/orders`
- Return a single order on **GET** `https://fast-food-fast-api.herokuapp.com/api/v1/orders/<orderID>`
- Post an order on **POST** `https://fast-food-fast-api.herokuapp.com/api/v1/orders`
- Update the status of the order on **PUT** `https://fast-food-fast-api.herokuapp.com/api/v1/orders/<orderID>`
## Testing
- Install Git
- Install Python 3
- Install `pytest` in your virtualenv
- Open console and run:
> `git clone https://github.com/CkCreative/fff.git`
>`cd fff && git checkout dev`
>`python run.py`
- On a new console window, cd to the /fff project directory and run:
>`pytest tests.py`
- You can also use Postman to test the endpoints.
> Sample data to post with **POST** `/api/v1/orders`: `{
"id" : 11,
"customer_id" : 1254,
"status" : ""
}`
> Sample data to update order status using **PUT** `/api/v1/orders/<orderID>`:
`{
"status" : "Completed"
}`
> **Only valid JSON is accepted for POST and PUT**
> To be able to test **PUT**, first **POST** and then try **PUT** to see the changes take effect.
|
Python
|
UTF-8
| 2,793
| 3.8125
| 4
|
[] |
no_license
|
'''
188. 买卖股票的最佳时机 IV
给定一个整数数组 prices ,它的第 i 个元素 prices[i] 是一支给定的股票在第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你最多可以完成 k 笔交易。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
示例 1:
输入:k = 2, prices = [2,4,1]
输出:2
解释:在第 1 天 (股票价格 = 2) 的时候买入,在第 2 天 (股票价格 = 4) 的时候卖出,这笔交易所能获得利润 = 4-2 = 2 。
示例 2:
输入:k = 2, prices = [3,2,6,5,0,3]
输出:7
解释:在第 2 天 (股票价格 = 2) 的时候买入,在第 3 天 (股票价格 = 6) 的时候卖出, 这笔交易所能获得利润 = 6-2 = 4 。
随后,在第 5 天 (股票价格 = 0) 的时候买入,在第 6 天 (股票价格 = 3) 的时候卖出, 这笔交易所能获得利润 = 3-0 = 3 。
'''
class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
# 交易数受到限制,交易数影响状态
n = len(prices)
if n == 0 or n == 1: return 0
K = k
def max_infi(prices):
n = len(prices)
if n == 0 or n == 1: return 0
dp_0, dp_1 = 0, -prices[0] # 前一天不持有股票的最大获利/持有股票的最大获利
for i in range(1, n):
i_not_have = max(dp_1 + prices[i], dp_0) # 第i天不持有股票的最大获利:两种情况取最大
# (1) 前一天不持有 (2)前一天持有,第i天卖出
i_have = b = max(dp_1, dp_0 - prices[i]) # 第i天持有股票的最大获利: 两种情况取最大
# (1) 前一天持有 (2)前一天不持有,第i天买进(因为买进卖出次数不受限制,所以这里使用dp_0 ! 而不是121题中的0, 仅仅跟121题有这点区别!)
dp_0, dp_1 = i_not_have, i_have
return i_not_have
if K > n // 2: return max_infi(prices)
# create 三维 dp list
dp = []
for i in range(n):
dp_item = [[float('-inf')] * 2 for i in range(K + 1)]
dp.append(dp_item)
# 初始化边界
for k in range(K + 1):
dp[0][k][0] = 0
dp[0][k][1] = -prices[0]
for i in range(n):
dp[i][0][0], dp[i][0][1] = 0, 0
# 状态转移
for i in range(1, n):
for k in range(1, K + 1):
dp[i][k][0] = max(dp[i - 1][k][0], dp[i - 1][k][1] + prices[i])
dp[i][k][1] = max(dp[i - 1][k][1], dp[i - 1][k - 1][0] - prices[i])
return dp[n - 1][K][0]
|
C#
|
UTF-8
| 1,897
| 3.265625
| 3
|
[] |
no_license
|
using System;
using System.Windows.Forms;
namespace snake_program
{
public abstract class Enemy
{
// true if snake can eat the enemy
public bool CanEat(ContinuousSnake snake)
{
double unitsLength = (double)snake.Length / BodyPart.SIZE;// get the snake length in body part size units
return unitsLength >= threshold;
}
// check for head collisions with snake
public bool HeadCollision(ContinuousSnake snake)
{
return (snake.Collided(Bounds) & ContinuousSnake.HEAD_COLLISION) > 0; // true if head collision occurred
}
// check for body collision with snake
public bool BodyCollision(ContinuousSnake snake)
{
return (snake.Collided(Bounds) & ContinuousSnake.BODY_COLLISION) > 0; // true if body collision occurred
}
// for when the snake attempts to eat the enemy (returns true if eat was successful)
public bool AttemptEat(ContinuousSnake snake)
{
if (CanEat(snake)) // make sure the snake can kill the enemy
{
// run death animations/functions blahblahblah
Death();
return true;
}
else
{
// run attack animations/functions
Attack();
return false;
}
}
public virtual void Death() { Alive = false; } // run when the enemy dies
public abstract void Attack(); // run for when the enemy attacks
// threshold for snake to eat the enemy (in body part size units)
public int threshold;
// picture that represents bounds of the enemy
public PictureBox Bounds;
//reference to main form
public CoreForm form;
// true if the enemy is alive
public bool Alive = true;
}
}
|
Swift
|
UTF-8
| 727
| 2.90625
| 3
|
[] |
no_license
|
//
// ContentView.swift
// SwiftUINavStackRadar
//
// Created by Simon Rice on 22/12/2019.
// Copyright © 2019 Simon Rice. All rights reserved.
//
import SwiftUI
struct MasterView: View {
private var items: [String] {
(1 ... 100).map { "Item \($0)" }
}
var body: some View {
NavigationView {
List(items, id: \.self) { item in
NavigationLink(
destination: EmptyView().navigationBarTitle(item),
label: { Text(item) }
)
}
.navigationBarTitle("Select Your Item")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
MasterView()
}
}
|
Java
|
ISO-8859-1
| 673
| 1.898438
| 2
|
[] |
no_license
|
package com.example.curso05072012_2;
import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Bundle;
import android.widget.TextView;
public class Notificacao extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancel(R.string.app_name);
TextView text = new TextView(this);
text.setText("Notificao selecionada e executada!");
setContentView(text);
}
}
|
Python
|
UTF-8
| 994
| 3
| 3
|
[] |
no_license
|
# coding=utf-8
'''
Created on 2016年5月9日
@author: 李健博
程序作用:
从bigFile中删除smallFile中出现的行
'''
from __future__ import division
from __future__ import unicode_literals
import sys
reload(sys)
sys.setdefaultencoding('utf-8') # @UndefinedVariable
bigFile="minus_4.txt"
smallFile="1.txt"
newFile="minus_5.txt"
lis_write=[]
with open(bigFile,'rb') as somefile:
for line in somefile:
line = line.decode('utf-8')
line= line.strip() # 去除换行符号
lis_write.append(line)
smallSet=set()
with open(smallFile,'rb') as somefile:
for line in somefile:
line = line.decode('utf-8')
line= line.strip() # 去除换行符号
smallSet.add(line)
with open(newFile,'wb') as somefile:
for line in lis_write: # 不会自动换行
if line not in smallSet:
line+="\r\n"
somefile.write(line)
print "down"
|
Shell
|
UTF-8
| 1,207
| 3.21875
| 3
|
[] |
no_license
|
#!/bin/bash
# Rackspace Cloud Queues / Openstack Zaqar Service
# Usage: cq [METHOD] [ENDPOINT] [BODY]
#
# This service is compatible with Rackspace Cloud Queues and the Openstack
# Zaqar REST API. More information about the API can be found here:
#
# https://developer.rackspace.com/docs/cloud-queues/v1/developer-guide/
#
cq () {
stekUser=$(_stek_user)
_stek_ensure_valid_catalog "$stekUser"
authToken=$(_stek_token "$stekUser")
serviceBase=$(_stek_service "$stekUser" "cloudQueues")
defaultClientId=$(_stek_cq_client_id "$stekUser")
clientId="${CQ_CLIENT_ID:-$defaultClientId}"
if [[ -n "$3" ]]
then
curl -H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-H "User-Agent: $(uname -mnrs); $stekUser; stek 0.1.0" \
-H "X-Auth-Token: $authToken" \
-H "Client-ID: $clientId" \
"-X$1" "$serviceBase$2" -d "$3" \
2>/dev/null | jq '.'
else
curl -H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-H "User-Agent: $(uname -mnrs); $stekUser; stek 0.1.0" \
-H "X-Auth-Token: $authToken" \
-H "Client-ID: $clientId" \
"-X$1" "$serviceBase$2" \
2>/dev/null | jq '.'
fi
}
|
Markdown
|
UTF-8
| 1,367
| 2.546875
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
This started out as example code for odd decoding of utf-8 in java vs jni
This is because of:
http://banachowski.com/deprogramming/2012/02/working-around-jni-utf-8-strings/
It now also contains code that will help generate code for shclepping things between jni and java.
Mostly to work around the UTF-8 issue of strings above while at the same time not passing byte[]
This has forked into a way to take a given class, and generate java and c code to copy the bytes back and forth.
The example is:
java -cp build/libs/TestUTF8Decoding.jar:TestProject/build/classes/main/ com.yahoo.wildwest.jnih.ObjectJniH com.yahoo.example.test.SampleInfo -javapath TestProject/src/main/java/ -cfile TestProject/src/main/native/generateSample
This will generate:
TestProject//src/main/java/com/yahoo/example/test/SampleInfo.java
TestProject//src/main/java/com/yahoo/example/test/SampleInfoGenerated.java
TestProject//src/main/native/generateSample.cpp
TestProject//src/main/native/generateSample.h
Those can then be used to copy bytes back and forth.
TestProject is a contained example, to demonstrate this code.
There is still other bits that are needed, this generates the bits that make it easier to cooperate.
There is a lot of speed to be gathered by just allocating memory and copying a struct into it in C, instead of creating 10 or 15 java
objects from the jni.
|
Java
|
UTF-8
| 3,226
| 1.75
| 2
|
[] |
no_license
|
package com.multipz.kc.Model;
/**
* Created by Admin on 26-09-2017.
*/
public class GetStaffAsPerTypeModel {
private String attendance_id, user_id, date, amount, name, work_type_id, mobile, profile_img, proof_img, password, user_type, salary, salary_based_type, created_date, modified_date, is_status, is_delete, work_type;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getWork_type() {
return work_type;
}
public void setWork_type(String work_type) {
this.work_type = work_type;
}
public String getAttendance_id() {
return attendance_id;
}
public void setAttendance_id(String attendance_id) {
this.attendance_id = attendance_id;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getWork_type_id() {
return work_type_id;
}
public void setWork_type_id(String work_type_id) {
this.work_type_id = work_type_id;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getProfile_img() {
return profile_img;
}
public void setProfile_img(String profile_img) {
this.profile_img = profile_img;
}
public String getProof_img() {
return proof_img;
}
public void setProof_img(String proof_img) {
this.proof_img = proof_img;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUser_type() {
return user_type;
}
public void setUser_type(String user_type) {
this.user_type = user_type;
}
public String getSalary() {
return salary;
}
public void setSalary(String salary) {
this.salary = salary;
}
public String getSalary_based_type() {
return salary_based_type;
}
public void setSalary_based_type(String salary_based_type) {
this.salary_based_type = salary_based_type;
}
public String getCreated_date() {
return created_date;
}
public void setCreated_date(String created_date) {
this.created_date = created_date;
}
public String getModified_date() {
return modified_date;
}
public void setModified_date(String modified_date) {
this.modified_date = modified_date;
}
public String getIs_status() {
return is_status;
}
public void setIs_status(String is_status) {
this.is_status = is_status;
}
public String getIs_delete() {
return is_delete;
}
public void setIs_delete(String is_delete) {
this.is_delete = is_delete;
}
}
|
JavaScript
|
UTF-8
| 3,999
| 2.6875
| 3
|
[] |
no_license
|
//クッキーの取得
function GetCookies2(response){
var headers = response.getAllHeaders();
var cookies = [];
if ( typeof headers['Set-Cookie'] !== 'undefined' ) {
// Set-Cookieヘッダーが2つ以上の場合はheaders['Set-Cookie']の中身は配列
var cookies = typeof headers['Set-Cookie'] == 'string' ? [ headers['Set-Cookie'] ] : headers['Set-Cookie'];
for (var i = 0; i < cookies.length; i++) {
// Set-Cookieヘッダーからname=valueだけ取り出し、セミコロン以降の属性は除外する
cookies[i] = cookies[i].split( ';' )[0];
};
}
return cookies;
}
//初期セッションID取得
function GetPreJSessionID(){
var FIRST_SESSION_URL = "https://websv.aichi-pref-library.jp/winj//opac/login.do?lang=ja&dispatch=/opac/mylibrary.do";
var options = {
method : "get",
contentType: "text/plain"
};
var response = UrlFetchApp.fetch(FIRST_SESSION_URL,options);
var cookies = GetCookies2(response)
return cookies;
}
//ユーザ情報の送信
function SendUserInfo2(cookies){
var conf = config(2);
var SEND_USER_INFO_URL = conf["SEND_USER_INFO_URL"];
var txt_usercd = conf["txt_usercd"];
var txt_password = conf["txt_password"];
var submit_btn_login = "ログイン";
var cookie = cookies.join(';');
// HTTPリクエストのパラメータをobjectで設定
// POSTで渡すフォームデータはpayloadで指定
var options = {
method : "post",
followRedirects: false,
contentType: "application/x-www-form-urlencoded",
headers: {
Cookie: cookies.join(';'),
Pragma: "no-cache",
},
payload : {
txt_usercd: txt_usercd,
txt_password: txt_password,
submit_btn_login : submit_btn_login
}
};
var response = UrlFetchApp.fetch(SEND_USER_INFO_URL,options)
var cookies = GetCookies2(response)
return cookies;
}
//貸し出し状況の取得
function GetLendList(cookies){
var FIRST_SESSION_URL = "https://websv.aichi-pref-library.jp/winj/opac/lend-list.do";
var options = {
method : "get",
contentType: "text/plain",
headers: {
Cookie: cookies.join(';'),
Pragma: "no-cache",
}
};
var response = UrlFetchApp.fetch(FIRST_SESSION_URL,options);
return response;
}
function main2(){
try{
//ログイン前のセッションIDを取得
var PreJSessionID = GetPreJSessionID();
//ログインして本セッションIDを取得
var JSessionID = SendUserInfo2(PreJSessionID);
//貸し出し状況の取得
var response = GetLendList(JSessionID);
var html = response.getContentText();
var itemTable = Parser.data(html).from('<ol class="list-book result hook-check-all">').to('</ol>').build();
var itemTitle = Parser.data(itemTable).from('<span class="title">').to('</span>').iterate();
var itemInfo = Parser.data(itemTable).from('<div class="column info">').to('</div>').iterate();
var titleArray = [];
var libArray = [];
var dateArray = [];
//タイトルの抽出
itemTitle.forEach(function(value,index,array){
if (String(value).indexOf("DOCTYPE") == -1){
titleArray.push(value);
libArray.push("県図書館");
}
})
var x;
x = 3;
//貸出日の抽出
itemInfo.forEach(function(value,index,array){
if (String(value).indexOf("貸") !== -1){
dateArray.push(value.match(/貸出日:(\d{4}\/\d{2}\/\d{2})/)[1]);
}
})
var lastRow = sheet.getLastRow();
var flatten = sheet.getRange(2, 2, lastRow).getValues();
Array.prototype.concat.apply([],flatten);
// Logger.log(flatten);
flatten.filter
titleArray.forEach(function(value,index,array){
lastRow = sheet.getLastRow();
sheet.getRange(lastRow+1, 1).setValue(dateArray[index]);
sheet.getRange(lastRow+1, 2).setValue(titleArray[index]);
sheet.getRange(lastRow+1, 3).setValue(libArray[index]);
})
}catch(e){
result = "エラー内容:" + e;
Logger.log(result);
}
}
|
Python
|
UTF-8
| 1,486
| 2.9375
| 3
|
[] |
no_license
|
import tensorflow as tf
from tensorflow.keras import layers
def conv2d_bn(x,
filters,
filter_shape,
padding='valid',
strides=(1, 1),
data_format='channels_first',
name=None):
"""Utility function to apply conv + BN.
# Arguments
x: input tensor.
num_filters: num filters in `Conv2D`.
filter_shape: shape of the convolution kernel.
padding: padding mode in `Conv2D`.
strides: strides in `Conv2D`.
data_format: 'channels_first' or 'channels_last'
name: name of the ops; will become `name + '_conv'`
for the convolution and `name + '_bn'` for the
batch norm layer.
# Returns
Output tensor after applying `Conv2D` and `BatchNormalization`.
"""
if name is not None:
bn_name = name + '_bn'
conv_name = name + '_conv'
else:
bn_name = None
conv_name = None
bn_axis = 1 if data_format=='channels_first' else -1
x = layers.Conv2D(
filters, filter_shape,
strides=strides,
padding=padding,
use_bias=False, # batch norm already does some shifting
data_format=data_format,
name=conv_name)(x)
x = layers.BatchNormalization(
axis=bn_axis,
scale=False, # scaling will be done by the next layer (only for linear activation)
name=bn_name)(x)
return layers.Activation('relu', name=name)(x)
|
C++
|
UTF-8
| 3,926
| 3.1875
| 3
|
[] |
no_license
|
/*******************************************************************************
* @File : 097_interleaving_string.cpp
* @Author: Zhang Zixuan
* @Email : zixuan.zhang.victor@gmail.com
* @Blog : www.noathinker.com
* @Date : 2016年03月21日 星期一 21时10分01秒
******************************************************************************/
/*
* Question:
*
* Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
*
* For example,
* Given:
* s1 = "aabcc",
* s2 = "dbbca",
*
* When s3 = "aadbbcbcac", return true.
* When s3 = "aadbbbaccc", return false.
*
*/
class Solution
{
public:
bool isInter(string s1, int start1, string s2, int start2, string s3, int start3)
{
if (s3.length() == start3)
return true;
bool result = false;
if (start1 < s1.length() && s1[start1] == s3[start3])
result = isInter(s1, start1+1, s2, start2, s3, start3+1);
if (result)
return result;
if (start2 < s2.length() && s2[start2] == s3[start3])
result = isInter(s1, start1, s2, start2+1, s3, start3+1);
return result;
}
bool isInterleave(string s1, string s2, string s3)
{
if (s1.length() + s2.length() != s3.length())
return false;
int start1 = 0;
int start2 = 0;
int start3 = 0;
return isInter(s1, start1, s2, start2, s3, start3);
}
bool isInterleaveWithStack(string s1, string s2, string s3)
{
if (s1.length()+s2.length() != s3.length())
return false;
vector<int> vec(s3.length());
stack<int> stack1;
stack<int> stack2;
stack<int> stack3;
bool res = false;
if (s1.length() > 0 && s1[0] == s3[0])
{
stack1.push(1);
stack2.push(0);
stack3.push(1);
res = true;
}
if (s2.length() >0 && s2[0] == s3[0])
{
stack1.push(0);
stack2.push(1);
stack3.push(1);
res = true;
}
if (!res)
return false;
int index1, index2, index3;
while (!stack3.empty())
{
index1 = stack1.top();
index2 = stack2.top();
index3 = stack3.top();
stack1.pop();
stack2.pop();
stack3.pop();
if (index3 == s3.length())
return true;
if (index1 < s1.length() && s1[index1] == s3[index3])
{
stack1.push(index1+1);
stack2.push(index2);
stack3.push(index3+1);
}
if (index2 < s2.length() && s2[index2] == s3[index3])
{
stack1.push(index1);
stack2.push(index2+1);
stack3.push(index3+1);
}
}
return false;
}
bool isInterleavingWithDP(string s1, string s2, string s3)
{
if (s1.length()+s2.length() != s3.length())
return false;
if (s1.length() == 0)
return s2 == s3;
if (s2.length() == 0)
return s1 == s3;
int len1 = s1.length();
int len2 = s2.length();
vector<vector<int> > matrix;
vector<int> vec(len2+1, 1);
for (int i = 0; i < len1+1; ++i)
matrix.push_back(vec);
// initialize
for (int i = 1; i <= len1; ++i)
matrix[i][0] = (matrix[i-1][0] && s1[i-1] == s3[i-1]);
for (int i = 1; i <= len2; ++i)
matrix[0][i] = (matrix[0][i-1] && s2[i-1] == s3[i-1]);
for (int i = 1; i <= len1; ++i)
{
for (int j = 1; j <= len2; ++j)
{
matrix[i][j] = (matrix[i-1][j] && s1[i-1] == s3[i+j-1]) ||
(matrix[i][j-1] && s2[j-1] == s3[i+j-1]);
}
}
return matrix[len1][len2];
}
};
|
Shell
|
UTF-8
| 298
| 2.640625
| 3
|
[] |
no_license
|
#!/bin/bash
source fs-setup.sh
./mkfs_lvm.sh
./mountfs_lvm.sh
mkdir -p /mnt/temp
start=`fdisk -l /vm/guest0.img | tail -n 1 | awk '{print $3}'`
mount -o loop,offset=$(($start * 512)) /vm/guest0.img /mnt/temp
pushd /mnt/vm
cp -a /mnt/temp/* .
popd
./unmountfs_lvm.sh
./reinstall-grub.sh
|
JavaScript
|
UTF-8
| 807
| 2.78125
| 3
|
[] |
no_license
|
import React from 'react';
class ClockTimer extends React.Component {
constructor (props) {
super(props)
this.state={count: 0}
this.tick = this.tick.bind(this)
this.state={value: this.props.value}
}
componentDidMount (){
this.interval = setInterval(this.tick, 1000)
}
tick () {
console.log ("this.props.value", this.props.value)
console.log ("this.props.start", this.props.start)
console.log("Asdasd", typeof this.props.value)
this.setState({count: (this.props.value - this.props.start)/86400000 })
}
render(){
return(
<div>
<h1> {Math.round(this.state.count)} days left </h1>
</div>
)
}
componentWillUnmount(){
clearInterval(this.interval);
}
}
export default ClockTimer;
|
Java
|
UTF-8
| 885
| 3.5625
| 4
|
[] |
no_license
|
package practice;
import java.util.Scanner;
public class PrimeNo {
public static void main(String[] args) {
//String str1;
// Scanner in = new Scanner(System.in);
System.out.println("Enter your String");
//str1 = in.nextLine();
int a = Integer.parseInt(new Scanner(System.in).nextLine());
PrimeNo p = new PrimeNo();
/*boolean b =*/ p.fibonacci(a);
//System.out.println(b);
}
public boolean prime(int a)
{
boolean b = false;
for (int i =2; i<a ; i++)
{
if(a%i == 0)
{
b = false;
break;
}
else
{
b = true;
}
//System.out.println("i is "+i);
}
return b;
}
public void fibonacci(int a)
{
int b=0,c=1,d;
for(int i=1;i<=a;i++)
{
d = c;
c =b;
b = d+c;
System.out.println(b);
}
}
}
|
Python
|
UTF-8
| 1,896
| 2.765625
| 3
|
[] |
no_license
|
import logging
import time, sys
import socket
import threading, queue
import hashlib
from jim.convert import json_to_bytes, bytes_to_json
logger = logging.getLogger('root')
send_queue = queue.Queue()
class Client():
username = ''
def __init__(self, host, port):
self._host = host
self._port = port
self.lock = threading.Lock()
self.recv_queue = queue.Queue()
self.send_queue = send_queue
@property
def socket(self):
return self._sock
def _send_message(self):
while 1:
data = self.send_queue.get()
if data:
msg = json_to_bytes(data)
self.socket.send(msg)
self.send_queue.task_done()
def _get_message(self):
#получение сообщений от сервера, пока только вывод в консоль, сервер без бд поэтому просто пересылает сообщение
sock = self.socket
cont_l = []
while True:
try:
sock.settimeout(12)
data_recv = sock.recv(1024)
data_recv = bytes_to_json(data_recv)
self.recv_queue.put(data_recv)
except socket.timeout:
pass
def start_thread(self):
t1 = threading.Thread(target=self._send_message)
t2 = threading.Thread(target=self._get_message)
t1.daemon = True
t2.daemon = True
t1.start()
t2.start()
def run(self):
try:
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.connect((self._host, self._port))
logger.debug('Client is connected to server: {}:{}'.format(self._host, self._port))
self.start_thread()
except:
return 'Сервер не отвечает'
|
Java
|
UTF-8
| 5,620
| 2.515625
| 3
|
[] |
no_license
|
package DAO;
import DAOInterfaces.AdresDAO;
import DAOInterfaces.OVChipkaartDAO;
import DAOInterfaces.ReizigerDAO;
import Domein.Reiziger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class ReizigerDAOPsql implements ReizigerDAO {
private Connection conn;
private AdresDAO adao;
private OVChipkaartDAO odao;
public ReizigerDAOPsql(Connection conn) {
this.conn = conn;
}
public void setAdao(AdresDAO adao) {
this.adao = adao;
}
public void setOdao(OVChipkaartDAO odao) {this.odao = odao;}
@Override
public boolean save(Reiziger reiziger) {
try {
String q = "INSERT INTO reiziger (reiziger_id, voorletters, tussenvoegsel, achternaam, geboortedatum)\n" +
"VALUES (?, ?, ?, ?, TO_DATE(?, 'yyyy-mm-dd'));";
PreparedStatement pst = conn.prepareStatement(q);
pst.setInt(1, reiziger.getId());
pst.setString(2, reiziger.getVoorletters());
pst.setString(3, reiziger.getTussenvoegsel());
pst.setString(4, reiziger.getAchternaam());
pst.setString(5, "" + reiziger.getGeboortedatum());
pst.executeUpdate();
return true;
} catch (SQLException e) {
System.out.println(e.getMessage());
return false;
}
}
@Override
public boolean update(Reiziger reiziger) {
try {
String q = "UPDATE reiziger " +
"SET voorletters = ?, tussenvoegsel = ?, achternaam = ?, geboortedatum = TO_DATE(?, 'yyyy-mm-dd') " +
"WHERE reiziger_id=?;";
PreparedStatement pst = conn.prepareStatement(q);
pst.setInt(5, reiziger.getId());
pst.setString(1, reiziger.getVoorletters());
pst.setString(2, reiziger.getTussenvoegsel());
pst.setString(3, reiziger.getAchternaam());
pst.setString(4, "" + reiziger.getGeboortedatum());
pst.executeUpdate();
return true;
} catch (SQLException e) {
System.out.println(e.getMessage());
return false;
}
}
@Override
public boolean delete(Reiziger reiziger) {
try {
String q = "DELETE FROM reiziger WHERE reiziger_id=?;";
PreparedStatement pst = conn.prepareStatement(q);
pst.setInt(1, reiziger.getId());
pst.executeUpdate();
return true;
} catch (SQLException e) {
System.out.println(e.getMessage());
return false;
}
}
@Override
public Reiziger findById(int id) throws Exception {
try {
String q = "SELECT * FROM reiziger WHERE reiziger_id=?;";
PreparedStatement pst = conn.prepareStatement(q);
pst.setInt(1, id);
ResultSet rs = pst.executeQuery();
if (rs.next()) {
Reiziger r1 = new Reiziger(rs.getInt("reiziger_id"),rs.getString("voorletters"),rs.getString("tussenvoegsel")+" ",rs.getString("achternaam"),java.sql.Date.valueOf(rs.getString("geboortedatum")));
r1.setAdres(adao.findByReiziger(r1));
r1.setKaarten(odao.findByReiziger(r1));
if (rs.next()) {
System.out.println(rs);
System.out.println(rs.getInt("reiziger_id"));
throw new Exception("More than one person listed at id");
}
return r1;
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return null;
}
@Override
public List<Reiziger> findByGbdatum(String datum) {
try {
String q = "SELECT * FROM reiziger WHERE geboortedatum=TO_DATE(?, 'yyyy,mm,dd');";
PreparedStatement pst = conn.prepareStatement(q);
pst.setString(1, datum);
ResultSet rs = pst.executeQuery();
List<Reiziger> lr = new ArrayList<>();
while (rs.next()) {
Reiziger r1 = new Reiziger(rs.getInt("reiziger_id"),rs.getString("voorletters"),rs.getString("tussenvoegsel")+" ",rs.getString("achternaam"),java.sql.Date.valueOf(rs.getString("geboortedatum")));
r1.setAdres(adao.findByReiziger(r1));
r1.setKaarten(odao.findByReiziger(r1));
lr.add(r1);
}
return lr;
} catch (SQLException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public List<Reiziger> findAll() {
try {
String q = "SELECT * FROM reiziger";
PreparedStatement pst = conn.prepareStatement(q);
ResultSet rs = pst.executeQuery();
List<Reiziger> lr = new ArrayList<>();
while (rs.next()) {
Reiziger r1 = new Reiziger(rs.getInt("reiziger_id"),rs.getString("voorletters"),rs.getString("tussenvoegsel")+" ",rs.getString("achternaam"),java.sql.Date.valueOf(rs.getString("geboortedatum")));
r1.setAdres(adao.findByReiziger(r1));
r1.setKaarten(odao.findByReiziger(r1));
lr.add(r1);
}
return lr;
} catch (SQLException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
|
Java
|
UTF-8
| 2,811
| 2.0625
| 2
|
[] |
no_license
|
package com.beisheng.synews.fragment;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import com.beisheng.base.utils.BaseCommonUtils;
import com.beisheng.base.utils.BitmapUtil;
import com.beisheng.synews.activity.LoginActivity;
import com.im.zhsy.R;
public class GuideFragment extends Fragment implements OnClickListener {
private Activity mActivity;
private RelativeLayout mLogoLayout1;
private int index;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.guide_fragment, container, false);
return view;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.mActivity = activity;
}
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(mActivity, LoginActivity.class);
this.startActivity(intent);
mActivity.finish();
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mLogoLayout1 = (RelativeLayout) view.findViewById(R.id.logo_layout1);
showView(index);
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public void showView(int index) {
Bitmap bitmap = null;
switch (index) {
case 0:
bitmap = BitmapFactory.decodeResource(mActivity.getResources(), R.drawable.guide_1);
break;
case 1:
bitmap = BitmapFactory.decodeResource(mActivity.getResources(), R.drawable.guide_2);
break;
case 2:
bitmap = BitmapFactory.decodeResource(mActivity.getResources(), R.drawable.guide_3);
break;
default:
bitmap = BitmapFactory.decodeResource(mActivity.getResources(), R.drawable.guide_1);
break;
}
Bitmap newBitmap = BitmapUtil.zoomImg(bitmap, BaseCommonUtils.getScreenWidth(mActivity), BaseCommonUtils.getScreenHigh(mActivity));
Drawable drawable = new BitmapDrawable(newBitmap);
mLogoLayout1.setBackgroundDrawable(drawable);
}
}
|
Java
|
UTF-8
| 408
| 1.757813
| 2
|
[] |
no_license
|
package spring.service;
import java.util.List;
import spring.beans.Teachers;
public interface ITeachersService {
Teachers findTeacherByNumber(String tnumber);
void delTeacherById(int id);
List<Teachers> findTeachers(int collId);
void addOrupdateTeacher(Teachers teacher);
int countPhone(String tphone);
Teachers findByTid(int id);
List<Teachers> findTeacherByPage(int begin, int collId);
}
|
Python
|
UTF-8
| 1,133
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
import mongoengine
from demo2.model.base_model import BaseModel
class Article(BaseModel, mongoengine.Document):
title = mongoengine.StringField(required=True, default='')
added = mongoengine.DateTimeField(required=True, default='')
url = mongoengine.StringField(required=True, unique=True, default='')
author = mongoengine.ReferenceField('User', default=False)
meta = {
'collection': 'articles',
'indexes': [
{
'fields': ['url'],
'unique': True
}
]
}
@classmethod
def get_by_id(cls, id):
return cls.objects(id=id).first()
@classmethod
def delete_by_id(cls, id):
lunch = cls.objects(id=id).first()
lunch.delete()
def api_base_response(self):
return {'id': str(self.id), 'url': self.url}
def api_response(self):
return {
'id': str(self.id),
'title': self.title,
'added': self.added.timestamp(),
'url': self.url,
'author': (str(self.author.id)
if self.author else {})
}
|
Swift
|
UTF-8
| 2,247
| 3.25
| 3
|
[] |
no_license
|
//
// CalcOperations.swift
// Calculator
//
// Created by SHIVAM SHAH on 27/09/17.
// Copyright © 2017 Centennial College. All rights reserved.
//
/*
import Foundation
class CalcOperations
{
private var accumulator: Double = 0.0
func setOperand (operand: Double) {
accumulator = operand
}
var operations: Dictionary<String,Operation> = [
// "+" : Operation.BinaryOperation({ $0 + $1 }),
"+" : Operation.BinaryOperation({ $0 + $1}),
"−" : Operation.BinaryOperation({ $0 - $1 }),
"×" : Operation.BinaryOperation({ $0 * $1 }),
"÷" : Operation.BinaryOperation({ $0 / $1 }),
"=": Operation.Equals
]
enum Operation
{
//case Constant
case BinaryOperation
case Equals
}
func performOperation (symbol: String) {
if let operation = operations[symbol]{
switch operation
{
case .BinaryOperation(let function):
executePendingBinaryOperation()
pending = pendingBinaryOperationInfo(binaryFunction: function, firstOperand: accumulator)
case .Equals: break
executePendingBinaryOperation()
}
}
}
private func executePendingBinaryOperation()
{
if pending != nil {
accumulator = pending!.binaryFunction(pending!.firstOperand, accumulator)
pending = nil
}
}
private var pending: pendingBinaryOperationInfo?
struct pendingBinaryOperationInfo
{
var binaryFunction: (Double, Double) -> Double
var firstOperand: Double
}
var result: Double {
get
{
return accumulator
}
}
}
*/
|
JavaScript
|
UTF-8
| 590
| 2.546875
| 3
|
[] |
no_license
|
import React from "react";
import { Select } from "../components/Select";
export default class MultipleSelect extends React.Component {
state = {
value: this.props.value,
};
onChooseItem = (items) => {
const value = items.join(", ").slice(0, 20);
this.setState({
value: value === items.join(", ") ? value : `${value}...`,
});
};
render() {
const { items } = this.props;
const { value } = this.state;
return (
<Select
items={items}
multiple
value={value}
onChange={this.onChooseItem}
/>
);
}
}
|
Markdown
|
UTF-8
| 1,830
| 3.765625
| 4
|
[
"MIT"
] |
permissive
|
---
layout: leetcode
date: 2016-07-15
title: Intersection of Two Linked Lists
tags: [Linked List]
---
* Contents
{:toc #toc_of_keans_blog}
## Question
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
<pre>
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
</pre>
begin to intersect at node c1.
**Notes:**
- If the two linked lists have no intersection at all, return `null`.
- The linked lists must retain their original structure after the function returns.
- You may assume there are no cycles anywhere in the entire linked structure.
- Your code should preferably run in O(n) time and use only O(1) memory.
***
## Solution
**Result:** Accepted **Time:** 36 ms
Here should be some explanations.
```c
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
struct ListNode * a = headA,*b = headB,*tmp;
int cnt = 0;
while(a && b)
{
a = a->next;
b = b->next;
cnt ++;
}
if(a == NULL)
{
tmp = headB;
while(b)
tmp = tmp->next,
b = b->next;
b = tmp;
a = headA;
}
if(b == NULL)
{
tmp = headA;
while(a)
a = a->next,
tmp = tmp->next;
a = tmp;
b = headB;
}
while(a != b && a && b)
{
a = a->next;
b = b->next;
}
if(a && b) return a;
return NULL;
}
```
**Complexity Analytics**
- Time Complexity: $$O(n)$$
- Space Complexity: $$O(1)$$
|
Java
|
UHC
| 3,296
| 3.0625
| 3
|
[] |
no_license
|
package SwingMember2;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Iterator;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MemberDelete {
MemberMgmUI main;
//Field
JPanel deletePane;
JPanel jp_deltetSearch;
JLabel jl_deleteSearchName;
JTextField jt_deleteSearch;
//Consturctor
public MemberDelete() {
// TODO Auto-generated constructor stub
}
public MemberDelete(MemberMgmUI main) {
this.main = main;
this.deletePane = main.deletePane;
}
//Method
public void delete() {
// switchPane("delete");
main.switchPane(MemberMgmUI.DELETE);
// object
jp_deltetSearch = new JPanel();
jl_deleteSearchName = new JLabel(">>");
jt_deleteSearch = new JTextField(20);
// font_set
jl_deleteSearchName.setFont(main.font);
// component_add
jp_deltetSearch.add(jl_deleteSearchName);
jp_deltetSearch.add(jt_deleteSearch);
// panel_add
deletePane.add(jp_deltetSearch);
main.add(deletePane);
main.setVisible(true);
jt_deleteSearch.addActionListener(new MemberDeleteEvent());
}// delete_Method//**
/**
* listener ʿ inner Class _Event ü;
* @author user
*/
public class MemberDeleteEvent implements ActionListener{
public void actionPerformed(ActionEvent e) {
if(! jt_deleteSearch.getText().equals("")) {
String name =jt_deleteSearch.getText().trim();
if (deleteDataCheck(name)) {
int flag = JOptionPane.showConfirmDialog(null, main.getMsg(" Ͻðڽϱ?"), "Ȯ", 0);
if (flag == 0) {
deleteProc(name);
}
}else {
JOptionPane.showMessageDialog(null, main.getMsg(" Ͱ ʽϴ."));
}
}else {
JOptionPane.showMessageDialog(null, main.getMsg(" ̸ Էּ."));
jt_deleteSearch.requestFocus();
}
}
}//inner_class
public boolean deleteDataCheck(String name) {
boolean result = false;
for (MemberVO vo : MemberMgmUI.list) {
if (vo.getName().equals(name)) {
result = true;
}
}
return result;
}//deleteDataCheck()**//
// public boolean deleteFormCheck() {
// boolean flag =false;
// if(jt_deleteSearch.getText().equals("")) {
// JOptionPane.showMessageDialog(null, main.getMsg(" ̸ Էּ."));
// jt_deleteSearch.requestFocus();
// }else {
// flag=true;
// }
// return flag;
// }//deleteDateCheck();;**/
public void deleteProc(String name) {//Error -> ArrayList Ѱ ó:Iterator ذ
// String name = jt_deleteSearch.getText();
Iterator<MemberVO> it = MemberMgmUI.list.iterator();
while(it.hasNext()) {
MemberVO vo = it.next();
if(vo.getName().equals(name)) {
it.remove();
JOptionPane.showMessageDialog(null, main.getMsg("Ϸ"));
}
}
// for (MemberVO vo : MemberMgmUI.list) {
// if (vo.getName().equals(dname)) {
// if (MemberMgmUI.list.remove(vo)) {
// JOptionPane.showMessageDialog(null, main.getMsg("Ϸ"));
// }
// }
// }
}// Proc**//
}//class
|
Shell
|
UTF-8
| 5,951
| 3.84375
| 4
|
[
"Apache-2.0"
] |
permissive
|
#!/bin/bash -x
die() {
if [[ "$1" = "" ]] ; then
echo "Exiting program due to error."
else
echo $1
fi
exit 1
}
function usage() {
echo "upgrader v0.3"
echo ""
echo "upgrader.sh OPTIONS DASHBOARD_NAME"
echo ""
echo "Valid options:"
echo " -b --dashboardname The dashboard name (Example: MyNewDashboard)"
echo " -t --tagname Tag Name (Default: trunk)"
echo " -c --clonedashboard Dashboard Name to clone (Default: none)"
echo " -i --clonedbhost Database Host to clone from (Default: none). Not used if --clone_dashboard is not set"
echo " -v --clonedbusername Username to access clone database (Default: none). Not used if --clone_dashboard is not set"
echo " -q --clonedbpassword Password to access clone database (Default: none). Not used if --clone_dashboard is not set"
echo " -y --deploydb Deploy DB (Default: true)"
echo " -k --locktablesonclone Lock tables on clone (Default: true)"
echo " -h --help Display this help."
exit 0
}
#defaults!
PROXY_HOST=127.0.0.1
TAG_NAME=trunk
DB_HOST=127.0.0.1
DEPLOY_DB=true
while getopts ":ht:c:i:v:q:y:b:k:-:" opt; do
case $opt in
-)
case "${OPTARG}" in
dashboardname)
DASHBOARD_NAME="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
;;
tagname)
TAG_NAME="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
;;
clonedashboard)
CLONE_DASHBOARD="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
;;
clonedbhost)
CLONE_DB_HOST="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
;;
clonedbusername)
CLONE_DB_USER="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
;;
clonedbpassword)
CLONE_DB_PW="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
;;
deploydb)
DEPLOY_DB="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
;;
locktablesonclone)
LOCK_TABLES_ON_CLONE="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
;;
help)
usage
;;
*)
echo "Unknown parameter: $OPTARG" >&2 && exit 1;
;;
esac
;;
b) DASHBOARD_NAME=$OPTARG
;;
t) TAG_NAME=$OPTARG
;;
c) CLONE_DASHBOARD=$OPTARG
;;
i) CLONE_DB_HOST=$OPTARG
;;
v) CLONE_DB_USER=$OPTARG
;;
q) CLONE_DB_PW=$OPTARG
;;
y) DEPLOY_DB=$OPTARG
;;
k) LOCK_TABLES_ON_CLONE=$OPTARG
;;
h) usage
;;
esac
done
echo "e-upgrader DASHBOARD_NAME=$DASHBOARD_NAME"
echo "e-upgrader TAG_NAME=$TAG_NAME"
echo "e-upgrader CLONE_DASHBOARD=$CLONE_DASHBOARD"
echo "e-upgrader CLONE_DB_HOST=$CLONE_DB_HOST"
echo "e-upgrader CLONE_DB_USER=$CLONE_DB_USER"
echo "e-upgrader CLONE_DB_PW=$CLONE_DB_PW"
echo "e-upgrader DEPLOY_DB=$DEPLOY_DB"
echo "e-upgrader LOCK_TABLES_ON_CLONE=$LOCK_TABLES_ON_CLONE"
echo "The dashboard name is ${DASHBOARD_NAME}. Checking !OPTIND value ${!OPTIND}."
if [[ ${!OPTIND} != false ]]; then
echo "Setting dashboard name from ${DASHBOARD_NAME} to ${!OPTIND} "
DASHBOARD_NAME=${!OPTIND}
fi
echo "Upgrading $DASHBOARD_NAME to tag $TAG_NAME"
if [[ $CLONE_DASHBOARD != "" ]]; then
echo "From clone of $CLONE_DASHBOARD ($CLONE_DB_HOST)"
fi
DIR_NAME=`echo $DASHBOARD_NAME | tr A-Z a-z | sed "s/dashboard/-dashboard/"`
CLONE_DASHBOARD_DIR=`echo $CLONE_DASHBOARD | tr A-Z a-z | sed "s/dashboard/-dashboard/"`
cd $DIR_NAME || die "$DIR_NAME does not exist"
# load existing config
source base-dashboard.properties
export DB_NAME=${schema_name}
export DB_HOST=${dbHost}
export DB_USER=`grep username conf/Catalina/localhost/dashboard.xml | sed s/\"\//g | sed s/username\=//`
export DB_PW=`grep password conf/Catalina/localhost/dashboard.xml | sed s/\"\//g | sed s/password\=//`
# Shutdown
cd bin || die "bin does not exist"
./shutdown.sh
cd ..
# setup ssh-agent
eval `ssh-agent`
ssh-add /home/naehas/.au/id_rsa
if [[ "$TAG_NAME" != "trunk" ]]; then
TAG_NAME="tags/$TAG_NAME"
fi
svn info svn+ssh://svn.naehas.com/home/svn/repository/base-dashboard/$TAG_NAME > SVN_INFO
# clean up old directories to handle files deleted in the new version
# we don't remove everything because we want to keep logs, downloads, etc.
rm -rf bin
rm -rf conf
rm -rf endorsed
rm -rf lib
rm -rf scripts
rm -rf src
rm -f webapps/dashboard/*
rm -rf webapps/dashboard/resources
rm -rf webapps/dashboard/scripts
rm -rf webapps/dashboard/styles
rm -f webapps/dashboard/WEB-INF/*
rm -rf webapps/dashboard/WEB-INF/lib
rm -rf webapps/dashboard/WEB-INF/classes
rm -rf webapps/dashboard/WEB-INF/build
rm -rf webapps/dashboard/WEB-INF/jsp
rm -rf webapps/dashboard/WEB-INF/lib
rm -rf webapps/dashboard/WEB-INF/messages
rm -rf webapps/dashboard/WEB-INF/tiles
rm -rf work
# svn export
svn export svn+ssh://svn.naehas.com/home/svn/repository/base-dashboard/$TAG_NAME . --force
# override scripts since it might be outdated FRED-19118
echo "Overriding scripts since they might be outdated on older tags FRED-19118"
svn export svn+ssh://svn.naehas.com/home/svn/repository/base-dashboard/trunk/scripts/create-first-campaign scripts/create-first-campaign --force
svn export svn+ssh://svn.naehas.com/home/svn/repository/base-dashboard/trunk/scripts/make-base-config scripts/make-base-config --force
svn export svn+ssh://svn.naehas.com/home/svn/repository/base-dashboard/trunk/setup setup --force
if [[ $CLONE_DASHBOARD != "" ]]; then
# clone customizations
../e-cloner-copy.sh
./customize -clone:$CLONE_DASHBOARD_DIR
fi
if [[ $CLONE_DASHBOARD != "" ]]; then
../e-cloner-load.sh
fi
./setup -n
cd /usr/java;
./setup_newrelic.sh $DIR_NAME
cd $DIR_NAME
# startup
cd bin
ps aux | grep $DIR_NAME
BUILD_ID=dontKillDashboard ./startup.sh
cd ..
sleep 60
#cleanup
ssh-agent -k
|
Markdown
|
UTF-8
| 5,875
| 3.4375
| 3
|
[] |
no_license
|
# Java基础系列10: 回调机制
本文是作者的读书笔记和心得整理,部分内容来源于网络,如有侵权,请联系作者。
## 几种调用机制
### 同步调用
同步调用是最基本并且最简单的一种调用方式,类A的方法a()调用类B的方法b(),一直等待b()方法执行完毕,a()方法继续往下走。这种调用方式适用于方法b()执行时间不长的情况,因为b()方法执行时间一长或者直接阻塞的话,a()方法的余下代码是无法执行下去的,这样会造成整个流程的阻塞
### 异步调用
类A的方法a()通过新建立一个线程的方式调用类B的方法b(),代码继续往后执行.
这种方法不确定什么时候能拿到b返回的结果,所以需要监听b
### 回调
回调的定义:A调用B执行一个任务,B执行完之后又调用A继续执行.
往往使用在多线程中,可以使用callable和future或者futuretask结合来获取线程执行之后的返回值
以下例子来源于https://how2playlife.com/2019/09/11/11%E8%A7%A3%E8%AF%BBJava%E4%B8%AD%E7%9A%84%E5%9B%9E%E8%B0%83/
一个简单的例子:
小明和小李相约一起去吃早饭,但是小李起的有点晚要先洗漱,等小李洗漱完成后,通知小明再一起去吃饭。小明就是类A,小李就是类B。一起去吃饭这个事件就是方法a(),小李去洗漱就是方法b()。
进阶例子:
小明和小李相约一起去吃早饭,但是小李起的有点晚要先洗漱,等小李洗漱完成后,通知小明再一起去吃饭,或者和小王去上网。小明就是类A,小李就是类B。不同的是我们新建一个吃饭的接口EatRice,接口中有个抽象方法eat()。在小明中调用这个接口,并实现eat();小李声明这个接口对象,并且调用这个接口的抽象方法。
和小王去上网的代码
```
public class XiaoWang implements EatRice{//小王
//小王和小李一起去上网
public void eatFood() {
XiaoLi xl = new XiaoLi();
//A调用B的方法
xl.washFace("轻舞飞扬上网", this);
}
@Override
public void eat(String bar) {
// TODO Auto-generated method stub
System.out.println("小王和小李一起去" + bar);
}
}
```
再看一个学生做题的例子:
数学老师让Tom做一道题,并且Tom做题期间数学老师不用盯着Tom,而是在玩手机,等Tom把题目做完后再把答案告诉老师。
这个过程可以分为3步:
数学老师使用Tom的引用,把题目发给tom
tom做题,然后使用老师的引用,调用老师的一个callback方法,把答案告诉这位老师,或者告诉其他老师.
所以每位老师都需要实现一个callback接口,以便接收学生的答案
```
//回调指的是A调用B来做一件事,B做完以后将结果告诉给A,这期间A可以做别的事情。
//这个接口中有一个方法,意为B做完题目后告诉A时使用的方法。
//所以我们必须提供这个接口以便让B来回调。
//回调接口,
public interface CallBack {
void tellAnswer(int res);
}
```
老师代码:
```
//老师类实例化回调接口,即学生写完题目之后通过老师的提供的方法进行回调。
//那么学生如何调用到老师的方法呢,只要在学生类的方法中传入老师的引用即可。
//而老师需要指定学生答题,所以也要传入学生的实例。
public class Teacher implements CallBack{
private Student student;
Teacher(Student student) {
this.student = student;
}
void askProblem (Student student, Teacher teacher) {
//main方法是主线程运行,为了实现异步回调,这里开启一个线程来操作
new Thread(new Runnable() {
@Override
public void run() {
student.resolveProblem(teacher);
}
}).start();
//老师让学生做题以后,等待学生回答的这段时间,可以做别的事,比如玩手机.\
//而不需要同步等待,这就是回调的好处。
//当然你可以说开启一个线程让学生做题就行了,但是这样无法让学生通知老师。
//需要另外的机制去实现通知过程。
// 当然,多线程中的future和callable也可以实现数据获取的功能。
for (int i = 1;i < 4;i ++) {
System.out.println("等学生回答问题的时候老师玩了 " + i + "秒的手机");
}
}
@Override
public void tellAnswer(int res) {
System.out.println("the answer is " + res);
}
}
```
学生代码:
```
//学生的接口,解决问题的方法中要传入老师的引用,否则无法完成对具体实例的回调。
//写为接口的好处就是,很多个学生都可以实现这个接口,并且老师在提问题时可以通过
//传入List<Student>来聚合学生,十分方便。
public interface Student {
void resolveProblem (Teacher teacher);
}
public class Tom implements Student{
@Override
public void resolveProblem(Teacher teacher) {
try {
//学生思考了3秒后得到了答案,通过老师提供的回调方法告诉老师。
Thread.sleep(3000);
System.out.println("work out");
teacher.tellAnswer(111);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
```
测试代码:
```
public class Test {
public static void main(String[] args) {
//测试
Student tom = new Tom();
Teacher lee = new Teacher(tom);
lee.askProblem(tom, lee);
//结果
// 等学生回答问题的时候老师玩了 1秒的手机
// 等学生回答问题的时候老师玩了 2秒的手机
// 等学生回答问题的时候老师玩了 3秒的手机
// work out
// the answer is 111
}
}
```
|
C++
|
UTF-8
| 894
| 3.140625
| 3
|
[] |
no_license
|
#include <bitset>
#include <iostream>
#include <set>
#include <vector>
using namespace std;
inline int odd(int x) { return bitset<12>(x).count() % 2; }
int main() {
int t;
cin >> t;
for (int case_num = 1; case_num <= t; ++case_num) {
cout << "Case #" << case_num << ": ";
int n, q;
cin >> n >> q;
vector<int> a(n);
set<int> odds;
int tot = 0;
for (int i = 0; i < n; ++i) {
int ai;
cin >> ai;
a[i] = odd(ai);
tot += a[i];
if (a[i])
odds.insert(i);
}
for (int i = 0; i < q; ++i) {
int p, v;
cin >> p >> v;
int new_val = odd(v);
tot += new_val - a[p];
if (a[p])
odds.erase(p);
if (new_val)
odds.insert(p);
a[p] = new_val;
int ans = tot % 2 == 0 ? n : max(*odds.rbegin(), n - *odds.begin() - 1);
cout << ans << " ";
}
cout << endl;
}
}
|
JavaScript
|
UTF-8
| 5,442
| 3.453125
| 3
|
[] |
no_license
|
// 利用scheduler 调度器来控制副作用函数的执行时机和方式、
// 用全局变量存储被注册的副作用函数
let activeEffect
const effectStack = []
const bucket = new WeakMap()
const data = {foo: 1, bar: 2}
const obj = new Proxy(data, {
get(target, key) {
track(target, key)
return target[key]
},
set(target, key, newVal) {
target[key] = newVal
trigger(target, key)
}
})
function cleanup(effectFn) {
for(let i = 0; i < effectFn.deps.length; i++) {
// deps是依赖集合
const deps = effectFn.deps[i]
// 将effectFn从依赖集合中移除
deps.delete(effectFn)
}
effectFn.deps.length = 0
}
// 用于注册副作用函数
function effect(fn, options = {}) {
const effectFn = () => {
// 调用cleanup函数完成清除工作
cleanup(effectFn)
activeEffect = effectFn
effectStack.push(effectFn)
// 将fn的执行结果存储到res中
const res = fn()
effectStack.pop()
activeEffect = effectStack[effectStack.length - 1]
return res
}
// 讲options挂载到effectFn上
effectFn.options = options
// 用来存储所有与该副作用函数相关联的依赖集合
effectFn.deps = []
// 只有非lazy的时候,才执行
if (!options.lazy) {
// 执行副作用函数
effectFn()
}
// 将副作用函数作为返回值返回
return effectFn
}
function track(target, key) {
if (!activeEffect) return
let depsMap = bucket.get(target)
if (!depsMap) {
bucket.set(target, (depsMap = new Map()))
}
let deps = depsMap.get(key)
if (!deps) {
depsMap.set(key, (deps = new Set()))
}
// 把当前激活的副作用函数添加到依赖集合deps中
deps.add(activeEffect)
// deps就是一个与当前副作用函数存在联系的依赖集合
activeEffect.deps.push(deps)
}
function trigger(target, key) {
const depsMap = bucket.get(target)
if (!depsMap) return
const effects = depsMap.get(key)
// 重新构造一个set集合并遍历它,防止无限循环执行
const effectsToRun = new Set()
effects && effects.forEach(effectFn => {
// 如果trigger触发执行的副作用函数与当前正在执行的副作用函数相同,则不触发执行
if (effectFn !== activeEffect) {
effectsToRun.add(effectFn)
}
})
effectsToRun.forEach(effectFn => {
if (effectFn.options.scheduler) {
console.log(123);
effectFn.options.scheduler(effectFn)
} else {
effectFn()
}
})
// 无限循环执行
// effects && effects.forEach(fn => fn())
}
// watch接收两个参数, source是响应式数据,cb是回调函数
function watch(source, cb, options) {
// 定义getter
let getter
// 如果source是函数,说明用户传递的是getter,所以直接把source赋值给getter
if (typeof source === 'function') {
getter = source
} else {
getter = () => traverse(source)
}
// 定义旧值和新值
let oldValue, newValue
// cleanup 用来存储用户注册的过期回调
let cleanup
// 定义 onInvalidate 函数
function onInvalidate(fn) {
// 将过期回调存储到cleanup中
cleanup = fn
}
// 提取scheduler调度函数为一个独立的job函数
const job = () => {
// 在scheduler中重新执行副作用函数,得到的是新值
newValue = effectFn()
// 在调用回调函数cb之前,先调用过期回调
if (cleanup) {
cleanup()
}
// 将onInvalidate作为回调函数的第三个参数,以便用户使用
// 当数据变化时,调用回调函数cb
// 将旧值和新值作为回调函数的参数
cb(newValue, oldValue, onInvalidate)
// 更新旧值,不然下一次会得到错误的旧值
oldValue = newValue
}
// 使用effect注册副作用函数时,开启lazy选项,并把返回值存储到effectFn中以便后续手动调用
const effectFn = effect(
// 执行getter
() => getter(),
{
lazy: true,
// 使用job函数作为调度器函数
scheduler: () => {
// 在调度函数中判断flush 是否为'post' 如果是,将其放到微任务队列中执行
if (options.flush === 'post') {
const p = Promise.resolve()
p.then(job)
} else {
job()
}
}
}
)
if(options.immediate) {
job()
} else {
// 手动调用副作用函数,拿到的值就是旧值
oldValue = effectFn()
}
}
function traverse(value, seen = new Set()) {
// 如果要读取的数据是原始值,或者已经被读取过了,那么什么都不做
if (typeof value !== 'object' || value === null || seen.has(value)) return
// 将数据添加到seen中,代表遍历地读取过了,避免循环引用引起的死循环
seen.add(value)
// 暂时不考虑数组等其他结构
// 假设value就是一个对象,使用for...in 读取对象的每一个值,并递归地调用traverse 进行处理
for(const k in value) {
traverse(value[k], seen)
}
return value
}
let finalData
watch(obj, async (newValue, oldValue, onInvalidate) => {
let expired = false
onInvalidate(() => {
expired = true
})
// 发送并等待网络请求
const res = await fetch('/path/to/request')
if (!expired) {
finalData = res
}
// 将请求结果赋值给data
finalData = res
})
// 修改响应数据的值,会导致回调函数执行
obj.foo++
setTimeout(() => {
obj.foo++
}, 200);
|
Python
|
UTF-8
| 1,415
| 3.125
| 3
|
[] |
no_license
|
#!/usr/bin/env python
# encoding: utf-8
# A sample for turnstile state
# for python 2.7 to python 3.4
state_table = {
"locked":{
"coin":{
"next_state": "unlocked",
"output": "Release turnstile so customer can push through"
},
"push":{
"next_state": "locked",
"output": None
}
},
"unlocked":{
"coin":{
"next_state": "unlocked",
"output": None
},
"push":{
"next_state": "locked",
"output": "When customer has pushed through lock turnstile"
}
}
}
def get_next_state(current_state, act):
print("current_state -> " + current_state + " , input -> " + act +":")
state_get = state_table.get(current_state)
if state_get and state_get.get(act):
print("output --> " + str(state_get.get(act).get("output")))
print("next_state --> " + state_get.get(act).get("next_state"))
return state_get.get(act).get("next_state")
else:
print("invalid current_state or input.")
return None
for current_state in ("locked", "unlocked", "unknown"):
for act in ("coin", "push", "unknown"):
get_next_state(current_state, act)
print("-----------------------------------------\n")
|
Java
|
UTF-8
| 228
| 1.640625
| 2
|
[] |
no_license
|
package com.liujia.config;
import lombok.Data;
/**
* @author ex_111806190
* @since 2020-9-21 16:35
*/
@Data
public class ConfigBean {
private String id;
public ConfigBean(String id) {
this.id = id;
}
}
|
PHP
|
UTF-8
| 2,348
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
<?php declare(strict_types=1);
namespace Imatic\Bundle\ViewBundle\Templating\Helper\Html;
use Imatic\Bundle\ViewBundle\Templating\Utils\StringUtil;
class HtmlElement
{
protected static $emptyElements = ['img' => 1, 'hr' => 1, 'br' => 1, 'input' => 1, 'meta' => 1, 'area' => 1, 'embed' => 1, 'keygen' => 1,
'source' => 1, 'base' => 1, 'col' => 1, 'link' => 1, 'param' => 1, 'basefont' => 1, 'frame' => 1, 'isindex' => 1, 'wbr' => 1, 'command' => 1, 'track' => 1, ];
/**
* @var ClassCollection
*/
protected $classes;
/**
* @var DataAttributeCollection
*/
protected $data;
/**
* @var AttributeCollection
*/
protected $attributes;
/**
* @var string
*/
protected $name;
/**
* @var mixed
*/
protected $value;
public function __construct($name, $value = null, array $attributes = [])
{
$this->setValue($value);
$this->name = \trim($name);
$this->attributes = new AttributeCollection($attributes);
$this->classes = new ClassCollection();
$this->data = new DataAttributeCollection();
}
public function create($name, $value = null, array $attributes = [])
{
return new static($name, $value, $attributes);
}
public function setValue($value)
{
$this->value = $value;
}
public function getValue()
{
return $this->value;
}
public function render()
{
$elementString = \trim(\implode(' ', [$this->attributes, $this->classes, $this->data]));
$elementString = \strlen($elementString) ? ' ' . $elementString : $elementString;
if ($this->value || !isset(self::$emptyElements[$this->name])) {
return \sprintf('<%s%s>%s</%s>', $this->name, $elementString, StringUtil::escape($this->value), $this->name);
}
return \sprintf('<%s%s>', $this->name, $elementString);
}
public function __get($name)
{
return $this->attributes->$name;
}
public function __set($name, $value)
{
$this->attributes->$name = $value;
}
public function classes()
{
return $this->classes;
}
public function data()
{
return $this->data;
}
public function __toString()
{
return (string) $this->render();
}
}
|
Java
|
UTF-8
| 744
| 2.5625
| 3
|
[] |
no_license
|
package org.mkab.chatapp.model;
public class Information {
private String title;
private String type;
private String fileName;
public Information(String title, String type, String fileName) {
super();
this.title = title;
this.type = type;
this.fileName = fileName;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
}
|
Java
|
UTF-8
| 1,222
| 2.234375
| 2
|
[] |
no_license
|
package com.caitou.bean;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Table(name="t_dyndata")
public class DynData {
@Id
@GeneratedValue(generator="JDBC")
private Integer id;
private String url;
private String title;
private Integer dynId;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Integer getDynId() {
return dynId;
}
public void setDynId(Integer dynId) {
this.dynId = dynId;
}
@Override
public String toString() {
return "DynData [id=" + id + ", url=" + url + ", title=" + title + ", dynId=" + dynId + "]";
}
public DynData(Integer id, String url, String title, Integer dynId) {
super();
this.id = id;
this.url = url;
this.title = title;
this.dynId = dynId;
}
public DynData() {
super();
// TODO Auto-generated constructor stub
}
}
|
Markdown
|
UTF-8
| 1,222
| 2.921875
| 3
|
[
"Apache-2.0",
"CC-BY-4.0"
] |
permissive
|
# Using DVC Commands
DVC is a command line tool. Here we provide the specifications, complete
descriptions, and comprehensive usage examples for `dvc` commands. For a list of
commands, type `dvc -h`.
💡 To execute any DVC command in a different directory, use
`dvc --cd <path> ...` before the actual command and it's options/arguments (this
does not change directories in your terminal).
## Typical DVC workflow
- In an existing Git repository, initialize a <abbr>DVC project</abbr> with
`dvc init`.
- Copy data files or dataset directories for modeling into the repository, and
track them with DVC using the `dvc add` command.
- Process the data with your own source code, using `dvc.yaml` and/or the
`dvc run` command, specifying further <abbr>outputs</abbr> that should also be
tracked by DVC after the code is executed.
- Sharing a <abbr>DVC repository</abbr> with the codified data
[pipeline](/doc/command-reference/dag) will not include the project's
<abbr>cache</abbr>. Use [remote storage](/doc/command-reference/remote) and
`dvc push` to share this cache (data tracked by DVC).
- Use `dvc repro` to automatically reproduce your full pipeline iteratively as
input data or source code change.
|
C#
|
UTF-8
| 591
| 2.75
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankDemo
{
// een abstracte class vind ik hier handiger want Deposit()/Withdraw() zijn hetzelfde bij de
// subclasses
// testbaarheid: unittests => interfaces komen hier ook veel terug
public interface IBankrekening
{
public string Iban { get; set; }
public long Saldo { get; }
public string Rekeninghouder { get; }
void Deposit(long amount);
void Withdraw(long amount);
void AddInterest(decimal interest);
void Buy(long price);
}
}
|
C#
|
UTF-8
| 563
| 4
| 4
|
[] |
no_license
|
//Write a program to convert binary numbers to hexadecimal numbers (directly).
using System;
class BinaryToHexadecimal
{
static void Main(string[] args)
{
Console.Write("Numbers: ");
int numbers = int.Parse(Console.ReadLine());
for (int i = 0; i < numbers; i++)
{
Console.Write("Binary: ");
string binary = Console.ReadLine();
string hexadecimal = Convert.ToString(Convert.ToInt32(binary, 2), 16);
Console.WriteLine("\tHexadecimal: " + hexadecimal);
}
}
}
|
Markdown
|
UTF-8
| 4,496
| 3.578125
| 4
|
[
"MIT",
"CC-BY-4.0"
] |
permissive
|
# createComponent
A HoC ([Higher-order Component](https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750#.njbld18x8)) that creates a presentational React component using the rendered `rule` as className.
It automatically composes rules and passed props for nested Fela components.
## Arguments
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
| rule | *Function*<br>*Object* | | Either a [style object](../basics/Rules.md#styleobject) or rule function which satisfies the [rule](../basics/Rules.md) behavior and returns a valid [style object](../basics/Rules.md#styleobject). |
| type | *string?*<br>*[Component](https://facebook.github.io/react/docs/top-level-api.html#react.component)?* | `div` | Component or HTML element which is used as the render base element.<br>**Note**: If a Component is passed, then it receives a className property. |
| passThroughProps | *Array?*<br>*Function?* | | A list of props that get passed to the underlying element.<br>Alternatively a function of `props` that returns an array of prop names. |
## Returns
(*Function*): Stateless functional component.
## Imports
```javascript
import { createComponent } from 'react-fela'
import { createComponent } from 'preact-fela'
import { createComponent } from 'inferno-fela'
```
## Example
```javascript
const title = ({ small, fontSize, color }) => ({
lineHeight: small ? 1.2 : 1.5,
fontSize: fontSize + 'px',
color: color
})
const Title = createComponent(title, 'div', [ 'onClick' ])
<Title fontSize={23} color="red" onClick={...}>Hello World</Title>
// <div className="a b c" onclick="...">Hello World</div>
```
## Passing Props
Using the `passThroughProps` parameter allows us to pass props to the underlying DOM element. This is helpful if you want to pass e.g. events such as `onClick`. There are some props that are automatically passed and thus do not need to be specified explicitly:
* `className`
* `style`
* `id`
If passing a className, it will automatically be concatenated with the Fela generated className. This allows composing multiple Fela Components.
#### Functional passThroughProps
You may also pass a function of `props` as `passThroughProps`. It must return an array of prop names. e.g. to pass all props you can do:
```javascript
const Title = createComponent(title, 'div', props => Object.keys(props))
// shorthand
const Title = createComponent(title, 'div', Object.keys)
```
> **Note**: The same can be achieved via [createComponentWithProxy](https://github.com/rofrischmann/fela/blob/master/packages/react-fela/docs/createComponentWithProxy.md#createcomponentwithproxyrule-type-passthroughprops).
#### Dynamically passing Props
This use case is especially important for library owners. Instead of passing the `passThroughProps` to the `createComponent` call directly, one can also use the `passThrough` prop on the created component to achieve the same effect.
```javascript
const title = () => ({
color: 'red'
})
const Title = createComponent(title)
<Title onClick={...} passThrough={[ 'onClick' ]}>Hello World</Title>
// => <div className="a" onclick="...">Hello World</div>
```
#### Extending Styles
It's possible to extend component styles with an `extend` prop that can be either an object or a function.
```javascript
const title = () => ({
color: 'red'
})
const Title = createComponent(title)
<Title extend={{ color: 'blue' }}>Hello World</Title>,
// => <div className="a">Hello World</div>
// => .a { color: blue }
const extendTitle = props => ({
color: props.color
})
<Title extend={extendTitle} color="green">Hello World</Title>
// => <div className="a">Hello World</div>
// => .a { color: green }
```
## Custom Type on Runtime
To change the `type` on runtime and/or for each component, you may use the `as` prop.
```javascript
const title = props => ({
color: 'red'
})
const Title = createComponent(title)
<Title as="h1">Hello World</Title>
// => <h1 className="a">Hello World</h1>
```
## Static Style Object
Instead of rendering a props-depending rule, we can also use plain objects to render static style objects.
```javascript
const style = {
fontSize: '15px',
color: 'red'
}
const Title = createComponent(style, 'h1')
<Title>Hello World</Title>
// => <h1 className="a b">Hello World</h1>
```
## Related
- [Recipe - Explicit Component displayName](../../recipes/DisplayNameComponents.md)
- [API Reference - `createComponentWithProxy`](createComponentWithProxy.md)
|
Python
|
UTF-8
| 1,047
| 3.625
| 4
|
[] |
no_license
|
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def upsideDownBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
def flip_tree(node):
if not node.left:
return node, node
new_root, new_rightmost = flip_tree(node.left)
new_rightmost.left, new_rightmost.right, node.left, node.right = (
node.right, node, None, None)
return new_root, new_rightmost.right
if root:
root, _ = flip_tree(root)
return root
if __name__ == '__main__':
sol = Solution()
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root = sol.upsideDownBinaryTree(root)
print root.val, root.left.val, root.right.val
print root.right.left.val, root.right.right.val
|
Markdown
|
UTF-8
| 3,556
| 2.53125
| 3
|
[] |
no_license
|
<p align="center">
<img src="https://github.com/0x25/piTurtle/blob/master/piturtle.png" alt="piTurtle">
</p>
# piTurtle
automatic open remote shell on an internal network with raspberryPI
# need
- stunnel
- ssh
- vps or server on internet
- raspberry
# subject
Create a stunnel connection (ssl 443) to the a server on internet and the open a remote shell inside the stunnel connection with SSH.
<p align="center">
<img src="https://github.com/0x25/piTurtle/blob/master/netDiagram.png" alt="net diagram">
</p>
# stunnel
install stunnel4 on both rpi and server
```# sudo apt-get update
sudo apt-get install stunnel4
```
##### Configure server side (server)
enable service
```
sudo nano /etc/default/stunnel4
```
> ENABLE=1
Generate certificat
```
cd /etc/stunnel
openssl genrsa -out KeyServer.key 2048
openssl req -new -key KeyServer.key -out certif.csr
openssl x509 -req -days 3650 -in certif.csr -signkey KeyServer.key -out certserver.crt
cat KeyServer.key certserver.crt > server.pem
```
configure stunnel.conf
```
mv stunnel.conf stunnel.conf.bkp
nano stunnel.conf
```
>; It is recommended to drop root privileges if stunnel is started by root
>chroot = /var/lib/stunnel4/
>setuid = stunnel4
>setgid = stunnel4
>
>; PID file is created inside the chroot jail (if enabled)
>pid = /stunnel.pid
>; pid = /stunnel.pid
>
>; Debugging stuff (may be useful for troubleshooting)
>foreground = yes
>debug = debug
>output = /var/log/stunnel4/stunnel.log
>
>; TLS front-end to a web server
>[https]
>accept = 443
>connect = 22
>cert=/etc/stunnel/server.pem
>key=/etc/stunnel/keyServer.key
will create a HTTPS service on port 443
view of the chroot
>cd /var/lib/stunnel4/
>/var/lib/stunnel4$ tree
>.
>├── stunnel.pid
>└── var
> ├── log
> │ └── stunnel4
> │ └── stunnel.log
> └── run
>
>4 directories, 2 files
Start stunnel on boot service
```
chkconfig stunnel4 on
/etc/init.d/stunnel4 start
```
check port (normally 443 is up)
```
sudo netstat -tanlp | grep stunnel
```
##### Configure rpi side (client)
upload server.pem on /etc/stunnel/
```
sudo nano /etc/stunnel/stunnel.conf
```
>debug = info
>output = /var/log/stunnel.log
>
>cert = /etc/stunnel/server.pem
>pid = /var/run/stunnel.pid
>client = yes
>
>[ssh]
>accept = 127.0.0.1:2222
>connect = <Ip or domain>:443
Start stunnel
```
stunnel /etc/stunnel/stunnel.conf
```
Check if stunnel is up
```
sudo netstat -tanlp | grep stunnel
```
now SSH is listen on 2222 and go up stunnel
# Create reverse shell \o/
##### On the rpi
Create a user and a ssh key on RPI
```
useradd remote
cd /home/remote/.ssh/
ssh-keygen -f remote -P ""
```
2 files is created (private (remote) key stay on the RPI and remote.pub to DL on the server)
##### On the server
```
useradd remote
```
copy remote.pub in /home/remote/.ssh/
Edit the ssh conf to allow authentification with key (/etc/ssh/sshd_config)
>PasswordAuthentication no
>AuthenticationMethods publickey
##### On the rpi
start ssh reverse shell
```
ssh -i /home/remote/.ssh/remote -R 2201:localhost:22 -p 2222 remote@localhost -f -N
```
and normally on the server a port is open localhost:2201 and you can ssh to it
>netstat -tanlp | grep 2201
>tcp 0 0 127.0.0.1:2201 0.0.0.0:* LISTEN >24227/sshd: remote
##### my crontab
>*/2 * * * * /opt/remoteShell/check.sh >> /opt/remoteShell/cron.log
|
Python
|
UTF-8
| 566
| 3
| 3
|
[] |
no_license
|
import csv
import json
def csvToJson(file):
out = []
with open(file) as f:
reader = csv.DictReader(f)
for row in reader:
out.append(row)
return out
def writeToFile(data, filename):
file = open(filename, "w")
file.write(json.dumps(data))
file.close()
def generateFromCsv(filenames):
for filename in filenames:
data = csvToJson(filename + ".csv")
writeToFile(data, filename + ".json")
if __name__ == "__main__":
filenames = ['../data/MAF_Served_Airstrips']
generateFromCsv(filenames)
|
Python
|
UTF-8
| 341
| 3.5
| 4
|
[
"MIT"
] |
permissive
|
class Accumulator:
"""Sum a list of numbers over time."""
def __init__(self, n):
self.data = [0.0] * n
def add(self, *args):
self.data = [a+float(b) for a, b in zip(self.data, args)]
def reset(self):
self.data = [0.0] * len(self.data)
def __getitem__(self, idx):
return self.data[idx]
|
Python
|
UTF-8
| 2,699
| 3.765625
| 4
|
[] |
no_license
|
import matplotlib.pyplot as plt #Para visualizacao dos dados e do erro
import numpy as np #Biblioteca de manipulacao de arrays Numpy
from matplotlib.colors import ListedColormap #Lista de cores para plotagens
import pandas as pd
### Carregar iris dataset
df = pd.read_csv("/home/davi/Área de Trabalho/workspace/logatti/Linguagens de programação/extracao-dados/Dados_Treinamento_Sinal.csv",encoding = "ISO-8859-1")
df.head()
X = df.iloc[0:10,[0,1,2,3]].values
y = df.iloc[0:10,4].values
print(X)
print("Y:", y)
### Assumindo que Setosa(0) seja -1 e Versicolor = 1
### Plotar o grafico
### vermelhos ----> Classe2 (-1)
### azuis ----> Classe1 (1)
cm_bright = ListedColormap(['#FF0000', '#0000FF'])
plt.figure(figsize=(7,5))
plt.scatter(X[:,0], X[:,1], c=y, cmap=cm_bright)
plt.scatter(None, None, color = 'r', label='Classe1')
plt.scatter(None, None, color = 'b', label='Classe2')
plt.legend()
plt.title('Visualizacao do Dataset')
plt.show()
###Construindo Adaline
class Adaline(object):
def __init__(self, eta = 0.001, epoch = 100):
self.eta = eta
self.epoch = epoch
def fit(self, X, y):
np.random.seed(16)
self.weight_ = np.random.uniform(-1, 1, X.shape[1] + 1)
self.error_ = []
cost = 0
for _ in range(self.epoch):
output = self.activation_function(X)
error = y - output
self.weight_[0] += self.eta * sum(error)
self.weight_[1:] += self.eta * X.T.dot(error)
cost = 1./2 * sum((error**2))
self.error_.append(cost)
return self
def net_input(self, X):
"""Calculo da entrada z"""
return np.dot(X, self.weight_[1:]) + self.weight_[0]
def activation_function(self, X):
"""Calculo da saida da funcao g(z)"""
return self.net_input(X)
def predict(self, X):
"""Retornar valores binaros 0 ou 1"""
return np.where(self.activation_function(X) >= 0.0, 1, -1)
###Plotando erros apos 100 epocas
names = ['Taxa de Aprendizado = 0.001', 'Taxa de Aprendizado = 0.01']
classifiers = [Adaline(), Adaline(eta = 0.01)]
step = 1
plt.figure(figsize=(14,5))
for name, classifier in zip(names, classifiers):
ax = plt.subplot(1, 2, step)
clf = classifier.fit(X, y)
ax.plot(range(len(clf.error_)), clf.error_)
ax.set_ylabel('Error')
ax.set_xlabel('Epoch')
ax.set_title(name)
step += 1
plt.show()
### Plotando as fronteiras de decisao com Adaline
clf = Adaline()
clf.fit(X, y)
A = [0.4329,-1.3719,0.7022,-0.8535] # Classe 1
B = [0.3024,0.2286,0.8630,2.7909] #Classe -1
print (clf.predict(A))
print (clf.predict(B))
|
Python
|
UTF-8
| 216
| 3.25
| 3
|
[] |
no_license
|
# This is practice using nested conditionals
def binomial_coeff(n, k):
return 1 if k == 0
return 0 if n == 0
res = binomial_coeff(n-1, k) + binomial_coeff(n-1, k-1)
return res
binomial_coeff(0, 1)
|
Java
|
UTF-8
| 4,328
| 2.015625
| 2
|
[] |
no_license
|
package com.tw.controller;
import com.tw.common.base.AppResultBuilder;
import com.tw.common.base.ResponseObject;
import com.tw.helper.Page;
import com.tw.model.Goods;
import com.tw.model.GoodsGallery;
import com.tw.model.GoodsSku;
import com.tw.model.GoodsSkuCompose;
import com.tw.service.ApiAttributeService;
import com.tw.service.ApiGoodsGalleryService;
import com.tw.service.ApiGoodsService;
import com.tw.service.ApiGoodsSkuService;
import com.tw.view.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by aisiA on 2019/4/17.
*/
@RestController
@EnableAutoConfiguration
@RequestMapping(value = "/api/goods", produces = "application/json; charset=utf-8")
@Api(value = "分类接口", description = "分类接口")
@CrossOrigin(origins = "*", methods = {RequestMethod.POST})
public class ApiGoodsController {
private final static Logger logger = LoggerFactory.getLogger(ApiGoodsController.class);
@Autowired
private ApiGoodsService apiGoodsService;
@Autowired
private ApiGoodsGalleryService apiGoodsGalleryService;
@Autowired
private ApiAttributeService apiAttributeService;
@Autowired
private ApiGoodsSkuService apiGoodsSkuService;
@ResponseBody
@RequestMapping(value = "/count", method = RequestMethod.POST)
@ApiOperation(value = "总数")
public ResponseObject<?> count(
){
GoodsSearchView goodsSearchView=new GoodsSearchView();
goodsSearchView.setOnlineStatus("1");
long count=apiGoodsService.countGoodsListBySearch(goodsSearchView);
Map<String, Object> resultObj = new HashMap();
resultObj.put("goodsCount", count);
return AppResultBuilder.success(resultObj);
}
@ResponseBody
@RequestMapping(value = "/detail", method = RequestMethod.POST)
@ApiOperation(value = "详情")
public ResponseObject<?> detail( @ApiParam(required = true, value = "ID") @RequestParam(required = true) String id
){
Goods info=apiGoodsService.selectGoodsById(id);
List<GoodsGallery> gallery=apiGoodsGalleryService.selectGoodsGalleryList(id);
List<GoodsAttributeView> attribute=apiAttributeService.selectGoodsAttributeView(id);
List<SkuView> specificationList=apiGoodsSkuService.selectSkuViewList(id);
List<GoodsSku> productList=apiGoodsSkuService.selectGoodsSkuList(id);
Map<String, Object> resultObj = new HashMap();
resultObj.put("info", info);
resultObj.put("gallery", gallery);
resultObj.put("attribute", attribute);
resultObj.put("specificationList", specificationList);
resultObj.put("productList", productList);
return AppResultBuilder.success(resultObj);
}
@ResponseBody
@RequestMapping(value = "/selectGoodsDetail", method = RequestMethod.POST)
@ApiOperation(value = "根据sku查询商品信息")
public GoodsView selectGoodsDetail( @ApiParam(required = true, value = "goodsId") @RequestParam(required = true) String goodsId,
@ApiParam(required = true, value = "skuId") @RequestParam(required = true) String skuId
){
GoodsView goodsView=new GoodsView();
Goods info=apiGoodsService.selectGoodsById(goodsId);
GoodsSku productInfo=apiGoodsSkuService.selectGoodsSkuById(skuId);
if(info!=null){
goodsView.setGoodsCode(info.getGoodsCode());
goodsView.setGoodsId(info.getGoodsId());
goodsView.setGoodsImgUrl(info.getGoodsImg());
goodsView.setGoodsName(info.getGoodsName());
goodsView.setLabelPrice(info.getLabelPrice());
goodsView.setMarketPrice(info.getMarketPrice());
goodsView.setStorageNum(info.getStorageNum());
}
if(productInfo!=null){
goodsView.setSkuId(productInfo.getSkuId());
goodsView.setSkuValueText(productInfo.getSkuName());
}
return goodsView;
}
}
|
C++
|
UTF-8
| 5,945
| 2.625
| 3
|
[] |
no_license
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->lineEdit->setText("");
ui->lineEdit_2->setText("");
ui->lineEdit_3->setText("");
ui->lineEdit->setVisible(true);
ui->lineEdit_2->setVisible(true);
ui->lineEdit_3->setVisible(false);
ui->label_2->setVisible(false);
ui->label_3->setText("Название магазина:");
ui->label_3->setVisible(true);
ui->label_4->setText("Номер чека:");
ui->label_4->setVisible(true);
ui->label_5->setText("");
ui->label_5->setVisible(false);
ui->spinBox->setVisible(false);
this->setWindowTitle("Check");
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
int value = ui->comboBox->currentIndex();
try
{
switch (value)
{
case 0: //name, number
{
check.setMarketName(String(ui->lineEdit->text().toStdString().c_str()));
check.setNumber(String(ui->lineEdit_2->text().toStdString().c_str()));
ui->textBrowser->setText("Название магазина и номер чека установлены.");
break;
}
case 1: //add
{
Product product(String(ui->lineEdit->text().toStdString().c_str()), ui->lineEdit_2->text().toInt(), ui->lineEdit_3->text().toInt());
size_t number = ui->spinBox->value();
for(size_t i = 0; i < number; i++)
check.addProduct(product);
ui->textBrowser->setText("Добавлен продукт.");
break;
}
case 2: //delete
{
check.deleteProduct(ui->lineEdit_3->text().toInt());
ui->textBrowser->setText("Удален продукт.");
break;
}
case 3: //info
{
QString buffer;
char* str;
buffer.append("Название магазина:");
str = check.getMarketName().getString();
buffer.append(str);
buffer.append("\n");
buffer.append("Номер:");
str = check.getNumber().getString();
buffer.append(str);
buffer.append("\n");
buffer.append("Количество продуктов:");
buffer.append(QString::number(check.getAmountProducts()));
buffer.append("\n");
buffer.append("Список продуктов:\n");
size_t number =check.getAmountProducts();
for(size_t i = 0; i < number; i++)
{
str = check[i].getName().getString();
buffer.append(str);
delete str;
buffer.append(" ");
buffer.append(QString::number(check[i].getCost()));
buffer.append(" ");
buffer.append(QString::number(check[i].getProductCode()));
buffer.append("\n");
}
buffer.append("Сумма:");
buffer.append(QString::number(check.getSum()));
ui->textBrowser->setText(buffer);
break;
}
}
} catch (invalid_argument arg)
{
ui->textBrowser->setText(tr("Ошибка"));
}
}
void MainWindow::on_comboBox_currentIndexChanged(int index)
{
switch (index)
{
case 0:
{
ui->lineEdit->setText("");
ui->lineEdit_2->setText("");
ui->lineEdit_3->setText("");
ui->lineEdit->setVisible(true);
ui->lineEdit_2->setVisible(true);
ui->lineEdit_3->setVisible(false);
ui->label_2->setVisible(false);
ui->label_3->setText("Название магазина:");
ui->label_3->setVisible(true);
ui->label_4->setText("Номер чека:");
ui->label_4->setVisible(true);
ui->label_5->setText("");
ui->label_5->setVisible(false);
ui->spinBox->setVisible(false);
break;
}
case 1:
{
ui->lineEdit->setText("");
ui->lineEdit_2->setText("");
ui->lineEdit_3->setText("");
ui->lineEdit->setVisible(true);
ui->lineEdit_2->setVisible(true);
ui->lineEdit_3->setVisible(true);
ui->label_2->setVisible(true);
ui->label_3->setText("Название продукта:");
ui->label_4->setText("Цена:");
ui->label_5->setText("Код товара:");
ui->label_3->setVisible(true);
ui->label_4->setVisible(true);
ui->label_5->setVisible(true);
ui->spinBox->setVisible(true);
break;
}
case 2:
{
ui->lineEdit->setText("");
ui->lineEdit_2->setText("");
ui->lineEdit_3->setText("");
ui->lineEdit->setVisible(true);
ui->lineEdit_2->setVisible(true);
ui->lineEdit_3->setVisible(false);
ui->label_2->setVisible(false);
ui->label_3->setText("Название магазина:");
ui->label_4->setText("Номер чека:");
ui->label_5->setText("");
ui->label_3->setVisible(true);
ui->label_4->setVisible(true);
ui->label_5->setVisible(false);
ui->spinBox->setVisible(false);
break;
}
case 3:
{
ui->lineEdit->setText("");
ui->lineEdit_2->setText("");
ui->lineEdit_3->setText("");
ui->lineEdit->setVisible(false);
ui->lineEdit_2->setVisible(false);
ui->lineEdit_3->setVisible(false);
ui->label_2->setVisible(false);
ui->label_3->setText("");
ui->label_4->setText("");
ui->label_5->setText("");
ui->label_3->setVisible(false);
ui->label_4->setVisible(false);
ui->label_5->setVisible(false);
ui->spinBox->setVisible(false);
break;
}
}
}
|
C++
|
UTF-8
| 1,323
| 3.6875
| 4
|
[] |
no_license
|
#include <iostream>
#include <conio.h>
#include <iomanip>
#include <fstream>
#include <new>
using namespace std;
int main()
{
//Local Variables for main
int ArraySize = 0;
int Total = 0;
//Ask user how big the array is going to be
cout << "How many numbers do you wish to enter? (Whole numbers only): ";
cin >> ArraySize;
cout << endl;
//Create the array
int *arrNumbers = new int[ArraySize];
//Set array size to the number the user selected
//arrNumbers[ArraySize];
//For loop to assign values to array
for (int i = 0; i < ArraySize; i++)
{
cout << "Please enter " << i << " number: ";
cin >> arrNumbers[i];
}
//Create a space before output
cout << endl;
//First output line
cout << "Your Array of numbers is: ";
//For loop to display values to user
for (int i = 0; i < ArraySize; i++)
{
cout << arrNumbers[i] << " ";
Total += arrNumbers[i];
}
//Display total
cout << endl << "The total value of the numbers is " << Total << endl;
//Second output line
cout << endl << "Your Array of numbers in reversed order: ";
//For loop to display values to user
for (int i = ArraySize - 1; i >= 0; i--)
{
cout << arrNumbers[i] << " ";
}
//Delete array to free up memory
delete[] arrNumbers;
_getch();
return 0;
}
|
C++
|
UTF-8
| 1,009
| 3.046875
| 3
|
[] |
no_license
|
//nhap ma tran A mxn Bmxn tinh tong C=A+B
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void nhap(int*a,int m,int n)
{
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
{
printf("a[%d][%d]=",i,j);
scanf("%d",(a+n*i+j));
}
}
void xuat(int*a,int m,int n)
{ printf("ma tran vua nhap la:\n");
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
printf("%5d",*(a+n*i+j));
printf("\n");
}
}
void tong(int*a,int*b,int m,int n)
{ int*c;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
*(c+n*i+j)=*(a+n*i+j)+*(b+n*i+j);
printf("%5d", *(c+n*i+j));
}
printf("\n");
}}
int main()
{ int m,n;
printf("nhap so hang :");
scanf("%d",&m);
printf("nhap so cot: ");
scanf("%d",&n);
int *a=(int*)malloc(m*n*sizeof(int));
int *b=(int*)malloc(m*n*sizeof(int));
printf("nhap ma tran A:\n");
nhap(a,m,n);
xuat(a,m,n);
printf("nhap ma tran B:\n");
nhap(b,m,n);
xuat(b,m,n);
printf("tong 2 ma tran la:\n");
tong(a,b,m,n);
}
|
C++
|
ISO-8859-1
| 1,133
| 2.765625
| 3
|
[] |
no_license
|
#ifndef SCHACHBRETTANZEIGE_H
#define SCHACHBRETTANZEIGE_H
#include <vector>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include "Schachfeld.h"
#include "Zug.h"
using namespace std;
/**
Erzeugt das Schachbrett mit seinen 64 Schachfeldern und aktualisiert diese.
@author Arne Maier
*/
class SchachbrettAnzeige : public QObject
{
Q_OBJECT
private:
vector<Schachfeld*> schachFelder;
Schachfeld* feld;
Schachlogik* logik;
Zug* schachZug;
Schachfeld* erzeugeFeld(Position* position);
public:
/**
Erzeugt ein SchachbrettAnzeige Objekt.
@param logik Schachlogik die fr den Spielablauf verantwortlich ist.
@param schachZug Zug der die Bewegungen der Figuren auf dem Feld registriert.
*/
SchachbrettAnzeige(Schachlogik* logik, Zug* schachZug);
/**
Erzeugt ein horizontales Layout mit den 64 Schachfeldern.
*/
QVBoxLayout* initializeChessField();
/**
Aktualisiert die Schachfelder, sodass die aktuellen Figuren angezeigt werden.
*/
void aktualisiereSchachfeld();
~SchachbrettAnzeige();
public slots:
/**
Macht den letzten Zug rckgngig.
*/
void zugZurueck();
signals:
};
#endif // SCHACHBRETT_H
|
JavaScript
|
UTF-8
| 402
| 4.1875
| 4
|
[] |
no_license
|
/*Write a script that shows the sign (+, - or 0) of the product of three real numbers, without calculating it.
Use a sequence of if operators.*/
var a=-2;
var b=-2;
var c=1;
var product=a*b*c;
console.log('a='+a);
console.log('b='+b);
console.log('c='+c);
console.log('product='+product);
if(product>0){
console.log('+');
}
else if(product<0){
console.log('-');
}
else{
console.log('0');
}
|
C++
|
UTF-8
| 4,482
| 3.21875
| 3
|
[] |
no_license
|
#include <SFML/Graphics.hpp>
#include <iostream>
#include <string>
using namespace sf;
struct Cell {
bool isAlive;
int neighborCount;
RectangleShape Rect;
int Width;
int Height;
bool dirty;
Cell(int size = 16) {
Width = size;
Height = size;
std::cout << Width << " " << Height << std::endl;
Rect.setSize(sf::Vector2f((float)Width, (float)Height));
Rect.setFillColor(Color::Red);
Rect.setOutlineColor(Color::Black);
Rect.setOutlineThickness(1);
dirty = false;
}
void setCellPos(int x, int y) {
std::cout << x << " " << y << std::endl;
Rect.setPosition((float)x, (float)y);
}
void setRectSize(int w, int h) {
Rect.setSize(sf::Vector2f((float)w, (float)h));
}
void setCellColor(Color C) { Rect.setFillColor(C); }
};
struct Character {
sf::Sprite sprite;
sf::Texture texture;
Character(std::string file) {
texture.loadFromFile(file);
sprite.setTexture(texture);
sprite.setTextureRect(sf::IntRect(0, 0, 16, 16));
}
};
struct Grid {
int Width;
int Height;
int CellSize;
int CellWidth;
int CellHeight;
int NumRows;
int NumCols;
int PlayerRow;
int PlayerCol;
Character *c;
RenderWindow Window;
Cell*** World;
Grid(int width, int height, int cellsize) {
Width = width;
Height = height;
if (Width % cellsize != 0 || Height % cellsize != 0) {
std::cout << "Error: Grid's Width and Height must be divisible by "
"CellSize! Exiting..."
<< std::endl;
exit(0);
}
CellWidth = cellsize;
CellHeight = cellsize;
CellSize = cellsize;
NumRows = (float)Width / (float)CellHeight;
NumCols = (float)Height / (float)CellWidth;
// std::cout<<CellWidth<<" "<<CellHeight<<std::endl;
// std::cout<<NumRows<<" "<<NumCols<<std::endl;
Window.create(VideoMode(Width, Height), "Grid Example");
World = new Cell**[NumRows];
for (int i = 0; i < NumRows; i++) {
World[i] = new Cell*[NumCols];
for (int j = 0; j < NumCols; j++) {
World[i][j] = new Cell(CellSize);
World[i][j]->setCellPos(i * CellHeight, j * CellWidth);
World[i][j]->dirty = true;
}
}
c = new Character("person2_128.png");
}
void changeRandomCell() {
int r = rand() % NumRows;
int c = rand() % NumCols;
int i = rand() % 6;
World[r][c]->dirty = true;
switch (i) {
case 0:
World[r][c]->setCellColor(Color::Blue);
break;
case 1:
World[r][c]->setCellColor(Color::Cyan);
break;
case 2:
World[r][c]->setCellColor(Color::Green);
break;
case 3:
World[r][c]->setCellColor(Color::Magenta);
break;
case 4:
World[r][c]->setCellColor(Color::Red);
break;
case 5:
World[r][c]->setCellColor(Color::White);
break;
case 6:
World[r][c]->setCellColor(Color::Yellow);
break;
}
}
void setPlayerPosition(int r, int c) {
PlayerRow = r;
PlayerCol = c;
World[PlayerRow][PlayerCol]->setCellColor(Color::Blue);
World[PlayerRow][PlayerCol]->dirty = true;
}
void randomlyMove() {
World[PlayerRow][PlayerCol]->setCellColor(Color::Red);
World[PlayerRow][PlayerCol]->dirty = true;
if (rand() % 2 == 0) {
++PlayerRow;
} else {
--PlayerRow;
}
if (rand() % 2 == 0) {
++PlayerCol;
} else {
--PlayerCol;
}
World[PlayerRow][PlayerCol]->setCellColor(Color::Blue);
World[PlayerRow][PlayerCol]->dirty = true;
}
// void buildGrid(){
// sf::Vertex line[2];
// line[0].position = sf::Vector2f(10, 0);
// line[0].color = sf::Color::Red;
// line[1].position = sf::Vector2f(20, 0);
// line[1].color = sf::Color::Red;
// }
void drawGrid() {
Window.clear();
for (int i = 0; i < NumRows; i++) {
for (int j = 0; j < NumCols; j++) {
if (World[i][j]->dirty) {
Window.draw(World[i][j]->Rect);
World[i][j]->dirty = false;
}
}
}
Window.draw(c->sprite);
Window.display();
}
};
int main() {
Grid G(1040, 1040, 16);
int i = 0;
G.setPlayerPosition(50, 50);
while (G.Window.isOpen()) {
Event event;
while (G.Window.pollEvent(event)) {
if (event.type == Event::Closed) {
G.Window.close();
}
}
if (i % 1000 == 0) {
G.drawGrid();
G.randomlyMove();
}
++i;
}
return 0;
}
|
C++
|
UTF-8
| 12,622
| 3.09375
| 3
|
[] |
no_license
|
#include "bignumber.h"
BigNumber::BigNumber(uint64_t base, std::string value) : base_(base) {
if (value[0] == '-') {
value = value.substr(1, value.length() - 1);
sign_ = sign_flag::NEGATIVE;
} else sign_ = sign_flag::POSITIVE;
while (value.length() > static_cast<uint64_t>(log10(base))) {
value_.push_back(std::stoull(value.substr(value.length() - static_cast<uint64_t>(log10(base)),
static_cast<uint64_t>(log10(base)))));
value = value.substr(0, value.length() - static_cast<uint64_t>(log10(base)));
}
value_.push_back(std::stoull(value));
return;
}
BigNumber::BigNumber(double value) : base_(1e9), sign_(sign_flag::POSITIVE) {
value = floor(value);
if (value < kEps && value > -kEps) {
value_.push_back(0);
return;
}
if (value < 0) {
value *= -1;
sign_ = sign_flag::NEGATIVE;
}
while (value > kEps) {
value_.push_back(static_cast<uint64_t>(value - floor(value / base_) * base_));
value = floor(value / base_);
}
return;
}
BigNumber::BigNumber(const BigNumber& other) : base_(other.base_), value_(other.value_),
sign_(other.sign_) { return; }
std::string BigNumber::ToString() {
std::string output = "";
for (uint64_t i = 0; i < value_.size(); ++i) {
output = std::to_string(value_[i]) + output;
if (i != value_.size() - 1) {
for (uint64_t j = std::to_string(this->value_[i]).size();
j < static_cast<uint64_t>(log10(base_)); ++j) {
output = "0" + output;
}
}
}
if (sign_ == sign_flag::NEGATIVE) output = "-" + output;
return output;
}
double BigNumber::ToDouble() {
double result = 0.0;
for (uint64_t i = this->size() - 1; i > 0; --i) {
result += (*this)[i];
result *= this->base_;
}
result += (*this)[0];
if (this->sign_ == BigNumber::sign_flag::NEGATIVE) result *= -1.0;
return result;
}
BigNumber BigNumber::abs() {
BigNumber result = BigNumber(*this);
result.sign_ = sign_flag::POSITIVE;
return result;
}
uint64_t BigNumber::size() {
return this->value_.size();
}
void BigNumber::resize(uint64_t size, uint64_t value) {
this->value_.resize(size, value);
return;
}
void BigNumber::push_back(uint64_t value) {
this->value_.push_back(value);
return;
}
void BigNumber::pop_back() {
this->value_.pop_back();
return;
}
BigNumber BigNumber::pow(BigNumber base, BigNumber power) {
BigNumber result(1e9, "1");
BigNumber zero(1e9, "0");
BigNumber one(1e9, "1");
BigNumber two(1e9, "2");
if (power == zero) {
if (base == zero) throw "error: exponentiation result is NAN";
return one;
}
if (power < zero) {
if (base == zero) throw "error: division by zero";
return zero;
}
while (power > zero) {
if (power % two == one) {
result = result * base;
}
base = base * base;
power = power / two;
}
return result;
}
double BigNumber::pow(BigNumber base, double power) {
BigNumber zero(1e9, "0");
if (base < zero && !(power - floor(power) < kEps && power - floor(power) > -kEps)) {
throw "error: wrong exponentiation definition";
}
if (base == zero && power < kEps) throw "error: exponentiation result is NAN";
if (base < zero) return pow(base, static_cast<BigNumber>(power)).ToDouble();
else return std::pow(base.ToDouble(), power);
}
double BigNumber::pow(double base, BigNumber power) {
BigNumber zero(1e9, "0");
BigNumber one(1e9, "1");
BigNumber two(1e9, "2");
if (power == zero) {
if (base > -kEps && base < kEps) throw "error: exponentiation result is NAN";
return one;
}
if (power < zero) {
if (base < kEps && base > -kEps) throw "error: division by zero";
base = 1.0 / base;
power = -power;
}
double result = 1.0;
while (power > zero) {
if (power % two == one) result *= base;
base *= base;
power = power / two;
}
return result;
}
double BigNumber::pow(double base, double power) {
if ((power - floor(power) < kEps && power - floor(power) > -kEps)) {
return pow(base, BigNumber(power));
}
if (base < -kEps) throw "error: wrong exponentiation definition";
if (base > -kEps && base < kEps && power < kEps) throw "error: exponentiation result is NAN";
return std::pow(base, power);
}
void BigNumber::Swap(BigNumber &other) {
std::swap(this->base_, other.base_);
std::swap(this->sign_, other.sign_);
std::swap(this->value_, other.value_);
return;
}
uint64_t& BigNumber::operator[](uint64_t index) {
return this->value_[index];
}
bool BigNumber::operator ==(BigNumber other) {
if (this->size() == other.size() && this->sign_ == other.sign_) {
for (uint64_t i = 0; i < this->size(); ++i) {
if ((*this)[i] != other[i]) return false;
}
return true;
}
return false;
}
bool BigNumber::operator <(BigNumber other) {
if (this->sign_ != other.sign_) {
if (this->sign_ == BigNumber::sign_flag::NEGATIVE) return true;
return false;
}
if (this->sign_ == BigNumber::sign_flag::NEGATIVE && this->sign_ == other.sign_) {
return -other < -(*this);
}
if (this->size() < other.size()) return true;
if (this->size() > other.size()) return false;
for (uint64_t i = this->size() - 1; i > 0; --i) {
if ((*this)[i] > other[i]) return false;
else if ((*this)[i] < other[i]) return true;
}
if ((*this)[0] < other[0]) return true;
return false;
}
bool BigNumber::operator >(BigNumber other) {
return !(*this < other || *this == other);
}
bool BigNumber::operator !=(BigNumber other) {
return !(*this == other);
}
bool BigNumber::operator <=(BigNumber other) {
return !(*this > other);
}
bool BigNumber::operator >=(BigNumber other) {
return !(*this < other);
}
BigNumber operator -(BigNumber operand) {
operand.sign_ = static_cast<BigNumber::sign_flag>(static_cast<int>(operand.sign_) * (-1));
return operand;
}
BigNumber operator <<(BigNumber operand, uint64_t shift) {
operand.resize(operand.size() + shift);
for (uint64_t i = operand.size() - 1; i >= shift; --i) {
operand[i] = operand[i - shift];
}
for (uint64_t i = 0; i < shift; ++i) {
operand[i] = 0;
}
return operand;
}
BigNumber operator >>(BigNumber operand, uint64_t shift) {
for (uint64_t i = 0; i < operand.size() - shift; ++i) {
operand[i] = operand[i + shift];
}
operand.resize(operand.size() - shift);
return operand;
}
BigNumber operator +(BigNumber first, BigNumber second) {
BigNumber result(first.base_);
if (first.abs() < second.abs()) first.Swap(second);
result.sign_= first.sign_;
if (first.sign_ == second.sign_) {
for (uint64_t i = 0; i < second.size(); ++i) {
uint64_t term = first[i] + second[i];
result.push_back(term / result.base_);
result[i] += term % result.base_;
}
for (uint64_t i = second.size(); i < first.size(); ++i) {
result[i] += first[i];
result.push_back(result[i] / result.base_);
result[i] = result[i] % result.base_;
}
} else {
result.pop_back();
for (uint64_t i = 0; i < second.size(); ++i) {
if (first[i] < second[i]) {
uint64_t j = i + 1;
for (; first[j] == 0; ++j) {}
for (; j > i; --j) {
first[j] -= 1;
first[j - 1] += result.base_;
}
}
result.push_back(first[i] - second[i]);
}
for (uint64_t i = second.size(); i < first.size(); ++i) {
result.push_back(first[i]);
}
}
for (uint64_t i = result.size() - 1; i > 0 && result[i] == 0; --i) {
result.pop_back();
}
if (result[result.size() - 1] == 0) result.sign_ = BigNumber::sign_flag::POSITIVE;
if (result.size() * std::log10(result.base_) >= result.kMaxLength) {
throw "thrown exception: number is too big(length >= " +
std::to_string(first.kMaxLength - static_cast<size_t>(std::log10(result.base_))) +
" numbers)";
}
return result;
}
BigNumber operator -(BigNumber first, BigNumber second) {
return first + (-second);
}
BigNumber operator *(BigNumber first, BigNumber second) {
if (first.size() == 1 || second.size() == 1) {
BigNumber zero(1e9, "0");
if (first.abs() == zero || second.abs() == zero) return zero;
BigNumber result(first.base_);
result.sign_ = static_cast<BigNumber::sign_flag>(static_cast<int>(first.sign_) *
static_cast<int>(second.sign_));
result.resize(3, 0);
if (first.size() < second.size()) first.Swap(second);
for (uint64_t i = 0; i < first.size(); ++i) {
uint64_t term = first[i] * second[0];
result[i] += term % result.base_;
result[i + 1] += term / result.base_;
if (result[i] >= result.base_) {
result[i + 1] += result[i] / result.base_;
result[i] %= result.base_;
}
}
for (uint64_t i = result.size() - 1; i > 0 && result[i] == 0; --i) {
result.pop_back();
}
if (result.size() == 1 && result[0] == 0) result.sign_ = BigNumber::sign_flag::POSITIVE;
return result;
}
for (uint64_t i = first.size(); i < second.size(); ++i) first.push_back(0);
for (uint64_t i = second.size(); i < first.size(); ++i) second.push_back(0);
uint64_t power = first.size() / 2;
BigNumber first_first = first;
first_first.resize(power);
BigNumber first_second = first >> power;
BigNumber second_first = second;
second_first.resize(power);
BigNumber second_second = second >> power;
BigNumber ff_sf = first_first * second_first;
BigNumber fs_ss = first_second * second_second;
BigNumber result = ff_sf + (((first_first + first_second) *
(second_first + second_second) - ff_sf - fs_ss) << power) +
(fs_ss << (power + power));
for (uint64_t i = result.size() - 1; i > 0 && result[i] == 0; --i) {
result.pop_back();
}
if (result.size() == 1 && result[0] == 0) result.sign_ = BigNumber::sign_flag::POSITIVE;
return result;
}
BigNumber operator /(BigNumber first, BigNumber second) {
if (second == BigNumber(1e9, "0")) throw "error: division by zero";
if (first < second) return BigNumber(1e9, "0");
if (second.size() > 1) throw "error: division by big number";
BigNumber result(first);
uint64_t carry = 0;
for (int64_t i = static_cast<int64_t>(first.size()) - 1; i >= 0; --i) {
uint64_t term = first[static_cast<uint64_t>(i)] + carry * result.base_;
result[static_cast<uint64_t>(i)] = term / second[0];
carry = term % second[0];
}
while (result.size() > 1 && result[result.size() - 1] == 0) result.pop_back();
if (first.sign_ != second.sign_) result.sign_ = BigNumber::sign_flag::NEGATIVE;
return result;
}
double operator /(BigNumber first, double second) {
if (second >= -kEps && second <= kEps) throw "error: division by zero";
return first.ToDouble() / second;
}
double operator /(double first, BigNumber second) {
if (second == BigNumber(1e9, "0")) throw "error: division by zero";
return first / second.ToDouble();
}
BigNumber operator %(BigNumber first, BigNumber second) {
if (second == BigNumber(1e9, "0")) throw "error: division by zero";
if (first < second) return first;
if (second.size() > 1) throw "error: division by big number";
BigNumber carry = BigNumber(first.base_, "0");
for (int64_t i = static_cast<int64_t>(first.size()) - 1; i >= 0; --i) {
uint64_t term = first[static_cast<uint64_t>(i)] + carry[0] * first.base_;
carry[0] = term % second[0];
}
if (first.sign_ != second.sign_ && carry != BigNumber(1e9, "0")) {
carry = BigNumber(1e9, "1000000000") - carry;
}
return carry;
}
double operator %(BigNumber, double) {
throw "error: modular division by double";
}
double operator %(double, BigNumber) {
throw "error: modular division of double";
}
std::ostream& operator <<(std::ostream &outstream, BigNumber &data) {
outstream << data.ToString();
return outstream;
}
double operator +(BigNumber first, double second) {
return first.ToDouble() + second;
}
double operator +(double first, BigNumber second) {
return first + second.ToDouble();
}
double operator -(BigNumber first, double second) {
return first.ToDouble() - second;
}
double operator -(double first, BigNumber second) {
return first - second.ToDouble();
}
double operator *(BigNumber first, double second) {
return first.ToDouble() * second;
}
double operator *(double first, BigNumber second) {
return first * second.ToDouble();
}
BigNumber::operator double() {
return this->ToDouble();
}
BigNumber& BigNumber::operator =(BigNumber other) {
this->Swap(other);
return *this;
}
|
Markdown
|
UTF-8
| 1,094
| 2.53125
| 3
|
[
"Apache-2.0"
] |
permissive
|
# Analyzing Movie Reviews using LDA models. Pycones2018
Resources used for my talk at [*Pycon Spain 2018*](https://2018.es.pycon.org/talk/y-hoyque-vemos-analizando-reviews-de-peliculas-con-python)
The main objective of the talk was to introduce the audience into the gensim library for Topic Modelling through a use case where a dataset of movies' reviews from IMDB is analyzed to automatically discover fine-grained topics that can be used to better contextualize movies' profiles.
The Notebook shows how to train LDA models using gensim and how a first noise and useless model can be improved mainly by using different NLP techniques for filtering the initial vocabulary trying to keep only those terms that are semantically valuable in this domain.
## Instructions
1. Uncompress the movies' reviews dataset at resources/aclImdb folder
2. Build the Dockerfile using a tag name of your selection
3. Run the built docker image in this way:
```
docker run --rm -p 8888:8888 -v "$PWD":/home/jovyan/work jupyter/[YOUR_TAG]
```
4. Select the Notebook at 'work' folder in the Jupyter Dashboard
|
Java
|
UTF-8
| 357
| 1.859375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.xfl.pingguopai.dao;
import com.xfl.pingguopai.common.Mapper;
import com.xfl.pingguopai.model.OrderTask;
import com.xfl.pingguopai.model.User;
import org.apache.ibatis.annotations.Select;
public interface OrderTaskMapper extends Mapper<OrderTask> {
@Select("select * from t_order_task where id=#{id}")
OrderTask findByCustom(Long id);
}
|
Ruby
|
UTF-8
| 3,646
| 3.265625
| 3
|
[] |
no_license
|
module Planning
# a class for complex conditions
class Condition
def eval context
end
end
class ConditionVariable < Condition
def initialize name
@name=name
end
def eval context
context[@name]
end
end
class ConditionConst < Condition
def initialize value
@value=value
end
def eval context
@value
end
end
class NotCondition < Condition
def initialize cond
@cond=cond
end
def eval context
! @cond.eval(context)
end
end
class BinaryCondition < Condition
def initialize operation, op1, op2
raise "Unknown operation #{operation}" unless
[ :eq, :neq, :lt, :gt, :lte, :gte].include? operation
@operation=operation
@op1=op1
@op2=op2
end
def eval context
v1=@op1.eval(context)
v2=@op2.eval(context)
case @operation
when :eq
v1==v2
when :neq
v1!=v2
when :gt
v1>v2
when :lt
v1<v2
when :gte
v1>=v2
when :lte
v1<=v2
end
end
end
class MultinodeCondition < Condition
def initialize op, conditions
raise "Unknown operation #{op}" unless [ :and, :or].include? op
@operation=op
@conditions=conditions
end
def eval context
case @operation
when :or
not @conditions.find{|c| c.eval(context)}.nil?
when :and
@conditions.find{|c| not c.eval(context)}.nil?
end
end
end
class SampleContext
def initialize
@values = {}
end
def []= name, value
@values[name] = value
end
def [] name
@values[name]
end
end
def self.assert expected, actual
unless expected==actual
raise StandardError, "Expected '#{expected}', but got #{actual}", caller[0..-2]
else
#puts "OK"
end
end
def self.test
ctx = SampleContext.new
ctx['x']='A'
ctx['y']='B'
ctx['z']='C'
c = MultinodeCondition.new :and, [BinaryCondition.new(:eq, ConditionVariable.new('x'), ConditionConst.new('A')),
BinaryCondition.new(:eq, ConditionVariable.new('y'), ConditionConst.new('B'))]
assert true, c.eval(ctx)
c = MultinodeCondition.new :and, [BinaryCondition.new(:eq, ConditionVariable.new('x'), ConditionConst.new('A2')),
BinaryCondition.new(:eq, ConditionVariable.new('y'), ConditionConst.new('B'))]
assert false, c.eval(ctx)
c = MultinodeCondition.new :and, [BinaryCondition.new(:eq, ConditionVariable.new('x'), ConditionConst.new('A')),
BinaryCondition.new(:eq, ConditionVariable.new('y'), ConditionConst.new('YB'))]
assert false, c.eval(ctx)
c = MultinodeCondition.new :or, [BinaryCondition.new(:eq, ConditionVariable.new('x'), ConditionConst.new('A')),
BinaryCondition.new(:eq, ConditionVariable.new('y'), ConditionConst.new('YB'))]
assert true, c.eval(ctx)
c = MultinodeCondition.new :or, [BinaryCondition.new(:eq, ConditionVariable.new('x'), ConditionConst.new('A2')),
BinaryCondition.new(:eq, ConditionVariable.new('y'), ConditionConst.new('B'))]
assert true, c.eval(ctx)
end
test
end
|
C++
|
UTF-8
| 3,441
| 2.890625
| 3
|
[] |
no_license
|
// PrePolygon.hpp
//
// by Janice Richards, Mar 17, 2018
//
//----------------------------------------
#ifndef PREPOLYGON_HPP_
#define PREPOLYGON_HPP_
#include <algorithm> // std::sort
#include <string>
#include <iostream>
#include <vector>
#include <map>
#include <cstdio>
#include <math.h>
namespace GeoStar {
template <class T>
class PrePolygon {
private:
int previousRowIndex;
bool done;
bool hasHoles;
bool isContained;
std::vector<PolygonPoint*> emptyVector;
// edges are the pixel boundaries; these are recalculated after each full pass
// of a column of pixel data. e.g. (0,2) -> (0,5)
// Until the complete polygon boundaries have been found, the edges consist
// of all the pixel addresses which are part of the edge, with x,y being the
// CENTER of the pixel:
//
std::vector<PolygonPoint*> edges_xsorted;
std::vector<PolygonPoint*> edges_ysorted;
// These are the (compressed) edges used for setting up the gdal polygon
// - only calculated when the polygon's complete bounds have been determined:
std::vector<PolygonPoint*> edges_list;
int polygonNumber;
T pixelValue;
// will only save 2 entries in pixelAddrs, y and y - 1 (if y != 0)
// key is y-value and value is list of pixel points
std::map<int, std::vector<PolygonPoint*> > pixelAddrs;
std::vector<PrePolygon*> containedPolygons;
EdgeXSorter xSorter;
EdgeYSorter ySorter;
void checkPointOnRightHole(PolygonPoint *pt);
void checkPointOnLeftHole(PolygonPoint *pt);
void checkPointOnBottomHole(PolygonPoint *pt);
void checkPointOnTopHole(PolygonPoint *pt);
bool anyPointJustLeft(PolygonPoint *pt, int index);
bool anyPointJustRight(PolygonPoint *pt, int index);
bool anyPointJustAbove(PolygonPoint *pt);
bool anyPointJustBelow(PolygonPoint *pt);
bool anyPointAbove(PolygonPoint *pt);
int findXsortedPoint(PolygonPoint *pt);
int findYsortedPoint(PolygonPoint *pt);
int findXsortedPoint(int x, int y);
int findYsortedPoint(int x, int y);
bool minMaxRowOrCol(PolygonPoint *pt);
bool isPointInside(PolygonPoint *testPt);
int getNumberThisPointsAbove(PolygonPoint *pt);
int getNumberThisPointsLeft(PolygonPoint *pt);
int getNumberThisPointsRight(PolygonPoint *pt);
int getNumberThisPointsBelow(PolygonPoint *pt);
public:
PrePolygon();
PrePolygon(int &polygonNumber, T &pixelValue, int x, int y);
PrePolygon(int &polygonNumber, T &pixelValue, std::vector<PolygonPoint*> &points);
int getPolygonNumber();
T getPixelValue();
std::vector<PolygonPoint*> getEdgePoints();
// This function is called when another polygon is coalesced into
// this polygon.
void addEdgePoints(std::vector<PolygonPoint*> newEdgePoints);
std::vector<PolygonPoint*> getPoints(int y);
void addPoints(std::vector<PolygonPoint*> newPoints, int y);
void addPoint(int x, int y);
void setDone(bool done);
bool isDone();
void setAlreadyContained();
bool isAlreadyContained();
void edgify(int y);
void findFinalBoundingPolygon();
bool hasAnyHoles();
bool isPolygonInside(PrePolygon *smallerPolygon);
void addContainedPolygon(PrePolygon *insidePolygon);
void spinOffPolygon();
void printMoreCrap();
}; // end class: PrePolygon
}// end namespace GeoStar
#endif //PREPOLYGON_HPP_
|
Java
|
UTF-8
| 2,571
| 3.21875
| 3
|
[] |
no_license
|
package nl.tudelft.ti2206.group9.shop.soundtrack;
import nl.tudelft.ti2206.group9.audio.SoundtrackPlayer;
import nl.tudelft.ti2206.group9.shop.ShopItem;
/**
* The abstract shop item class for soundtracks, based on the
* requirements from the ShopItem interface.
* Besides, every soundtrack item has it's own SoundtrackPlayer.
*
* @author Mitchell.
*/
public abstract class AbstractSoundtrack implements ShopItem {
/**
* The price of this soundtrack in the shop.
*/
private final int soundtrackPrice;
/**
* The soundtrack name to display in the shop.
*/
private final String soundtrackName;
/**
* The SoundtrackPlayer of the soundtrack that can be bought.
*/
private final SoundtrackPlayer soundtrackPlayer;
/**
* The beginning part of the path to every audio file.
*/
private static final String AUDIOPATH = "nl/tudelft/ti2206/group9/audio/";
/**
* Constructor for a soundtrack that can be bought or is default.
* Every (buyable) soundtrack consists of a name, a price
* and the soundtrackPlayer for playing it.
*
* @param price Price of this soundtrack in shop.
* @param name Name of the soundtrack to display.
* @param soundtrackFileName Name of soundtrack file.
*/
public AbstractSoundtrack(final int price, final String name,
final String soundtrackFileName) {
soundtrackPrice = price;
soundtrackName = name;
soundtrackPlayer = loadSoundtrackPlayer(soundtrackFileName);
}
@Override
public int getItemPrice() {
return soundtrackPrice;
}
@Override
public String getItemName() {
return soundtrackName;
}
/**
* Gets the SoundtrackPlayer of a Soundtrack.
* This SoundtrackPlayer will be or is already initialized.
*
* @return SoundtrackPlayer that will be / is initialized with a soundtrack.
*/
public SoundtrackPlayer getSoundtrackPlayer() {
return soundtrackPlayer;
}
/**
* Loads the soundtrackPlayer that is to be used
* by the buyable soundtrack.
*
* @param soundtrackFileName the name of the file to be initialized.
* @return SountrackPlayer initialized based on the given file name.
*/
private SoundtrackPlayer loadSoundtrackPlayer(
final String soundtrackFileName) {
final String soundtrackPath = AUDIOPATH + soundtrackFileName + ".mp3";
return new SoundtrackPlayer(soundtrackPath);
}
}
|
Java
|
UTF-8
| 1,703
| 3.171875
| 3
|
[] |
no_license
|
package com.cfyj.design.pattern.template;
import lombok.extern.slf4j.Slf4j;
/**
*
* 维护动态线路信息模版方法设计模式:
* 1.获取当前线路信息,
* 2.解析线路信息--抽象,因为获取的渠道有多种
* 3.根据解析好的线路维护系统内部的动态线路表(当前站,下一站,当前行驶方向,当前时间)
* 4.将动态行驶线路持久化
*
* @author lius
*
*/
@Slf4j
public abstract class AbstractTemplateUpdateStationInfo {
public void updateDynamicStationInfo() {
log.info("维护静态线路信息");
//普通方法:获取当前动态线路信息,抽象类有固定的获取方式,但也可以由子类提供获取方式
String dynamicStationInfo = getDynamicStationInfo();
//抽象方法:每个渠道的信息解析方式不同,由子类提供
String afterResolvingStationInfo = ResolvingStationInfo(dynamicStationInfo);
//固定方法:更新线路映射关系
updateDynamicStationInfo(afterResolvingStationInfo);
//固定方法:持久化线路映射关系
PersistenceDynamicStationInfo();
}
private void PersistenceDynamicStationInfo() {
log.info("持久化线路信息");
}
private void updateDynamicStationInfo(String afterResolvingStationInfo) {
log.info("更新线路信息:解析后的线路信息为:{}",afterResolvingStationInfo);
}
protected abstract String ResolvingStationInfo(String dynamicStationInfo);
protected String getDynamicStationInfo() {
log.info("获取动态线路信息");
return "currentStation=人民广场&nextStation=浦东大道¤tTime=1558746765&direction=上行";
}
}
|
C
|
UTF-8
| 721
| 2.8125
| 3
|
[] |
no_license
|
/**
* @file
* @author Mark Said Camilleri
* @version 20170521.
*/
#include "network_server.h"
#include "arena.h"
pthread_mutex_t gameLockWhenPlayerAddedMutex = PTHREAD_MUTEX_INITIALIZER;
void delay(unsigned int secs) {
unsigned int retTime = time(NULL) + secs; // Get finishing time.
while (time(NULL) < retTime); // Loop until it arrives.
}
int main(void) {
int start_sending = 0;
pthread_t connectionThread;
if (pthread_create(&connectionThread, NULL, init_server_and_accept_connections, &start_sending) != 0) {
ZF_LOGF_STR("Error when creating new thread");
exit(EXIT_FAILURE);
}
while (!start_sending);
init_arena();
play();
exit(EXIT_SUCCESS);
}
|
Java
|
UTF-8
| 734
| 3.484375
| 3
|
[] |
no_license
|
/**
* Write a description of class Player here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Player
{
private String name;
private int numberTaken;
public Player(String name){
this.name = name;
numberTaken = 0;
}
public boolean takeTurn(int number, Pile pile) {
// This fetches the remove sticks method from the pile class.
boolean success = pile.removeSticks(number);
if (success)
{
numberTaken = number;
}
else
{
numberTaken = 0;
}
return success;
}
public String getName(){
return name;
}
public int getNumberTaken(){
return numberTaken;
}
}
|
SQL
|
UTF-8
| 5,720
| 2.890625
| 3
|
[] |
no_license
|
-- phpMyAdmin SQL Dump
-- version 5.0.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Apr 11, 2021 at 09:20 PM
-- Server version: 10.4.17-MariaDB
-- PHP Version: 8.0.1
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
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 */;
--
-- Database: `budget_facebook`
--
-- --------------------------------------------------------
--
-- Table structure for table `permissions`
--
CREATE TABLE `permissions` (
`id` tinyint(4) NOT NULL,
`name` varchar(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `permissions`
--
INSERT INTO `permissions` (`id`, `name`) VALUES
(1, 'like'),
(2, 'comment'),
(3, 'share');
-- --------------------------------------------------------
--
-- Table structure for table `posts`
--
CREATE TABLE `posts` (
`status_code` varchar(5) NOT NULL,
`content` varchar(280) NOT NULL,
`date` date NOT NULL,
`visibility_id` int(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `posts`
--
INSERT INTO `posts` (`status_code`, `content`, `date`, `visibility_id`) VALUES
('S1241', 'dsfafwa', '2021-04-10', 102),
('S2352', '32423', '2021-04-06', 103),
('S2532', 'afrqwwq', '2021-04-12', 102),
('S3216', 'Shgasvfjkaswbflkiawq', '2021-04-08', 103),
('S3241', '324235235', '2021-04-12', 102),
('S3254', 'asfdwqa', '2021-04-12', 102),
('S3323', '46 a4ft gs4 d4w3sa345r ***&532', '2021-04-12', 102),
('S3334', '2qwre2 2 aswdreaqwew', '2021-04-07', 102),
('S3423', 'rhrtwer4tew4', '2021-04-12', 102),
('S3463', 'Z***Q3w4rq24e1', '2021-04-12', 102),
('S3673', 'ewt3452345', '2021-04-12', 102),
('S4363', 'sdazfegreasfwea', '2021-04-12', 102),
('S4365', 'dsgsetw345', '2021-04-12', 102),
('S4564', 'asdwq', '2021-04-12', 102),
('S4575', 'cvsdffew', '2021-04-12', 102),
('S4634', '43653453', '2021-04-06', 102),
('S5223', 'sadawq', '2021-04-12', 102),
('S5325', 'asdgddeee', '2021-04-11', 102),
('S5466', 'gdr', '2021-04-12', 102),
('S5474', 'dhgdsrtfswer', '2021-04-12', 102),
('S5555', 'gfsgsdvds ewqrqwrq', '2021-04-08', 101),
('S5735', 'dsgeew', '2021-04-12', 102),
('S5856', 'sdgwe5w', '2021-04-12', 102),
('S6345', 'sdgewewf', '2021-04-12', 102),
('S6436', 'asfwa', '2021-04-12', 102),
('S6546', 'asfwa', '2021-04-12', 102),
('S6555', 'dsfawfw', '2021-04-12', 102),
('S6785', 'Actual post; who woulda thought', '2021-04-12', 102),
('S6969', 'HELLO WORLD PLEASE WORK', '2021-04-12', 103),
('S7354', '&&&&&#W532q', '2021-04-12', 102),
('S7634', 'dgaeeas', '2021-04-12', 102),
('S7697', 'tjruty', '2021-04-12', 102),
('S7986', 'fdgwetwe4', '2021-04-12', 102),
('S8586', '**% %754swESDF', '2021-04-12', 102),
('S9080', 'hdrfyherty', '2021-04-12', 102),
('Syery', 'dsfghryweyr', '2021-04-12', 102);
-- --------------------------------------------------------
--
-- Table structure for table `post_permissions`
--
CREATE TABLE `post_permissions` (
`id` int(11) NOT NULL,
`code` varchar(5) NOT NULL,
`permission_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `post_permissions`
--
INSERT INTO `post_permissions` (`id`, `code`, `permission_id`) VALUES
(25, 'S2352', 1),
(26, 'S2352', 3),
(27, 'S3334', 2),
(28, 'S5555', 1),
(29, 'S5555', 2),
(30, 'S5555', 3),
(31, 'S3216', 1),
(32, 'S1241', 1),
(33, 'S1241', 2),
(34, 'S1241', 3),
(35, 'S5325', 1),
(36, 'S5325', 3),
(42, 'S4564', 1),
(43, 'S4564', 2),
(44, 'S4564', 3),
(45, 'S5223', 1),
(46, 'S5223', 2),
(47, 'S5223', 3),
(48, 'S3254', 1),
(49, 'S6785', 1),
(50, 'S6785', 2),
(51, 'S6785', 3),
(52, 'S4575', 2),
(53, 'S4575', 3),
(54, 'S6345', 1),
(55, 'S6345', 3),
(56, 'S5735', 2),
(57, 'S5735', 3),
(58, 'S4363', 2),
(59, 'S4363', 3),
(60, 'S6546', 1),
(61, 'S6546', 3),
(62, 'S6436', 1),
(63, 'S6436', 3),
(64, 'S6969', 1),
(65, 'S6969', 2),
(66, 'S6969', 3),
(67, 'S6969', 1),
(68, 'S6969', 2),
(69, 'S6969', 3),
(70, 'S6969', 1),
(71, 'S6969', 2),
(72, 'S6969', 3),
(73, 'S6969', 1),
(74, 'S6969', 2),
(75, 'S6969', 3),
(76, 'S7354', 1),
(77, 'S7354', 2);
-- --------------------------------------------------------
--
-- Table structure for table `visibility`
--
CREATE TABLE `visibility` (
`id` int(11) NOT NULL,
`name` varchar(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `visibility`
--
INSERT INTO `visibility` (`id`, `name`) VALUES
(101, 'Only Me'),
(102, 'Friends'),
(103, 'Public');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `permissions`
--
ALTER TABLE `permissions`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `posts`
--
ALTER TABLE `posts`
ADD PRIMARY KEY (`status_code`);
--
-- Indexes for table `post_permissions`
--
ALTER TABLE `post_permissions`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `visibility`
--
ALTER TABLE `visibility`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `permissions`
--
ALTER TABLE `permissions`
MODIFY `id` tinyint(4) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `post_permissions`
--
ALTER TABLE `post_permissions`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=78;
--
-- AUTO_INCREMENT for table `visibility`
--
ALTER TABLE `visibility`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=104;
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 */;
|
Java
|
UTF-8
| 1,724
| 2.359375
| 2
|
[] |
no_license
|
package com.coolbook.erp.repository.specs;
import com.coolbook.erp.entity.PettyCashEntity;
import org.springframework.data.jpa.domain.Specification;
import javax.persistence.Tuple;
import javax.persistence.criteria.*;
import java.text.ParseException;
import java.util.Date;
public class PettyCashSearchSpecification extends SearchSpecification implements Specification<PettyCashEntity> {
private String searchValue;
private long companyId;
public PettyCashSearchSpecification(String searchValue, long companyId) {
this.searchValue = searchValue;
this.companyId = companyId;
}
@Override
public Predicate toPredicate(Root<PettyCashEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
Predicate predicate = cb.conjunction();
if (searchValue != null) {
Expression<String> description = root.get("description");
predicate = cb.or(predicate,cb.like(cb.upper(description), "%" + searchValue.toUpperCase() + "%"));
if(!"".equals(searchValue) && isDateValid(searchValue)) {
Path<Tuple> tuple = root.<Tuple>get("date");
if(tuple.getJavaType().isAssignableFrom(Date.class)){
Expression<String> dateStringExpr = cb.function("TO_CHAR", String.class, root.get("date"), cb.literal("'YYYY-MM-DD'"));
try {
predicate=cb.or(predicate,cb.like(cb.lower(dateStringExpr), "%"+dateFormat.format(dateFormat2.parse(searchValue)).toLowerCase()+"%"));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
}
return predicate;
}
}
|
PHP
|
ISO-8859-1
| 466
| 3.4375
| 3
|
[] |
no_license
|
<?php
/**
* Lanza una excepcin por defecto
*/
$miLado = -3;
function areaCuadrado($lado){
if ($lado < 0){
// Lanzamos una excepcin
throw new Exception ('Debes insertar un nmero positivo');
}
return $lado * $lado;
}
try {
areaCuadrado($miLado);
} catch (Exception $e) {
print 'Ha saltado la excepcin: ' . $e->getMessage();
}
// Devuelve: Uncaught exception 'Exception' with message 'Debes insertar un nmero positivo'
|
Java
|
UTF-8
| 2,671
| 2.15625
| 2
|
[] |
no_license
|
/*
* Copyright 2010, 2011 Institut Pasteur.
*
* This file is part of ICY.
*
* ICY 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.
*
* ICY 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 ICY. If not, see <http://www.gnu.org/licenses/>.
*/
package plugins.tutorial.vtk;
import icy.canvas.IcyCanvas;
import icy.painter.Overlay;
import icy.painter.VtkPainter;
import icy.sequence.Sequence;
import java.awt.Graphics2D;
import plugins.kernel.canvas.VtkCanvas;
import vtk.vtkActor2D;
import vtk.vtkCubeSource;
import vtk.vtkLabeledDataMapper;
import vtk.vtkProp;
import vtk.vtkRenderer;
import vtk.vtkSelectVisiblePoints;
/**
* @author stephane
*/
public class VtkLabelPainter extends Overlay implements VtkPainter
{
private vtkActor2D pointLabels;
private vtkSelectVisiblePoints visPts;
public VtkLabelPainter()
{
super("VTK label");
init();
}
// init vtk objects
private void init()
{
// labellers to display coordinates
final vtkCubeSource cubeSource = new vtkCubeSource();
cubeSource.SetBounds(0, 50, 100, 150, 300, 200);
// Create labels for points
visPts = new vtkSelectVisiblePoints();
visPts.SetInputConnection(cubeSource.GetOutputPort());
// Create the mapper to display the point ids. Specify the format to
// use for the labels. Also create the associated actor.
final vtkLabeledDataMapper ldm = new vtkLabeledDataMapper();
ldm.SetInputConnection(visPts.GetOutputPort());
ldm.SetLabelFormat("%g");
ldm.SetLabelModeToLabelFieldData();
pointLabels = new vtkActor2D();
pointLabels.SetMapper(ldm);
}
@Override
public void paint(Graphics2D g, Sequence sequence, IcyCanvas canvas)
{
if (canvas instanceof VtkCanvas)
{
final vtkRenderer renderer = ((VtkCanvas) canvas).getRenderer();
if (visPts.GetRenderer() == null)
visPts.SetRenderer(renderer);
}
}
@Override
public vtkProp[] getProps()
{
return new vtkProp[] {pointLabels};
}
}
|
Shell
|
UTF-8
| 1,397
| 4.21875
| 4
|
[] |
no_license
|
#!/bin/bash
# Script to create a MySQL image with a phpMyAdmin image
# Usage
function usage() {
echo "Usage: $0 image_name mysql_password path_to_data host_mysql_port host_admin_port"
exit 1
}
if [ $# -lt 5 ] ; then
usage
exit 1
fi
if [[ "$OSTYPE" == "darwin"* ]]; then
command -v greadlink >/dev/null 2>&1 || { echo >&2 "Please install brew coreutils first. Aborting..."; exit 1; }
fi
# Variables
MYSQL_NAME="$1_mysql"
MYSQL_PASSWORD=$2
DB_PATH=$3
HOST_PORT=$4
PHPMYADMIN_PORT=$5
if [[ "$OSTYPE" == "linux-gnu" ]]; then
FULL_PATH=$(readlink -f $DB_PATH)
elif [[ "$OSTYPE" == "darwin"* ]]; then
FULL_PATH=$(greadlink -f $DB_PATH)
fi
PHPMYADMIN_NAME="$1_admin"
NETWORK_NAME="$1_network"
# Create a network
docker network create ${NETWORK_NAME}
sleep 2
# Create a MySQL docker image
docker run \
--detach \
--name=${MYSQL_NAME} \
--env MYSQL_ROOT_PASSWORD=${MYSQL_PASSWORD} \
--publish ${HOST_PORT}:3306 \
--net=${NETWORK_NAME} \
--volume=${FULL_PATH}:/var/lib/mysql \
mysql:5.7;
sleep 2
# Create a phpMyAdmin docker image
docker run \
--detach \
--name=${PHPMYADMIN_NAME} \
--net=${NETWORK_NAME} \
--publish ${PHPMYADMIN_PORT}:80 \
--env PMA_HOST=${MYSQL_NAME} \
phpmyadmin/phpmyadmin;
echo "Containers created use docker start/stop ${MYSQL_NAME} and/or docker start/stop ${PHPMYADMIN_NAME} to manipulate them"
|
C#
|
UTF-8
| 511
| 2.5625
| 3
|
[] |
no_license
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawner : MonoBehaviour {
int RandX;
int RandY;
public GameObject ball;
void Start () {
Spawn ();
}
void Update () {
if(Input.GetMouseButtonDown(0) ) {
Spawn();
}
}
void CreateRandomPosition()
{
RandX = Random.Range (-8, 8);
RandY = Random.Range (-4, 4);
}
void Spawn()
{
CreateRandomPosition ();
Instantiate (ball, new Vector3 (RandX, RandY, 0), Quaternion.identity);
}
}
|
Python
|
UTF-8
| 380
| 3.3125
| 3
|
[] |
no_license
|
def main():
while True:
# Keep prompting for input untill valid
try:
height = int(input("Height: "))
if height > 0:
break
except ValueError:
pass
for space,star in zip(range(height-1,-1,-1), range(1,height+1)):
print (" "*space+"#"*star+" "+"#"*star)
if __name__ == "__main__":
main()
|
SQL
|
UTF-8
| 42,200
| 3.65625
| 4
|
[] |
no_license
|
/**
*
* SQL file for the Automotive Repair Shop for CECS 323 Term Project.
* The tables in this file was constructed based on our class diagrams and relation schemes.
* After creating our tables, we inserted fictional data that we created to help us generate
* queries and views.
*
* Author: Abram Villanueva <abramvillan@gmail.com>, Caren Briones <carenpbriones@gmail.com>
* Gregory Abellanosa <gregoryabellanosa@gmail.com>, and Ryan Luong <ryanluong911@gmail.com>
* Created: Nov 29 , 2016
*/
CREATE TABLE customers
(
c_id VARCHAR(10) NOT NULL,
c_fname VARCHAR(20) NOT NULL,
c_lname VARCHAR(20) NOT NULL,
c_email VARCHAR(50) NOT NULL,
cType VARCHAR(20) NOT NULL,
CONSTRAINT pk_customers PRIMARY KEY (c_id)
);
CREATE TABLE vehicles
(
c_id VARCHAR(10) NOT NULL,
v_id VARCHAR(10) NOT NULL,
vinNum VARCHAR(17) NOT NULL,
plateNum VARCHAR(20) NOT NULL,
make VARCHAR(20) NOT NULL,
mileage INTEGER NOT NULL,
model VARCHAR(20) NOT NULL,
color VARCHAR(40) NOT NULL,
yearMade INTEGER NOT NULL,
serviceFreq VARCHAR(30),
numOfAccidents INTEGER,
CONSTRAINT pk_vehicles PRIMARY KEY (c_id, v_id),
CONSTRAINT vehicles_customers_fk FOREIGN KEY (c_id) REFERENCES customers (c_id)
);
CREATE TABLE employees
(
e_id VARCHAR(10) NOT NULL,
efname VARCHAR(20) NOT NULL,
elname VARCHAR(20) NOT NULL,
eEmail VARCHAR(50) NOT NULL,
workPhone VARCHAR(20),
timeContract VARCHAR(50),
salary VARCHAR(20),
CONSTRAINT pk_employees PRIMARY KEY (e_id)
);
CREATE TABLE addresses
(
c_id VARCHAR(10) NOT NULL,
addr_id VARCHAR(10) NOT NULL,
addrType VARCHAR(10) NOT NULL,
street VARCHAR(40) NOT NULL,
city VARCHAR(20) NOT NULL,
state VARCHAR(20) NOT NULL,
zipCode VARCHAR(20) NOT NULL,
CONSTRAINT pk_addresses PRIMARY KEY (c_id, addr_id),
CONSTRAINT addresses_customers_fk FOREIGN KEY (c_id) REFERENCES customers (c_id)
);
CREATE TABLE phones
(
c_id VARCHAR(10) NOT NULL,
phoneType VARCHAR(10) NOT NULL,
phoneNum VARCHAR(20) NOT NULL,
CONSTRAINT pk_phones PRIMARY KEY (c_id, phoneNum),
CONSTRAINT phones_customers_fk FOREIGN KEY (c_id) REFERENCES customers (c_id)
);
CREATE TABLE prospective_c
(
c_id VARCHAR(10) NOT NULL,
referralDate DATE,
CONSTRAINT pk_prospective_c PRIMARY KEY (c_id),
CONSTRAINT prospectivec_customers_fk FOREIGN KEY (c_id) REFERENCES customers (c_id)
);
CREATE TABLE existing_c
(
c_id VARCHAR(10) NOT NULL,
joinDate DATE NOT NULL,
CONSTRAINT pk_existing_c PRIMARY KEY (c_id),
CONSTRAINT existingc_customers_fk FOREIGN KEY (c_id) REFERENCES customers (c_id)
);
CREATE TABLE premier_c
(
c_id VARCHAR(10) NOT NULL,
CONSTRAINT pk_premier_c PRIMARY KEY (c_id),
CONSTRAINT premierc_existingc_fk FOREIGN KEY (c_id) REFERENCES existing_c (c_id)
);
CREATE TABLE steady_c
(
c_id VARCHAR(10) NOT NULL,
lastVisit VARCHAR(20),
CONSTRAINT pk_steady_c PRIMARY KEY (c_id),
CONSTRAINT steadyc_existingc_fk FOREIGN KEY (c_id) REFERENCES existing_c (c_id)
);
CREATE TABLE referral_c
(
proC_id VARCHAR(10) NOT NULL,
sc_id VARCHAR(10) NOT NULL,
CONSTRAINT pk_referralContacts PRIMARY KEY (proC_id, sc_id),
CONSTRAINT referralc_prospectivec_fk FOREIGN KEY (proC_id) REFERENCES prospective_c (c_id),
CONSTRAINT referralc_steadyc_fk FOREIGN KEY (sc_id) REFERENCES steady_c (c_id)
);
CREATE TABLE specials
(
s_id VARCHAR(10) NOT NULL,
discountRate DECIMAL(2,2) NOT NULL,
CONSTRAINT pk_specials PRIMARY KEY (s_id)
);
CREATE TABLE offers
(
proC_id VARCHAR(10) NOT NULL,
s_id VARCHAR(10) NOT NULL,
offer VARCHAR(20) NOT NULL,
contactDate DATE NOT NULL,
expirationDate DATE NOT NULL,
CONSTRAINT pk_offers PRIMARY KEY (proC_id, s_id),
CONSTRAINT offers_prospectivec_fk FOREIGN KEY (proC_id) REFERENCES prospective_c (c_id),
CONSTRAINT offers_specials_fk FOREIGN KEY (s_id) REFERENCES specials (s_id)
);
CREATE TABLE monthlyInstallments
(
c_id VARCHAR(10) NOT NULL,
v_id VARCHAR(10) NOT NULL,
preC_id VARCHAR(10) NOT NULL,
monthStarted VARCHAR(15) NOT NULL,
amountDue DECIMAL(15,2) NOT NULL,
CONSTRAINT pk_monthlyInstallments PRIMARY KEY (c_id, v_id, preC_id),
CONSTRAINT monthlyInstallments_vehicles_fk FOREIGN KEY (c_id, v_id) REFERENCES vehicles (c_id, v_id),
CONSTRAINT monthlyInstallments_premierc_fk FOREIGN KEY (preC_id) REFERENCES premier_c (c_id)
);
CREATE TABLE notifications
(
c_id VARCHAR(10) NOT NULL,
v_id VARCHAR(10) NOT NULL,
sc_id VARCHAR(10) NOT NULL,
emailDate DATE NOT NULL,
CONSTRAINT pk_notifications PRIMARY KEY (c_id, v_id, sc_id, emailDate),
CONSTRAINT notifications_steadyc_fk FOREIGN KEY (sc_id) REFERENCES steady_c (c_id),
CONSTRAINT notifications_vehicles_FK FOREIGN KEY (c_id, v_id) REFERENCES vehicles (c_id, v_id)
);
CREATE TABLE serviceTechnicians
(
st_id VARCHAR(10) NOT NULL,
consultationOffice VARCHAR(10),
CONSTRAINT pk_serviceTechnicians PRIMARY KEY (st_id),
CONSTRAINT serviceTechnicians_employees_fk FOREIGN KEY (st_id) REFERENCES employees (e_id)
);
CREATE TABLE mechanics
(
mech_id VARCHAR(10) NOT NULL,
station VARCHAR(20) NOT NULL,
CONSTRAINT pk_mechanics PRIMARY KEY (mech_id),
CONSTRAINT mechanics_employees_fk FOREIGN KEY (mech_id) REFERENCES employees (e_id)
);
CREATE TABLE certifications
(
cert_id VARCHAR(10) NOT NULL,
certName VARCHAR(50) NOT NULL,
CONSTRAINT pk_certifications PRIMARY KEY (cert_id)
);
CREATE TABLE mechanicCertifications
(
cert_id VARCHAR(10) NOT NULL,
mech_id VARCHAR(10) NOT NULL,
dateReceived VARCHAR(20),
CONSTRAINT pk_mechanicCertifications PRIMARY KEY (cert_id, mech_id),
CONSTRAINT mechanicCertifications_mechanics_fk FOREIGN KEY (mech_id) REFERENCES mechanics (mech_id),
CONSTRAINT mechanicCertifications_certifications_fk FOREIGN KEY (cert_id) REFERENCES certifications (cert_id)
);
CREATE TABLE skills
(
mech_id VARCHAR(10) NOT NULL,
skillName VARCHAR(50) NOT NULL,
CONSTRAINT pk_skills PRIMARY KEY (mech_id, skillName),
CONSTRAINT skills_mechanics_fk FOREIGN KEY (mech_id) REFERENCES mechanics (mech_id)
);
CREATE TABLE mentorships
(
mentee_eid VARCHAR(10) NOT NULL,
mentor_eid VARCHAR(10) NOT NULL,
startDate DATE NOT NULL,
endDate DATE,
CONSTRAINT pk_mentorships PRIMARY KEY (mentee_eid, mentor_eid, startDate),
CONSTRAINT mentorships_mentees_fk FOREIGN KEY (mentee_eid) REFERENCES mechanics (mech_id),
CONSTRAINT mentorships_mentors_fk FOREIGN KEY (mentor_eid) REFERENCES mechanics (mech_id)
);
CREATE TABLE skillsLearned
(
mentee_eid VARCHAR(10) NOT NULL,
mentor_eid VARCHAR(10) NOT NULL,
startDate DATE NOT NULL,
skillName VARCHAR(50) NOT NULL,
CONSTRAINT pk_skillsLearned PRIMARY KEY (mentee_eid, mentor_eid, startDate, skillName),
CONSTRAINT skillsLearned_mentorships_fk FOREIGN KEY (mentee_eid, mentor_eid, startDate) REFERENCES mentorships (mentee_eid, mentor_eid, startDate)
);
CREATE TABLE appointments
(
app_id VARCHAR(10) NOT NULL,
c_id VARCHAR(10) NOT NULL,
v_id VARCHAR(10) NOT NULL,
visitDate DATE NOT NULL,
CONSTRAINT pk_appointments PRIMARY KEY (c_id, v_id, app_id),
CONSTRAINT appointments_fk FOREIGN KEY (c_id, v_id) REFERENCES vehicles (c_id, v_id)
);
CREATE TABLE maintenanceOrders
(
app_id VARCHAR(10) NOT NULL,
c_id VARCHAR(10) NOT NULL,
v_id VARCHAR(10) NOT NULL,
mo_id VARCHAR(10) NOT NULL,
st_id VARCHAR(10) NOT NULL,
CONSTRAINT pk_maintenanceOrders PRIMARY KEY (c_id, v_id, app_id, st_id, mo_id),
CONSTRAINT maintenanceOrders_appointment_fk FOREIGN KEY (c_id, v_id, app_id) REFERENCES appointments (c_id, v_id, app_id),
CONSTRAINT maintenanceOrders_serviceTechnicians_fk FOREIGN KEY (st_id) REFERENCES serviceTechnicians (st_id)
);
CREATE TABLE maintenancePackages
(
mp_id VARCHAR(10) NOT NULL,
packageName VARCHAR(50) NOT NULL,
CONSTRAINT pk_maintenancePackage PRIMARY KEY (mp_id)
);
CREATE TABLE maintenanceItems
(
mi_id VARCHAR(10) NOT NULL,
app_id VARCHAR(10) NOT NULL,
c_id VARCHAR(10) NOT NULL,
v_id VARCHAR(10) NOT NULL,
mo_id VARCHAR(10) NOT NULL,
mp_id VARCHAR(10) NOT NULL,
st_id VARCHAR(10) NOT NULL,
repairName VARCHAR(50) NOT NULL,
price DECIMAL(5, 2) NOT NULL,
CONSTRAINT pk_maintenanceItems PRIMARY KEY (mi_id, app_id, c_id, v_id, mo_id, mp_id, st_id),
CONSTRAINT maintenanceItems_maintenanceOrders_fk FOREIGN KEY (c_id, v_id, app_id, st_id, mo_id) REFERENCES maintenanceOrders (c_id, v_id, app_id, st_id, mo_id),
CONSTRAINT maintenanceItems_maintenancePackages_fk FOREIGN KEY (mp_id) REFERENCES maintenancePackages (mp_id)
);
CREATE TABLE assignments
(
mi_id VARCHAR(10) NOT NULL,
app_id VARCHAR(10) NOT NULL,
c_id VARCHAR(10) NOT NULL,
v_id VARCHAR(10) NOT NULL,
mo_id VARCHAR(10) NOT NULL,
mp_id VARCHAR(10) NOT NULL,
st_id VARCHAR(10) NOT NULL,
mech_id VARCHAR(10) NOT NULL,
assignmentDate DATE NOT NULL,
CONSTRAINT pk_assignments PRIMARY KEY (app_id, mi_id, c_id, v_id, mo_id, st_id, mp_id, mech_id),
CONSTRAINT assignments_maintenanceItems_fk FOREIGN KEY (mi_id, app_id, c_id, v_id, mo_id, mp_id, st_id) REFERENCES maintenanceItems (mi_id, app_id, c_id, v_id, mo_id, mp_id, st_id),
CONSTRAINT assignments_mechanics_fk FOREIGN KEY (mech_id) REFERENCES mechanics (mech_id)
);
CREATE TABLE skills_needed
(
mi_id VARCHAR(10) NOT NULL,
app_id VARCHAR(10) NOT NULL,
c_id VARCHAR(10) NOT NULL,
v_id VARCHAR(10) NOT NULL,
mo_id VARCHAR(10) NOT NULL,
st_id VARCHAR(10) NOT NULL,
mp_id VARCHAR(10) NOT NULL,
skillName VARCHAR(50) NOT NULL,
CONSTRAINT pk_skills_needed PRIMARY KEY (mi_id, app_id, c_id, v_id, mo_id, st_id, mp_id, skillName),
CONSTRAINT skillsneeded_maintenanceItems_fk FOREIGN KEY (mi_id, app_id, c_id, v_id, mo_id, mp_id, st_id) REFERENCES maintenanceItems (mi_id, app_id, c_id, v_id, mo_id, mp_id, st_id)
);
INSERT INTO customers (c_id, c_fname, c_lname, c_email, cType) VALUES
('0URKY', 'Gergory', 'Abellanosa', 'gergoryabellanosa@gmail.com', 'private'),
('0RLU1', 'Caren', 'Rionesbay', 'carenprionesbay@gmail.com', 'private'),
('0QPG7', 'Ablam', 'Villanueva', 'ablamvillan00@thebobatruck.com', 'company'),
('0Q5EO', 'Ryan', 'Luong', 'ryanluong411@gmail.com', 'private'),
('0FM12', 'Aiko', 'Doggo', 'aikoruffsyou@flyingbathtub.com', 'company'),
('0JK90', 'Fate', 'Yap', 'fy@safelink.com', 'company'),
('07FR3', 'Duke', 'Borks', 'dukeborks@ruffmail.com', 'private'),
('0L56H', 'Bruno', 'Rionesbay', 'brunomars@dogmail.com', 'private'),
('0P75G', 'Soulja', 'Boy', 'crankdat@youuuuu.com', 'private'),
('0LD4F', 'Drake', 'Grahm', 'jimmybrooks@degrassi.edu', 'private'),
('0IK3G', 'Lobelt', 'Rim', 'robert.lim@hotkoala.com', 'private'),
('0IK3Y', 'Hyorin', 'Trouble', 'doubletroublemakerhyuna@hotmail.com', 'private');
INSERT INTO addresses (c_id, addr_id, addrType, street, city, state, zipCode) VALUES
('0URKY', 'AJG8', 'home', '1248 Binary Ave', 'Boolia', 'CA', '97061'),
('0RLU1', 'AMG9', 'home', '87601 Bae Blvd', 'San Fransokyo', 'CA', '97234'),
('0QPG7', 'AJQE', 'home', '7834 Hamaro St', 'Big Pakka', 'CA', '98451'),
('0Q5EO', 'AE5V', 'work', '3487 Crystal Cove Ave', 'Luong Beach', 'CA', '98732'),
('0FM12', 'AEU2', 'work', '99879 Ceasar St', 'Tails Gate', 'NV', '75483'),
('0JK90', 'AW47', 'home', '7838 Piero St', 'Big Pakka', 'CA', '98541'),
('07FR3', 'AHWX', 'work', '2232 Bitt Ave', 'San Fransokyo', 'CA', '97061'),
('0L56H', 'A3A6', 'home', '87601 Bae Blvd', 'San Fransokyo', 'CA', '97234'),
('0P75G', 'AR2F', 'home', '4455 Wave Ave', 'Luong Beach', 'CA', '98732'),
('0LD4F', 'AT62', 'home', '9567 Poonai Blvd', 'Big Pakka', 'CA', '98541'),
('0IK3G', 'AVHN', 'home', '3476 Compy St', 'Boolia', 'CA', '97061'),
('0IK3Y', 'A4T6', 'home', '3787 Mayonaka Ave', 'Big Pakka', 'CA', '98541');
INSERT INTO phones (c_id, phoneType, phoneNum) VALUES
('0URKY', 'cell', '5622191769'),
('0RLU1', 'cell', '8188188118'),
('0QPG7', 'cell', '5622655626'),
('0Q5EO', 'cell', '8188188118'),
('0FM12', 'work', '8008888888'),
('0JK90', 'cell', '8188188118'),
('07FR3', 'cell', '5627459822'),
('0L56H', 'cell', '8184577623'),
('0P75G', 'cell', '6789998212'),
('0LD4F', 'cell', '8004685462'),
('0IK3G', 'cell', '3234572389'),
('0IK3Y', 'cell', '6261234567');
INSERT INTO prospective_c (c_id, referralDate) VALUES
('07FR3', '2016-02-05'),
('0JK90', '2016-03-04'),
('0IK3Y', '2016-04-15');
INSERT INTO existing_c (c_id, joinDate) VALUES
('0URKY', '2015-12-21'),
('0RLU1', '2013-01-10'),
('0QPG7', '2016-01-05'),
('0Q5EO', '2016-05-28'),
('0FM12', '2014-11-14'),
('0L56H', '2015-06-07'),
('0P75G', '2015-12-01'),
('0LD4F', '2015-08-08'),
('0IK3G', '2016-08-08');
INSERT INTO steady_c (c_id, lastVisit) VALUES
('0URKY', '2016-01-13'),
('0QPG7', '2016-04-15'),
('0P75G', '2016-01-05'),
('0Q5EO', '2016-08-19'),
('0LD4F', '2016-04-08'),
('0IK3G', '2016-09-11');
INSERT INTO premier_c (c_id) VALUES
('0RLU1'),
('0FM12'),
('0L56H');
INSERT INTO employees (e_id, efname, elname, eEmail, workPhone, timeContract, salary) VALUES
('0074WA', 'Bob', 'Builder', 'bobthebuilder@hotwheels.com', '2025550190', 'part time both', '50000'),
('004X7E', 'Haffi', 'Work', 'haffiworkx5@hotwheels.com', '2025550167', 'part time both', '45000'),
('0022TK', 'Lightning', 'McQueen', 'lmcqueen@hotwheels.com', '2025550103', 'full time service technician', '59500'),
('002IR0', 'Herbie', 'Volks', 'hvolks@hotwheels.com', '2025551119', 'part time service technician', '34000'),
('00O0QT', 'Lindsay', 'Lohannon', 'llohannon@hotwheels.com', '2025557896', 'part time mechanic', '20000'),
('00B21W', 'Dominic', 'Torretto', 'dom@hotwheels.com', '2025555710', 'full time mechanic', '57000'),
('0097N2', 'Paul', 'Walker', 'seeyouagain@hotwheels', '2025551129', 'full time mechanic', '47000'),
('00JNKS', 'Letty', 'Rodriguez', 'letty@hotwheels.com', '2025550098', 'full time mechanic', '50050'),
('00V5KL', 'Mater', 'Rusty', 'matertrucks@gmail.com', '2025551234', 'full time mechanic', '49710'),
('00RYVF', 'Doc', 'Hudson', 'docodoc@hotwheels.com', '2025556709', 'full time mechanic', '51000'),
('00Q3HU', 'Suki', 'Suki', 'suki2@gmail.com', '2025558711', 'part time both', '45060'),
('00UT75', 'Nich', 'Dich', 'ditchnich@hotwheels.com', '2025550901', 'part time service technician', '20100');
INSERT INTO serviceTechnicians (st_id, consultationOffice) VALUES
('0074WA', '100'),
('004X7E', '102'),
('0022TK', '104'),
('002IR0', '106'),
('00Q3HU', '108'),
('00UT75', '110');
INSERT INTO mechanics (mech_id, station) VALUES
('0074WA', '1'),
('004X7E', '2'),
('00O0QT', '3'),
('00B21W', '4'),
('0097N2', '5'),
('00JNKS', '6'),
('00V5KL', '7'),
('00RYVF', '8'),
('00Q3HU', '9');
INSERT INTO certifications (cert_id, certName) VALUES
('CERT001', 'A1 Engine Repair'),
('CERT002', 'A2 Automatic Transmission/Transaxle'),
('CERT003', 'A3 Manual Drive Train and Axles'),
('CERT004', 'A4 Suspension and Steering'),
('CERT005', 'A5 Brakes'),
('CERT006', 'A6 Electrical/Electronic Systems'),
('CERT007', 'A7 Heating and Air Conditioning'),
('CERT008', 'A8 Engine Performance');
INSERT INTO mechanicCertifications (cert_id, mech_id, dateReceived) VALUES
('CERT001', '0074WA', '1985-08-23'),
('CERT002', '0074WA', '1987-01-03'),
('CERT003', '0074WA', '1989-02-19'),
('CERT004', '0074WA', '1989-07-05'),
('CERT005', '0074WA', '1998-09-04'),
('CERT006', '0074WA', '2002-01-02'),
('CERT008', '0074WA', '2010-04-09'),
('CERT001', '004X7E', '1980-04-01'),
('CERT005', '004X7E', '1981-07-20'),
('CERT007', '004X7E', '1994-06-24'),
('CERT001', '00O0QT', '1997-11-04'),
('CERT004', '00O0QT', '2005-09-11'),
('CERT005', '00O0QT', '2007-03-16'),
('CERT007', '00O0QT', '2012-11-05'),
('CERT001', '00B21W', '1983-09-03'),
('CERT004', '00B21W', '1984-10-05'),
('CERT005', '00B21W', '1986-08-17'),
('CERT006', '00B21W', '1994-12-18'),
('CERT007', '00B21W', '1989-09-29'),
('CERT008', '00B21W', '2009-04-25'),
('CERT001', '0097N2', '1996-07-09'),
('CERT005', '0097N2', '2002-10-23'),
('CERT006', '0097N2', '1980-09-09'),
('CERT001', '00JNKS', '2000-04-23'),
('CERT002', '00JNKS', '2002-08-23'),
('CERT003', '00JNKS', '2008-01-23'),
('CERT004', '00JNKS', '1965-11-28'),
('CERT005', '00JNKS', '1998-05-30'),
('CERT008', '00JNKS', '2014-06-28'),
('CERT001', '00V5KL', '1969-12-21'),
('CERT004', '00V5KL', '1971-11-21'),
('CERT006', '00V5KL', '1975-06-23'),
('CERT008', '00V5KL', '1975-12-29'),
('CERT002', '00RYVF', '1995-06-01'),
('CERT003', '00RYVF', '2006-04-27'),
('CERT004', '00RYVF', '2008-04-08'),
('CERT006', '00RYVF', '2012-10-10'),
('CERT002', '00Q3HU', '1997-06-21'),
('CERT003', '00Q3HU', '2003-05-17'),
('CERT004', '00Q3HU', '1996-05-17');
INSERT INTO skills (mech_id, skillName) VALUES
('0074WA', 'change oil'),
('0074WA', 'change tires'),
('0074WA', 'align tires'),
('0074WA', 'replace spark plugs'),
('0074WA', 'replace brake fluid'),
('0074WA', 'replace ignition wires'),
('0074WA', 'replace transmission fluid'),
('0074WA', 'replace propeller shaft'),
('0074WA', 'inspect battery'),
('004X7E', 'change oil'),
('004X7E', 'change tires'),
('004X7E', 'align tires'),
('004X7E', 'replace spark plugs'),
('004X7E', 'replace brake fluid'),
('00O0QT', 'change oil'),
('00O0QT', 'change tires'),
('00O0QT', 'align tires'),
('00O0QT', 'inspect brakes'),
('00O0QT', 'replace brake fluid'),
('00O0QT', 'replace brake pads'),
('00O0QT', 'replace light bulbs'),
('00O0QT', 'replace battery'),
('00B21W', 'change oil'),
('00B21W', 'change tires'),
('00B21W', 'align tires'),
('00B21W', 'replace brake pads'),
('00B21W', 'inspect brakes'),
('00B21W', 'replace light bulbs'),
('00B21W', 'replace ignition wires'),
('00B21W', 'inspect smog'),
('0097N2', 'change oil'),
('0097N2', 'change tires'),
('0097N2', 'align tires'),
('0097N2', 'replace light bulbs'),
('0097N2', 'replace ignition wires'),
('0097N2', 'replace catalytic converter'),
('0097N2', 'inspect battery'),
('0097N2', 'replace battery'),
('0097N2', 'inspect brakes'),
('00JNKS', 'change oil'),
('00JNKS', 'change tires'),
('00JNKS', 'align tires'),
('00JNKS', 'replace catalytic converter'),
('00JNKS', 'replace transmission fluid'),
('00JNKS', 'inspect smog'),
('00JNKS', 'inspect brakes'),
('00V5KL', 'change oil'),
('00V5KL', 'change tires'),
('00V5KL', 'align tires'),
('00V5KL', 'replace transmission fluid'),
('00V5KL', 'inspect smog'),
('00V5KL', 'inspect battery'),
('00RYVF', 'change oil'),
('00RYVF', 'change tires'),
('00RYVF', 'align tires'),
('00RYVF', 'replace light bulbs'),
('00RYVF', 'replace ignition wires'),
('00RYVF', 'replace battery'),
('00Q3HU', 'change oil'),
('00Q3HU', 'align tires');
INSERT INTO mentorships (mentee_eid, mentor_eid, startDate, endDate) VALUES
('0074WA', '00Q3HU', '2015-04-09', '2015-07-17'),
('0074WA', '00Q3HU', '2015-06-17', '2015-09-15'),
('0097N2', '00JNKS', '2015-07-20', '2015-11-25'),
('004X7E', '00O0QT', '2015-10-01', '2016-02-25'),
('0097N2', '00RYVF', '2016-09-18', '2016-12-04'),
('0097N2', '00RYVF', '2016-12-05', NULL);
INSERT INTO skillsLearned (mentee_eid, mentor_eid, startDate, skillName) VALUES
('0074WA', '00Q3HU', '2015-04-09', 'change oil'),
('0074WA', '00Q3HU', '2015-06-17', 'align tires'),
('0097N2', '00JNKS', '2015-07-20', 'replace catalytic converter'),
('004X7E', '00O0QT', '2015-10-01', 'replace brake fluid'),
('0097N2', '00RYVF', '2016-09-18', 'change tires');
INSERT INTO vehicles (c_id, v_id, vinNum, plateNum, make, mileage, model, color, yearMade, serviceFreq, numOfAccidents) VALUES
('0URKY', 'V30S7', '1HGFA16808LL01292', '6KAY876', 'Honda', 106972, 'Civic', 'Cosmic Blue Metallic', 2008, '10000', 0),
('0URKY', 'V0T3A', 'I5L3OP04JFMNT85J6', '4OOD713', 'Toyota', 163215, 'Prius', 'Sea Glass Pearl', 2008, '15000', 0),
('0RLU1', 'VYYPG', '1HGCT2B83FA000162', '9BYM093', 'Honda', 14639, 'Accord', 'San Marino Red', 2015, '20000', 0),
('0RLU1', 'VZENX', '48GH529DJRIEMG04J', '5UED833', 'Hyundai', 45213, 'Santa Fe', 'Juniper Green', 2014, '20000', 0),
('0QPG7', 'VKWMP', '4T1BE32K95U637166', '4VEI922', 'Toyota', 156972, 'Camry', 'Lunar Mist Metallic', 2005, '15000', 2),
('0Q5EO', 'V7ZXT', 'JF4K3ODLR5MT0GLT6', '30T70U3', 'Ford', 163492, 'Transit', 'Oxford White', 2008, '14000', 0),
('0FM12', 'V53JY', 'MG01LD5M4KRL5OT98', '94B472', 'Ford', 63851, 'Focus', 'Ingot Silver', 2013, '19000', 1),
('0JK90', 'V86A0', 'SF4914J596KGJQ91J', 'DQNF178', 'Honda', 249850, 'Odyssey', 'White', 1999, '10000', 0),
('07FR3', 'V0005', 'FMDL2K39FJ5UTIGHJ', '7A00005', 'Mazda', 75699, 'RX-8', 'Brilliant Black', 2011, '15000', 1),
('0L56H', 'VT479', 'MLP104JR7FH5MGJSI', 'T4793KV', 'Scion', 146690, 'TC', 'Flint Mica', 2008, '19000', 0),
('0P75G', 'V3KVQ', 'ZMXI34K5K4M5KF0PT', 'QF24I25', 'Mazda', 189913, '3', 'Meteor Gray Mica', 2008, '19000', 0),
('0P75G', 'VF421', 'PEPE4C0LT1LEP4O95', 'FM0A1RA', 'Mercedes', 38551, 'GLA', 'Night Black', 2014, '20000', 4),
('0LD4F', 'V25EM', 'P34M5FCLO394JF8XJ', 'QP8V8Y1', 'Nissan', 14990, '350z', 'Le Mans Sunset', 2007, '18000', 0),
('0IK3G', 'V091R', '3M5LF02KJR749DMFU', 'J194HFV', 'Acura', 32970, 'Tsx', 'Premium White Pearl', 2014, '20000', 0),
('0IK3Y', 'VRLIR', 'LF02LPORM4JFAMWIF', '55GIKFW', 'Mercedes', 300957, 'C 200', 'Polar White', 1997, '10000', 2);
INSERT INTO appointments (app_id, c_id, v_id, visitDate) VALUES
('APP0010', '0URKY', 'V30S7', '2015-12-21'),
('APP0016', '0URKY', 'V30S7', '2016-03-10'),
('APP0019', '0URKY', 'V0T3A', '2016-05-11'),
('APP0013', '0RLU1', 'VYYPG', '2016-01-10'),
('APP0001', '0RLU1', 'VZENX', '2013-03-05'),
('APP0012', '0QPG7', 'VKWMP', '2016-01-05'),
('APP0018', '0QPG7', 'VKWMP', '2016-04-13'),
('APP0020', '0Q5EO', 'V7ZXT', '2016-05-28'),
('APP0022', '0Q5EO', 'V7ZXT', '2016-07-09'),
('APP0024', '0Q5EO', 'V7ZXT', '2016-08-17'),
('APP0002', '0FM12', 'V53JY', '2014-11-14'),
('APP0003', '0FM12', 'V53JY', '2015-04-08'),
('APP0004', '0FM12', 'V53JY', '2015-05-05'),
('APP0005', '0L56H', 'VT479', '2015-06-07'),
('APP0008', '0L56H', 'VT479', '2015-12-12'),
('APP0007', '0P75G', 'V3KVQ', '2015-12-01'),
('APP0011', '0P75G', 'VF421', '2016-01-01'),
('APP0006', '0LD4F', 'V25EM', '2015-08-08'),
('APP0009', '0LD4F', 'V25EM', '2015-12-13'),
('APP0014', '0LD4F', 'V25EM', '2016-02-09'),
('APP0017', '0LD4F', 'V25EM', '2016-04-06'),
('APP0023', '0IK3G', 'V091R', '2016-08-08'),
('APP0026', '0IK3G', 'V091R', '2016-09-09'),
('APP0025', '07FR3', 'V0005', '2016-09-01'),
('APP0015', '0JK90', 'V86A0', '2016-03-08'),
('APP0021', '0IK3Y', 'VRLIR', '2016-06-09');
INSERT INTO maintenanceOrders (app_id, c_id, v_id, mo_id, st_id) VALUES
('APP0010', '0URKY', 'V30S7', 'MO0010', '0074WA'),
('APP0016', '0URKY', 'V30S7', 'MO0016', '0074WA'),
('APP0019', '0URKY', 'V0T3A', 'MO0019', '0074WA'),
('APP0013', '0RLU1', 'VYYPG', 'MO0013', '0022TK'),
('APP0001', '0RLU1', 'VZENX', 'MO0001', '0022TK'),
('APP0012', '0QPG7', 'VKWMP', 'MO0012', '004X7E'),
('APP0018', '0QPG7', 'VKWMP', 'MO0018', '00UT75'),
('APP0020', '0Q5EO', 'V7ZXT', 'MO0020', '00Q3HU'),
('APP0022', '0Q5EO', 'V7ZXT', 'MO0022', '00Q3HU'),
('APP0024', '0Q5EO', 'V7ZXT', 'MO0024', '002IR0'),
('APP0002', '0FM12', 'V53JY', 'MO0002', '00UT75'),
('APP0003', '0FM12', 'V53JY', 'MO0003', '00UT75'),
('APP0004', '0FM12', 'V53JY', 'MO0004', '0074WA'),
('APP0005', '0L56H', 'VT479', 'MO0005', '0074WA'),
('APP0008', '0L56H', 'VT479', 'MO0008', '002IR0'),
('APP0007', '0P75G', 'V3KVQ', 'MO0007', '004X7E'),
('APP0011', '0P75G', 'VF421', 'MO0011', '00Q3HU'),
('APP0006', '0LD4F', 'V25EM', 'MO0006', '0022TK'),
('APP0009', '0LD4F', 'V25EM', 'MO0009', '0022TK'),
('APP0014', '0LD4F', 'V25EM', 'MO0014', '0022TK'),
('APP0017', '0LD4F', 'V25EM', 'MO0017', '00UT75'),
('APP0023', '0IK3G', 'V091R', 'MO0023', '002IR0'),
('APP0026', '0IK3G', 'V091R', 'MO0026', '002IR0');
INSERT INTO maintenancePackages (mp_id, packageName) VALUES
('000', 'not a package'),
('001', 'Tired of Tires'),
('010', 'Simple Changes'),
('011', 'Brake Up'),
('100', 'Brakes & Tires'),
('101', 'Oil & Catalytic Converter');
INSERT INTO maintenanceItems (mi_id, app_id, c_id, v_id, mo_id, mp_id, st_id, repairName, price) VALUES
('MI2Z', 'APP0010', '0URKY', 'V30S7', 'MO0010', '100', '0074WA', 'tire replacement', 200),
('MIQL', 'APP0010', '0URKY', 'V30S7', 'MO0010', '100', '0074WA', 'tire alignment', 60),
('MIR5', 'APP0010', '0URKY', 'V30S7', 'MO0010', '100', '0074WA', 'brake fluid replacement', 85),
('MIZS', 'APP0010', '0URKY', 'V30S7', 'MO0010', '100', '0074WA', 'brake pad replacement', 150),
('MI29', 'APP0016', '0URKY', 'V30S7', 'MO0016', '101', '0074WA', 'oil change', 20),
('MIXX', 'APP0016', '0URKY', 'V30S7', 'MO0016', '101', '0074WA', 'catalytic converter replacement', 900),
('MI4X', 'APP0016', '0URKY', 'V30S7', 'MO0016', '000', '0074WA', 'smog check', 50),
('MIOF', 'APP0019', '0URKY', 'V0T3A', 'MO0019', '000', '0074WA', 'spark plugs replacement', 300),
('MIXD', 'APP0013', '0RLU1', 'VYYPG', 'MO0013', '010', '0022TK', 'oil change', 20),
('MIMV', 'APP0013', '0RLU1', 'VYYPG', 'MO0013', '010', '0022TK', 'tire replacement', 200),
('MIJV', 'APP0013', '0RLU1', 'VYYPG', 'MO0013', '010', '0022TK', 'tire alignment', 60),
('MILK', 'APP0013', '0RLU1', 'VYYPG', 'MO0013', '010', '0022TK', 'battery replacement', 200),
('MILO', 'APP0001', '0RLU1', 'VZENX', 'MO0001', '000', '0022TK', 'spark plugs replacement', 300),
('MI6Y', 'APP0012', '0QPG7', 'VKWMP', 'MO0012', '000', '004X7E', 'light bulb replacement', 100),
('ML0M', 'APP0012', '0QPG7', 'VKWMP', 'MO0012', '000', '004X7E', 'battery replacement', 200),
('MIWR', 'APP0018', '0QPG7', 'VKWMP', 'MO0018', '000', '00UT75', 'transmission fluid replacement', 100),
('MIIX', 'APP0022', '0Q5EO', 'V7ZXT', 'MO0022', '011', '00Q3HU', 'brake fluid replacement', 85),
('MIEI', 'APP0022', '0Q5EO', 'V7ZXT', 'MO0022', '011', '00Q3HU', 'brake pad replacement', 150),
('MIFO', 'APP0024', '0Q5EO', 'V7ZXT', 'MO0024', '000', '002IR0', 'ignition wire replacement', 250),
('MAC1', 'APP0024', '0Q5EO', 'V7ZXT', 'MO0024', '000', '002IR0', 'smog check', 50),
('MOMY', 'APP0024', '0Q5EO', 'V7ZXT', 'MO0024', '010', '002IR0', 'battery replacement', 200),
('MIQ0', 'APP0002', '0FM12', 'V53JY', 'MO0002', '100', '00UT75', 'tire replacement', 200),
('MIFG', 'APP0002', '0FM12', 'V53JY', 'MO0002', '100', '00UT75', 'tire alignment', 60),
('MIMT', 'APP0002', '0FM12', 'V53JY', 'MO0002', '100', '00UT75', 'brake pad replacement', 150),
('MZAC', 'APP0002', '0FM12', 'V53JY', 'MO0002', '100', '00UT75', 'brake fluid replacement', 85),
('MIQA', 'APP0003', '0FM12', 'V53JY', 'MO0003', '000', '00UT75', 'oil change', 20),
('MICP', 'APP0005', '0L56H', 'VT479', 'MO0005', '100', '0074WA', 'tire replacement', 200),
('MIAA', 'APP0005', '0L56H', 'VT479', 'MO0005', '100', '0074WA', 'tire alignment', 60),
('MILE', 'APP0005', '0L56H', 'VT479', 'MO0005', '100', '0074WA', 'brake fluid replacement', 85),
('MI06', 'APP0005', '0L56H', 'VT479', 'MO0005', '100', '0074WA', 'brake pad replacement', 150),
('MI65', 'APP0008', '0L56H', 'VT479', 'MO0008', '000', '002IR0', 'spark plugs replacement', 300),
('MI9Y', 'APP0007', '0P75G', 'V3KVQ', 'MO0007', '000', '004X7E', 'transmission fluid replacement', 100),
('MITY', 'APP0011', '0P75G', 'VF421', 'MO0011', '101', '00Q3HU', 'oil change', 20),
('MIJS', 'APP0011', '0P75G', 'VF421', 'MO0011', '101', '00Q3HU', 'catalytic converter replacement', 900),
('MIS3', 'APP0006', '0LD4F', 'V25EM', 'MO0006', '000', '0022TK', 'ignition wire replacement', 250),
('MIZ3', 'APP0006', '0LD4F', 'V25EM', 'MO0006', '000', '0022TK', 'smog check', 50),
('MI68', 'APP0009', '0LD4F', 'V25EM', 'MO0009', '101', '0022TK', 'oil change', 20),
('MI2J', 'APP0009', '0LD4F', 'V25EM', 'MO0009', '101', '0022TK', 'catalytic converter replacement', 900),
('MIUO', 'APP0014', '0LD4F', 'V25EM', 'MO0014', '000', '0022TK', 'brake fluid replacement', 85),
('MID1', 'APP0017', '0LD4F', 'V25EM', 'MO0017', '000', '00UT75', 'oil change', 20),
('MI3H', 'APP0023', '0IK3G', 'V091R', 'MO0023', '010', '002IR0', 'oil change', 20),
('MI04', 'APP0023', '0IK3G', 'V091R', 'MO0023', '010', '002IR0', 'tire replacement', 200),
('MIDK', 'APP0023', '0IK3G', 'V091R', 'MO0023', '010', '002IR0', 'tire alignment', 60),
('MI1S', 'APP0023', '0IK3G', 'V091R', 'MO0023', '010', '002IR0', 'battery replacement', 200),
('MIZ8', 'APP0026', '0IK3G', 'V091R', 'MO0026', '000', '002IR0', 'oil change', 20),
('MI42', 'APP0020', '0Q5EO', 'V7ZXT', 'MO0020', '000', '00Q3HU', 'catalytic converter replacement', 900),
('MILY', 'APP0004', '0FM12', 'V53JY', 'MO0004', '000', '0074WA', 'oil change', 20),
('MSAI', 'APP0024', '0Q5EO', 'V7ZXT', 'MO0024', '010', '002IR0', 'tire replacement', 200),
('MD6Y', 'APP0024', '0Q5EO', 'V7ZXT', 'MO0024', '010', '002IR0', 'tire alignment', 60),
('MDQY', 'APP0024', '0Q5EO', 'V7ZXT', 'MO0024', '010', '002IR0', 'oil change', 20);
INSERT INTO skills_needed (mi_id, app_id, c_id, v_id, mo_id, mp_id, st_id, skillName) VALUES
('MI2Z', 'APP0010', '0URKY', 'V30S7', 'MO0010', '100', '0074WA', 'change tires'),
('MIQL', 'APP0010', '0URKY', 'V30S7', 'MO0010', '100', '0074WA', 'align tires'),
('MIR5', 'APP0010', '0URKY', 'V30S7', 'MO0010', '100', '0074WA', 'inspect brakes'),
('MIR5', 'APP0010', '0URKY', 'V30S7', 'MO0010', '100', '0074WA', 'replace brake fluid'),
('MIZS', 'APP0010', '0URKY', 'V30S7', 'MO0010', '100', '0074WA', 'inspect brakes'),
('MIZS', 'APP0010', '0URKY', 'V30S7', 'MO0010', '100', '0074WA', 'replace brake pads'),
('MI29', 'APP0016', '0URKY', 'V30S7', 'MO0016', '101', '0074WA', 'change oil'),
('MIXX', 'APP0016', '0URKY', 'V30S7', 'MO0016', '101', '0074WA', 'replace catalytic converter'),
('MI4X', 'APP0016', '0URKY', 'V30S7', 'MO0016', '000', '0074WA', 'inspect smog'),
('MIOF', 'APP0019', '0URKY', 'V0T3A', 'MO0019', '000', '0074WA','replace spark plugs'),
('MIXD', 'APP0013', '0RLU1', 'VYYPG', 'MO0013', '010', '0022TK', 'change oil'),
('MIMV', 'APP0013', '0RLU1', 'VYYPG', 'MO0013', '010', '0022TK', 'change tires'),
('MIJV', 'APP0013', '0RLU1', 'VYYPG', 'MO0013', '010', '0022TK', 'align tires'),
('MILK', 'APP0013', '0RLU1', 'VYYPG', 'MO0013', '010', '0022TK', 'inspect battery'),
('MILK', 'APP0013', '0RLU1', 'VYYPG', 'MO0013', '010', '0022TK', 'replace battery'),
('MILO', 'APP0001', '0RLU1', 'VZENX', 'MO0001', '000', '0022TK', 'replace spark plugs'),
('MI6Y', 'APP0012', '0QPG7', 'VKWMP', 'MO0012', '000', '004X7E', 'replace light bulbs'),
('ML0M', 'APP0012', '0QPG7', 'VKWMP', 'MO0012', '000', '004X7E', 'replace battery'),
('ML0M', 'APP0012', '0QPG7', 'VKWMP', 'MO0012', '000', '004X7E', 'inspect battery'),
('MIWR', 'APP0018', '0QPG7', 'VKWMP', 'MO0018', '000', '00UT75', 'replace transmission fluid'),
('MIIX', 'APP0022', '0Q5EO', 'V7ZXT', 'MO0022', '011', '00Q3HU', 'replace brake fluid'),
('MIIX', 'APP0022', '0Q5EO', 'V7ZXT', 'MO0022', '011', '00Q3HU', 'inspect brakes'),
('MIEI', 'APP0022', '0Q5EO', 'V7ZXT', 'MO0022', '011', '00Q3HU', 'replace brake pads'),
('MIEI', 'APP0022', '0Q5EO', 'V7ZXT', 'MO0022', '011', '00Q3HU', 'inspect brakes'),
('MIFO', 'APP0024', '0Q5EO', 'V7ZXT', 'MO0024', '000', '002IR0', 'replace ignition wires'),
('MAC1', 'APP0024', '0Q5EO', 'V7ZXT', 'MO0024', '000', '002IR0', 'inspect smog'),
('MOMY', 'APP0024', '0Q5EO', 'V7ZXT', 'MO0024', '010', '002IR0', 'inspect battery'),
('MOMY', 'APP0024', '0Q5EO', 'V7ZXT', 'MO0024', '010', '002IR0', 'replace battery'),
('MIQ0', 'APP0002', '0FM12', 'V53JY', 'MO0002', '100', '00UT75', 'change tires'),
('MIFG', 'APP0002', '0FM12', 'V53JY', 'MO0002', '100', '00UT75', 'align tires'),
('MIMT', 'APP0002', '0FM12', 'V53JY', 'MO0002', '100', '00UT75', 'inspect brakes'),
('MIMT', 'APP0002', '0FM12', 'V53JY', 'MO0002', '100', '00UT75', 'replace brake pads'),
('MIQA', 'APP0003', '0FM12', 'V53JY', 'MO0003', '000', '00UT75', 'change oil'),
('MICP', 'APP0005', '0L56H', 'VT479', 'MO0005', '100', '0074WA', 'change tires'),
('MIAA', 'APP0005', '0L56H', 'VT479', 'MO0005', '100', '0074WA', 'align tires'),
('MILE', 'APP0005', '0L56H', 'VT479', 'MO0005', '100', '0074WA', 'inspect brakes'),
('MILE', 'APP0005', '0L56H', 'VT479', 'MO0005', '100', '0074WA', 'replace brake fluid'),
('MI06', 'APP0005', '0L56H', 'VT479', 'MO0005', '100', '0074WA', 'inspect brakes'),
('MI06', 'APP0005', '0L56H', 'VT479', 'MO0005', '100', '0074WA', 'replace brake pads'),
('MI65', 'APP0008', '0L56H', 'VT479', 'MO0008', '000', '002IR0', 'replace spark plugs'),
('MI9Y', 'APP0007', '0P75G', 'V3KVQ', 'MO0007', '000', '004X7E', 'replace transmission fluid'),
('MITY', 'APP0011', '0P75G', 'VF421', 'MO0011', '101', '00Q3HU', 'change oil'),
('MIJS', 'APP0011', '0P75G', 'VF421', 'MO0011', '101', '00Q3HU', 'replace catalytic converter'),
('MIS3', 'APP0006', '0LD4F', 'V25EM', 'MO0006', '000', '0022TK', 'replace ignition wires'),
('MIZ3', 'APP0006', '0LD4F', 'V25EM', 'MO0006', '000', '0022TK', 'inspect smog'),
('MI68', 'APP0009', '0LD4F', 'V25EM', 'MO0009', '101', '0022TK', 'change oil'),
('MI2J', 'APP0009', '0LD4F', 'V25EM', 'MO0009', '101', '0022TK', 'replace catalytic converter'),
('MIUO', 'APP0014', '0LD4F', 'V25EM', 'MO0014', '000', '0022TK', 'inspect brakes'),
('MIUO', 'APP0014', '0LD4F', 'V25EM', 'MO0014', '000', '0022TK','replace brake fluid'),
('MID1', 'APP0017', '0LD4F', 'V25EM', 'MO0017', '000', '00UT75', 'change oil'),
('MI3H', 'APP0023', '0IK3G', 'V091R', 'MO0023', '010', '002IR0', 'change oil'),
('MI04', 'APP0023', '0IK3G', 'V091R', 'MO0023', '010', '002IR0', 'change tires'),
('MIDK', 'APP0023', '0IK3G', 'V091R', 'MO0023', '010', '002IR0', 'align tires'),
('MI1S', 'APP0023', '0IK3G', 'V091R', 'MO0023', '010', '002IR0', 'inspect battery' ),
('MI1S', 'APP0023', '0IK3G', 'V091R', 'MO0023', '010', '002IR0', 'replace battery'),
('MIZ8', 'APP0026', '0IK3G', 'V091R', 'MO0026', '000', '002IR0', 'change oil'),
('MI42', 'APP0020', '0Q5EO', 'V7ZXT', 'MO0020', '000', '00Q3HU', 'replace catalytic converter'),
('MILY', 'APP0004', '0FM12', 'V53JY', 'MO0004', '000', '0074WA', 'change oil'),
('MSAI', 'APP0024', '0Q5EO', 'V7ZXT', 'MO0024', '010', '002IR0', 'change tires'),
('MD6Y', 'APP0024', '0Q5EO', 'V7ZXT', 'MO0024', '010', '002IR0','align tires'),
('MDQY', 'APP0024', '0Q5EO', 'V7ZXT', 'MO0024', '010', '002IR0','change oil'),
('MZAC', 'APP0002', '0FM12', 'V53JY', 'MO0002', '100', '00UT75', 'inspect brakes'),
('MZAC', 'APP0002', '0FM12', 'V53JY', 'MO0002', '100', '00UT75', 'replace brake fluid');
INSERT INTO assignments (mi_id, app_id, c_id, v_id, mo_id, mp_id, st_id, mech_id, assignmentDate) VALUES
('MI2Z', 'APP0010', '0URKY', 'V30S7', 'MO0010', '100', '0074WA', '0074WA', '2015-12-21'),
('MIR5', 'APP0010', '0URKY', 'V30S7', 'MO0010', '100', '0074WA', '004X7E', '2015-12-21'),
('MIZS', 'APP0010', '0URKY', 'V30S7', 'MO0010', '100', '0074WA', '00B21W', '2015-12-23'),
('MI29', 'APP0016', '0URKY', 'V30S7', 'MO0016', '101', '0074WA', '0097N2', '2016-03-12'),
('MIXX', 'APP0016', '0URKY', 'V30S7', 'MO0016', '101', '0074WA', '0097N2', '2016-03-11'),
('MI4X', 'APP0016', '0URKY', 'V30S7', 'MO0016', '000', '0074WA', '00B21W', '2016-03-11'),
('MIOF', 'APP0019', '0URKY', 'V0T3A', 'MO0019', '000', '0074WA', '004X7E', '2016-05-11'),
('MIXD', 'APP0013', '0RLU1', 'VYYPG', 'MO0013', '010', '0022TK', '00RYVF', '2016-01-10'),
('MIMV', 'APP0013', '0RLU1', 'VYYPG', 'MO0013', '010', '0022TK', '00JNKS', '2016-01-14'),
('MIJV', 'APP0013', '0RLU1', 'VYYPG', 'MO0013', '010', '0022TK', '00JNKS', '2016-01-11'),
('MILK', 'APP0013', '0RLU1', 'VYYPG', 'MO0013', '010', '0022TK', '0097N2', '2016-01-11'),
('MILO', 'APP0001', '0RLU1', 'VZENX', 'MO0001', '000', '0022TK', '004X7E', '2013-03-06'),
('MI6Y', 'APP0012', '0QPG7', 'VKWMP', 'MO0012', '000', '004X7E', '00O0QT', '2016-01-07'),
('ML0M', 'APP0012', '0QPG7', 'VKWMP', 'MO0012', '000', '004X7E', '00B21W', '2016-01-07'),
('MIWR', 'APP0018', '0QPG7', 'VKWMP', 'MO0018', '000', '00UT75', '0074WA', '2016-04-13'),
('MI42', 'APP0020', '0Q5EO', 'V7ZXT', 'MO0020', '000', '00Q3HU', '00RYVF', '2016-05-29'),
('MIIX', 'APP0022', '0Q5EO', 'V7ZXT', 'MO0022', '011', '00Q3HU', '00O0QT', '2016-07-10'),
('MIEI', 'APP0022', '0Q5EO', 'V7ZXT', 'MO0022', '011', '00Q3HU', '00B21W', '2016-07-09'),
('MIFO', 'APP0024', '0Q5EO', 'V7ZXT', 'MO0024', '000', '002IR0', '00B21W', '2016-08-17'),
('MAC1', 'APP0024', '0Q5EO', 'V7ZXT', 'MO0024', '000', '002IR0', '00RYVF', '2016-08-18'),
('MOMY', 'APP0024', '0Q5EO', 'V7ZXT', 'MO0024', '010', '002IR0', '00JNKS', '2016-08-17'),
('MSAI', 'APP0024', '0Q5EO', 'V7ZXT', 'MO0024', '010', '002IR0', '00JNKS', '2016-08-17'),
('MD6Y', 'APP0024', '0Q5EO', 'V7ZXT', 'MO0024', '010', '002IR0', '00JNKS', '2016-08-17'),
('MDQY', 'APP0024', '0Q5EO', 'V7ZXT', 'MO0024', '010', '002IR0', '00JNKS', '2016-08-17'),
('MIQ0', 'APP0002', '0FM12', 'V53JY', 'MO0002', '100', '00UT75', '004X7E', '2014-11-14'),
('MIFG', 'APP0002', '0FM12', 'V53JY', 'MO0002', '100', '00UT75', '00V5KL', '2014-11-15'),
('MIMT', 'APP0002', '0FM12', 'V53JY', 'MO0002', '100', '00UT75', '00B21W', '2014-11-14'),
('MIQA', 'APP0003', '0FM12', 'V53JY', 'MO0003', '000', '00UT75', '0097N2', '2015-04-08'),
('MILY', 'APP0004', '0FM12', 'V53JY', 'MO0004', '000', '0074WA', '00O0QT', '2015-05-05'),
('MICP', 'APP0005', '0L56H', 'VT479', 'MO0005', '100', '0074WA', '00RYVF', '2015-06-07'),
('MILE', 'APP0005', '0L56H', 'VT479', 'MO0005', '100', '0074WA', '004X7E', '2015-06-07'),
('MI06', 'APP0005', '0L56H', 'VT479', 'MO0005', '100', '0074WA', '00O0QT', '2015-06-07'),
('MI65', 'APP0008', '0L56H', 'VT479', 'MO0008', '000', '002IR0', '0074WA', '2015-12-12'),
('MI9Y', 'APP0007', '0P75G', 'V3KVQ', 'MO0007', '000', '004X7E', '00JNKS', '2015-12-02'),
('MITY', 'APP0011', '0P75G', 'VF421', 'MO0011', '101', '00Q3HU', '00Q3HU', '2016-01-02'),
('MIJS', 'APP0011', '0P75G', 'VF421', 'MO0011', '101', '00Q3HU', '00JNKS', '2016-01-03'),
('MIS3', 'APP0006', '0LD4F', 'V25EM', 'MO0006', '000', '0022TK', '0097N2', '2015-08-08'),
('MIZ3', 'APP0006', '0LD4F', 'V25EM', 'MO0006', '000', '0022TK', '00V5KL', '2015-08-08'),
('MI68', 'APP0009', '0LD4F', 'V25EM', 'MO0009', '101', '0022TK', '00RYVF', '2015-12-13'),
('MI2J', 'APP0009', '0LD4F', 'V25EM', 'MO0009', '101', '0022TK', '00JNKS', '2015-12-14'),
('MIUO', 'APP0014', '0LD4F', 'V25EM', 'MO0014', '000', '0022TK', '00O0QT', '2016-02-10'),
('MID1', 'APP0017', '0LD4F', 'V25EM', 'MO0017', '000', '00UT75', '00JNKS', '2016-04-06'),
('MI3H', 'APP0023', '0IK3G', 'V091R', 'MO0023', '010', '002IR0', '00Q3HU', '2016-08-08'),
('MI04', 'APP0023', '0IK3G', 'V091R', 'MO0023', '010', '002IR0', '004X7E', '2016-08-08'),
('MIDK', 'APP0023', '0IK3G', 'V091R', 'MO0023', '010', '002IR0', '00V5KL', '2016-08-09'),
('MI1S', 'APP0023', '0IK3G', 'V091R', 'MO0023', '010', '002IR0', '00O0QT', '2016-08-09'),
('MIZ8', 'APP0026', '0IK3G', 'V091R', 'MO0026', '000', '002IR0', '00V5KL', '2016-09-09'),
('MZAC', 'APP0002', '0FM12', 'V53JY', 'MO0002', '100', '00UT75', '00JNKS', '2014-11-14');
INSERT INTO referral_c (proC_id, sc_id) VALUES
('07FR3', '0URKY'),
('0JK90', '0Q5EO'),
('0IK3Y', '0LD4F');
INSERT INTO specials (s_id, discountRate) VALUES
('SP01', 0.05),
('SP02', 0.10),
('SP03', 0.15),
('SP04', 0.20),
('SP05', 0.50);
INSERT INTO offers (proC_id, s_id, offer, contactDate, expirationDate) VALUES
('07FR3', 'SP01', 'battery replacement', '2015-02-05', '2015-03-05'),
('07FR3', 'SP03', 'oil change', '2014-05-23', '2015-06-23'),
('07FR3', 'SP05', 'tire replacement', '2014-08-15', '2015-09-15'),
('0JK90', 'SP02', 'tire alignment', '2016-03-16', '2016-04-16'),
('0IK3Y', 'SP02', 'tire replacement', '2016-04-15', '2016-05-15'),
('0IK3Y', 'SP04', 'oil change', '2016-07-29', '2016-08-29');
INSERT INTO monthlyInstallments (c_id, v_id, preC_id, monthStarted, amountDue) VALUES
('0RLU1', 'VYYPG', '0RLU1', 'Febuary', 80.00),
('0RLU1', 'VZENX', '0RLU1', 'March', 80.00),
('0FM12', 'V53JY', '0FM12', 'June', 70.00),
('0L56H', 'VT479', '0L56H', 'November', 50.00);
INSERT INTO notifications (c_id, v_id, sc_id, emailDate) VALUES
('0URKY', 'V30S7', '0URKY', '2017-01-21'),
('0URKY', 'V0T3A', '0URKY', '2017-01-21'),
('0QPG7', 'VKWMP', '0QPG7', '2017-02-05'),
('0P75G', 'V3KVQ', '0P75G', '2017-01-01'),
('0Q5EO', 'V7ZXT', '0Q5EO', '2017-01-28'),
('0LD4F', 'V25EM', '0LD4F', '2017-01-05'),
('0IK3G', 'V091R', '0IK3G', '2017-01-05');
|
C#
|
UTF-8
| 624
| 3.015625
| 3
|
[] |
no_license
|
using System;
using Common;
using System.IO;
namespace Sender
{
class Program
{
static void Main(string[] args)
{
var pipe = PipeHelper.CreateClient(PipeNames.Sender);
var writer = new StreamWriter(pipe);
while (true)
{
Console.Write("Type your message: ");
var message = Console.ReadLine();
Console.WriteLine($"Sending: {message}");
writer.WriteLine(message);
writer.Flush();
Console.WriteLine($"Message Sent!");
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.