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
|
---|---|---|---|---|---|---|---|
SQL
|
UTF-8
| 5,480 | 2.609375 | 3 |
[] |
no_license
|
-- dml/532.sql
-- script changes from change pond
-- Making Existing Entries false; let me know if you wish this to be deleted.
update reportassessmentprogram set activeflag=false;
-- Insert scripts for given combinations.
Select * from reportassessmentprogram_fn('KAP','GEN_ST','ELA','VIEW_GENERAL_STUDENT_REPORT');
Select * from reportassessmentprogram_fn('KAP','GEN_ST','M','VIEW_GENERAL_STUDENT_REPORT');
Select * from reportassessmentprogram_fn('KAP','GEN_ST','SS','VIEW_GENERAL_STUDENT_REPORT');
Select * from reportassessmentprogram_fn('KAP','GEN_ST_ALL','','VIEW_GNRL_STUDENT_RPT_BUNDLED');
Select * from reportassessmentprogram_fn('KAP','GEN_SD','ELA','VIEW_GENERAL_SCHOOL_REPORT');
Select * from reportassessmentprogram_fn('KAP','GEN_SD','M','VIEW_GENERAL_SCHOOL_REPORT');
Select * from reportassessmentprogram_fn('KAP','GEN_SD','SS','VIEW_GENERAL_SCHOOL_REPORT');
Select * from reportassessmentprogram_fn('KAP','GEN_SS','ELA','VIEW_GENERAL_SCHOOL_REPORT');
Select * from reportassessmentprogram_fn('KAP','GEN_SS','M','VIEW_GENERAL_SCHOOL_REPORT');
Select * from reportassessmentprogram_fn('KAP','GEN_SS','SS','VIEW_GENERAL_SCHOOL_REPORT');
Select * from reportassessmentprogram_fn('KAP','GEN_DD','ELA','VIEW_GENERAL_DISTRICT_REPORT');
Select * from reportassessmentprogram_fn('KAP','GEN_DD','M','VIEW_GENERAL_DISTRICT_REPORT');
Select * from reportassessmentprogram_fn('KAP','GEN_DD','SS','VIEW_GENERAL_DISTRICT_REPORT');
Select * from reportassessmentprogram_fn('KAP','GEN_DS','ELA','VIEW_GENERAL_DISTRICT_REPORT');
Select * from reportassessmentprogram_fn('KAP','GEN_DS','M','VIEW_GENERAL_DISTRICT_REPORT');
Select * from reportassessmentprogram_fn('KAP','GEN_DS','SS','VIEW_GENERAL_DISTRICT_REPORT');
Select * from reportassessmentprogram_fn('cPass','GEN_ST','GKS','');
Select * from reportassessmentprogram_fn('cPass','GEN_ST','AGF&NR','');
Select * from reportassessmentprogram_fn('cPass','GEN_ST','MFG','');
Select * from reportassessmentprogram_fn('cPass','GEN_ST_ALL','GKS','');
Select * from reportassessmentprogram_fn('cPass','GEN_ST_ALL','AGF&NR','');
Select * from reportassessmentprogram_fn('cPass','GEN_ST_ALL','MFG','');
Select * from reportassessmentprogram_fn('cPass','GEN_SD','GKS','');
Select * from reportassessmentprogram_fn('cPass','GEN_SD','AGF&NR','');
Select * from reportassessmentprogram_fn('cPass','GEN_SD','MFG','');
Select * from reportassessmentprogram_fn('DLM','ALT_ST','ELA','VIEW_ALTERNATE_STUDENT_REPORT');
Select * from reportassessmentprogram_fn('DLM','ALT_ST','M','VIEW_ALTERNATE_STUDENT_REPORT');
Select * from reportassessmentprogram_fn('DLM','ALT_CR','ELA','VIEW_ALTERNATE_ROSTER_REPORT');
Select * from reportassessmentprogram_fn('DLM','ALT_CR','M','VIEW_ALTERNATE_ROSTER_REPORT');
Select * from reportassessmentprogram_fn('DLM','GEN_ST','ELA','');
Select * from reportassessmentprogram_fn('DLM','GEN_ST','M','');
Select * from reportassessmentprogram_fn('DLM','GEN_ST','SCI','');
Select * from reportassessmentprogram_fn('DLM','GEN_ST','SS','');
Select * from reportassessmentprogram_fn('DLM','GEN_ST_ALL','','');
-- Added access for Alaska reports
-- Still have to update ready to view flag and reports set up tab
Select * from reportassessmentprogram_fn('AMP','GEN_ST','ELA','VIEW_GENERAL_STUDENT_REPORT');
Select * from reportassessmentprogram_fn('AMP','GEN_ST','M','VIEW_GENERAL_STUDENT_REPORT');
Select * from reportassessmentprogram_fn('AMP','GEN_ST_ALL','','VIEW_GNRL_STUDENT_RPT_BUNDLED');
Select * from reportassessmentprogram_fn('AMP','GEN_SD','ELA','VIEW_GENERAL_SCHOOL_REPORT');
Select * from reportassessmentprogram_fn('AMP','GEN_SD','M','VIEW_GENERAL_SCHOOL_REPORT');
Select * from reportassessmentprogram_fn('AMP','GEN_SS','ELA','VIEW_GENERAL_SCHOOL_REPORT');
Select * from reportassessmentprogram_fn('AMP','GEN_SS','M','VIEW_GENERAL_SCHOOL_REPORT');
Select * from reportassessmentprogram_fn('AMP','GEN_DD','ELA','VIEW_GENERAL_DISTRICT_REPORT');
Select * from reportassessmentprogram_fn('AMP','GEN_DD','M','VIEW_GENERAL_DISTRICT_REPORT');
Select * from reportassessmentprogram_fn('AMP','GEN_DS','ELA','VIEW_GENERAL_DISTRICT_REPORT');
Select * from reportassessmentprogram_fn('AMP','GEN_DS','M','VIEW_GENERAL_DISTRICT_REPORT');
-- remove permission
UPDATE AUTHORITIES SET activeflag = false where displayname = 'Lock AMP Reports' and authority = 'LOCK_AMP_REPORTS';
-- add new permission
INSERT INTO authorities(authority, displayname, objecttype, createddate, createduser,
activeflag, modifieddate, modifieduser)
VALUES ('VIEW_REPORT_CONTROL_ACCESS', 'View Reports Control Access', 'Reports-Performance Reports',CURRENT_TIMESTAMP,(select id from aartuser where email='cete@ku.edu'), true,
CURRENT_TIMESTAMP,(select id from aartuser where email='cete@ku.edu'));
INSERT INTO authorities(authority, displayname, objecttype, createddate, createduser,
activeflag, modifieddate, modifieduser)
VALUES ('EDIT_REPORT_CONTROL_ACCESS', 'Edit Reports Control Access', 'Reports-Performance Reports',CURRENT_TIMESTAMP,(select id from aartuser where email='cete@ku.edu'), true,
CURRENT_TIMESTAMP,(select id from aartuser where email='cete@ku.edu'));
update fieldspecification set rejectifempty = false, rejectifinvalid = false, showerror = false where fieldname= 'comment' and id in(
select fieldspecificationid from fieldspecificationsrecordtypes where recordtypeid =(select id from category where categorycode='COMBINED_LEVEL_MAP')
);
|
C++
|
UTF-8
| 1,444 | 3.265625 | 3 |
[] |
no_license
|
#include <util/string.h>
#include <catch/catch.hpp>
TEST_CASE("split", "[string]") {
SECTION("zero") {
CHECK(util::split("", ',') == std::vector<std::string>{ "" });
CHECK(util::split(" ", ',') == std::vector<std::string>{ " " });
CHECK(util::split("a", ',') == std::vector<std::string>{ "a" });
CHECK(util::split("abcd", ',') == std::vector<std::string>{ "abcd" });
}
SECTION("positive") {
CHECK(util::split(",", ',') == std::vector<std::string>{ "", "" });
CHECK(util::split("a,b", ',') == std::vector<std::string>{ "a", "b" });
CHECK(util::split("a,b,c", ',') == std::vector<std::string>{ "a", "b", "c" });
CHECK(util::split(",,,", ',') == std::vector<std::string>{ "", "", "", "" });
CHECK(util::split("one,two,three", ',') == std::vector<std::string>{ "one", "two", "three" });
}
SECTION("negative") {
CHECK(util::split("one,two,three", ' ') == std::vector<std::string>{ "one,two,three" });
}
}
TEST_CASE("strip", "[string]") {
std::string empty = "";
std::string abc = "abc";
SECTION("negative") {
util::strip(empty, '"');
CHECK(empty == "");
util::strip(abc, '"');
CHECK(abc == "abc");
}
SECTION("positive") {
util::strip(abc, 'a');
CHECK(abc == "bc");
std::string a = "\"hello\"";
util::strip(a, '"');
CHECK(a == "hello");
}
}
|
Java
|
UTF-8
| 351 | 2.1875 | 2 |
[] |
no_license
|
package bean;
import org.jgrapht.graph.DefaultWeightedEdge;
import javax.xml.bind.annotation.XmlElement;
public class Edge extends DefaultWeightedEdge{
private Flight flight;
@XmlElement
public Flight getFlight()
{
return flight;
}
public void setFlight(Flight flight)
{
this.flight = flight;
}
}
|
Java
|
UTF-8
| 1,943 | 2.0625 | 2 |
[] |
no_license
|
package com.cess.clinica.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@Entity
@Table(name="habitacion")
public class Habitacion implements Serializable{
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
@ManyToOne
@JoinColumn(name="piso_id")
private Piso piso;
@ManyToOne
@JoinColumn(name="estado_id")
@JsonIgnoreProperties("habitaciones")
private EstadoHabitacion estadoHabitacion;
@ManyToOne
@JoinColumn(name="tipo_id")
private TipoHabitacion tipoHabitacion;
@ManyToOne
@JoinColumn(name="genero_id")
private Genero genero;
private String numero;
@Column(name="hay_paciente")
private boolean hayPaciente;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Piso getPiso() {
return piso;
}
public void setPiso(Piso piso) {
this.piso = piso;
}
public EstadoHabitacion getEstadoHabitacion() {
return estadoHabitacion;
}
public void setEstadoHabitacion(EstadoHabitacion estadoHabitacion) {
this.estadoHabitacion = estadoHabitacion;
}
public TipoHabitacion getTipoHabitacion() {
return tipoHabitacion;
}
public void setTipoHabitacion(TipoHabitacion tipoHabitacion) {
this.tipoHabitacion = tipoHabitacion;
}
public Genero getGenero() {
return genero;
}
public void setGenero(Genero genero) {
this.genero = genero;
}
public String getNumero() {
return numero;
}
public void setNumero(String numero) {
this.numero = numero;
}
public boolean isHayPaciente() {
return hayPaciente;
}
public void setHayPaciente(boolean hayPaciente) {
this.hayPaciente = hayPaciente;
}
}
|
Python
|
UTF-8
| 3,131 | 3.359375 | 3 |
[] |
no_license
|
# defender.py
# mg 2013
#
# look - think - behave
import rg
class Brain:
# Empty actions dict
actions = {}
# Constructor
# initialize the actions dict
# set the instance variables
# copy down the game and the robot's parameters
def __init__(self, r, g):
self.actions = {'move': True,
'guard': False,
'attack': False,
'suicide': False}
self.center = False
self.surrounded = False
self.enemies = []
self.robot = r
self.game = g
# Observe the board
def look(self):
# If I'm at the center, mark center as true
if self.robot.location == rg.CENTER_POINT:
self.center = True
# If there are more than 2 enemies next to me
# mark surrounded as true
self.enemies = self.count_enemies()
if len(self.enemies) > 2:
self.surrounded = True
# Make an assessment
def think(self):
# If I'm surrounded sacrifice myself for
# the greater good of the team
if self.surrounded:
self.actions['suicide'] = True
# If I'm at the center, CASTLE UP!
if self.center:
self.stop()
self.actions['guard']
# If my health is low, head for the center
if self.robot.hp <= 20:
self.actions['move'] = True
# If my health is ok, attack if I can,
# or head for the center
elif self.robot.hp <= 50:
self.actions['attack'] = True
self.actions['move'] = True
# If my health is high, attack with prejudice!
else:
self.actions['attack'] = True
# Act accordingly
def behave(self):
# From hell's heart I stab at thee
# for hate's sake, my last breath I spit at thee
if self.actions['suicide']:
return ['suicide']
# Attack if I can
if self.actions['attack']:
if len(self.enemies) > 0:
for loc in self.enemies:
if rg.dist(loc, self.robot.location) <= 1:
return ['attack', loc]
# Move towards the center
if self.actions['move']:
new_loc = rg.toward(self.robot.location, rg.CENTER_POINT)
return ['move', new_loc]
# Protect the herd
if self.actions['guard']:
return ['guard']
# Read a list of enemy locations
# Return a list of adjacent enemies
def count_enemies(self):
around = rg.locs_around(self.robot.location,
filter_out=('invalid','obstacle'))
enemies = self.check_for_enemies()
enemy_locs = []
for l in around:
for e in enemies:
if l == e:
enemy_locs.append(e)
return enemy_locs
# Scan the board for a enemy bots
# return a list of enemy locations (list of tuples)
def check_for_enemies(self):
bots = []
for loc, bot in self.game.get('robots').items():
if bot.player_id != self.robot.player_id:
bots.append(loc)
return bots
# Clear all actions from the actions dict
def stop(self):
for a in self.actions:
self.actions[a] = False
class Robot:
def act(self, game):
robot = self
# Give the bot a brain
ai = Brain(robot, game)
# look - think - act
ai.look()
ai.think()
action = ai.behave()
# Do the needful
return action
|
Java
|
UTF-8
| 927 | 3.578125 | 4 |
[] |
no_license
|
package com.omisoft.basic_java.Threads.practice;
public class Bank {
public void doTransaction(Transaction transaction)
{
int balance;
switch(transaction.getType())
{
case CREDIT:
synchronized(transaction.getAccount())
{
balance = transaction.getAccount().getBalance();
}
try
{
Thread.sleep(100);
}
catch(InterruptedException e)
{
System.out.println(e);
}
balance += transaction.getAmount();
transaction.getAccount().setBalance(balance);
break;
case DEBIT:
synchronized (transaction.getAccount()) {
balance = transaction.getAccount().getBalance();
}
try
{
Thread.sleep(150);
}
catch(InterruptedException e)
{
System.out.println(e);
}
balance -= transaction.getAmount();
transaction.getAccount().setBalance(balance);
break;
default:
System.out.println("Invalid transaction");
System.exit(1);
}
}
}
|
JavaScript
|
UTF-8
| 4,189 | 2.734375 | 3 |
[] |
no_license
|
import React, {Component} from "react";
import { BrowserRouter as Router, Route } from "react-router-dom";
import Home from './components/Home';
import UserProfile from './components/UserProfile';
import LogIn from './components/LogIn';
import Debit from './components/Debit';
import Credit from './components/Credit';
import axios from 'axios';
class App extends Component {
constructor() {
super();
this.state = {
accountBalance: 0,
currentUser: {
userName: 'bob_loblaw',
memberSince: '08/23/99',
},
creditData: [],
creditBalance: 0,
debitData: [],
debitBalance: 0,
}
}
// LOGIN
mockLogIn = (logInInfo) => {
const newUser = {...this.state.currentUser}
newUser.userName = logInInfo.userName
this.setState({currentUser: newUser})
}
// INITIAL MOUNTS
componentDidMount() {
this.fetchCredit();
this.fetchDebit();
}
// API CALLS
// CREDIT
fetchCredit=()=>{
axios.get(`https://moj-api.herokuapp.com/credits`)
.then(res => {
this.setState({
creditData : res.data,
})
this.calculateCredit();
this.calculateBalance();
})
.catch(err => {
console.log(err);
})
}
// DEBIT
fetchDebit=()=>{
axios.get(`https://moj-api.herokuapp.com/debits`)
.then(res => {
this.setState({
debitData : res.data,
})
this.calculateDebit();
this.calculateBalance();
})
.catch(err => {
console.log(err);
})
}
// ADDING CREDIT AND DEBIT CARDS TO DATA
// CREDIT
addNewCredit = (des, amount) =>{
let new_data = {
description : des,
amount : amount,
}
let num = this.state.accountBalance + new_data.amount;
num = num.toFixed(2);
num = parseFloat(num);
this.setState(prevState => ({
creditData: [...prevState.creditData, new_data],
accountBalance: num,
}))
}
// DEBIT
addNewDebit = (des, amount) =>{
let new_data = {
description : des,
amount : amount,
}
let num = this.state.accountBalance - new_data.amount;
num = num.toFixed(2);
num = parseFloat(num);
this.setState(prevState => ({
debitData: [...prevState.debitData, new_data],
accountBalance: num,
}))
}
// INITIAL CALCULATIONS AFTER API CALL
// BALANCE
calculateBalance = () => {
let num = this.state.creditBalance - this.state.debitBalance;
num = num.toFixed(2);
num = parseFloat(num);
this.setState({
accountBalance: num,
})
}
// CREDIT
calculateCredit = () => {
let value = 0;
for(let i = 0; i < this.state.creditData.length; i++) {
value += this.state.creditData[i].amount;
}
value = value.toFixed(2);
value = parseFloat(value);
this.setState({
creditBalance : value,
})
}
// DEBIT
calculateDebit = () => {
let value = 0;
for(let i = 0; i < this.state.debitData.length; i++) {
value += this.state.debitData[i].amount;
}
value = value.toFixed(2);
value = parseFloat(value);
this.setState({
debitBalance : value,
})
}
render() {
const HomeComponent = () => (<Home accountBalance={this.state.accountBalance}/>);
const UserProfileComponent = () => (<UserProfile user={this.state.currentUser} balance={this.state.accountBalance} />);
const LogInComponent = () => (<LogIn user={this.state.currentUser} mockLogIn={this.mockLogIn} />);
const DebitComponent = () => (<Debit debitData={this.state.debitData} addNewDebit={this.addNewDebit} balance={this.state.accountBalance}/>);
const CreditComponent = () => (<Credit creditData={this.state.creditData} addNewCredit={this.addNewCredit} balance={this.state.accountBalance} />);
return (
<Router basename ="/reactrouter">
<Route exact path="/" render={LogInComponent} />
<Route exact path="/userProfile" render={UserProfileComponent}/>
<Route exact path="/home" render={HomeComponent}/>
<Route exact path="/debit" render={DebitComponent}/>
<Route exact path="/credit" render={CreditComponent}/>
</Router>
);
}
}
export default App;
|
Python
|
UTF-8
| 810 | 2.65625 | 3 |
[] |
no_license
|
import requests
from urllib.parse import urlparse
keyword = '광운대학교'
url = "https://openapi.naver.com/v1/search/blog?query="+keyword
result = requests.get(urlparse(url).geturl(),
headers={"X-Naver-Client-Id":"Q92Fl0iqHMCMyN2hekCT",
"X-Naver-Client-Secret":"3vcCxHfNO4"})
# print(result.json())
json_obj = result.json()
# for item in json_obj['items']:
# print(item)
# print(json_obj['title']),print(json_obj['link']) #당연히 안됨
# for item in json_obj['items']:
# print('Title :'+item['title'],' Link :'+item['link'])
# print('Title :'+item['title'].replace("<b>","").replace("<b>",""),' Link :'+item['link'])
print("display : " + str(json_obj['display']))
print("start : " + str(json_obj['start']))
print("items : " + str(json_obj['items']))
|
Java
|
UTF-8
| 621 | 3.53125 | 4 |
[] |
no_license
|
package com.dsr.sortParatice;
public class InsertSort {
public static void main(String[] args) {
int[] arr=new int[]{5,7,4,6,1,3,8,5,6};
insertSort(arr);
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}
public static void insertSort(int[] arr){
for(int i=0;i<arr.length;i++){
for(int j=i;j>0;j--){
if(arr[j]<arr[j-1])
swap(arr,j,j-1);
}
}
}
public static void swap(int[] arr,int i,int j){
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
|
SQL
|
UTF-8
| 50,936 | 2.65625 | 3 |
[] |
no_license
|
drop table if exists `media172`;
drop table if exists `media152`;
drop table if exists `media153`;
drop table if exists `media154`;
drop table if exists `media155`;
drop table if exists `media156`;
drop table if exists `media157`;
drop table if exists `media158`;
drop table if exists `media159`;
drop table if exists `media160`;
drop table if exists `media161`;
drop table if exists `media162`;
drop table if exists `media163`;
drop table if exists `media164`;
drop table if exists `media165`;
drop table if exists `media166`;
drop table if exists `media167`;
drop table if exists `media168`;
drop table if exists `media169`;
drop table if exists `media170`;
drop table if exists `media171`;
CREATE TABLE IF NOT EXISTS `media172` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item_seq` varchar(10) NOT NULL,
`jpc_seq` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`campaign_id` int(11) NOT NULL,
`cue` int(11) NOT NULL,
`website` varchar(255) DEFAULT NULL,
`channel` varchar(255) DEFAULT NULL,
`actions` varchar(30) DEFAULT NULL,
`phonesystem` varchar(255) DEFAULT NULL,
`position` varchar(255) DEFAULT NULL,
`format1` text,
`format2` text,
`rules` text,
`wheel` varchar(255) DEFAULT NULL,
`ctr` varchar(255) DEFAULT NULL,
`date1` int(11) NOT NULL DEFAULT '0',
`date2` int(11) NOT NULL DEFAULT '0',
`date3` int(11) NOT NULL DEFAULT '0',
`date4` int(11) NOT NULL DEFAULT '0',
`date5` int(11) NOT NULL DEFAULT '0',
`date6` int(11) NOT NULL DEFAULT '0',
`date7` int(11) NOT NULL DEFAULT '0',
`date8` int(11) NOT NULL DEFAULT '0',
`date9` int(11) NOT NULL DEFAULT '0',
`date10` int(11) NOT NULL DEFAULT '0',
`days` varchar(20) DEFAULT NULL,
`due` text,
`quantity` varchar(20) DEFAULT NULL,
`quantity2` varchar(20) DEFAULT NULL,
`price` varchar(20) DEFAULT NULL,
`totalprice` varchar(20) DEFAULT NULL,
`times` int(11) NOT NULL,
`items` varchar(20) DEFAULT NULL,
`others` text,
`status` int(11) NOT NULL DEFAULT '0',
`days1` varchar(20) DEFAULT NULL,
`days2` varchar(20) DEFAULT NULL,
`days3` varchar(20) DEFAULT NULL,
`days4` varchar(20) DEFAULT NULL,
`days5` varchar(20) DEFAULT NULL,
`price1` varchar(20) DEFAULT NULL,
`price2` varchar(20) DEFAULT NULL,
`price3` varchar(20) DEFAULT NULL,
`price4` varchar(20) DEFAULT NULL,
`price5` varchar(20) DEFAULT NULL,
`totalprice1` varchar(20) DEFAULT NULL,
`totalprice2` varchar(20) DEFAULT NULL,
`totalprice3` varchar(20) DEFAULT NULL,
`totalprice4` varchar(20) DEFAULT NULL,
`totalprice5` varchar(20) DEFAULT NULL,
`click1` varchar(20) DEFAULT NULL,
`click2` varchar(20) DEFAULT NULL,
`click3` varchar(20) DEFAULT NULL,
`click4` varchar(20) DEFAULT NULL,
`click5` varchar(20) DEFAULT NULL,
`impression1` varchar(20) DEFAULT NULL,
`impression2` varchar(20) DEFAULT NULL,
`impression3` varchar(20) DEFAULT NULL,
`impression4` varchar(20) DEFAULT NULL,
`impression5` varchar(20) DEFAULT NULL,
`a` varchar(20) DEFAULT NULL,
`a0` varchar(20) DEFAULT NULL,
`a1` varchar(20) DEFAULT NULL,
`a2` varchar(20) DEFAULT NULL,
`a3` varchar(20) DEFAULT NULL,
`a4` varchar(20) DEFAULT NULL,
`a5` varchar(20) DEFAULT NULL,
`text13` text,
`items2` varchar(20) DEFAULT NULL,
`items3` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `campaign_id` (`campaign_id`),
KEY `status` (`status`),
KEY `cue` (`cue`),
KEY `a` (`a`) USING BTREE,
KEY `a0` (`a0`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `media152` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item_seq` varchar(10) DEFAULT NULL,
`jpc_seq` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`campaign_id` int(11) NOT NULL,
`cue` int(11) NOT NULL,
`website` varchar(255) DEFAULT NULL,
`actions` varchar(30) DEFAULT NULL,
`channel` varchar(255) DEFAULT NULL,
`phonesystem` varchar(255) DEFAULT NULL,
`position` varchar(255) DEFAULT NULL,
`format1` text,
`format2` text,
`wheel` varchar(255) DEFAULT NULL,
`ctr` varchar(255) DEFAULT NULL,
`date1` int(11) NOT NULL DEFAULT '0',
`date2` int(11) NOT NULL DEFAULT '0',
`date3` int(11) NOT NULL DEFAULT '0',
`date4` int(11) NOT NULL DEFAULT '0',
`date5` int(11) NOT NULL DEFAULT '0',
`date6` int(11) NOT NULL DEFAULT '0',
`date7` int(11) NOT NULL DEFAULT '0',
`date8` int(11) NOT NULL DEFAULT '0',
`date9` int(11) NOT NULL DEFAULT '0',
`date10` int(11) NOT NULL DEFAULT '0',
`days` varchar(20) DEFAULT NULL,
`due` text,
`quantity` varchar(20) DEFAULT NULL,
`price` varchar(20) DEFAULT NULL,
`totalprice` varchar(20) DEFAULT NULL,
`times` int(11) NOT NULL,
`others` text,
`status` int(11) NOT NULL DEFAULT '0',
`days1` varchar(20) DEFAULT NULL,
`days2` varchar(20) DEFAULT NULL,
`days3` varchar(20) DEFAULT NULL,
`days4` varchar(20) DEFAULT NULL,
`days5` varchar(20) DEFAULT NULL,
`price1` varchar(20) DEFAULT NULL,
`price2` varchar(20) DEFAULT NULL,
`price3` varchar(20) DEFAULT NULL,
`price4` varchar(20) DEFAULT NULL,
`price5` varchar(20) DEFAULT NULL,
`totalprice1` varchar(20) DEFAULT NULL,
`totalprice2` varchar(20) DEFAULT NULL,
`totalprice3` varchar(20) DEFAULT NULL,
`totalprice4` varchar(20) DEFAULT NULL,
`totalprice5` varchar(20) DEFAULT NULL,
`click1` varchar(20) DEFAULT NULL,
`click2` varchar(20) DEFAULT NULL,
`click3` varchar(20) DEFAULT NULL,
`click4` varchar(20) DEFAULT NULL,
`click5` varchar(20) DEFAULT NULL,
`a` varchar(20) DEFAULT NULL,
`a0` varchar(20) DEFAULT NULL,
`a1` varchar(20) DEFAULT NULL,
`a2` varchar(20) DEFAULT NULL,
`a3` varchar(20) DEFAULT NULL,
`a4` varchar(20) DEFAULT NULL,
`a5` varchar(20) DEFAULT NULL,
`text13` text,
`items2` varchar(20) DEFAULT NULL,
`items3` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `campaign_id` (`campaign_id`),
KEY `status` (`status`),
KEY `cue` (`cue`),
KEY `a` (`a`) USING BTREE,
KEY `a0` (`a0`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `media153` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item_seq` varchar(20) DEFAULT NULL,
`jpc_seq` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`campaign_id` int(11) NOT NULL,
`cue` int(11) NOT NULL,
`website` varchar(255) DEFAULT NULL,
`channel` varchar(255) DEFAULT NULL,
`actions` varchar(30) DEFAULT NULL,
`taget` varchar(20) DEFAULT NULL,
`phonesystem` varchar(255) DEFAULT NULL,
`position` varchar(255) DEFAULT NULL,
`format1` text,
`format2` text,
`rules` text,
`wheel` varchar(255) DEFAULT NULL,
`ctr` varchar(255) DEFAULT NULL,
`date1` int(11) NOT NULL DEFAULT '0',
`date2` int(11) NOT NULL DEFAULT '0',
`date3` int(11) NOT NULL DEFAULT '0',
`date4` int(11) NOT NULL DEFAULT '0',
`date5` int(11) NOT NULL DEFAULT '0',
`date6` int(11) NOT NULL DEFAULT '0',
`date7` int(11) NOT NULL DEFAULT '0',
`date8` int(11) NOT NULL DEFAULT '0',
`date9` int(11) NOT NULL DEFAULT '0',
`date10` int(11) NOT NULL DEFAULT '0',
`days` varchar(20) DEFAULT NULL,
`due` text,
`quantity` varchar(20) DEFAULT NULL,
`quantity2` varchar(20) DEFAULT NULL,
`price` varchar(20) DEFAULT NULL,
`totalprice` varchar(20) DEFAULT NULL,
`times` int(11) NOT NULL,
`items` varchar(20) DEFAULT NULL,
`others` text,
`status` int(11) NOT NULL DEFAULT '0',
`days1` varchar(20) DEFAULT NULL,
`days2` varchar(20) DEFAULT NULL,
`days3` varchar(20) DEFAULT NULL,
`days4` varchar(20) DEFAULT NULL,
`days5` varchar(20) DEFAULT NULL,
`price1` varchar(20) DEFAULT NULL,
`price2` varchar(20) DEFAULT NULL,
`price3` varchar(20) DEFAULT NULL,
`price4` varchar(20) DEFAULT NULL,
`price5` varchar(20) DEFAULT NULL,
`totalprice1` varchar(20) DEFAULT NULL,
`totalprice2` varchar(20) DEFAULT NULL,
`totalprice3` varchar(20) DEFAULT NULL,
`totalprice4` varchar(20) DEFAULT NULL,
`totalprice5` varchar(20) DEFAULT NULL,
`click1` varchar(20) DEFAULT NULL,
`click2` varchar(20) DEFAULT NULL,
`click3` varchar(20) DEFAULT NULL,
`click4` varchar(20) DEFAULT NULL,
`click5` varchar(20) DEFAULT NULL,
`impression1` varchar(20) DEFAULT NULL,
`impression2` varchar(20) DEFAULT NULL,
`impression3` varchar(20) DEFAULT NULL,
`impression4` varchar(20) DEFAULT NULL,
`impression5` varchar(20) DEFAULT NULL,
`a` varchar(20) DEFAULT NULL,
`a0` varchar(20) DEFAULT NULL,
`a1` varchar(20) DEFAULT NULL,
`a2` varchar(20) DEFAULT NULL,
`a3` varchar(20) DEFAULT NULL,
`a4` varchar(20) DEFAULT NULL,
`a5` varchar(20) DEFAULT NULL,
`text13` text,
`items2` varchar(20) DEFAULT NULL,
`items3` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `campaign_id` (`campaign_id`),
KEY `status` (`status`),
KEY `cue` (`cue`),
KEY `a` (`a`) USING BTREE,
KEY `a0` (`a0`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `media154` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item_seq` varchar(20) DEFAULT NULL,
`jpc_seq` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`campaign_id` int(11) NOT NULL,
`cue` int(11) NOT NULL,
`website` varchar(255) DEFAULT NULL,
`channel` varchar(255) DEFAULT NULL,
`phonesystem` varchar(255) DEFAULT NULL,
`position` varchar(255) DEFAULT NULL,
`format1` text,
`format2` text,
`wheel` varchar(255) DEFAULT NULL,
`ctr` varchar(255) DEFAULT NULL,
`date1` int(11) NOT NULL DEFAULT '0',
`date2` int(11) NOT NULL DEFAULT '0',
`date3` int(11) NOT NULL DEFAULT '0',
`date4` int(11) NOT NULL DEFAULT '0',
`date5` int(11) NOT NULL DEFAULT '0',
`date6` int(11) NOT NULL DEFAULT '0',
`date7` int(11) NOT NULL DEFAULT '0',
`date8` int(11) NOT NULL DEFAULT '0',
`date9` int(11) NOT NULL DEFAULT '0',
`date10` int(11) NOT NULL DEFAULT '0',
`days` varchar(20) DEFAULT NULL,
`due` text,
`quantity` varchar(20) DEFAULT NULL,
`quantity2` varchar(20) DEFAULT NULL,
`price` varchar(20) DEFAULT NULL,
`totalprice` varchar(20) DEFAULT NULL,
`times` int(11) NOT NULL,
`others` text,
`status` int(11) NOT NULL DEFAULT '0',
`days1` varchar(20) DEFAULT NULL,
`days2` varchar(20) DEFAULT NULL,
`days3` varchar(20) DEFAULT NULL,
`days4` varchar(20) DEFAULT NULL,
`days5` varchar(20) DEFAULT NULL,
`price1` varchar(20) DEFAULT NULL,
`price2` varchar(20) DEFAULT NULL,
`price3` varchar(20) DEFAULT NULL,
`price4` varchar(20) DEFAULT NULL,
`price5` varchar(20) DEFAULT NULL,
`totalprice1` varchar(20) DEFAULT NULL,
`totalprice2` varchar(20) DEFAULT NULL,
`totalprice3` varchar(20) DEFAULT NULL,
`totalprice4` varchar(20) DEFAULT NULL,
`totalprice5` varchar(20) DEFAULT NULL,
`click1` varchar(20) DEFAULT NULL,
`click2` varchar(20) DEFAULT NULL,
`click3` varchar(20) DEFAULT NULL,
`click4` varchar(20) DEFAULT NULL,
`click5` varchar(20) DEFAULT NULL,
`impression1` varchar(20) DEFAULT NULL,
`impression2` varchar(20) DEFAULT NULL,
`impression3` varchar(20) DEFAULT NULL,
`impression4` varchar(20) DEFAULT NULL,
`impression5` varchar(20) DEFAULT NULL,
`a` varchar(20) DEFAULT NULL,
`a0` varchar(20) DEFAULT NULL,
`a1` varchar(20) DEFAULT NULL,
`a2` varchar(20) DEFAULT NULL,
`a3` varchar(20) DEFAULT NULL,
`a4` varchar(20) DEFAULT NULL,
`a5` varchar(20) DEFAULT NULL,
`text13` text,
`items2` varchar(20) DEFAULT NULL,
`items3` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `campaign_id` (`campaign_id`),
KEY `status` (`status`),
KEY `cue` (`cue`),
KEY `a` (`a`) USING BTREE,
KEY `a0` (`a0`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `media155` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item_seq` varchar(20) DEFAULT NULL,
`jpc_seq` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`campaign_id` int(11) NOT NULL,
`cue` int(11) NOT NULL,
`website` varchar(255) DEFAULT NULL,
`actions` varchar(30) DEFAULT NULL,
`phonesystem` varchar(255) DEFAULT NULL,
`position` varchar(255) DEFAULT NULL,
`format1` text,
`format2` text,
`wheel` varchar(255) DEFAULT NULL,
`date1` int(11) NOT NULL DEFAULT '0',
`date2` int(11) NOT NULL DEFAULT '0',
`date3` int(11) NOT NULL DEFAULT '0',
`date4` int(11) NOT NULL DEFAULT '0',
`date5` int(11) NOT NULL DEFAULT '0',
`date6` int(11) NOT NULL DEFAULT '0',
`date7` int(11) NOT NULL DEFAULT '0',
`date8` int(11) NOT NULL DEFAULT '0',
`date9` int(11) NOT NULL DEFAULT '0',
`date10` int(11) NOT NULL DEFAULT '0',
`days` varchar(20) DEFAULT NULL,
`due` text,
`quantity` varchar(20) DEFAULT NULL,
`price` varchar(20) DEFAULT NULL,
`totalprice` varchar(20) DEFAULT NULL,
`times` int(11) NOT NULL,
`items` varchar(20) DEFAULT NULL,
`others` text,
`status` int(11) NOT NULL DEFAULT '0',
`days1` varchar(20) DEFAULT NULL,
`days2` varchar(20) DEFAULT NULL,
`days3` varchar(20) DEFAULT NULL,
`days4` varchar(20) DEFAULT NULL,
`days5` varchar(20) DEFAULT NULL,
`price1` varchar(20) DEFAULT NULL,
`price2` varchar(20) DEFAULT NULL,
`price3` varchar(20) DEFAULT NULL,
`price4` varchar(20) DEFAULT NULL,
`price5` varchar(20) DEFAULT NULL,
`totalprice1` varchar(20) DEFAULT NULL,
`totalprice2` varchar(20) DEFAULT NULL,
`totalprice3` varchar(20) DEFAULT NULL,
`totalprice4` varchar(20) DEFAULT NULL,
`totalprice5` varchar(20) DEFAULT NULL,
`click1` varchar(20) DEFAULT NULL,
`click2` varchar(20) DEFAULT NULL,
`click3` varchar(20) DEFAULT NULL,
`click4` varchar(20) DEFAULT NULL,
`click5` varchar(20) DEFAULT NULL,
`a` varchar(20) DEFAULT NULL,
`a0` varchar(20) DEFAULT NULL,
`a1` varchar(20) DEFAULT NULL,
`a2` varchar(20) DEFAULT NULL,
`a3` varchar(20) DEFAULT NULL,
`a4` varchar(20) DEFAULT NULL,
`a5` varchar(20) DEFAULT NULL,
`text13` text,
`items2` varchar(20) DEFAULT NULL,
`items3` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `campaign_id` (`campaign_id`),
KEY `status` (`status`),
KEY `cue` (`cue`),
KEY `a` (`a`) USING BTREE,
KEY `a0` (`a0`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `media156` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item_seq` varchar(20) DEFAULT NULL,
`jpc_seq` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`campaign_id` int(11) NOT NULL,
`cue` int(11) NOT NULL,
`website` varchar(255) DEFAULT NULL,
`actions` varchar(30) DEFAULT NULL,
`channel` varchar(255) DEFAULT NULL,
`phonesystem` varchar(255) DEFAULT NULL,
`position` varchar(255) DEFAULT NULL,
`format1` text,
`format2` text,
`wheel` varchar(255) DEFAULT NULL,
`ctr` varchar(255) DEFAULT NULL,
`date1` int(11) NOT NULL DEFAULT '0',
`date2` int(11) NOT NULL DEFAULT '0',
`date3` int(11) NOT NULL DEFAULT '0',
`date4` int(11) NOT NULL DEFAULT '0',
`date5` int(11) NOT NULL DEFAULT '0',
`date6` int(11) NOT NULL DEFAULT '0',
`date7` int(11) NOT NULL DEFAULT '0',
`date8` int(11) NOT NULL DEFAULT '0',
`date9` int(11) NOT NULL DEFAULT '0',
`date10` int(11) NOT NULL DEFAULT '0',
`days` varchar(20) DEFAULT NULL,
`due` text,
`quantity` varchar(20) DEFAULT NULL,
`price` varchar(20) DEFAULT NULL,
`totalprice` varchar(20) DEFAULT NULL,
`times` int(11) NOT NULL,
`others` text,
`status` int(11) NOT NULL DEFAULT '0',
`a` varchar(20) DEFAULT NULL,
`a0` varchar(20) DEFAULT NULL,
`a1` varchar(20) DEFAULT NULL,
`a2` varchar(20) DEFAULT NULL,
`a3` varchar(20) DEFAULT NULL,
`a4` varchar(20) DEFAULT NULL,
`a5` varchar(20) DEFAULT NULL,
`text13` text,
`totalprice1` varchar(20) DEFAULT NULL,
`totalprice2` varchar(20) DEFAULT NULL,
`totalprice3` varchar(20) DEFAULT NULL,
`totalprice4` varchar(20) DEFAULT NULL,
`totalprice5` varchar(20) DEFAULT NULL,
`click1` varchar(20) DEFAULT NULL,
`click2` varchar(20) DEFAULT NULL,
`click3` varchar(20) DEFAULT NULL,
`click4` varchar(20) DEFAULT NULL,
`click5` varchar(20) DEFAULT NULL,
`items2` varchar(20) DEFAULT NULL,
`items3` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `campaign_id` (`campaign_id`),
KEY `status` (`status`),
KEY `cue` (`cue`),
KEY `a` (`a`) USING BTREE,
KEY `a0` (`a0`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `media157` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item_seq` varchar(20) DEFAULT NULL,
`jpc_seq` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`campaign_id` int(11) NOT NULL,
`cue` int(11) NOT NULL,
`website` varchar(255) DEFAULT NULL,
`channel` varchar(255) DEFAULT NULL,
`actions` varchar(30) DEFAULT NULL,
`taget` varchar(20) DEFAULT NULL,
`phonesystem` varchar(255) DEFAULT NULL,
`position` varchar(255) DEFAULT NULL,
`format1` text,
`format2` text,
`rules` text,
`wheel` varchar(255) DEFAULT NULL,
`ctr` varchar(255) DEFAULT NULL,
`date1` int(11) NOT NULL DEFAULT '0',
`date2` int(11) NOT NULL DEFAULT '0',
`date3` int(11) NOT NULL DEFAULT '0',
`date4` int(11) NOT NULL DEFAULT '0',
`date5` int(11) NOT NULL DEFAULT '0',
`date6` int(11) NOT NULL DEFAULT '0',
`date7` int(11) NOT NULL DEFAULT '0',
`date8` int(11) NOT NULL DEFAULT '0',
`date9` int(11) NOT NULL DEFAULT '0',
`date10` int(11) NOT NULL DEFAULT '0',
`days` varchar(20) DEFAULT NULL,
`due` text,
`quantity` varchar(20) DEFAULT NULL,
`quantity2` varchar(20) DEFAULT NULL,
`price` varchar(20) DEFAULT NULL,
`totalprice` varchar(20) DEFAULT NULL,
`times` int(11) NOT NULL,
`items` varchar(20) DEFAULT NULL,
`others` text,
`status` int(11) NOT NULL DEFAULT '0',
`days1` varchar(20) DEFAULT NULL,
`days2` varchar(20) DEFAULT NULL,
`days3` varchar(20) DEFAULT NULL,
`days4` varchar(20) DEFAULT NULL,
`days5` varchar(20) DEFAULT NULL,
`price1` varchar(20) DEFAULT NULL,
`price2` varchar(20) DEFAULT NULL,
`price3` varchar(20) DEFAULT NULL,
`price4` varchar(20) DEFAULT NULL,
`price5` varchar(20) DEFAULT NULL,
`totalprice1` varchar(20) DEFAULT NULL,
`totalprice2` varchar(20) DEFAULT NULL,
`totalprice3` varchar(20) DEFAULT NULL,
`totalprice4` varchar(20) DEFAULT NULL,
`totalprice5` varchar(20) DEFAULT NULL,
`click1` varchar(20) DEFAULT NULL,
`click2` varchar(20) DEFAULT NULL,
`click3` varchar(20) DEFAULT NULL,
`click4` varchar(20) DEFAULT NULL,
`click5` varchar(20) DEFAULT NULL,
`impression1` varchar(20) DEFAULT NULL,
`impression2` varchar(20) DEFAULT NULL,
`impression3` varchar(20) DEFAULT NULL,
`impression4` varchar(20) DEFAULT NULL,
`impression5` varchar(20) DEFAULT NULL,
`a` varchar(20) DEFAULT NULL,
`a0` varchar(20) DEFAULT NULL,
`a1` varchar(20) DEFAULT NULL,
`a2` varchar(20) DEFAULT NULL,
`a3` varchar(20) DEFAULT NULL,
`a4` varchar(20) DEFAULT NULL,
`a5` varchar(20) DEFAULT NULL,
`text13` text,
`items2` varchar(20) DEFAULT NULL,
`items3` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `campaign_id` (`campaign_id`),
KEY `status` (`status`),
KEY `cue` (`cue`),
KEY `a` (`a`) USING BTREE,
KEY `a0` (`a0`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `media158` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item_seq` varchar(20) DEFAULT NULL,
`jpc_seq` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`campaign_id` int(11) NOT NULL,
`cue` int(11) NOT NULL,
`website` varchar(255) DEFAULT NULL,
`channel` varchar(255) DEFAULT NULL,
`phonesystem` varchar(255) DEFAULT NULL,
`position` varchar(255) DEFAULT NULL,
`format1` text,
`format2` text,
`wheel` varchar(255) DEFAULT NULL,
`ctr` varchar(255) DEFAULT NULL,
`date1` int(11) NOT NULL DEFAULT '0',
`date2` int(11) NOT NULL DEFAULT '0',
`date3` int(11) NOT NULL DEFAULT '0',
`date4` int(11) NOT NULL DEFAULT '0',
`date5` int(11) NOT NULL DEFAULT '0',
`date6` int(11) NOT NULL DEFAULT '0',
`date7` int(11) NOT NULL DEFAULT '0',
`date8` int(11) NOT NULL DEFAULT '0',
`date9` int(11) NOT NULL DEFAULT '0',
`date10` int(11) NOT NULL DEFAULT '0',
`days` varchar(20) DEFAULT NULL,
`due` text,
`quantity` varchar(20) DEFAULT NULL,
`quantity2` varchar(20) DEFAULT NULL,
`price` varchar(20) DEFAULT NULL,
`totalprice` varchar(20) DEFAULT NULL,
`times` int(11) NOT NULL,
`others` text,
`status` int(11) NOT NULL DEFAULT '0',
`a` varchar(20) DEFAULT NULL,
`a0` varchar(20) DEFAULT NULL,
`a1` varchar(20) DEFAULT NULL,
`a2` varchar(20) DEFAULT NULL,
`a3` varchar(20) DEFAULT NULL,
`a4` varchar(20) DEFAULT NULL,
`a5` varchar(20) DEFAULT NULL,
`days1` varchar(20) DEFAULT NULL,
`days2` varchar(20) DEFAULT NULL,
`days3` varchar(20) DEFAULT NULL,
`days4` varchar(20) DEFAULT NULL,
`days5` varchar(20) DEFAULT NULL,
`text13` text,
`items2` varchar(20) DEFAULT NULL,
`items3` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `campaign_id` (`campaign_id`),
KEY `status` (`status`),
KEY `cue` (`cue`),
KEY `a` (`a`) USING BTREE,
KEY `a0` (`a0`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `media159` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item_seq` varchar(10) NOT NULL,
`jpc_seq` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`campaign_id` int(11) NOT NULL,
`cue` int(11) NOT NULL,
`website` varchar(255) DEFAULT NULL,
`channel` varchar(255) DEFAULT NULL,
`actions` varchar(30) DEFAULT NULL,
`phonesystem` varchar(255) DEFAULT NULL,
`position` varchar(255) DEFAULT NULL,
`format1` text,
`format2` text,
`rules` text,
`wheel` varchar(255) DEFAULT NULL,
`ctr` varchar(255) DEFAULT NULL,
`date1` int(11) NOT NULL DEFAULT '0',
`date2` int(11) NOT NULL DEFAULT '0',
`date3` int(11) NOT NULL DEFAULT '0',
`date4` int(11) NOT NULL DEFAULT '0',
`date5` int(11) NOT NULL DEFAULT '0',
`date6` int(11) NOT NULL DEFAULT '0',
`date7` int(11) NOT NULL DEFAULT '0',
`date8` int(11) NOT NULL DEFAULT '0',
`date9` int(11) NOT NULL DEFAULT '0',
`date10` int(11) NOT NULL DEFAULT '0',
`days` varchar(20) DEFAULT NULL,
`due` text,
`quantity` varchar(20) DEFAULT NULL,
`quantity2` varchar(20) DEFAULT NULL,
`price` varchar(20) DEFAULT NULL,
`totalprice` varchar(20) DEFAULT NULL,
`times` int(11) NOT NULL,
`items` varchar(20) DEFAULT NULL,
`others` text,
`status` int(11) NOT NULL DEFAULT '0',
`days1` varchar(20) DEFAULT NULL,
`days2` varchar(20) DEFAULT NULL,
`days3` varchar(20) DEFAULT NULL,
`days4` varchar(20) DEFAULT NULL,
`days5` varchar(20) DEFAULT NULL,
`price1` varchar(20) DEFAULT NULL,
`price2` varchar(20) DEFAULT NULL,
`price3` varchar(20) DEFAULT NULL,
`price4` varchar(20) DEFAULT NULL,
`price5` varchar(20) DEFAULT NULL,
`totalprice1` varchar(20) DEFAULT NULL,
`totalprice2` varchar(20) DEFAULT NULL,
`totalprice3` varchar(20) DEFAULT NULL,
`totalprice4` varchar(20) DEFAULT NULL,
`totalprice5` varchar(20) DEFAULT NULL,
`click1` varchar(20) DEFAULT NULL,
`click2` varchar(20) DEFAULT NULL,
`click3` varchar(20) DEFAULT NULL,
`click4` varchar(20) DEFAULT NULL,
`click5` varchar(20) DEFAULT NULL,
`impression1` varchar(20) DEFAULT NULL,
`impression2` varchar(20) DEFAULT NULL,
`impression3` varchar(20) DEFAULT NULL,
`impression4` varchar(20) DEFAULT NULL,
`impression5` varchar(20) DEFAULT NULL,
`a` varchar(20) DEFAULT NULL,
`a0` varchar(20) DEFAULT NULL,
`a1` varchar(20) DEFAULT NULL,
`a2` varchar(20) DEFAULT NULL,
`a3` varchar(20) DEFAULT NULL,
`a4` varchar(20) DEFAULT NULL,
`a5` varchar(20) DEFAULT NULL,
`text13` text,
`items2` varchar(20) DEFAULT NULL,
`items3` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `campaign_id` (`campaign_id`),
KEY `status` (`status`),
KEY `cue` (`cue`),
KEY `a` (`a`) USING BTREE,
KEY `a0` (`a0`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `media160` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item_seq` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`jpc_seq` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`campaign_id` int(11) NOT NULL,
`cue` int(11) NOT NULL,
`website` varchar(255) DEFAULT NULL,
`channel` varchar(255) DEFAULT NULL,
`phonesystem` varchar(255) DEFAULT NULL,
`position` varchar(255) DEFAULT NULL,
`format1` text,
`format2` text,
`wheel` varchar(255) DEFAULT NULL,
`ctr` varchar(255) DEFAULT NULL,
`date1` int(11) NOT NULL DEFAULT '0',
`date2` int(11) NOT NULL DEFAULT '0',
`date3` int(11) NOT NULL DEFAULT '0',
`date4` int(11) NOT NULL DEFAULT '0',
`date5` int(11) NOT NULL DEFAULT '0',
`date6` int(11) NOT NULL DEFAULT '0',
`date7` int(11) NOT NULL DEFAULT '0',
`date8` int(11) NOT NULL DEFAULT '0',
`date9` int(11) NOT NULL DEFAULT '0',
`date10` int(11) NOT NULL DEFAULT '0',
`days` varchar(20) DEFAULT NULL,
`due` text,
`quantity` varchar(20) DEFAULT NULL,
`quantity2` varchar(20) DEFAULT NULL,
`price` varchar(20) DEFAULT NULL,
`totalprice` varchar(20) DEFAULT NULL,
`times` int(11) NOT NULL,
`others` text,
`status` int(11) NOT NULL DEFAULT '0',
`a` varchar(20) DEFAULT NULL,
`a0` varchar(20) DEFAULT NULL,
`a1` varchar(20) DEFAULT NULL,
`a2` varchar(20) DEFAULT NULL,
`a3` varchar(20) DEFAULT NULL,
`a4` varchar(20) DEFAULT NULL,
`a5` varchar(20) DEFAULT NULL,
`days1` varchar(20) DEFAULT NULL,
`days2` varchar(20) DEFAULT NULL,
`days3` varchar(20) DEFAULT NULL,
`days4` varchar(20) DEFAULT NULL,
`days5` varchar(20) DEFAULT NULL,
`text13` text,
`actions` varchar(20) DEFAULT NULL,
`items2` varchar(20) DEFAULT NULL,
`items3` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `campaign_id` (`campaign_id`),
KEY `status` (`status`),
KEY `cue` (`cue`),
KEY `a` (`a`) USING BTREE,
KEY `a0` (`a0`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `media161` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item_seq` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`jpc_seq` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`campaign_id` int(11) NOT NULL,
`cue` int(11) NOT NULL,
`itemname` varchar(255) DEFAULT NULL,
`website` varchar(255) DEFAULT NULL,
`price` varchar(20) DEFAULT NULL,
`quantity` varchar(20) DEFAULT NULL,
`totalprice` varchar(20) DEFAULT NULL,
`other` text,
`times` int(11) NOT NULL,
`others` text,
`status` int(11) NOT NULL DEFAULT '0',
`a` varchar(20) DEFAULT NULL,
`a0` varchar(20) DEFAULT NULL,
`a1` varchar(20) DEFAULT NULL,
`a2` varchar(20) DEFAULT NULL,
`a3` varchar(20) DEFAULT NULL,
`a4` varchar(20) DEFAULT NULL,
`a5` varchar(20) DEFAULT NULL,
`text13` text,
`items2` varchar(20) DEFAULT NULL,
`items3` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `campaign_id` (`campaign_id`),
KEY `status` (`status`),
KEY `cue` (`cue`),
KEY `a` (`a`) USING BTREE,
KEY `a0` (`a0`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `media162` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item_seq` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`jpc_seq` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`campaign_id` int(11) NOT NULL,
`cue` int(11) NOT NULL,
`website` varchar(255) DEFAULT NULL,
`channel` varchar(255) DEFAULT NULL,
`phonesystem` varchar(255) DEFAULT NULL,
`position` varchar(255) DEFAULT NULL,
`format1` text,
`format2` text,
`wheel` varchar(255) DEFAULT NULL,
`ctr` varchar(255) DEFAULT NULL,
`date1` text,
`date2` varchar(20) DEFAULT NULL,
`days` varchar(20) DEFAULT NULL,
`due` text,
`quantity` varchar(20) DEFAULT NULL,
`price` varchar(20) DEFAULT NULL,
`totalprice` varchar(20) DEFAULT NULL,
`totalprice2` varchar(20) DEFAULT NULL,
`totalprice3` varchar(20) DEFAULT NULL,
`times` int(11) NOT NULL,
`others` text,
`status` int(11) NOT NULL DEFAULT '0',
`a` varchar(20) DEFAULT NULL,
`a0` varchar(20) DEFAULT NULL,
`a1` varchar(20) DEFAULT NULL,
`a2` varchar(20) DEFAULT NULL,
`a3` varchar(20) DEFAULT NULL,
`a4` varchar(20) DEFAULT NULL,
`a5` varchar(20) DEFAULT NULL,
`text13` text,
`items2` varchar(20) DEFAULT NULL,
`items3` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `campaign_id` (`campaign_id`),
KEY `status` (`status`),
KEY `cue` (`cue`),
KEY `a` (`a`) USING BTREE,
KEY `a0` (`a0`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `media162_detail` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`campaign_id` int(11) NOT NULL,
`blogid` int(11) NOT NULL,
`blog` varchar(255) DEFAULT NULL,
`blog1` varchar(255) DEFAULT NULL,
`blog2` text,
`blog3` text,
`type` text,
`price` int(11) NOT NULL,
`price2` int(11) NOT NULL DEFAULT '0',
`price3` int(11) NOT NULL DEFAULT '0',
`times` int(11) NOT NULL,
`others` text,
`status` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `campaign_id` (`campaign_id`),
KEY `status` (`status`),
KEY `blogid` (`blogid`),
KEY `campaign_blog` (`campaign_id`,`blogid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `media163` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item_seq` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`jpc_seq` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`campaign_id` int(11) NOT NULL,
`cue` int(11) NOT NULL,
`website` varchar(255) DEFAULT NULL,
`channel` varchar(255) NOT NULL DEFAULT '',
`action` varchar(255) NOT NULL DEFAULT '',
`date1` int(11) NOT NULL DEFAULT '0',
`date2` int(11) NOT NULL DEFAULT '0',
`date3` int(11) NOT NULL DEFAULT '0',
`date4` int(11) NOT NULL DEFAULT '0',
`date5` int(11) NOT NULL DEFAULT '0',
`date6` int(11) NOT NULL DEFAULT '0',
`date7` int(11) NOT NULL DEFAULT '0',
`date8` int(11) NOT NULL DEFAULT '0',
`date9` int(11) NOT NULL DEFAULT '0',
`date10` int(11) NOT NULL DEFAULT '0',
`days` varchar(20) DEFAULT NULL,
`due` text,
`price` varchar(20) DEFAULT NULL,
`totalprice` varchar(20) DEFAULT NULL,
`times` int(11) NOT NULL,
`others` text,
`status` int(11) NOT NULL DEFAULT '0',
`days1` varchar(20) DEFAULT NULL,
`days2` varchar(20) DEFAULT NULL,
`days3` varchar(20) DEFAULT NULL,
`days4` varchar(20) DEFAULT NULL,
`days5` varchar(20) DEFAULT NULL,
`price1` varchar(20) DEFAULT NULL,
`price2` varchar(20) DEFAULT NULL,
`price3` varchar(20) DEFAULT NULL,
`price4` varchar(20) DEFAULT NULL,
`price5` varchar(20) DEFAULT NULL,
`totalprice1` varchar(20) DEFAULT NULL,
`totalprice2` varchar(20) DEFAULT NULL,
`totalprice3` varchar(20) DEFAULT NULL,
`totalprice4` varchar(20) DEFAULT NULL,
`totalprice5` varchar(20) DEFAULT NULL,
`a` varchar(20) DEFAULT NULL,
`a0` varchar(20) DEFAULT NULL,
`a1` varchar(20) DEFAULT NULL,
`a2` varchar(20) DEFAULT NULL,
`a3` varchar(20) DEFAULT NULL,
`a4` varchar(20) DEFAULT NULL,
`a5` varchar(20) DEFAULT NULL,
`text13` text,
`items2` varchar(20) DEFAULT NULL,
`items3` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `campaign_id` (`campaign_id`),
KEY `status` (`status`),
KEY `cue` (`cue`),
KEY `a` (`a`) USING BTREE,
KEY `a0` (`a0`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `media164` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item_seq` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`jpc_seq` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`campaign_id` int(11) NOT NULL,
`cue` int(11) NOT NULL,
`website` varchar(255) DEFAULT NULL,
`channel` varchar(255) DEFAULT NULL,
`phonesystem` varchar(255) DEFAULT NULL,
`screening` varchar(20) DEFAULT NULL,
`position` varchar(255) DEFAULT NULL,
`format1` text,
`format2` text,
`wheel` varchar(255) DEFAULT NULL,
`ctr` varchar(255) DEFAULT NULL,
`date1` int(11) NOT NULL DEFAULT '0',
`date2` int(11) NOT NULL DEFAULT '0',
`date3` int(11) NOT NULL DEFAULT '0',
`date4` int(11) NOT NULL DEFAULT '0',
`date5` int(11) NOT NULL DEFAULT '0',
`date6` int(11) NOT NULL DEFAULT '0',
`date7` int(11) NOT NULL DEFAULT '0',
`date8` int(11) NOT NULL DEFAULT '0',
`date9` int(11) NOT NULL DEFAULT '0',
`date10` int(11) NOT NULL DEFAULT '0',
`days` varchar(20) DEFAULT NULL,
`due` text,
`quantity` varchar(20) DEFAULT NULL,
`quantity2` varchar(20) DEFAULT NULL,
`price` varchar(20) DEFAULT NULL,
`totalprice` varchar(20) DEFAULT NULL,
`times` int(11) NOT NULL,
`others` text,
`status` int(11) NOT NULL DEFAULT '0',
`days1` varchar(20) DEFAULT NULL,
`days2` varchar(20) DEFAULT NULL,
`days3` varchar(20) DEFAULT NULL,
`days4` varchar(20) DEFAULT NULL,
`days5` varchar(20) DEFAULT NULL,
`price1` varchar(20) DEFAULT NULL,
`price2` varchar(20) DEFAULT NULL,
`price3` varchar(20) DEFAULT NULL,
`price4` varchar(20) DEFAULT NULL,
`price5` varchar(20) DEFAULT NULL,
`totalprice1` varchar(20) DEFAULT NULL,
`totalprice2` varchar(20) DEFAULT NULL,
`totalprice3` varchar(20) DEFAULT NULL,
`totalprice4` varchar(20) DEFAULT NULL,
`totalprice5` varchar(20) DEFAULT NULL,
`click1` varchar(20) DEFAULT NULL,
`click2` varchar(20) DEFAULT NULL,
`click3` varchar(20) DEFAULT NULL,
`click4` varchar(20) DEFAULT NULL,
`click5` varchar(20) DEFAULT NULL,
`impression1` varchar(20) DEFAULT NULL,
`impression2` varchar(20) DEFAULT NULL,
`impression3` varchar(20) DEFAULT NULL,
`impression4` varchar(20) DEFAULT NULL,
`impression5` varchar(20) DEFAULT NULL,
`a` varchar(20) DEFAULT NULL,
`a0` varchar(20) DEFAULT NULL,
`a1` varchar(20) DEFAULT NULL,
`a2` varchar(20) DEFAULT NULL,
`a3` varchar(20) DEFAULT NULL,
`a4` varchar(20) DEFAULT NULL,
`a5` varchar(20) DEFAULT NULL,
`text13` text,
`actions` varchar(20) DEFAULT NULL,
`items2` varchar(20) DEFAULT NULL,
`items3` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `campaign_id` (`campaign_id`),
KEY `status` (`status`),
KEY `cue` (`cue`),
KEY `a` (`a`) USING BTREE,
KEY `a0` (`a0`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `media165` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item_seq` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`jpc_seq` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`campaign_id` int(11) NOT NULL,
`cue` int(11) NOT NULL,
`website` varchar(255) DEFAULT NULL,
`channel` varchar(255) DEFAULT NULL,
`phonesystem` varchar(255) DEFAULT NULL,
`position` varchar(255) DEFAULT NULL,
`format1` text,
`format2` text,
`wheel` varchar(255) DEFAULT NULL,
`ctr` varchar(255) DEFAULT NULL,
`date1` int(11) NOT NULL DEFAULT '0',
`date2` int(11) NOT NULL DEFAULT '0',
`date3` int(11) NOT NULL DEFAULT '0',
`date4` int(11) NOT NULL DEFAULT '0',
`date5` int(11) NOT NULL DEFAULT '0',
`date6` int(11) NOT NULL DEFAULT '0',
`date7` int(11) NOT NULL DEFAULT '0',
`date8` int(11) NOT NULL DEFAULT '0',
`date9` int(11) NOT NULL DEFAULT '0',
`date10` int(11) NOT NULL DEFAULT '0',
`days` varchar(20) DEFAULT NULL,
`due` text,
`quantity` varchar(20) DEFAULT NULL,
`quantity2` varchar(20) DEFAULT NULL,
`price` varchar(20) DEFAULT NULL,
`totalprice` varchar(20) DEFAULT NULL,
`times` int(11) NOT NULL,
`others` text,
`status` int(11) NOT NULL DEFAULT '0',
`a` varchar(20) DEFAULT NULL,
`a0` varchar(20) DEFAULT NULL,
`a1` varchar(20) DEFAULT NULL,
`a2` varchar(20) DEFAULT NULL,
`a3` varchar(20) DEFAULT NULL,
`a4` varchar(20) DEFAULT NULL,
`a5` varchar(20) DEFAULT NULL,
`days1` varchar(20) DEFAULT NULL,
`days2` varchar(20) DEFAULT NULL,
`days3` varchar(20) DEFAULT NULL,
`days4` varchar(20) DEFAULT NULL,
`days5` varchar(20) DEFAULT NULL,
`text13` text,
`actions` varchar(20) DEFAULT NULL,
`items2` varchar(20) DEFAULT NULL,
`items3` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `campaign_id` (`campaign_id`),
KEY `status` (`status`),
KEY `cue` (`cue`),
KEY `a` (`a`) USING BTREE,
KEY `a0` (`a0`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `media166` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item_seq` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`jpc_seq` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`campaign_id` int(11) NOT NULL,
`cue` int(11) NOT NULL,
`website` varchar(255) DEFAULT NULL,
`channel` varchar(255) DEFAULT NULL,
`phonesystem` varchar(255) DEFAULT NULL,
`position` varchar(255) DEFAULT NULL,
`format1` text,
`format2` text,
`wheel` varchar(255) DEFAULT NULL,
`ctr` varchar(255) DEFAULT NULL,
`date1` text,
`date2` varchar(20) DEFAULT NULL,
`days` varchar(20) DEFAULT NULL,
`due` text,
`quantity` varchar(20) DEFAULT NULL,
`price` varchar(20) DEFAULT NULL,
`totalprice` varchar(20) DEFAULT NULL,
`totalprice2` varchar(20) DEFAULT NULL,
`totalprice3` varchar(20) DEFAULT NULL,
`times` int(11) NOT NULL,
`others` text,
`status` int(11) NOT NULL DEFAULT '0',
`a` varchar(20) DEFAULT NULL,
`a0` varchar(20) DEFAULT NULL,
`a1` varchar(20) DEFAULT NULL,
`a2` varchar(20) DEFAULT NULL,
`a3` varchar(20) DEFAULT NULL,
`a4` varchar(20) DEFAULT NULL,
`a5` varchar(20) DEFAULT NULL,
`text13` text,
`items2` varchar(20) DEFAULT NULL,
`items3` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `campaign_id` (`campaign_id`),
KEY `status` (`status`),
KEY `cue` (`cue`),
KEY `a` (`a`) USING BTREE,
KEY `a0` (`a0`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `media166_detail` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`campaign_id` int(11) NOT NULL,
`blogid` int(11) NOT NULL,
`blog` varchar(20) DEFAULT NULL,
`blog1` varchar(20) DEFAULT NULL,
`blog2` text,
`blog3` text,
`type` text,
`price` int(11) NOT NULL,
`price2` int(11) NOT NULL DEFAULT '0',
`price3` int(11) NOT NULL DEFAULT '0',
`times` int(11) NOT NULL,
`others` text,
`status` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `campaign_id` (`campaign_id`),
KEY `status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `media167` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item_seq` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`jpc_seq` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`campaign_id` int(11) NOT NULL,
`cue` int(11) NOT NULL,
`website` varchar(255) DEFAULT NULL,
`actions` varchar(30) DEFAULT NULL,
`channel` varchar(255) DEFAULT NULL,
`phonesystem` varchar(255) DEFAULT NULL,
`position` varchar(255) DEFAULT NULL,
`format1` text,
`format2` text,
`wheel` varchar(255) DEFAULT NULL,
`ctr` varchar(255) DEFAULT NULL,
`date1` int(11) NOT NULL DEFAULT '0',
`date2` int(11) NOT NULL DEFAULT '0',
`date3` int(11) NOT NULL DEFAULT '0',
`date4` int(11) NOT NULL DEFAULT '0',
`date5` int(11) NOT NULL DEFAULT '0',
`date6` int(11) NOT NULL DEFAULT '0',
`date7` int(11) NOT NULL DEFAULT '0',
`date8` int(11) NOT NULL DEFAULT '0',
`date9` int(11) NOT NULL DEFAULT '0',
`date10` int(11) NOT NULL DEFAULT '0',
`days` varchar(20) DEFAULT NULL,
`due` text,
`quantity` varchar(20) DEFAULT NULL,
`price` varchar(20) DEFAULT NULL,
`totalprice` varchar(20) DEFAULT NULL,
`times` int(11) NOT NULL,
`others` text,
`status` int(11) NOT NULL DEFAULT '0',
`a` varchar(20) DEFAULT NULL,
`a0` varchar(20) DEFAULT NULL,
`a1` varchar(20) DEFAULT NULL,
`a2` varchar(20) DEFAULT NULL,
`a3` varchar(20) DEFAULT NULL,
`a4` varchar(20) DEFAULT NULL,
`a5` varchar(20) DEFAULT NULL,
`text13` text,
`totalprice1` varchar(20) DEFAULT NULL,
`totalprice2` varchar(20) DEFAULT NULL,
`totalprice3` varchar(20) DEFAULT NULL,
`totalprice4` varchar(20) DEFAULT NULL,
`totalprice5` varchar(20) DEFAULT NULL,
`click1` varchar(20) DEFAULT NULL,
`click2` varchar(20) DEFAULT NULL,
`click3` varchar(20) DEFAULT NULL,
`click4` varchar(20) DEFAULT NULL,
`click5` varchar(20) DEFAULT NULL,
`items2` varchar(20) DEFAULT NULL,
`items3` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `campaign_id` (`campaign_id`),
KEY `status` (`status`),
KEY `cue` (`cue`),
KEY `a` (`a`) USING BTREE,
KEY `a0` (`a0`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `media168` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item_seq` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`jpc_seq` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`campaign_id` int(11) NOT NULL,
`cue` int(11) NOT NULL,
`website` varchar(255) DEFAULT NULL,
`actions` varchar(20) DEFAULT NULL,
`channel` varchar(255) DEFAULT NULL,
`phonesystem` varchar(255) DEFAULT NULL,
`position` varchar(255) DEFAULT NULL,
`format1` text,
`format2` text,
`wheel` varchar(255) DEFAULT NULL,
`ctr` varchar(255) DEFAULT NULL,
`date1` int(11) NOT NULL DEFAULT '0',
`date2` int(11) NOT NULL DEFAULT '0',
`date3` int(11) NOT NULL DEFAULT '0',
`date4` int(11) NOT NULL DEFAULT '0',
`date5` int(11) NOT NULL DEFAULT '0',
`date6` int(11) NOT NULL DEFAULT '0',
`date7` int(11) NOT NULL DEFAULT '0',
`date8` int(11) NOT NULL DEFAULT '0',
`date9` int(11) NOT NULL DEFAULT '0',
`date10` int(11) NOT NULL DEFAULT '0',
`days` varchar(20) DEFAULT NULL,
`due` text,
`quantity` varchar(20) DEFAULT NULL,
`quantity2` varchar(20) DEFAULT NULL,
`price` varchar(20) DEFAULT NULL,
`totalprice` varchar(20) DEFAULT NULL,
`times` int(11) NOT NULL,
`others` text,
`status` int(11) NOT NULL DEFAULT '0',
`days1` varchar(20) DEFAULT NULL,
`days2` varchar(20) DEFAULT NULL,
`days3` varchar(20) DEFAULT NULL,
`days4` varchar(20) DEFAULT NULL,
`days5` varchar(20) DEFAULT NULL,
`price1` varchar(20) DEFAULT NULL,
`price2` varchar(20) DEFAULT NULL,
`price3` varchar(20) DEFAULT NULL,
`price4` varchar(20) DEFAULT NULL,
`price5` varchar(20) DEFAULT NULL,
`totalprice1` varchar(20) DEFAULT NULL,
`totalprice2` varchar(20) DEFAULT NULL,
`totalprice3` varchar(20) DEFAULT NULL,
`totalprice4` varchar(20) DEFAULT NULL,
`totalprice5` varchar(20) DEFAULT NULL,
`click1` varchar(20) DEFAULT NULL,
`click2` varchar(20) DEFAULT NULL,
`click3` varchar(20) DEFAULT NULL,
`click4` varchar(20) DEFAULT NULL,
`click5` varchar(20) DEFAULT NULL,
`impression1` varchar(20) DEFAULT NULL,
`impression2` varchar(20) DEFAULT NULL,
`impression3` varchar(20) DEFAULT NULL,
`impression4` varchar(20) DEFAULT NULL,
`impression5` varchar(20) DEFAULT NULL,
`a` varchar(20) DEFAULT NULL,
`a0` varchar(20) DEFAULT NULL,
`a1` varchar(20) DEFAULT NULL,
`a2` varchar(20) DEFAULT NULL,
`a3` varchar(20) DEFAULT NULL,
`a4` varchar(20) DEFAULT NULL,
`a5` varchar(20) DEFAULT NULL,
`text13` text,
`items2` varchar(20) DEFAULT NULL,
`actions2` varchar(20) DEFAULT NULL,
`items3` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `campaign_id` (`campaign_id`),
KEY `status` (`status`),
KEY `cue` (`cue`),
KEY `a` (`a`) USING BTREE,
KEY `a0` (`a0`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `media169` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item_seq` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`jpc_seq` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`campaign_id` int(11) NOT NULL,
`cue` int(11) NOT NULL,
`website` varchar(255) DEFAULT NULL,
`channel` varchar(255) DEFAULT NULL,
`actions` varchar(30) DEFAULT NULL,
`actions2` varchar(20) DEFAULT NULL,
`phonesystem` varchar(255) DEFAULT NULL,
`position` varchar(255) DEFAULT NULL,
`format1` text,
`format2` text,
`wheel` varchar(255) DEFAULT NULL,
`date1` int(11) NOT NULL DEFAULT '0',
`date2` int(11) NOT NULL DEFAULT '0',
`date3` int(11) NOT NULL DEFAULT '0',
`date4` int(11) NOT NULL DEFAULT '0',
`date5` int(11) NOT NULL DEFAULT '0',
`date6` int(11) NOT NULL DEFAULT '0',
`date7` int(11) NOT NULL DEFAULT '0',
`date8` int(11) NOT NULL DEFAULT '0',
`date9` int(11) NOT NULL DEFAULT '0',
`date10` int(11) NOT NULL DEFAULT '0',
`days` varchar(20) DEFAULT NULL,
`due` text,
`quantity` varchar(20) DEFAULT NULL,
`price` varchar(20) DEFAULT NULL,
`totalprice` varchar(20) DEFAULT NULL,
`times` int(11) NOT NULL,
`items` varchar(20) DEFAULT NULL,
`others` text,
`status` int(11) NOT NULL DEFAULT '0',
`days1` varchar(20) DEFAULT NULL,
`days2` varchar(20) DEFAULT NULL,
`days3` varchar(20) DEFAULT NULL,
`days4` varchar(20) DEFAULT NULL,
`days5` varchar(20) DEFAULT NULL,
`price1` varchar(20) DEFAULT NULL,
`price2` varchar(20) DEFAULT NULL,
`price3` varchar(20) DEFAULT NULL,
`price4` varchar(20) DEFAULT NULL,
`price5` varchar(20) DEFAULT NULL,
`totalprice1` varchar(20) DEFAULT NULL,
`totalprice2` varchar(20) DEFAULT NULL,
`totalprice3` varchar(20) DEFAULT NULL,
`totalprice4` varchar(20) DEFAULT NULL,
`totalprice5` varchar(20) DEFAULT NULL,
`click1` varchar(20) DEFAULT NULL,
`click2` varchar(20) DEFAULT NULL,
`click3` varchar(20) DEFAULT NULL,
`click4` varchar(20) DEFAULT NULL,
`click5` varchar(20) DEFAULT NULL,
`a` varchar(20) DEFAULT NULL,
`a0` varchar(20) DEFAULT NULL,
`a1` varchar(20) DEFAULT NULL,
`a2` varchar(20) DEFAULT NULL,
`a3` varchar(20) DEFAULT NULL,
`a4` varchar(20) DEFAULT NULL,
`a5` varchar(20) DEFAULT NULL,
`text13` text,
`items2` varchar(20) DEFAULT NULL,
`items3` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `campaign_id` (`campaign_id`),
KEY `status` (`status`),
KEY `cue` (`cue`),
KEY `a` (`a`) USING BTREE,
KEY `a0` (`a0`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `media170` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item_seq` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`jpc_seq` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`campaign_id` int(11) NOT NULL,
`cue` int(11) NOT NULL,
`website` varchar(255) DEFAULT NULL,
`actions` varchar(20) DEFAULT NULL,
`actions2` text,
`position` varchar(255) DEFAULT NULL,
`format1` text,
`format2` text,
`wheel` varchar(255) DEFAULT NULL,
`date1` int(11) NOT NULL DEFAULT '0',
`date2` int(11) NOT NULL DEFAULT '0',
`date3` int(11) NOT NULL DEFAULT '0',
`date4` int(11) NOT NULL DEFAULT '0',
`date5` int(11) NOT NULL DEFAULT '0',
`date6` int(11) NOT NULL DEFAULT '0',
`date7` int(11) NOT NULL DEFAULT '0',
`date8` int(11) NOT NULL DEFAULT '0',
`date9` int(11) NOT NULL DEFAULT '0',
`date10` int(11) NOT NULL DEFAULT '0',
`days` varchar(20) DEFAULT NULL,
`due` text,
`quantity` varchar(20) DEFAULT NULL,
`price` varchar(20) DEFAULT NULL,
`totalprice` varchar(20) DEFAULT NULL,
`times` int(11) NOT NULL,
`others` text,
`status` int(11) NOT NULL DEFAULT '0',
`days1` varchar(20) DEFAULT NULL,
`days2` varchar(20) DEFAULT NULL,
`days3` varchar(20) DEFAULT NULL,
`days4` varchar(20) DEFAULT NULL,
`days5` varchar(20) DEFAULT NULL,
`price1` varchar(20) DEFAULT NULL,
`price2` varchar(20) DEFAULT NULL,
`price3` varchar(20) DEFAULT NULL,
`price4` varchar(20) DEFAULT NULL,
`price5` varchar(20) DEFAULT NULL,
`totalprice1` varchar(20) DEFAULT NULL,
`totalprice2` varchar(20) DEFAULT NULL,
`totalprice3` varchar(20) DEFAULT NULL,
`totalprice4` varchar(20) DEFAULT NULL,
`totalprice5` varchar(20) DEFAULT NULL,
`click1` varchar(20) DEFAULT NULL,
`click2` varchar(20) DEFAULT NULL,
`click3` varchar(20) DEFAULT NULL,
`click4` varchar(20) DEFAULT NULL,
`click5` varchar(20) DEFAULT NULL,
`a` varchar(20) DEFAULT NULL,
`a0` varchar(20) DEFAULT NULL,
`a1` varchar(20) DEFAULT NULL,
`a2` varchar(20) DEFAULT NULL,
`a3` varchar(20) DEFAULT NULL,
`a4` varchar(20) DEFAULT NULL,
`a5` varchar(20) DEFAULT NULL,
`text13` text,
`items2` varchar(20) DEFAULT NULL,
`items3` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `campaign_id` (`campaign_id`),
KEY `status` (`status`),
KEY `cue` (`cue`),
KEY `a` (`a`) USING BTREE,
KEY `a0` (`a0`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `media171` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item_seq` varchar(10) NOT NULL,
`jpc_seq` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`campaign_id` int(11) NOT NULL,
`cue` int(11) NOT NULL,
`website` varchar(255) DEFAULT NULL,
`channel` varchar(255) DEFAULT NULL,
`actions` varchar(30) DEFAULT NULL,
`phonesystem` varchar(255) DEFAULT NULL,
`position` varchar(255) DEFAULT NULL,
`format1` text,
`format2` text,
`rules` text,
`wheel` varchar(255) DEFAULT NULL,
`ctr` varchar(255) DEFAULT NULL,
`date1` int(11) NOT NULL DEFAULT '0',
`date2` int(11) NOT NULL DEFAULT '0',
`date3` int(11) NOT NULL DEFAULT '0',
`date4` int(11) NOT NULL DEFAULT '0',
`date5` int(11) NOT NULL DEFAULT '0',
`date6` int(11) NOT NULL DEFAULT '0',
`date7` int(11) NOT NULL DEFAULT '0',
`date8` int(11) NOT NULL DEFAULT '0',
`date9` int(11) NOT NULL DEFAULT '0',
`date10` int(11) NOT NULL DEFAULT '0',
`days` varchar(20) DEFAULT NULL,
`due` text,
`quantity` varchar(20) DEFAULT NULL,
`quantity2` varchar(20) DEFAULT NULL,
`price` varchar(20) DEFAULT NULL,
`totalprice` varchar(20) DEFAULT NULL,
`times` int(11) NOT NULL,
`items` varchar(20) DEFAULT NULL,
`others` text,
`status` int(11) NOT NULL DEFAULT '0',
`days1` varchar(20) DEFAULT NULL,
`days2` varchar(20) DEFAULT NULL,
`days3` varchar(20) DEFAULT NULL,
`days4` varchar(20) DEFAULT NULL,
`days5` varchar(20) DEFAULT NULL,
`price1` varchar(20) DEFAULT NULL,
`price2` varchar(20) DEFAULT NULL,
`price3` varchar(20) DEFAULT NULL,
`price4` varchar(20) DEFAULT NULL,
`price5` varchar(20) DEFAULT NULL,
`totalprice1` varchar(20) DEFAULT NULL,
`totalprice2` varchar(20) DEFAULT NULL,
`totalprice3` varchar(20) DEFAULT NULL,
`totalprice4` varchar(20) DEFAULT NULL,
`totalprice5` varchar(20) DEFAULT NULL,
`click1` varchar(20) DEFAULT NULL,
`click2` varchar(20) DEFAULT NULL,
`click3` varchar(20) DEFAULT NULL,
`click4` varchar(20) DEFAULT NULL,
`click5` varchar(20) DEFAULT NULL,
`impression1` varchar(20) DEFAULT NULL,
`impression2` varchar(20) DEFAULT NULL,
`impression3` varchar(20) DEFAULT NULL,
`impression4` varchar(20) DEFAULT NULL,
`impression5` varchar(20) DEFAULT NULL,
`a` varchar(20) DEFAULT NULL,
`a0` varchar(20) DEFAULT NULL,
`a1` varchar(20) DEFAULT NULL,
`a2` varchar(20) DEFAULT NULL,
`a3` varchar(20) DEFAULT NULL,
`a4` varchar(20) DEFAULT NULL,
`a5` varchar(20) DEFAULT NULL,
`text13` text,
`items2` varchar(20) DEFAULT NULL,
`items3` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `campaign_id` (`campaign_id`),
KEY `status` (`status`),
KEY `cue` (`cue`),
KEY `a` (`a`) USING BTREE,
KEY `a0` (`a0`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
C++
|
UTF-8
| 9,722 | 3.09375 | 3 |
[
"MIT",
"BSD-2-Clause"
] |
permissive
|
/**
* Interfaces for SDC/MLSDC/PFASST algorithms.
*
* @file pfasst/interfaces.hpp
* @since v0.1.0
*/
#ifndef _PFASST_INTERFACES_HPP_
#define _PFASST_INTERFACES_HPP_
#include <memory>
#include <stdexcept>
#include <string>
using namespace std;
namespace pfasst
{
using time_precision = double;
/**
* Not implemented yet exception.
*
* Used by PFASST to mark methods that are required for a particular algorithm (SDC/MLSDC/PFASST)
* that may not be necessary for all others.
*
* @since v0.1.0
*/
class NotImplementedYet
: public runtime_error
{
string msg;
public:
/**
* @param[in] msg component or algorithm the throwing function is required for.
*/
explicit NotImplementedYet(const string& m);
virtual const char* what() const throw();
};
/**
* Value exception.
*
* Thrown when a PFASST routine is passed an invalid value.
*
* @since v0.1.0
*/
class ValueError
: public invalid_argument
{
string msg;
public:
explicit ValueError(const string& msg);
virtual const char* what() const throw();
};
class IStatus;
/**
* Abstract interface for communicators.
*/
class ICommunicator
{
public:
virtual ~ICommunicator();
virtual int size() = 0;
virtual int rank() = 0;
shared_ptr<IStatus> status;
};
/**
* Abstract interface for the current status of the algorithm.
*/
class IStatus
{
public:
static const int NOT_CONVERGED = 0;
static const int CONVERGED = 1;
protected:
ICommunicator* comm;
public:
virtual ~IStatus();
//! @{
/**
* Reset status.
*
* @note Logic is implementation defined.
*/
virtual void clear() = 0;
/**
* Set new converged state of current rank.
*/
virtual void set_converged(bool converged) = 0;
/**
* Retreive converged state for specific processor.
*
* @param[in] rank ID of processor to check converged state for
* @returns `true` if processor with ID @p rank has converged; `false` otherwise
*
* @note Inspection logic is implementation defined.
*/
virtual bool get_converged(int rank) = 0;
//! @}
//! @{
/**
* Set communicator.
*/
virtual void set_comm(ICommunicator* comm);
/**
* Check whether previous processor is still iterating.
*
* @returns `true` if previous processor has converged; `false` if it is still iterating
*/
virtual bool previous_is_iterating();
/**
* Check whether this processor should keep iterating.
*
* @returns `true` if this processor should keep iterating; `false` if it should switch to
* `converged` state
*/
virtual bool keep_iterating();
//! @}
//! @{
virtual void post(int tag) = 0;
virtual void send(int tag) = 0;
virtual void recv(int tag) = 0;
//! @}
};
template<typename time>
class Controller;
/**
* Abstract SDC sweeper.
*
* @tparam time time precision; defaults to pfasst::time_precision
*/
template<typename time = time_precision>
class ISweeper
{
protected:
/**
* Backreference to the controller managing the sweeper instance.
*/
Controller<time>* controller;
public:
//! @{
ISweeper();
virtual ~ISweeper();
//! @}
//! @{
/**
* Set the sweepers controller.
*
* @param[in] ctrl new controller to manage this sweeper
*/
virtual void set_controller(Controller<time>* ctrl);
/**
* Accessor to the controller managing this sweeper.
*
* @returns controller managing this sweeper
*/
virtual Controller<time>* get_controller();
//! @}
//! @{
/**
* Setup (allocate etc) the sweeper.
*
* @param[in] coarse `true` if this sweeper exists on a coarsened MLSDC or PFASST level.
* This implies that space for an FAS correction and "saved" solutions are necessary.
*/
virtual void setup(bool coarse = false);
/**
* Perform a predictor sweep.
*
* Compute a provisional solution from the initial condition.
* This is typically very similar to a regular SDC sweep, except that integral terms based on
* previous iterations don't exist yet.
*
* @param[in] initial `true` if function values at the first node need to be computed.
* `false` if functions values at the first node already exist (usually this is the case
* when advancing from one time step to the next).
*/
virtual void predict(bool initial) = 0;
/**
* Perform one SDC sweep/iteration.
*
* Compute a correction and update solution values.
* Note that this function can assume that valid function values exist from a previous
* pfasst::ISweeper::sweep() or pfasst::ISweeper::predict().
*/
virtual void sweep() = 0;
/**
* Advance from one time step to the next.
*
* Essentially this means copying the solution and function values from the last node to the
* first node.
*/
virtual void advance() = 0;
/**
* Return convergence status.
*
* This is used by controllers to shortcircuit iterations.
*/
virtual bool converged();
/**
* Save states (and/or function values) at all nodes.
*
* This is typically done in MLSDC/PFASST immediately after a call to restrict.
* The saved states are used to compute deltas during interpolation.
*
* @param[in] initial_only flag indicating whether only the initial state should be saved
*
* @note This method must be implemented in derived sweepers.
*/
virtual void save(bool initial_only=false);
/**
* Initialize solution values at all time nodes with meaningful values.
*/
virtual void spread();
//! @}
//! @{
/**
* Hook automatically run after each completed sweep.
*/
virtual void post_sweep();
/**
* Hook automatically run after each completed predict.
*/
virtual void post_predict();
/**
* Hook automatically run after each completed time step.
*/
virtual void post_step();
//! @}
//! @{
virtual void post(ICommunicator* comm, int tag);
virtual void send(ICommunicator* comm, int tag, bool blocking);
virtual void recv(ICommunicator* comm, int tag, bool blocking);
virtual void broadcast(ICommunicator* comm);
//! @}
};
/**
* Abstract time/space transfer (restrict/interpolate) class.
*
* @tparam time time precision; defaults to pfasst::time_precision
*/
template<typename time = time_precision>
class ITransfer
{
public:
//! @{
virtual ~ITransfer();
//! @}
//! @{
/**
* Interpolate initial condition from the coarse sweeper to the fine sweeper.
*
* @param[in,out] dst sweeper to interpolate onto (i.e. fine level)
* @param[in] src sweeper to interpolate from (i.e. coarse level)
*/
virtual void interpolate_initial(shared_ptr<ISweeper<time>> dst,
shared_ptr<const ISweeper<time>> src);
/**
* Interpolate, in time and space, from the coarse sweeper to the fine sweeper.
*
* @param[in,out] dst sweeper to interpolate onto (i.e. fine level)
* @param[in] src sweeper to interpolate from (i.e. coarse level)
* @param[in] interp_initial `true` if a delta for the initial condtion should also be
* computed (PFASST)
*/
virtual void interpolate(shared_ptr<ISweeper<time>> dst,
shared_ptr<const ISweeper<time>> src,
bool interp_initial = false) = 0;
//! @}
//! @{
/**
* Restrict initial condition from the fine sweeper to the coarse sweeper.
*
* @param[in,out] dst sweeper to restrict onto (i.e. coarse level)
* @param[in] src sweeper to restrict from (i.e. fine level)
*/
virtual void restrict_initial(shared_ptr<ISweeper<time>> dst,
shared_ptr<const ISweeper<time>> src);
/**
* Restrict, in time and space, from the fine sweeper to the coarse sweeper.
*
* @param[in,out] dst sweeper to restrict onto (i.e. coarse level)
* @param[in] src sweeper to restrict from (i.e. fine level)
* @param[in] restrict_initial `true` if the initial condition should also be restricted
*/
virtual void restrict(shared_ptr<ISweeper<time>> dst,
shared_ptr<const ISweeper<time>> src,
bool restrict_initial = false) = 0;
//! @}
//! @{
/**
* Compute FAS correction between the coarse and fine sweepers.
*
* @param[in] dt width of the time step to compute FAS correction for
* @param[in,out] dst sweeper to compute FAS correction for (i.e. coarse level)
* @param[in] src sweeper to compute FAS correction from (i.e. fine level)
*/
virtual void fas(time dt, shared_ptr<ISweeper<time>> dst,
shared_ptr<const ISweeper<time>> src) = 0;
//! @}
};
} // ::pfasst
#include "pfasst/interfaces_impl.hpp"
#endif
|
Java
|
UTF-8
| 357 | 2.796875 | 3 |
[] |
no_license
|
package whiz.filtering;
import java.util.stream.IntStream;
/**
* Created by yevgeniya.zuyeva on 15.02.2017.
*/
public class Tester2 {
public static void main(String[] args) {
IntStream ints = IntStream.range(1, 3);
ints.forEach(System.out::print);
ints.forEach(i ->System.out.print(i*2)); //exception
}
}
|
JavaScript
|
UTF-8
| 7,574 | 3.375 | 3 |
[] |
no_license
|
/*
Free Code Camp - Build a Pomodoro Clock
Created by Patrick Burns
TODO: Create Countdown Clock
DONE: Set
DONE: Start
DONE: Tick
DONE: Reset
TODO: Basic UI
DONE: Current time display
DONE: Work/Rest Time Set Value Inputs/buttons
DONE: Set/Start/Reset button
TODO: Build Pomodoro Clock (2 Countdown Clocks Together)
DONE: When work ends, start rest
DONE: When rest ends, start work
DONE: Reset each clock on expiry
TODO: Bells/whistles
TODO: Alert sound
DONE: Quick start buttons (25/5, 50/10, 10/1)
TODO: Further UI
DONE: Clocks side by side
TODO: Active highlighted, stopped faded
*/
let counter;
function PomodoroClock(duration, clockType) {
this.running = false;
this.duration = duration;
this.remaining = duration; //time left in sec
this.tickFtns = [];
this.obj = PomodoroClock.parse(duration);
this.lastDuration = duration;
this.counterpart; //counterpart Rest or Work Clock
this.clockType = clockType; //WORK or REST
}
PomodoroClock.prototype.onTick = function (ftn) { //pass in a function
if (typeof ftn === 'function') { //if arg is a function
this.tickFtns.push(ftn); //add it to list of tick functions
}
return this;
};
PomodoroClock.prototype.start = function () {
if (this.running || this.counterpart.running) { //if anything is running, don't do anything
return;
}
console.log("START: " + this);
this.running = true;
let start = Date.now();
let that = this;
//init
that.obj = PomodoroClock.parse(that.remaining); //returns min/sec at this moment to PomodoroClock object
that.tickFtns.forEach(function (ftn) {
ftn.call(this, that.obj.minutes, that.obj.seconds, that.clockType); //call each function in tickFtns, passing minutes and seconds to each
}, that);
counter = setInterval(timer, 500);
function timer() {
that.remaining = that.duration - (((Date.now() - start) / 1000) | 0);
if (that.remaining <= 0) {
that.remaining = 0;
clearInterval(counter);
that.running = false;
that.reset();
}
that.obj = PomodoroClock.parse(that.remaining); //returns min/sec at this moment to PomodoroClock object
that.tickFtns.forEach(function (ftn) {
ftn.call(this, that.obj.minutes, that.obj.seconds, that.clockType); //call each function in tickFtns, passing minutes and seconds to each
}, that);
if (!that.running) { //if expired
return that.counterpart.start(); //start counterpart clock
}
}
};
PomodoroClock.parse = function (seconds) {
return {
'minutes': (seconds / 60) | 0,
'seconds': (seconds % 60) | 0
};
};
//Stop timing
PomodoroClock.prototype.stop = function () {
if (!this.running) {
return;
}
this.running = false;
clearInterval(counter);
this.duration = this.remaining;
};
PomodoroClock.prototype.reset = function () {
if (this.lastDuration !== this.remaining || this.counterpart.lastDuration !== this.counterpart.remaining) {
this.running = false;
clearInterval(counter);
this.duration = this.lastDuration;
this.remaining = this.duration;
this.obj = PomodoroClock.parse(this.duration);
return this.counterpart.reset();
}
};
PomodoroClock.prototype.set = function (seconds) {
this.running = false;
clearInterval(counter);
this.lastDuration = seconds;
this.duration = seconds;
this.remaining = seconds;
this.obj = PomodoroClock.parse(seconds);
};
window.onload = function () {
let workDisplay = document.querySelector('#clock_text');
let workClock = new PomodoroClock(1500, 'WORK');
let workClockObj = PomodoroClock.parse(1500);
let restDisplay = document.querySelector('#rest_clock_text');
let restClock = new PomodoroClock(300, 'REST');
let restClockObj = PomodoroClock.parse(300);
let workText = document.querySelector('#work_text');
let restText = document.querySelector('#rest_text');
let workElem = document.getElementById('clock');
let restElem = document.getElementById('rest_clock');
//Relate the clocks to each other
workClock.counterpart = restClock;
restClock.counterpart = workClock;
//Initial clock draw
formatWork(workClockObj.minutes, workClockObj.seconds, 'WORK');
formatRest(restClockObj.minutes, restClockObj.seconds, 'REST');
workClock.onTick(formatWork); //Draw clock every tick
restClock.onTick(formatRest);
function formatWork(minutes, seconds, clockType) {
seconds = seconds < 10 ? '0' + seconds : seconds;
workDisplay.textContent = minutes + ':' + seconds;
workText.textContent = clockType;
if (workClock.running) {
workElem.classList.add('bg-primary', 'text-white');
restElem.classList.remove('bg-primary', 'text-white');
}
}
function formatRest(minutes, seconds, clockType) {
seconds = seconds < 10 ? '0' + seconds : seconds;
restDisplay.textContent = minutes + ':' + seconds;
restText.textContent = clockType;
if (restClock.running) {
restElem.classList.add('bg-primary', 'text-white');
workElem.classList.remove('bg-primary', 'text-white');
}
}
$("#work_plus").click(function () {
let setVal = workClock.duration + 60;
workClock.set(setVal);
formatWork(workClock.obj.minutes, workClock.obj.seconds, 'WORK');
});
$("#work_minus").click(function () {
let setVal = 0;
if (workClock.duration >= 60) { // if less than 60, set to 0
setVal = workClock.duration - 60;
}
workClock.set(setVal);
formatWork(workClock.obj.minutes, workClock.obj.seconds, 'WORK');
});
$("#rest_plus").click(function () {
let setVal = restClock.duration + 60;
restClock.set(setVal);
formatRest(restClock.obj.minutes, restClock.obj.seconds, 'REST');
});
$("#rest_minus").click(function () {
let setVal = 0;
if (restClock.duration >= 60) { // if less than 60, set to 0
setVal = restClock.duration - 60;
}
restClock.set(setVal);
formatRest(restClock.obj.minutes, restClock.obj.seconds, 'REST');
});
$("#start").click(function () {
workClock.start();
});
$("#reset").click(function () {
workClock.reset();
restClock.reset();
formatWork(workClock.obj.minutes, workClock.obj.seconds, 'WORK');
formatRest(restClock.obj.minutes, restClock.obj.seconds, 'REST');
workElem.classList.remove('bg-primary', 'text-white');
restElem.classList.remove('bg-primary', 'text-white');
});
$("#10_1").click(function () {
workClock.set(600);
restClock.set(60);
formatWork(workClock.obj.minutes, workClock.obj.seconds, 'WORK');
formatRest(restClock.obj.minutes, restClock.obj.seconds, 'REST');
});
$("#25_5").click(function () {
workClock.set(1500);
restClock.set(300);
formatWork(workClock.obj.minutes, workClock.obj.seconds, 'WORK');
formatRest(restClock.obj.minutes, restClock.obj.seconds, 'REST');
});
$("#50_10").click(function () {
workClock.set(3000);
restClock.set(600);
formatWork(workClock.obj.minutes, workClock.obj.seconds, 'WORK');
formatRest(restClock.obj.minutes, restClock.obj.seconds, 'REST');
});
};
|
PHP
|
UTF-8
| 1,013 | 3.625 | 4 |
[] |
no_license
|
<?php
/**
* Created by PhpStorm.
* User: hovsep
* Date: 16.01.19
* Time: 14:05
*/
namespace ArraysAndStrings;
/**
* Question 1.3
*
* URLify: Write a method to replace all spaces in a string with '%20'. You may assume that the string
* has sufficient space at the end to hold the additional characters, and that you are given the "true"
* length of the string. (Note: if implementing in Java, please use a character array so that you can
* perform this operation in place.)
*/
class Urlify
{
const SPACE = ' ';
public static function urlify($input, $l) {
for ($i = 0; $i < strlen($input); $i++) {
if ($input[$i] == self::SPACE) {
//Shift rest string
for ($j = $l - 1; $j > $i; $j--) {
$input[$j+2] = $input[$j];
}
$input[$i] = '%';
$input[$i+1] = '2';
$input[$i+2] = '0';
$l +=2;
}
}
return $input;
}
}
|
SQL
|
UHC
| 426 | 3.453125 | 3 |
[] |
no_license
|
create table student03(
num number primary key,
name varchar2(9),
age number(2) check (age between 1 and 80)
);
create sequence stu03_seq start with 21001;
--num,name,age
create table grade03(
num number primary key,
kor number(3) default 0, -- Է ϸ ڵ 0
eng number(3) default 0,
math number(3) default 0,
foreign key(num) references student03(num)
);
-- num,kor,math
|
JavaScript
|
UTF-8
| 1,483 | 2.984375 | 3 |
[] |
no_license
|
import _ from 'underscore'
import utils from './utils/index'
import Glass from './components/glass'
const cacehCanvas = utils.getCacheCanvas(500, 500);
const cacheContext = utils.getContext(cacehCanvas);
const context = utils.getContext('#canvas');
let range = 0.01;
const gap = 20;
const glasses=getGlasses(gap,500);
init(cacheContext);
animate();
function init(context) {
context.translate(0.5, 0.5);
context.lineWidth = 1;
context.strokeStyle = '#006633';
}
function getGlasses(gap,width) {
const glasses = [];
for (let i = 0; i < width; i += gap / 2) {
let rand = Math.random().toFixed(1) / 1 + 0.5; //0.5-1.5
let glass = new Glass({
x: i + gap * rand - gap,
y: 500
});
glasses.push(glass)
}
return glasses;
}
// console.timeEnd();
function animate() {
// cacheContext.clearRect(0, 0, 500, 500);
// console.time();
drawGlasses(cacheContext, glasses);
context.clearRect(0, 0, 500, 500);
context.drawImage(cacehCanvas, 0, 0, 500, 500);
// console.timeEnd();
requestAnimationFrame(animate);
// setTimeout(animate,500)
range += 0.005;
}
function drawGlasses(context, glasses) {
// console.time();
cacheContext.fillStyle = '#33ccff';
cacheContext.fillRect(0, 0, 500, 500);
let rand = Math.sin(range * Math.PI);
context.fillStyle = '#339933';
let ancle = 60 * rand;
glasses.forEach(glass => glass.draw(cacheContext, ancle))
// console.timeEnd();
}
// utils.drawRect(75,25,150,1 50)(cacheContext);
|
C
|
UTF-8
| 2,493 | 2.6875 | 3 |
[] |
no_license
|
#include "dfs_mem_allocator.h"
#include "dfs_shmem_allocator.h"
#include "dfs_mempool_allocator.h"
dfs_mem_allocator_t *dfs_mem_allocator_new(int allocator_type)
{
dfs_mem_allocator_t *allocator = NULL;
allocator = (dfs_mem_allocator_t *)malloc(sizeof(dfs_mem_allocator_t));
if (!allocator)
{
return NULL;
}
switch (allocator_type)
{
case DFS_MEM_ALLOCATOR_TYPE_SHMEM:
*allocator = *dfs_get_shmem_allocator();
break;
case DFS_MEM_ALLOCATOR_TYPE_MEMPOOL:
*allocator = *dfs_get_mempool_allocator();
break;
case DFS_MEM_ALLOCATOR_TYPE_COMMPOOL:
*allocator = *dfs_get_commpool_allocator();
default:
return NULL;
}
allocator->private_data = NULL;
return allocator;
}
dfs_mem_allocator_t *dfs_mem_allocator_new_init(int allocator_type,
void *init_param)
{
dfs_mem_allocator_t *allocator = NULL;
allocator = (dfs_mem_allocator_t *)malloc(sizeof(dfs_mem_allocator_t));
if (!allocator)
{
return NULL;
}
switch (allocator_type)
{
case DFS_MEM_ALLOCATOR_TYPE_SHMEM:
*allocator = *dfs_get_shmem_allocator();
break;
case DFS_MEM_ALLOCATOR_TYPE_MEMPOOL:
*allocator = *dfs_get_mempool_allocator();
break;
case DFS_MEM_ALLOCATOR_TYPE_COMMPOOL:
*allocator = *dfs_get_commpool_allocator();
break;
default:
return NULL;
}
allocator->private_data = NULL;
if (init_param && allocator->init(allocator, init_param)
== DFS_MEM_ALLOCATOR_ERROR)
{
return NULL;
}
return allocator;
}
void dfs_mem_allocator_delete(dfs_mem_allocator_t *allocator)
{
dfs_shmem_allocator_param_t shmem;
dfs_mempool_allocator_param_t mempool;
if (!allocator)
{
return;
}
if (allocator->private_data)
{
switch (allocator->type)
{
case DFS_MEM_ALLOCATOR_TYPE_SHMEM:
allocator->release(allocator, &shmem);
break;
case DFS_MEM_ALLOCATOR_TYPE_MEMPOOL:
allocator->release(allocator, &mempool);
break;
case DFS_MEM_ALLOCATOR_TYPE_COMMPOOL:
allocator->release(allocator, NULL);
break;
}
}
free(allocator);
}
|
Python
|
UTF-8
| 4,344 | 2.609375 | 3 |
[] |
no_license
|
from socket import *
server = "127.0.0.1"
serverPort = 25
#cria socket
socketClient = socket(AF_INET, SOCK_DGRAM)
usuarios = input("Digite o arquivo de usuarios a ser lido: ")
socketClient.sendto(usuarios.encode(), (server, serverPort))
msgUsers, addr = socketClient.recvfrom(2048)
msgUser = msgUsers.decode("UTF-8")
if(msgUser == "Arquivo aberto com sucesso"):
print(msgUser)
while 1:
aux3 = 0
#envio do helo
helo = input("Digite o comando HELO + username para iniciar a transação\n")
socketClient.sendto(helo.encode(), (server, serverPort))
respHelo, addr = socketClient.recvfrom(2048)
respHel = respHelo.decode("UTF-8")
if(respHel == "QUIT"):
break
while(respHel == "500 Syntax error, command unrecognized"):
#caso helo receba um erro, pede para repetir o processp
print(respHel)
helo = input("Digite o comando HELO + user para iniciar a transação\n")
socketClient.sendto(helo.encode(), (server, serverPort) )
respHelo, addr = socketClient.recvfrom(2048)
respHel = respHelo.decode("UTF-8")
if(respHel == "QUIT"):
aux3 = 1
break
if(aux3 == 1):
break
print(respHel)
#recebe o email e faz o envio para o servidor
mailFrom = input("Mail From: ")
#envia email para o servidor
socketClient.sendto(mailFrom.encode(), (server, serverPort))
respMailFrom, addr = socketClient.recvfrom(2048)
respMailFro = respMailFrom.decode("UTF-8")
if(respMailFro == "QUIT"):
break
#se a resposta for um email que não existe pede para repetir o processo
while(respMailFro == "550 Address Unkonown"):
print(respMailFro)
mailFrom = input("Mail From: ")
socketClient.sendto(mailFrom.encode(), (server, serverPort))
respMailFrom, addr = socketClient.recvfrom(2048)
respMailFro = respMailFrom.decode("UTF-8")
if(respMailFro == "QUIT"):
aux3 = 1
break
if(aux3 == 1):
break
print(respMailFro)
sndRCPT = input("RCPT TO: ")
socketClient.sendto(sndRCPT.encode(), (server, serverPort))
rcvRCPT, addr = socketClient.recvfrom(2048)
rcvRCP = rcvRCPT.decode("UTF-8")
if(rcvRCP == "QUIT"):
break
#o remetente nao existe
while(rcvRCP == "550 Address Unkonown"):
print(rcvRCP)
sndRCPT = input("RCPT TO: ")
socketClient.sendto(sndRCPT.encode(), (server, serverPort))
rcvRCPT, addr = socketClient.recvfrom(2048)
rcvRCP = rcvRCPT.decode("UTF-8")
if(rcvRCP == "QUIT"):
aux3 = 1
break
if(aux3 == 1):
break
print(rcvRCP)
#Recebe Data
sndDATA = input()
socketClient.sendto(sndDATA.encode(), (server, serverPort))
rcvDATA, addr = socketClient.recvfrom(2048)
rcvDAT = rcvDATA.decode("UTF-8")
if(rcvDAT == "QUIT"):
break
while(rcvDAT == "500 Syntax error, command unrecognized"):
print(rcvDAT)
sndDATA = input()
socketClient.sendto(sndDATA.encode(), (server, serverPort))
rcvDATA, addr = socketClient.recvfrom(2048)
rcvDAT = rcvDATA.decode("UTF-8")
if(rcvDAT == "QUIT"):
aux3 = 1
break
if(aux3 == 1):
break
print(rcvDAT)
listEmail = []
while(1):#recebe a mensagem do email
email = input()
if(email == "."):
listEmail.append(email)
break
else:
listEmail.append(email)
for i in range (len(listEmail)):
socketClient.sendto(listEmail[i].encode(), (server, serverPort))
msgEmail, addr = socketClient.recvfrom(2048)
msg = msgEmail.decode("UTF-8")
print(msg)
else:
print(msgUser)
socketClient.close()
|
Java
|
UTF-8
| 1,059 | 2.15625 | 2 |
[] |
no_license
|
package controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import entity.UserEntity;
import service.UserService;
@WebServlet("/list")
public class ListController extends HttpServlet {
private static final long serialVersionUID = 1L;
private UserService userSerivce = new UserService();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<UserEntity> list = userSerivce.getAll();
request.setAttribute("list",list);
//请求转发
request.getRequestDispatcher("/WEB-INF/jsp/list.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
|
Shell
|
UTF-8
| 4,673 | 3.734375 | 4 |
[
"Apache-2.0"
] |
permissive
|
#!/bin/bash
# Apache License 2.0
# Copyright 2016 Random Archer
# This file is part of https://github.com/random-archer/nspawn.sh
# import source once
___="source_${BASH_SOURCE//[![:alnum:]]/_}" ; [[ ${!___-} ]] && return 0 || eval "declare -gr $___=@" ;
#!
#
# systemd unit.nspawn and unit.service file generator
#
# discover system unit identity
ns_unit_args() {
[[ ${url-} && ${name-} ]] && echo "url=$url name=$name" && return 0
ns_log_fail "can not resolve unit: provide 'id' or 'url' + 'name'"
}
# generate /etc/systemd/nspawn/<machine-id>.nspawn content
ns_unit_profile_text() {
local text= entry=
ns_a_define text << EOF
#
# $(ns_a_date_time) $(ns_a_prog_name) container profile
#
#[Log]
$(for entry in "${machine_log[@]-}" ; do echo "$entry" ; done)
#
[Exec]
$(for entry in "${machine_entry[@]-}" ; do [[ $entry =~ ${ns_VAL[prof_exec]} ]] && echo "$entry" || continue ; done)
#
[Files]
$(for entry in "${machine_entry[@]-}" ; do [[ $entry =~ ${ns_VAL[prof_files]} ]] && echo "$entry" || continue ; done)
#
[Network]
$(for entry in "${machine_entry[@]-}" ; do [[ $entry =~ ${ns_VAL[prof_network]} ]] && echo "$entry" || continue ; done)
#
EOF
printf "%q" "$text"
}
#
ns_unit_service_overlay_assert() {
local overlay=$(ns_overlay_extract)
local entry= ; for entry in ${overlay//':'/' '} ; do
echo "AssertPathExists=$entry"
done
}
#
ns_unit_service_create() {
local cmd_mkdir="$(type -p mkdir)"
local point="${machine[machine_dir]}"
true && {
echo "ExecStartPre=$cmd_mkdir -p ${machine[root_dir]}"
echo "ExecStartPre=$cmd_mkdir -p ${machine[work_dir]}"
}
echo "ExecStartPre=$(ns_overlay_create_cmd)"
}
ns_unit_service_delete() {
local cmd_rm="$(type -p rm)"
local point="${machine[machine_dir]}"
echo "ExecStopPost=$(ns_overlay_delete_cmd)"
[[ "${ns_CONF[unit_runtime_persist]}" == yes ]] || {
echo "ExecStopPost=$cmd_rm -r -f ${machine[root_dir]}"
echo "ExecStopPost=$cmd_rm -r -f ${machine[work_dir]}"
}
}
ns_unit_service_invoke() {
local cmd_nspawn="$(type -p systemd-nspawn)"
local machine_id=${machine[id]}
local nspawn_options=(
${ns_CONF[unit_nspawn_options]}
--uuid=$(ns_a_guid) # TODO expose to config
)
echo ExecStart="$cmd_nspawn" --machine="$machine_id" "${nspawn_options[@]}"
}
# parse: unit_DeviceAllow="char-tty0 rwm;char-ttyUSB rwm;"
ns_unit_service_text_device() {
[[ ${ns_CONF[unit_DeviceAllow]} ]] || return 0
local IFS=';' ; local entry_list=(${ns_CONF[unit_DeviceAllow]-}) ; unset IFS # parse param
local rx_space="^[[:space:]]*$" # invalid
local entry= ; for entry in "${entry_list[@]-}" ; do
[[ $entry =~ $rx_space ]] && continue # drop empty
echo "DeviceAllow=$entry"
done
}
# generate /etc/systemd/system/machine.service file
ns_unit_service_text() {
local machine_id=${machine[id]}
local text= entry=
ns_a_define text << EOF
#
# $(ns_a_date_time) $(ns_a_prog_name) container service
#
[Unit]
Description=$(ns_a_prog_name)/$machine_id
After=${ns_CONF[unit_After]}
Requires=${ns_CONF[unit_Requires]}
#
# Container Mount:
AssertPathExists=${machine[machine_dir]}
#
# Container Profile:
AssertPathExists=${machine[profile_file]}
#
# Container Overlay:
$(for entry in "$(ns_unit_service_overlay_assert)" ; do echo "$entry" ; done)
#
[Service]
KillMode=${ns_CONF[unit_KillMode]}
Slice=${ns_CONF[unit_Slice]}
CPUQuota=${ns_CONF[unit_CPUQuota]}
RestartSec=${ns_CONF[unit_RestartSec]}
TimeoutStartSec=${ns_CONF[unit_TimeoutStartSec]}
TimeoutStopSec=${ns_CONF[unit_TimeoutStopSec]}
SyslogIdentifier=$machine_id
RestartForceExitStatus=${ns_CONF[unit_RestartForceExitStatus]}
RestartPreventExitStatus=${ns_CONF[unit_RestartPreventExitStatus]}
$(ns_unit_service_text_device)
#
# Container Create:
$(for entry in "$(ns_unit_service_create)" ; do echo "$entry" ; done)
#
# Container Invoke:
$(for entry in "$(ns_unit_service_invoke)" ; do echo "$entry" ; done)
#
# Container Delete:
$(for entry in "$(ns_unit_service_delete)" ; do echo "$entry" ; done)
#
[Install]
WantedBy=${ns_CONF[unit_WantedBy]}
#
EOF
printf "%q" "$text"
}
# provision unit service/profile files
ns_unit_resource() {
local "$@" ; ns_log_req --dbug mode
ns_a_resource file="${machine[profile_file]}" text="$(ns_unit_profile_text)"
ns_a_resource file="${machine[service_file]}" text="$(ns_unit_service_text)"
local conf_file=${machine[conf_file]}
case "$mode" in
create) ns_context_machine_save file="$conf_file" ;;
delete) ns_a_sudo rm -f "$conf_file" ;;
ignore) ;;
*) ns_log_fail "wrong mode '$mode'" ;;
esac
}
|
Swift
|
UTF-8
| 351 | 2.578125 | 3 |
[] |
no_license
|
//
// Dragable.swift
// Htlaeh
//
// Created by Cody Weaver on 7/2/16.
// Copyright © 2016 Htlaeh. All rights reserved.
//
import Foundation
import UIKit
/**
Anything that can swipe or be dragged
Replacement for UIPanGesture
*/
protocol Draggable {
var dragAction: (Int) -> () { get }
var dragFinished: (Int) -> () { get }
}
|
Python
|
UTF-8
| 945 | 2.78125 | 3 |
[
"Apache-2.0"
] |
permissive
|
import requests
from bs4 import BeautifulSoup
import os
import pprint
import sys
inp = str(sys.argv[1])
f = open(inp)
soup = BeautifulSoup(f.read(),"lxml")
table = soup.find_all("div",{"id":"\\\"issue_types\\\""})
table = BeautifulSoup(str(table),"lxml")
data = table.find_all("table")
categories = []
catFile = open("categories.txt")
catFile = catFile.read()
requiredCategories = catFile.split("\n")
finalCount = 0
for issue in table:
issue = BeautifulSoup(str(issue),"lxml")
datasList = issue.find_all("td")
# print len(datas)
for datas in datasList:
try:
tr = BeautifulSoup(str(datas),"lxml")
name = tr.find_all("span")[0]
count = tr.find_all("span")[1]
Name = name.string
Count = count.string.split("(")[1].split(")")[0]
categories.append({"name":Name,"count":Count})
except:
pass
for i in categories:
for j in requiredCategories:
if(i["name"]==j):
finalCount += int(i["count"])
print finalCount
|
JavaScript
|
UTF-8
| 2,299 | 2.875 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
const hospital = location.href.substring(8, location.href.indexOf('.'));
const patientId = sessionStorage.getItem('patient_id');
const dataToSend = {};
dataToSend.patient_id = patientId;
dataToSend.hospital = hospital;
init();
async function init() {
const patientInfo = await executeAction('get_patient');
for (let prop in patientInfo) {
if (prop !== 'medical_info') {
document.getElementById(prop).value = patientInfo[prop];
}
else {
for (let data in patientInfo.medical_info) {
document.getElementById(`med_${data}`).value = patientInfo.medical_info[data];
}
}
}
}
async function executeAction(action) {
let response = await fetch(`https://api.spetz.online:4040/icu/patients/${action}`,{
method: 'POST',
headers: {
'Access-Control-Allow-Origin': '*',
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': `Bearer ${sessionStorage.getItem('token')}`
},
body: JSON.stringify(dataToSend)
});
if (response.status == 401) {
sessionStorage.clear();
location.href = `login.html`;
}
if (action === 'update_patient' || action === 'delete_patient') {
return response;
}
else {
let data = await response.json();
return data;
}
}
const deletePatient = async () => {
const response = await executeAction('delete_patient');
if (response.status === 200) {
alert('המחיקה בוצעה בהצלחה!');
}
else {
alert('המטופל אינו קיים במערכת, אנא נסו שנית');
}
sessionStorage.removeItem('patient_id');
location.href = `main.html`;
}
const updatePatient = async () => {
const form = document.querySelectorAll('.form-control');
dataToSend.medical_info = {};
for (let input of form) {
if (input.value !== "") {
if (input.id.startsWith('med_'))
dataToSend.medical_info[input.id.substring(4)] = input.value;
else {
if (input.id === 'phone_list') {
input.value = input.value.replace(/\s/g,'');
dataToSend[input.id] = input.value.split(',');
}
else
dataToSend[input.id] = input.value;
}
}
}
await executeAction('update_patient');
alert('העדכון בוצע בהצלחה!');
sessionStorage.removeItem('patient_id');
location.href = `main.html`;
}
|
Java
|
UTF-8
| 1,228 | 2.15625 | 2 |
[] |
no_license
|
/* Generated By:JJTree: Do not edit this line. ASTTerm.java Version 6.0 */
/* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */
public
class ASTTerm extends SimpleNode {
private String op = "+";
private String name;
public ASTTerm(int id) {
super(id);
}
public ASTTerm(YAL2JVM p, int id) {
super(p, id);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOp() {
return op;
}
public void setOp(String op) {
this.op = op;
}
public String toString() {
String test = super.toString();
if(name != null)
return test + " " + op + " " + name;
return test + " " + op;
}
public int checkScalarOrArray(Table currentTable) {
if(name == null)
return this.jjtGetChild(0).checkScalarOrArray(currentTable);
else {
return 0;
}
}
/** Accept the visitor. **/
public Object jjtAccept(YAL2JVMVisitor visitor, Object data) {
return
visitor.visit(this, data);
}
}
/* JavaCC - OriginalChecksum=5d3a68fdda66f7b9326bf5f7cb948322 (do not edit this line) */
|
Markdown
|
UTF-8
| 4,774 | 2.671875 | 3 |
[] |
no_license
|
* [首頁](README.md)
<!-- 了解babel -->
- 了解 Babel
- [Babel 定義和作用](babel/README)
- [ES 版本列表](es6/es-version)
<!-- ES6常用語法 -->
- ES6 常用語法
- [let 和 const 用法](es6/let-const)
- [模組化(module)](es6/es-module)
- [解構賦值](es6/object-array)
- [對象拓展](es6/object)
- [模板字串](es6/string)
- [拓展運算符](es6/Spread-operator)
- [includes](es6/includes)
- [class類](es6/class)
- [箭頭函數](es6/arrow-function)
- [類修飾器 Decorator](es6/Decorator)
- [Promise 處理非同步](es6/promise)
- [generator 處理非同步](es6/generator)
- [async/await 非同步終結者](es6/async-await)
<!-- react基礎知識 -->
- React組件寫法
- [- React 組件的類型](react-base/component/React組件的類型.md)
- [- class 類組件](react-base/component/class類組件.md)
- [- 函數組件](react-base/component/函數組件.md)
- JSX 語法
- [- jsx和html的區別](react-base/jsx/jsx和html的區別.md)
- [- jsx的基本使用](react-base/jsx/jsx的基本使用.md)
- [- jsx條件判斷](react-base/jsx/jsx條件判斷.md)
- [- 處理列表渲染](react-base/jsx/處理列表渲染.md)
- CSS 處理方案
- [- css處理方案有哪些 ?](react-base/style/css處理方案有哪些.md)
- [- Sass](react-base/style/使用Sass.md)
- [- css-module](react-base/style/css-module.md)
- [- postcss](react-base/style/postcss.md)
- [- styled-components(推薦)](react-base/style/css-in-js.md)
- [- flex 彈性布局](react-base/style/flex彈性布局.md)
- state 和props 的用法
- [- state基本使用](react-base/state-props/state的基本使用.md)
- [- setState用法](react-base/state-props/setState.md)
- [- props基本使用](react-base/state-props/props基本使用.md)
- [- react組件通信方式](react-base/state-props/react組件通信方式.md)
- React 組件生命週期
- [- 理解react組件生命週期](react-base/lifeCycle/理解React組件生命週期.md)
- [- 新版組件生命週期](react-base/lifeCycle/新版組件生命週期.md)
- [- 舊版組件生命週期](react-base/lifeCycle/舊版組件生命週期.md)
- 實踐課:開發個人網站
- [- 技術選型](react-base/website/技術選型.md)
- [- 頁面布局](react-base/website/頁面布局.md)
- [- 頭部導航和底部文案](react-base/website/頭部導航和底部文案.md)
- [- 首頁](react-base/website/首頁.md)
- [- 作品列表頁](react-base/website/作品列表頁.md)
- [- 作品詳情頁](react-base/website/作品詳情頁.md)
<!-- react進階知識 -->
- 處理表單和事件綁定
- [React 事件處理](react-progress/forms/React事件處理.md)
- [Refs 實現DOM的訪問](react-progress/forms/Refs實現DOM的訪問.md)
- [使用受控組件處理表單](react-progress/forms/使用受控組件處理表單.md)
- [使用非受控組件處理表單](react-progress/forms/使用非受控組件處理表單.md)
- [處理表單驗證](react-progress/forms/處理表單驗證.md)
- Portals 和 PropTypes
- [Portals 的基本使用](react-progress/porpro/Portals的基本使用.md)
- [使用 Portals 封裝跳出視窗組件](react-progress/porpro/使用Portals封裝跳出視窗組件.md)
- [PropTypes(類型檢查)](react-progress/porpro/PropTypes(類型檢查).md)
- 處理API請求
- [如何在 React 中處理數據請求](react-progress/api/如何在react中處理數據請求.md)
- [使用 fetch 和 axios 請求數據](react-progress/api/使用fetch和axios請求數據.md)
- [API統一管理](react-progress/api/API統一管理.md)
<!-- react高階知識 -->
- React 高級特性
- [memo](react-Advanced/features/memo.md)
- [代碼分割](react-Advanced/features/代碼分割.md)
- [Suspense和lazy](react-Advanced/features/Suspense和lazy.md)
- React hooks
- [介紹 Hooks](react-Advanced/react-hooks/介紹Hooks.md)
- [useState](react-Advanced/react-hooks/useState.md)
- [useEffect](react-Advanced/react-hooks/useEffect.md)
- [useContext](react-Advanced/react-hooks/useContext.md)
- [useReducer](react-Advanced/react-hooks/useReducer.md)
- [額外的Hooks](react-Advanced/react-hooks/額外的Hooks.md)
- [自訂Hooks](react-Advanced/react-hooks/自訂Hooks.md)
- [Hooks的規則](react-Advanced/react-hooks/Hooks的規則.md)
- React 生態系統
- [圖解react生態系統](react-Advanced/ecosystem/圖解react生態系統.md)
- [案例1:使用工具庫](react-Advanced/ecosystem/案例1:使用工具庫.md)
- [案例2:使用UI庫](react-Advanced/ecosystem/案例2:使用UI庫.md)
- Redux
- [Redux 簡介](redux/Redux簡介.md)
- [Redux 基本使用與實踐](redux/Redux基本使用與實踐.md)
|
Java
|
UTF-8
| 1,002 | 2.171875 | 2 |
[] |
no_license
|
package com.una.app.placefinder506;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
/**
* Created by
* Angélica
* Bryhan
* Marco
* Massiel Mora Rodríguez cedula: 604190071
*/
public class Leg {
@SerializedName("distance")
@Expose
private Distance distance;
@SerializedName("duration")
@Expose
private Duration duration;
/**
*
* @return
* The distance
*/
public Distance getDistance() {
return distance;
}
/**
*
* @param distance
* The distance
*/
public void setDistance(Distance distance) {
this.distance = distance;
}
/**
*
* @return
* The duration
*/
public Duration getDuration() {
return duration;
}
/**
*
* @param duration
* The duration
*/
public void setDuration(Duration duration) {
this.duration = duration;
}
}
|
C++
|
UTF-8
| 540 | 3.046875 | 3 |
[] |
no_license
|
class Solution {
private:
int square(int n)
{
int res=0;
while(n!=0)
{
res=res+(n%10)*(n%10);
n=n/10;
}
return res;
}
public:
bool isHappy(int n) {
if(n==1)
return true;
unordered_set<int> myset;
while(n!=1 && myset.find(n)==myset.end())
{
myset.insert(n);
n=square(n);
}
return n==1;
}
};
//while条件的设置
//退出之后n就符合条件了
|
Markdown
|
UTF-8
| 8,551 | 2.5625 | 3 |
[
"LicenseRef-scancode-public-domain"
] |
permissive
|
> *The following text is extracted and transformed from the ucpress.edu privacy policy that was archived on 2019-10-23. Please check the [original snapshot on the Wayback Machine](https://web.archive.org/web/20191023161752id_/https%3A//www.ucpress.edu/about/privacy-policy) for the most accurate reproduction.*
# Privacy Policy - University of California Press
This website is owned and operated by University of California Press, on behalf of the Regents of the University of California (“UC Press”, “we”, “our”, or “us”). This privacy policy (“Privacy Policy”) explains to our customers and visitors (“you”, “your”) how we collect, use and disclose personal information that we obtain through this website.
UC Press is committed to protecting the privacy and accuracy of your personally identifiable information to the extent possible, subject to provisions of state and federal law. Other than as required by laws that guarantee public access to certain types of information, or in response to subpoenas or other legal instruments that authorize disclosure, personally identifiable information is not disclosed without your consent. We take reasonable steps to maintain the security, integrity and privacy of any information in accordance with this Privacy Policy.
**Data Collection:** UC Press may collect personal information during the login process used to access certain portions of our website or to use other functions or features, as noted. We may collect and use personally identifiable information including, but not limited to, the following: name, address, phone number, fax number, email address, employer, title, user ID and password, course information, credit card information, and IP address. Any demographic information we request is generally used in aggregate form for various analyses conducted by UC Press regarding our website and related materials.
**Use of Information Collected on UC Press’s Site:** We use personal information to provide the highest quality of service to our customers, prospects, and general visitors to this website. This may include using and reporting of de-identified, anonymous, aggregated data. In addition to the specific purposes for which we collect certain data, as described further in this Privacy Policy, UC Press may collect personal information so that we can contact you, provide materials to you upon your request, keep you posted on new products and services, track your orders, register you, send relevant messages via email or postal mail, or for any other purpose identified when personal information is collected. Our website provides a way to indicate that you do not wish to receive these messages in which case we will remove your information from the appropriate list.
**Shopping cart/Examination/Desk Copy Request Form:** Both our online Shopping Cart and our Examination/Desk Copy Request Form use your email address to track your order. This allows us to automatically send you a receipt and a shipping confirmation electronically, and to contact you in case of a problem or a need for more information to process your order. We reserve the right to send you periodic communications for marketing and promotional purposes. When you order from us, we may ask you at the end of your order if you would like to receive eNews email (see below), but you will not be signed up automatically for eNews. You will need to manually click the indicated link, choose one or more product categories, and then submit a form to get signed up for eNews updates.
**eNews:** Our eNews email messages are based on an opt-in system, and such notification will be conducted in conformance with University of California and campus policies implementing anti-spam laws ( <http://www.ucop.edu/irc/policy/antispam.pdf>). If you received such a message from us, someone using that address signed up to receive our messages. If you are the owner of this account and did not sign up, you may remove your email address by clicking the unsubscribe link at the bottom of the eNews email. This will permanently remove your address from UC Press’s email distribution list unless you choose to join again later.
If you have any trouble, please contact us and we will resolve your issue as quickly as possible.
**Referrals/Recommendations:** If you receive an email from us marked “Tell a Friend,” these messages have been sent via a Web-form by an individual who indicated that they were a colleague or friend of yours and wanted you to receive information about something they were browsing on our website, such as a newly published title or newly released website. The name and email address of the individual who has sent you the referral will be included in the email you receive.
Email addresses to which we send Tell-a-Friend messages are NOT saved for our further use. The software we use to send these messages is “double-blind,” meaning that we do not know whom these messages are being sent, and you will not be contacted by us again in the future as a result of receiving or sending one of these referrals or recommendations.
**Information Sharing:** UC Press will not disclose or share, without your consent, personally identifiable information, except for certain explicit circumstances in which disclosure may be required by law. Your personally identifiable information will not be distributed or sold to third-party organizations.
**Data Protection:** UC Press is committed to ensuring the security of your information. We use industry-standard processes designed to protect sensitive data.
**Consent:** By use of the UC Press website, and entry of any personal information into this site or in any UC Press program accessed through our website, you are consenting to the collection, use and transfer of your personal information as outlined in this Privacy Policy. If you are located outside the United States, your use and entry of personal information into this site constitutes your consent to the transfer of your personal information into the United States.
**Updating Personal Information:** Questions regarding your options to review, modify or delete previously provided personal information should be directed to us via our contact form.
**Cookies and other Tracking Devices:** UC Press may use cookies, IP addresses, and other passive tracking devices to collect aggregate statistics about our website. Personally identifiable information is not stored within cookies. We use this aggregate information to monitor the performance of this site so we can improve its use and add features and programs to make it more effective. UC Press may also disclose this aggregate information to third parties. You may choose to set your browser settings to disable cookies, however, please note that if you do so, you may not be able to complete certain activities or access certain information on our website.
**Links:** UC Press’s website may contain links to other websites. Please note that these other websites’ privacy policies may differ from UC Press’s and we encourage you to carefully read those policies, as well. UC Press is not responsible for and does not endorse the contents of any website of another party or for the policies or actions of any such party.
**Surveys and Drawings:** From time-to-time, UC Press may request information from users via surveys or drawing entries. Participation in these surveys or drawings is completely voluntary, so you can decide whether you want to provide the information. Information requested may include contact information (such as name and address), and demographic information (such as postal code, age range). If you give UC Press information in connection with a UC Press drawing, survey, or similar promotion, you agree that we can use that information to manage those activities. Contact information will be used to notify the winners and award prizes, if applicable.
**Revisions to this Privacy Policy:** This Privacy Policy has been created and approved by UC Press. UC Press reserves the right to revise this Privacy Policy at any time, so please review this Privacy Policy frequently. Each version of this Privacy Policy will have a date, as noted below.
**Feedback:** If you have any questions or comments about UC Press’s Privacy Policy, please contact us at [generalmailbox@ucpress.edu](mailto:generalmailbox@ucpress.edu).
University of California Press Privacy Policy (September 2012)
|
Shell
|
UTF-8
| 1,809 | 3.5625 | 4 |
[] |
no_license
|
#! /bin/sh
set -eux
function commitChangedPoms() {
POMS=$(find . -name pom.xml -not -path '*/target/*')
if [ $(git status -s $POMS|grep -vc '^??') -gt 0 ]; then
git commit -m "$1" $POMS
git push
fi
}
if [ $(git branch | grep '^*' | cut -c 2-) = 'master' ]; then
echo 'Performing mainline release'
# figure out version
VERSION=$(mvn help:evaluate -Dexpression=project.version|grep '^[0-9]*\.[0-9]*\.[0-9]*-SNAPSHOT'|sed 's/-SNAPSHOT//')
MAJOR=$(echo $VERSION|tr '.' ' '|awk '{print $1}')
MINOR=$(echo $VERSION|tr '.' ' '|awk '{print $2}')
PATCH=$(echo $VERSION|tr '.' ' '|awk '{print $3}')
# create a mainline release branch
BRANCH=$MAJOR.$MINOR.x
mvn release:branch -B -DbranchName=$BRANCH -DreleaseVersion=$MAJOR.$MINOR.0 -DdevelopmentVersion=$MAJOR.$(expr $MINOR + 1).0-SNAPSHOT
# update minor and patch versions on the branch
git checkout $BRANCH
mvn versions:use-latest-releases -DallowMajorUpdates=false
commitChangedPoms 'Updated branch dependency minor versions for release'
# perform release
mvn release:prepare release:perform -B -DreleaseVersion=$MAJOR.$MINOR.0
# commitChangedPoms 'Updated master project version after release'
# updated master to latest snapshot versions
git checkout master
mvn versions:use-latest-versions -DallowMajorUpdates=false
commitChangedPoms 'Updated master dependency minor versions after release'
else
echo 'Performing interim release'
# update patch versions
mvn versions:use-latest-releases -DallowMajorUpdates=false -DallowMinorUpdates=false
commitChangedPoms 'Updated branch dependency patch versions for release'
mvn release:prepare release:perform -B
# commitChangedPoms 'Updated branch project version after release'
fi
|
Markdown
|
UTF-8
| 3,706 | 4 | 4 |
[
"Apache-2.0"
] |
permissive
|
## 判断一棵二叉树是否是平衡二叉树
【**平衡二叉树概念**】当二叉树的任意一棵子树的左子树的高度和右子树的高度相差不超过 1 时,该二叉树为平衡二叉树。
【**解答方案**】根据定义可知,要确认一个二叉树是否是平衡二叉树势必要遍历所有结点。
即将问题分解为:只要保证以每个结点为根节点的树是否平衡;而遍历到每个结点时,要想知道以该结点为根结点的子树是否是平衡二叉树,首先判断该结点的左子树是否平衡,然后判断该结点的右子树是否平衡,如果两个子树都平衡,分别计算左子树和右子树的高度。因此我们要收集两个信息:
- 该结点的左子树、右子树是否是平衡二叉树
- 左右子树的高度分别是多少,相差是否超过 1
那么我们来到某个结点时(子过程),我们需要向上层(父过程)**返回的信息就是该结点为根结点的树是否是平衡二叉树以及以该结点为根的树高度**,这样的话,父过程就能继续向上层返回应该收集的信息。
【**方案改进**】
因为使用递归进行二叉树的遍历的时候,每个递归函数会到一个节点 3 次:首先会到一次,然后访问左子树之后会回来一次,最后访问右子树之后会回来一次; 对于二叉树使用递归的时候,首先想办法收集一下左子树上的信息,然后想办法收集一下右子树上的信息,最后将这些信息进行整合皆可以得到该结点所在的整棵树符不符合标准;本题中的标准就是判断该数是否平衡;
```java
/**
* 判断是否为平衡树
*
* @author GJXAIOU
*/
public class IsBalancedTree {
public static class Node {
public int value;
public Node left;
public Node right;
public Node(int value) {
this.value = value;
}
}
public static boolean isBalance(Node head) {
// 这里需要使用数组,因为作为参数传入 getHeight 函数,同时在该函数中修改了值,需要同步修改这里的值返回值才会变化。
boolean[] res = new boolean[1];
res[0] = true;
getHeight(head, 1, res);
return res[0];
}
public static int getHeight(Node head, int level, boolean[] res) {
if (head == null) {
return level;
}
int leftHeight = getHeight(head.left, level + 1, res);
if (!res[0]) {
return level;
}
int rightHeight = getHeight(head.right, level + 1, res);
if (!res[0]) {
return level;
}
// 如果左右高度差大于 1 则返回 false
if (Math.abs(leftHeight - rightHeight) > 1) {
res[0] = false;
}
return Math.max(leftHeight, rightHeight);
}
public static void main(String[] args) {
Node head = new Node(1);
head.left = new Node(2);
head.right = new Node(3);
head.left.left = new Node(4);
head.left.right = new Node(5);
head.right.left = new Node(6);
head.right.right = new Node(7);
System.out.println(isBalance(head));
}
}
```
### 注:递归过程总结
递归很好用,该题中的递归用法也是一种经典用法,可以高度套路:
1. 分析问题的解决需要哪些步骤(这里是遍历每个结点,确认每个结点为根节点的子树是否为平衡二叉树)
2. 确定递归:父问题是否和子问题相同
3. 子过程要收集哪些信息
4. 本次递归如何利用子过程返回的信息得到本过程要返回的信息
5. 处理 `base case`
|
Ruby
|
UTF-8
| 316 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
class Url
attr_accessor :key_request
def initialize(key_request = 'developer+remote')
@key_request = key_request
end
def requested_url
"https://www.indeed.com/jobs?q=#{key_word_filter(@key_request)}&l="
end
private
def key_word_filter(key)
key.downcase!
key.sub(' ', '+')
end
end
|
Markdown
|
UTF-8
| 2,311 | 3.703125 | 4 |
[] |
no_license
|
# Вывести односвязный список
[importance 5]
[Односвязный список](http://ru.wikipedia.org/wiki/Связный_список) -- это структура данных, которая состоит из *элементов*, каждый из которых хранит ссылку на следующий. Последний элемент может не иметь ссылки, либо она равна `null`.
Например, объект ниже задаёт односвязный список, в `next` хранится ссылка на следующий элемент:
```js
var list = {
value: 1,
next: {
value: 2,
next: {
value: 3,
next: {
value: 4,
next: null
}
}
}
};
```
Графическое представление этого списка:
<img src="linked-list.png">
Альтернативный способ создания:
```js
//+ no-beautify
var list = { value: 1 };
list.next = { value: 2 };
list.next.next = { value: 3 };
list.next.next.next = { value: 4 };
```
Такая структура данных интересна тем, что можно очень быстро разбить список на части, объединить списки, удалить или добавить элемент в любое место, включая начало. При использовании массива такие действия требуют обширных перенумерований.
Задачи:
<ol>
<li>Напишите функцию `printList(list)`, которая выводит элементы списка по очереди, при помощи цикла.</li>
<li>Напишите функцию `printList(list)` при помощи рекурсии.</li>
<li>Напишите функцию `printReverseList(list)`, которая выводит элементы списка в обратном порядке, при помощи рекурсии.
Для списка выше она должна выводить `4`,`3`,`2`,`1`</li>
<li>Сделайте вариант `printReverseList(list)`, использующий не рекурсию, а цикл.</li>
</ol>
Как лучше -- с рекурсией или без?
|
Java
|
UTF-8
| 589 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
package com.example.communityhero;
public class Message {
private String text;
private MemberData memberData;
private boolean belongsToCurrentUser;
public Message(String text, MemberData data, boolean belongsToCurrentUser) {
this.text = text;
this.memberData = data;
this.belongsToCurrentUser = belongsToCurrentUser;
}
public String getText() {
return text;
}
public MemberData getMemberData() {
return memberData;
}
public boolean isBelongsToCurrentUser() {
return belongsToCurrentUser;
}
}
|
JavaScript
|
UTF-8
| 4,864 | 3.75 | 4 |
[] |
no_license
|
/*
* TP 1 - IFT1015
* Auteurs:
* Mael Le Petit (matricule),
* Fannie Filion Bienvenue (20104125)
*
* Ce programme permet de modifier une image selon differents paramètres :
* la mettre en noir et blanc, augmenté ou réduire la clarté, appliquer un
* filtre "flou" et détecter les contours
*/
let canvas = document.getElementById('canvas');
//Fonction pour la formule de la luminance
var nuanceGris = function(r, g, b) {
return (0.2126 * r) + (0.7152 * g) + (0.0722 * b);
};
//Fonction qui met l'image en noir et blanc
function noirEtBlanc(imageOriginale) {
for (var y = 0; y < canvas.height; y++) { //Iterer tous les pixels
for (var x = 0; x < canvas.width; x++) {
//Application de la fonction nuanceGris sur chacun des pixels
var valeur = nuanceGris(imageOriginale[y][x].r, imageOriginale[y][x].g ,imageOriginale[y][x].b);
imageOriginale[y][x].r = valeur;
imageOriginale[y][x].g = valeur;
imageOriginale[y][x].b = valeur;
}
}
return imageOriginale;
}
//Fonction qui calcul l'eclat selon la couleur du pixel. Valeur de l'eclat : < 1 = foncé, > 1 = claire
function brightness(couleur, eclat) {
return (Math.pow((couleur/255), eclat) * 255);
}
//Fonction qui augmente ou diminue la clarté de l'image
function correctionClarte(imageOriginale, quantite) {
for (var y = 0; y < canvas.height; y++) { //Iterer tous les pixels
for (var x = 0; x < canvas.width; x++) {
//Application de la fonction brightness sur chacun des pixels
imageOriginale[y][x].r = brightness(imageOriginale[y][x].r, quantite);
imageOriginale[y][x].g = brightness(imageOriginale[y][x].g, quantite);
imageOriginale[y][x].b = brightness(imageOriginale[y][x].b, quantite);
}
}
return imageOriginale;
}
//Fonction qui applique un filtre "flou" a l'image
function flou (imageOriginale, taille) {
let ponderation = (1/Math.pow(taille, 2)); //Valeur de la ponderation selon la taille
var centre = Math.floor(taille/2); //Centre de la matrice
for (var y = 0; y < canvas.height; y++) { //Iterer tous les pixels
for (var x = 0; x < canvas.width; x++) {
var red = ponderation * imageOriginale[y][x].r,
green = ponderation * imageOriginale[y][x].g,
blue = ponderation * imageOriginale[y][x].b;
let indexX = x - centre,
indexY = y - centre,
horizontale = 0, // x of matrix
verticale = 0; // y of matrix
for(var a = indexY; a < (indexY + taille); a++) {
for(var b = indexX; b < (indexX + taille); b++) {
if (b > 0 && b < canvas.width && a > 0 && a < canvas.height) { //Depassement des bornes
red += ponderation * imageOriginale[a][b].r;
green += ponderation * imageOriginale[a][b].g;
blue += ponderation * imageOriginale[a][b].b;
}
horizontale++;
}
verticale++;
}
imageOriginale[y][x].r = red;
imageOriginale[y][x].g = green;
imageOriginale[y][x].b = blue;
}
}
return imageOriginale;
}
//Fonction qui fait ressortir les contours
function detectionContours(imageOriginale) {
//Mettre l'image en noir et blanc afin d'avoir la meme valeur pour les pixels r, g, b
var image = noirEtBlanc(imageOriginale);
//Ponderation verticale et horizontale des pixels de la matrice 3 x 3
let ponderation_verticale = [[-1, -2, -1], [0, 0, 0], [1, 2, 1]],
ponderation_horizontale = [[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]];
for (var y = 0; y < canvas.height; y++) { //Iterer tous les pixels
for (var x = 0; x < canvas.width; x++) {
var variationX = 0, variationY = 0,
bound = 3,
indexX = x - 1,
indexY = y - 1;
var verticale = 0;
for(var a = indexY; a < (indexY + bound); a++) { //Iterer les pixels de la matrice 3 x 3
var horizontale = 0;
for(var b = indexX; b < (indexX + bound); b++) {
if (a >= 0 && a < canvas.height && b >= 0 && b < canvas.width) {
var couleur = image[a][b].r; //Choix du canal rouge
variationX += (ponderation_horizontale[verticale][horizontale] * couleur);
variationY += (ponderation_verticale[verticale][horizontale] * couleur);
}
horizontale++;
}
verticale++;
}
//Intensite des contours
var intensiteContour = Math.floor(Math.max(Math.abs(variationX), Math.abs(variationY)));
if (intensiteContour > 255) {
intensiteContour = 255;
}
image[y][x].r = intensiteContour;
image[y][x].g = intensiteContour;
image[y][x].b = intensiteContour;
}
}
return image;
}
function tests() {
}
|
Markdown
|
UTF-8
| 908 | 3.359375 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
### Envato Tuts+ Course: Optimize Your Website Without AMP
#### Instructor: [Kezz Bracey](https://tutsplus.com/authors/kezz-bracey)
AMP is Google’s collection of plug-and-play code that helps optimize sites to load and run faster. It works, however its use is controversial and there are many good reasons you might consider handling optimization yourself. AMP undoubtedly does a great job in speeding up sites, but you can achieve results just as well, if not better under your own steam if you know how to go about it.
In this course we’ll be taking an existing AMP based site and converting it to use non-AMP equivalents, giving you methods to make your sites run blazing fast, but where the optimization techniques are those you decide on for yourself.
So let’s go ahead and “Optimize Your Website Without AMP“!
**Available on [Envato Tuts+](https://tutsplus.com/courses) from September, 2017**
|
Java
|
UTF-8
| 908 | 3.84375 | 4 |
[] |
no_license
|
package BitProblems;
import java.util.BitSet;
/**
* Class to identify the duplicates in an int[] and in a string
* @author pramothinidk
*
*/
public class BitsetExample {
BitSet bs = new BitSet(10);
BitSet bsChar = new BitSet(52);
public void findDuplicate(int[] a){
for(int i=0; i<a.length ; i++)
if(!bs.get(a[i])){
bs.set(a[i]);
}
else
System.out.println(" the duplicate element is "+a[i]);
}
public void findDuplicate(String a){
for(int i=0; i<a.length() ; i++){
int s = a.charAt(i) - 'A';
if(!bsChar.get(s)){
bsChar.set(s);
}
else
System.out.println(" the duplicate element is "+a.charAt(i));
}
}
public static void main(String args[]){
BitsetExample be = new BitsetExample();
int findduplicates[] = {1,2,3,4,2,3,4,5,1,12};
be.findDuplicate(findduplicates);
String findDuplicate = "AappleAZZPSzz";
be.findDuplicate(findDuplicate);
}
}
|
C++
|
UTF-8
| 2,248 | 2.953125 | 3 |
[] |
no_license
|
/*
Problem : APAC 2016 University Test : Round C : Problem B : gFiles
Link : http://code.google.com/codejam/contest/4284487/dashboard#s=p1
Author : Utsav Chokshi
Date : 01/09/2016
*/
/***********************************************************************
Logic :
Let P = percentage
K = number of files
x = total number of files
Then we need to solve the following equation for each pair of input:
=> Px = 100K
P is actually floor of some value.
So Range of values P can take [P,P+1) (including P , but excluding P+1, as floor(P+1) = P+1)
There will be N such equations.
For each equation,
(100K/P+1) < x <= (100K/P)
So we get two values of x :
cur_minx = (100K/(P+1))+1 (as x will be greater than this value and also x is integer so next value x can take is exactly one bigger)
cur_maxx = (100K/P)
After each equation,
we try to tighten overall range for x.
so minx = max(minx, cur_minx)
maxx = min(maxx, cur_maxx)
After solving all equations,
if minx == maxx
then "answer exists i.e. ans = minx = maxx"
otherwise "answer does not exist"
************************************************************************/
#include<bits/stdc++.h>
#define fr freopen("B-large.in","r",stdin)
#define fo freopen("B-large.out","w",stdout)
#define print(cnt,x) cout<<"Case #"<<cnt++<<": "<<x<<"\n";
using namespace std;
typedef unsigned int ui;
typedef long long ll;
typedef unsigned long long ull;
ull INF = 1e18;
int main(){
//input
ui T = 0, caseNumber = 1;
cin >> T;
ui N = 0; //Number of status updates
ull P = 0; //Percentage
ull K = 0; //Number of files
ull cur_minx = 0;
ull cur_maxx = 0;
ull minx = 0;
ull maxx = 0;
bool isPossible = false;
ll ans = 0;
while(T--){
cin >> N;
isPossible = false;
minx = 0;
maxx = INF;
ans = -1;
while(N--){
cin >> P >> K;
if(!isPossible){
if(P == 0){
cur_minx = 100*K + 1;
cur_maxx = INF;
}
else if(P == 100){
isPossible = true;
minx = maxx = (100*K)/P;
}
else{
cur_minx = ((100*K)/(P+1)) + 1;
cur_maxx = (100*K)/P;
}
minx = max(minx,cur_minx);
maxx = min(maxx,cur_maxx);
}
}
if(minx == maxx){
ans = minx;
}
print(caseNumber,ans);
}
return 0;
}
|
JavaScript
|
UTF-8
| 1,652 | 2.53125 | 3 |
[] |
no_license
|
const Discord = require("discord.js");
module.exports.run = async (client, message, args) => {
const moddingJSON = require("../storage/modding.json");
if (!args[0]) {
message.channel.send(
`Learning to Mod? Check out the Modding Guide and FAQ! \nOur Modding Guide is at https://modding.melodicalbuild.me \nOur in Discord FAQ is found here! <#831103119252520960>`
);
} else {
var needle = args[0].toLowerCase();
var foundEntries = [];
moddingJSON.data.forEach((dataEntry) => {
dataEntry.searchTerms.forEach((haystackElement) => {
var lowercaseHaystack = haystackElement.toLowerCase();
if (lowercaseHaystack == needle || lowercaseHaystack.includes(needle)) {
foundEntries.push(dataEntry);
}
});
});
let embed = new Discord.MessageEmbed()
.setTitle("Search Results:")
.setTimestamp()
.setFooter(
"Friendly Coggo",
client.user.avatarURL({ format: "png", size: 2048 })
);
let count = 0;
if (foundEntries.length > 0) {
embed.setColor("#0cc20f");
foundEntries.forEach((element) => {
if(count != 5) {
embed.addField(`${element.id}:`, moddingJSON.baseURL + element.url);
count++;
}
});
} else {
embed.setColor("#b80000");
embed.addField(
"Search Results:",
"Your Search Term was not found, Try again!"
);
}
message.channel.send(embed);
}
};
exports.help = {
name: "modding",
desc: "Open the Modding FAQ",
aliases: ["mod"],
permLvl: 0,
hidden: true,
category: "volc",
usage: "modding <guide name>",
};
|
Python
|
UTF-8
| 1,174 | 2.8125 | 3 |
[] |
no_license
|
from servicios import *
import json, pprint
# 1 es inicio de sesion
# 2 es nueva orden
# 3 es nueva promocion
def cola(sdata):
data_cruda = json.loads(sdata)
tipo_transaccion = data_cruda['tipo']
data_real = data_cruda['data']
if tipo_transaccion == 1:
# es inicio de sesion
respuesta = 'inicio de sesion'
data_usuario = {}
data_usuario['email'] = data_real['user']
data_usuario['contrasena'] = data_real['password']
try:
usuario = Servicios_de_Autenticacion().iniciar_sesion(data_usuario)
respuesta = {
'message': 'welcome %s, your token is %s'%(usuario.email.user,usuario.token),
'token': usuario.token
}
respuesta = json.dumps(respuesta, ensure_ascii=False).encode('utf8')
except Exception as e:
respuesta = e.message
print e.message
elif tipo_transaccion == 2:
# es nueva orden
respuesta = 'nueva orden'
elif tipo_transaccion == 3:
# es promocion
respuesta = 'promociones'
else:
respuesta = "Error en solicitud"
return respuesta
|
C++
|
UTF-8
| 1,555 | 3.234375 | 3 |
[
"MIT"
] |
permissive
|
#include <stdio.h>
#define MAX 20
typedef enum { FALSE, TRUE } BOOL;
char board[MAX][MAX]; // 알파벳 저장 보드
int check[26]; // 방문한 알파벳 체크 배열
int dx[] = { 0, 0, 1, -1 };
int dy[] = { 1, -1, 0, 0 };
int row, col;
int dfs(int x, int y); // 문자의 개수를 세기 위한 깊이우선탐색(DFS) 하는 재귀함수
int main() {
int i, j;
int tc, ti;
freopen("data.txt", "rt", stdin);
scanf("%d", &tc);
// TODO
for (ti = 1; ti <= tc; ti++) {
scanf("%d %D", &row, &col);
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
scanf(" %c", &board[i][j]);
}
}
for (i = 0; i < 26; i++) {
check[i] = FALSE;
}
check[board[0][0] - 'A'] = TRUE;
printf("TC%d : %d\n", ti, dfs(0,0));
}
return 0;
}
/*--------------------------------------------------------------------------------------
Function Name : dfs() - 문자의 개수를 세기 위한 깊이우선탐색(DFS) 하는 재귀함수
Argument : x, y - 현재위치
Return Valuse : 지나온 문자의 개수
--------------------------------------------------------------------------------------*/
int dfs(int x, int y) {
// TODO
int ans = 0;
int next = 0;
int nx, ny;
for (int k = 0; k < 4; k++) {
nx = x + dx[k];
ny = y + dy[k];
if (nx >= 0 && nx < row && ny >= 0 && ny < col) {
if (check[board[nx][ny] = 'A'] == FALSE) {
check[board[nx][ny] = 'A'] = TRUE;
next = dfs(nx, ny);
if (ans < next) {
ans = next;
}
check[board[nx][ny] = 'A'] = FALSE;
}
}
}
return ans + 1;
}
|
PHP
|
UTF-8
| 176 | 2.8125 | 3 |
[
"MIT"
] |
permissive
|
<?php
//define ('Test','This is a test!');
//echo TEST . PHP_EOL;
//echo Test . PHP_EOL;
$fruit= array("grapes","apple","cherry");
//var_dump($fruit);
echo $fruit[2][3];
|
JavaScript
|
UTF-8
| 668 | 3.5625 | 4 |
[] |
no_license
|
// http://www.codewars.com/kata/5376343a003bf6e034000c56/train/javascript
var checkDistance = function(point1, point2){
return Math.sqrt(Math.pow((point1[0] - point2[0]), 2) + Math.pow((point1[1] - point2[1]), 2));
}
// Calculate a pair of closest points
function closestPair( points ){
var currClose;
for (var i = 0; i < points.length-1; i++){
for (var j = i+1; j < points.length; j++){
if (currClose === undefined){
currClose = [points[i], points[j]];
}
else if (checkDistance(points[i], points[j]) < checkDistance(currClose[0], currClose[1])){
currClose = [points[i], points[j]];
}
}
}
return currClose;
}
|
Java
|
UTF-8
| 917 | 2.1875 | 2 |
[] |
no_license
|
package com.myspringproject.university.controller;
import com.myspringproject.university.domain.model.StudentDto;
import com.myspringproject.university.service.StudentService;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class StudentControllerTest {
@InjectMocks
private StudentController studentController;
@Mock
private StudentService studentService;
@Test
public void void_test(){
StudentDto studentDto=StudentDto.builder().build();
Mockito.when(studentService.getStudentById(1)).thenReturn(studentDto);
StudentDto studentById=studentController.getStudentById(1);
Assertions.assertThat(studentById).isSameAs(studentDto);
}
}
|
PHP
|
UTF-8
| 444 | 2.59375 | 3 |
[] |
no_license
|
<?php
/**
* Created by PhpStorm.
* User: Snxt
* Date: 2018/5/8
* Time: 15:24
*/
include_once "MyDB.php";
$db = new MyDB();
$sql = "select * from pages";
$result = $db->query($sql);
$response = array();
while (($row = $result->fetch_assoc()) !== null) {
$page = array(
"id"=>$row["id"],
"path"=>$row["path"],
"title"=>$row["title"]
);
$response[] = $page;
}
echo json_encode($response);
$db->close();
|
JavaScript
|
UTF-8
| 1,274 | 2.953125 | 3 |
[
"MIT"
] |
permissive
|
// ----------------------------------------------------------------------
// LearnWords 2
//
// File:
// LWcsvString2JSON.js
//
// Purpose:
// Converts a CSV string
// to an array of objects
//
// Date:
// 1st February 2017
//
// ----------------------------------------------------------------------
var Papa = require("papaparse");
var LWcsvString2JSON = function (aCSVString) {
"use strict";
var result = Papa.parse(aCSVString, {
dynamicTyping: true,
encoding: "utf8",
skipEmptyLines: true
});
var arrayOfObjects = [];
var propertyName;
var obj;
if (result.errors.length === 0) {
// result.data is array of arrays
// row with index 0 is header
// we want an array of objects.
for (var j = 1; j < result.data.length; j++) {
obj = {};
for (var k = 0; k < result.data[0].length; k++){
if(k < result.data[j].length){
propertyName = result.data[0][k];
obj[propertyName] = result.data[j][k];
}
}
arrayOfObjects.push(obj);
}
} else {
console.log(result.errors);
}
return arrayOfObjects;
};
module.exports = LWcsvString2JSON;
|
C++
|
UTF-8
| 1,387 | 2.609375 | 3 |
[] |
no_license
|
#pragma once
#include "DynamicObject.h"
class spr_Player;
class Player : public DynamicObject
{
public:
Player();
~Player();
void Init(float x, float y);
void UpdateBegin();
void Update();
void UpdateEnd();
void Draw();
void Kill();
void Destroy();
void Collided(GameObject *other);
float GetGravity() const {return gravity;}
bool GetCollisionWallUp() const {return collisionWallUp;}
bool GetCollisionWallDown() const {return collisionWallDown;}
bool GetDir() const {return dir;}
bool GetVerticalDir() const {return vertical_dir;}
bool GetJump() const {return jump;}
bool GetIdle() const {return idle;}
void SetGravity(float gravity) {Player::gravity = gravity;}
void SetDir(bool dir) {Player::dir = dir;}
void SetVerticalDir(bool vertical_dir) {Player::vertical_dir = vertical_dir;}
void SetJump(bool jump) {Player::jump = jump;}
void SetIdle(bool idle) {Player::idle = idle;}
private:
bool collisionWallUp;
bool collisionWallDown;
bool collidedWithTreadmillLeft;
bool collidedWithTreadmillRight;
bool idle;
bool dir;
bool vertical_dir;
bool jump;
float gravity;
spr_Player *sprite;
static const int exceptionIDsSize = 6;
int exceptionIDs[6];
//Functions to make the Update() function clearer
void Jump();
void Move();
void Shoot();
void InvertGravity();
void SetGravitySpeed();
void SetSpriteData();
};
|
Python
|
UTF-8
| 774 | 3.90625 | 4 |
[] |
no_license
|
'''
Функции
'''
def dictUpdate(a):
a.update([("x",5)])
print("dict in function: ",a)
return
def dictNoUpdate(a):
a = a.copy()
a.update([("y",3)])
print("dict in function: ",a)
return
def returnFunc(a):
def f1(a):
print("returned f1(a): ",a)
return f1
d= {"v":7}
dictUpdate(d)
print("dict out of function: ",d)
dictNoUpdate(d)
print("dict out of function: ",d)
f = returnFunc(d)
print("f: ", f)
f(2)
print("\n")
'''
Дополнение кода программы
'''
def returnMod(x):
def f2(x):
mod15 = x % 15
print("Остаток от деления введённого числа на 15: ", mod15)
return mod15
return f2(x)
mod15 = returnMod(int(input("Введите число: ")))
|
PHP
|
UTF-8
| 476 | 3.46875 | 3 |
[] |
no_license
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Sort an Array</title>
</head>
<body>
<?php
$numbers = array(10, 32, 3, 645, 9, -3, 88);
sort($numbers);
print_r($numbers);
echo '<br />';
rsort($numbers);
print_r($numbers);
?>
</body>
</html>
|
JavaScript
|
UTF-8
| 1,787 | 2.78125 | 3 |
[] |
no_license
|
const service = require("../models/consultasMensajes")
class Producto {
constructor() {
this.productos = [];
}
getId() {
return this.productos.length + 1;
}
async guardar(producto) {
let id = await service.guardar(producto);
return await service.listarIndividual(id[0])
}
async listarTodos() {
let prods = await service.listarTodos();
return prods.length > 0 ? await prods : "No hay productos cargados"
}
async listarIndividual(id) {
let prod = await service.listarIndividual(id)
if(prod[0]){
return await prod[0]
}else{
return `No existe producto con el id ${id}`
}
}
async actualizar(id, param){
const prod = await service.listarIndividual(id)
if (prod[0]) {
return await service.actualizar(id, param);
} else {
return `No existe el producto con el id ${id}`
}
}
async borrar(id) {
const prod = await service.listarIndividual(id)
if(prod[0]){
await service.borrar(id);
return prod
}else{
return `No existe el producto con el id ${id}`;
}
}
}
// const nuevosProductos = new Producto();
/* nuevosProductos.guardar({
id: nuevosProductos.getId(),
title: "Computadora Desktop",
price: 120000,
thumbnail:
"https://www.flaticon.es/icono-gratis/ordenador-de-sobremesa_1792525",
});
nuevosProductos.guardar({
id: nuevosProductos.getId(),
title: "Televisor SmarTV",
price: 90000,
thumbnail: "https://www.flaticon.es/icono-gratis/televisor_4384367",
}); */
// nuevosProductos.listarIndividual(2)
// nuevosProductos.productos.forEach(index => console.log(index))
// nuevosProductos.borrar(1)
// console.log(nuevosProductos.listarTodos())
// export default GenerarProductos;
module.exports = new Producto();
|
C
|
UTF-8
| 485 | 3.140625 | 3 |
[
"Apache-2.0"
] |
permissive
|
#include <stdio.h>
#include <stdlib.h> // atoi
#define A 1103515256
#define B 12345
#define C 65536
#define D 32768
unsigned long int next = 1;
int myrand() {
next = A * next + B;
return (unsigned int)(next / C) % D;
}
void mysrand(unsigned int seed) {
next = seed;
return;
}
int main(int argc, char** args) {
int i, n;
mysrand(atoi(args[1])); // set seed
n = atoi(args[2]);
for (i = 0; i < n; i++) {
printf("%d ", myrand());
}
printf("\n");
return 1;
}
|
Markdown
|
UTF-8
| 6,739 | 2.84375 | 3 |
[] |
no_license
|
# 《TCP/IP详解卷一:协议》学习笔记一
### 一、分层
1、网络协议通常分不同层次进行开发,每一层分别负责不同的通信功能。
2、TCP/IP通常被认为是一个四层协议系统:

1)、链路层,有时候也被称作数据链路层或网络接口层,通常包括操作系统中的设备驱动程序和计算机中对应的网络接口卡。它们一起处理与电缆(或其他任何传输媒介)的物理接口细节。
2)、网络层,有时也称作互联网层,处理分组在网络中的活动。在TCP/IP协议族中,网络层协议包括IP协议(网际协议),ICMP协议(internet互联网控制报文协议),以及IGMP协议(internet组管理协议)。
3)、运输层主要为两台主机上的应用程序提供端到端的通信。在TCP/IP协议族中,有两个互不相同的传输协议:TCP(传输控制协议)和UDP(用户数据报协议)。
4)、应用层负责处理特定的应用程序细节。
3、在TCP/IP协议族中,网络层IP提供的是一个不可靠的服务,它只是尽可能快地把分组从源节点送到目的节点,不提供任何可靠性的保证。另一方面,TCP在不可靠的IP层上提供一个可靠的运输层。
### 二、TCP/IP的分层
1、TCP/IP协议族中不同层次的协议

2、TCP使用不可靠的IP服务,但是它提供一种可靠的运输层服务。
3、UDP为应用程序接收和发送数据报。但是EDP是不可靠的,它不保证数据报能安全无误的到达目的地。
4、IP是网际层的主要协议,同时被TCP和UDP使用。
5、ICMP是IP的附属协议。IP层用它来与其他主机或路由器交换错误报文和其他重要的信息。
6、IGMP是Internet组管理协议。它用来把一个UDP数据报多播到多个主机。
7、ARP(地址解析协议)和RARP(逆地址解析协议)是某些网络接口使用的特殊协议,用来转换IP层和网络接口层使用的地址。
### 三、互联网的地址
1、互联网上的每个接口必须有一个唯一的Internet地址(也称作IP地址)。IP地址长32bit。Internet地址并不采用平面形式的地址空间。IP地址具有一定的接口,五类不同的互联网地址格式如下:

2、32位IP地址“点分十进制表示法”

3、有三类IP地址
1)、单播地址(目标为单个主机)
2)、广播地址(目的端为给定网络上的左右主机)
3)、多播地址(目的端为同一组类的所有主机)
### 四、域名系统
1、域名系统是一个分布的数据库,由它来提供IP地址和主机名之间的映射信息。
### 五、封装
1、数据进入协议栈的封装过程:

1)、帧头和帧尾所标注的数字是典型以太网首部的长度。
2)、以太网数据帧的物理特性是其长度必须在46~1500字节之间。
3)、图中IP和网络接口层传送的数据单元应该是分组。分组既可以是一个IP数据报,也可以是IP数据报的一个片。
4)、UDP数据和TCP数据基本一致。唯一不同的是UDP传送给IP的信息单元称作UDP数据报,而UDP首部的长度为8位。
5)、由于TCP、UDP、ICMP、IGMP都要向IP传送数据,因此IP必须在生成的IP首部加入某种标识,以表明数据属于那一层。IP在首部存入一个长度为8位的数值,称作协议域。1表示IGMP协议,2表示ICMP协议,6表示TCP协议,17表示UDP协议。
6)、TCP、UDP、网络接口也要在首部加入标识符。
2、当应用程序用TCP传送数据时,数据被送入协议栈中,然后逐个通过每一层直到被当作一串比特流送入网络。其中每一层对收到的数据都要添加一些首部信息(有时还要添加尾部信息)。
3、TCP传给IP的数据单元称作TCP报文段或简为TCP段,IP传给网络接口层的数据单元称作IP数据报。通过以太网传输的比特流称作数据帧。
### 六、分用Demultiplexing
1、当目的主机收到一个以太网数据帧时,数据就开始从协议栈中由低往上升,同时去掉各层协议加上的报文首部。每层协议盒都要去检查报文首部中的协议标识,以确定接受数据的上层协议。这个过程称作分用。
2、以太网数据帧的分用过程

### 七、客户-服务器模型
1、服务器提供的服务分两种类型:
1)、重复型
2)、并发型
2、重复型服务器通过以下步骤进行交互:
I、等待一个客户请求的到来
II、处理客户请求
III、发送响应给发送请求的客户
IV、返回第I步
3、并发型服务器采用以下步骤:
I、等待一个客户请求的到来
II、启动一个新的服务器来处理这个请求
III、返回第I步
4、一般来说,TCP服务器是并发的,而UDP服务器是重复的,但也存在一些例外。
### 八、端口号
1、服务器一般都是通过知名端口号来识别的。客户使用临时设定的端口号。(ftp21,telnet23)
2、客户端口号又称作临时端口号(即存在时间很短暂)
3、大多数TCP/IP实现给临时端口分配1024~5000之间的端口号。大于5000的端口号是为其他服务器预留的。
3、Uinx系统有保留端口号的概念。只有超级用户特权的进程才允许给它自己分配一个保留端口号
|
Shell
|
UTF-8
| 483 | 3.015625 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/bin/env bats
readonly ARTIFACT_DIR="openponk"
@test "master build has been deployed" {
mkdir -p $ARTIFACT_DIR
echo "image" > $ARTIFACT_DIR/openponk.image
echo "changes" > $ARTIFACT_DIR/openponk.changes
export CI_JOB_ID=0
export CI_COMMIT_REF_NAME=master
export ARTIFACT_DIR
run ../deploy.sh
echo $output
[ "${lines[0]}" = "deploy test master-0 ok" ]
[ $status -eq 0 ]
}
teardown() {
rm -rf openponk
rm -rf openponk-master-0
rm -f openponk-image-master-0.zip
}
|
PHP
|
UTF-8
| 3,941 | 2.8125 | 3 |
[
"MIT"
] |
permissive
|
<?php
/**
* Author: Amir Hossein Jahani | iAmir.net
* Last modified: 1/8/21, 9:58 AM
* Copyright (c) 2021. Powered by iamir.net
*/
function _getDistanceGeo($c1, $c2, $opt_radius = 6371008.8)
{
$radius = $opt_radius;
$lat1 = deg2rad($c1[1]);
$lat2 = deg2rad($c2[1]);
$deltaLatBy2 = ($lat2 - $lat1) / 2;
$deltaLonBy2 = deg2rad($c2[0] - $c1[0]) / 2;
$a = sin($deltaLatBy2) * sin($deltaLatBy2) +
sin($deltaLonBy2) * sin($deltaLonBy2) *
cos($lat1) * cos($lat2);
return 2 * $radius * atan2(sqrt($a), sqrt(1 - $a));
}
function _getBearingGeo($lonlat1, $lonlat2, $precision = 2)
{
$lat1 = deg2rad((float)$lonlat1[1]);
$lat2 = deg2rad((float)$lonlat2[1]);
$lon1 = deg2rad((float)$lonlat1[0]);
$lon2 = deg2rad((float)$lonlat2[0]);
$dLon = $lon2 - $lon1;
$y = sin($dLon) * cos($lat2);
$x = cos($lat1) * sin($lat2) - sin($lat1) * cos($lat2) * cos($dLon);
$result = (rad2deg(atan2($y, $x)) + 360) / 360;
return round(($result - (int)$result) * 360, $precision);
}
function _uv2ddff($u, $v)
{
$wind = ['speed' => 0, 'dir' => 0];
if($v==0) {
if ($u == 0) return $wind;
if ($u > 0) return ['speed' => $u, 'dir' => 270];
else return ['speed' => $u, 'dir' => 90];
}if($v<0)
$wind['dir']= atan($u/$v)*180/pi();
else
$wind['dir']= atan($u/$v)*180/pi()+180;
if($wind['dir'] <0)
$wind['dir']= $wind['dir']+360;
$wind['speed'] = sqrt($u*$u+$v*$v);
return $wind;
}
function _find_second_point($start, $dist, $bearing, $precision = 4)
{
$radius = 6371008.8 / 1000;
$lon = deg2rad($start[0]);
$lat = deg2rad($start[1]);
$brng = deg2rad($bearing);
/*$lat2 = $lat + cos($dist / $radius) * cos($brng);
$lon2 = $lon + sin($dist / $radius) * sin($brng);*/
$lat2 = asin(sin($lat) * cos($dist / $radius) + cos($lat) * sin($dist / $radius) * cos($brng));
$lon2 = $lon + atan2(sin($brng) * sin($dist / $radius) * cos($lat), cos($dist / $radius) - sin($lat) * sin($lat));
return [
round(rad2deg($lon2), $precision),
round(rad2deg($lat2), $precision),
];
}
function _toNM($number)
{
return round($number * 0.000539956803, 2);
}
function _NMtoM($number)
{
return round($number * 1852, 2);
}
function even(array $numbers) {
return array_filter($numbers, function ($number) {
return $number % 2 == 0;
});
}
function odd(array $numbers) {
return array_filter($numbers, function ($number) {
return !($number % 2 == 0);
});
}
function _pa_to_alt($num, $h = false) {
if (!$h) $num = $num / 100;
return (pow(10,log10($num / 1013.25) / 5.2558797) - 1)/ (-6.8755856*pow(10,-6));
}
function _alt_to_pa($num, $h = false) {
$calc = 1013.25 * pow((1 - 6.87535 * pow(10,-6) * $num), 5.2561);
return $h ? $calc : $calc * 100;
}
function WGS84Lat($latitude, $nordsud = 1)
{
$lat_degrees = (float) _get_value($latitude, '0', 0);
$lat_minutes = (float) _get_value($latitude, '1', 0);
$lat_minutes = $lat_minutes ? $lat_minutes / 60 : $lat_minutes;
$lat_seconds = (float) _get_value($latitude, '2', 0);
$lat_seconds = $lat_seconds ? $lat_seconds / 3600 : $lat_seconds;
$lat = $nordsud * ($lat_degrees + $lat_minutes + $lat_seconds);
return round(round($lat*10000000)/10000000, 6);
}
function WGS84Lng($longitude, $estouest = 1)
{
$lng_degrees = (float) _get_value($longitude, '0', 0);
$lng_minutes = (float) _get_value($longitude, '1', 0);
$lng_minutes = $lng_minutes ? $lng_minutes / 60 : $lng_minutes;
$lng_seconds = (float) _get_value($longitude, '2', 0);
$lng_seconds = $lng_seconds ? $lng_seconds / 3600 : $lng_seconds;
$lng = $estouest * ($lng_degrees + $lng_minutes + $lng_seconds);
return round($lng, 6);
}
function WGS84LL($longitude, $latitude, $nordsud = 1, $estouest = 1)
{
return [WGS84Lat($latitude, $nordsud), WGS84Lng($longitude, $estouest)];
}
|
Markdown
|
UTF-8
| 222 | 2.921875 | 3 |
[] |
no_license
|
### MISC-C (To-be-organized)
- Cannot change variable's type unless cast it to a new variable whose type is desired.
``` c
int *yp, *xp;
*(char *)yp = *((char *)xp + 1);
//*yp is still a integer pointer, so is *xp
```
|
Shell
|
UTF-8
| 1,430 | 3.625 | 4 |
[] |
no_license
|
#!/bin/bash
DIR="$(dirname "$(readlink -f "$0")")"
source $DIR/../conf/cluster-admin-env.sh
if [ "$#" != "1" ];then
echo "Usage: $0 <username>"
exit 1
fi
echo "Password:"
read -s password
echo "Repeat the password:"
read -s password2
if [ "$password" != "$password2" ];then
echo "Passwords don't match."
exit 1
fi
pssh -h $DIR/../conf/all-hosts "sudo useradd -s /bin/bash $1 && echo '$1:$password'|sudo chpasswd && sudo mkdir -p /home/$1/.ssh && sudo chown -R $1:$1 /home/$1"
echo "Creating HDFS home directory for the user..."
sudo su -l hdfs -c "hdfs dfs -mkdir /user/$1"
sudo su -l hdfs -c "hdfs dfs -chown $1:$1 /user/$1"
echo "Configuring passwordless SSH access to the cluster nodes..."
sudo su -l $1 -c 'ssh-keygen -t rsa -P "" -f ~/.ssh/id_rsa' &>/dev/null
sudo cat /home/$1/.ssh/id_rsa.pub|pssh -I -h $DIR/../conf/all-hosts "sudo tee /home/$1/.ssh/authorized_keys"
pssh -h $DIR/../conf/all-hosts "sudo chown $1:$1 /home/$1/.ssh/authorized_keys" &>/dev/null
echo "Creating MongoDB user..."
mongo -u $ADMIN_USER -p $ADMIN_PASS --eval 'db.createUser({user: "'$1'", pwd: "'$password'", roles: [ { role: "readWrite", db: "test" } ]})' $MONGO_ENDPOINT/auth
echo "Creating Cassandra User..."
cqlsh -u $ADMIN_USER -p $ADMIN_PASS -e "CREATE USER $1 WITH PASSWORD '$password'" $CASSANDRA_ENDPOINT
echo "Creating Neo4J User..."
ssh $NEO4J_HOST "sudo neo4j-adduser ""$1"":""$password"" && sudo service neo4j restart"
|
Java
|
UTF-8
| 859 | 2.046875 | 2 |
[] |
no_license
|
package com.bazi.ttmk.web;
import com.bazi.ttmk.model.Sudija;
import com.bazi.ttmk.service.SudiiService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(path = "/sudii")
@CrossOrigin(origins = "http://localhost:3000")
public class SudiiController {
private final SudiiService sudiiService;
public SudiiController(SudiiService sudiiService) {
this.sudiiService = sudiiService;
}
@GetMapping
public List<Sudija> findAll() {
return this.sudiiService.getAllSudii();
}
@PostMapping
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Sudija createSudija(Integer idLice,
String titula) {
return this.sudiiService.createSudija(idLice, titula);
}
}
|
Java
|
UTF-8
| 995 | 1.609375 | 2 |
[] |
no_license
|
package com.tencent.beacon.upload;
import android.content.Context;
import com.tencent.beacon.a.f;
public final class c
extends a
{
public c(Context paramContext, int paramInt1, int paramInt2)
{
super(paramContext, 0, 100);
}
public final com.tencent.beacon.c.a.b a()
{
Object localObject = f.m();
byte[] arrayOfByte = "".getBytes();
try
{
localObject = com.tencent.beacon.b.a.a(c(), (f)localObject, arrayOfByte, -1, -1);
if (localObject != null) {
return (com.tencent.beacon.c.a.b)localObject;
}
return null;
}
catch (Throwable localThrowable)
{
localThrowable.printStackTrace();
com.tencent.beacon.e.b.d("encode2RequestPackage failed", new Object[0]);
}
return null;
}
public final void b(boolean paramBoolean) {}
}
/* Location: E:\apk\dazhihui2\classes-dex2jar.jar!\com\tencent\beacon\upload\c.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/
|
C++
|
WINDOWS-1251
| 4,796 | 2.96875 | 3 |
[] |
no_license
|
#include "prototype.h"
void sort(int,int);///
void swap(int);/// swap file
char directory[] = "ClientFile\\";///
struct _finddata_t* m_data = new _finddata_t[256];
/*
1.
2.
3.
4.
*/
int SortFile(int a)
{
setlocale(LC_ALL, "Russian");
struct _finddata_t c_file;
intptr_t hFile;
int size = 0;
//
if ((hFile = _findfirst("ClientFile\\*", &c_file)) == -1L)
printf("No files in current directory!\n");
else
{
do {
char buffer[30];
if (strcmp(c_file.name, ".") != 0 && strcmp(c_file.name, "..") != 0)//
{
ctime_s(buffer, _countof(buffer), &c_file.time_write);
// printf(" %-30s%.20s %20d\n", c_file.name, buffer, c_file.size);
///
m_data[size++] = c_file;
}
} while (_findnext(hFile, &c_file) == 0);
sort(a,size); //
/* , a.txt (1 KByte), b.txt (3 KByte), c.txt (2 KByte),
, 볺
1_a.txt, 2_c.txt, 3_b.txt.*/
char oldfilename[512]; //
char newfilename[512]; //
for (int i = 0; i < size; i++)
{
sprintf(oldfilename, "%s%s", &directory, m_data[i].name);
sprintf(newfilename, "%s%i%s%s", &directory, i, "_", m_data[i].name);
if (rename(oldfilename, newfilename) != 0) printf("EROR ,%d\n",i);
}
_findclose(hFile);
//system("pause");
}
return 0;
}
void sort(int a, int size)
{
bool pr; ///
do
{
pr = false;
switch (a)
{
case 1:
for (int i = 0; i < size; i++) ///
if (m_data[i].attrib < m_data[i + 1].attrib) { swap(i); pr = true; }
break;
case 2:
for (int i = 0; i < size; i++) ///
if (m_data[i].name < m_data[i + 1].name) { swap(i); pr = true; }
break;
case 3:
for (int i = 0; i < size; i++) ///
if (m_data[i].size < m_data[i + 1].size) { swap(i); pr = true; }
break;
case 4:
for (int i = 0; i < size; i++) ///
if (m_data[i].time_create < m_data[i + 1].time_create) { swap(i); pr = true; }
break;
}
} while (pr);
printf("\n * \n");
}
void swap(int i) /// Swap
{
_finddata_t temp;
temp = m_data[i];
m_data[i] = m_data[i + 1];
m_data[i + 1] = temp;
}
/* */
std::string outListFile()
{
struct _finddata_t c_file;
intptr_t hFile;
if ((hFile = _findfirst("ClientFile\\*", &c_file)) == -1L)
printf("No files in current directory!\n");
else
{
std::string s;
s += "Listing of files\n\n";
s += " FILE DATE SIZE\n";
s += " ---- ---- ----\n";
do {
char buffer[30];
char text[512];
if (strcmp(c_file.name, ".") != 0 && strcmp(c_file.name, "..") != 0)
{
ctime_s(buffer, _countof(buffer), &c_file.time_write);
sprintf(text, " %-30s%.20s %20d\n", c_file.name, buffer, c_file.size);
s += text;
}
} while (_findnext(hFile, &c_file) == 0);
return s;
}
}
|
Markdown
|
UTF-8
| 9,661 | 3.015625 | 3 |
[] |
no_license
|
# 面试题目
##属性相关
- 让页面里的字体变清晰,变细用CSS怎么做?
- -webkit-font-smoothing: antialiased;
- font-style属性可以让它赋值为“oblique” oblique是什么意思?
- 让没有斜体属性的文字倾斜
- line-height比例单位和百分比单位的计算方法
- 父元素的行高为150%时,会根据父元素的字体大小先计算出行高值然后再让子元素继承。所以当line-height:150%时,子元素的行高等于父元素字体大小 * 150% :
- 父元素行高为1.5时,会根据子元素的字体大小动态计算出行高值让子元素继承。所以,当line-height:1.5时,子元素行高等于子元素字体大小 * 1.5 = 45px:
- 元素竖向的百分比设定是相对于容器的高度吗?
- margin、padding是相对于宽度,height是相对于高度
- CSS里的visibility属性有个collapse属性值是干嘛用的?在不同浏览器下以后什么区别?
- 当在表格元素中使用时,此值可删除一行或一列,但是它不会影响表格的布局。如果此值被用在其他的元素上,会呈现为 "hidden"。
- 怎么让Chrome支持小于12px 的文字?
- 可通过加入 CSS 属性 -webkit-text-size-adjust: none; 解决.
- overflow: scroll时不能平滑滚动的问题怎么处理?
- - 用纯CSS创建一个三角形的原理是什么?
把上、左、右三条边隐藏掉(颜色设为 `transparent`)
#demo {
width: 0;
height: 0;
border-width: 20px;
border-style: solid;
border-color: transparent transparent red transparent;
}
## 方法
- 一个ul里有若干个li,想要每个li都有一个border-bottom,最后一个li不想要boder-bottom要怎么做
- (ul:last-child{border-bottom:none;}
- 或者给最后一个li加一个class选择器设置border:none;
- 用js或jquery来实现
- 很长一段话要进行截取,超过之后是三个点怎么做?
- 不考虑兼容的话CSS3有 text-overflow:ellipsis
- 或者overflow:hidden 在边框前侧加入一个三个点的span
- 或者用伪元素`:after{content:"..."}`
- 如何平铺一张背景图?
- repeat
- css方法:设置一张图片 {position: absolute; top: 0; left: 0; bottom: 0; right: 0; z-index: -1;}
- 有一个高度自适应的div,里面有两个div,一个高度100px,希望另一个填满剩下的高度。
- absolute 定位
- 外层box-sizing: border-box; 同时设置padding: 100px 0 0;内层100像素高的元素向上移动100像素,或使用absolute定位防止占据空间;另一个元素直接height: 100%;
- height: calc(100%-100px)
- flex
## css hack
- 条件注释
<!--[if IE]>用于 IE <![endif]-->
<!--[if IE 6]>用于 IE6 <![endif]-->
<!--[if IE 7]>用于 IE7 <![endif]-->
<!--[if IE 8]>用于 IE8 <![endif]-->
<!--[if IE 9]>用于 IE9 <![endif]-->
<!--[if gt IE 6]> 用于 IE6 以上版本<![endif]-->
<!--[if lte IE 7]> 用于 IE7或更低版本 <![endif]-->
<!--[if gte IE 8]>用于 IE8 或更高版本 <![endif]-->
<!--[if lt IE 9]>用于 IE9 以下版本<![endif]-->
<!--[if !IE]> -->用于非 IE <!-- <![endif]-->
- 为什么要初始化CSS样式。
因为浏览器的兼容问题,不同浏览器对有些标签的默认值是不同的,如果没对CSS初始化往往会出现浏览器之间的页面显示差异。
当然,初始化样式会对SEO有一定的影响,但鱼和熊掌不可兼得,但力求影响最小的情况下初始化。
最简单的初始化方法就是:* {padding: 0; margin: 0;}
- haslayout是什么,怎么触发
“Layout”是一个 IE/Win 的私有概念,它决定了一个元素如何显示以及约束其包含的内容、如何与其他元素交互和建立联系、如何响应和传递应用程序事件/用户事件等,这有点类似于一个窗体的概念。
触发:大部分的 IE 显示错误,都可以通过激发元素的 haslayout 属性来修正。可以通过设置 css 尺寸属性(width/height)等来激发元素的 haslayout,使其“拥有布局”。如下所示,通过设置以下 css 属性即可。
* display: inline-block
* height: (任何值除了auto)
* float: (left 或 right)
* position: absolute
* width: (任何值除了auto)
* writing-mode: tb-rl
* zoom: (除 normal 外任意值)
Internet Explorer 7 还有一些额外的属性(不完全列表):
* min-height: (任意值)
* max-height: (除 none 外任意值)
* min-width: (任意值)
* max-width: (除 none 外任意值)
* overflow-x: (除 visible 外任意值)
* overflow-y: (除 visible 外任意值)
* position: fixed
可以使用JavaScript函数hasLayout查看一个元素是否拥有布局,函数返回true即该元素拥有layout,否则返回false。hasLayout是一个只读属性。
## 动画
- 视差滚动效果,如何给每页做不同的动画?(回到顶部,向下滑动要再次出现,和只出现一次分别怎么做?)
- 如果需要手动写动画,你认为最小时间间隔是多久,为什么?
多数显示器默认频率是60Hz,即1秒刷新60次,所以理论上最小间隔为1/60*1000ms = 16.7ms
## 移动端
- 用过媒体查询,针对移动端的布局吗?
- @media screen and (min-width:600px) {...}
- 全屏滚动的原理是什么?用到了CSS的那些属性?
- 什么是响应式设计?响应式设计的基本原理是什么?如何兼容低版本的IE?
- 页面的设计与开发应当根据用户行为以及设备环境(系统平台、屏幕尺寸、屏幕定向等)进行相应的响应和调整。
## 其他
- 什么是CSS 预处理器 / 后处理器?
- 预处理器例如:LESS、Sass、Stylus,用来预编译Sass或less,增强了css代码的复用性,
还有层级、mixin、变量、循环、函数等,具有很方便的UI组件模块化开发能力,极大的提高工作效率。
- 后处理器例如:PostCSS,通常被视为在完成的样式表中根据CSS规范处理CSS,让其更有效;目前最常做的是给CSS属性添加浏览器私有前缀,实现跨浏览器兼容性的问题。
- CSS中link 和@import的区别是?
- (1) link属于HTML标签,而@import是CSS提供的;
- (2) 页面被加载的时,link会同时被加载,而@import引用的CSS会**等到页面被加载完再加载**;
- (3) import只在IE5以上才能识别,而link是HTML标签,无兼容问题;
- (4) link方式的样式的权重高于@import的权重.
- 在网页中的应该使用奇数还是偶数的字体?为什么呢?
- 偶数。
- 一、UI设计师的原因:多数设计师用的设计软件(如:ps)大多数都是偶数,所以前端工程师一般都是用偶数字体
- 二、浏览器的原因:ie6会把定义为13px的字渲染成14px;偶数宽的汉字,比如12px宽的汉字,去掉1像素的间距,填充了像素的实际宽是11px,这样汉字的中竖线左右是平分的,以“中”这个字为例,在12像素时,竖线在中间,左右各5像素,显得均衡。像谷歌一些比较流行的浏览器一般会有个默认的最小字体,而且对奇数字体渲染的不太好看
- 三、实际应用:偶数字号相对更容易和 web 设计的其他部分构成比例关系。比如:当我用了 14 px 的正文字号,我可能会在一些地方用
- 抽离样式模块怎么写,说出思路,有无实践经验?
- 按照CSS的性质和用途,将CSS文件分成“公共型样式”、“特殊型样式”、“皮肤型样式”,并以此顺序引用(按需求决定是否添加版本号)。
- 公共型样式:包括了以下几个部分:“标签的重置和设置默认值”、“统一调用背景图和清除浮动或其他需统一处理的长样式”、“网站通用布局”、“通用模块和其扩展”、“元件和其扩展”、“功能类样式”、“皮肤类样式”。
- 特殊型样式:当某个栏目或页面的样式与网站整体差异较大或者维护率较高时,可以独立引用一个样式:“特殊的布局、模块和元件及扩展”、“特殊的功能、颜色和背景”,也可以是某个大型控件或模块的独立样式。
- 皮肤型样式:如果产品需要换肤功能,那么我们需要将颜色、背景等抽离出来放在这里。
- CSS Sprites:利用CSS的“background-image”,“background- repeat”,“background-position”的组合进行背景定位, 访问页面时避免图片载入缓慢的现象。
优点
- CSS Sprites能很好地减少网页的http请求,从而大大的提高页面的性能,这是CSS Sprites最大的优点,也是其被广泛传播和应用的主要原因;
- CSS Sprites能减少图片的字节;
- CSS Sprites解决了网页设计师在图片命名上的困扰,只需对一张集合的图片命名,不需要对每一个小图片进行命名,从而提高了网页制作效率。
- CSS Sprites只需要修改一张或少张图片的颜色或样式来改变整个网页的风格。
缺点
- 图片合并麻烦:图片合并时,需要把多张图片有序的合理的合并成一张图片,并留好足够的空间防止版块出现不必要的背景。
- 图片适应性差:在高分辨的屏幕下自适应页面,若图片不够宽会出现背景断裂。
- 图片定位繁琐:开发时需要通过工具测量计算每个背景单元的精确位置。
- 可维护性差:页面背景需要少许改动,可能要修改部分或整张已合并的图片,进而要改动css。在避免改动图片的前提下,又只能(最好)往下追加图片,但这样增加了图片字节。
|
Java
|
UTF-8
| 545 | 1.773438 | 2 |
[] |
no_license
|
package org.irri.iric.chado.so;
// Generated 05 26, 14 1:32:25 PM by Hibernate Tools 3.4.0.CR1
/**
* FiveHydroxymethylcytidine generated by hbm2java
*/
public class FiveHydroxymethylcytidine implements java.io.Serializable {
private FiveHydroxymethylcytidineId id;
public FiveHydroxymethylcytidine() {
}
public FiveHydroxymethylcytidine(FiveHydroxymethylcytidineId id) {
this.id = id;
}
public FiveHydroxymethylcytidineId getId() {
return this.id;
}
public void setId(FiveHydroxymethylcytidineId id) {
this.id = id;
}
}
|
PHP
|
UTF-8
| 3,022 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace console\controllers;
use yii\console\controllers\MigrateController;
/**
* @inheritdoc
*/
class MigrateAllController extends MigrateController
{
/**
* @var array path for find migrations as alias => level
*/
protected static $paths = [
'@app' => 0,
'@vendor' => 2,
];
/**
* @inheritdoc
*/
protected function getNewMigrations()
{
$applied = $this->getApplied();
$migrations = [];
foreach (static::$paths as $alias => $level) {
$this->handleDir($alias, $migrations, $applied, $level);
}
sort($migrations);
return $migrations;
}
protected function handleDir($alias, &$migrations, $applied, $level = 0, $full = false, $new = true)
{
$dir = \Yii::getAlias($alias);
if ($level == 0) {
$alias .= '/migrations';
$dir .= '/migrations';
}
if (!is_dir($dir)) {
return;
}
$handle = opendir($dir);
while (($file = readdir($handle)) !== false) {
if ($file === '.' || $file === '..') {
continue;
}
$path = $dir . '/' . $file;
$fileAlias = $alias . '/' . $file;
if ($level > 0 && is_dir($path)) {
$this->handleDir($fileAlias, $migrations, $applied, $level - 1, $full, $new);
} else {
if (preg_match('/^(m(\d{6}_\d{6})_.*?)\.php$/', $file, $matches) && is_file($path)) {
if (!isset($applied[$matches[1]]) || !$new) {
if ($full) {
$migrations[] = $path;
} else {
$migrations[] = $matches[1];
}
}
}
}
}
closedir($handle);
}
/**
* @inheritdoc
*/
protected function createMigration($class)
{
$file = $this->findFile($class);
if ($file === null) {
$this->stderr('Migration file not found.');
\Yii::$app->end(self::EXIT_CODE_ERROR);
}
if (preg_match('/(m(\d{6}_\d{6})_.*?)\.php$/i', $class, $matches)) {
$class = $matches[1];
}
require_once($file);
return new $class(['db' => $this->db]);
}
protected function findFile($class)
{
$migrations = [];
$applied = $this->getApplied();
foreach (static::$paths as $alias => $level) {
$this->handleDir($alias, $migrations, $applied, $level, true, false);
}
foreach ($migrations as $m) {
if (strpos($m, $class) !== false) {
return $m;
}
}
return null;
}
protected function getApplied()
{
$applied = [];
foreach ($this->getMigrationHistory(null) as $version => $time) {
$applied[$version] = true;
}
return $applied;
}
}
|
Java
|
UTF-8
| 5,846 | 2.46875 | 2 |
[] |
no_license
|
package com.example.maks.filesstatisticapp;
import android.app.Service;
import android.content.Intent;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import java.io.File;
import java.util.ArrayList;
import java.util.TreeMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class DataProcessing extends Service {
public static final String LOG_TAG = "data";
ExecutorService es;
File root;
static int target;
int count = 0;
long totalFilesSize = 0;
public void onCreate() {
super.onCreate();
es = Executors.newFixedThreadPool(2);
}
public int onStartCommand(Intent intent, int flags, int startId) {
int testingTarget = intent.getIntExtra(Constants.TEST_TARGET, 1);
switch (testingTarget){
case Constants.EXTERNAL_TESTING:
root = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath());
target = Constants.EXTERNAL_TESTING;
break;
case Constants.INTERNAL_TESTING:
root = new File(Environment.getRootDirectory().getAbsolutePath());
target = Constants.INTERNAL_TESTING;
break;
default:
}
es.execute(new MyRun(startId, root, target));
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
class MyRun implements Runnable {
int startId;
File root;
int target;
File[] files = new File[10];
TreeMap<String, Integer> extensions = new TreeMap<>();
long averageFileSize = 0;
public MyRun( int startId, File root, int target) {
this.startId = startId;
this.root = root;
this.target = target;
}
public void run() {
scanFiles(root);
stop();
}
void stop() {
stopSelf(startId);
sendBroadcast(new Intent(Constants.BROADCAST_ACTION)
.putExtra(Constants.TEST_TARGET, Constants.TESTING_FINISH));
Log.d(LOG_TAG, "MyRun#" + startId + " end, stopSelfResult("
+ startId + ") = " + stopSelfResult(startId));
Log.d(LOG_TAG, "MyRun#" + startId + " end, stopSelf(" + startId + ")");
}
protected void sendExtensionsAndSize(File[] files, TreeMap<String, Integer> extensions, long averageFileSize){
SortingInformation.sortByValues(extensions);
ArrayList<String> extensionsValues = new ArrayList<>();
ArrayList<String> extensionsNames = new ArrayList<>();
ArrayList<String> filesNames = new ArrayList<>();
ArrayList<String> filesSize = new ArrayList<>();
for(Object o : extensions.values()) extensionsValues.add(o.toString());
for(Object o : extensions.keySet()) extensionsNames.add(o.toString());
for (File f : files) {
filesNames.add(f.getName());
filesSize.add(f.length() / 1024 + "Kb");
}
Intent intent = new Intent(Constants.BROADCAST_ACTION)
.putExtra(Constants.AVERAGE_FILE_SIZE, averageFileSize)
.putStringArrayListExtra(Constants.EXTENSIONS_NAMES, extensionsNames)
.putStringArrayListExtra(Constants.EXTENSIONS_FREQUENCY, extensionsValues)
.putStringArrayListExtra(Constants.FILE_NAMES, filesNames)
.putStringArrayListExtra(Constants.FILE_SIZE, filesSize)
.putExtra(Constants.TEST_TARGET,target);
sendBroadcast(intent);
}
public File[] scanFiles(File dir) {
File currentFile[] = dir.listFiles();
if (currentFile != null && currentFile.length > 0) {
for (int i = 0; i < currentFile.length; i++) {
if (currentFile[i].isDirectory()) {
scanFiles(currentFile[i]);
} else {
//Adding to Extensions map
if(currentFile[i].getName().contains(".")) {
int extensionPoint = currentFile[i].getName().lastIndexOf('.');
String extension = currentFile[i].getName().substring(extensionPoint);
if (extensions.containsKey(extension)) {
extensions.put(extension, extensions.get(extension) + 1);
} else {
extensions.put(extension, 1);
}
}
//Total file size
totalFilesSize += currentFile[i].length();
++count;
averageFileSize = (totalFilesSize / count);
//Sorting file list
if(count <= 10) {
files[count - 1] = currentFile[i];
if(count == 10) {
SortingInformation.insertionSort(files);
sendExtensionsAndSize(files, extensions, averageFileSize);
}
}else if (count > 10 &&
currentFile[i].length() > files[0].length()) {
files[0] = currentFile[i];
SortingInformation.insertionSort(files);
sendExtensionsAndSize(files, extensions, averageFileSize);
}
}
}
}
return null;
}
}
}
|
Markdown
|
UTF-8
| 1,521 | 2.578125 | 3 |
[] |
no_license
|

[View 👀](https://github.com/claflamme/toa-guide-printouts/blob/master/guides.pdf) or
[Download ⬇️](https://github.com/claflamme/toa-guide-printouts/raw/master/guides.pdf)
# Tomb of Annihilation Guide Printouts
I thought it was kind of shitty that the wilderness guides in ToA didn't have their own stat blocks. Their description tells you which monster stat block they use, but then also adds a bunch of modifications and overrides for some of them. The end result is that you have to flip back and forth between the monster stat block and the guide description, which is super annoying.
So, here's a PDF with stat blocks for each recruitable wilderness guide (and their sidekicks) with all modifications applied, as well as their picture and the relevant parts of their character description.
## Made for Dungeon Masters
The printouts contain descriptions of the motivations and true identities of some of the guides, which is handy for when the DM needs to roleplay the characters. However, Some of the information could spoil a few storylines so make sure you don't give them out to your players.
If you like your players to control NPC party members, you can still let them without handing over the printouts. Let your characters control the NPCs in combat and exploration by giving them simple commands which you, the DM, can then follow through on. For example: _"attack that"_, _"unlock this"_, _"lead us back to Port Nyanzaru"_.
|
Markdown
|
UTF-8
| 1,003 | 2.734375 | 3 |
[
"Apache-2.0"
] |
permissive
|
# Narwhal!
[](https://pkg.go.dev/github.com/yourbase/narwhal?tab=doc)
Narwhal is a simplistic wrapper around the Docker Go API.
## Examples
For full examples and usage see [pkg.go.dev][examples].
```go
// Create a client
client := narwhal.DockerClient()
// Create a container
containerID, err := narwhal.CreateContainer(ctx, client, os.Stdout, narwhal.ContainerDefinition{
Image: "ubuntu:latest",
})
// Start a container
err := narwhal.StartContainer(ctx, client, containerID)
// Copy a file into a container
f, err := ioutil.TempFile("./", "tmpfile")
err = narwhal.UploadFile(ctx, client, containerID, "/tmp/tmpfile", f.Name())
// Execute a command in a container
err := narwhal.ExecShell(ctx, client, containerID, "echo 'Hello world!'", &narwhal.ExecShellOptions{})
```
[docs]: https://pkg.go.dev/github.com/yourbase/narwhal?tab=doc
[examples]: https://pkg.go.dev/github.com/yourbase/narwhal?tab=doc#pkg-examples
|
C#
|
UTF-8
| 1,189 | 2.59375 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BussinessLayer;
namespace PresentationLayer.WebForms
{
public partial class SignUpForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnRegister_Click(object sender, EventArgs e)
{
if(txtPassword.Text.ToString().Equals(txtConfirmPassword.Text.ToString())==false)
{
divMessageArea.Visible = true;
lblMessage.Text = "Va rugam sa reconfirmati parola.";
txtConfirmPassword.Text = string.Empty;
}
else if(txtCNP.Text.Length!=13 || txtCNP.Text.Any(x => char.IsLetter(x)))
{
divMessageArea.Visible = true;
lblMessage.Text = "CNP-ul nu este valid.";
}
else
{
divMessageArea.Visible = true;
lblMessage.Text = "Inregistrarea s-a efectuat cu succes.";
}
System.Diagnostics.Debugger.Break();
}
}
}
|
C++
|
UTF-8
| 869 | 2.96875 | 3 |
[] |
no_license
|
#ifndef MATRIX_H
#define MATRIX_H
//macros to define header
class Matrix{
// class constructor, destructor and prototypes
private:
int **mat;
long unsigned row;
long unsigned col;
public:
Matrix();
Matrix(long unsigned x, long unsigned y);
~Matrix();
//prints
void printMatrix();
//allocates
void allMat();
//makes random Matrix
void fillmat();
//makes a diagonal matrix
void makeDiag();
//makes a triangle Matrix
void makeTri();
//makes an identity Matrix
void makeId();
long unsigned getRow() const {return row;}
long unsigned getCol() const {return col;}
//assigns entire matrices
Matrix& operator=(const Matrix& mx);
//multiplies matrices
Matrix operator*(const Matrix& mx);
//Scalar multiplication bonus
Matrix operator*(int scalar);
//adds matrices
Matrix operator+(const Matrix& mx);
//subtracts matrices
Matrix operator-(const Matrix& mx);
};
#endif
|
Python
|
UTF-8
| 1,294 | 2.8125 | 3 |
[] |
no_license
|
import csv
import json
def deduck(v):
if type(v) is not str:
return v
if v.lower()=='y':
return True
if v.lower()=='n':
return False
# range specific
if v.lower()=='touch':
return 5
if v.lower()=='self':
return 0
if v.lower().startswith('self ('):
v=v[6:-1].strip()
if v.lower().startswith('touch ('):
v=v[7:-1].strip()
if v.lower()=='unlimited':
return 2^31
if v.lower()=='sight': # sight range outdoors is ~2 miles
return 2000
if v.lower().endswith('mile'):
return 1056
if v.lower().endswith(' miles'):
return int(v[:-6])*1056
if 'ft' in v.lower():
v=v[:v.lower().index('ft')].strip() # also cuts of radius range
# generic again
v=v.replace(',','') # 1,000
if v.isdecimal():
return int(v)
return v
def convert(csv, key, fields):
data={}
for row in reader:
row={k:e for k,e in row.items() if k and e}
data[row[key].strip().lower()]={k.lower():deduck(row[k]) for k in fields if k in row}
return data
if __name__ == "__main__":
with open('.\\spells.csv', newline='') as csvfile:
reader = csv.DictReader(csvfile)
data = convert(reader, 'Name', ['Level','Attack','Save','Range'])
with open('.\\spells.json',mode='w',newline='') as jsonFile:
jsonFile.write(json.dumps(data,indent='\t'))
|
Markdown
|
UTF-8
| 20,988 | 3.140625 | 3 |
[] |
no_license
|
# Software Architecture & Technology Rationale
### Technologies Used:
### Frameworks, Language and Libraries to be used in this project:
- Python for implementing functionality throughout the project.
- SpeechRecognition for implementing STT engines into the system.
- YAML for importing, reading and configuring the user profile.
- eSpeak to implement the TTS engine.
- Pip to manage python packages
- PyAudio to record and output audio across multiple OS.
- Google STT to convert audio input into strings
### Why we chose STT, TTS and Logic Engine?
The engines used provide the groundwork for the VA to work. Therefore, different people are able to communicate with it at different times.
The core components of the VA are are: STT, Logic, Responses and TTS.
- Google STT converts the users speech into a string via audio processing and sends this as a variable to Logic Handling.
- Logic takes the string and and checks whether the string matches against the arguments of functions. The string is then passed to the Responses file.
- Responses.py is the encyclopedia of set responses for the questions asked by the user. It stores these ansers inside functions, which are then passed to the TTS engine.
- TTS outputs the response via the TTS engine, eSpeak (Linux) or Say (for OS X).

This is what the Spring MVC framework file structure looks like:

The model, repository, service and validator is our main project body which handles the data information and software implementation, and we work with the css and js in the webapp below. The view folder works for webpages displayed through the project.

### External APIs:
The usage of external API’s is to expand the components in our system in order to implement key core features. The features include:
- **OpenStreetMap**
In order to implement a functional map system we need an API that was easy to work with, so we decided to use Open Street Map. A great advantage of using Open Street Map data is that it is open-source and hence it is free to use. It is also easy to place into an application which makes for a great alternative to Google Maps. We will need it to create routes to and from Lecturer and Learner meetups and to ensure that the Lecturer or Learner can interact with the map in real time (by incorporating javascript) which would allow organising a meetup to be a quick, simple and satisfying experience. It is also flexible in terms of scaling, so a lecturer or learner can easily use it on different environments such as their mobile device as well as a desktop.
- **JavaMail**
JavaMail is imported by the (org.springframework.mail.javamail) library which is a core API which will add lots of functionality to our system. It allows the system to automatically send emails out to users from the system in that users are sent emails after certain events such as creating an account for the first time, changing an password and recovering an account. JavaMail will also would enable emailing between learners, lecturers and administrators which is a core aspect to the overall functionality of service. It is also supported by the Spring Framework supports which makes it easier to integrate into our system.

- **Java Message Service (JMS)**
Java Message Service (JMS) API is allows us to create, send, receive and read messages using reliable coupled communication. JMS is a Java API which defines a common set of interfaces that allow Java programs to communicate with other messaging implementations. It allows communication that is asynchronous and reliable. Jave Messaging Service allows the users of the website to message each other. As JMS is asynchronous, the user is not required to request messages in order to receive them.

- **Java Persistence (JPA)**
Java Persistence API allows us to develop our webapp with an object/relational mapping facility for managing relational data in our application. Java Persistence API allows us to perform object to relational Mapping (ORM) in our database. It is an open source implementation but requires a database to persist to. The Java Persistence API allows us to map our queries to the database and converts the results to our model. It allows us to handle any incoming requests.

- **Leaflet.js**
Leaflet.js API allows us to create a map on a page and manipulate it. It is an open-source JavaScript library for mobile-friendly interactive map. The API uses JavaScript to allow the map to be implemented into the system. By using Leaflet.js API we are able to implement OpenStreetMaps into our system. We are also able teo view the maps on a mobile device as well as on major desktops and mobile platforms. Leaflet.js allows us to use any map provider and roll our own tiles.
### Security Strategy:
- **Spring Security**
We will be using the Spring security framework to authenticate and authorize different users. The security framework enables users to login to an application by verifying their credentials and additionally provides the ability to hide a certain portion of a webpage if the user's account type does not have the appropriate privileges. For example, a user with a learner account type is unable to view the assessment scores or grades of another learner as this privilege is given to a lecturer. Furthermore, only administrators have the ability to delete or suspend both learner and lecture's accounts, whereas a user with a lecturer account has the privilege to upload/delete lectures from the system. This system ensures that a user only has the authorisation to modify their data, and not the data of other users. Moreover, by using the Spring security framework, we will be able to identify incoming requests from HTTP sources from users and envoy these requests to a controller. The controller can give a response to the user after handling the request and in turn, this allows for more efficiency and added security.
The Spring security framework provides us with the flexibility of selecting exactly how we wish to secure the system - we are not presented with a fixed set of options and are free to make our own methods if we choose to. The requirements have given us insight as to which features would need to be secure, e.g. when lecturers organise meet ups with learners, only the learners and lecturers enrolled on that particular course are able to view the meetup locations. Also implementing a login system guarantees that only legitimate account holders can access the live chat, which ensures that non-users are unable to read private messages between users. The system will be monitored by the administrators, who will make sure that any inappropriate behaviour is dealt with appropriately, and will additionally overlook all activities, including verifying that the location for a Meet-Up is suitable.
- **Cross-Site Scripting (XSS)**
We have taken special measures to prevent Cross-site scripting (XSS) from taking place in our system. Cross-site scripting is when an attacker executes a script which allows them to gain access to certain parts of a website. Most of the times, XSS is used to steal cookies and steal session tokens of a valid user to perform session hijacking. We have decided to add filters into our system to prevent cross site scripting. Although this doesn't fully protect our website, it would take a very skilled hijacker to hijack our website. The hijacker would have to load the malicious script on the server and wait for it to be executed. This would be injected onto the webpage, then onto the database, leaving the webpage in a vulnerable state. It is important for the system to have filters in place which prevent XSS attacks.

- **SQL Injections**
We have also taken consideration for SQL injection attacks so that users are not able to inject SQL queries into our website. If an attacker successfully proceeds with an SQL Injection then they would have access to our database, allowing them to access, modify and delete data. We are protected from SQL injections as nothing is passed through our URLs, meaning an attacker cannot use a SQL Injection to gain access to our website. We have also added SQL parameters in our SQL statements so that there is no other way for attackers to bypass our website using SQL injections

- **Form Validation**
We have added form validation into our forms to ensure that information is valid and is being entered. Some ways we have done this is by making the user input their data twice (confirming email address and password). This ensure the users are actual users and are not hackers using an automated script. We also plan to add a validator which checks if the user is a human. We did the form validation using spring and also created classes in our validator folder.

- **Firewalls**
For the network we will be having a firewall to control traffic flow of incoming requests from the outside world and blocking any unauthorised requests. The firewall will filter incoming packets, considering their source, destination and the data it contains and discard any that do not match its internal rule set. Also the firewall will log traffic coming in so we can see what type of traffic is passing the system, helpful for identifying external attacks to the system. Furthermore it can alert us to internal threats as it monitors internal packets leaving the system so if malware enters the system it sends a signal to the author that it is in the system, this adds further security and protection to the system. Users can have external firewalls on their hard drive. Some external firewalls are loaded on antivirus software and work with browsers to prevent malicious web pages. These external firewalls help limit the inflow of fata from outside sources but also control data coming in.

### Two-Factor Authentication
For authentication we decided to use Google Authenticator because it is from a well-known and trusted source and it adds extra secure communication between client and server. Google Authenticator allows for authentication for mobile users as it uses a two-step verification process. Time-based One-time Password Algorithm (TOTP) and HMAC-based One-time Password Algorithm (HOTP). The TOTP algorithm uses a one-time password with a time stamp of the current time for a one use password. The authenticator provides a six to eight digit one-time password that users must provide along with their username and password. This is great as if there was to be a hacker trying to break into a user’s account, knowing the username and password isn't enough as they would need knowledge of the shared secret key or access to the authenticator from the device. So this is a great way for adding extra security to the system.

### Performance Strategy:
- To manage out performance we will use the developer tools in Google Chrome to monitor the details of each webpage to make sure the application is working well. We will also use it to check the time spent between the time the HTTP request was made and the time the view is displayed on the browser. If we see that it is taking too long for the page to display then we will perform and create some testing scripts that will focus on absolute performance, testing how long it takes to render a certain page and on a performance scale how does the system slow as more users are using the system at once.
- Moreover we will be incorporating database normalization in our mySQL scripts which reduce data redundancy and improve data integrity which will ensure that our system is performing in the most efficient manner it can.
### Architectural Design Decisions
- **How did JavaMail support our project? What design decisions did we change during or after implementation?**
Javamail allowed us to send emails out to the users after a certain reqeust was sent on the system. We had to create a default email address for the emails to be sent from. Some instances where we have used the JavaMail API is when users register to the system. When users register, an email is sent to the user wecloming them to our website. We were originally going to use JavaMail to send the users password to them if they forgot it, however we realised that because of the security of our website, the password send would be encrypted. We then decided to have a 'forgot username' page as an aditional feature, where an email is sent to the user containing their username. This was done via JavaMail. We have also used the JavaMail API for learners and lecturers to email each other. It is one of the core aspects of our functionality.
- **How did Spring Security support our project? Why did we not use other means of security?**
By implementing Spring Security into our project, we were able to keep the website secure. It has protected us from many attacks such as XSS attacks, file upload and form validation. Spring Security has allowed us to add authentication into our system. Users are now required to enter their password and email address twice, just to ensure they are real users. Non registered users cannot access the system. We decided not to add other security measures as Spring Securirt was protecting our website enough. Nevertheless, we did add a few classes which protected the website even more. Our main form of security was done via Spring Security.
- **Why did we use Gradle JettyRunWar instead of Gradle BootRun?**
We decided to use Gradle JettyRunWar instead of BootRun as JettyRunWar would deploys a WAR (web application archive) to an embedded Jetty web container. This meant that we would not have to have anything stored locally, saving space for our developers but also making it a lot simpler to deploy. Although it meant that we had to redeploy the server everytime we made a change to the JSP pages, it was more effecient for us to use JettyRunWar. After the project is completed, we plan on converting to the newest version of Jetty as Gradle are removing the current method in future releases.
- **Why did we decide to do the CSS manually rather than using Bootstrap?**
When deploying multiple webpages using bootstrap, we realised that there were things which overlapped each other. Bootstrap didnt allow us to have as much control over the design of our web pages. Our objects + design was fixed. We did not like this as some things on our web page looked odd. We decided to create our CSS manually and upload to RAWGIT, which allowed us to use the CSS on our page without it being inside the directory. It allowed anyone to edit it from anywhere. It also allowed us to have full control over the design of our webapp.
- **Why did we decide to use emails as our way of sending meetup requests?**
We decided to use emails as our way of sending meetup requests because of the simplicity of doing it. We originally wanterd to have meetups done via a notification on the website but after careful discussion and planning we decided to implement the meeting requests via email. We ensured that we were still meeting the requirements and that the users could still send meetups to each other. Another influence in our decision to do this was because we had already used the email messages for other features. This includesthe report a problem page, where the problem would be sent to the BrainWave email address where the admin can view the problem. It was also used on the signup page where the user would receive an email upon signup. We saw this to be a vital part of our system as it ensures the user it signed up to the website with a valid email address.
- **Why did we decide to use Google Authenticator for our two factor authentication?**
We decided to use Google Authenticator over any other authenticator for many reasons. The Google authenticator app works independently to any other app so nobody can access the code through a third party device. Another reason it is so secure is because it creates a new code every 60 seconds. This ensures that the code is more protected as the authentication code is not stored for very long. The Google authenticator app does not require any internet or mobile phone connection. Because of the TOTP algorithm inbuilt into the authenticator, we are able to see the code without the need of internet. Google Authenticator also allows us to have multiple accounts in one place. If a user is both a lecturer and learner then they would require two authentication codes and Google Authenticator allows this. One of the most important factors of why we chose Google Authenticator was because it was free and had the ability to be used with Non-Google websites. You are just required to scan the QR code and then your code would be given to you.
- **Why did we decide to use the Leaflet.js API to implement OpenStreetMaps?**
At first we were struggling to find an API to implement OpenStreetMaps into our system. We thought about using the OpenLayers API but it was conflicting with other features of our system. We had a group meeting and decided to use the Leaflet.js API as it was a JavaScript library which had many plugins, allowing us to have free control over the maps we implemented into our system. We ensured that we did our research before implementing Leaflet.js into our system as we didnt want to cause any conflict errors in our system.
- **Why did we decide to send reports to admin via email?**
We implemented a report a problem page for users to send reports. When the user submits the report, the report is sent to the BrainWave platform email address - brainwaveplatform@gmail.com. Only the administrators have access to this email address and will be able to view the reports. The reason we decided to have reports sent by email is because it was simpler as only the administrators have access to the account. If the administrator account was hacked then the hacker would be able to see all of the reports, as well as other information. As the security of our website improves, we plan to implement the reports directly into the amdministrator account.
- **Why did we decide to give the administrator accounts a seperate login page rather than having them on the standard login/register page?**
We decided to give the administrator a seperate login page due to security reasons. The administrator login page is hidden. Initially there is only one administrator account which is owned by one of the developers. The administrator can then give the hidden login page to another administrator, who can then register an account. We did this as we didn't want users registering as an administrator and taking advantage of the administrator features, such as deleting other user accounts. In future releases we plan to give administrators rights to promote other administrators rather than having a register page.
### Architectural Decisions (200 words)
Throughout my project, I have made many architectural design decisions which were set to contribute to the project. Some of these decisions were to use different STT and TTS engines to support the natural language input/output. By implementing these engines (such as Google STT) it has been easier to reach the project requirements. Another decision I had was to choose where system responses came from. Originally I intended to use a database, however this would not be efficient as the VA would only be reading data, so I decided to store all responses in a seperate Python file. On the other hand, many design decisions have had to change due to tasks not being able to be completed. This resulted in me having to find a different way to gather feedback and requirements for my system, resulting in a change to the project schedule and aim.
|
C++
|
UTF-8
| 200 | 2.640625 | 3 |
[] |
no_license
|
#include <iostream>
#include <set>
using namespace std;
int main(){
set<int> si;
for(int i = 0; i < 100000; ++i){
si.insert(i);
}
cout << si.size() << endl;
return 0;
}
|
Java
|
UTF-8
| 1,047 | 3.4375 | 3 |
[] |
no_license
|
// 11 ms
class Solution {
public int minDeletionSize(String[] A) {
int count = 0;
for (int i = 0; i < A[0].length(); i++) {
for (int j = 1; j < A.length; j++) {
if (A[j-1].charAt(i) > A[j].charAt(i)) {
count++;
break;
}
}
}
return count;
}
}
/* Reference : 1 ms
class Solution {
public int minDeletionSize(String[] A) {
if(A == null) return 0;
int ret = 0;
int numCols = A[0].toCharArray().length;
for(int i = 0; i < numCols; i++){
if(!colIsOrdered(A, i)) ret++;
}
return ret;
}
public static boolean colIsOrdered(String[] A, int col){
char prev = A[0].charAt(col);
for(int i = 0; i < A.length; i++){
if(A[i].charAt(col) < prev){
return false;
}
prev = A[i].charAt(col);
}
return true;
}
}
*/
|
TypeScript
|
UTF-8
| 319 | 2.546875 | 3 |
[] |
no_license
|
import { Pipe, PipeTransform } from "@angular/core";
@Pipe({
name: "market"
})
export class MarketPipe implements PipeTransform {
public transform(value: number, x: string): string {
let z = status[value]
return z;
}
}
const status = {
2: 'Binance',
3: 'Huobi',
4: 'Bitfinex'
}
|
Java
|
UTF-8
| 6,496 | 1.898438 | 2 |
[] |
no_license
|
package com.microsoft.azure.iot.hackathon.accompany.common;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import com.google.gson.Gson;
import com.mapbox.geojson.Geometry;
import com.mapbox.geojson.GeometryCollection;
import com.mapbox.geojson.LineString;
import com.mapbox.geojson.Point;
import com.microsoft.azure.iot.hackathon.accompany.common.constants.AccompanyIntents;
import com.microsoft.azure.iot.hackathon.accompany.common.models.LineGeometry;
import java.util.ArrayList;
import java.util.List;
public class AccompanyReceiveMessageService extends FirebaseMessagingService {
private static final String TAG = "AccompanyReceiveMessage";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom() + " Message: " + remoteMessage.getData());
String notificationType = remoteMessage.getData().get("Type");
switch(notificationType) {
case "5" :
DisplayLineGeometry(remoteMessage);
break;
default:
DisplayAckNotification(remoteMessage.getData().get("SourceDeviceId"));
}
}
private void DisplayLineGeometry(RemoteMessage remoteMessage) {
Log.d(TAG, "Showing directions on map.");
String resourceUrl = remoteMessage.getData().get("ResourceUrl");
RequestQueue requestQueue = Volley.newRequestQueue(this);
String registrationService = BuildConfig.REGISTRATIONSERVICE_HOSTNAME;
AccompanyReceiveMessageService service = this;
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, registrationService + resourceUrl, null,
response -> {
Log.d(TAG, "Retrieved line geometry response. Response: " + response.toString());
LineGeometry lineGeometry = new Gson().fromJson(response.toString(), LineGeometry.class);
try {
List<Point> pointList = new ArrayList<Point>();
pointList.add(Point.fromLngLat(-122.1335814,47.6366275));
pointList.add(Point.fromLngLat(-122.33, 47.64));
Point destPoint = Point.fromLngLat(-122.1335814,47.6366275);
//AccompanyMapData.lineGeom = LineString.fromLngLats(pointList);
AccompanyMapData.destination = destPoint;
Log.d(TAG, "GEOMETRY: " + lineGeometry + " SIZE: " + lineGeometry.coordinates.size());
List<Geometry> pointCollection = new ArrayList<Geometry>();
for(int x = 0; x < lineGeometry.coordinates.size(); x++) {
for(int y = 0; y < lineGeometry.coordinates.get(x).size(); y++) {
try {
Log.d(TAG, "Point X: " + lineGeometry.coordinates.get(x).get(y) + " Point Y: " + lineGeometry.coordinates.get(x).get(y+1));
pointCollection.add(Point.fromLngLat(lineGeometry.coordinates.get(x).get(y), lineGeometry.coordinates.get(x).get(y+1)));
} catch(Exception e) {
}
}
}
pointCollection.add(LineString.fromLngLats(pointList));
AccompanyMapData.destinations = GeometryCollection.fromGeometries(pointCollection);
//AccompanyMapData.lineGeom = LineString.fromJson(response.toString());
LocalBroadcastManager.getInstance(service).sendBroadcast(new Intent(AccompanyMapData.UPDATED));
} catch (Exception ex) {
Log.e(TAG, ex.getMessage());
}
}, error -> Log.e(TAG, "Error retrieving resource geometry to display pedestrian path on map control. VolleyError: " + error));
requestQueue.add(request);
}
private void DisplayAckNotification(String sourceDeviceId) {
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel("default", "default", NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("Channel Description");
// TODO: Depending on type of notification - display something different.
Intent answerAckIntent = new Intent(this, AcknowledgeBroadcastReceiver.class);
answerAckIntent.setAction(AccompanyIntents.ACK_INTENT);
answerAckIntent.putExtra("NotificationId", 01);
answerAckIntent.putExtra("SourceDeviceId", sourceDeviceId);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, answerAckIntent, PendingIntent.FLAG_ONE_SHOT);
Intent denyAckIntent = new Intent(this, AcknowledgeBroadcastReceiver.class);
denyAckIntent.setAction(AccompanyIntents.DENY_INTENT);
denyAckIntent.putExtra("NotificationId", 01);
PendingIntent pendingCloseIntent = PendingIntent.getBroadcast(this, 1, denyAckIntent, PendingIntent.FLAG_ONE_SHOT);
manager.createNotificationChannel(channel);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "default")
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Request for help")
.setContentText("Acknowledge call for help.")
.addAction(R.drawable.mapcontrol_point_circle_blue, "Yes, I can help", pendingIntent)
.addAction(R.drawable.mapbox_info_icon_default, "Not right now", pendingCloseIntent)
.setOngoing(true)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
manager.notify(01, builder.build());
}
@Override
public void onNewToken(String token) {
Log.d(TAG,"Refreshed token: " + token);
}
}
|
Shell
|
UTF-8
| 2,077 | 3.59375 | 4 |
[
"MIT"
] |
permissive
|
#!/bin/sh
set -e
FRAMEWORKS_PATH="${BUILD_DIR}/Frameworks"
[[ "${TARGET_NAME}" =~ (iOS|watchOS) ]] && FRAMEWORK_NAME="PubNub (${BASH_REMATCH[1]})"
PRODUCTS_PATH="${SRCROOT}/Products"
# Clean up from previous builds
if [[ -d "${FRAMEWORKS_PATH}" ]]; then
rm -R "${FRAMEWORKS_PATH}"
fi
if [[ -d "${PRODUCTS_PATH}" ]]; then
rm -R "${PRODUCTS_PATH}"
fi
PLATFORMS=($SUPPORTED_PLATFORMS)
# Compile framework for all required platforms.
for sdk in "${PLATFORMS[@]}"
do
echo "Building ${FRAMEWORK_NAME} for ${sdk}..."
xcrun --no-cache xcodebuild -project "${PROJECT_FILE_PATH}" -target "${FRAMEWORK_NAME}" -configuration "${CONFIGURATION}" -sdk "${sdk}" BUILD_DIR="${BUILD_DIR}" OBJROOT="${OBJROOT}" BUILD_ROOT="${BUILD_ROOT}" SYMROOT="${SYMROOT}" ONLY_ACTIVE_ARCH=NO $ACTION > /dev/null
echo "Built ${FRAMEWORK_NAME} for ${sdk}"
done
# Building universal binary
echo "Building universal framework..."
echo "Artifacts stored in: ${BUILD_DIR}"
BUILT_FRAMEWORKS=("CocoaLumberjack" "PubNub")
for sdk in "${PLATFORMS[@]}"
do
if [[ $sdk =~ (simulator) ]]; then
SIMULATOR_ARTIFACTS_PATH="${BUILD_DIR}/${CONFIGURATION}-${sdk}"
else
OS_ARTIFACTS_PATH="${BUILD_DIR}/${CONFIGURATION}-${sdk}"
fi
done
## Prepare folders
mkdir -p "${FRAMEWORKS_PATH}"
mkdir -p "${PRODUCTS_PATH}"
# Copy ARM binaries and build "fat" binary for each built framework.
for frameworkName in "${BUILT_FRAMEWORKS[@]}"
do
FRAMEWORK_BUNDLE_NAME="${frameworkName}.framework"
FRAMEWORK_ARM_BUILD_PATH="${OS_ARTIFACTS_PATH}/${FRAMEWORK_BUNDLE_NAME}"
FRAMEWORK_SIM_BUILD_PATH="${SIMULATOR_ARTIFACTS_PATH}/${FRAMEWORK_BUNDLE_NAME}"
FRAMEWORK_DESTINATION_PATH="${FRAMEWORKS_PATH}/${FRAMEWORK_BUNDLE_NAME}"
cp -r "${FRAMEWORK_ARM_BUILD_PATH}" "${FRAMEWORK_DESTINATION_PATH}"
xcrun lipo -create "${FRAMEWORK_DESTINATION_PATH}/${frameworkName}" "${FRAMEWORK_SIM_BUILD_PATH}/${frameworkName}" -output "${FRAMEWORK_DESTINATION_PATH}/${frameworkName}"
cp -r "${FRAMEWORKS_PATH}/${FRAMEWORK_BUNDLE_NAME}" "${PRODUCTS_PATH}/${FRAMEWORK_BUNDLE_NAME}"
done
|
Python
|
UTF-8
| 1,150 | 3.734375 | 4 |
[] |
no_license
|
with open('input.txt') as f:
players = f.read().split('\n\n')
p1 = [int(i) for i in players[0].split()[2:]]
p2 = [int(i) for i in players[1].split()[2:]]
def round():
global p1
global p2
#print("Player 1's deck:", p1)
#print("Player 2's deck:", p2)
m1 = p1.pop(0)
m2 = p2.pop(0)
#print('Player 1 plays:', m1)
#print('Player 2 plays:', m2)
if m1 > m2:
#print('Player 1 wins the round!')
p1.append(m1)
p1.append(m2)
else:
#print('Player 2 wins the round!')
p2.append(m2)
p2.append(m1)
# There is no intersection of p1 and p2.
def play():
global p1
global p2
games = 0
while len(p1) > 0 and len(p2) > 0:
round()
games += 1
score = 0
if len(p1) == 0:
winner = p2
else:
winner = p1
#print('== Post-game results ==')
#print("Player 1's deck:", p1)
#print("Player 2's deck:", p2)
for i in range(len(winner)):
#print('Winning players score +=', winner[i], '*', len(winner) - i)
score += winner[i] * (len(winner) - i)
return score
print('Part 1:', play())
|
C++
|
UTF-8
| 1,611 | 4.25 | 4 |
[] |
no_license
|
//Alternative solution for the fourth problem of Project Euler
//Instead of vectors I use strings
//It is slower but it's a new way to do it, for funsies
#include "stdafx.h"
#include <iostream>
#include <sstream> //for converting ints to strings
#include <algorithm> //for reversing strings
using namespace std;
bool CheckPalindrome(int number); //function to check if a number is a palindrome
int main(){
int number = 0; //create and initiate number
for (int i = 100; i < 1000; i++) { //starts at 100 and goes to 999
for (int j = 100; j < 1000; j++) { //starts at 100 and goes to 999
if (CheckPalindrome(i * j) && (i * j) > number) { //checks to see if i * j is a palindrome and larger than the last result
number = i * j; //sets number to i * j
break; //ends this for loop
} //end if
} //end nested for
} //end for
cout << number << endl; //prints out number
system("PAUSE"); //pauses the console
return 0;
}
bool CheckPalindrome(int number) {
string fwd_number; //string for number
string rev_number; //string for reversed number
ostringstream converter; //converter for int to string
converter << number; //inputs number into the converter
fwd_number = converter.str(); //does some magic and makes the int into a string
rev_number = converter.str(); //does some magic and makes the int into a string
if (fwd_number == string(rev_number.rbegin(), rev_number.rend())) { //checks to see if the number is equal to it's reverse
return true; //returns true
} //end if
else { //runs if the number is not a palindrome
return false; //returns false
} //end else
}
|
Java
|
UTF-8
| 235 | 2.09375 | 2 |
[] |
no_license
|
package annotations;
import java.lang.annotation.*;
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface SmartPhone
{
String os() default "Android";
String version() default "1.0.0";
}
|
Swift
|
UTF-8
| 6,704 | 2.90625 | 3 |
[
"Apache-2.0"
] |
permissive
|
import Component
import ComposableArchitecture
import Model
public enum MediaState: Equatable {
case needToInitialize
case initialized(MediaListState)
public init() {
self = .needToInitialize
}
}
public struct MediaListState: Equatable {
enum Next: Equatable {
case searchText(String)
case more(for: MediaType)
}
var blogs: [FeedContent]
var videos: [FeedContent]
var podcasts: [FeedContent]
var next: Next?
}
public enum MediaType {
case blog
case video
case podcast
}
public enum MediaAction: Equatable {
case loadItems
case itemsLoaded([FeedContent])
case mediaList(MediaListAction)
}
public enum MediaListAction: Equatable {
case searchTextDidChange(to: String?)
case willDismissSearchController
case showMore(for: MediaType)
case moreDismissed
}
public struct MediaEnvironment {
public init() {}
}
let mediaListReducer = Reducer<MediaListState, MediaListAction, Void> { state, action, _ in
switch action {
case let .searchTextDidChange(to: searchText):
switch state.next {
case nil,
.searchText:
state.next = searchText.map { .searchText($0) }
default:
break
}
return .none
case .willDismissSearchController:
if case .searchText = state.next {
state.next = nil
}
return .none
case let .showMore(mediaType):
if state.next == nil {
state.next = .more(for: mediaType)
}
return .none
case .moreDismissed:
if case .more = state.next {
state.next = nil
}
return .none
}
}
public let mediaReducer = Reducer<MediaState, MediaAction, MediaEnvironment>.combine(
mediaListReducer.pullback(
state: /MediaState.initialized,
action: /MediaAction.mediaList,
environment: { _ in () }
),
.init { state, action, _ in
switch action {
case .loadItems:
// TODO: Load items from the repository
return Effect(value: .mockItemsLoads)
.delay(for: 1, scheduler: DispatchQueue.main)
.eraseToEffect()
case let .itemsLoaded(contents):
var blogs: [FeedContent] = .init()
var videos: [FeedContent] = .init()
var podcasts: [FeedContent] = .init()
for content in contents {
switch content.item.wrappedValue {
case is Blog:
blogs.append(content)
case is Video:
videos.append(content)
case is Podcast:
podcasts.append(content)
default:
assertionFailure("Unexpected FeedItem: (\(content.item.wrappedValue)")
break
}
}
if var listState = (/MediaState.initialized).extract(from: state) {
listState.blogs = blogs
listState.videos = videos
listState.podcasts = podcasts
state = .initialized(listState)
} else {
state = .initialized(.init(blogs: blogs, videos: videos, podcasts: podcasts, next: nil))
}
return .none
case .mediaList:
return .none
}
}
)
private extension MediaAction {
static let mockItemsLoads: Self = .itemsLoaded(.mockBlogs + .mockVideos + .mockPodcasts)
}
extension MediaListState {
static let mock: Self = .init(blogs: .mockBlogs, videos: .mockVideos, podcasts: .mockPodcasts, next: nil)
}
extension Array where Element == FeedContent {
static let mockBlogs: Self = [
Blog(
id: "0",
image: .init(largeURLString: "", smallURLString: "", standardURLString: ""),
link: "",
media: .medium,
publishedAt: Date(timeIntervalSince1970: 0),
summary: .init(enTitle: "", jaTitle: ""),
title: .init(enTitle: "", jaTitle: "DroidKaigi 2020でのCodelabsについて"),
author: .init(link: "", name: ""),
language: ""
),
Blog(
id: "1",
image: .init(largeURLString: "", smallURLString: "", standardURLString: ""),
link: "",
media: .medium,
publishedAt: Date(timeIntervalSince1970: 0),
summary: .init(enTitle: "", jaTitle: ""),
title: .init(enTitle: "", jaTitle: "DroidKaigi 2020 Codelabs"),
author: .init(link: "", name: ""),
language: ""
),
]
.map(AnyFeedItem.init)
.map { .init(item: $0, isFavorited: false) }
static let mockVideos: Self = [
Video(
id: "0",
image: .init(largeURLString: "", smallURLString: "", standardURLString: ""),
link: "",
media: .youtube,
publishedAt: Date(timeIntervalSince1970: 0),
summary: .init(enTitle: "", jaTitle: ""),
title: .init(enTitle: "", jaTitle: "DroidKaigi 2020 Lite - KotlinのDelegated Propertiesを活用してAndroidアプリ開発をもっと便利にする / chibatching [JA]")
),
Video(
id: "1",
image: .init(largeURLString: "", smallURLString: "", standardURLString: ""),
link: "",
media: .youtube,
publishedAt: Date(timeIntervalSince1970: 0),
summary: .init(enTitle: "", jaTitle: ""),
title: .init(enTitle: "", jaTitle: "DroidKaigi 2020 Lite - Day 2 Night Session")
),
]
.map(AnyFeedItem.init)
.map { .init(item: $0, isFavorited: false) }
static let mockPodcasts: Self = [
Podcast(
id: "0",
image: .init(largeURLString: "", smallURLString: "", standardURLString: ""),
link: "",
media: .droidKaigiFm,
podcastLink: "",
publishedAt: Date(timeIntervalSince1970: 0),
speakers: [],
summary: .init(enTitle: "", jaTitle: ""),
title: .init(enTitle: "", jaTitle: "2. Android 11 Talks")
),
Podcast(
id: "1",
image: .init(largeURLString: "", smallURLString: "", standardURLString: ""),
link: "",
media: .droidKaigiFm,
podcastLink: "",
publishedAt: Date(timeIntervalSince1970: 0),
speakers: [],
summary: .init(enTitle: "", jaTitle: ""),
title: .init(enTitle: "", jaTitle: "5. Notificiationよもやま話")
),
]
.map(AnyFeedItem.init)
.map { .init(item: $0, isFavorited: false) }
}
|
PHP
|
UTF-8
| 759 | 2.609375 | 3 |
[] |
no_license
|
<?php
$conn = mysqli_connect('localhost', 'root', '', 'logistics');
if(!$conn) {
die("Failed to connect" . mysqli_connect_error());
}
date_default_timezone_set('Asia/Bangkok');
$_SESSION['now'] = date("Y-m-d H:i:s");
function query($query) {
global $conn;
return mysqli_query($conn, $query);
}
function escape($string) {
global $conn;
return mysqli_real_escape_string($conn, $string);
}
function fetch_assoc($result) {
return mysqli_fetch_assoc($result);
}
function num_rows($result) {
return mysqli_num_rows($result);
}
function redirect($location) {
return header('location: {$location}');
}
?>
|
Markdown
|
UTF-8
| 4,978 | 2.53125 | 3 |
[
"CC-BY-3.0",
"LicenseRef-scancode-generic-cla"
] |
permissive
|
<properties
pageTitle="Azure SQL Database 資源限制"
description="此頁面描述一些 Azure SQL Database 常見的資源限制。"
services="sql-database"
documentationCenter="na"
authors="rothja"
manager="jeffreyg"
editor="monicar" />
<tags
ms.service="sql-database"
ms.devlang="na"
ms.topic="article"
ms.tgt_pltfrm="na"
ms.workload="data-management"
ms.date="02/17/2016"
ms.author="jroth" />
# Azure SQL Database 資源限制
## 概觀
Azure SQL Database 使用兩種不同機制來管理資料庫可使用的資源:**資源管理**和**限制強制執行**。本主題將說明資源管理的這兩種主要方法。
## 資源管理
基本、標準和進階服務層的設計目的之一,是讓 Azure SQL Database 彷彿在獨立的電腦上執行,與其他資料庫完全隔離。資源管理便會模擬這個行為。如果彙總的資源使用率達到可用 CPU、記憶體、記錄 I/O 和資料 I/O 資源 (指派至資料庫) 的上限,資源管理會將查詢排入執行佇列中,並在系統釋出資源時,適時將資源指派給佇列中的查詢。
在專用的電腦上使用所有可用的資源,會導致目前正在執行的查詢花費更多執行時間,而這可能會使得用戶端上的命令逾時。具備積極重試邏輯的應用程式,以及時常對資料庫執行查詢的應用程式,若在嘗試執行新查詢時達到並行要求的上限,便可能出現錯誤訊息。
### 建議:
資料庫使用率接近上限時,監視資源使用率以及查詢的平均回應時間。查詢的延遲較高時,您通常可採取三種應對方式:
1. 減少資料庫的傳入要求數量,以避免逾時和要求不斷累積。
2. 為資料庫指派更高的效能層級。
3. 將查詢最佳化,以降低每個查詢的資源使用率。如需詳細資訊,請參閱<Azure SQL Database 效能指南>一文的「查詢微調/提示」章節。
## 限制強制執行
系統會在達到上限時拒絕新的要求,藉此強制執行 CPU、記憶體、記錄 I/O 和資料 I/O 以外的資源。用戶端收到的[錯誤訊息](sql-database-develop-error-messages.md)會因達到的上限而有所不同。
例如,SQL Database 的連接數,以及可以處理的並行要求數目都將受到限制。SQL Database 可允許資料庫的連接數大於並行要求的數目,以支援連接共用。雖然應用程式能輕易控制可用的連接數,但平行要求的數量通常難以預估及控制。尤其在尖峰負載期間,應用程式往往傳送過多的要求,或是資料庫在達到資源上限後,因為執行耗時較長的查詢而開始累積背景工作執行緒,此時就可能發生錯誤。
## 服務層和效能層級
對於單一資料庫,資料庫的限制是由服務層級和效能等級所定義。下表說明基本、標準和高階資料庫在不同效能等級的特性。
[AZURE.INCLUDE [SQL DB 服務層資料表](../../includes/sql-database-service-tiers-table.md)]
[彈性資料庫集區](sql-database-elastic-pool.md)在集區中的資料庫之間共用資源。下表說明基本、標準和高階彈性資料庫集區的特性。
[AZURE.INCLUDE [彈性資料庫的 SQL DB 服務層資料表](../../includes/sql-database-service-tiers-table-elastic-db-pools.md)]
如需上述表格所列之每項資源的擴充定義,請參閱[服務層功能和限制](sql-database-performance-guidance.md#service-tier-capabilities-and-limits)中的說明。如需服務層的概觀,請參閱 [Azure SQL Database 服務層和效能等級](sql-database-service-tiers.md)。
## 每部伺服器的 DTU 配額
Azure SQL Database 的每個邏輯伺服器目前有 15000 個 DTU 的 DTU 配額。此配額代表一部邏輯伺服器可以裝載的 DTU 數目,取決於 DTU 總數,以及伺服器上每個資料庫的效能層級。例如,若伺服器具備 5 個基本資料庫 (最多 5 X 5 個 DTU)、2 個標準 S1 資料庫 (最多 2 X 20 個 DTU),以及 3 個進階 P1 資料庫 (最多 3 X 100 個 DTU),便已用掉 15000 個 DTU 配額中的 365 個 DTU。
>[AZURE.NOTE] 您可以[連絡支援人員](https://azure.microsoft.com/blog/2014/06/04/azure-limits-quotas-increase-requests/),要求增加此配額。
## 其他 SQL Database 限制
| 領域 | 限制 | 說明 |
|---|---|---|
| 每個訂用帳戶使用自動匯出的資料庫 | 10 | 自動匯出可讓您建立自訂排程以備份 SQL Database。如需詳細資訊,請參閱 [SQL Database:自動 SQL Database 匯出的支援](http://weblogs.asp.net/scottgu/windows-azure-july-updates-sql-database-traffic-manager-autoscale-virtual-machines)。|
## 資源
[Azure 訂用帳戶和服務限制、配額與限制](../azure-subscription-service-limits.md)
[Azure SQL Database 服務層和效能層級](sql-database-service-tiers.md)
[SQL Database 用戶端程式的錯誤訊息](sql-database-develop-error-messages.md)
<!---HONumber=AcomDC_0218_2016-->
|
Shell
|
UTF-8
| 816 | 3.609375 | 4 |
[] |
no_license
|
#!/bin/bash
source "$(pwd)/env"
docker stack ps "wp-${CONTAINER_NAME}" > /dev/null 2>&1
if [ $? -eq 0 ];then
echo "stack running - executing command"
else
echo "could not find stack wp-${CONTAINER_NAME}! Make sure it's running."
exit
fi
CLI_IMAGE="wordpress:cli-php7.1"
DATA=$(docker service inspect --pretty "wp-${CONTAINER_NAME}_wordpress")
NETWORK=$(echo "$DATA" | sed -n 's/Networks:\s\(.*\)/\1/p' | tr -d '[:space:]')
VOL_SRC=$(echo "$DATA" | sed -n 's/Source\s=\s\(.*\)/\1/p' | tr -d '[:space:]')
VOL_TRG=$(echo "$DATA" | sed -n 's/Target\s=\s\(.*\)/\1/p' | tr -d '[:space:]')
echo "container: wp-${CONTAINER_NAME}_wordpress"
echo "network: $NETWORK"
echo "volume: $VOL_SRC:$VOL_TRG"
docker run -it --rm \
--user 33:33 \
--volume "$VOL_SRC:$VOL_TRG" \
--network "$NETWORK" \
$CLI_IMAGE "$@"
|
Python
|
UTF-8
| 954 | 3.125 | 3 |
[] |
no_license
|
import math
from networkx import Graph
class Bruteforce:
min_cost = math.inf
solution = []
count = 0
def solve(self, graph: Graph, first_node):
self.min_cost = math.inf
self.solution = []
self._solve(graph, first_node, first_node, [], 0)
print('cost={}, solution={}'.format(self.min_cost, self.solution))
print('expanded nodes', self.count)
def _solve(self, graph: Graph, first_node, cur_node, visited_nodes: list, cost):
self.count += 1
if len(visited_nodes) == len(graph.nodes):
if visited_nodes[-1] == first_node and cost < self.min_cost:
self.min_cost = cost
self.solution = [first_node] + visited_nodes
return
for node, attrs in graph.adj[cur_node].items():
if node not in visited_nodes:
self._solve(graph, first_node, node, visited_nodes + [node], cost + attrs['weight'])
|
JavaScript
|
UTF-8
| 4,590 | 2.546875 | 3 |
[] |
no_license
|
var express= require('express');
var app= express();
var jwt = require('jsonwebtoken');
///Connect to DataBasae
var mongoose = require('mongoose');
var config= require('../DBconfig');
mongoose.connect(config.database);
// Get Mongoose to use the global promise library
mongoose.Promise = global.Promise;
//Get the default connection
var db = mongoose.connection;
//Bind connection to error event (to get notification of connection errors)
(db.on('error', console.error.bind(console, 'MongoDB connection error:')));
var UserInstance = require('../models/user');
var StudyInstance = require('../models/study');
var SurveyInstance = require('../models/surveyQuestions');
var TokenInstance = require('../models/surveyTokens');
//Function To Login
exports.loginandGetToken = function(req, res)
{
UserInstance.findOne(
// query
{email :req.body.email}, (err, Doc) => {
if (err) return res.status(200).send(err)
if(Doc==null)
{
return res.status(200).json(message='Invalid Email')
}
else if(!Doc.validPassword(req.body.password))
{
return res.send({msg:'password Invalid'});
}
else if(Doc.type !='doctor')
{
return res.send({msg:'This user is not allowed to Access this Domain'});
}
else
{
// res.send('login Successfull and token generated');
//Generate JWT Token
const payload = {
name: req.body.name
};
var token = jwt.sign(payload, config.secret, {expiresIn: 86400 // expires in 24 hours
});
// return the information including token as JSON
return res.json({
success: true,
message: 'logged in!!! Enjoy your token!',
token: token,
type: Doc.type,
email : Doc.email
});
}
});
};
//Function to Create new Article
exports.CreateNewStudy= function(req, res)
{
var studyInstance = new StudyInstance({
name : req.body.title,
date : req.body.date,
patientsEnrolled : req.body.patients,
inclusionCriteria : req.body.ic,
exclusionCriteria : req.body.ec,
treatmentProtocol : req.body.tp,
studyInfo : req.body.info,
studyBy : req.body.studyBy
});
//save new article
studyInstance.save(function (err) {
if (err)
return res.json(err);
else
return res.json('Added successfully');
});
}
//Function to Fetch all Articles
exports.FetchAllStudies= function(req,res){
StudyInstance.find()
.then(article => {
if(article==null){ res.json({message:'No Article Found'})}
else
return res.json(article);
}).catch(err => {
return res.status(500).send({
message: err.message || "Some error occurred while retrieving all Articles."
});
});
};
//Function to Fetch all RESPONSES
exports.FetchAllResponses= function(req,res){
SurveyInstance.find({studyBy:req.body.studyBy})
.then(article => {
if(article==null){ res.json({message:'No Responses Found'})}
else
return res.json(article);
}).catch(err => {
return res.status(500).send({
message: err.message || "Some error occurred while retrieving all Articles."
});
});
};
exports.CreatePassCode = function(req,res){
tokenInstance = new TokenInstance({
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
token:req.body.passcode,
studyBy: req.body.studyBy,
studyName:req.body.studyName,
});
tokenInstance.save(function (err) {
if (err)
return res.json(err);
else
return res.json('Added successfully');
});
}
exports.FetchAllPatients= function(req,res){
UserInstance.find({
type:'patient'
})
.then(article => {
if(article==null){ res.json({message:'No Article Found'})}
else
return res.json(article);
}).catch(err => {
return res.status(500).send({
message: err.message || "Some error occurred while retrieving all Articles."
});
});
};
//update study
exports.UpdateStudy = function (req, res) {
var tempPatients= req.body.patients.split(',');
StudyInstance.findOneAndUpdate({name: req.body.name}, {$set:{patientsAdded:tempPatients}}, {new: true}, (err, doc) => {
if (err) return res.status(200).send(err)
if(doc==null)
return res.status(200).json(message='No study With this id')
else
return res.status(200).json(doc)
});
}
|
Java
|
UTF-8
| 1,664 | 2.015625 | 2 |
[
"MIT"
] |
permissive
|
package edu.ucdavis.dss.ipa.api.components.registrarReconciliationReport.views;
import org.javers.core.metamodel.annotation.DiffIgnore;
import javax.persistence.Id;
public class ActivityDiffDto {
@DiffIgnore
private long id;
@Id
private String uniqueKey;
private char typeCode;
private String bannerLocation, dayIndicator, startTime, endTime;
public ActivityDiffDto(
long activityId,
char typeCode,
String bannerLocation,
String dayIndicator,
String startTime,
String endTime,
String uniqueKey) {
setId(activityId);
setUniqueKey(uniqueKey);
setTypeCode(typeCode);
setBannerLocation(bannerLocation);
setDayIndicator(dayIndicator);
setStartTime(startTime);
setEndTime(endTime);
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUniqueKey() {
return uniqueKey;
}
public void setUniqueKey(String uniqueKey) {
this.uniqueKey = uniqueKey;
}
public char getTypeCode() {
return typeCode;
}
public void setTypeCode(char typeCode) {
this.typeCode = typeCode;
}
public String getBannerLocation() {
return bannerLocation;
}
public void setBannerLocation(String bannerLocation) {
this.bannerLocation = bannerLocation;
}
public String getDayIndicator() {
return dayIndicator;
}
public void setDayIndicator(String dayIndicator) {
this.dayIndicator = dayIndicator;
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
}
|
Markdown
|
UTF-8
| 9,211 | 3.125 | 3 |
[] |
no_license
|
# ORM 테스트
* shell열기
```bash
$ python manage.py shell_plus
```
DB 있는 지 확인하기
<img src="images/image-20200625092354086.png" alt="image-20200625092354086" style="zoom:80%;" />
# 1:N 관계
**게시글 생성 ORM**
```shell
article1 = Article.objects.create(title ='title',content='content', user=user1)
```
```shell
Article.objects.create(title='title',content='content',user_id=user1.pk)
```
**댓글 생성 ORM**
```python
User.objects.create_user(username="name", password="password")
```
```shell
Comment.objects.create(content='content',user=user1,article=article1)
```
<img src="images/image-20200625094004408.png" alt="image-20200625094004408" style="zoom:80%;" />
**게시글이 가지고 있는 전체 댓글 불러오기**
```shell
article = Article.objects.get(pk=8) #특정 게시글이 각지고 있는 전체 댓글 조회
article.comment_set.all()
```
```markdown
## Article에서 Comment로 접근할 때는 _set을 사용해주어야 한다.
```
:star: **특정 댓글이 어느 게시글과 연결되어 있는지 확인하기**
:star: **게시글이 어느 유저와 연결되어 있는지 확인하기**
**특정 유저가 작성한 전체 게시글 가져오기**
```shell
user1.article_set.all()
# for문 - 제목만 가져오기
for article in user1.article_set.all():
print(article.title)
```
<img src="images/image-20200625094402207.png" alt="image-20200625094402207" style="zoom:80%;" />
**특정 유저가 작성한 전체 댓글 가져오기**
<img src="images/image-20200625154718854.png" alt="image-20200625154718854" style="zoom:80%;" />
# M:N 관계
> PK들로 만들어진 class(Table)을 새로 생성한다.
>
> *[실습] 특정 의사의 환자 누가 있는지 확인*
* models.py
* 1:N 관계
<img src="images/image-20200625103310293.png" alt="image-20200625103310293" style="zoom:67%;" />
* M : N 관계
<img src="images/image-20200625103416445.png" alt="image-20200625103416445" style="zoom:80%;" />
* ORM 테스트
* 의사 - 환자 생성
```shell
In [1]: doctor = Doctor.objects.create(name='KIM')
In [2]: patient = Patient.objects.create(name="TOM")
```
* 의사 - 환자 연결해주기
```SHELL
In [3]: Reservation.objects.create(doctor=doctor, patient=patient)
Out[3]: <Reservation: 2번 의사 KIM의 환자 -2번 환자, TOM>
```
* 의사 - 환자 조회
```SHELL
In [4]: doctor.reservation_set.all()
Out[4]: <QuerySet [<Reservation: 2번 의사 KIM의 환자 -2번 환자, TOM>]>
In [5]: patient.reservation_set.all()
Out[5]: <QuerySet [<Reservation: 2번 의사 KIM의 환자 -2번 환자, TOM>]>
```
```SHELL
In [6]: patient2 = Patient.objects.create(name="yoon")
In [7]: Reservation.objects.create(doctor=doctor, patient = patient2)
Out[7]: <Reservation: 2번 의사 KIM의 환자 -3번 환자, yoon>
```
* 조회
```SHELL
In [8]: doctor.reservation_set.all()
Out[8]: <QuerySet [<Reservation: 2번 의사 KIM의 환자 -2번 환자, TOM>, <Reservation: 2번 의사 KIM의 환자 -3번 환자, yoon>]>
# 환자 이름 조회
In [9]: for reservation in doctor.reservation_set.all():
...: print(reservation.patient.name)
...:
TOM
yoon
# 환자 pk 조회
In [10]: for reservation in doctor.reservation_set.all():
...: print(reservation.patient.pk)
...:
...:
2
3
```
```SHELL
In [11]: for reservation in patient.reservation_set.all():
...: print(reservation.doctor.name)
...:
KIM
```
<img src="images/image-20200625103548626.png" alt="image-20200625103548626" style="zoom:80%;" />
<img src="images/image-20200625103621052.png" alt="image-20200625103621052" style="zoom:80%;" />
<img src="images/image-20200625103814711.png" alt="image-20200625103814711" style="zoom:80%;" />
* doctor가 `_set`을 꼭 사용해야 하는 것은 아니다.
* **역참조값**을 사용해주면 됨
```python
class Patient(models.Model):
name = models.CharField(max_length=20)
doctors = models.ManyToManyField(Doctor, through='Reservation', related_name="patients")
```
<img src="images/image-20200625104031756.png" alt="image-20200625104031756" style="zoom:80%;" />
* 역참조값을 사용하면 더이상 patient_set.all()은 사용할 수 없다.
<img src="images/image-20200625104150807.png" alt="image-20200625104150807" style="zoom:80%;" />
* 또한 이렇게 한다면 Reservation을 사용하지 않아도 된다.
*주의 : sqlite와 001xxx 파일을 지운 뒤, 다시 makemigrations와 migrate을 해주어야 한다.*
<img src="images/image-20200625104355844.png" alt="image-20200625104355844" style="zoom:80%;" />

* 관계 설계로 추가 필드가 필요할 때는 Reservation 처럼 class 만들어주면 된다.
* <최종 스키마>
<img src="images/image-20200625110717040.png" alt="image-20200625110717040" style="zoom:80%;" />
# 좋아요 구현
* [font awesome](https://fontawesome.com/)
```python
# views.py
@login_required
def like(request, article_pk):
# 특정 게시물에 대한 정보
article = get_object_or_404(Article, pk=article_pk)
# 좋아요를 누른 유저에 대한 정보
user = request.user
# 사용자가 게시글의 좋아요 목록에 있으면,
if user in article.like_users.all(): #user가 sequence안에 있는지 확인 - 있으면 좋아요 취소
article.like_users.remove(user)
else:
article.like_users.add(users)
return redirect('articles:index')
```
* article - models.py
<img src="C:\Users\sec\AppData\Roaming\Typora\typora-user-images\image-20200625091833282.png" alt="image-20200625091833282" style="zoom:80%;" />
```python
{% for article in articles %}
<p>{{ article.pk }}번째 글</p>
<p><a href="{% url 'articles:detail' article.pk %}">{{ article.title }}</a></p>
<p>작성자 : {{ article.user.username }} </p>
<p>
</a> 댓글 {{ article.comment_set.all|length }} 개
{% if user in article.like_users.all %}
<a href="{% url 'articles:like' article.pk %}"> <i class="fas fa-heart fa-lg text-danger"></i></a> {{ article.like_users.all|length }}
{% else %}
<a href="{% url 'articles:like' article.pk %}"><i class="far fa-heart fa-lg text-danger"></i> </a>{{ article.like_users.all|length }}
{% endif %}
</p>
```
## :fire: 템플릿의 모듈화
> 반복되는 로직을 모듈화해주어 div 지옥 탈출 @@!!! :imp:
<img src="images/image-20200625154817485.png" alt="image-20200625154817485" style="zoom:80%;" />
<img src="images/image-20200625154930268.png" alt="image-20200625154930268" style="zoom:80%;" />
[결과]
<img src="images/image-20200625155058212.png" alt="image-20200625155058212" style="zoom:80%;" />
# 프로필
* [user custom](https://github.com/django/django/blob/master/django/contrib/auth/models.py)
* ```python
# urls.py
path('<str:username>/', views.profile, name="profile"),
```

* 맨 밑에 위치하여야 한다. 만약 위에 위치하게 된다면
/login/ 시 login을 이름으로 인식하기 때문에 page not found 가 발생한다..
* AUTH_USER_MODEL의 경로가 달라지기 때문에 settings에서 경로를 설정해주어야 한다.
* user커스터마이징 후 db를 날려주어야 한다.
* get_user_model : User객체를 가져온다. 활성화된 유저를 가져온다. ( 생성된 테이블 - 자동적으로 accounts의 User를 찾는다)
* AUTH_USER_MODEL는 string을 리턴해준다. ( 수동적으로 accounts의 User를 찾는다)

* 모델 정의할 때는 문자열 - 설계도 작성 - 테이블 작성
## 친구 추가 구현
* models.py
```python
# Usercustomizing
class User(AbstractUser):
followers = models.ManyToManyField(
settings.AUTH_USER_MODEL,
related_name="followings",
blank=True,
)
```

* views.py
```python
@login_required
def follow(request, user_pk ):
person = get_object_or_404(get_user_model(), pk=user_pk)
user = request.user
# 원래 person에 담긴 user_pk값을 가진 유저는 프로필의 주인이다.
# request.user는 나, 요청을 보내온 사용자이다.
if user in person.followers.all():
person.followers.remove(user)
else:
person.followers.add(user)
return redirect('accounts:profile', person.username)
```
* 뷰
```html
{% if user != person %}
{% if user in person.followers.all %}
<a href="{% url 'accounts:follow' person.pk %}"><i class="fas fa-user-plus"> follow </i></a>
{% else %}
<a href="{% url 'accounts:follow' person.pk %}"><i class="fas fa-handshake-slash"> cancel </i> </a>
{% endif %}
{% endif %}
```
<img src="images/image-20200626105006945.png" alt="image-20200626105006945" style="zoom:80%;" />
|
Shell
|
UTF-8
| 3,711 | 2.8125 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
#!/usr/bin/env bash
# Copyright (c) 2018, University of Kaiserslautern
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER
# OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Author: Éder F. Zulian
DIR="$(cd "$(dirname "$0")" && pwd)"
TOPDIR=$DIR/../..
source $TOPDIR/common/defaults.in
source $TOPDIR/common/util.in
currtime=$(date "+%Y.%m.%d-%H.%M.%S")
arch="ARM"
mode="opt"
gem5_elf="build/$arch/gem5.$mode"
cd $ROOTDIR/gem5
if [[ ! -e $gem5_elf ]]; then
pfile="$TOPDIR/patches/gem5/asimbench/gem5_ARMv7a-ICS-Android.SMP.Asimbench-v3.patch"
patch -fs -p1 < $pfile &>/dev/null
build_gem5 $arch $mode
fi
imgdir="$FSDIRARM/asimbench/disks"
mkdir -p $imgdir
if [[ ! -e $imgdir/sdcard-1g-mxplayer.img ]]; then
tar -xaf $FSDIRARM/asimbench/asimbench_disk_image/sdcard-1g.tar.gz -C $imgdir
fi
if [[ ! -e $imgdir/ARMv7a-ICS-Android.SMP.Asimbench-v3.img ]]; then
tar -xaf $FSDIRARM/asimbench/asimbench_disk_image/ARMv7a-ICS-Android.SMP.Asimbench.tar.gz -C $imgdir
fi
target="boot_android"
config_script="configs/example/fs.py"
ncores="2"
cpu_options="--cpu-type=TimingSimpleCPU --num-cpu=$ncores"
mem_options="--mem-size=256MB --mem-type=DDR3_1600_8x8 --mem-channels=1 --caches --l2cache"
#tlm_options="--tlm-memory=transactor"
machine_options="--machine-type=RealView_PBX"
os_options="--os-type=android-ics"
#misc_options="--frame-capture"
disk_options="--disk=$FSDIRARM/asimbench/disks/ARMv7a-ICS-Android.SMP.Asimbench-v3.img"
kernel="--kernel=$FSDIRARM/asimbench/asimbench_android_arm_kernel/vmlinux.smp.ics.arm.asimbench.2.6.35"
call_m5_exit="no"
sleep_before_exit="0"
checkpoint_before_exit="no"
restore_from_checkpoint="no"
checkpoint_dir="${target}_${ncores}c_"
checkpoint_tick_number="0"
if [ "$restore_from_checkpoint" == "yes" ]; then
restore_checkpoint_options="--restore=${checkpoint_dir}/cpt.${checkpoint_tick_number}/"
fi
#bootscript="${target}_${ncores}c.rcS"
#bootscript_options="--script=$ROOTDIR/gem5/$bootscript"
output_dir="${target}_${ncores}c_$currtime"
mkdir -p ${output_dir}
logfile=${output_dir}/gem5.log
export M5_PATH=${M5_PATH}:"$FSDIRARM/asimbench":
$gem5_elf -d $output_dir $config_script $restore_checkpoint_options $cpu_options $mem_options $tlm_options $kernel $disk_options $machine_options $os_options $misc_options $bootscript_options 2>&1 | tee $logfile
|
Java
|
UTF-8
| 358 | 1.898438 | 2 |
[] |
no_license
|
package org.rta.core.dao.license;
import java.util.List;
import org.rta.core.dao.base.GenericDAO;
import org.rta.core.entity.licence.LicenseVehicleClassMasterEntity;
public interface LicenceVehicleClassMasterDAO extends GenericDAO<LicenseVehicleClassMasterEntity>{
public List<LicenseVehicleClassMasterEntity> getVehicleTransportType(String covcode);
}
|
Java
|
UTF-8
| 1,164 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
package com.BobScript.BobCode;
/**
* Created by zinov on 20.02.2016.
*/
public enum Type {
NULL, INT, FLOAT, STRING, ARRAY, SET, MAP, BOOLEAN, FUNCTION, FILE, RANGE, ITERATOR,USERS;
@Override
public String toString() {
switch (this) {
case INT:
return "integer";
case NULL:
return "null";
case FLOAT:
return "float";
case STRING:
return "string";
case ARRAY:
return "array";
case SET:
return "set";
case MAP:
return "set";
case BOOLEAN:
return "boolean";
case FUNCTION:
return "function";
case FILE:
return "file";
case RANGE:
return "range";
case USERS:
return "users";
case ITERATOR:
return "iterator";
default:
return "unknown";
}
}
public boolean isCopy() {
return this == INT || this == NULL || this == FLOAT;
}
}
|
JavaScript
|
UTF-8
| 2,564 | 2.9375 | 3 |
[] |
no_license
|
'use strict'
var _ = require('lodash');
module.exports = {
informationGain: function(attribute, examples, target) {
// need to know the entropy of the target
var targetEntropy = this.entropy(target, examples);
return targetEntropy - this.remainder(attribute, examples, target);
},
entropy: function(attribute, examples) {
var values = _.pluck(examples, attribute);
var uniqueValues = _.uniq(values);
var args = [];
for (var i = 0; i < uniqueValues.length; i++) {
args.push(this.proportion(uniqueValues[i], values));
}
return this.ent(args);
},
ent: function(args) {
var utils = this;
args = args.map(function(arg) {
if (arg === 0) {
return 0;
}
return -arg * utils.log(arg, 2);
});
return utils.sum(args);
},
log: function(n, base){
return Math.log(n) / Math.log(base);
},
remainder: function(attribute, examples, target) {
var attributeValues = _.pluck(examples, attribute);
var targetValues = _.pluck(examples, target);
var uniqueAttributeValues = _.uniq(attributeValues);
var uniqueTargetValues = _.uniq(targetValues);
var outputs = uniqueAttributeValues.map(function(v) {
var filtered = examples.filter(function(example) {
return example[attribute] === v;
});
return _.pluck(filtered, target);
});
var utils = this;
outputs = outputs.map(function(output) {
var proportions = uniqueTargetValues.map(function(v) {
return utils.proportion(v, output);
});
return output.length/targetValues.length * utils.ent(proportions);
});
return utils.sum(outputs);
},
sum: function(array) {
return array.reduce(function(a, b) { return a+b }, 0);
},
proportion: function(value, data) {
var count = 0;
for (var i = 0; i < data.length; i++) {
if (data[i] === value) {
count++;
}
}
return count/data.length;
},
pluralityValue: function(examples, target) {
var utils = this;
var values = _.pluck(examples, target);
var uniqueValues = _.uniq(values);
var proportions = uniqueValues.map(function(v) {
return utils.proportion(v, values);
});
var max = _.max(proportions);
return uniqueValues[proportions.indexOf(max)];
},
chooseAttribute: function(examples, attributes, target) {
var utils = this;
var igs = attributes.map(function(a) {
return utils.informationGain(a, examples, target);
});
var max = _.max(igs);
return attributes[igs.indexOf(max)];
}
}
|
Java
|
UTF-8
| 2,017 | 2.03125 | 2 |
[] |
no_license
|
package io.reactivex.internal.operators.flowable;
import io.reactivex.ai;
import io.reactivex.al;
import io.reactivex.b.c;
import io.reactivex.internal.b.b;
import io.reactivex.internal.subscriptions.SubscriptionHelper;
import io.reactivex.j;
import io.reactivex.o;
import org.b.d;
public final class ae<T> extends ai<Long> implements b<Long> {
/* renamed from: a reason: collision with root package name */
final j<T> f7932a;
static final class a implements c, o<Object> {
/* renamed from: a reason: collision with root package name */
final al<? super Long> f7933a;
/* renamed from: b reason: collision with root package name */
d f7934b;
long c;
a(al<? super Long> alVar) {
this.f7933a = alVar;
}
public final void onSubscribe(d dVar) {
if (SubscriptionHelper.validate(this.f7934b, dVar)) {
this.f7934b = dVar;
this.f7933a.onSubscribe(this);
dVar.request(Long.MAX_VALUE);
}
}
public final void onNext(Object obj) {
this.c++;
}
public final void onError(Throwable th) {
this.f7934b = SubscriptionHelper.CANCELLED;
this.f7933a.onError(th);
}
public final void onComplete() {
this.f7934b = SubscriptionHelper.CANCELLED;
this.f7933a.onSuccess(Long.valueOf(this.c));
}
public final void dispose() {
this.f7934b.cancel();
this.f7934b = SubscriptionHelper.CANCELLED;
}
public final boolean isDisposed() {
return this.f7934b == SubscriptionHelper.CANCELLED;
}
}
public ae(j<T> jVar) {
this.f7932a = jVar;
}
public final void subscribeActual(al<? super Long> alVar) {
this.f7932a.subscribe(new a(alVar));
}
public final j<Long> fuseToFlowable() {
return io.reactivex.g.a.onAssembly(new ad(this.f7932a));
}
}
|
PHP
|
UTF-8
| 1,052 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
<?php
Namespace Task;
class AllTimesheetController extends Controller
{
protected $footer = "View/Template/footer.php";
protected $template = "timesheetViewAll";
public function invoke()
{
$taskLoader = new TaskLoader();
$taskLoader->setDatabase($this->database);
if(! isset($_SESSION['account'])){
echo "Please login to view this page";
}
$taskHandler = new TaskHandler();
$taskHandler->setDatabase($this->database);
/* LOAD POSSIBLE TASK STATUS' */
$allStatus = $taskHandler->getAllTaskStatus();
if($allStatus['success'] === false)
{
/* HANDLE ERROR HERE OR IN VIEW */
}
/* GET HOW MANY TASKS THERE ARE FOR THE PAGEINATOR */
$amountOfTasks = $taskHandler->countAllTasks(false);
parent::invoke();
//create a new view and pass it our template
$view = new TimesheetView($this->template,$this->footer, 0);
$view->assign('title' , 'Logged in');
$view->assign('allTaskStatus' , $allStatus);
$view->assign('taskCount' , $amountOfTasks);
$view->assign('task' , null);
} // end function
}
?>
|
C++
|
UHC
| 906 | 3.625 | 4 |
[] |
no_license
|
#include<iostream>
#include<vector>
using namespace std;
#define N 10000 // 迭 ũ
bool arr[N]; // selfNumber ƴ
// Լ
int unSelfNum(int n) {
int sum = n; // ڱ ڽ
while (1) {
if (n == 0) break; // 0 Ǹ break
sum += n % 10; // 1 ڸ ϰ
n /= 10; // ڸ
}
return sum;
}
int main() {
ios_base::sync_with_stdio(false); cout.tie(NULL);
//1~10000 selfNumber ƴ true
for (int i = 1; i < N; i++) {
// ̰ outOfBounds.
// unSelfNum(9999) 10000 Ѵµ װ 迭 ε
if(unSelfNum(i) < N)
arr[unSelfNum(i)] = true;
}
// selfNumber ƴ false شϴ i
for (int i = 1; i < N; i++) {
if (!arr[i]) cout << i << '\n';
}
}
|
JavaScript
|
UTF-8
| 372 | 2.546875 | 3 |
[] |
no_license
|
$(function () {
var path = window.location.pathname;
$('a').each(function () {
var href = $(this).attr('href');
if(href == path){
$(this).parent().parent().parent('li').toggleClass("open");
$(this).parent('li').addClass('active');
$(this).parent().parent('.submenu').css('display','block');
}
});
});
|
PHP
|
UTF-8
| 812 | 3.171875 | 3 |
[] |
no_license
|
<?php
function substrwords($text, $maxchar, $end='...') {
if (strlen($text) > $maxchar || $text == '') {
$words = preg_split('/\s/', $text);
$output = '';
$i = 0;
while (1) {
$length = strlen($output)+strlen($words[$i]);
if ($length > $maxchar) {
break;
}
else {
$output .= " " . $words[$i];
++$i;
}
}
$output .= $end;
}
else {
$output = $text;
}
return $output;
}
function formatVideoTime($seconds) {
$hours = floor($seconds / 3600);
$minutes = floor(($seconds / 60) % 60);
$seconds = $seconds % 60;
if ($hours) {
return "$hours h $minutes m";
}
return "$minutes m $seconds ";
}
|
Python
|
UTF-8
| 3,913 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
from __future__ import print_function
from IPython.core.magic import Magics, magics_class, line_magic
from IPython.utils.io import capture_output
from .. import SimpleOlogClient
from .utils import save_pyplot_figure, get_screenshot, get_text_from_editor
olog_client = SimpleOlogClient()
def olog(msg=None, edit=False, logbooks=None, tags=None,
attachments=None, **kwargs):
"""Make a log entry to the Olog
:param msg: Message for log entry.
If None use and editor to get message.
:param logbooks: Logbooks to add message to.
:type logbooks: String or List of Strings.
:param tags: Tags to tag the log entry with.
:type tags: String or List of Strings.
:param attachments: List of attachments to add to log entry.
:type attachments: Attchment objects
"""
if not msg:
msg = get_text_from_editor()
olog_client.log(msg, logbooks=logbooks, tags=tags,
attachments=attachments)
return
def olog_savefig(**kwargs):
"""Save a pyplot figure and place it in tho Olog
The **kwargs are all passed onto the :func savefig: function
and then onto the :func olog" function
:returns: None
"""
fig = save_pyplot_figure(**kwargs)
if 'attachments' in kwargs:
if isinstance(kwargs['attachments'], list):
kwargs['attachments'].append(fig)
else:
kwargs['attachments'] = [kwargs['attatchments'], fig]
else:
kwargs['attachments'] = fig
olog(**kwargs)
return
def olog_grab(root=False, **kwargs):
"""Grab a screenshot and place it in tho Olog
:param root" If True, the entire screen is grabbed else select
an area as a rubber band.
The **kwargs are all passed onto the :func olog: function
:returns: None
"""
if not root:
print("Select area of screen to grab .........")
try:
a = get_screenshot(root)
except KeyboardInterrupt:
print("Canceled, no entry created")
return
if 'attachments' in kwargs:
if isinstance(kwargs['attachments'], list):
kwargs['attachments'].append(a)
else:
kwargs['attachments'] = [kwargs['attatchments'], a]
else:
kwargs['attachments'] = a
olog(**kwargs)
return
@magics_class
class OlogMagics(Magics):
msg_store = ''
@line_magic
def log_add(self, line):
"""Run the line and capture the output for the Olog"""
self.msg_store += ">>>{}\n".format(line)
self.msg_store += "\n"
with capture_output() as c:
self.shell.run_cell(line)
c.show()
self.msg_store += c.stdout
self.msg_store += '\n'
@line_magic
def log_end(self, line):
"""Store the captured lines in the Olog"""
text = get_text_from_editor(prepend=self.msg_store)
olog(text)
self.msg_store = ''
@line_magic
def log_clear(self, line):
"""Clear the store of captured lines"""
self.msg_store = ''
@line_magic
def log_line(self, line):
"""Run the line and add the output to the Olog"""
msg = ">>>{}\n".format(line)
msg += "\n"
with capture_output() as c:
self.shell.run_cell(line)
c.show()
msg += c.stdout
olog(msg)
@line_magic
def logit(self, line):
"""Add a log entry to the Olog"""
if line.strip() == '':
olog()
else:
olog(line.strip())
@line_magic
def grabit(self, line):
"""Grab a screenshot and add it to the Olog"""
olog_grab()
def load_ipython_extension(ipython):
push_vars = {'olog': olog,
'olog_savefig': olog_savefig,
'olog_grab': olog_grab,
'olog_client': olog_client}
ipython.push(push_vars)
ipython.register_magics(OlogMagics)
|
C#
|
UTF-8
| 1,886 | 3.125 | 3 |
[] |
no_license
|
using System.IO;
using System.Net.Mail;
namespace MailLibrary
{
/// <summary>
/// Container for use with sending email messages which gets contents of a file
/// from a varbinary column. The Attachment property permits using for sending email
/// messages.
/// </summary>
public class AttachmentByteArray
{
/// <summary>
/// Represents the name for the byte array in FileContent
/// </summary>
public string FullFilename { get; set; }
/// <summary>
/// What displays to the read for the file name
/// </summary>
public string DisplayName => Path.GetFileName(FullFilename);
/// <summary>
/// Represents a file in a byte array. This property could be
/// eliminated as in Attachement property File.ReadAllBytes
/// can be done inline with creating the MemoryStream but this
/// provides access to the array for debugging if needed.
/// </summary>
public byte[] FileContent { get; set; }
/// <summary>
/// Creates a smtp mail attachment from a byte array returned from a row in
/// a table.
/// </summary>
/// <returns></returns>
/// <remarks>
/// Since not using mime types this is not passed to the Attachment,
/// only a file name.
///
/// MemoryStream is safe to leave undisposed, gac handle this.
///
/// Two variables are used to create symbols for the gac to work with.
/// </remarks>
public Attachment Attachment
{
get
{
FileContent = File.ReadAllBytes(FullFilename);
var stream = new MemoryStream(FileContent);
var attachment = new Attachment(stream, DisplayName);
return attachment;
}
}
}
}
|
PHP
|
UTF-8
| 1,547 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace App\Traits;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
use Throwable;
trait Requests
{
/**
* Função que define o formato do resultado das requests
*
* @param string $message
* @param int $status
* @param Throwable|null $exception
* @return JsonResponse
*/
public function returnResponse(string $message, int $status, Throwable $exception = null)
{
$response['message'] = $message;
if ($exception) {
if (config('app.debug')) {
$response['line'] = $exception->getLine();
$response['file'] = $exception->getFile();
$response['trace'] = $exception->getTrace();
$response['msg'] = $exception->getMessage();
$response['code'] = $exception->getCode();
}
}
return response()->json($response, $status);
}
/**
* Lanca excecao de erro com log
*
* @param Throwable $exception
* @param string|null $messageLog
* @throws Throwable
*/
public function shootExeception(Throwable $exception, string $messageLog = null)
{
if ($messageLog) {
$this->log_format($messageLog);
}
throw $exception;
}
/**
* @param string $messageLog
*/
private function log_format(string $messageLog)
{
if (auth()->user()) {
$messageLog .= "; User: ". auth()->user()->id;
}
Log::warning($messageLog);
}
}
|
Markdown
|
UTF-8
| 2,346 | 3.46875 | 3 |
[] |
no_license
|
# What is a Function?
#### let you group a series of statements together to perform a specific task. you can reuse the function (rather than repeating the same set of st atements).
__some example, the message is held in an HTML element whose id attribute has a value of message.__
*The message is going to be changed using JavaScript.*
__Before the closing </body> tag, you can see the link to the JavaScript file. then JavaScript file starts with a variable used to hold a new message, and is followed by a function.__

;
## Declaring a function
- to create a function, you give name and then write the statements needed.
;
## calling a function
- you can execute all of the statements between its curly braces with just one line of code.
## Declaring function that need inforimation
- sometimes needs to specific inforimation to perform its task.
- give it parameters, inside the function the parameteract like variables.
;
## calling a function that need inforimation
- specify the values it shoude in the parentheses that folloe its name.
> the values are called arguments, they can be provided as **values or variables**.
|values | variables |
|--- |--|
|such as: getArea(3,5);| such as: wWidth = 2; wHeight = 2; getArea(wWidth,wHeight);|
##### *******************************************************
|parameters | arguments |
|--|---|
|*such as: getArea(3,5);* | *such as: wWidth = 2; wHeight = 2; getArea(wWidth,wHeight);* |
|*when the function is declared, you can see the words width and height used (in parentheses on the first line). Inside the curly braces of the function*|*getArea () function is being called and the code specifies real numbers that will be used to perform the calculation (or variables that hold real numbers). These values that you pass into the code (the information it needs to calculate the size of this particular wall)* |
## getting a single value out of a function
- return inforimation
|
C++
|
UTF-8
| 1,653 | 3.484375 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
using namespace std;
//https://leetcode.com/problems/merge-intervals/
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
struct Interval {
int start;
int end;
Interval() : start(0), end(0) {}
Interval(int s, int e) : start(s), end(e) {}
};
class Solution {
public:
static int intervalComp(const Interval& i1, const Interval& i2) {
return (i2.start - i1.start) > 0;
}
vector<Interval> merge(vector<Interval>& intervals) {
vector<Interval> result;
if (intervals.empty()) return result;
sort(intervals.begin(), intervals.end(), intervalComp);
int left = 0, right = 0, max_end = intervals[left].end;
while (right < intervals.size() - 1) {
++right;
if (intervals[right].start <= max_end) {
max_end = max(max_end, intervals[right].end);
} else {
Interval interval(intervals[left].start, max_end);
result.push_back(interval);
left = right;
max_end = intervals[left].end;
}
}
Interval interval(intervals[left].start, max_end);
result.push_back(interval);
return result;
}
};
int main() {
Solution s;
vector<Interval> v;
Interval i1(1,3);
Interval i2(2,6);
Interval i3(8,10);
Interval i4(15,18);
v.push_back(i1);
v.push_back(i2);
v.push_back(i3);
v.push_back(i4);
v = s.merge(v);
cout <<v.size() <<endl;
}
|
Python
|
UTF-8
| 1,445 | 2.765625 | 3 |
[] |
no_license
|
from models.event import Event, EventSchema
from datetime import datetime
event_schema = EventSchema()
def create_event(data, new_client): #Called from event_controller.py
print(f'Entering create_event()')
print(f'data:{data}')
print(f'new_client:{new_client}')
new_event = Event(
title=data['title'],
menu_choice=data['menu_choice'],
ev_date=data['ev_date'],
client_id=new_client,
date_created=datetime.utcnow(),
last_modified=datetime.utcnow()
)
try:
new_event.save()
message = 'Event saved successfully'
return message, 200
except Exception as e:
return str(e), 400
# return "Created new event"
def edit_event(evnt_id, data): # called from event_controller.py::event_id(evnt_id)
x = Event.get_one_event(evnt_id) # get_one_event() defined in event.py
updated = x.update(x, data)
new_event = event_schema.dump(updated)
return new_event
def delete_event(evnt_id):
x = Event.get_one_event(evnt['id'])
x.delete()
return 'Deleted'
def fetch_one_event(evnt_id):
x = Event.get_one_event(evnt_id)
event_posts = event_schema.dump(x)
return event_posts
def fetch_events():
x = Event.get_all_events() # defined as static method in Class Event
all_events = event_schema.dump(x, many=True)
return all_events
def get_event(data, user):
return 'Event retrieved successfully'
|
C#
|
UTF-8
| 31,090 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
namespace CustomCode.Core.DesignByContract
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
/// <summary>
/// Preconditions for <see cref="Nullable{Int64}"/> types.
/// </summary>
/// <remarks>
/// https://stackoverflow.com/questions/15319025/methodimploptions-aggressiveinlining-vs-targetedpatchingoptout
/// https://stackoverflow.com/questions/14937647/method-inlining-across-native-images-of-assemblies/14982340#14982340
/// </remarks>
public partial class Requires
{
#region Logic
/// <summary>
/// Precondition that requires a nullable long <paramref name="value"/> to fullfill the specified
/// boolean <paramref name="condition"/>.
/// </summary>
/// <param name="value"> The <see cref="Nullable{Int64}"/> value to be checked. </param>
/// <param name="condition"> A boolean condition that must be fullfilled by the specified value. </param>
/// <param name="parameterName"> The name of the parameter to be checked. </param>
/// <param name="errorMessage"> The error message that is shown when the <paramref name="value"/> check is not successfull. </param>
/// <example>
/// Requires.ToBeNegative(value);
/// </example>
[Conditional("contracts_throw")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ToBe(long? value, Func<long?, bool> condition,
string parameterName = "Value", string errorMessage = "Value is invalid")
{
if (new Lazy<bool>(() => condition(value)).Value == false) // invoking the delegate directly will prevent inlining
{
throw new ArgumentException(errorMessage, parameterName);
}
}
/// <summary>
/// Precondition that requires a nullable long <paramref name="value"/> to fullfill the specified
/// boolean <paramref name="condition"/>.
/// </summary>
/// <param name="value"> The <see cref="Nullable{Int64}"/> value to be checked. </param>
/// <param name="condition"> A boolean condition that must be fullfilled by the specified value. </param>
/// <param name="exceptionFactory"> A delegate that creates the exception to be thrown. </param>
/// <example>
/// Requires.ToBeNegative(value, () => new ArgumentException("Invalid value", "value"));
/// </example>
[Conditional("contracts_throw")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ToBe<E>(long? value, Func<long?, bool> condition, Func<E> exceptionFactory)
where E : Exception
{
if (new Lazy<bool>(() => condition(value)).Value == false) // invoking the delegate directly will prevent inlining
{
var factory = new Lazy<E>(exceptionFactory); // invoking the delegate directly will prevent inlining
throw factory.Value;
}
}
/// <summary>
/// Precondition that requires a nullable long <paramref name="value"/> to fullfill the specified
/// boolean <paramref name="condition"/>.
/// </summary>
/// <param name="value"> The <see cref="Nullable{Int64}"/> value to be checked. </param>
/// <param name="condition"> A boolean condition that must be fullfilled by the specified value. </param>
/// <param name="exceptionFactory"> A delegate that creates the exception to be thrown. </param>
/// <example>
/// Requires.ToBeNegative(value, (v) => new ArgumentException("Invalid value", "value"));
/// </example>
[Conditional("contracts_throw")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ToBe<E>(long? value, Func<long?, bool> condition, Func<long?, E> exceptionFactory)
where E : Exception
{
if (new Lazy<bool>(() => condition(value)).Value == false) // invoking the delegate directly will prevent inlining
{
var factory = new Lazy<E>(() => exceptionFactory(value)); // invoking the delegate directly will prevent inlining
throw factory.Value;
}
}
/// <summary>
/// Precondition that requires a nullable long <paramref name="value"/> to be between the specified
/// <paramref name="minimum"/> and <paramref name="maximum"/> value.
/// </summary>
/// <param name="value"> The <see cref="Nullable{Int64}"/> value to be checked. </param>
/// <param name="minimum"> The allowed minimum value. </param>
/// <param name="maximum"> The allowed maximum value. </param>
/// <param name="parameterName"> The name of the parameter to be checked. </param>
/// <param name="errorMessage"> The error message that is shown when the <paramref name="value"/> check is not successfull. </param>
/// <example>
/// Requires.ToBeBetween(value, 1, 10);
/// </example>
[Conditional("contracts_throw")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ToBeBetween(long? value, long minimum, long maximum,
string parameterName = "Value", string errorMessage = "Value must be between the specified minimum and maximum")
{
if (value == null || value < minimum || value > maximum)
{
throw new ArgumentException(errorMessage, parameterName);
}
}
/// <summary>
/// Precondition that requires a nullable long <paramref name="value"/> to be between the specified
/// <paramref name="minimum"/> and <paramref name="maximum"/> value.
/// </summary>
/// <param name="value"> The <see cref="Nullable{Int64}"/> value to be checked. </param>
/// <param name="minimum"> The allowed minimum value. </param>
/// <param name="maximum"> The allowed maximum value. </param>
/// <param name="exceptionFactory"> A delegate that creates the exception to be thrown. </param>
/// <example>
/// Requires.ToBeBetween(value, 1, 10, () => new ArgumentException("Invalid value", "value"));
/// </example>
[Conditional("contracts_throw")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ToBeBetween<E>(long? value, long minimum, long maximum, Func<E> exceptionFactory)
where E : Exception
{
if (value == null || value < minimum || value > maximum)
{
var factory = new Lazy<E>(exceptionFactory); // invoking the delegate directly will prevent inlining
throw factory.Value;
}
}
/// <summary>
/// Precondition that requires a nullable long <paramref name="value"/> to be between the specified
/// <paramref name="minimum"/> and <paramref name="maximum"/> value.
/// </summary>
/// <param name="value"> The <see cref="Nullable{Int64}"/> value to be checked. </param>
/// <param name="minimum"> The allowed minimum value. </param>
/// <param name="maximum"> The allowed maximum value. </param>
/// <param name="exceptionFactory"> A delegate that creates the exception to be thrown. </param>
/// <example>
/// Requires.ToBeBetween(value, 1, 10, (v, min, max) => new ArgumentException("Invalid value", "value"));
/// </example>
[Conditional("contracts_throw")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ToBeBetween<E>(long? value, long minimum, long maximum, Func<long?, long, long, E> exceptionFactory)
where E : Exception
{
if (value == null || value < minimum || value > maximum)
{
var factory = new Lazy<E>(() => exceptionFactory(value, minimum, maximum)); // invoking the delegate directly will prevent inlining
throw factory.Value;
}
}
/// <summary>
/// Precondition that requires a nullable long <paramref name="value"/> to be greater than the specified
/// <paramref name="minimum"/> value.
/// </summary>
/// <param name="value"> The <see cref="Nullable{Int64}"/> value to be checked. </param>
/// <param name="minimum"> The allowed minimum value. </param>
/// <param name="parameterName"> The name of the parameter to be checked. </param>
/// <param name="errorMessage"> The error message that is shown when the <paramref name="value"/> check is not successfull. </param>
/// <example>
/// Requires.ToBeGreaterThan(value, 1);
/// </example>
[Conditional("contracts_throw")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ToBeGreaterThan(long? value, long minimum,
string parameterName = "Value", string errorMessage = "Value must be greater than the specified minimum")
{
if (value == null || value <= minimum)
{
throw new ArgumentException(errorMessage, parameterName);
}
}
/// <summary>
/// Precondition that requires a nullable long <paramref name="value"/> to be greater than the specified
/// <paramref name="minimum"/> value.
/// </summary>
/// <param name="value"> The <see cref="Nullable{Int64}"/> value to be checked. </param>
/// <param name="minimum"> The allowed minimum value. </param>
/// <param name="exceptionFactory"> A delegate that creates the exception to be thrown. </param>
/// <example>
/// Requires.ToBeGreaterThan(value, 1, () => new ArgumentException("Invalid value", "value"));
/// </example>
[Conditional("contracts_throw")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ToBeGreaterThan<E>(long? value, long minimum, Func<E> exceptionFactory)
where E : Exception
{
if (value == null || value <= minimum)
{
var factory = new Lazy<E>(exceptionFactory); // invoking the delegate directly will prevent inlining
throw factory.Value;
}
}
/// <summary>
/// Precondition that requires a nullable long <paramref name="value"/> to be greater than the specified
/// <paramref name="minimum"/> value.
/// </summary>
/// <param name="value"> The <see cref="Nullable{Int64}"/> value to be checked. </param>
/// <param name="minimum"> The allowed minimum value. </param>
/// <param name="exceptionFactory"> A delegate that creates the exception to be thrown. </param>
/// <example>
/// Requires.ToBeGreaterThan(value, 1, (v, min) => new ArgumentException("Invalid value", "value"));
/// </example>
[Conditional("contracts_throw")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ToBeGreaterThan<E>(long? value, long minimum, Func<long?, long, E> exceptionFactory)
where E : Exception
{
if (value == null || value <= minimum)
{
var factory = new Lazy<E>(() => exceptionFactory(value, minimum)); // invoking the delegate directly will prevent inlining
throw factory.Value;
}
}
/// <summary>
/// Precondition that requires a nullable long <paramref name="value"/> to be greater than or equal to the specified
/// <paramref name="minimum"/> value.
/// </summary>
/// <param name="value"> The <see cref="Nullable{Int64}"/> value to be checked. </param>
/// <param name="minimum"> The allowed minimum value. </param>
/// <param name="parameterName"> The name of the parameter to be checked. </param>
/// <param name="errorMessage"> The error message that is shown when the <paramref name="value"/> check is not successfull. </param>
/// <example>
/// Requires.ToBeGreaterThan(value, 1);
/// </example>
[Conditional("contracts_throw")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ToBeGreaterThanOrEqualTo(long? value, long minimum,
string parameterName = "Value", string errorMessage = "Value must be greater than or equal to the specified minimum")
{
if (value == null || value < minimum)
{
throw new ArgumentException(errorMessage, parameterName);
}
}
/// <summary>
/// Precondition that requires a nullable long <paramref name="value"/> to be greater than or equal to the specified
/// <paramref name="minimum"/> value.
/// </summary>
/// <param name="value"> The <see cref="Nullable{Int64}"/> value to be checked. </param>
/// <param name="minimum"> The allowed minimum value. </param>
/// <param name="exceptionFactory"> A delegate that creates the exception to be thrown. </param>
/// <example>
/// Requires.ToBeGreaterThan(value, 1, () => new ArgumentException("Invalid value", "value"));
/// </example>
[Conditional("contracts_throw")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ToBeGreaterThanOrEqualTo<E>(long? value, long minimum, Func<E> exceptionFactory)
where E : Exception
{
if (value == null || value < minimum)
{
var factory = new Lazy<E>(exceptionFactory); // invoking the delegate directly will prevent inlining
throw factory.Value;
}
}
/// <summary>
/// Precondition that requires a nullable long <paramref name="value"/> to be greater than or equal to the specified
/// <paramref name="minimum"/> value.
/// </summary>
/// <param name="value"> The <see cref="Nullable{Int64}"/> value to be checked. </param>
/// <param name="minimum"> The allowed minimum value. </param>
/// <param name="exceptionFactory"> A delegate that creates the exception to be thrown. </param>
/// <example>
/// Requires.ToBeGreaterThan(value, 1, (v, min) => new ArgumentException("Invalid value", "value"));
/// </example>
[Conditional("contracts_throw")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ToBeGreaterThanOrEqualTo<E>(long? value, long minimum, Func<long?, long, E> exceptionFactory)
where E : Exception
{
if (value == null || value < minimum)
{
var factory = new Lazy<E>(() => exceptionFactory(value, minimum)); // invoking the delegate directly will prevent inlining
throw factory.Value;
}
}
/// <summary>
/// Precondition that requires a nullable long <paramref name="value"/> to be less than the specified
/// <paramref name="maximum"/> value.
/// </summary>
/// <param name="value"> The <see cref="Nullable{Int64}"/> value to be checked. </param>
/// <param name="maximum"> The allowed maximum value. </param>
/// <param name="parameterName"> The name of the parameter to be checked. </param>
/// <param name="errorMessage"> The error message that is shown when the <paramref name="value"/> check is not successfull. </param>
/// <example>
/// Requires.ToBeLessThan(value, 10);
/// </example>
[Conditional("contracts_throw")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ToBeLessThan(long? value, long maximum,
string parameterName = "Value", string errorMessage = "Value must be less than the specified maximum")
{
if (value == null || value >= maximum)
{
throw new ArgumentException(errorMessage, parameterName);
}
}
/// <summary>
/// Precondition that requires a nullable long <paramref name="value"/> to be less than the specified
/// <paramref name="maximum"/> value.
/// </summary>
/// <param name="value"> The <see cref="Nullable{Int64}"/> value to be checked. </param>
/// <param name="maximum"> The allowed maximum value. </param>
/// <param name="exceptionFactory"> A delegate that creates the exception to be thrown. </param>
/// <example>
/// Requires.ToBeLessThan(value, 10, () => new ArgumentException("Invalid value", "value"));
/// </example>
[Conditional("contracts_throw")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ToBeLessThan<E>(long? value, long maximum, Func<E> exceptionFactory)
where E : Exception
{
if (value == null || value >= maximum)
{
var factory = new Lazy<E>(exceptionFactory); // invoking the delegate directly will prevent inlining
throw factory.Value;
}
}
/// <summary>
/// Precondition that requires a nullable long <paramref name="value"/> to be less than the specified
/// <paramref name="maximum"/> value.
/// </summary>
/// <param name="value"> The <see cref="Nullable{Int64}"/> value to be checked. </param>
/// <param name="maximum"> The allowed maximum value. </param>
/// <param name="exceptionFactory"> A delegate that creates the exception to be thrown. </param>
/// <example>
/// Requires.ToBeLessThan(value, 10, (v, max) => new ArgumentException("Invalid value", "value"));
/// </example>
[Conditional("contracts_throw")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ToBeLessThan<E>(long? value, long maximum, Func<long?, long, E> exceptionFactory)
where E : Exception
{
if (value == null || value >= maximum)
{
var factory = new Lazy<E>(() => exceptionFactory(value, maximum)); // invoking the delegate directly will prevent inlining
throw factory.Value;
}
}
/// <summary>
/// Precondition that requires a nullable long <paramref name="value"/> to be less than or equal to the specified
/// <paramref name="maximum"/> value.
/// </summary>
/// <param name="value"> The <see cref="Nullable{Int64}"/> value to be checked. </param>
/// <param name="maximum"> The allowed maximum value. </param>
/// <param name="parameterName"> The name of the parameter to be checked. </param>
/// <param name="errorMessage"> The error message that is shown when the <paramref name="value"/> check is not successfull. </param>
/// <example>
/// Requires.ToBeLessThan(value, 10);
/// </example>
[Conditional("contracts_throw")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ToBeLessThanOrEqualTo(long? value, long maximum,
string parameterName = "Value", string errorMessage = "Value must be less than or equal to the specified maximum")
{
if (value == null || value > maximum)
{
throw new ArgumentException(errorMessage, parameterName);
}
}
/// <summary>
/// Precondition that requires a nullable long <paramref name="value"/> to be less than or equal to the specified
/// <paramref name="maximum"/> value.
/// </summary>
/// <param name="value"> The <see cref="Nullable{Int64}"/> value to be checked. </param>
/// <param name="maximum"> The allowed maximum value. </param>
/// <param name="exceptionFactory"> A delegate that creates the exception to be thrown. </param>
/// <example>
/// Requires.ToBeLessThan(value, 10, () => new ArgumentException("Invalid value", "value"));
/// </example>
[Conditional("contracts_throw")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ToBeLessThanOrEqualTo<E>(long? value, long maximum, Func<E> exceptionFactory)
where E : Exception
{
if (value == null || value > maximum)
{
var factory = new Lazy<E>(exceptionFactory); // invoking the delegate directly will prevent inlining
throw factory.Value;
}
}
/// <summary>
/// Precondition that requires a nullable long <paramref name="value"/> to be less than or equal to the specified
/// <paramref name="maximum"/> value.
/// </summary>
/// <param name="value"> The <see cref="Nullable{Int64}"/> value to be checked. </param>
/// <param name="maximum"> The allowed maximum value. </param>
/// <param name="exceptionFactory"> A delegate that creates the exception to be thrown. </param>
/// <example>
/// Requires.ToBeLessThan(value, 10, (v, max) => new ArgumentException("Invalid value", "value"));
/// </example>
[Conditional("contracts_throw")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ToBeLessThanOrEqualTo<E>(long? value, long maximum, Func<long?, long, E> exceptionFactory)
where E : Exception
{
if (value == null || value > maximum)
{
var factory = new Lazy<E>(() => exceptionFactory(value, maximum)); // invoking the delegate directly will prevent inlining
throw factory.Value;
}
}
/// <summary>
/// Precondition that requires a nullable long <paramref name="value"/> to be negative.
/// </summary>
/// <param name="value"> The <see cref="Nullable{Int64}"/> value to be checked. </param>
/// <param name="parameterName"> The name of the parameter to be checked. </param>
/// <param name="errorMessage"> The error message that is shown when the <paramref name="value"/> check is not successfull. </param>
/// <example>
/// Requires.ToBeNegative(value);
/// </example>
[Conditional("contracts_throw")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ToBeNegative(long? value, string parameterName = "Value", string errorMessage = "Value must be negative")
{
if (value == null || value >= 0)
{
throw new ArgumentException(errorMessage, parameterName);
}
}
/// <summary>
/// Precondition that requires a nullable long <paramref name="value"/> to be negative.
/// </summary>
/// <param name="value"> The <see cref="Nullable{Int64}"/> value to be checked. </param>
/// <param name="exceptionFactory"> A delegate that creates the exception to be thrown. </param>
/// <example>
/// Requires.ToBeNegative(value, () => new ArgumentException("Invalid value", "value"));
/// </example>
[Conditional("contracts_throw")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ToBeNegative<E>(long? value, Func<E> exceptionFactory)
where E : Exception
{
if (value == null || value >= 0)
{
var factory = new Lazy<E>(exceptionFactory); // invoking the delegate directly will prevent inlining
throw factory.Value;
}
}
/// <summary>
/// Precondition that requires a nullable long <paramref name="value"/> to be negative.
/// </summary>
/// <param name="value"> The <see cref="Nullable{Int64}"/> value to be checked. </param>
/// <param name="exceptionFactory"> A delegate that creates the exception to be thrown. </param>
/// <example>
/// Requires.ToBeNegative(value, (v) => new ArgumentException("Invalid value", "value"));
/// </example>
[Conditional("contracts_throw")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ToBeNegative<E>(long? value, Func<long?, E> exceptionFactory)
where E : Exception
{
if (value == null || value >= 0)
{
var factory = new Lazy<E>(() => exceptionFactory(value)); // invoking the delegate directly will prevent inlining
throw factory.Value;
}
}
/// <summary>
/// Precondition that requires a nullable long <paramref name="value"/> to be one of the expected values.
/// </summary>
/// <param name="value"> The <see cref="Nullable{Int64}"/> value to be checked. </param>
/// <param name="expectedValues"> The expected values. </param>
/// <param name="parameterName"> The name of the parameter to be checked. </param>
/// <param name="errorMessage"> The error message that is shown when the <paramref name="value"/> check is not successfull. </param>
/// <example>
/// Requires.ToBeOneOf(value, new[] { 1, 2, 10 });
/// </example>
[Conditional("contracts_throw")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ToBeOneOf(long? value, IEnumerable<long?> expectedValues,
string parameterName = "Value", string errorMessage = "Value is invalid")
{
if (expectedValues.Any(v => v == value) == false)
{
throw new ArgumentException(errorMessage, parameterName);
}
}
/// <summary>
/// Precondition that requires a nullable long <paramref name="value"/> to be one of the expected values.
/// </summary>
/// <param name="value"> The <see cref="Nullable{Int64}"/> value to be checked. </param>
/// <param name="expectedValues"> The expected values. </param>
/// <param name="exceptionFactory"> A delegate that creates the exception to be thrown. </param>
/// <example>
/// Requires.ToBeOneOf(value, new[] { 1, 2, 10 }, () => new ArgumentException("Invalid value", "value"));
/// </example>
[Conditional("contracts_throw")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ToBeOneOf<E>(long? value, IEnumerable<long?> expectedValues, Func<E> exceptionFactory)
where E : Exception
{
if (expectedValues.Any(v => v == value) == false)
{
var factory = new Lazy<E>(exceptionFactory); // invoking the delegate directly will prevent inlining
throw factory.Value;
}
}
/// <summary>
/// Precondition that requires a nullable long <paramref name="value"/> to be one of the expected values.
/// </summary>
/// <param name="value"> The <see cref="Nullable{Int64}"/> value to be checked. </param>
/// <param name="expectedValues"> The expected values. </param>
/// <param name="exceptionFactory"> A delegate that creates the exception to be thrown. </param>
/// <example>
/// Requires.ToBeOneOf(value, new[] { 1, 2, 10 }, (v) => new ArgumentException("Invalid value", "value"));
/// </example>
[Conditional("contracts_throw")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ToBeOneOf<E>(long? value, IEnumerable<long?> expectedValues, Func<long?, IEnumerable<long?>, E> exceptionFactory)
where E : Exception
{
if (expectedValues.Any(v => v == value) == false)
{
var factory = new Lazy<E>(() => exceptionFactory(value, expectedValues)); // invoking the delegate directly will prevent inlining
throw factory.Value;
}
}
/// <summary>
/// Precondition that requires a nullable long <paramref name="value"/> to be positive.
/// </summary>
/// <param name="value"> The <see cref="Nullable{Int64}"/> value to be checked. </param>
/// <param name="parameterName"> The name of the parameter to be checked. </param>
/// <param name="errorMessage"> The error message that is shown when the <paramref name="value"/> check is not successfull. </param>
/// <example>
/// Requires.ToBePositive(value);
/// </example>
[Conditional("contracts_throw")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ToBePositive(long? value, string parameterName = "Value", string errorMessage = "Value must be positive")
{
if (value == null || value < 0)
{
throw new ArgumentException(errorMessage, parameterName);
}
}
/// <summary>
/// Precondition that requires a nullable long <paramref name="value"/> to be positive.
/// </summary>
/// <param name="value"> The <see cref="Nullable{Int64}"/> value to be checked. </param>
/// <param name="exceptionFactory"> A delegate that creates the exception to be thrown. </param>
/// <example>
/// Requires.ToBePositive(value, () => new ArgumentException("Invalid value", "value"));
/// </example>
[Conditional("contracts_throw")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ToBePositive<E>(long? value, Func<E> exceptionFactory)
where E : Exception
{
if (value == null || value < 0)
{
var factory = new Lazy<E>(exceptionFactory); // invoking the delegate directly will prevent inlining
throw factory.Value;
}
}
/// <summary>
/// Precondition that requires a nullable long <paramref name="value"/> to be positive.
/// </summary>
/// <param name="value"> The <see cref="Nullable{Int64}"/> value to be checked. </param>
/// <param name="exceptionFactory"> A delegate that creates the exception to be thrown. </param>
/// <example>
/// Requires.ToBePositive(value, (v) => new ArgumentException("Invalid value", "value"));
/// </example>
[Conditional("contracts_throw")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ToBePositive<E>(long? value, Func<long?, E> exceptionFactory)
where E : Exception
{
if (value == null || value < 0)
{
var factory = new Lazy<E>(() => exceptionFactory(value)); // invoking the delegate directly will prevent inlining
throw factory.Value;
}
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.