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
|
---|---|---|---|---|---|---|---|
C++
|
UTF-8
| 654 | 3.09375 | 3 |
[] |
no_license
|
#include "Motorcycle.h"
Motorcycle::Motorcycle(const std::string& n) : Vehicle(n) {}
void Motorcycle::lanesplitAndRace( int topSpeed )
{
setSpeed(topSpeed);
std::cout << name << (topSpeed > 90 ? ": yeeehawwww" : ": zzzzzzzz") << std::endl;
}
void Motorcycle::tryToEvade()
{
std::cout << name << ": you'll never take me alive, ya dirty coppers!" << std::endl;
setSpeed(120);
}
void Motorcycle::setSpeed(int s)
{
if( s < 90 )
{
//ignore the request to lower the speed
std::cout<< name << ": uh, no. i'm currently lane-splitting and racing" << std::endl;
}
else
{
Vehicle::setSpeed(s);
}
}
|
Shell
|
UTF-8
| 499 | 3.046875 | 3 |
[] |
no_license
|
#!/bin/sh
g++ -O2 main.cpp -o main
g++ -O2 generator.cpp -o generator
g++ -O2 simple.cpp -o simple
random="test/random.txt"
for i in `seq -w 60`
do
echo "testing case${i}"
input="test/case${i}/testcase_${i}.txt"
simple_output="test/case${i}/simple_output_${i}.txt"
main_output="test/case${i}/main_output_${i}.txt"
./generator > ${input}
./simple < ${input} > ${simple_output}
./main < ${input} > ${main_output}
diff -q ${simple_output} ${main_output}
done
rm main
rm generator
rm simple
|
Go
|
UTF-8
| 945 | 2.75 | 3 |
[
"MIT",
"BSD-3-Clause"
] |
permissive
|
package jose
import (
"crypto/rsa"
"crypto/x509"
"encoding/pem"
)
// RSAPrivateKey parses data as *rsa.PrivateKey
func RSAPrivateKey(data []byte) (*rsa.PrivateKey, error) {
input := pemDecode(data)
var err error
var key interface{}
if key, err = x509.ParsePKCS1PrivateKey(input); err != nil {
if key, err = x509.ParsePKCS8PrivateKey(input); err != nil {
return nil, err
}
}
return key.(*rsa.PrivateKey), nil
}
// RSAPublicKey parses data as *rsa.PublicKey
func RSAPublicKey(data []byte) (*rsa.PublicKey, error) {
input := pemDecode(data)
var err error
var key interface{}
if key, err = x509.ParsePKIXPublicKey(input); err != nil {
if cert, err := x509.ParseCertificate(input); err == nil {
key = cert.PublicKey
} else {
return nil, err
}
}
return key.(*rsa.PublicKey), nil
}
func pemDecode(data []byte) []byte {
if block, _ := pem.Decode(data); block != nil {
return block.Bytes
}
return data
}
|
Python
|
UTF-8
| 4,361 | 2.703125 | 3 |
[] |
no_license
|
import logging
import random
import os
import json
import time
import sys
from bs4 import BeautifulSoup
from urllib.request import urlopen
from flask import Flask, Response, request
# Grabber
class StaffbotGrabber():
__STAFF_URL = "https://www.lancaster.ac.uk/scc/about-us/people/"
def __init__(self, logger):
''' create a staffbot grabber '''
self.logger = logger
self.logger.info("Creating staffbot grabber | ")
self.__staff_list = []
self.__build_list()
self.logger.info("Created staffbot grabber | ok")
def __build_list(self, rebuild=False):
''' build the initial staff list '''
self.logger.info("Building Staff List")
webpage = None
try:
webpage = self.__get_webpage()
except:
if rebuild == True:
return 1
else:
time.sleep(10)
self.__build_list()
soup = BeautifulSoup(webpage, 'html.parser')
academic_html = soup.findAll('div', attrs={'data-categories':'academic'})
professional_html = soup.findAll('div', attrs={'data-categories':'professional'})
research_html = soup.findAll('div', attrs={'data-categories':'research'})
staff_html = academic_html + professional_html + research_html
staff_list_tmp = []
for member in staff_html:
member_img = member.find('img')
staff_list_tmp.append(
{
"name": member_img['alt'],
"img_url": member_img['data-src']
}
)
self.__staff_list = staff_list_tmp
self.logger.info("Staff list length | {}".format(len(self.__staff_list)))
return 0
def __get_webpage(self):
''' get the staff webpage '''
url = self.__STAFF_URL
content = urlopen(url).read()
return str(content)
def get(self, name=None):
''' get a staff member '''
if len(self.__staff_list) == 0:
return None
if not name == None:
for member in self.__staff_list:
if member.get("name") == name:
return member
return None
return random.choice(self.__staff_list)
def rebuild_list(self):
''' rebuild the staff list '''
return self.__build_list(rebuild=True)
# Setup
secret_key = os.environ['SECRET_KEY']
debug_mode = int(os.environ['DEBUG'])
if debug_mode > 0:
log_lvl = logging.DEBUG
else:
log_lvl = logging.ERROR
logging.basicConfig(stream=sys.stdout, level=log_lvl)
grabber_logger = logging.getLogger('StaffBot-Grabber')
staffbot_grabber = StaffbotGrabber(grabber_logger)
# API
logger = logging.getLogger('StaffBot-API')
API_VERSION = os.environ['API_VERSION']
app = Flask(__name__)
@app.route('/v'+str(API_VERSION)+'/get_member')
def get_member():
''' get a staff member '''
logger.info("Request for staff member info")
name = request.args.get('name', None)
if not name == None:
logger.info("Request searching for staff member " + name)
staff_member = staffbot_grabber.get(name=name)
if staff_member == None:
return Response(json.dumps({'Error': 'Staff member not found'}),
status=404,
mimetype='application/json')
return Response(json.dumps(staff_member),
status=200,
mimetype='application/json')
@app.route('/v'+str(API_VERSION)+'/rebuild')
def rebuild_list():
''' rebuild the list of staff members '''
logger.info("Request to rebuild stafflist")
key = request.args.get('key', None)
if not key == secret_key:
return Response(json.dumps({'Error': 'Invalid key'}),
status=403,
mimetype='application/json')
return_code = staffbot_grabber.rebuild_list()
if return_code == 0:
return Response(json.dumps({'Success': 'Stafflist rebuilt'}),
status=200,
mimetype='application/json')
return Response(json.dumps({'Error': 'Failed to rebuild list'}),
status=500,
mimetype='application/json')
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8080)
|
Python
|
UTF-8
| 1,508 | 4.21875 | 4 |
[] |
no_license
|
import random
# Create a deck of Cards and assign hands to players
class Deck(object):
def __init__(self):
self.reset()
def reset(self):
self.deck = []
suits =['Hearts','Clubs','Diamonds','Spades']
values =[2,3,4,5,6,7,8,9,10,'Jack', 'Queen','King','Ace']
for suit in suits:
for value in values:
self.deck.append(Card(value, suit))
def shuffle(self):
random.shuffle(self.deck)
def calculateValue(self, card):
if card.value == 'King' or 'Queen' or 'Jack':
value = 10
def deal(self, players, num):
for i in range(num):
for player in players:
player.hand.append(self.deck.pop())
class Card(object):
def __init__(self, value, suit):
self.suit = suit
self.value = value
class Player(object):
def __init__(self, name, hand):
self.name = name
self.hand = hand
a = Deck()
a.shuffle()
print 'After Shuffle:'
for card in a.deck:
print "{} of {}".format(card.value, card.suit)
a.reset()
print 'After Reset'
for card in a.deck:
print "{} of {}".format(card.value, card.suit)
# player1= Player('Player1')
# player2= Player('Player2')
# player3= Player('Player3')
# players = [player1, player2, player3]
# a.deal(players, 2)
# for player in players:
# print '*' *50
# print "{}'s hand contains:".format(player.name)
# for card in player.hand:
# print "{} of {}".format(card.value, card.suit)
|
C
|
UTF-8
| 4,741 | 2.8125 | 3 |
[
"Unlicense",
"LicenseRef-scancode-public-domain"
] |
permissive
|
/* 3D random walker animation
* $ cc -Ofast -o walk3d walk3d.c -lm
* $ ./walk3d | mpv --no-correct-pts --fps=60 -
* $ ./walk3d | x264 --fps 60 --frames 3600 -o walk3d.mp4 /dev/stdin
* https://redd.it/geka1q
* https://nullprogram.com/video/?v=walk3d
* This is free and unencumbered software released into the public domain.
*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define N 32
#define W 1024
#define H 1024
#define SCALE 25.0f
#define MAX 150
#define DELAY 25
#define PI 3.1415927f
static unsigned long long u32s;
static unsigned long u32(void)
{
return (u32s = u32s*0xfc5434fdb4a9e74d + 1) >> 32 & 0xffffffff;
}
static float rnd(float min, float max)
{
return ldexpf(u32(), -32)*(max - min) + min;
}
struct v2 { int x, y; };
struct v3 { float x, y, z; };
/* Orthographic projection of 3D point into the screen. */
static struct v2
project(struct v3 p, float scale, float az, float el)
{
float x = p.x*cosf(az) - p.y*sinf(az);
float y = p.x*sinf(az) + p.y*cosf(az);
return (struct v2){
roundf(scale*x + W/2),
roundf(scale*(y*sinf(el) + p.z*cosf(el)) + H/2)
};
}
static unsigned char buf[H][W][3];
static void clear(void) { memset(buf, 0, sizeof(buf)); }
static void
point(struct v2 p, long color)
{
if (p.x >= 0 && p.x < W && p.y >= 0 && p.y < H) {
buf[p.y][p.x][0] = color >> 16;
buf[p.y][p.x][1] = color >> 8;
buf[p.y][p.x][2] = color >> 0;
}
}
static void
line(struct v2 a, struct v2 b, long color)
{
int dx = abs(b.x - a.x);
int dy = abs(b.y - a.y);
int sx = b.x < a.x ? -1 : 1;
int sy = b.y < a.y ? -1 : 1;
if (dx > dy) {
int d = 2 * dy - dx;
struct v2 p = {0, a.y};
for (p.x = a.x; p.x != b.x; p.x += sx) {
point(p, color);
if (d > 0) {
p.y += sy;
d -= 2 * dx;
}
d += 2 * dy;
}
} else {
int d = 2 * dx - dy;
struct v2 p = {a.x, 0};
for (p.y = a.y; p.y != b.y; p.y += sy) {
point(p, color);
if (d > 0) {
p.x += sx;
d -= 2 * dy;
}
d += 2 * dx;
}
}
point(b, color);
}
static void
frame(void)
{
#define xstr(s) str(s)
#define str(s) #s
const char header[] = "P6\n" xstr(W) " " xstr(H) "\n255\n";
fwrite(header, sizeof(header) - 1, 1, stdout);
if (!fwrite(buf, sizeof(buf), 1, stdout)) exit(1);
}
static float
biasrnd(float v)
{
float bias = 0.1f;
float r = v + rnd(-1.0f, +1.0f);
if (v < 0.0f) {
r -= bias;
} else if (v > 0.0f) {
r += bias;
}
return r;
}
static void
animate(void)
{
struct {
long color;
struct v3 pos[MAX];
} points[N];
for (int i = 0; i < N; i++) {
points[i].color = u32()>>8 | 0x404040;
points[i].pos[0].x = 0;
points[i].pos[0].y = 0;
points[i].pos[0].z = 0;
for (int j = 1; j < MAX; j++) {
points[i].pos[j].x = biasrnd(points[i].pos[j-1].x);
points[i].pos[j].y = biasrnd(points[i].pos[j-1].y);
points[i].pos[j].z = biasrnd(points[i].pos[j-1].z);
}
}
float az = 0;
float daz = rnd(+0.005f, +0.02) * (u32()&1 ? -1 : 1);
float el = 0;
float del = rnd(0.0f, +0.005f) * (u32()&1 ? -1 : 1);
for (int n = 0; n < MAX*DELAY; n++) {
clear();
for (int i = 0; i < N; i++) {
struct v2 p = project(points[i].pos[0], SCALE, az, el);
for (int j = 1; j < n/DELAY; j++) {
struct v2 c = project(points[i].pos[j], SCALE, az, el);
line(p, c, points[i].color);
p = c;
}
struct v2 c = project(points[i].pos[n/DELAY], SCALE, az, el);
float t = n % DELAY / (float)DELAY;
struct v2 r = {
roundf(p.x + t*(c.x - p.x)),
roundf(p.y + t*(c.y - p.y))
};
line(p, r, points[i].color);
point((struct v2){r.x+1, r.y+0}, points[i].color);
point((struct v2){r.x-1, r.y+0}, points[i].color);
point((struct v2){r.x+0, r.y+1}, points[i].color);
point((struct v2){r.x+0, r.y-1}, points[i].color);
}
frame();
az = az*0.999f + daz;
daz += rnd(-0.0001, +0.0001);
el = el*0.999f + del;
del += rnd(-0.0001, +0.0001);
}
}
int
main(void)
{
#ifdef _WIN32
int _setmode(int, int);
_setmode(1, 0x8000); /* Set stdin/stdout to binary mode. */
#endif
u32s = time(0);
for (;;) {
animate();
u32s ^= clock();
}
}
|
Java
|
UTF-8
| 493 | 1.953125 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.example.weatherforecast.receive;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.example.weatherforecast.service.AutoUpdateService;
/**
* Created by misaki on 2016/7/4.
*/
public class AutoUpdateReceive extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent i=new Intent(context, AutoUpdateService.class);
context.startService(i);
}
}
|
Java
|
UTF-8
| 806 | 2.296875 | 2 |
[] |
no_license
|
package journey.android.backgroundlicker;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
/**
* Created by Machinatron on 2017-07-14.
*/
public class ExampleService extends IntentService {
private static final String TAG = "EXAMPLESERVICE";
public static Intent newIntent(Context context){
return new Intent(context, ExampleService.class);
}
public ExampleService() {
super(TAG);
}
@Override
protected void onHandleIntent(Intent intent) {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent,flags,startId);
}
}
|
TypeScript
|
UTF-8
| 2,110 | 2.53125 | 3 |
[
"Apache-2.0"
] |
permissive
|
class LunrIndexResource extends IndexResource {
constructor(name ? : string, base ? : string, index?: any) {
super(name, base, index);
}
protected restoreIndex(elasticlunr: any, callback) {
callback();
}
protected makeIndex(elasticlunr: any, callback) {
elasticlunr.tokenizer.setSeperator(/[\W]+/);
let index = elasticlunr(function () {
this.setRef('id');
this.addField('body');
this.addField('path');
this.addField('name');
this.saveDocument(false);
});
callback(index);
}
public initIndexEngine(callback) {
let self = this;
let elasticlunr = window['elasticlunr'];
if (this.getIndexEngine()) {
self.makeIndex(elasticlunr, callback);
}
else {
self.restoreIndex(elasticlunr, function(index) {
if (index) {
callback(index);
}
else {
self.makeIndex(elasticlunr, callback);
}
});
}
}
public searchResources(qry: string, callback) {
let indx = this.getIndexEngine();
let list = [];
let opts = {
expand: true,
bool: "AND"
};
let rv = indx.search(qry, opts);
for (let i = 0; i < rv.length; i++) {
let doc = rv[i];
let ref = doc['ref'];
let score = doc['score'];
if (score > 0) {
let res = new ObjectResource({'reference':ref, 'score':doc['score']}, ref);
list.push(res);
}
}
callback(list);
}
public indexTextData(text, callback) {
let name = this.baseName;
let path = this.getStoragePath();
let id = '/'+path;
let indx = this.getIndexEngine();
let doc = {
id:id,
name:name,
path:path,
body:text
};
indx.removeDoc(doc);
indx.addDoc(doc);
callback();
}
public removeResourcesFromIndex(name: string, callback) {
let path = this.getStoragePath(name);
let id = '/'+path;
let indx = this.getIndexEngine();
indx.removeDoc({id:id});
callback();
}
public saveIndexAsJSON() : string {
let indx = this.getIndexEngine();
return indx.toJSON();
}
}
|
Python
|
UTF-8
| 6,144 | 2.71875 | 3 |
[] |
no_license
|
import json
class Architecture:
def __init__(self, archJson, patterns):
# initialize the architectures
with open(archJson, "r") as f:
arch = json.load(f)
self.services = []
for ms in arch["microservices"]:
self.services.append(Microservice(ms))
for ms in self.services:
for op in ms.operations:
op.init_dependencies(self.services)
self.patterns = patterns
# set circuit breakers, based on patterns parameter
# TODO: Use architectural model, instead of patterns parameter
# TODO: Clarify how to use circuit breakers, if dependency does not have 100% demand
for i in range(len(self.services)):
for j in range(len(self.services[i].operations)):
if self.services[i].operations[j].name + 'true' in patterns:
cb = CircuitBreaker(arch["microservices"][i]['operations'][j]['circuitBreaker'])
ops = []
ops.append(self.services[i].operations[j])
seen = set()
seen.add(self.services[i].operations[j])
# each operation has list of circuit breakers
# this list contains all circuit breakers of operations that (indirectly) use this operation
# example: a1 has circuit breaker cb, a1 depends on b1 and c1, b1 depends on d1
# a1.circuitbreaker = []
# b1.circuitbreaker = [cb]
# c1.circuitbreaker = [cb]
# d1.circuitbreaker = [cb]
# TODO: For use in live system, this has to be changed. Currently this assumes that all dependencies are used all the time.
while len(ops) > 0:
operation = ops.pop()
for dep in operation.dependencies:
if dep.operation not in seen:
ops.append(dep.operation)
seen.add(dep.operation)
dep.operation.circuitbreaker.append(cb)
def get_operations(self):
"""
Returns all operations.
"""
operations = []
for service in self.services:
for operation in service.operations:
operations.append(operation)
return operations
def get_incoming_dependencies(self,operation):
"""
Returns all incoming dependencies for a service, except a1,a2
"""
# TODO: Remove the a1,a2 bit for use in live system. Add parameter for exclusion?
operations = set()
for service in self.services:
for op in service.operations:
for dep in op.dependencies:
if dep.operation.name == operation.name and op.name not in ['a1','a2']:
operations.add(op)
return list(operations)
def to_string(self):
results = self.patterns + "\n"
results = results + "Services \n"
for service in self.services:
results = results + service.name + "\n"
for operation in service.operations:
if operation.circuitbreaker:
results = results + operation.name + " " + str(operation.circuitbreaker.rollingwindow) + ", "
else:
results = results + operation.name + ", "
for dep in operation.dependencies:
results = results + dep.operation.name + " "
results = results + "\n"
return results
class Microservice:
def __init__(self,ms):
self.name = ms['name']
self.instances = ms['instances']
self.patterns = ms['patterns']
self.capacity = ms['capacity']
self.operations = []
for op in ms['operations']:
self.operations.append(Operation(self,op))
class Pattern:
def __init__(self,p):
self.name = p['name']
self.arguments = []
for arg in p['arguments']:
self.arguments.append(arg)
class Operation:
def __init__(self,ms,operation):
self.service = ms
self.name = operation['name']
self.demand = operation['demand']
self.circuitbreaker = []
self.dependencies = []
for dp in operation['dependencies']:
self.dependencies.append(Dependency(dp))
def init_dependencies(self,mss):
for dp in self.dependencies:
dp.update(mss)
class CircuitBreaker:
def __init__(self,cb):
if cb != None:
self.rollingwindow = cb['rollingWindow']
self.requestvolumethreshold = cb['requestVolumeThreshold']
self.errorthresholdpercentage = cb['errorThresholdPercentage']
self.timeout = cb['timeout']
self.sleepwindow = cb['sleepWindow']
else:
self.rollingWindow = None
self.requestvolumethreshold = None
self.errorthresholdpercentage = None
self.timeout = None
self.sleepwindow = None
class Dependency:
def __init__(self,dp):
self.service = dp['service'] # TODO get the correct service from the architecture
self.operation = dp['operation'] # TODO get the correct operation from the architecture
self.probability = dp['probability']
def update(self,mss):
try:
self.find_op(self.service,self.operation,mss)
except Exception as error:
print("Caught this exception: " + repr(error))
def find_op(self,name_ms,name_op,mss):
for ms in mss:
if ms.name == name_ms:
self.service = ms
for op in ms.operations:
if op.name ==name_op:
self.operation = op
return op
raise Exception("Couldnt find the operation: " + name_op)
raise Exception("Couldn't find the microservice: " + name_ms)
|
Python
|
UTF-8
| 5,451 | 2.90625 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
"""Interface to Baxter-King bandpass filter from `statsmodels`.
Interfaces `bk_filter` from `statsmodels.tsa.filters`.
"""
# copyright: sktime developers, BSD-3-Clause License (see LICENSE file)
__author__ = ["klam-data", "pyyim", "mgorlin"]
__all__ = ["BKFilter"]
import pandas as pd
from sktime.transformations.base import BaseTransformer
class BKFilter(BaseTransformer):
"""Filter a times series using the Baxter-King filter.
This is a wrapper around the `bkfilter` function from `statsmodels`.
(see `statsmodels.tsa.filters.bk_filter.bkfilter`).
The Baxter-King filter is intended for economic and econometric time series
data and deals with the periodicity of the business cycle. Applying their
band-pass filter to a series will produce a new series that does not contain
fluctuations at a higher or lower frequency than those of the business cycle.
Baxter-King follow Burns and Mitchell's work on business cycles, which suggests
that U.S. business cycles typically last from 1.5 to 8 years.
Parameters
----------
low : float
Minimum period for oscillations. Baxter and King recommend a value of 6
for quarterly data and 1.5 for annual data.
high : float
Maximum period for oscillations. BK recommend 32 for U.S. business cycle
quarterly data and 8 for annual data.
K : int
Lead-lag length of the filter. Baxter and King suggest a truncation
length of 12 for quarterly data and 3 for annual data.
Notes
-----
Returns a centered weighted moving average of the original series.
References
----------
Baxter, M. and R. G. King. "Measuring Business Cycles: Approximate
Band-Pass Filters for Economic Time Series." *Review of Economics and
Statistics*, 1999, 81(4), 575-593.
Examples
--------
>>> from sktime.transformations.series.bkfilter import BKFilter # doctest: +SKIP
>>> import pandas as pd # doctest: +SKIP
>>> import statsmodels.api as sm # doctest: +SKIP
>>> dta = sm.datasets.macrodata.load_pandas().data # doctest: +SKIP
>>> index = pd.date_range(start='1959Q1', end='2009Q4', freq='Q') # doctest: +SKIP
>>> dta.set_index(index, inplace=True) # doctest: +SKIP
>>> bk = BKFilter(6, 24, 12) # doctest: +SKIP
>>> cycles = bk.fit_transform(X=dta[['realinv']]) # doctest: +SKIP
"""
_tags = {
"scitype:transform-input": "Series",
# what is the scitype of X: Series, or Panel
"scitype:transform-output": "Series",
# what scitype is returned: Primitives, Series, Panel
"scitype:instancewise": True, # is this an instance-wise transform?
"univariate-only": False, # can the transformer handle multivariate X?
"X_inner_mtype": "np.ndarray", # which mtypes do _fit/_predict support for X?
# this can be a Panel mtype even if transform-input is Series, vectorized
"y_inner_mtype": "None", # which mtypes do _fit/_predict support for y?
"requires_y": False, # does y need to be passed in fit?
"enforce_index_type": [
pd.RangeIndex
], # index type that needs to be enforced in X/y
"fit_is_empty": True, # is fit empty and can be skipped? Yes = True
"transform-returns-same-time-index": False,
# does transform return have the same time index as input X
"capability:unequal_length": True,
# can the transformer handle unequal length time series (if passed Panel)?
"handles-missing-data": False, # can estimator handle missing data?
"remember_data": False, # whether all data seen is remembered as self._X
"python_dependencies": "statsmodels",
}
def __init__(
self,
low=6,
high=32,
K=12,
):
self.low = low
self.high = high
self.K = K
super().__init__()
def _transform(self, X, y=None):
"""Transform X and return a transformed version.
private _transform containing core logic, called from transform
Parameters
----------
X : array_like
A 1 or 2d ndarray. If 2d, variables are assumed to be in columns.
Returns
-------
transformed cyclical version of X
"""
from statsmodels.tsa.filters.bk_filter import bkfilter
kwargs = {"low": self.low, "high": self.high, "K": self.K}
return bkfilter(X, **kwargs)
@classmethod
def get_test_params(cls, parameter_set="default"):
"""Return testing parameter settings for the estimator.
Parameters
----------
parameter_set : str, default="default"
Name of the set of test parameters to return, for use in tests. If no
special parameters are defined for a value, will return `"default"` set.
There are currently no reserved values for transformers.
Returns
-------
params : dict or list of dict, default = {}
Parameters to create testing instances of the class
Each dict are parameters to construct an "interesting" test instance, i.e.,
`MyClass(**params)` or `MyClass(**params[i])` creates a valid test instance.
`create_test_instance` uses the first (or only) dictionary in `params`
"""
params1 = {"low": 5, "high": 24, "K": 4}
params2 = {}
return [params1, params2]
|
Java
|
UTF-8
| 7,021 | 3.03125 | 3 |
[] |
no_license
|
package com.hotstar.fastival;
/* IMPORTANT: Multiple classes and nested static classes are supported */
/*
* uncomment this if you want to read input.
//imports for BufferedReader
import java.io.BufferedReader;
import java.io.InputStreamReader;
//import for Scanner and other utility classes
import java.util.*;
*/
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Map;
// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
/**
* https://www.hackerearth.com/challenge/hiring/hotstar-java-hiring-challenge/algorithm/suzakus-festivals-14dacd7c/
* @author evfandroid
*2
6
B 20
A 2
A 10
A 10
B 30
A 30
3
abc 10
xyz 15
oop 8
*/
public class TestClass {
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String readLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
OutputWriter out = new OutputWriter(System.out);
int T = in.readInt();
StringBuilder output = new StringBuilder();
while (T-->0) {
int N = in.readInt();
Map<String, List<Integer>> festivalMap = new HashMap<>();
for (int i=0;i<N;i++) {
String festival = in.readString();
int spending = in.readInt();
if (!festivalMap.containsKey(festival)) {
List<Integer> spendList = new ArrayList<>();
spendList.add(spending);
festivalMap.put(festival, spendList);
}
else {
List<Integer> spendList = festivalMap.get(festival);
spendList.add(spending);
festivalMap.put(festival, spendList);
}
}
long maxFestivalSpending = Long.MIN_VALUE;
String maxFestival= "";
for (Map.Entry<String, List<Integer>> entry : festivalMap.entrySet()) {
String festival = entry.getKey();
List<Integer> festiValSpending = entry.getValue();
Collections.sort(festiValSpending);
if (festiValSpending.size() < 3) {
long temp=0;
for (int i=0;i<festiValSpending.size();i++) {
temp+=festiValSpending.get(i);
}
if (temp > maxFestivalSpending) {
maxFestivalSpending = temp;
maxFestival = festival;
}
else if (temp == maxFestivalSpending) {
if ((festival.compareTo(maxFestival)) <0) {
maxFestival = festival;
maxFestivalSpending = temp;
}
}
}
else {
long temp = 0;
for (int i=festiValSpending.size()-3;i<festiValSpending.size();i++) {
temp+=festiValSpending.get(i);
}
if (temp > maxFestivalSpending) {
maxFestivalSpending = temp;
maxFestival = festival;
}
else if (temp == maxFestivalSpending) {
if ((festival.compareTo(maxFestival)) <0) {
maxFestival = festival;
maxFestivalSpending = temp;
}
}
}
}
output.append(maxFestival).append(" ").append(maxFestivalSpending).append("\n");
}
out.print(output);
out.close();
}
}
|
C#
|
UTF-8
| 1,507 | 2.953125 | 3 |
[] |
no_license
|
using System;
namespace TextToSeqDiag
{
public sealed class Position
{
public PositionKind Kind { get; private set; }
public int Column { get; private set; }
public int Column2 { get; private set; }
public int Row { get; private set; }
public static Position Message(int source, int destination, int row)
{
if (source < 0) throw new ArgumentOutOfRangeException();
if (row < 0) throw new ArgumentOutOfRangeException();
if (source >= destination) throw new ArgumentOutOfRangeException();
return new Position
{
Column = source,
Column2 = destination,
Row = row,
Kind = PositionKind.Message,
};
}
public static Position OneColumn(int column, int row)
{
if (column < 0) throw new ArgumentOutOfRangeException();
if (row < 0) throw new ArgumentOutOfRangeException();
return new Position
{
Column = column,
Row = row,
Kind = PositionKind.OneColumn
};
}
public static Position Body(int column)
{
if (column < 0) throw new ArgumentOutOfRangeException();
return new Position
{
Column = column,
Kind = PositionKind.Body
};
}
}
}
|
C#
|
UTF-8
| 8,034 | 2.875 | 3 |
[] |
no_license
|
using UnityEngine;
using System.Collections;
using Mirror;
/**
* Manages trading between players.
* Player who is currently having a turn may be able to ask for a certain resouce.
* Other players may send offers in exchange for that resource (one at a time for networking ease).
*
* Process:
* - A player sends a request to another player (one of the players must at least be the player who is trading)
* - As soon as the player accepts the trade offer, the trade begins. (trading is set to true)
* - Once the trade begins, players can now set values for how many resources they each wish to offer (setting the receiver/offerer resource values)
* - If each player is satisfied, they can then attempt to each accept the trades (receiverAccept and offererAccept set to true)
* - If both players are satisfied, then they must both press the trade button (receiverWantsToTrade and offererWantsToTrade set to true)
* - The trade then resolves, and each player exchanges resources.
*/
public class PlayerTradeManager : NetworkBehaviour
{
public static PlayerTradeManager Instance { get; private set; }
private void Awake()
{
if (Instance == null)
{
Instance = this;
}
}
[SyncVar]
public bool trading = false; // This flag is enabled if there is a trade in progress.
[Header("Receiver")]
[SyncVar]
public bool receiverAccept = false;
[SyncVar]
public string receiverId = "";
[SyncVar]
public int receiverLumber = 0;
[SyncVar]
public int receiverWool = 0;
[SyncVar]
public int receiverGrain = 0;
[SyncVar]
public int receiverBrick = 0;
[SyncVar]
public int receiverOre = 0;
[Header("Offerer")]
[SyncVar]
public bool offererAccept = false;
[SyncVar]
public string offererId = "";
[SyncVar]
public int offererLumber = 0;
[SyncVar]
public int offererWool = 0;
[SyncVar]
public int offererGrain = 0;
[SyncVar]
public int offererBrick = 0;
[SyncVar]
public int offererOre = 0;
public void MakeTradeOffer(string offererId, int lumber, int wool, int grain, int brick, int ore)
{
this.offererId = offererId;
this.offererLumber = lumber;
this.offererWool = wool;
this.offererGrain = grain;
this.offererBrick = brick;
this.offererOre = ore;
}
/**
* Accept the trade as a receiving player.
*/
public void AcceptAsReceiver()
{
this.receiverAccept = true;
}
/**
* Unaccept the trade as a receiving player.
*/
public void UnAcceptAsReceiver()
{
this.receiverAccept = false;
}
/**
* Accept the trade as an offering player.
*/
public void AcceptAsOfferer()
{
this.offererAccept = true;
}
/**
* Unaccept the trade as an offering player.
*/
public void UnAcceptAsOfferer()
{
this.offererAccept = false;
}
/**
* Increase or decrease a resource by a certain amount.
*/
public void ChangeTradeAmount(string playerId, int resourceType, int amount)
{
Player player = GameManager.Instance.GetPlayerById(playerId);
// Check if player is offerer or receiver
if (playerId.Equals(receiverId))
{
// This player is the receiver. Add resource based on type, and if the transaction is possible.
switch((ResourceType)resourceType)
{
case ResourceType.Lumber:
if(receiverLumber + amount <= player.GetResourceCount((ResourceType)resourceType)
&& receiverLumber + amount >= 0)
{
receiverLumber += amount;
}
break;
case ResourceType.Wool:
if (receiverWool + amount <= player.GetResourceCount((ResourceType)resourceType)
&& receiverWool + amount >= 0)
{
receiverWool += amount;
}
break;
case ResourceType.Grain:
if (receiverGrain + amount <= player.GetResourceCount((ResourceType)resourceType)
&& receiverGrain + amount >= 0)
{
receiverGrain += amount;
}
break;
case ResourceType.Brick:
if (receiverBrick + amount <= player.GetResourceCount((ResourceType)resourceType)
&& receiverBrick + amount >= 0)
{
receiverBrick += amount;
}
break;
case ResourceType.Ore:
if (receiverOre + amount <= player.GetResourceCount((ResourceType)resourceType)
&& receiverOre + amount >= 0)
{
receiverOre += amount;
}
break;
}
} else if (playerId.Equals(offererId))
{
// This player is the offerer. Add resource based on type, and if the transaction is possible.
switch ((ResourceType)resourceType)
{
case ResourceType.Lumber:
if (offererLumber + amount <= player.GetResourceCount((ResourceType)resourceType)
&& offererLumber + amount >= 0)
{
offererLumber += amount;
}
break;
case ResourceType.Wool:
if (offererWool + amount <= player.GetResourceCount((ResourceType)resourceType)
&& offererWool + amount >= 0)
{
offererWool += amount;
}
break;
case ResourceType.Grain:
if (offererGrain + amount <= player.GetResourceCount((ResourceType)resourceType)
&& offererGrain + amount >= 0)
{
offererGrain += amount;
}
break;
case ResourceType.Brick:
if (offererBrick + amount <= player.GetResourceCount((ResourceType)resourceType)
&& offererBrick + amount >= 0)
{
offererBrick += amount;
}
break;
case ResourceType.Ore:
if (offererOre + amount <= player.GetResourceCount((ResourceType)resourceType)
&& offererOre + amount >= 0)
{
offererOre += amount;
}
break;
}
} else
{
// This player is not authorized to make a trade. Do nothing.
}
}
/**
* Resets confirmation for trade for all players.
*/
public void UnAcceptAll()
{
this.receiverAccept = false;
this.offererAccept = false;
}
public void ResetTrade()
{
this.trading = false;
this.receiverAccept = false;
this.offererAccept = false;
this.receiverId = "";
this.receiverBrick = 0;
this.receiverGrain = 0;
this.receiverLumber = 0;
this.receiverOre = 0;
this.receiverWool = 0;
this.offererId = "";
this.offererBrick = 0;
this.offererGrain = 0;
this.offererLumber = 0;
this.offererOre = 0;
this.offererWool = 0;
}
public bool IsPlayerOffering(string id)
{
return offererId.Equals(id) && trading;
}
public bool IsPlayerReceiving(string id)
{
return receiverId.Equals(id) && trading;
}
public bool ShouldTradeResolve()
{
return receiverAccept && offererAccept;
}
}
|
C++
|
UTF-8
| 12,534 | 3.40625 | 3 |
[] |
no_license
|
//
// Created by Sohini Roy on 5/29/20.
//
#ifndef TREES_BST_H
#define TREES_BST_H
#include <iostream>
#include <vector>
#include <queue>
#include "BSTNode.h"
using namespace std;
namespace trees {
enum Direction {
Left,
Right,
};
template<class T>
class BST {
private:
void traversingInOrder(BSTNode<T> *node, std::vector<T>& v);
void traversingPreOrder(BSTNode<T> *node, std::vector<T>& v);
void traversingPostOrder(BSTNode<T> *node, std::vector<T>& v);
trees::BSTNode<T> *findParentforAdd(const T value);
BSTNode<T>* getMin(BSTNode<T> *node);
BSTNode<T>* getMax(trees::BSTNode<T> *node);
int getHeight(BSTNode<T>* nd);
int getSize(BSTNode<T>* nd);
public:
BSTNode<T> *root;
BST<T>();
BST<T>(std::initializer_list<T> initializerList);
BST(vector<T>preOrdList, vector<T>inOrdLst);
//~BST();
int size();
int height();
bool isLeaf(BSTNode<T> *nd);
bool isLeftChild(BSTNode<T>* nd);
bool isRightChild(BSTNode<T>* nd);
void addNode(const T value);
virtual void addNode(BSTNode<T> *node);
BSTNode<T>* find(const T value);
BSTNode<T>* successor(const T value);
BSTNode<T>* predecessor(const T value);
BSTNode<T>* min();
BSTNode<T>* max();
void leftRotate(const T value);
void rightRotate(const T value);
void rotateNode(T value, Direction dir);
void deleteNode(T value);
vector<T> preOrderTraverse();
vector<T> inOrderTraverse();
vector<T> postOrderTraverse();
vector<T> levelOrderTraverse();
//T lessThan(const T value);
//int kThSmallest(int K, trees::BST<T> tree);
//vector<T> zigzagLevelOrderTraverse();
//void deleteTree(BSTNode<T> *node);
};
}
template<class T>
trees::BST<T>::BST() {
root = nullptr;
}
template<class T>
trees::BST<T>::BST(initializer_list<T> initializerList) {
root = nullptr;
for (auto x : initializerList) {
addNode(x);
}
}
template<class T>
trees::BST<T>::BST(vector<T> preOrdList, vector<T> inOrdLst) {
preOrdList = preOrderTraverse();
inOrdLst = inOrderTraverse();
}
template<class T>
bool trees::BST<T>::isLeaf(trees::BSTNode<T> *nd) {
return nd != nullptr &&
nd->right == nullptr &&
nd->left == nullptr;
}
template<class T>
trees::BSTNode<T> *trees::BST<T>::find(const T value) {
BSTNode<T> *current = root;
while (current != nullptr) {
if (current->data == value) {
return current;
} else if (current->data > value) {
current = current->left;
} else {
current = current->right;
}
}
return nullptr;
}
template <class T>
trees::BSTNode<T> *trees::BST<T>::findParentforAdd(const T value) {
BSTNode<T> *current = root;
BSTNode<T> *par = nullptr;
while (current != nullptr) {
if (current->data > value) {
par = current;
current = current->left;
} else if (current->data < value) {
par = current;
current = current->right;
}
}
return par;
}
template<class T>
void trees::BST<T>::addNode(const T value) {
if (root == nullptr) {
root = new BSTNode<T>(value);
} else {
BSTNode<T> *current = root;
BSTNode<T> *par = findParentforAdd(value);
if (par->data < value) {
par->right = new BSTNode<T>(value);
par->right->parent = par;
} else if (par->data > value) {
par->left = new BSTNode<T>(value);
par->left->parent = par;
} else {
cout << "Cannot handle duplicate values" << endl;
}
}
}
template<class T>
void trees::BST<T>::addNode(BSTNode <T> *node) {
if (root == nullptr) {
root = node;
} else {
BSTNode<T> *current = root;
BSTNode<T> *par = findParentforAdd(node->data);
if (par->data < node->data) {
par->right = node;
par->right->parent = par;
} else if (par->data > node->data) {
par->left = node;
par->left->parent = par;
} else {
cout << "Cannot handle duplicate values" << endl;
}
}
}
template<class T>
trees::BSTNode<T> *trees::BST<T>::getMin(trees::BSTNode<T> *node) {
BSTNode<T> *current = node;
while (current != nullptr) {
if (current->left == nullptr) {
return current;
} else {
current = current->left;
}
}
return nullptr;
}
template<class T>
trees::BSTNode<T> *trees::BST<T>::getMax(trees::BSTNode<T> *node) {
BSTNode<T> *current = node;
while (current != nullptr) {
if (current->right == nullptr) {
return current;
} else {
current = current->right;
}
}
return nullptr;
}
template<class T>
trees::BSTNode<T> *trees::BST<T>::min() {
return getMin(root);
}
template<class T>
trees::BSTNode<T> *trees::BST<T>::max() {
return getMax(root);
}
template<class T>
vector<T> trees::BST<T>::preOrderTraverse() {
std::vector<T> v;
traversingPreOrder(root, v);
return v;
}
template<class T>
vector<T> trees::BST<T>::inOrderTraverse() {
std::vector<T> v;
traversingInOrder(root, v);
return v;
}
template<class T>
vector<T> trees::BST<T>::postOrderTraverse() {
std::vector<T> v;
traversingPostOrder(root, v);
return v;
}
template<class T>
void trees::BST<T>::traversingInOrder(trees::BSTNode<T> *node, vector<T> &v) {
if (node != nullptr) {
traversingInOrder(node->left, v);
v.push_back(node->data);
traversingInOrder(node->right, v);
}
}
template<class T>
void trees::BST<T>::traversingPreOrder(trees::BSTNode<T> *node, vector<T> &v) {
if (node != nullptr) {
v.push_back(node->data);
traversingPreOrder(node->left, v);
traversingPreOrder(node->right, v);
}
}
template<class T>
void trees::BST<T>::traversingPostOrder(trees::BSTNode<T> *node, vector<T> &v) {
if (node != nullptr) {
traversingPostOrder(node->left, v);
traversingPostOrder(node->right, v);
v.push_back(node->data);
}
}
template<class T>
vector<T> trees::BST<T>::levelOrderTraverse() {
queue<BSTNode<T>*> Q;
Q.push(root);
vector<T> v;
while (Q.size() != 0) {
BSTNode<T>* current = Q.front();
Q.pop();
v.push_back(current->data);
if (current->left != nullptr) {
Q.push(current->left);
}
if (current->right != nullptr) {
Q.push(current->right);
}
}
return v;
}
template<class T>
trees::BSTNode<T> *trees::BST<T>::predecessor(const T value) {
BSTNode<T> *node = find(value);
if (node == nullptr) {
return node;
}
if (node->left != nullptr) {
return getMin(node->left);
} else {
while (node != nullptr && node->parent != nullptr && node->parent->left == node) {
node = node->parent;
}
}
return node->parent;
}
template<class T>
trees::BSTNode<T> *trees::BST<T>::successor(const T value) {
BSTNode<T> *node = find(value);
if (node == nullptr) {
return node;
}
if (node->right != nullptr) {
return getMin(node->right);
} else {
while (node != nullptr && node->parent != nullptr && node->parent->right == node) {
node = node->parent;
}
}
return node->parent;
}
template<class T>
int trees::BST<T>::getSize(trees::BSTNode<T>* nd) {
BSTNode<T>* current = nd;
if (current == nullptr) {
return 0;
} else {
return getSize(current->left) + getSize(current->right) + 1;
}
}
template<class T>
int trees::BST<T>::size() {
return getSize(root);
}
template<class T>
int trees::BST<T>::getHeight(trees::BSTNode<T> *nd) {
BSTNode<T>* current = nd;
if (current == nullptr) {
return 0;
} else {
int left = getHeight(current->left);
int right = getHeight(current->right);
if (left > right) {
return left + 1;
} else {
return right + 1;
}
}
}
template<class T>
int trees::BST<T>::height() {
return getHeight(root) - 1;
}
template<class T>
void trees::BST<T>::deleteNode(T value) {
BSTNode<T>* current = find(value);
if (current == nullptr) {
return;
}
if (current->left == nullptr && current->right == nullptr) {
if (current == current->parent->right) {
current->parent->right = nullptr;
} else {
current->parent->left = nullptr;
}
delete current;
} else if ((current->left == nullptr && current->right != nullptr) ||
(current->left != nullptr && current->right == nullptr)) {
if (current->left == nullptr && current->right != nullptr) {
if (current == current->parent->right) {
current->parent->right = current->right;
}
else {
current->parent->left = current->right;
}
} else {
if (current == current->parent->left) {
current->parent->left = current->left;
} else {
current->parent->right = current->left;
}
}
delete current;
} else {
BSTNode<T>* success = successor(current->data);
if (success->left == nullptr && success->right == nullptr) {
current->data = success->data;
current->right = nullptr;
} else {
if (success == success->parent->right) {
success->parent->right = success->right;
} else {
success->parent->left = success->right;
}
current->data = success->data;
}
}
}
template<class T>
void trees::BST<T>::rightRotate(const T value) {
BSTNode<T> *node = find(value);
if (node == nullptr) {
return;
}
if (isLeaf(node)) {
return;
} else {
BSTNode<T> *par = node->parent;
if (par == nullptr) {
if (node->left != nullptr) {
BSTNode<T> *leftNode = node->left;
node->left = leftNode->right;
root = leftNode;
root->right = node;
node->parent = root;
}
}
}
}
template<class T>
void trees::BST<T>::leftRotate(const T value) {
BSTNode<T> *node = find(value);
if (node == nullptr) {
return;
}
if (isLeaf(node)) {
return;
} else {
BSTNode<T> *par = node->parent;
if (par == nullptr) {
if (node->right != nullptr) {
BSTNode<T> *rightNode = node->right;
node->right = rightNode->left;
root = rightNode;
root->left = node;
node->parent = root;
}
}
}
}
template<class T>
void trees::BST<T>::rotateNode(T value, Direction dir){
//Find the node corresponding to the value supplied
BSTNode<T>* nodeToRotate = find(value);
//Can't do much if value is not found in the tree
if(nodeToRotate == nullptr) {
return;
}
if((dir == Right && nodeToRotate->left == nullptr) || (dir == Left && nodeToRotate->right == nullptr)) {
return;
}
BSTNode<T>* newParent = (dir == Left)?nodeToRotate->right:nodeToRotate->left;
BSTNode<T>* grandParent = nodeToRotate->parent;
if(grandParent) {
if(isLeftChild(nodeToRotate)) {
grandParent->left = newParent;
}
else {
grandParent->right = newParent;
}
newParent->parent = grandParent;
}
else {
root = newParent;
}
if(dir == Left){
nodeToRotate->right = newParent->left;
newParent->left = nodeToRotate;
}
else {
nodeToRotate->left = newParent->right;
newParent->right = nodeToRotate;
}
nodeToRotate->parent = newParent;
if(newParent != nullptr)
newParent->parent = grandParent;
return;
}
template<class T>
bool trees::BST<T>::isLeftChild(trees::BSTNode<T> *nd) {
return (nd != nullptr && (nd->parent->left == nd));
}
template<class T>
bool trees::BST<T>::isRightChild(trees::BSTNode<T> *nd) {
return (nd != nullptr && (nd->parent->right == nd));
}
#endif //TREES_BST_H
|
Markdown
|
UTF-8
| 1,106 | 2.578125 | 3 |
[
"Apache-2.0"
] |
permissive
|
# Prometheus in a Container
Source code for [hiveco/prometheus](https://hub.docker.com/r/hiveco/prometheus). This image is designed to be an extremely thin wrapper around the official `prom/prometheus` image, providing support for supplying command line arguments in environment variables. See [#504](https://github.com/prometheus/alertmanager/issues/504) for details on why the Prometheus authors chose not to include this functionality in the official image.
Environment variables given to `docker run` that are prefixed with `PROM_` are converted into command line arguments to Prometheus. Underscores are converted to periods and double-underscores to dashes.
Examples:
* To set `--log.level=error`, add the option `-e PROM_LOG_LEVEL=error`
* To set `--web.external-url=http://localhost`, add the option `-e PROM_WEB_EXTERNAL__URL=http://localhost`.
See also [hiveco/alertmanager](https://hub.docker.com/r/hiveco/alertmanager), the Alertmanager sister image to this one.
> Another project by [Hive Collective](http://hivecollective.co). *DevOps-on-Demand, so you can focus on shipping features.*
|
Markdown
|
UTF-8
| 647 | 3.328125 | 3 |
[
"MIT"
] |
permissive
|
# has-trailing-slash  [](https://badge.fury.io/js/has-trailing-slash) 
Checks if a string has a trailing slash
## Installation
with [npm](https://npmjs.org/):
$ npm install has-trailing-slash
## API
### `hasTrailingSlash(str)`
Checks if `str` ends with `/`
## Example
```js
const hasTrailingSlashes = require('has-trailing-slash');
expect(hasTrailingSlashes('http://google.com/')).to.be.true;
```
## License
MIT
|
JavaScript
|
UTF-8
| 293 | 2.65625 | 3 |
[] |
no_license
|
var inputField = document.querySelector('.post-content'),
form = document.querySelector('#post-form')
inputField.addEventListener('keydown', function (e) {
if (e.key == 'Enter') {
if (!e.shiftKey) {
e.preventDefault();
form.submit();
}
}
})
|
Java
|
UTF-8
| 1,506 | 2.125 | 2 |
[] |
no_license
|
/*
* Copyright (C) 2009-2013 Typesafe Inc. <http://www.typesafe.com>
*/
package play.db.ebean;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.TxCallable;
import play.libs.F;
import play.mvc.Action;
import play.mvc.Http.Context;
import play.mvc.Result;
/**
* Wraps an action in an Ebean transaction.
*/
public class TransactionalAction extends Action<Transactional> {
public F.Promise<Result> call(final Context ctx) throws Throwable {
Action<Transactional> action = new Action<Transactional>() {
@Override
public F.Promise<Result> call(Context context) throws Throwable {
return Ebean.execute(new TxCallable<F.Promise<Result>>() {
public F.Promise<Result> call() {
try {
return delegate.call(ctx);
} catch (RuntimeException e) {
throw e;
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
});
}
};
Action<?> previousDelegate = this;
Action<?> lastDelegate = delegate;
while (lastDelegate.delegate != null) {
previousDelegate = lastDelegate;
lastDelegate = lastDelegate.delegate;
}
action.delegate = lastDelegate;
previousDelegate.delegate = action;
return delegate.call(ctx);
}
}
|
Markdown
|
UTF-8
| 683 | 3.03125 | 3 |
[
"CC0-1.0"
] |
permissive
|
# prepend
Edit a file to insert lines on head.
See [help.txt](./src/help.txt).
## Installation
You need cargo (Rust build tool).
```sh
cargo install --git https://github.com/vain0x/prepend
```
## Motivation
Since pipe-like works concurrently, this doesn't work as you expected:
```sh
# a.txt has some data.
echo world >a.txt
# Prepend to a.txt. (NOT WORK)
echo hello | cat a.txt - >a.txt
# See what happened.
cat a.txt
#=> hello
```
Because `>a.txt` truncates all data from `a.txt` first. `cat` opens it and reads nothing.
## With prepend command
```sh
echo world >a.txt
prepend a.txt hello
cat a.txt
#=> hello
# world
```
## Examples
See [tests/data](tests/data).
|
Python
|
UTF-8
| 426 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
from Biscuit.utils.version import Version
def test_version():
v1 = Version(0, 1, 2, 0)
v2 = Version(1, 2, 1, 1)
v3 = Version(1, 11, 2, 3)
v4 = Version.from_repr('1.3')
v5 = Version.from_repr('v2.9.31')
v6 = Version.from_repr('1.11.2-b3')
assert str(v1) == '0.1.2'
assert str(v2) == '1.2.1-b1'
assert v2 > v1
assert v3 >= v1
assert v4 < v5
assert v6 <= v3
assert v3 == v6
|
C#
|
UTF-8
| 900 | 2.625 | 3 |
[] |
no_license
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Enemy type: Skeleton archer
/// </summary>
public class Archer : Enemy {
public float arrowCooldown;
public GameObject arrowPrefab;
bool canFire = false;
void Start() {
StartCoroutine (ArrowCooldownCoroutine (Random.Range (1, 3)));
}
void FixedUpdate () {
if (canFire) {
Vector2 firePosition = transform.position;
firePosition.y += 1.5f;
Instantiate(arrowPrefab, firePosition, Quaternion.AngleAxis(90, Vector3.forward));
// Disallow attacking for the duration of the cooldown
canFire = false;
StartCoroutine(ArrowCooldownCoroutine (5));
}
}
protected override void Die () {
base.Die ();
ScoreManager.instance.archersDefeated++;
}
IEnumerator ArrowCooldownCoroutine (float cooldown) {
yield return new WaitForSeconds (cooldown);
canFire = true;
}
}
|
Python
|
UTF-8
| 770 | 3.28125 | 3 |
[] |
no_license
|
print("Starting")
import math
MAX = 10**15
def D(x):
return 3*x
def U(x):
return (3*x-2)/4
def d(x):
return (3*x+1)/2
def string(code):
x = 1
for i in range(len(code)-1,-1,-1):
while True:
temp = x
if code[i] == 'D':
temp = D(x)
if code[i] == 'U':
temp = U(x)
if code[i] == 'd':
temp = d(x)
if int(temp) != temp:
x+=3**(len(code)-i)
else:
x=temp
break
return x
def answer(code):
x = string(code)
power = 3**(len(code))
return math.ceil(MAX/power)*power+(x%(power))
print(answer("UDDDUdddDDUDDddDdDddDDUDDdUUDd"))
|
C
|
GB18030
| 805 | 3.09375 | 3 |
[] |
no_license
|
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#if 0
int Mystrncmp(const char *string1, const char *string2, size_t count)
{
int i = 0;
assert(string1 != NULL);
assert(string2 != NULL);
for (i = 0; i < count; i++)
{
if ((*string1 == *string2) && (i = count-1))
{
return 0;
}
else
{
break;
}
string1++;
string2++;
}
if (*string1 > *string2)
{
return 1;
}
else
{
return -1;
}
}
int main()
{
char arr1[10] = { 0 };
char arr2[10] = { 0 };
int num = 0;
int ret = 0;
printf("ַ1\n");
scanf("%s",arr1);
printf("ַ2\n");
scanf("%s",arr2);
printf("븴Ƹ\n");
scanf("%d", &num);
ret = Mystrncmp(arr1, arr2, num);
printf("%d\n", ret);
system("pause");
return 0;
}
#endif
|
Java
|
UTF-8
| 1,181 | 2.078125 | 2 |
[
"Apache-2.0"
] |
permissive
|
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.ftlines.wicket.validation.bean;
import org.apache.wicket.model.IPropertyReflectionAwareModel;
/**
* A {@link IPropertyResolver} that knows about common Wicket models that can provide
* {@link IProperty} information
*
* @see IPropertyReflectionAwareModel
*
* @author igor
*/
public class ModelPropertyResolver implements IPropertyResolver
{
@Override
public IProperty resolve(Object object)
{
if (object instanceof IPropertyReflectionAwareModel)
{
return new ReflectableProperty((IPropertyReflectionAwareModel)object);
}
return null;
}
}
|
Java
|
UTF-8
| 5,463 | 2.09375 | 2 |
[
"Apache-2.0"
] |
permissive
|
package net.floodlightcontroller.baadal;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import org.projectfloodlight.openflow.types.IPv4Address;
import org.projectfloodlight.openflow.types.VlanVid;
import org.restlet.data.Status;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.restlet.resource.Put;
import org.restlet.resource.ServerResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.MappingJsonFactory;
public class baadalPolicyResource extends ServerResource{
protected static Logger logger = LoggerFactory.getLogger(baadalPolicyResource.class);
/**
* Get basic info about the tool
* @return
*/
@Get("json")
public Object handleRequest() {
//return "{\"status\" : \"okay\", \"details\" : \"Invalid Operation\"}";
IBaadalService b =
(IBaadalService)getContext().getAttributes().
get(IBaadalService.class.getCanonicalName());
return b.getInterVmPolicy();
}
@Put
@Post
public Object addEntry(String json) throws IOException {
List< List<Object> > policies = new ArrayList<List<Object>>();
IBaadalService b =
(IBaadalService)getContext().getAttributes().
get(IBaadalService.class.getCanonicalName());
MappingJsonFactory f = new MappingJsonFactory();
JsonParser jp;
try {
jp = f.createParser(json);
} catch (JsonParseException e) {
throw new IOException(e);
}
jp.nextToken();
if(jp.getCurrentToken() != JsonToken.START_ARRAY){
throw new IOException("Expected START_ARRAY");
}
while(jp.nextToken() != JsonToken.END_ARRAY){
if (jp.getCurrentToken() != JsonToken.START_OBJECT) {
throw new IOException("Expected START_OBJECT");
}
IPv4Address ip1, ip2;
boolean decision;
// get the first ip address
if (jp.nextToken() != JsonToken.FIELD_NAME) {
throw new IOException("Expected FIELD_NAME");
}
// check for name "ip"
if(!jp.getCurrentName().equals("ip"))
throw new IOException("Expected ip");
else
{
// get the value of ip
jp.nextToken();
// attempt to create ip address
try{
//logger.info("look here{} and {}", jp.getCurrentName(), jp.getText());
ip1 = IPv4Address.of(jp.getText());
}
catch(Exception e)
{
logger.error("IP address 1 is not well formed " + e);
return "IP address 1 is not well formed";
}
}
// get the second ip address
if (jp.nextToken() != JsonToken.FIELD_NAME) {
throw new IOException("Expected FIELD_NAME");
}
// check for name "ip"
if(!jp.getCurrentName().equals("ip"))
throw new IOException("Expected ip");
else
{
// get the value of ip
jp.nextToken();
// attempt to create ip address
try{
//logger.info("look here{} and {}", jp.getCurrentName(), jp.getText());
ip2 = IPv4Address.of(jp.getText());
}
catch(Exception e)
{
logger.error("IP address 2 is not well formed " + e);
return "IP address 2 is not well formed";
}
}
// get the decision
if (jp.nextToken() != JsonToken.FIELD_NAME) {
throw new IOException("Expected FIELD_NAME");
}
// check for name "decision"
if(!jp.getCurrentName().equals("decision"))
throw new IOException("Expected decision");
else
{
// get the next token
jp.nextToken();
// attempt to create vlan tag
try{
decision = Boolean.valueOf(jp.getText());
}
catch(Exception e)
{
logger.error("Decision is not well formed, should be true or false" + e);
return "Decision is not well formed, should be true or false";
}
}
List<Object> policy = new ArrayList<Object>();
policy.add(ip1);policy.add(ip2);policy.add(decision);
policies.add(policy);
logger.info("policies {}",policies);
//jp.nextToken();
//logger.info("look here {} and {}", jp.getCurrentName(), jp.getText());
// }
//jp.close();
if (jp.nextToken() != JsonToken.END_OBJECT) {
throw new IOException("Expected END_OBJECT");
}
}
jp.close();
b.addInterVmPolicy(policies);
setStatus(Status.SUCCESS_OK);
return "{\"status\":\"ok\"}";
}
}
|
Python
|
UTF-8
| 519 | 3.640625 | 4 |
[] |
no_license
|
cars = ['mazda', 'renault', 'kia', 'chevrolet']
for car in cars:
print(car)
pet = {
"name": "davor",
"age": 31,
"country": "Colombia"
}
for key in pet:
print(f"key: {key} value: {pet[key]}")
for key, value in pet.items():
print(f"key: {key} value: {value}")
for n in [1, 2, 3, 4, 5, 6, 7, 8]:
if n <= 4:
continue
print(n)
# for i in range(6):
# if i % 2 == 0:
# print(f'Valor {i}')
for i in range(6):
if i % 2 != 0:
continue
print(f'Valor {i}')
|
Swift
|
UTF-8
| 1,243 | 2.65625 | 3 |
[] |
no_license
|
//
// ViewController.swift
// MyFirstApp
//
// Created by Ben Liong on 24/3/15.
// Copyright (c) 2015 General Assembly. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var temperatureLabel: UILabel?
@IBOutlet weak var getTemperatureButton: UIButton?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func getCurrentTemperature(sender: UIButton) {
<# General Assembly, Put Networking Code Here #>
// let url = NSURL(string: "http://pixelicious.com.hk/weather.html")
//
// let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
// let content = NSString(data: data, encoding: NSUTF8StringEncoding)
// println(content!)
// dispatch_async(dispatch_get_main_queue(), { () -> Void in
// self.temperatureLabel!.text = content
// })
// }
//
// task.resume()
}
}
|
JavaScript
|
UTF-8
| 4,210 | 2.578125 | 3 |
[] |
no_license
|
/*
* Copyright IBM Corp. All Rights Reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
'use strict';
const { Contract } = require('fabric-contract-api');
class Insurance extends Contract {
var currentClaimNum = 0;
async initLedger(ctx) {
console.info('START: Initialize Ledger');
console.info('END: Initialize Ledger');
}
async fileClaim(ctx, claimNum, name, licencePlate, nameOther, licencePlateOther) {
console.info('START: Create Claim');
const claim = {
state: 0,
name,
licencePlate,
nameOther,
licencePlateOther,
claimAdjuster: '',
proofOfLoss: '',
amountToPay: null,
amountToPayOther: null
}
await ctx.stub.putState(claimNum, Buffer.from(JSON.stringify(claim)));
console.info('STOP: Create Claim');
}
async assignClaimAdjuster(ctx, claimNum, claimAdjusterName) {
console.info('START: assignClaimAdjuster');
const claimAsString = await self.checkStatus(claimNum);
var claim = JSON.parse(claimAsString);
if (claim.state > 1) {
throw new Error(`Cannot assign a new claim adjuster for ${claimNum}`);
}
claim.state = 1;
claim.claimAdjuster = claimAdjusterName;
await ctx.stub.putState(claimNum, Buffer.from(JSON.stringify(claim)));
console.info('END: assignClaimAdjuster');
}
async completeAssessment(ctx, claimNum, amountToPay, amountToPayOther) {
console.info('START: completeAssessment');
const claimAsString = await self.checkStatus(claimNum);
var claim = JSON.parse(claimAsString);
if (claim.state != 1) {
throw new Error(`${claimNum} is not under assessment`);
}
claim.state = 2;
claim.amountToPay = amountToPay;
claim.amountToPayOther = amountToPayOther;
await ctx.stub.putState(claimNum, Buffer.from(JSON.stringify(claim)));
console.info('END: completeAssessment');
}
async agreeOnAssessment(ctx, claimNum, agreement) {
console.info('START: agreeOnAssessment');
const claimAsString = await self.checkStatus(claimNum);
var claim = JSON.parse(claimAsString);
if (claim.state < 2) {
throw new Error(`${claimNum} is not assessed yet`);
} elif (claim.state > 2) {
throw new Error(`Agreed on loss assessment for ${claimNum} already`);
}
if (agreement) {
claim.state = 3;
} else {
claim.state = 1;
}
await ctx.stub.putState(claimNum, Buffer.from(JSON.stringify(claim)));
console.info('END: agreeOnAssessment');
}
async submitProofOfLoss(ctx, claimNum, proofOfLoss) {
console.info('START: submitProofOfLoss');
const claimAsString = await self.checkStatus(claimNum);
var claim = JSON.parse(claimAsString);
if (claim.state != 3) {
throw new Error(`${claimNum} does not need Proof of Loss yet`);
}
claim.state = 4;
claim.proofOfLoss = proofOfLoss;
await ctx.stub.putState(claimNum, Buffer.from(JSON.stringify(claim)));
console.info('END: submitProofOfLoss');
}
async validProofOfLoss(ctx, claimNum, valid) {
console.info('START: validProofOfLoss');
const claimAsString = await self.checkStatus(claimNum);
var claim = JSON.parse(claimAsString);
if (claim.state != 4) {
throw new Error(`Proof of Loss for ${claimNum} is not submitted yet`);
}
if (valid) {
claim.state = 5;
} else {
claim.state = 3;
}
await ctx.stub.putState(claimNum, Buffer.from(JSON.stringify(claim)));
console.info('END: validProofOfLoss');
}
async checkStatus(claimNum) {
const claimAsBytes = await ctx.stub.getState(claimNum);
if (!claimAsBytes || claimAsBytes.length === 0) {
throw new Error(`${claimNum} does not exist`);
}
console.log(claimAsBytes.toString());
return claimAsBytes.toString();
}
}
module.exports = Insurance;
|
JavaScript
|
UTF-8
| 1,407 | 3.03125 | 3 |
[] |
no_license
|
$(document).ready(function(){
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div><hr><input type="text" name="sku[]" id="sku[]" style="height: 30px" placeholder="sku"/>\n' +
' <input type="text" name="size[]" style="height: 30px" id="size[]" placeholder="size"/>\n' +
' <br><br> <input type="text" name="price[]" id="price[]" style="height: 30px" placeholder="price"/>\n' +
' <input type="text" name="stock[]" id="stock[]" style="height: 30px" placeholder="stock"/>\n<a href="javascript:void(0);" class="remove_button">Remove</a></div>'; //New input field html
var x = 1; //Initial field counter is 1
//Once add button is clicked
$(addButton).click(function(){
//Check maximum number of input fields
if(x < maxField){
x++; //Increment field counter
$(wrapper).append(fieldHTML); //Add field html
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function(e){
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
|
Java
|
UTF-8
| 1,679 | 3 | 3 |
[] |
no_license
|
package inheritanceExample05;
public class StarCraft {
public static void main(String[] args) {
Marine my = new Marine();
Marine com = new Marine();
//��ü�� ��ü��
//ü�� : 100 ü�� : 100
System.out.println(my + "\t" + com);
System.out.println("���� ���� 2ȸ ����!!!!");
for(int i=0;i<2;i++)
my.attack(com);
//ü�� : 100 ü�� : 80
System.out.println(my + "\t" + com);
System.out.println("���� ���� 6ȸ ����!!!!");
for(int i=0;i<6;i++)
com.attack(my);
//ü�� : 40 ü�� : 80
System.out.println(my + "\t" + com);
System.out.println("���� ���� 4ȸ ����!!!!");
for(int i=0;i<4;i++)
my.attack(com);
//ü�� : 40 ü�� : 40
System.out.println(my + "\t" + com);
System.out.println("�������� ���� ����");
my.setMode(1);
//ü�� : 15 ü�� : 40
System.out.println(my + "\t" + com);
System.out.println("���� ���� 1ȸ ����!!!!");
my.attack(com);
//ü�� : 15 ü�� : 15
System.out.println(my + "\t" + com);
System.out.println("�������� ���� ����");
my.setMode(1);
//ü���� 30�����̹Ƿ� ��庯�� �Ұ���.
System.out.println(my + "\t" + com);
System.out.println("���� ���� 1ȸ ����!!!!");
my.attack(com);
//ü�� : 15 ü�� : die
System.out.println(my + "\t" + com);
my.setMode(1);
//ü�� : 15 ü�� : 40
System.out.println(my + "\t" + com);
}
}
|
Python
|
UTF-8
| 1,351 | 2.65625 | 3 |
[
"Apache-2.0"
] |
permissive
|
# Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at
# http://www.apache.org/licenses/LICENSE-2.0
# or in the "license" file accompanying this file. This file is distributed
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied. See the License for the specific language governing
# permissions and limitations under the License.
"""
NDArray utils
"""
import mxnet as mx
import numpy as np
def top_probability(data, labels, top=5):
"""
Get top probability prediction from NDArray.
:param data: NDArray
Data to be predicted
:param labels: List
List of class labels
:param top:
:return: List
List of probability: class pairs in sorted order
"""
dim = len(data.shape)
if dim > 2:
data = mx.nd.array(
np.squeeze(data.asnumpy(), axis=tuple(range(dim)[2:])))
sorted_prob = mx.nd.argsort(data[0], is_ascend=False)
# pylint: disable=deprecated-lambda
top_prob = map(lambda x: int(x.asscalar()), sorted_prob[0:top])
return [{'probability': float(data[0, i].asscalar()), 'class': labels[i]}
for i in top_prob]
|
Markdown
|
UTF-8
| 10,823 | 3.09375 | 3 |
[
"MIT"
] |
permissive
|
---
title: network 1
author: CYM
date: 2020-12-25 22:00:00
categories: [network]
tags: [network]
---
**(1) an IP address**<br>
IP주소는 네트워크 계층에서 사용하는 주소이며, IP 헤더에 포함된 데이터 주소.<br>
| |IPv4주소|IPv6주소|
|-|--------|--------|
|주소 체계|32bit(2^32개)|128bit(2^128개)|
|주소 표기|10진수|16진수|
|주소 구성|8bit씩 4개의 옥텟|16bit씩 8개의 필드|
|주소 예제|192.168.1.1|2002:1032:bc:198:1:13:113:19|
<br>
<br>
**(2)a Netmask**<br>
[개요]<br>
- 정확한 표현은 서브넷마스크(subnet mask)라고 함.<br>
- 하나의 네트워크를 몇 개의 네트워크로 나누어 사용할 때 나눠진 각각의 네트워크를 구분하기 위해 사용하는 특수한 bit.<br>
- 서브넷 마스크는 IP주소에 대한 네트워크 아이디와 호스트 아이디를 구분하기 위해서 사용.<br>
- 21세기에 가까워질수록 IPv4 주소의 고갈이 현실화되었고 각국의 NIC에서는 이를 최대한 늦추기 위해 각 라우터가 브로드캐스팅하는 로컬 네트워크 영역에 공인 IP 대역을 호스트가 필요한 만큼만 할당하려는 노력을 함.<br>
- 이러한 NIC 기관의 요구에 맞춰서 IETF에서는 로컬 네트워크 내부에서 접속한 호스트의 IP 대역을 외부 네트워크와 명확하게 구분할 수 있는 수단을 표준화하였고 이것이 서브넷 마스크.<br>
[표시 방법]<br>
- IPv4 주소는 4개의 바이너리 8자리수로 이루어져 총 32bit로 구성.
- ex) 192.168.0.1은 1100 0000.1010 1000.0000 0000.0000 0001로 표현됨.
- IP 주소는 네트워크 부분과 호스트 부분으로 나누어짐. 하나의 로컬 네트워크란 하나의 라우터를 거쳐가는 여러 개의 호스트들이 연결된 브로드캐스트 영역. 즉, 어떤 네트워크에서 한 노드가 브로드캐스트를 했을 때 그 네트워크의 모든 노드가 신호를 받았다면 그 네트워크는 하나의 네트워크. 호스트란 각각의 노드(PC, 스마트폰, 태블릿 등).
- 하나의 로컬 네트워크에서 IP 주소의 네트워크 부분은 같아야 하고, 호스트 부분은 달라야 함.
- IP주소 32bit에 공통 비트 1을 씌워서 네트워크를 표기하기 때문에 서브넷 마스크는 IP 주소와 마찬가지로 32bit 체계.<br>
- /24와 /255.255.255.0은 같음. 255.255.255.0을 2진수로 쓰면 1111 1111.1111 1111.1111 1111.0000 0000이다. 앞에서부터 연속된 1의 개수만 나타낸 것이 /24.<br>
[네트워크 주소]
- 서브넷 마스크를 계산할 때는 논리곱(논리 AND)를 사용.
- 맨 앞에 비트부터 1이 연속된 구간까지를 공통비트로 처리하여 네트워크 아이디로 사용하고, 0으로 끝나는 마지막 구간까지를 공통하지 않은 비트로 처리하여 호스트 아이디로 사용.<br>
- ex) 192.168.0.1/24
- 여기서 1을 논리곱하는 부분이 네트워크 부분, 0을 논리곱하는 부분이 호스트 부분.
- IP주소: 1100 0000.1010 1000.0000 0000.0000 0001
- 서브넷 마스크: 1111 1111.1111 1111.1111 1111.0000 0000
- 서브넷 네트워크: 1100 0000.1010 1000.0000 0000.0000 0000
- 호스트 개수: 네트워크 주소와 브로드캐스트 주소를 제외한 253개.
- 네트워크 개수: 1개<br>
<br>
<br>
**(3) the subnet of an IP with Netmask**<br>
[what's a subnet?]
- device interface with same subnet part of IP address.
- can physically reach each other without intervening router.
- to determine the subnets, detach each interface from its host or router, creating islands of isolated networks.
- each isolated network is called a subnet.
- 서브넷은 말그대로 부분망이라는 뜻. 그리고 이 서브넷을 만들 때 쓰이는 것이 바로 서브넷 마스크.
<br>
ex) 192.168.1.0 255.255.255.0과 192.168.8.0 255.255.255.0은 서로 다른 네트워크 대역.<br>
192.168.1.0는 서브넷 마스크가 255.255.255.0 이므로 네트워크 아이디는 192.168.1.이고 호스트 아이디는 .0<br>
따라서 범위는 192.168.1.0 ~ 192.168.1.255 까지임.<br>
192.168.8.0은 192.168.8.0 ~ 192.168.8.255 범위에 포함됨.<br>
만약 192.168.1.0 255.255.0.0 과 192.168.8.0 255.255.0.0 이라면 같은 네트워크 대역.<br>
서브넷 마스크가 255.255.0.0 이므로 네트워크 아이디는 192.168.이고 호스트 아이디는 .0.1<br>
따라서 범위는 192.168.0.0 ~ 192.168.255.255 까지임.<br>
<br>
<br>
**(4) the broadcast address of a subnet**<br>
브로드캐스트 주소 구하는 법<br>
IP address: 192.168.16.1<br>
Subnet mask: 255.255.255.224<br>
<br>
1 - Subnet mask를 invert한다.<br>
255.255.255.224 => 11111111.11111111.11111111.11100000<br>
이것을 invert하면 00000000.00000000.00000000.00011111<br>
<br>
2 - Invert한 subnet과 IP address를 Logical OR를 한다.<br>
192.168.16.1 => 11000000.10101000.00010000.00000001<br>
Invert한 서브넷 => 00000000.00000000.00000000.00011111<br>
결과는 => 11000000.10101000.00010000.00011111 => 192.168.16.31<br>
<br>
<br>
**(5) the different ways to represent an ip address with the Netmask**<br>
Netmask is a 32-bit "mask" used to divide an IP address into subnets and specify the network's available hosts.
```
255.255.255.0 is applied to the 129.144.41.101 , the result is the IPv4 address of 129.144.41.0
```
130.129.144.41.101 AND 255.255.255.0 = 129.144.41.0
In binary form, the operation is:
```
10000001.10010000.00101001.01100101 <== (IPv4 address)
AND
11111111.11111111.11111111.00000000 <==(netmask)
```
<br>
<br>
**(6) the differences between public and private IPs**<br>
[공인 IP 주소 (Public IP Address]<br>
인터넷에 있는 라우터를 통과할 수 있는 주소.<br>
[사설 IP 주소 (Private IP Address]<br>
같은 네트워크에서는 통신이 되지만, 인터넷은 통과 불가능한 주소.<br>
<br>
사설 아이피 대역은 A, B, C클래스에 각각 존재하며, <br>
A 클래스: 10.0.0.0 ~ 10.255.255.255<br>
B 클래스: 172.16.0.0 ~ 172.32.255.255<br>
C 클래스: 192.168.0.0 ~ 192.168.255.255<br>
<br>
<br>
**(7) a class of IP addresses**<br>
IP 주소 범위는 0.0.0.0 ~ 255.255.255.255까지 포함될 수 있음. 하지만 5개의 클래스로 정의하여 IP 주소 낭비 방지와 효율적인 서브넷 관리 가능.<br>
- A Class (Unicast Address)
- 첫 번째 필드를 2진수로 변환할 경우 맨 앞에 0이라는 공통 비트를 갇는다면 A Class로 정의.(00000000 ~ 01111111: 0부터 127까지)
- A Class가 가지는 기본 서브넷 마스크는 255.0.0.0이며 호스트 아이디가 24bit이므로 네트워크 아이디당 나올 수 있는 IP 주소는 2^24 - 2개.
- 초대형 네트워크 즉 국가간의 네트워크나 또는 범국가적 네트워크를 구축할 때 많이 사용.
- B Class (Unicast Address)
- 첫 번째 필드를 2진수로 변환할 경우 맨 앞에 10이라는 공통 비트를 갖는다면 B Class로 정의.(10000000 ~ 10111111: 128부터 191까지)
- B Class가 사용하는 기본 서브넷 마스크는 255.255.0.0이며 호스트 아이디가 16bit이므로 네트워크 아이디당 나올 수 있는 IP 주소는 2^16 -2개.
-대규모 네트워크 즉, IPS 단 네트워크에서 사용되는 IP로서 주로 서버 구축 시에 많이 사용.
- C Class (unicast Address)
- 첫 번째 필드를 2진수로 변환할 경우 맨 앞에 110이라는 공통 비트를 갇는다면 C Class로 정의.(11000000 ~ 11011111: 192부터 223까지)
- C Class가 사용하는 기본 서브넷 마스크는 255.255.255.0이며 호스트 아이디가 8bit이므로 네트워크 아이디당 나올 수 있는 IP 주소는 2^8 -2개.
- 소규모 네트워크 즉, 일반 사용자 또는 사무실에서 사용되는 IP로서 작은 사무실에 서버 구축이나 또는 작은 사업장에 IP주소를 할당할 때 사용.
- D Class (Multicast Address)
- 첫 번째 필드를 2진수로 변환할 경우 맨 앞에 1110이라는 공통 비트를 갖는다면 D Class로 정의.(11100000 ~ 11101111: 224부터 239까지)
- D Class는 멀티캐스트 주소로 예약되어 있으며 서브넷 마스크를 이용하여 블락 단위로 동작하지 않기 때문에 서브넷 마스크를 사용하지 않음.
- E Class (Broadcast Address)
- 첫 번째 필드를 2진수로 변환할 경우 맨 앞에 1111이라는 공통 비트를 갖는다면 E Class로 정의.(11110000 ~ 11111111: 240부터 255까지)
- E Class는 IANA에서 사용을 제한 시킨 주소이기 때문에 네트워크 인터페이스에 설정이 불가능.
<br>
<br>
**(8) TCP**<br>
TCP는 데이터를 패킷으로 자르고 다시 합치며 IP는 TCP에 의해 잘려진 패킷을 목적지로 전송하는 역할을 함.<br>
TCP는 생산자 역할을, IP는 택배 역할을 함.<br>
IP는 목적지까지만 잘 도착하는 데만 신경을 쓰고 안에 있는 데이터가 잘 보관되어 있는지는 확인을 안 함.<br>
TCP는 생산자 역할인 만큼, 그 데이터가 잘 배달되었는지 확인하고 제대로 배달이 안 되었다면 다시 데이터를 보냄.<br>
TCP와 IP의 역할은 각각 다르지만 각자의 역할을 합쳐 패킷이 목적지에 확실하게 도착하게 함.<br>
TCP의 3 way shaking
- 1. Source(출발지)에서 Destination(목적지)dprp Syn를 보냄.
- 2. 목적지는 해당 패킷을 받고 출발지에게 다시 Syn과 ACK를 보냄.
- 3. 출발지는 해당 패킷들을 받고 데이터와 목적지에 Syn에 대한 ACK를 동시에 보냄.
3 way hand shaking을 통해 신뢰성을 보장하고 패킷을 세그먼트로 잘라서 패킷의 전달을 쉽게 만들며 다시 헤더를 앞에 붙여 패킷이 오류가 발생하거나 조립 과정에서 문제가 없도록 보장.<br>
<br>
<br>
TCP (Transmision Control Protocol) Main protocols of the internet protol suite.
- Keeps track of lost packages, makes sure that lost packages are re-sent
- Addes sequesce numbers to packets and reorders any packets that arrive in thenworng order.
- Slower, because of all added additional functionality.
- Requieres more computer resources, because the OS needs to keep track of ongoing communication sessions and manage them on a much deeper level.
<br>
<br>
**(9) UDP**<br>
Why we use UDP?<br>
Many applications that requiere real-time communication prefer to use UDP, applications that requiere speed and that torerat partial data loss.<br>
- Doesn't keep track of lost packages
- Doesn't care about package arrival order.
- Faster, bacause it lacks any extra features.
- Requieres less computer resources.
- Examples of programs and services that use UPD:
- DNS
- IP telephony
- DHCP
- Many computer games
<br>
<br>
|
C++
|
UTF-8
| 549 | 2.734375 | 3 |
[] |
no_license
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define StrLength 100
int main(){
char buf[StrLength];
int i=0,count=0;
scanf("%s",buf);
while(strcmp(buf,"end")!=0){
count=0;
for(i=0;i<strlen(buf);i++){
if(buf[i]=='(')
count++;
else if(buf[i]==')')
count--;
}
if(count!=0)
puts("-1");
else
puts("1");
scanf("%s",buf);
}
}
|
PHP
|
UTF-8
| 369 | 2.78125 | 3 |
[] |
no_license
|
<?php
namespace App\Model\Fisica;
class Dvd extends \App\Model\Produto{
private $preco;
function __construct($nome, $ator, $preco){
parent::__construct($nome, $ator);
$this->preco = $preco;
}
function getPreco(){
return $this->preco;
}
function setPreco($preco){
$this->preco = $preco;
}
}
?>
|
Java
|
UTF-8
| 5,327 | 2.6875 | 3 |
[] |
no_license
|
package com.sundy.simple.annotation.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import java.lang.reflect.Field;
import java.util.ArrayList;
/**
* 项目名称:AnnotationStudy
*
* @Author bamboolife
* 邮箱:core_it@163.com
* 创建时间:2020-01-11 19:25
* 描述:AbstractDB 是一个抽象类,用于数据库的操作
*/
public abstract class AbstractDB {
public static final String TAG = "AbstractDB";
private SQLiteDatabase db;
private SqliteHelper dbHelper;
// 版本
private int version;
// 数据库名称
private String dbName;
// 表名
private String tableName;
// 建表语句
private StringBuilder createBuilder;
// 插入的数据
private ContentValues contentValues = new ContentValues();
// 是否存在数据
private boolean isColums;
private ArrayList<String> clumsList = new ArrayList<String>();
/**
* 打开数据库
*
* @param _context
* @param _clazz
* @param _object
* @return
*/
public AbstractDB open(Context _context, Class<?> _clazz, Object _object) {
if (paramsDB(_clazz, _object)) {
dbHelper = new SqliteHelper(_context, dbName, null, version, createBuilder.toString(), tableName);
db = dbHelper.getWritableDatabase();
Log.e(TAG, "-------------数据库打开成功!----------");
} else {
Log.e(TAG, "-------------数据库打开失败!----------");
}
return this;
}
/**
* 打开数据库时是否进行插入操作
*
* @param isInsert
* @return
*/
public AbstractDB isInsert(boolean isInsert) {
if (isInsert && isColums) {
insert();
}
return this;
}
/**
* 创建并检查数据库
*
* @param _object
* @param _clazz
* @return false:失败 true:成功
*/
public boolean paramsDB(Class<?> _clazz, Object _object) {
isColums = false;
contentValues.clear();
clumsList.clear();
createBuilder = new StringBuilder();
Class<?> clazz = _clazz;
Field[] fields = clazz.getDeclaredFields();
createBuilder.append("CREATE TABLE IF NOT EXISTS ");
/*
* 表名
*/
TableDB tDb = _clazz.getAnnotation(TableDB.class);
if (tDb != null) {
dbName = tDb.dbName();
tableName = tDb.table();
version = tDb.version();
createBuilder.append(tableName);
createBuilder.append("(");
} else {
return false;
}
/*
* 列
*/
for (Field field : fields) {
ColumDB requestParamsKey = field.getAnnotation(ColumDB.class);
if (requestParamsKey != null) {
String key = requestParamsKey.column();
String value;
try {
value = (String) field.get(_object);
clumsList.add(key);
if (!value.isEmpty()) {
contentValues.put(key, value);
}
createBuilder.append(key);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
createBuilder.append(" varchar,");
isColums = true;
}
}
if (!isColums) {
return false;
}
createBuilder.deleteCharAt(createBuilder.length() - 1);
createBuilder.append(")");
return true;
}
public AbstractDB insert() {
if (contentValues != null) {
db.insert(tableName, null, contentValues);
Log.e(TAG, "-------------数据添加成功!----------");
} else {
Log.e(TAG, "-------------数据添加失败!----------");
}
return this;
}
/**
* 获取数据
*
* @return
*/
public String getDate() {
StringBuilder dateBuilder = new StringBuilder();
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from " + tableName, null);
while (cursor.moveToNext()) {
if (clumsList != null) {
for (int i = 0, length = clumsList.size(); i < length; i++) {
String name = cursor.getString(cursor.getColumnIndex(clumsList.get(i)));
dateBuilder.append(clumsList.get(i));
dateBuilder.append("=");
dateBuilder.append(name);
dateBuilder.append(",");
}
dateBuilder.append("\n");
}
}
cursor.close();
if (dateBuilder.length() > 1) {
dateBuilder.deleteCharAt(dateBuilder.length() - 1);
return dateBuilder.toString();
} else {
Log.e(TAG, "-------------无数据解析!----------");
return "";
}
}
public void Close() {
db.close();
dbHelper.close();
}
}
|
Java
|
UTF-8
| 31,791 | 1.609375 | 2 |
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
* @author ehtesham, Arpan, Tanvir
*/
package PrePurchase;
import org.apache.struts2.ServletActionContext;
import pojo.hibernate.ErpmTenderMasterDAO;
import java.io.*;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.FileInputStream;
import java.util.*;
import org.apache.struts2.interceptor.validation.SkipValidation;
import pojo.hibernate.Departmentmaster;
import pojo.hibernate.DepartmentmasterDAO;
import pojo.hibernate.ErpmGenMaster;
import pojo.hibernate.ErpmGenMasterDao;
import pojo.hibernate.ErpmTenderMaster;
import pojo.hibernate.ErpmTenderSubmission;
import pojo.hibernate.ErpmTenderSubmissionDAO;
import pojo.hibernate.Institutionmaster;
import pojo.hibernate.InstitutionmasterDAO;
import pojo.hibernate.Subinstitutionmaster;
import pojo.hibernate.SubinstitutionmasterDAO;
import utils.DateUtilities;
import utils.DevelopmentSupport;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import pojo.hibernate.ErpmTenderSubmissionFiles;
import pojo.hibernate.ErpmTenderSubmissionFilesDao;
public class TenderSubmissionAction extends DevelopmentSupport {
private HttpServletRequest request;
public static Integer tsbTsbId;
public static Integer tsfTsfId ;
public static String localtendername;
public static String localtcompanyname;
public static String localttenderno;
public static String filename="-";//this var temprory used for checking same name of file in SaveUploadedFile method
private ErpmTenderMaster erpmTenderMaster;
private ErpmGenMaster erpmGenMaster;
private String tsbCompanyEmail;
private String tsbCompanyAddress;
private String tsbEmdReturnFileReference;
private Date tsbEmdReturnDate;
private Character tsbEmdReturned;
private String tsbDdCashReceiptNo;
private String tsbDdCash;
private Integer tsbTenderFee;
private Date tsbBgDdValidityDate;
private String tsbBgDdNo;
private String tsbEmdBankName;
private Integer tsbEmdAmount;
private String tsbCompanyPhone;
private String message;
private Character emdreturn;
private InputStream inputStream;
private String tsbCompanyName;
private String TenderName;
private Integer TenderNumber;
private Short DefaultInsitute1;
private Integer DefaultSubInsitute;
private String tname;
private String tendersubmission;
private short s = 24;
private Integer DefaultDepartment;
private List<ErpmTenderSubmission> erpmtsbList;
private ErpmGenMasterDao emdtypedao = new ErpmGenMasterDao();
private ErpmTenderSubmission erpmtsb;
private Departmentmaster departmentmaster;
private Subinstitutionmaster subinstitutionmaster;
private Institutionmaster institutionmaster;
private ErpmTenderSubmissionFiles erpmtsf;
private List<ErpmTenderSubmissionFiles> erpmtsfList = new ArrayList<ErpmTenderSubmissionFiles>();
private InstitutionmasterDAO imDao = new InstitutionmasterDAO();
private ErpmTenderSubmissionFilesDao erpmtsfDao = new ErpmTenderSubmissionFilesDao();
private List<Institutionmaster> imList = new ArrayList<Institutionmaster>();
private List<Departmentmaster> dmList = new ArrayList<Departmentmaster>();
private DepartmentmasterDAO dmDao = new DepartmentmasterDAO();
private List<Subinstitutionmaster> simList = new ArrayList<Subinstitutionmaster>();
private SubinstitutionmasterDAO simDao = new SubinstitutionmasterDAO();
private List<ErpmTenderMaster> tmList = new ArrayList<ErpmTenderMaster>();
private List<ErpmTenderSubmission> erpmtsmList = new ArrayList<ErpmTenderSubmission>();
private List<ErpmGenMaster> emdtypeList = new ArrayList<ErpmGenMaster>();
private ErpmTenderMasterDAO tmDao = new ErpmTenderMasterDAO();
private ErpmTenderSubmissionDAO erpmtsbDao = new ErpmTenderSubmissionDAO();
// GETTER SETTER METHODS
public static File Uploadfile;//Upload TenderSubmissionFile
public String UploadfileContentType;//this is content type of file
private static String fileUploadFileName;
private static String UploadfileFileName;//this is file name which is obtained direct from uploadfile without entering filename
private static String TsfFileRemarks;
private HttpServletRequest servletRequest;
public String getUploadfileContentType() {
return UploadfileContentType;
}
public void setUploadfileContentType(String UploadfileContentType) {
this.UploadfileContentType = UploadfileContentType;
}
public String getFileUploadFileName() {
return fileUploadFileName;
}
public void setFileUploadFileName(String fileUploadFileName) {
this.fileUploadFileName = fileUploadFileName;
}
public String getUploadfileFileName() {
return UploadfileFileName;
}
public void setUploadfileFileName(String UploadfileFileName) {
this.UploadfileFileName = UploadfileFileName;
}
public File getUploadfile() {
return Uploadfile;
}
public void setUploadfile(File Uploadfile) {
this.Uploadfile = Uploadfile;
}
public String getTendersubmission() {
return tendersubmission;
}
public void setTendersubmission(String tendersubmission) {
this.tendersubmission = tendersubmission;
}
public String getTname() {
return tname;
}
public void setTname(String tname) {
this.tname = tname;
}
public Character getEmdreturn() {
return emdreturn;
}
public void setEmdreturn(Character emdreturn) {
this.emdreturn = emdreturn;
}
public Short getDefaultInsitute1() {
return DefaultInsitute1;
}
public void setDefaultInsitute1(Short DefaultInsitute1) {
this.DefaultInsitute1 = DefaultInsitute1;
}
public Integer getDefaultSubInsitute() {
return DefaultSubInsitute;
}
public void setDefaultSubInsitute(Integer DefaultSubInsitute) {
this.DefaultSubInsitute = DefaultSubInsitute;
}
public Integer getDefaultDepartment() {
return DefaultDepartment;
}
public void setDefaultDepartment(Integer DefaultDepartment) {
this.DefaultDepartment = DefaultDepartment;
}
public Integer getTenderNumber() {
return TenderNumber;
}
public void setTenderNumber(Integer TenderNumber) {
this.TenderNumber = TenderNumber;
}
public ErpmTenderSubmission getErpmtsb() {
return erpmtsb;
}
public void setErpmtsb(ErpmTenderSubmission erpmtsb) {
this.erpmtsb = erpmtsb;
}
public String getTenderName() {
return TenderName;
}
public void setTenderName(String TenderName) {
this.TenderName = TenderName;
}
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public Institutionmaster getInstitutionmaster() {
return this.institutionmaster;
}
public void setInstitutionmaster(Institutionmaster institutionmaster) {
this.institutionmaster = institutionmaster;
}
public Subinstitutionmaster getSubinstitutionmaster() {
return this.subinstitutionmaster;
}
public void setSubinstitutionmaster(Subinstitutionmaster subinstitutionmaster) {
this.subinstitutionmaster = subinstitutionmaster;
}
public Departmentmaster getDepartmentmaster() {
return this.departmentmaster;
}
public void setDepartmentmaster(Departmentmaster departmentmaster) {
this.departmentmaster = departmentmaster;
}
public String getTsbCompanyName() {
return this.tsbCompanyName;
}
public void setTsbCompanyName(String tsbCompanyName) {
this.tsbCompanyName = tsbCompanyName;
}
public Integer getTsbTsbId() {
return this.tsbTsbId;
}
public void setTsbTsbId(Integer tsbTsbId) {
this.tsbTsbId = tsbTsbId;
}
public ErpmTenderMaster getErpmTenderMaster() {
return this.erpmTenderMaster;
}
public void setErpmTenderMaster(ErpmTenderMaster erpmTenderMaster) {
this.erpmTenderMaster = erpmTenderMaster;
}
public ErpmGenMaster getErpmGenMaster() {
return this.erpmGenMaster;
}
public void setErpmGenMaster(ErpmGenMaster erpmGenMaster) {
this.erpmGenMaster = erpmGenMaster;
}
public String getTsbCompanyEmail() {
return this.tsbCompanyEmail;
}
public void setTsbCompanyEmail(String tsbCompanyEmail) {
this.tsbCompanyEmail = tsbCompanyEmail;
}
public String getTsbCompanyAddress() {
return this.tsbCompanyAddress;
}
public void setTsbCompanyAddress(String tsbCompanyAddress) {
this.tsbCompanyAddress = tsbCompanyAddress;
}
public String getTsbCompanyPhone() {
return this.tsbCompanyPhone;
}
public void setTsbCompanyPhone(String tsbCompanyPhone) {
this.tsbCompanyPhone = tsbCompanyPhone;
}
public Integer getTsbEmdAmount() {
return this.tsbEmdAmount;
}
public void setTsbEmdAmount(Integer tsbEmdAmount) {
this.tsbEmdAmount = tsbEmdAmount;
}
public String getTsbEmdBankName() {
return this.tsbEmdBankName;
}
public void setTsbEmdBankName(String tsbEmdBankName) {
this.tsbEmdBankName = tsbEmdBankName;
}
public String getTsbBgDdNo() {
return this.tsbBgDdNo;
}
public void setTsbBgDdNo(String tsbBgDdNo) {
this.tsbBgDdNo = tsbBgDdNo;
}
public Date getTsbBgDdValidityDate() {
return this.tsbBgDdValidityDate;
}
public void setTsbBgDdValidityDate(Date tsbBgDdValidityDate) {
this.tsbBgDdValidityDate = tsbBgDdValidityDate;
}
public Integer getTsbTenderFee() {
return this.tsbTenderFee;
}
public void setTsbTenderFee(Integer tsbTenderFee) {
this.tsbTenderFee = tsbTenderFee;
}
public String getTsbDdCash() {
return this.tsbDdCash;
}
public void setTsbDdCash(String tsbDdCash) {
this.tsbDdCash = tsbDdCash;
}
public String getTsbDdCashReceiptNo() {
return this.tsbDdCashReceiptNo;
}
public void setTsbDdCashReceiptNo(String tsbDdCashReceiptNo) {
this.tsbDdCashReceiptNo = tsbDdCashReceiptNo;
}
public Character getTsbEmdReturned() {
return this.tsbEmdReturned;
}
public void setTsbEmdReturned(Character tsbEmdReturned) {
this.tsbEmdReturned = tsbEmdReturned;
}
public Date getTsbEmdReturnDate() {
return this.tsbEmdReturnDate;
}
public void setTsbEmdReturnDate(Date tsbEmdReturnDate) {
this.tsbEmdReturnDate = tsbEmdReturnDate;
}
public String getTsbEmdReturnFileReference() {
return this.tsbEmdReturnFileReference;
}
public void setTsbEmdReturnFileReference(String tsbEmdReturnFileReference) {
this.tsbEmdReturnFileReference = tsbEmdReturnFileReference;
}
public List<ErpmTenderSubmission> geterpmtsbList() {
return this.erpmtsmList;
}
public void seterpmtsmList(List< ErpmTenderSubmission> erpmtsmList) {
this.erpmtsmList = erpmtsmList;
}
public List<Institutionmaster> getimList() {
return this.imList;
}
public void setimList(List<Institutionmaster> imList) {
this.imList = imList;
}
public List<Subinstitutionmaster> getsimList() {
return this.simList;
}
public void setsimList(List<Subinstitutionmaster> simList) {
this.simList = simList;
}
public List<Departmentmaster> getdmList() {
return this.dmList;
}
public void setdmList(List<Departmentmaster> dmList) {
this.dmList = dmList;
}
public List<ErpmTenderMaster> gettmList() {
return this.tmList;
}
public void settmList(List<ErpmTenderMaster> tmList) {
this.tmList = tmList;
}
public void setMessage(String message) {
this.message = message;
}
public String getMessage() {
return this.message;
}
public List<ErpmGenMaster> getEmdtypeList() {
return emdtypeList;
}
public void setEmdtypeList(List<ErpmGenMaster> emdtypeList) {
this.emdtypeList = emdtypeList;
}
public ErpmGenMasterDao getEmdtypedao() {
return emdtypedao;
}
public void setEmdtypedao(ErpmGenMasterDao emdtypedao) {
this.emdtypedao = emdtypedao;
}
public ErpmTenderSubmissionDAO getErpmtsbDao() {
return erpmtsbDao;
}
public void setErpmtsbDao(ErpmTenderSubmissionDAO erpmtsbDao) {
this.erpmtsbDao = erpmtsbDao;
}
public List<ErpmTenderSubmission> getErpmtsbList() {
return erpmtsbList;
}
public void setErpmtsbList(List<ErpmTenderSubmission> erpmtsbList) {
this.erpmtsbList = erpmtsbList;
}
public void seterpmtsfList(List<ErpmTenderSubmissionFiles> erpmtsfList) {
this.erpmtsfList = erpmtsfList;
}
public List<ErpmTenderSubmissionFiles> geterpmtsfList() {
return this.erpmtsfList;
}
public ErpmTenderSubmissionFiles getErpmtsf() {
return erpmtsf;
}
public void setErpmtsf(ErpmTenderSubmissionFiles erpmtsf) {
this.erpmtsf = erpmtsf;
}
public int gettsfTsfId() {//this is used local id in action class for operation
return tsfTsfId;
}
public void settsfTsfId(int tsfTsfId) {
this.tsfTsfId = tsfTsfId;
}
public String getlocaltendername() {
return localtendername;
}
public void setlocaltendername(String localtendername) {
this.localtendername = localtendername;
}
public String getlocaltcompanyname() {
return localtcompanyname;
}
public void setlocaltcompanyname(String localtcompanyname) {
this.localtcompanyname = localtcompanyname;
}
public String getlocalttenderno() {
return localttenderno;
}
public void setlocalttenderno(String localttenderno) {
this.localttenderno = localttenderno;
}
public String getTsfFileRemarks() {
return TsfFileRemarks;
}
public void setTsfFileRemarks(String TsfFileRemarks) {
this.TsfFileRemarks = TsfFileRemarks;
}
@Override
public void setServletRequest(HttpServletRequest servletRequest) {
this.servletRequest = servletRequest;
}
@SkipValidation
public String execute() throws Exception {
try {
//TO SHOW OFF LIST
InitializeLOVs();
Date d = new Date();
DateUtilities d1 = new DateUtilities();
setTendersubmission(d1.convertDateToString(d, "dd-MM-yyyy"));
return SUCCESS;
} catch (Exception e) {
message = "Exception in -> ManageOpeningStockAction" + e.getMessage() + " Reported Cause is: " + e.getCause();
return ERROR;
}
}
@SkipValidation
public String BrowseTSB() throws Exception {
try {
//Retrieve Items which belong to the institutes in the perview of user
//erpmtsbList = erpmtsbDao.findAll();
//line added by shobhi
erpmtsbList = erpmtsbDao.findbyId(Short.valueOf(getSession().getAttribute("imId").toString()));
//findItemsForUserInstitutes(Integer.valueOf(getSession().getAttribute("userid").toString()));
tsfTsfId = 0;
InitializeLOVs();
return SUCCESS;
} catch (Exception e) {
message = "Exception in Browse method -> ManageItemsAxn" + e.getMessage() + " Reported Cause is: " + e.getCause();
return ERROR;
}
}
public String SaveTSB() throws Exception {
try {
//If part saves new record else parts is for record update
DateUtilities dt = new DateUtilities();
if (erpmtsb.getTsbTsbId() == null) {
erpmtsb.setTsbSubmissionDate(dt.convertStringToDate(getTendersubmission()));
erpmtsbDao.save(erpmtsb);
//THIS PART IS USED WHEN WE WANT TO SAVE VALUE AND BACK TO BLNK PAGE AFTER SAVING THE VALUE
erpmtsb = new ErpmTenderSubmission();
ErpmTenderSubmissionDAO erpmtsbDao = new ErpmTenderSubmissionDAO();
erpmtsbList = erpmtsbDao.findAll();
setTenderName(null);//USED FOR SETTNG THE BLANK VALUE OF TENDER NAME
message = "Item record saved successfully.";// " +(erpmtsb.getTsbTsbId());
} else {
ErpmTenderSubmission erpmtsb1 = erpmtsbDao.findByErpmtsbId(erpmtsb.getTsbTsbId()); //findByErpmicmItemId(erpmItemCategoryMaster.getErpmicmItemId());
erpmtsb1 = erpmtsb;
erpmtsb.setTsbSubmissionDate(dt.convertStringToDate(getTendersubmission()));
erpmtsbDao.update(erpmtsb1);
// FOR BLANK AFTER SAVING VALUES
erpmtsb = new ErpmTenderSubmission();
ErpmTenderSubmissionDAO erpmtsbDao = new ErpmTenderSubmissionDAO();
erpmtsbList = erpmtsbDao.findAll();
setTenderName(null);
message = "Record updated successfully.";
}
return SUCCESS;
} catch (Exception e) {
message = "Exception in Save method -> TenderSubissionAction" + e.getMessage() + " Reported Cause is: " + e.getCause();
return ERROR;
}
}
@SkipValidation
public String ClearTSB() throws Exception {
try {
message = "CLEARING ITEMS";
//tosImIdList = imDao.findInstForUser(Integer.valueOf(getSession().getAttribute("userid").toString()));
erpmtsb = null;
setTenderName(null);//FOR SETTNG BLNK NAME OF TENDER NAME
InitializeLOVs();
return SUCCESS;
} catch (Exception e) {
message = "Exception in Clear method -> TenderSubmissionAction " + e.getMessage() + " Reported Cause is: " + e.getCause();
return ERROR;
}
}
@SkipValidation
public String EditTSB() throws Exception {
try {
erpmtsb = erpmtsbDao.findByErpmtsbId(getTsbTsbId());
localtendername = "" + erpmtsb.getErpmTenderMaster().getTmName();
localtcompanyname = "" + erpmtsb.getTsbCompanyName();
localttenderno = "" + erpmtsb.getErpmTenderMaster().getTmTenderNo();
tsfTsfId = 1;//for apear of UploadSubmissionFile button int erpmtsf is not 0
message = "" + erpmtsb.getTsbCompanyName();
setTenderName(erpmtsb.getErpmTenderMaster().getTmName()); //FOR SET TENDER NAME
DateUtilities dt = new DateUtilities();
tendersubmission = dt.convertDateToString(erpmtsb.getTsbSubmissionDate(), "dd/MM/yyyy");
InitializeLOVs();
return SUCCESS;
} catch (Exception e) {
message = "Exception in Edit method ->" + e.getMessage() + " Reported Cause is: " + e.getCause();
return ERROR;
}
}
public String DeleteTSB() throws Exception {
try {
//Retrieve the record to be deleted
erpmtsb = erpmtsbDao.findByErpmtsbId(getTsbTsbId());
erpmtsbDao.delete(erpmtsb);
erpmtsbList = erpmtsbDao.findAll();
// findByImId(Short.parseShort(getSession().getAttribute("imId").toString()));
message = "Item Record deleted successfully.";
return SUCCESS;
} catch (Exception e) {
message = "Exception in Delete method -> ManageItemstAxn " + e.getMessage() + " Reported Cause is: " + e.getCause();
return ERROR;
}
}
@SkipValidation
public String UploadSubmissionFile() throws Exception {
try {
// message=""+erpmtsb.getTsbBgDdValidityDate();
tsbTsbId = getTsbTsbId();
tsfTsfId = null;
erpmtsfList = erpmtsfDao.getListofFile(tsbTsbId);
filename="";
return "success";
} catch (Exception e) {
message = "Exception in UploadSubmissionFile method -> ManageItemstAxn " + e.getMessage() + " Reported Cause is: " + e.getCause();
return ERROR;
}
}
@SkipValidation
public String ClearTenderSubmissionFile() throws Exception {
try {
tsfTsfId = null;
fileUploadFileName = "";
TsfFileRemarks = "";
erpmtsfList = erpmtsfDao.getListofFile(tsbTsbId);//get list of all file stored in database
filename="";
return "success";
} catch (Exception e) {
message = "Exception in UploadSubmissionFile method -> ManageItemstAxn " + e.getMessage() + " Reported Cause is: " + e.getCause();
return ERROR;
}
}
@SkipValidation
public String BackTenderSubmissionFile() throws Exception {
try {
// message=""+erpmtsb.getTsbBgDdValidityDate();
erpmtsb = erpmtsbDao.findByErpmtsbId(getTsbTsbId());
tsfTsfId = null;
fileUploadFileName = "";
TsfFileRemarks = "";
filename="";
return "success";
} catch (Exception e) {
message = "Exception in UploadSubmissionFile method -> ManageItemstAxn " + e.getMessage() + " Reported Cause is: " + e.getCause();
return ERROR;
}
}
@SkipValidation//this method to edit file of selected id
public String EditTenderSubmissionFile() throws Exception {
try {
// message=""+gettsfTsfId()+tsbTsbId;
tsfTsfId=gettsfTsfId();
// message=""+erpmtsb.getTsbBgDdValidityDate();
erpmtsf = erpmtsfDao.findByerpmtsfId(gettsfTsfId());//get object erpmtsf according selected id
fileUploadFileName = "" + erpmtsf.getTsfFileName();
TsfFileRemarks = "" + erpmtsf.getTsfFileRemarks();
erpmtsfList = erpmtsfDao.getListofFile(tsbTsbId);//get list of all file stored in database
filename="";
return "success";
} catch (Exception e) {
message = "Exception in DeleteTenderSubmissionFile method -> ManageItemstAxn " + e.getMessage() + " Reported Cause is: " + e.getCause();
return ERROR;
}
}
@SkipValidation//this method to delete file stored in database
public String DeleteTenderSubmissionFile() throws Exception {
try {
erpmtsf = erpmtsfDao.findByerpmtsfId(gettsfTsfId());//get object erpmtsf according selected id
erpmtsfDao.DeleteSubmissionFile(erpmtsf);
erpmtsf.setTsfTsfId(0);
erpmtsfList = erpmtsfDao.getListofFile(tsbTsbId);//get list of all file stored in database
tsfTsfId = null;
filename="";
return "success";
} catch (Exception e) {
message = "Exception in DeleteTenderSubmissionFile method -> ManageItemstAxn " + e.getMessage() + " Reported Cause is: " + e.getCause();
return ERROR;
}
}
//this method used to save file in database
@SkipValidation
public String SaveUploadedFile() throws Exception {
FileInputStream fis = null;
//System.out.println("getFileUpload()--m,.m,----------");
ErpmTenderSubmissionFiles erpmtsf1 = new ErpmTenderSubmissionFiles();
try {
String filePath = servletRequest.getRealPath("/");//getting server path
System.out.println("Server path:" + filePath);
System.out.println("TsfFileRemarks------------" + TsfFileRemarks);
System.out.println("content type: " + UploadfileContentType);
System.out.println(" File name: " + UploadfileFileName);
System.out.println("entered file name : " + fileUploadFileName.indexOf(".pdf"));
if (fileUploadFileName.equals("")) {
fileUploadFileName = UploadfileFileName;
System.out.println("fileUploadFileName : " + fileUploadFileName);
} else {
if (fileUploadFileName.indexOf(".pdf") == -1) {
fileUploadFileName = fileUploadFileName + ".pdf";
}
}
if(!filename.equals(UploadfileFileName)){
File fileToCreate = new File(filePath, this.fileUploadFileName);
System.out.println("fileToCreate: " + fileToCreate.getAbsolutePath());
String filepath = "" + fileToCreate.getAbsolutePath();
FileUtils.copyFile(this.Uploadfile, fileToCreate);//copy file to server
System.out.println("tsfTsfId:--------" + tsfTsfId);
if (tsfTsfId == null) {//if we are saving file then its tsftsfid will be zero
erpmtsf1.setTsfFileName(fileUploadFileName);
erpmtsf1.setTsfFileRemarks(TsfFileRemarks);
erpmtsb = erpmtsbDao.findByErpmtsbId(tsbTsbId);
erpmtsf1.setErpmTenderSubmission(erpmtsb);
//proccess to read file from filepath
File image = new File(filepath);
byte[] bFile = new byte[(int) image.length()];
try {
FileInputStream fileInputStream = new FileInputStream(image);
fileInputStream.read(bFile);
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
fis = new FileInputStream(image);
erpmtsf1.setTsfFileStream(bFile);
System.out.println("erpmtsf1-------" + erpmtsf1.getTsfFileRemarks());
erpmtsfDao.save(erpmtsf1);
System.out.println(" done-save--- ");
fis.close();
filepath = null;
erpmtsf1=null;
tsfTsfId = 0;
Uploadfile=null;
}
if (tsfTsfId != null) {//if we are updating file then its tsftsfid will not be zero
erpmtsf1.setTsfTsfId(tsfTsfId);
erpmtsf1.setTsfFileName(fileUploadFileName);
erpmtsf1.setTsfFileRemarks(TsfFileRemarks);
erpmtsb = erpmtsbDao.findByErpmtsbId(tsbTsbId);
erpmtsf1.setErpmTenderSubmission(erpmtsb);
//proccess to read file from filepath
File image = new File(filepath);
byte[] bFile = new byte[(int) image.length()];
try {
FileInputStream fileInputStream = new FileInputStream(image);
fileInputStream.read(bFile);
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
fis = new FileInputStream(image);
erpmtsf1.setTsfFileStream(bFile);
erpmtsfDao.update(erpmtsf1);
fis.close();
System.out.println(" done---- ");
erpmtsf1=null;
Uploadfile=null;
}
}
} catch (Exception e) {
e.printStackTrace();
}
filename=""+fileUploadFileName;
erpmtsf1=null;
UploadfileFileName=null;
tsfTsfId = null;
fileUploadFileName = null;
TsfFileRemarks = null;
erpmtsfList = null;
erpmtsfList = erpmtsfDao.getListofFile(tsbTsbId);//get list of all file stored in database
return "success";
}
//this method used for download file from database
@SkipValidation
public String DownLoadTenderSubmissionFile() throws Exception {
try {
erpmtsf = erpmtsfDao.findByerpmtsfId(gettsfTsfId());//getting erpmtsf object
String filename = "1";
HttpServletResponse response = ServletActionContext.getResponse();//get response object
byte[] bytearray = new byte[(int) erpmtsf.getTsfFileStream().length];//get array of size equal to file size
bytearray = erpmtsf.getTsfFileStream();
filename=erpmtsf.getTsfFileName();
response.reset();
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
response.setHeader("cache-control", "must-revalidate");
int size = bytearray.length;
try {
while (bytearray .length!=-1) {
response.getOutputStream().write(bytearray , 0, size);
break;
}
response.flushBuffer();
} catch (Exception e) {
}
filename="";
return "success";
} catch (Exception e) {
message = "Exception in DownLoadTenderSubmissionFile method -> ManageItemstAxn " + e.getMessage() + " Reported Cause is: " + e.getCause();
return ERROR;
}
}
private void InitializeLOVs() {
imList = imDao.findInstForUser(Integer.valueOf(getSession().getAttribute("userid").toString()));
simList = simDao.findSubInstForUser(Integer.valueOf(getSession().getAttribute("userid").toString()), Short.valueOf(getSession().getAttribute("imId").toString()));
dmList = dmDao.findDepartmentForUser(Integer.valueOf(getSession().getAttribute("userid").toString()), Integer.valueOf(getSession().getAttribute("simId").toString()));
//tmList = tmDao.findAll();
tmList = tmDao.findByImId(Short.valueOf(getSession().getAttribute("imId").toString()));
emdtypeList = emdtypedao.findByErpmGmType(s);
DefaultInsitute1 = Short.valueOf(getSession().getAttribute("imId").toString());
DefaultSubInsitute = Integer.valueOf(getSession().getAttribute("simId").toString());
DefaultDepartment = Integer.valueOf(getSession().getAttribute("dmId").toString());
dmList = dmDao.findAllDepartmentsForUser(Integer.valueOf(getSession().getAttribute("userid").toString()));
erpmtsfList = erpmtsfDao.getListofFile(tsbTsbId);
}
@Override
public void validate() {
try {
InitializeLOVs();
emdtypeList = emdtypedao.findByErpmGmType(s);
if (erpmtsb.getInstitutionmaster().getImId() == 0) {
addFieldError("erpmtsb.institutionmaster.imId", "Please select institution from the list");
}
if (erpmtsb.getSubinstitutionmaster().getSimId() == 0) {
addFieldError("erpmtsb.subinstitutionmaster.simId", "Please select Subinstitution");
}
if (erpmtsb.getDepartmentmaster().getDmId() == 0) {
addFieldError("erpmtsb.departmentmaster.dmId", "Please select Department");
}
if (erpmtsb.getErpmTenderMaster().getTmTmId() == 0) {
addFieldError("TenderName", "Please select Tender number");
}
if (erpmtsb.getTsbCompanyName().length() == 0) {
addFieldError("CompanyName", "Please select Company Name");
}
if (erpmtsb.getTsbCompanyEmail().length() == 0) {
addFieldError("erpmtsb.tsbCompanyEmail", "Please select company email");
}
} catch (Exception e) {
message = "Exception in Delete method -> ManageItemstAxn " + e.getMessage() + " Reported Cause is: " + e.getCause();
}
}
}
|
Python
|
UTF-8
| 3,419 | 2.8125 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 5 16:18:48 2018
@author: SRanganath
"""
import re
import pandas as pd
import datetime
# Time calculations
# current_year = datetime.datetime.now().year
# ts_years = list(pd.Series(range((current_year-3), (1+current_year))))
# Function to check wether rows are fit for Time Series
def start_time(X):
result = datetime.datetime.time(X)
return result
def end_time(X):
result = datetime.datetime.time(X)
return result
def TS_Check(x):
current_year = datetime.datetime.now().year
ts_years = list(pd.Series(range((current_year-3), (1+current_year))))
if set(x) & set(ts_years) == set(ts_years):
result = 'fit'
else:
result = 'unfit'
return result
# Flagging based on spot counts
def Spot_Check(row):
if((row['spot_sum'] >= row['spot_lb']) and
(row['spot_sum'] <= row['spot_ub'])):
result = 'good'
else:
result = 'bad'
return result
# Flagging Olympics and sports
olympic_pattern = re.compile('.*(olympic).*', re.IGNORECASE)
def SP_Olympic_Check(row):
global olympic_pattern
if (row['daypart_name'] == 'SP'):
m = re.match(olympic_pattern, row['invcode_name'])
if m:
result = 'olympic'
else:
result = 'sports'
else:
result = 'normal'
return result
def future_check(row):
current_date = datetime.datetime.now()
current_year = datetime.datetime.now().year
current_week = int(current_date.strftime("%V"))
if(int(row['air_year']) > int(current_year)):
result = 'good'
elif((int(row['air_year'] == int(current_year)))and
int(row['air_week']) >= int(current_week)):
result = 'good'
else:
result = row['spot_flag_temp']
return result
# Checking orders in the future
# def future_check(row):
# current_date = datetime.datetime.now()
# current_year = datetime.datetime.now().year
# current_week = int(current_date.strftime("%V"))
# if(row['air_year'] >= current_year
# and row['air_week'] >= current_week):
# result = 'good'
# else:
# result = row['spot_flag']
# return result
#
# good_check = Good_Data[Good_Data.invcode_name == 'Today Show 7-8a']
# group = good_check.groupby(['market', 'station_name', 'daypart_name',
# 'invcode_name', 'air_week',
# 'air_year'])
#
#
# def cum_sum(Y):
# Y['cum_sum'] = Y['spot_counts'].cumsum()
# Z = Y.reset_index()
# return Z
# def test_code(row):
# if(row['spot_flag'] == row['Spot_new']):
# result = 'same'
# else:
# result = 'check'
# return result
#
#
# data1['test'] = data1.apply(test_code, axis=1)
#
# check = data1[data1['test'] == 'check']
# def rolling_sum(X):
# arr = np.array(X)
# result = np.cumsum(arr)
# return result
#
#
# group['rolling_sum'] = group.spot_counts.apply(rolling_sum)
#
# group = good_check.groupby(['market', 'station_name', 'daypart_name',
# 'invcode_name', 'air_week' ,
# 'air_year'])
#
# def cum_sum(Y):
# Y['cum_sum'] = Y['spot_counts'].cumsum()
# Y.reset_index(inplace=True)
# return Y
#
# Z=group.apply(cum_sum)
|
Markdown
|
UTF-8
| 4,793 | 3.21875 | 3 |
[] |
no_license
|
# vue
当我们需要进行数值计算,并且依赖于其它数据时,应该使用 computed,因为可以利用 computed 的缓存特性,避免每次获取值时,都要重新计算;
当我们需要在数据变化时执行异步或开销较大的操作时,应该使用 watch,使用 watch 选项允许我们执行异步操作 ( 访问一个 API ),限制我们执行该操作的频率,并在我们得到最终结果前,设置中间状态。这些都是计算属性无法做到的。
## Vue 组件间通信有哪几种方式?
props / \$emit 适用 父子组件通信
ref 与 $parent / $children 适用 父子组件通信
EventBus ($emit / $on) 适用于 父子、隔代、兄弟组件通信
$attrs/$listeners 适用于 隔代组件通信
provide / inject 适用于 隔代组件通信
Vuex 适用于 父子、隔代、兄弟组件通信
## 16、你使用过 Vuex 吗?
State:定义了应用状态的数据结构,可以在这里设置默认的初始状态。
Getter:允许组件从 Store 中获取数据,mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性。
Mutation:是唯一更改 store 中状态的方法,且必须是同步函数。
Action:用于提交 mutation,而不是直接变更状态,可以包含任意异步操作。
Module:允许将单一的 Store 拆分为多个 store 且同时保存在单一的状态树中。
## Vue 怎么用 vm.\$set() 解决对象新增属性不能响应的问题 ?
受现代 JavaScript 的限制 ,Vue 无法检测到对象属性的添加或删除。由于 Vue 会在初始化实例时对属性执行 getter/setter 转化,所以属性必须在 data 对象上存在才能让 Vue 将它转换为响应式的。但是 Vue 提供了 Vue.set (object, propertyName, value) / vm.\$set (object, propertyName, value) 来实现为对象添加响应式属性,那框架本身是如何实现的呢?
```typescript
export function set(target: Array<any> | Object, key: any, val: any): any {
// target 为数组
if (Array.isArray(target) && isValidArrayIndex(key)) {
// 修改数组的长度, 避免索引>数组长度导致splcie()执行有误
target.length = Math.max(target.length, key)
// 利用数组的splice变异方法触发响应式
target.splice(key, 1, val)
return val
}
// key 已经存在,直接修改属性值
if (key in target && !(key in Object.prototype)) {
target[key] = val
return val
}
const ob = (target: any).__ob__
// target 本身就不是响应式数据, 直接赋值
if (!ob) {
target[key] = val
return val
}
// 对属性进行响应式处理
defineReactive(ob.value, key, val)
ob.dep.notify()
return val
}
```
## Vue 是如何实现数据双向绑定的?
Vue 主要通过以下 4 个步骤来实现数据双向绑定的:
实现一个监听器 Observer:对数据对象进行遍历,包括子属性对象的属性,利用 Object.defineProperty() 对属性都加上 setter 和 getter。这样的话,给这个对象的某个值赋值,就会触发 setter,那么就能监听到了数据变化。
实现一个解析器 Compile:解析 Vue 模板指令,将模板中的变量都替换成数据,然后初始化渲染页面视图,并将每个指令对应的节点绑定更新函数,添加监听数据的订阅者,一旦数据有变动,收到通知,调用更新函数进行数据更新。
实现一个订阅者 Watcher:Watcher 订阅者是 Observer 和 Compile 之间通信的桥梁 ,主要的任务是订阅 Observer 中的属性值变化的消息,当收到属性值变化的消息时,触发解析器 Compile 中对应的更新函数。
实现一个订阅器 Dep:订阅器采用 发布-订阅 设计模式,用来收集订阅者 Watcher,对监听器 Observer 和 订阅者 Watcher 进行统一管理。
## 优化
- (1)代码层面的优化
v-if 和 v-show 区分使用场景
computed 和 watch 区分使用场景
v-for 遍历必须为 item 添加 key,且避免同时使用 v-if
长列表性能优化
事件的销毁
图片资源懒加载
路由懒加载
第三方插件的按需引入
优化无限列表性能
服务端渲染 SSR or 预渲染
- (2)Webpack 层面的优化
Webpack 对图片进行压缩
减少 ES6 转为 ES5 的冗余代码
提取公共代码
模板预编译
提取组件的 CSS
优化 SourceMap
构建结果输出分析
Vue 项目的编译优化
- (3)基础的 Web 技术的优化
开启 gzip 压缩
浏览器缓存
CDN 的使用
使用 Chrome Performance 查找性能瓶颈
## links
- [30 道 Vue 面试题,内含详细讲解(涵盖入门到精通,自测 Vue 掌握程度)](https://juejin.im/post/5d59f2a451882549be53b170#heading-25)
- https://juejin.im/post/5e04411f6fb9a0166049a073#heading-7
|
Markdown
|
UTF-8
| 2,099 | 2.765625 | 3 |
[] |
no_license
|
# Response utils
A set of utitilties for response:
1. `topicUrl.fromConfig()` returns a topic url for a given response config
1. `EmbedTagParser` Parses a response embed tag and returns a config object.
## Response embed tag parser
## Response embed tag parser
Read and validate response embed config from different sources
### Example: Read an embed config from `data-attributes` of a DOM element
### Embed tag element
```html
<div data-kind="imagestream"
data-hash-tag="#banan"
data-title="Vis oss dine egne bananbilder!"
data-article-id="1337"
data-article-title="Jon (15) fant banan i fruktdisken"
data-article-url="http://www.banan.no/article1337.ece"
>
</div>
```
### Parse config from element
```javascript
var EmbedTag = require("response-util").EmbedTag;
// OR: var EmbedTag = require("response-util/embed-tag");
var embedTag = new EmbedTag.fromElement(element);
var result = embedTag.parse()
// result is now an object that looks like this:
{
// The configuration read from the element
config: {
kind: 'imagestream',
hashTag: 'banan',
title: 'Vis oss dine egne bananbilder',
article: {
id: '1337',
title: 'Jon (15) fant banan i fruktdisken',
url: 'http://www.banan.no/article1337.ece'
}
}
// Any errors that occurred while reading configuration. If this is not empty, the response embed
// can not be initialized
errors: [],
// Any warnings that occurred while reading configuration.
// If this is not empty, the response embed can be intialized, but some configuration values are
// probably just guesses
warnings: []
}
```
Errors are instances of the Error class, hand has an additional `attribute` property which refers to
the corresponding data-attribute that had the wrong value
## Development
### Getting started:
$ npm install
### Build
Remember to build project before bumping version and pushing a new version
$ npm run build
You can also watch source files and build project when a file changes with
$ gulp watch
### Run tests
$ npm test
|
Swift
|
UTF-8
| 1,347 | 3.03125 | 3 |
[] |
no_license
|
//
// RunToVentView.swift
// Aperture Escape
//
// Created by Xia He on 2021/7/26.
//
import SwiftUI
struct RunToVentView: View {
let gameState: GameState
var body: some View {
GeometryReader { metric in
ScrollView {
VStack {
HeaderImage(imageName: "vent")
Text("You found a metal vent door at one corner.")
.padding()
.frame(width: metric.size.width, alignment: .leading)
ImageButton(imageName: "crowbar", label: "", width: metric.size.width*0.8)
Text("With a crowbar out of nowhere, you broke it open and crawled inside. Fortunately, the neurotoxin floated high above the floor, so you are safe from being suffocated here.")
.padding()
NavigationLink("Move Forward", destination: CentralAIChamberView(gameState: gameState))
.font(.title2)
}
}
}
.navigationBarTitle("Through the Vent")
.preferredColorScheme(.light)
}
}
struct RunToVentView_Previews: PreviewProvider {
static var previews: some View {
RunToVentView(gameState: GameState())
}
}
|
Java
|
UTF-8
| 1,037 | 3.453125 | 3 |
[] |
no_license
|
//Figure / Sculpture
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int r, c;
r = sc.nextInt();
c = sc.nextInt();
int[][] input = new int[r][c];
//Leer todo el input
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
input[i][j] = sc.nextInt();
}
sc.nextLine();
}
for (int i = 0; i < c && r > 0; i++) {
System.out.print("0 ");
}
System.out.println("");
for (int i = 1; i < r-1; i++) {
System.out.print("0 ");
for (int j = 1; j < c-1; j++) {
if (input[i-1][j] > input[i][j] && input[i+1][j] > input[i][j] && input[i][j-1] > input[i][j] && input[i][j+1] > input[i][j]){
System.out.print("1 ");
} else {
System.out.print("0 ");
}
}
System.out.println(c > 2 ? "0": "");
}
for (int i = 0; i < c && r > 2; i++) {
System.out.print("0 ");
}
System.out.println("");
sc.close();
}
}
|
Java
|
UTF-8
| 535 | 1.976563 | 2 |
[] |
no_license
|
package com.service;
import com.POJO.User;
/**
* @author: 曹樾
* @program: task5-module
* @description: 登录
* @create: 2018/5/8 下午3:17
*/
public interface LoginService {
int deleteByPrimaryKey(Integer id);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
User selectByUser(User user);
User findUserByname(String name);
}
|
C
|
UTF-8
| 1,266 | 2.640625 | 3 |
[] |
no_license
|
#include "TPO.h"
int BorrarPost (int fd, NodePost *PRoot, int id)
{
char* buffer[BUFFER];
POST *find;
NodePost *Aux=PRoot;
int sel,i;
buffer[BUFFER]=NULL; //pongo el ultimo puntero a NULL para saber que termino
for(i=0; Aux!=NULL; i++) //Creo vector de Titulos
{
buffer[i]=(char *)malloc(sizeof(strlen(Aux->post.titulo)+1));
strcpy(buffer[i],Aux->post.titulo);
Aux=Aux->nxt;
}
buffer[i]=NULL;
if((send(fd,&i,sizeof(int),0))==-1) //Envio cantidad
{
perror("Send: ");
exit(1);
}
for(i=0; buffer[i]!=NULL; i++)
{
if((send(fd,buffer[i],strlen(buffer[i])+1,0))==-1) //Envio titulo post a post
{
perror("Send: ");
exit(1);
}
}
if((recv(fd,&sel,sizeof(int),0))==-1) //Recivo seleccion
{
perror("Recv: ");
exit(1);
}
find=BuscoPost(buffer[sel],PRoot); //Busco publicacion a borrar
if(find->id!=id && id!=1)
{
i=0;
if((send(fd,&i,sizeof(int),0))==-1) //Envio cantidad
{
perror("Send: ");
exit(1);
}
return 1;
}
if(BorrarNodoPub(find->id,PRoot)) //Borro
return 1;
i=1;
if((send(fd,&i,sizeof(int),0))==-1) //Envio cantidad
{
perror("Send: ");
exit(1);
}
return 0;
}
|
PHP
|
UTF-8
| 1,357 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace TheArKaID\LaravelFaspay\Debit\Entity;
class FaspayPaymentChannelResponse {
private $response_code;
private $response_desc;
private $response;
private $merchant_id;
private $merchant;
private $payment_channel;
function getResponse() {
return $this->response;
}
function getMerchant_id() {
return $this->merchant_id;
}
function getMerchant() {
return $this->merchant;
}
function getPayment_channel() {
return $this->payment_channel;
}
function setResponse($response) {
$this->response = $response;
}
function setMerchant_id($merchant_id) {
$this->merchant_id = $merchant_id;
}
function setMerchant($merchant) {
$this->merchant = $merchant;
}
function setPayment_channel($payment_channel) {
$this->payment_channel = $payment_channel;
}
function getResponse_code() {
return $this->response_code;
}
function getResponse_desc() {
return $this->response_desc;
}
function setResponse_code($response_code) {
$this->response_code = $response_code;
}
function setResponse_desc($response_desc) {
$this->response_desc = $response_desc;
}
}
|
Java
|
UTF-8
| 597 | 1.664063 | 2 |
[] |
no_license
|
package ir.ssa.parkban.repository;
import ir.ssa.parkban.domain.entities.MessageReceiverEntity;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.querydsl.QueryDslPredicateExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
/**
* author hym
*/
@Repository
public interface MessageReceiverDAO extends PagingAndSortingRepository<MessageReceiverEntity, Long>, JpaSpecificationExecutor<MessageReceiverEntity>, QueryDslPredicateExecutor<MessageReceiverEntity> {
}
|
Java
|
UTF-8
| 2,006 | 3.25 | 3 |
[] |
no_license
|
package com.example.abhishek.jokeprovider;
import java.util.Random;
public class JokeProvider {
private final Random random = new Random();
private String[] jokes = {
"The more I C.... the less I see.",
"July 4th is Independence day. And the day Chuck Norris was born. Coincidence? I think not.",
"Bill Gates thinks he's Chuck Norris. Chuck Norris actually laughed. Once.",
"In a world without fences and walls... who needs Gates and Windows?",
"If I wanted a warm fuzzy feeling... Id antialias my graphics!",
"Microsoft: You've got questions. We've got dancing paperclips.",
"binary digits are called bits i love ternary digits",
"To err is human and to blame it on a computer is even more so.",
"C://dos <br>C://dos.run <br>run.dos.run",
"Erik Naggum: Microsoft is not the answer. Microsoft is the question. NO is the answer.",
"There are only 10 types of people in the world: those that understand binary, those that don't, and those that didn't expect a ternary joke.",
"Computers make very fast and very accurate mistakes.",
"The beginning of the programmers wisdom is understanding the difference between getting program to run and having a runnable program.",
"There is no place like 127.0.0.1",
"I can't access Git. I guess I have... commitment issues",
"Why is C sad? Because C++ told him \"You have no class\".",
"My daily Unix command list: unzip; strip; touch; finger; mount; fsck; more; yes; unmount; sleep.",
"Mac users swear by their Mac and PC users swear at their PC.",
"Windows isn't a virus, at least viruses do something.",
"Le gf: I'll dump you.\nLe bf: hex dump or binary dump?"
};
public String getJoke() {
return "A random joke";
}
public String getRandomJoke() {
return jokes[random.nextInt(jokes.length)];
}
}
|
Java
|
UTF-8
| 2,319 | 3.703125 | 4 |
[] |
no_license
|
package lxl.y2020.DEC;
import java.util.PriorityQueue;
/**
* @program: leetcode-hz
* @description: 915. 分割数组
* 给定一个数组 A,将其划分为两个不相交(没有公共元素)的连续子数组 left 和 right, 使得:
* <p>
* left 中的每个元素都小于或等于 right 中的每个元素。
* left 和 right 都是非空的。
* left 要尽可能小。
* <p>
* 在完成这样的分组后返回 left 的长度。可以保证存在这样的划分方法。
* <p>
* <p>
* <p>
* 示例 1:
* <p>
* 输入:[5,0,3,8,6]
* 输出:3
* 解释:left = [5,0,3],right = [8,6]
* <p>
* 示例 2:
* <p>
* 输入:[1,1,1,0,6,12]
* 输出:4
* 解释:left = [1,1,1,0],right = [6,12]
* <p>
* <p>
* <p>
* 提示:
* <p>
* 2 <= A.length <= 30000
* 0 <= A[i] <= 10^6
* 可以保证至少有一种方法能够按题目所描述的那样对 A 进行划分。
* <p>
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/partition-array-into-disjoint-intervals
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
* @author: lxl
* @create: 2020-12-22 10:35
**/
public class PartitionArrayIntoDisjointIntervals {
public int partitionDisjoint(int[] A) {
int len = A.length;
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(len);
for (int i = 1; i < len; i++) {
priorityQueue.add(A[i]);
}
int ansLen = 1;
int max = A[0];
int temp;
while (max > priorityQueue.peek()) {
temp = A[ansLen];
ansLen++;
max = Math.max(max, temp);
priorityQueue.remove(temp);
}
return ansLen;
}
public int partitionDisjoint2(int[] A) {
int N = A.length;
int[] maxleft = new int[N];
int[] minright = new int[N];
int m = A[0];
for (int i = 0; i < N; ++i) {
m = Math.max(m, A[i]);
maxleft[i] = m;
}
m = A[N - 1];
for (int i = N - 1; i >= 0; --i) {
m = Math.min(m, A[i]);
minright[i] = m;
}
for (int i = 1; i < N; ++i)
if (maxleft[i - 1] <= minright[i])
return i;
throw null;
}
}
|
C++
|
UTF-8
| 815 | 2.6875 | 3 |
[] |
no_license
|
#include <iostream>
#include <stdio.h>
#include <map>
#include <string>
#include <string.h>
#include <set>
#include <math.h>
using namespace std;
double check(double x){
return 6*x*x*x+5*x*x+7*x+9;
}
int main()
{
double n;
while(scanf("%lf",&n)!=EOF){
double l=-0.000000001,r=10.00000000001;
int flag=0;
double ans=-1;
while(l+1e-12<r){
double mid=(l+r)/2;
if(fabs(check(mid)-n)<=1e-8)
{
ans=mid;
flag=1;
break;
}else if(check(mid)>n)
r=mid;
else if(check(mid)<n)
l=mid;
}
if(flag==1)
{
printf("%.4f\n",ans);
}else{
printf("No solution!\n");
}
}
return 0;
}
|
Python
|
UTF-8
| 1,159 | 2.796875 | 3 |
[] |
no_license
|
import os.path
import pickle
from conui import Contact
_path_ = "data.dat"
def load() -> dict:
if os.path.exists(_path_):
with open(_path_, "rb") as file:
data = pickle.load(file)
return data
else:
return {}
def save(db:dict):
with open(_path_, "wb") as file:
pickle.dump(db, file, pickle.HIGHEST_PROTOCOL)
def create(db:dict,contact: Contact):
db[get_code(contact)] = contact
def read(db:dict,id: str) -> Contact:
return db[id]
def update(db:dict, old: Contact, new: Contact):
db[get_code(old)] = new
def get_code(contact: Contact) -> str:
return contact.f_name[:3] + contact.l_name[:3]
def delete(db:dict, contact: Contact):
del db[get_code(contact)]
def exists(db:dict, contact: Contact) -> bool:
return get_code(contact) in db
def search(db: dict, name: str) -> list[[Contact]]:
rslt = []
for contact in db.values():
if contact.l_name.lower().startswith(name):
rslt.append(contact)
return rslt
def findall(db:dict):
return list(db.values())
def find(contact: Contact) -> Contact:
return read(get_code(contact))
|
Java
|
UTF-8
| 1,817 | 2.4375 | 2 |
[
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] |
permissive
|
/**
*
*
* @author WILEDION
*/
package kani.monde;
import kani.utils.KaniMap;
import org.newdawn.slick.Animation;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.geom.Polygon;
import org.newdawn.slick.geom.Shape;
/**
* Classe personnage de jeu
*/
public class Perso extends Chose {
Animation sprite;
int pv;
int mana;
float dx;
float dy;
int height;
int width;
int level_width;
int level_height;
int mode;
Polygon surface;
boolean is_dead;
public Perso() {
sprite = new Animation();
}
public void init() {
sprite = new Animation();
}
public void dessiner() {
sprite.draw(posx, posy);
}
public void dessiner(float X, float Y) {
sprite.draw(X, Y);
}
public void setX(float X) {
}
public void setY(float Y) {
}
public float getX() {
return posx;
}
public float getY() {
return posy;
}
public void setLevelWidth(int levelw) {
level_width = levelw;
}
public void setLevelHeight(int levelh) {
{
level_height = levelh;
}
}
public void setAnim(Animation anim) {
sprite = anim;
height = anim.getHeight();
width = anim.getWidth();
}
void set(float X, float Y) {
}
void deplacer(float X, float Y) {
}
public void update(KaniMap map) throws SlickException {
}
public void setMap(KaniMap maptest) {
setLevelWidth(maptest.getMapWidth());
setLevelHeight(maptest.getMapHeight());
surface = maptest.get_surface();
}
public Shape get_poly() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
|
Python
|
UTF-8
| 1,751 | 3.046875 | 3 |
[] |
no_license
|
## Downsampling
import pandas as pd
#detail
def detailDownsampled():
data=pd.read_csv("detail.csv",parse_dates =['Absolute Time'], index_col ='Absolute Time') #reading the csv file that was saved in task 1 and setting Absolute time as index column
data.drop(['Record Index'], axis='columns', inplace=True) # Droping Record index column as its not neccessary
detail_resampled = data.resample('1 min').mean() #sampling the dataset (Taking subsets (means)) at 1 sample/minute
detail_resampled.to_csv('detailDownsampled.csv') #saving the dataframe as csv file
#detailTemp
def detailTempDownsampled():
data=pd.read_csv("detailTemp.csv",parse_dates =['Realtime'], index_col ='Realtime') #reading the csv file that was saved in task 1 and setting Absolute time as index column
data.drop(['Record ID'], axis='columns', inplace=True) # Droping Record id column as its not neccessary
detailTemp_resampled = data.resample('1 min').mean() #sampling the dataset (Taking subsets (means)) at 1 sample/minute
detailTemp_resampled.to_csv('detailTempDownsampled.csv') #saving the dataframe as csv file
#detailVol
def detailVol_resample():
data=pd.read_csv("detailVol.csv",parse_dates =['Realtime'], index_col ='Realtime') #reading the csv file that was saved in task 1 and setting Absolute time as index column
data.drop(['Record ID'], axis='columns', inplace=True) # Droping Record id column as its not neccessary
detailVol_resampled = data.resample('1 min').mean() #sampling the dataset (Taking subsets (means)) at 1 sample/minute
detailVol_resampled.to_csv('detailVolDownsampled.csv') #saving the dataframe as csv file
detailDownsampled()
detailVol_resample()
detailTempDownsampled()
|
JavaScript
|
UTF-8
| 1,619 | 3.328125 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
const DOG_URL = 'http://localhost:3000/pups'
const dogBarEl = document.getElementById('dog-bar')
const dogInfoEl = document.getElementById('dog-info')
const dogFilterBtn = document.getElementById('good-dog-filter')
let toggle = false
const getDogs = () => {
return fetch(DOG_URL)
.then(resp => resp.json())
.then(dogs => renderAllDogs(dogs))
}
const renderAllDogs = dogs => {
dogs = filteredDogs(dogs)
dogBarEl.innerHTML = ''
dogs.forEach(dog => {
renderDog(dog)
});
}
const renderDog = dog => {
let dogSpan = document.createElement('span')
dogSpan.innerText = `${dog.name}`
dogSpan.addEventListener('click', e => renderDogInfo(dog))
dogBarEl.appendChild(dogSpan)
}
const renderDogInfo = dog => {
let btn = document.createElement('button')
btn.innerText = dog.isGoodDog ? 'Bad Dog!' : 'Good Dog!'
dogInfoEl.innerHTML = ` <img src='${dog.image}'>
<h2>${dog.name}</h2>`
btn.addEventListener('click', e => updateDog(dog))
dogInfoEl.appendChild(btn)
}
const updateDog = dog => {
return fetch(DOG_URL+'/'+dog.id, {
method: 'PATCH',
headers:{'content-type':'application/json'},
body: JSON.stringify({isGoodDog: !dog.isGoodDog})
})
.then(resp => resp.json())
.then(dog => renderDogInfo(dog))
.then(() => getDogs())
}
dogFilterBtn.addEventListener('click', e => {
toggle = !toggle
dogFilterBtn.innerText = toggle ? 'Filter good dogs: ON':'Filter good dogs: OFF'
getDogs()
})
const filteredDogs = dogs => {
return toggle ? dogs.filter(dog => dog.isGoodDog === toggle):dogs
}
getDogs()
|
Java
|
UTF-8
| 3,300 | 1.953125 | 2 |
[] |
no_license
|
package com.vf.ana;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class MonthWiseAggregationLast1YrTopLevelTests {
@Autowired
MonthWiseAggregationLast1YrTopLevel monthWiseAggregationLast1YrTopLevel;
Logger logger = LoggerFactory.getLogger(getClass());
@Test
void testOrderValue() {
logger.debug("----------ov----------------");
final Map<String, List<String>> filters = new HashMap<>();
monthWiseAggregationLast1YrTopLevel.aggregateMonthWiseForLastOneYear(Constants.ORDER_VALUE, filters);
final List<String> suppIds = new ArrayList<>();
// suppIds.add("xxxxxxxxxxxxxxxxxx");
suppIds.add("0400074915");
filters.put("supplierId", suppIds);
monthWiseAggregationLast1YrTopLevel.aggregateMonthWiseForLastOneYear(Constants.ORDER_VALUE, filters);
}
@Test
void testInvoiceValue() {
logger.debug("----------iv----------------");
final Map<String, List<String>> filters = new HashMap<>();
monthWiseAggregationLast1YrTopLevel.aggregateMonthWiseForLastOneYear(Constants.INVOICE_VALUE, filters);
final List<String> suppIds = new ArrayList<>();
// suppIds.add("xxxxxxxxxxxxxxxxxx");
suppIds.add("0400074915");
filters.put("supplierId", suppIds);
monthWiseAggregationLast1YrTopLevel.aggregateMonthWiseForLastOneYear(Constants.INVOICE_VALUE, filters);
}
@Test
void testActiveItems() {
logger.debug("----------AI----------------");
final Map<String, List<String>> filters = new HashMap<>();
monthWiseAggregationLast1YrTopLevel.aggregateMonthWiseForLastOneYear(Constants.ACTIVE_ITEMS, filters);
final List<String> suppIds = new ArrayList<>();
// suppIds.add("xxxxxxxxxxxxxxxxxx");
suppIds.add("0400074915");
filters.put("supplierId", suppIds);
monthWiseAggregationLast1YrTopLevel.aggregateMonthWiseForLastOneYear(Constants.ACTIVE_ITEMS, filters);
}
@Test
void testActivePAs() {
logger.debug("----------PA----------------");
final Map<String, List<String>> filters = new HashMap<>();
monthWiseAggregationLast1YrTopLevel.aggregateMonthWiseForLastOneYear(Constants.ACTIVE_PRICE_AGREEMENT, filters);
final List<String> suppIds = new ArrayList<>();
// suppIds.add("xxxxxxxxxxxxxxxxxx");
suppIds.add("0400074915");
filters.put("supplierId", suppIds);
monthWiseAggregationLast1YrTopLevel.aggregateMonthWiseForLastOneYear(Constants.ACTIVE_PRICE_AGREEMENT, filters);
}
@Test
void testOrderIssued() {
logger.debug("----------ov----------------");
final Map<String, List<String>> filters = new HashMap<>();
monthWiseAggregationLast1YrTopLevel.aggregateMonthWiseForLastOneYear(Constants.NUMBER_OF_ORDERS, filters);
final List<String> suppIds = new ArrayList<>();
// suppIds.add("xxxxxxxxxxxxxxxxxx");
suppIds.add("0400074915");
filters.put("supplierId", suppIds);
monthWiseAggregationLast1YrTopLevel.aggregateMonthWiseForLastOneYear(Constants.NUMBER_OF_ORDERS, filters);
}
}
|
JavaScript
|
UTF-8
| 1,871 | 2.75 | 3 |
[
"Apache-2.0"
] |
permissive
|
'use strict'
const { expect } = require('chai')
const fs = require('fs')
const path = require('path')
const programmeChangeWatcher = require('./../ProgrammeChangeWatcher')
const PATH = '.'
const FILE_NAME = 'programme.json'
const FILE_PATH = path.join(PATH, '/', FILE_NAME)
describe('ProgrammeFileWatcher', function () {
let watcher
beforeEach(() => {
try {
deleteFile()
} catch (e) {}
writeFile({})
})
afterEach(() => {
watcher.stop()
try {
deleteFile()
} catch (e) {}
})
function writeFile (programmeData) {
fs.writeFile(FILE_PATH, JSON.stringify(programmeData), function (err) {
if (err) {
console.log(`Error writing programme file: ${err}`)
throw err
}
console.log('Programme data file saved.')
})
}
function deleteFile () {
fs.unlinkSync(FILE_PATH)
}
it('should callback with new programme when new file written', function (done) {
watcher = programmeChangeWatcher.watchForChanges(PATH, function (programme) {
expect(programme.getComfortSetPoint()).to.equal(21)
watcher.stop()
done()
})
writeFile({ comfortTemp: 21 })
})
it('should callback a second time when written again', function (done) {
let calls = 0
watcher = programmeChangeWatcher.watchForChanges(PATH, function (programme) {
calls++
if (calls < 2) {
expect(programme.getComfortSetPoint()).to.equal(21)
writeFile({ comfortTemp: 22 })
} else {
expect(programme.getComfortSetPoint()).to.equal(22)
watcher.stop()
done()
}
})
writeFile({ comfortTemp: 21 })
})
})
|
Java
|
UTF-8
| 452 | 1.703125 | 2 |
[] |
no_license
|
package com.xiangyu.web.controller.test;
import com.xiangyu.ext.base.BaseController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Created by xiangyu on 2016/11/4.
*/
@SuppressWarnings("unused")
@Controller
@RequestMapping("/test")
public class testController extends BaseController {
@RequestMapping
public String index(){
return "test/test.html";
}
}
|
Markdown
|
UTF-8
| 133 | 2.5625 | 3 |
[] |
no_license
|
# Capstone project deals in analysing the hotel's reviews and predicting a score to the hotel based on its positive/negative reviews
|
Markdown
|
UTF-8
| 13,144 | 3.5 | 4 |
[] |
no_license
|
#Getting and Cleaning Data Course Project (Coursera)
>Codebook for the project of Getting and Cleaning Data Course, available in Coursera.
>This codebook describes the analysis performed by the `run_analysis.R` script, describing the
>variables, the data and the transformations performed to clean up the raw data in order to create
>a tidy data set. The purpose of the project is to demonstrate the ability to collect, work with,
>and clean a data set. The goal is to prepare a tidy data that can be used for later analysis.
##The data
The raw data set used in the project represent data collected from the accelerometers
from the Samsung Galaxy S smarthphone. A full description of the raw data set is available
in the [UCI Machine Learning Repository]. The data for the project can be directly downloaded
[here]. Unziping the downloaded file a `UCI HAR Dataset` folder is created, containing all
the files needed for the analysis. This folder must be located in the working directory.
The data set represents a series of experiments carried out with a group of 30 volunteers
within an age bracket of 19-48 years. Each person performed six activities (labelled in the
`activity_labels.txt` file) wearing a smarthphone (Samsung Galaxy S II) on the waist.
Using the embedded accelerometer and gyroscope, a 3-axial linear acceleration and 3-axial angular velocity
at a constant rate of 50 Hz were captured. The dataset has been randomly partitioned into two sets, where 70%
of the volunteers was selected for generating the training data (inside the `./UCI HAR Dataset/train` folder), and 30%
the test data (inside the `./UCI HAR Dataset/test` folder).
The sensor signals (accelerometer and gyroscope) were pre-processed by applying noise filters
and then sampled in fixed-width sliding windows of 2.56 sec and 50% overlap (128 readings/window).
The sensor acceleration signal, which has gravitational and body motion components, was separated using a
Butterworth low-pass filter into body acceleration and gravity. From each window, a vector of
features was obtained by calculating variables from the time and frequency domain. The last is
expressed in a 561-feature vector (the name of each feature measured is in `features.txt`).
The test and train datasets (in `./UCI HAR Dataset/test` and `./UCI HAR Dataset/train` folders) comprises three types
of text files that are used in the analysis:
- A file referring the volunteer identification of each measurement: `subject_test.txt` and `subject_train.txt`.
- A file with the activity performed during each measurement (codified as numbers): `Y_test.txt` and `Y_train.txt`.
- A bigger file with the 561-feature vector: `X_test.txt` and `X_train.txt`.
##The R script
The course project says:
> You should create one R script called run_analysis.R that does the following:
> 1. Merges the training and the test sets to create one data set.
> 2. Extracts only the measurements on the mean and standard deviation for each measurement.
> 3. Uses descriptive activity names to name the activities in the data set
> 4. Appropriately labels the data set with descriptive variable names.
> 5. From the data set in step 4, creates a second, independent tidy data set with the average of each variable for each activity and each subject.
The R script named `run_analysis.R` prepares a tidy dataset from the raw dataset.
The raw dataset must be in a unzip folder named `UCI HAR Dataset` in the working directory, and package "dplyr" must be installed. The procedure
follows a different order from the one specified in the list above in order to simplify some steps like filtering.
1. The first section of the code reads the text files containing the data using the `read.table()` function.
This data is assigned to a variable with the same name as the text file. To avoid messing up the data with factors, the
argument 'stringsAsFactors=FALSE' is used.
```
- activity_labels<-read.table("./UCI HAR Dataset/activity_labels.txt", stringsAsFactors=FALSE)
- features<-read.table("./UCI HAR Dataset/features.txt", stringsAsFactors=FALSE)
- subject_test<-read.table("./UCI HAR Dataset/test/subject_test.txt")
- X_test<-read.table("./UCI HAR Dataset/test/X_test.txt")
- Y_test<-read.table("./UCI HAR Dataset/test/Y_test.txt")
- subject_train<-read.table("./UCI HAR Dataset/train/subject_train.txt")
- X_train<-read.table("./UCI HAR Dataset/train/X_train.txt")
- Y_train<-read.table("./UCI HAR Dataset/train/Y_train.txt")
```
2. The data.frames containing activity labels, subjects and features labels (corresponding to features.txt, activity_labels.txt, Y_test.txt and Y_train.txt),
are converted to vectors by subsetting (using `[]`).
```
- features<-features[,2]
- subject_test<-subject_test[,1]
- Y_test<-Y_test[,1]
- subject_train<-subject_train[,1]
- Y_train<-Y_train[,1]
- activity_labels<-activity_labels[,2]
```
3. Activity data is converted to factors to assign self-descriptive labels, using `as.factor()` and `levels()` functions.
```
- Y_test<-as.factor(Y_test)
- Y_train<-as.factor(Y_train)
- levels(Y_test)<-activity_labels
- levels(Y_train)<-activity_labels
```
4. Two data frames are created joining subject, activity and measurements for each group (test and train), using `data.frame()` function. Using this data.frames, a unique dataset for both groups is created using `cbind()` function.
```
- test<-data.frame(subject=subject_test,activity=Y_test, X_test)
- train<-data.frame(subject=subject_train, activity=Y_train, X_train)
- dataset<-rbind(test, train)
```
5. Before filtering data to maintain only the measurements relative to mean() and std() values,
an appropriate label is assigned to the columns of the dataset (to make filtering easy). The labels are included in 'features.txt' file, however, this
includes characters that can`t be used as names in R (the characters "-" and "()"). This characters are replaced by a more addecuated ones
using the function `gsub()`. A vector with the features names is created to perform corrections.
```
- dataset_column_names<-c("Subject", "Activity", features)
- dataset_column_names<-gsub("\\(\\)", "" , dataset_column_names)
- dataset_column_names<-gsub("-", "_" , dataset_column_names)
```
6. Using the same `gsub()` function, self-descriptive names for features are generated, replacing the following characters:
* t prefix is replaced by time
* f prefix is replaced by frequency
* Acc is replaced by Accelerometer
* Gyro is replaced by Gyroscope
* Mag is replaced by Magnitude
* BodyBody is replaced by Body
```
- dataset_column_names<-gsub("^t", "time", dataset_column_names)
- dataset_column_names<-gsub("^f", "frequency", dataset_column_names)
- dataset_column_names<-gsub("Acc", "Accelerometer" , dataset_column_names)
- dataset_column_names<-gsub("Gyro", "Gyroscope" , dataset_column_names)
- dataset_column_names<-gsub("Mag", "Magnitude" , dataset_column_names)
- dataset_column_names<-gsub("BodyBody", "Body" , dataset_column_names)
```
7. Names are assigned to each column of the dataset using `names()` function.
```
- names(dataset)<-dataset_column_names
```
8. Using the column names, de dataset is filtered to maintain only the measurements relative
to mean() and std(). The function `grepl()` is used to generate the filters. A 'filter1' is used to
select only the columns with "Subject", "Activity", "mean" of "std" in the column name. A 'filter2' is
again used to eliminate from the generated subset the columns relative to "meanFreq".
```
- filter1<-grepl("Subject|Activity|mean|std", names(dataset))
- dataset<-dataset[,filter1]
- filter2<-grepl("meanFreq", names(dataset))
- dataset<-dataset[,!filter2]
```
9. Finally, a subset of the tidy dataset generated in 8 is created. This subset comprises only the average of each
variable for each activity and each subject. The packadge "dplyr" is used to achieve this. The subset is saved to a
text file `using write.table()` function (with the argument row.name=FALSE).
```
- library(dplyr)
- subset<-dataset %>% group_by(Subject,Activity) %>% summarise_each(funs(mean))
- write.table(subset, file="subset.txt", row.name=FALSE)
```
##The variables
The variables used in the script are described below:
- `activity_labels`: vector for activity labeling
- `features`: vector with the 561-features vector labels
- `subject_test`: vector with subject identification for test group
- `X_test`: dataframe with measurements for test group
- `Y_train`: vector with activity identification for test group
- `subject_train`: vector with subject identification for train group
- `X_train`: dataframe with measurements for train group
- `Y_train`: vector with activity identification for train group
- `test`: dataframe with the complete test data (subject, activity and measurements)
- `train`: dataframe with the complete train data (subject, activity and measurements)
- `dataset`: dataframe joining test and train data
- `dataset_column_names`: character vector with self-descriptive names for features
- `filter1`: logical vector to select columns referring "subject", "activity", "mean" of "std"
- `filter2`: logical vector to eliminate columns relative to "meanFreq"
- `subset`: dataframe with the final data, averaging each measurement by each subject and each activity
The raw data considers the following variables (unitless, because they are normalized):
>The features selected for this database come from the accelerometer and gyroscope 3-axial raw signals
tAcc-XYZ and tGyro-XYZ. These time domain signals (prefix 't' to denote time) were captured at a
constant rate of 50 Hz. Then they were filtered using a median filter and a 3rd order low pass
Butterworth filter with a corner frequency of 20 Hz to remove noise. Similarly, the acceleration
signal was then separated into body and gravity acceleration signals (tBodyAcc-XYZ and tGravityAcc-XYZ)
using another low pass Butterworth filter with a corner frequency of 0.3 Hz. Subsequently, the body
linear acceleration and angular velocity were derived in time to obtain Jerk signals
(tBodyAccJerk-XYZ and tBodyGyroJerk-XYZ). Also the magnitude of these three-dimensional
signals were calculated using the Euclidean norm (tBodyAccMag, tGravityAccMag, tBodyAccJerkMag,
tBodyGyroMag, tBodyGyroJerkMag). Finally a Fast Fourier Transform (FFT) was applied to
some of these signals producing fBodyAcc-XYZ, fBodyAccJerk-XYZ, fBodyGyro-XYZ, fBodyAccJerkMag,
fBodyGyroMag, fBodyGyroJerkMag. (Note the 'f' to indicate frequency domain signals).These signals were
used to estimate variables of the feature vector for each pattern: '-XYZ' is used to denote 3-axial
signals in the X, Y and Z directions.
> - tBodyAcc-XYZ
> - tGravityAcc-XYZ
> - tBodyAccJerk-XYZ
> - tBodyGyro-XYZ
> - tBodyGyroJerk-XYZ
> - tBodyAccMag
> - tGravityAccMag
> - tBodyAccJerkMag
> - tBodyGyroMag
> - tBodyGyroJerkMag
> - fBodyAcc-XYZ
> - fBodyAccJerk-XYZ
> - fBodyGyro-XYZ
> - fBodyAccMag
> - fBodyAccJerkMag
> - fBodyGyroMag
> - fBodyGyroJerkMag
>
>From these signals a set if variables were estimated:
> - mean(): Mean value
> - std(): Standard deviation
> - mad(): Median absolute deviation
> - max(): Largest value in array
> - min(): Smallest value in array
> - sma(): Signal magnitude area
> - energy(): Energy measure. Sum of the squares divided by the number of values.
> - iqr(): Interquartile range
> - entropy(): Signal entropy
> - arCoeff(): Autorregresion coefficients with Burg order equal to 4
> - correlation(): correlation coefficient between two signals
> - maxInds(): index of the frequency component with largest magnitude
> - meanFreq(): Weighted average of the frequency components to obtain a mean frequency
> - skewness(): skewness of the frequency domain signal
> - kurtosis(): kurtosis of the frequency domain signal
> - bandsEnergy(): Energy of a frequency interval within the 64 bins of the FFT of each window.
> - angle(): Angle between to vectors.
In the subset ('subset.txt') created only mean() and std() values are present, and the features names were changed to be more descriptive:
- timeBodyAccelerometer-XYZ
- timeGravityAccelerometer-XYZ
- timeBodyAccelerometerJerk-XYZ
- timeBodyGyroscope-XYZ
- timeBodyGyroscopeJerk-XYZ
- timeBodyAccelerometerMagnitude
- timeGravityAccelerometerMagnitude
- timeBodyAccelerometerJerkMagnitude
- timeBodyGyroscopeMagnitude
- timeBodyGyroscopeJerkMagnitude
- frequencyBodyAccelerometer-XYZ
- frequencyBodyAccelerometerJerk-XYZ
- frequencyBodyGyroscope-XYZ
- frequencyBodyAccelerometerMagnitude
- frequencyBodyAccelerometerJerkMagnitude
- frequencyBodyGyroscopeMagnitude
- frequencyBodyGyroscopeJerkMagnitude
[UCI Machine Learning Repository]:http://archive.ics.uci.edu/ml/datasets/Human+Activity+Recognition+Using+Smartphones#
[here]:https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip
|
C++
|
UTF-8
| 813 | 3.59375 | 4 |
[] |
no_license
|
#include <iostream>
using namespace std;
const int longi = 0;
int tama_cade_itera(const char cadena[], int longi);
void concate(char cadena1[], char cadena2[]);
int main(){
char cadena1[] = "Pepe";
char cadena2[20] = "Lucho";
concate(cadena1, cadena2);
cout<<cadena2;
return 0;
}
void concate(char cadena1[], char cadena2[]){
int i = 0;
int j = tama_cade_itera(cadena2,longi)+1;
while (cadena1[i] != '\0')
{
cadena2[j] = cadena1[i];
j++;
i++;
}
cadena2[tama_cade_itera(cadena2,longi)] = ' ';
cadena2[tama_cade_itera(cadena2,longi)+i] = '\0';
}
int tama_cade_itera(const char cadena[], int longi){
char actual = cadena[0];
for (; actual != '\0'; actual = cadena[++longi]);
return longi;
}
|
Markdown
|
UTF-8
| 13,386 | 2.703125 | 3 |
[
"MIT",
"CC-BY-4.0"
] |
permissive
|
---
title: Understanding and using Hyper-V hypervisor scheduler types
description: Provides information for Hyper-V host administrators on the use of Hyper-V's scheduler modes
author: allenma
ms.author: allenma
ms.date: 04/26/2018
ms.topic: article
ms.prod: windows-server-hyper-v
ms.technology: virtualization
ms.localizationpriority: low
ms.assetid: 6cb13f84-cb50-4e60-a685-54f67c9146be
---
# Understanding and using Hyper-V hypervisor scheduler types
Applies To: Windows 10, Windows Server 2016
This article describes new modes of virtual processor scheduling logic introduced in Windows Server 2016. These modes, or scheduler types, determine how the Hyper-V hypervisor allocates and manages work across guest virtual processors. A Hyper-V host administrator can select a hypervisor scheduler types that is best suited for the guest virtual machines (VMs) and configure the VMs to take advantage of the scheduling logic.
>[!NOTE]
>Updates are required to use the hypervisor scheduler features described in this document. For details, refer to Required updates.
## Background
Before discussing the logic and controls behind Hyper-V virtual processor scheduling, it’s helpful to review the basic concepts covered in this article.
### Understanding SMT
Simultaneous multithreading, or SMT, is a technique utilized in modern processor designs which allows the processor’s resources to be shared by separate, independent execution threads. SMT generally offers a modest performance boost to most workloads by parallelizing computations when possible, increasing instruction throughput, though no performance gain or even a slight loss in performance may occur when contention between threads for shared processor resources occurs.
Processors supporting SMT are available from both Intel and AMD. Intel refers to their SMT offerings as Intel Hyper Threading Technology, or Intel HT.
For the purposes of this article, the descriptions of SMT and how it is utilized by Hyper-V apply equally to both Intel and AMD systems.
* For more information on Intel HT Technology, refer to [Intel Hyper-Threading Technology](https://www.intel.com/content/www/us/en/architecture-and-technology/hyper-threading/hyper-threading-technology.html)
* For more information on AMD SMT, refer to [The "Zen" Core Architecture](https://www.amd.com/en/technologies/zen-core)
## Understanding how Hyper-V virtualizes processors
Before considering hypervisor scheduler types it’s also helpful to understand the Hyper-V architecture. You can find a general summary in the [Hyper-V Technology Overview](https://docs.microsoft.com/en-us/windows-server/virtualization/hyper-v/hyper-v-technology-overview) section. These are important concepts for this article:
* Hyper-V creates and manages virtual machine partitions, across which compute resources are allocated and shared, under control of the hypervisor. Partitions provide strong isolation boundaries between all guest virtual machines, and between guest VMs and the root partition.
* The root partition is itself a virtual machine partition, although it has unique properties and much greater privileges than guest virtual machines. The root partition provides the management services that control all guest virtual machines, provides virtual device support for guests, and manages all device I/O for guest virtual machines. Microsoft strongly recommends not running any application workloads in the root partition.
* Each virtual processor (VP) of the root partition is mapped 1:1 to an underlying logical processor (LP). A host VP will always run on the same underlying LP – there is no migration of the root partition’s VPs.
* By default, the LPs on which host VPs run can also run guest VPs.
* A guest VP may be scheduled by the hypervisor to run on any available logical processor. While the hypervisor scheduler takes care to consider temporal cache locality, NUMA topology, and many other factors when scheduling a guest VP, ultimately the VP could be scheduled on any host LP.
## Hypervisor scheduler types
Starting with Windows Server 2016, the Hyper-V hypervisor supports several modes of scheduler logic, which determine how the hypervisor schedules virtual processors on the underlying logical processors.
### The classic scheduler
The classic scheduler has been the default for all versions of the Windows Hyper-V hypervisor since its inception, including Windows Server 2016 Hyper-V. The classic scheduler provides a fair share, preemptive round- robin scheduling model for guest virtual processors.
The classic scheduler type is the most appropriate for the vast majority of traditional Hyper-V uses – for private clouds, hosting providers, and so on. The performance characteristics are well understood and are best optimized to support a wide range of virtualization scenarios, such as over-subscription of VPs to LPs, running many heterogenous VMs and workloads simultaneously, running larger scale high performance VMs, supporting the full feature set of Hyper-V without restrictions, and more.
### The core scheduler
The hypervisor core scheduler is a new alternative to the classic scheduler logic, introduced in Windows Server 2016 and Windows 10 version 1607. The core scheduler offers reduced performance variability for workloads inside of VMs which are running on an SMT- enabled virtualization host. The core scheduler allows running both SMT and non-SMT virtual machines simultaneously on the same SMT enabled virtualization host.
The core scheduler utilizes the virtualization host’s SMT topology, and optionally exposes SMT pairs to guest virtual machines, and schedules groups of guest virtual processors from the same virtual machine onto groups of SMT logical processors. This is done symmetrically so that if LPs are in groups of two, VPs are scheduled in groups of two, and a core is never shared between VMs.
When the VP for a virtual machine without SMT enabled is scheduled, that VP will consume the entire core when it runs.
The overall result of the core scheduler is that:
* Variability in throughput is significantly reduced.
* Performance is potentially reduced, because if only one of a group of VPs can run, only one of the instruction streams in the core executes while the other is left idle.
* The OS and applications running in the guest virtual machine can utilize SMT behavior and programming interfaces (APIs) to control and distribute work across SMT threads, just as they would when run non-virtualized.
The core scheduler is optional and must be explicitly enabled by the Hyper-V host administrator.
If the hypervisor is configured to use the core scheduler type but the SMT capability is disabled or not present on the virtualization host, then the hypervisor will use the classic scheduler behavior.
## Enabling SMT in guest virtual machines
Once the virtualization host’s hypervisor is configured to use the core scheduler type, guest virtual machines may be configured to utilize SMT if desired. Exposing the fact that VPs are hyperthreaded to a guest virtual machine allows the scheduler in the guest operating system and workloads running in the VM to detect and utilize the SMT topology in their own work scheduling. The SMT processor topology is not shown to a guest virtual machine by default and must be explicitly enabled by the Hyper-V host administrator.
PowerShell must be used enable SMT in a guest virtual machine; there is no user interface provided in the Hyper-V Manager UI.
To enable SMT in a guest virtual machine, open a PowerShell windows with sufficient permissions, and type:
``` powershell
Set-VMProcessor -VMName <VMName> -HwThreadCountPerCore 2
```
Below is an example of System Information taken from the guest operating system running in a virtual machine with 2 virtual processors and SMT enabled. The guest operating system is detecting 2 logical processors belonging to the same core.

### The root scheduler
The root scheduler was introduced with Windows 10 version 1804. When the root scheduler type is enabled, the hypervisor cedes control of work scheduling to the root partition. The NT scheduler in the root partition’s OS instance manages all aspects of scheduling work to system LPs.
The root scheduler addresses the unique requirements inherent with supporting a utility partition to provide strong workload isolation, as used with Windows Defender Application Guard (WDAG). In this scenario, leaving scheduling responsibilities to the root OS offers several advantages. For example, CPU resource controls applicable to container scenarios may be used with the utility partition, simplifying management and deployment. In addition, the root OS scheduler can readily gather metrics about workload CPU utilization inside the container and use this data as input to the same scheduling policy applicable to all other workloads in the system. These same metrics also help clearly attribute work done in an application container to the host system. Tracking these metrics is more difficult with traditional virtual machine workloads, where some work on all running VM’s behalf takes place in the root partition.
#### Root scheduler use on client systems
Starting with Windows 10 version 1804, the root scheduler is used by default on client systems only, where the hypervisor may be enabled in support of virtualization-based security and WDAG workload isolation, and for proper operation of future systems with heterogeneous core architectures. This is the only supported hypervisor scheduler configuration for client systems. Administrators should not attempt to override the default hypervisor scheduler type on Windows 10 client systems.
#### Virtual Machine CPU resource controls and the root scheduler
The virtual machine processor resource controls provided by Hyper-V are not supported when the hypervisor root scheduler is enabled as the root operating system’s scheduler logic is managing host resources on a global basis and does not have knowledge of a VM’s specific configuration settings. The Hyper-V per-VM processor resource controls, such as caps, weights, and reserves, are only applicable where the hypervisor directly controls VP scheduling, such as with the classic and core scheduler types.
#### Root scheduler use on server systems
The root scheduler is not recommended for use with Hyper-V on servers at this time, as its performance characteristics have not yet been fully characterized and tuned to accommodate the wide range of workloads typical of many server virtualization deployments.
## Configuring the hypervisor scheduler type on Windows Server Hyper-V
Windows Server 2016 and Windows Server 2019 1804 Hyper-V use the classic hypervisor scheduler model by default. The hypervisor can be optionally configured to use the core scheduler, to support the use of virtual machines with SMT scheduling for their guest VPs, and to constrain guest VPs to run only on corresponding physical SMT pairs.
### Required updates
>[!NOTE]
>The following updates are required to use the hypervisor scheduler features described in this document.
| Version | Release |Update Required |
|--------------------|------|---------:|
|Windows Server 2016 | 1607 | TBD |
|Windows Server 2016 | 1703 | TBD |
|Windows Server 2016 | 1709 | TBD |
|Windows Server 2019 | 1804 | None |
## Selecting the hypervisor scheduler type on Windows Server
The hypervisor scheduler configuration is controlled via the hypervisorschedulertype BCD entry.
To select a scheduler type, open a command prompt with administrator privileges:
``` command
bcdedit /set hypervisorschedulertype type
```
Where `type` is one of:
* Classic
* Core
The system must be rebooted for this change to take effect. Any changes to the hypervisor scheduler type require a reboot.
>[!NOTE]
>The hypervisor root scheduler is not supported on Windows Server Hyper-V at this time. Hyper-V administrators should not attempt to configure the root scheduler for use with server virtualization scenarios.
## How to determine the current scheduler type
You can determine the current hypervisor scheduler type in use by examining the Event Log for hypervisor launch event ID 2, which reports the hypervisor scheduler type configured at hypervisor launch. Hypervisor launch events can be obtained from the Windows Event Viewer, or via PowerShell.

Event ID denotes the hypervisor scheduler type, where:
1 = Classic scheduler SMT disabled
2 = Classic scheduler
3 = Core scheduler
4 = Root scheduler

### Viewing the Hyper-V hypervisor scheduler type launch event using PowerShell
To query for hypervisor event ID 2 using PowerShell, enter the following commands from a PowerShell prompt.
``` powershell
Get-WinEvent -FilterHashTable @{ProviderName="Microsoft-Windows-Hyper-V-Hypervisor"; ID=2} | select -Last 1
```

|
Go
|
UTF-8
| 4,346 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
package vc
import (
"bytes"
"fmt"
"os"
"runtime"
"strconv"
"sync"
"time"
)
import "./cmap"
func max(a, b int) int {
if a < b {
return b
}
return a
}
func GetGID() uint64 {
b := make([]byte, 64)
b = b[:runtime.Stack(b, false)]
b = bytes.TrimPrefix(b, []byte("goroutine "))
b = b[:bytes.IndexByte(b, ' ')]
n, _ := strconv.ParseUint(string(b), 10, 64)
return n
}
var f *os.File
var fLock *sync.Mutex
func init() {
f, _ = os.Create("./trace.log")
fLock = &sync.Mutex{}
watchDog = make(chan struct{})
done = make(chan struct{})
traces = hashmap.NewCMapv2()
}
type VectorClock map[uint64]int
func (vc VectorClock) String() string {
s := "["
for k, v := range vc {
s += fmt.Sprintf("(%v,%v)", k, v)
}
s += "]"
return s
}
func (vc VectorClock) clone() VectorClock {
nvc := NewVC()
for k, v := range vc {
nvc[k] = v
}
return nvc
}
func NewVC() VectorClock {
return make(VectorClock)
}
type ChanString struct {
ch chan struct {
m string
vc VectorClock
x chan VectorClock
}
name string
}
func NewChanString(name string) *ChanString {
return &ChanString{ch: make(chan struct {
m string
vc VectorClock
x chan VectorClock
}, 0), name: name}
}
func (ch *ChanString) Send(m string, vc VectorClock) {
tid := GetGID()
tmp := vc[tid]
tmp++
vc[tid] = tmp
ret := make(chan VectorClock)
ch.ch <- struct {
m string
vc VectorClock
x chan VectorClock
}{m, vc.clone(), ret}
pvc := <-ret
//sync vclocks
for k, v := range vc {
pv := pvc[k]
vc[k] = max(v, pv)
}
for k, v := range pvc {
pv := vc[k]
vc[k] = max(pv, v)
}
traces.Store(tid, fmt.Sprintf("%v,%v,%v,-,%v", tid, ch.name, "!", vc))
informWatchDog()
// fLock.Lock()
// defer fLock.Unlock()
// f.WriteString(fmt.Sprintf("%v,%v,%v,-,%v\n", tid, ch.name, "!", vc))
}
func (ch *ChanString) Rcv(vc VectorClock) string {
tid := GetGID()
tmp := vc[tid]
tmp++
vc[tid] = tmp
m := <-ch.ch
m.x <- vc.clone()
//sync vclocks
for k, v := range vc {
pv := m.vc[k]
vc[k] = max(v, pv)
}
for k, v := range m.vc {
pv := vc[k]
vc[k] = max(pv, v)
}
traces.Store(tid, fmt.Sprintf("%v,%v,%v,-,%v", tid, ch.name, "?", vc))
informWatchDog()
// fLock.Lock()
// defer fLock.Unlock()
// f.WriteString(fmt.Sprintf("%v,%v,%v,-,%v\n", tid, ch.name, "?", vc))
return m.m
}
type ChanInt struct {
ch chan struct {
m int
vc VectorClock
x chan VectorClock
}
name string
}
func NewChanInt(name string) *ChanInt {
return &ChanInt{ch: make(chan struct {
m int
vc VectorClock
x chan VectorClock
}, 0), name: name}
}
func (ch *ChanInt) Send(m int, vc VectorClock) {
tid := GetGID()
tmp := vc[tid]
tmp++
vc[tid] = tmp
ret := make(chan VectorClock)
ch.ch <- struct {
m int
vc VectorClock
x chan VectorClock
}{m, vc.clone(), ret}
pvc := <-ret
//sync vclocks
for k, v := range vc {
pv := pvc[k]
vc[k] = max(v, pv)
}
for k, v := range pvc {
pv := vc[k]
vc[k] = max(pv, v)
}
traces.Store(tid, fmt.Sprintf("%v,%v,%v,-,%v", tid, ch.name, "!", vc))
informWatchDog()
// fLock.Lock()
// defer fLock.Unlock()
// f.WriteString(fmt.Sprintf("%v,%v,%v,-,%v\n", tid, ch.name, "!", vc))
}
func (ch *ChanInt) Rcv(vc VectorClock) int {
tid := GetGID()
tmp := vc[tid]
tmp++
vc[tid] = tmp
m := <-ch.ch
m.x <- vc.clone()
//sync vclocks
for k, v := range vc {
pv := m.vc[k]
vc[k] = max(v, pv)
}
for k, v := range m.vc {
pv := vc[k]
vc[k] = max(pv, v)
}
traces.Store(tid, fmt.Sprintf("%v,%v,%v,-,%v", tid, ch.name, "?", vc))
informWatchDog()
//f.WriteString(fmt.Sprintf("%v,%v,%v,-,%v\n", tid, ch.name, "?", vc))
return m.m
}
var watchDog chan struct{}
var done chan struct{}
var traces *hashmap.CMapv2
func informWatchDog() {
go func() {
watchDog <- struct{}{}
}()
}
func Start() {
go func() { //watchdog
for {
select {
case <-watchDog:
case <-done:
//fmt.Println("DONE")
writeBack()
done <- struct{}{}
case <-time.After(1 * time.Second):
//fmt.Println("Timeout")
writeBack()
<-watchDog
}
}
}()
}
func Stop() {
done <- struct{}{}
<-done
}
func writeBack() {
f, err := os.Create("./trace.log")
if err != nil {
panic(err)
}
iter := traces.Iterator()
for iter.HasNext() {
iter2 := iter.Get()
for iter2.HasNext() {
f.WriteString(iter2.Get() + "\n")
iter2.Next()
}
iter.Next()
}
}
|
C++
|
UTF-8
| 853 | 2.8125 | 3 |
[] |
no_license
|
#include <vector>
#include <iostream>
#include <algorithm>
#include <time.h>
#include <cassert>
using namespace std;
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> vec_ret;
return vec_ret;
}
};
int main()
{
//int nums_1[] = {};
int nums_2[] = {1,3,5,6};
vector<int> vec_num_1;
//vector<int> vec_num_1(nums_1, nums_1 + sizeof(nums_1)/sizeof(nums_1[0]));
vector<int> vec_num_2(nums_2, nums_2 + sizeof(nums_2)/sizeof(nums_2[0]));
vector<int> vec_num_rand;
vector<vector<int>> vec_result;
Solution foo;
int ran_num;
//srand((unsigned)time(0));
srand(1);
for(auto i = 0; i < 500; i++){
ran_num = rand() % 2000 - 1000;
vec_num_rand.push_back(ran_num);
}
vector<vector<int>> res = foo.combinationSum(vec_num_2, 4);
int pauseline;
cin >> pauseline;
}
|
Python
|
UTF-8
| 2,700 | 3.015625 | 3 |
[] |
no_license
|
import sys
import typing
import argparse
import logging
parser = argparse.ArgumentParser()
parser.add_argument("-v", "--verbose", action="store_true", help="enable verbose logging")
parser.add_argument("-n", "--files", type=int, default=5, help="optional: number of ranks")
parser.add_argument("-m", "--ranks", type=int, default=0, help="optional: number of files, defaults to number of ranks (-n)")
parser.add_argument("-s", "--start", type=str, default="a1", help="optional: starting square")
args = parser.parse_args()
logging.basicConfig(
level=logging.DEBUG if args.verbose else logging.INFO,
format= '[%(asctime)s] %(pathname)s:%(lineno)d %(levelname)s - %(message)s' if args.verbose else "%(message)s",
datefmt='%H:%M:%S'
)
files = args.files
ranks = args.ranks or files
sq_count = files * ranks
sq_max = sq_count - 1
sq_start = (ord(args.start[0]) - ord('a')) + 8 * (int(args.start[1]) - 1)
if files <= 0:
logging.fatal(f"expected parameter 'files' to be a positive integer, got '{files}' instead")
parser.print_help(sys.stderr)
quit()
if ranks <= 0:
logging.fatal(f"expected parameter 'ranks' to be a positive integer, got '{ranks}' instead")
parser.print_help(sys.stderr)
quit()
if not (0 <= sq_start <= sq_max):
logging.fatal(f"starting square '{args.start}' ({sq_start}) is not valid")
parser.print_help(sys.stderr)
quit()
logging.info(f"using {files}x{ranks} board size")
logging.info(f"starting square is '{args.start}' ({sq_start})")
def rank_of(sq: int) -> int:
return sq // ranks
def file_of(sq: int) -> int:
return sq % files
def format_square(sq: int) -> str:
return f"{chr(file_of(sq) + ord('a'))}{rank_of(sq) + 1}"
def distance(sq1: int, sq2: int) -> int:
return max(abs(file_of(sq1) - file_of(sq2)), abs(rank_of(sq1) - rank_of(sq2)))
def step_attacks(sq: int, dirs: typing.Iterable[int]):
for d in dirs:
s = sq + d
if 0 <= s <= sq_max and distance(sq, s) <= 2:
yield s
logging.debug("generating attack table")
knight_directions = [2 * files + 1, 2 * files - 1, 2 + files, -2 + files, -2 * files + 1, -2 * files - 1, 2 - files, -2 - files]
knight_attacks = [list(step_attacks(sq, knight_directions)) for sq in range(sq_count)]
logging.debug("generating board")
board = [False] * sq_count
def filtered_attacks(sq: int):
return filter(lambda s: not board[s], knight_attacks[sq])
def open_tour(sq: int, res=[]):
board[sq] = True
res.append(format_square(sq))
attacks = list(filtered_attacks(sq))
degrees = [len(list(filtered_attacks(s))) for s in attacks]
if len(degrees) > 0:
min_degree = min(degrees)
next_sq = attacks[degrees.index(min_degree)]
open_tour(next_sq)
else:
logging.info("-".join(res))
open_tour(sq_start)
|
Python
|
UTF-8
| 351 | 3.3125 | 3 |
[] |
no_license
|
class Solution:
def findNumbers(self, nums: List[int]) -> int:
return len([ele for ele in nums if len(str(ele)) % 2 == 0])
class Solution:
def findNumbers(self, nums: List[int]) -> int:
count = 0
for ele in nums:
if len(str(ele)) % 2 == 0:
count += 1
return counta
|
C
|
UTF-8
| 350 | 3.46875 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int sex;
double age,height,w,m;
printf("Give sex: 1-male 2-female ");
scanf("%d",&sex);
printf("Give age and height ");
scanf("%lf %lf",&age,&height);
m=50+0.75*(height-150)+(age-20)/4;
w=m-10;
if(sex==1) printf("%f",m);
else printf("%f",w);
return 0;
}
|
Python
|
UTF-8
| 2,295 | 3.078125 | 3 |
[] |
no_license
|
#!/usr/bin/python
"""
Starter code for exploring the Enron dataset (emails + finances);
loads up the dataset (pickled dict of dicts).
The dataset has the form:
enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict }
{features_dict} is a dictionary of features associated with that person.
You should explore features_dict as part of the mini-project,
but here's an example to get you started:
enron_data["SKILLING JEFFREY K"]["bonus"] = 5600000
"""
import sys
import pickle
import numpy
sys.path.append("../tools/")
from feature_format import featureFormat
enron_data = pickle.load(open("../final_project/final_project_dataset.pkl", "r"))
keys = enron_data.keys()
#features = enron_data['DONAHUE JR JEFFREY M'].keys()
features = ["poi", "total_payments","salary"]
np = featureFormat(enron_data, features,remove_NaN=True)
print np
#print enron_data["SKILLING JEFFREY K"]["bonus"]
counter = 0
for poi in enron_data:
if enron_data[poi]['poi'] == True:
print enron_data[poi]['poi']
print enron_data[poi]['total_payments']
counter += 1
print counter
#for poi in enron_data:
# if enron_data[poi]['total_payments'] == 'NaN':
# print enron_data[poi]['total_payments']
# print enron_data[poi]['poi']
# counter +=1
#print counter
##146 = 100%
#21 = 14.38#
#POI = chave
#for poi in enron_data:
#print poi
#mostra cada objetos full
#print enron_data[poi]
#mostra a feature 'poi' de cada objeto
#print enron_data[poi]['poi']
# conta se e POI
#if enron_data[poi]["poi"] == True:
# counter += 1
#print poi + ": " + str(enron_data[poi]['total_stock_value'])
#print poi + " salary: " + str(enron_data[poi]['salary'])
#print poi + " email: " + str(enron_data[poi]['email_address'])
#if enron_data[poi]['email_address'] != 'NaN':
# print poi + " salary: " + str(enron_data[poi]['salary'])
# counter += 1
#print counter
#print "James Prentice:"
#print enron_data['PRENTICE JAMES']['total_stock_value']
#print "LAY: " + str(enron_data['LAY KENNETH L']['total_payments'])
#print "SKILLING: " + str(enron_data['SKILLING JEFFREY K']['total_payments'])
#print "FASTOW: " + str(enron_data['FASTOW ANDREW S']['total_payments'])
#print counter
|
C++
|
UTF-8
| 1,141 | 3.78125 | 4 |
[] |
no_license
|
/*Given a list arr of N integers, print sums of all subsets in it.
Output should be printed in increasing order of sums.
Input: N = 2 arr[] = {2, 3}
Output: [0, 2, 3, 5]
Explanation:
When no elements is taken then Sum = 0.
When only 2 is taken then Sum = 2.
When only 3 is taken then Sum = 3.
When element 2 and 3 are taken then Sum = 2+3 = 5. */
class Solution{
public:
//sumPS = sum of Power Set
void sumOfAllSubSets(vector<int> &ip, int ipItr, int &N,
int &subsetSum, vector<int> &sumPS)
{
if(ipItr == N) //base condition
{
sumPS.push_back(subsetSum);
return;
}
sumOfAllSubSets(ip, ipItr+1, N, subsetSum, sumPS);
subsetSum += ip[ipItr];
sumOfAllSubSets(ip, ipItr+1, N, subsetSum, sumPS);
subsetSum -= ip[ipItr];
}
vector<int> subsetSums(vector<int> arr, int N)
{
vector<int> sumOfallSubSets;
int subsetSum = 0;
sumOfAllSubSets(arr, 0, N, subsetSum, sumOfallSubSets);
sort(sumOfallSubSets.begin(), sumOfallSubSets.end());
return sumOfallSubSets;
}
};
|
Java
|
UTF-8
| 2,295 | 3.71875 | 4 |
[] |
no_license
|
package com.zjj.nowcoder.aiqiyi0822.ex4;
import java.util.Scanner;
import java.util.concurrent.Semaphore;
import java.util.function.IntConsumer;
public class Main {
public static void main(String[] args) {
final Scanner reader = new Scanner(System.in);
int n = reader.nextInt();
ZeroEvenOdd zeroEvenOdd = new ZeroEvenOdd(n);
new Thread(() -> {
try {
zeroEvenOdd.printZero(System.out::print);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
try {
zeroEvenOdd.printEven(System.out::print);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
try {
zeroEvenOdd.printOdd(System.out::print);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}
class ZeroEvenOdd {
private int n;
private Semaphore semaphoreZero;
private Semaphore semaphoreEven;
private Semaphore semaphoreOdd;
public ZeroEvenOdd(int n) {
this.n = n;
this.semaphoreZero = new Semaphore(1);
this.semaphoreEven = new Semaphore(0);
this.semaphoreOdd = new Semaphore(0);
}
// printNumber.accept(x) outputs "x", where x is an integer.
public void printZero(IntConsumer printNumber) throws InterruptedException {
for (int i = 1; i <= n; i++) {
semaphoreZero.acquire();
printNumber.accept(0);
if ((i & 1) == 1) {
semaphoreOdd.release();
} else {
semaphoreEven.release();
}
}
}
public void printEven(IntConsumer printNumber) throws InterruptedException {
for (int i = 2; i <= n; i += 2) {
semaphoreEven.acquire();
printNumber.accept(i);
semaphoreZero.release();
}
}
public void printOdd(IntConsumer printNumber) throws InterruptedException {
for (int i = 1; i <= n; i += 2) {
semaphoreOdd.acquire();
printNumber.accept(i);
semaphoreZero.release();
}
}
}
|
Java
|
UTF-8
| 217 | 1.820313 | 2 |
[] |
no_license
|
/* CS 5004 - Easy Animator - Model
* Vandita Attal & Swapnil Mittal
*/
package cs5004.animator.animation;
/**
* This is an enum class representing types of animations.
*/
public enum TypeOfAnimation {
MOVE, SCALE, COLOR
}
|
Python
|
UTF-8
| 695 | 3.734375 | 4 |
[] |
no_license
|
# 1. Read input data
width = int(input())
length = int(input())
height = int(input())
volume_home = width * length * height
number_boxes = 0
free_space = volume_home - (number_boxes * 1)
command = ""
done_command = False
while free_space > 0:
command = input()
if command != "Done":
boxes = int(command)
number_boxes += boxes
free_space = volume_home - (number_boxes * 1)
else:
left_free_space = free_space
done_command = True
break
if done_command:
print(f"{left_free_space} Cubic meters left.")
else:
needed_space = (number_boxes*1) - volume_home
print(f"No more free space! You need {needed_space} Cubic meters more.")
|
Python
|
UTF-8
| 617 | 3.296875 | 3 |
[] |
no_license
|
"""
矩形覆盖 Q: 我们可以用2 1的小矩形横着或者竖着去覆盖更大的矩形。请问用n个2 1的小矩形无重叠地覆盖一个2 * n的大矩形,总共有多少种方法?
A: 依然是斐波那契数列的变形。代码参考跳台阶。
"""
# -*- coding:utf-8 -*-
class Solution:
def rectCover(self, number):
# write code here
if number == 0:
return 0
tempArray = [1, 2]
if number >= 3:
for i in range(3, number + 1):
tempArray[(i + 1) % 2] = tempArray[0] + tempArray[1]
return tempArray[(number + 1) % 2]
|
Python
|
UTF-8
| 3,734 | 3.40625 | 3 |
[] |
no_license
|
from collections import defaultdict
import copy
import time
start = time.time()
def read_content_into_rules_and_strings(lines):
rules = defaultdict(list)
strings_to_attempt_to_match = []
rules_done = False
for line in lines:
if rules_done:
strings_to_attempt_to_match.append(line)
elif line == '':
rules_done = True
else:
rule_num, instructions = line.split(':')
for match in instructions.split('|'):
rules[rule_num].append(match.strip().split(' '))
return rules, strings_to_attempt_to_match
def rewrite_index_and_save_for_later_searching(rule_values, list_of_rules_to_follow, index, strings_that_can_be_made):
for ruleValue in rule_values:
copy_of_list = list_of_rules_to_follow[:]
del copy_of_list[index]
count = len(ruleValue) - 1
while count >= 0:
copy_of_list.insert(index, ruleValue[count])
count -= 1
strings_that_can_be_made.insert(0, [copy_of_list, index])
# everything before index is already set so start there when we come back to these strings
def replace_index_with_list_of_elements(index, elements_to_replace_with, list_to_replace_in):
increase_index = False
del list_to_replace_in[index]
count = len(elements_to_replace_with) - 1
while count >= 0:
value = elements_to_replace_with[count]
if value == '"a"' or value == '"b"':
increase_index = True
value = value[1]
list_to_replace_in.insert(index, value)
count -= 1
return increase_index
def find_count_possible_strings(rules_to_follow, list_strings_to_match):
found_count = 0
for string in list_strings_to_match:
strings_that_can_be_made = [[copy.deepcopy(rules_to_follow['0'][0]), 0]] # list of rules and index to start at
while 0 < len(strings_that_can_be_made):
list_of_rules_to_follow, index = strings_that_can_be_made.pop(0)
while index < len(list_of_rules_to_follow) <= len(string):
rule_values = rules_to_follow[list_of_rules_to_follow[index]]
# going to keep track of one list at a time
# so the ors get sent to the strings that can be made list for later work
rewrite_index_and_save_for_later_searching(
rule_values[1:],
list_of_rules_to_follow,
index,
strings_that_can_be_made
)
increase_index = replace_index_with_list_of_elements(index, rule_values[0], list_of_rules_to_follow)
if increase_index:
index += 1
# break if what we have so far is wrong
if string[0:index] != "".join(list_of_rules_to_follow[0:index]):
break
# if found just break and move on to next string since we already created it
if string == "".join(list_of_rules_to_follow):
found_count += 1
break
return found_count
with open('dayNineteenInput.txt') as f:
part1Lines = f.readlines()
part1Lines = [x.strip() for x in part1Lines]
with open('dayNineteenInputPart2.txt') as f:
part2Lines = f.readlines()
part2Lines = [x.strip() for x in part2Lines]
part1rules, part1StringsToMatch = read_content_into_rules_and_strings(part1Lines)
part2rules, part2StringsToMatch = read_content_into_rules_and_strings(part2Lines)
print('part one:', find_count_possible_strings(part1rules, part1StringsToMatch))
print('part two:', find_count_possible_strings(part2rules, part2StringsToMatch))
print('It took', time.time()-start, 'seconds.')
|
Python
|
UTF-8
| 13,016 | 2.875 | 3 |
[] |
no_license
|
import string
from operator import itemgetter
from couple import Couple
from dancer import Dancer
from heat import Heat, Heat_Report
from heatlist import Heatlist
# this module processes a ballroom competition heatlist file in HTML format generated by the CompMngr program.
class CompMngrHeat(Heat):
'''The CompMngrHeat derives from the Heat class, which stores heat information for a particular couple or dancer'''
def __init__(self, category, line="", dancer="", scoresheet_code=0, partner="", number=0):
'''The init function builds the Heat object by reading a line from the CompMngr heatlist.'''
super().__init__()
self.category = category # heat, solo, pro heat, formation
self.dancer = dancer
self.code = scoresheet_code
self.partner = partner # partner may be none for a member of a formation
self.heat_number = number
if len(line) > 0: # if line is not empty, parse it to obtain other properites
fields = line.split("<td>")
# get the session number, heat number, and multi-round info
heat_time = fields[1].split("</td>")[0]
if "@" in heat_time:
heat_time_fields = heat_time.split("@")
self.session = heat_time_fields[0]
heat_time = heat_time_fields[1]
else:
self.session = ""
if "<br>" in heat_time:
time_fields = heat_time.split("<br>")
if len(time_fields) == 4:
self.rounds = "Q" # start with quarter-final
else:
self.rounds = "S" # start with semi-final
self.time = time_fields[0] + "-" + self.rounds # truncate "Later rounds" from time string
else:
self.time = heat_time
self.rounds = "F" # final only
# get the shirt number
self.shirt_number = fields[2].split("</td>")[0]
# get the heat info
self.info = fields[4].split("</td>")[0]
self.set_level()
# pull any non-digit characters from the heat number into extra
start_pos = fields[3].find(category) + len(category) + 1
i = start_pos
# stop at the first non-digit
while fields[3][i] in string.digits:
i = i + 1
if i > start_pos:
self.heat_number = int(fields[3][start_pos:i])
# anything non-digit is extra information, like ballroom assignment
num_chars = len("</td>")
self.extra = fields[3][i:-num_chars]
self.extra = self.extra.replace("Ballroom ", "")
class CompMngrDancer(Dancer):
''' The CompMngrDancer class derives from Dancer, which stores information about a dancer that is in the competition'''
def __init__(self, line):
'''Extract the dancer's name and code from the line of text in CompMngr heatlist format.'''
super().__init__()
# find the dancer's name
start_pos = 8
end_pos = line.find("</td>")
self.name = line[start_pos:end_pos]
# find the code number that can be used to grab their results from a scoresheet
start_pos = line.find("TABLE_CODE_") + len("TABLE_CODE_")
end_pos = line.find("'", start_pos)
self.code = line[start_pos:end_pos]
class CompMngrHeatlist(Heatlist):
''' This class derives from Heatlist. It parses the heatlist in CompMngr format and stores
information about the heats in this competition.'''
def __init__(self):
super().__init__()
self.fhand = None
############### EXTRACTION ROUTINES #################################################
# the following methods extract specific data items from lines in the CompMngr file
######################################################################################
def get_age_division(self, line):
'''Look for an age division on the given line. Return it or None if no age division found.'''
prefixes = ("L-", "G-", "AC-", "Pro ") # valid prefixes for division
return super().get_age_division(line, prefixes)
def get_comp_name(self,line):
'''This method extracts the name of the competition.
It is found on the given line after a <strong> tag until the next HTML tag.'''
start_pos = line.find("<strong>") + len("<strong>")
end_pos = line.find("<", start_pos)
name = line[start_pos:end_pos]
return name
def get_dancer_name(self, line, start_pos=20):
'''This method returns the dancer name from a line, starting at a given column.
In the HTML file produced by CompMngr, the dancer names are inside a <strong> tag.'''
end_pos = line.find("</strong>")
name = line[start_pos:end_pos]
return name
################# READING THE HEATLIST HTML FILE ################################
# These methods process the HTML data file in CompMngr heatlist format
# and populates the data structures
##################################################################################
def open(self, filename):
'''This method opens the heatlist filename and finds all the dancer names.
The file is left open so other methods can find the heat information.'''
dancer = None # variables for the current dancer
found_last_dancer = False
# open the file and loop through all the lines until last dancer is found
self.fhand = open(filename,encoding="utf-8")
for line in self.fhand:
# if the line has "Show Entries", we can extract the name of a dancer
if "Show entries" in line:
dancer = CompMngrDancer(line.strip())
self.dancers.append(dancer)
# if we see the line that says "size="", extract the name of the competition
if 'size=' in line:
self.comp_name = self.get_comp_name(line.strip())
# if we see the closing </table> tag, we have found all the dancers
if "/table" in line:
print("Found", len(self.dancers), "dancers")
found_last_dancer = True
# once we have found the last dancer, stop after finding the closing </div> tag
if "/div" in line:
if found_last_dancer:
break;
# keep the file open
def get_next_dancer(self, dancer_index):
'''This method continues to parse the CompMngr heatlist file, extracting the heat
information for the next dancer.
The dancer_index is a counter, providing a quick way to find the dancer object
based on the dancer's name'''
dancer = None # object for the current dancer
couple = None # object for the current couple
while True:
line = self.fhand.readline()
# A line with "Entries For" indicates the start of a new dancer's heat information
if "Entries for" in line:
dancer_name = self.get_dancer_name(line.strip())
# check if this dancer name matches the dancer object at the given index
if dancer_name == self.dancers[dancer_index].name:
dancer = self.dancers[dancer_index]
dancer_index += 1
else: # if not, search for dancer object based on the name
print("Searching for dancer")
for d in self.dancers:
if d.name == dancer_name:
dancer = d
break
# A line with "With " indicates the start of a new partner for the current dancer
elif "With " in line:
partner = self.get_dancer_name(line.strip(), line.find("With ") + 5)
if "/" in partner:
couple = None
elif len(partner) == 0:
couple = None
else:
couple = Couple(dancer.name, partner)
new_couple = True # assume this is a new couple
for c in self.couples:
if couple.same_names_as(c):
new_couple = False
couple = c # set the couple variable to the existing couple object
break
# if this actually is a new couple, add them to the couples list
if new_couple:
self.couples.append(couple)
# look for lines with pro heat number information
elif "Pro heat " in line:
if couple is not None:
# turn that heat info into an object and add it to the couple
pro_heat = CompMngrHeat("Pro heat", line, dancer.name, dancer.code, partner)
if pro_heat.heat_number > self.max_pro_heat_num:
self.max_pro_heat_num = pro_heat.heat_number
couple.add_heat(pro_heat)
dancer.add_heat(pro_heat)
# look for lines with heat number information
elif "Heat " in line:
if couple is not None:
# turn this line into a heat object and add it to the couple and dancer
heat_obj = CompMngrHeat("Heat", line, dancer.name, dancer.code, partner)
if heat_obj.heat_number > self.max_heat_num:
self.max_heat_num = heat_obj.heat_number
if heat_obj.multi_dance():
self.add_multi_dance_heat(heat_obj.heat_number)
couple.add_heat(heat_obj)
dancer.add_heat(heat_obj)
# look for lines with solo number information
elif "Solo " in line:
if couple is not None:
# turn this line into a heat object and add it to the couple and dancer
solo_obj = CompMngrHeat("Solo", line, dancer.name, dancer.code, partner)
if solo_obj.heat_number > self.max_solo_num:
self.max_solo_num = solo_obj.heat_number
couple.add_heat(solo_obj)
dancer.add_heat(solo_obj)
# add this solo to the list of solos for the comp
if solo_obj not in self.solos:
self.solos.append(solo_obj)
# look for lines with formation number information
elif "Formation" in line:
if dancer is not None:
# turn that heat info into an object and add it to the dancer only
form_heat = CompMngrHeat("Formation", line, dancer.name, dancer.code, "")
if form_heat.heat_number > self.max_formation_num:
self.max_formation_num = form_heat.heat_number
dancer.add_heat(form_heat)
self.formations.append(form_heat)
# look for lines with team match number information
elif "Team match" in line or "Team Match" in line:
if dancer is not None:
# turn that heat info into an object and add it to the dancer only
team_heat = CompMngrHeat("Team match", line, dancer.name, dancer.code, "")
if team_heat.heat_number > self.max_team_match_num:
self.max_team_match_num = team_heat.heat_number
dancer.add_heat(team_heat)
self.team_matches.append(team_heat)
# if we see the closing </div? tag, we are done with this dancer.
elif "/div" in line:
break;
# no matter what branch we took, look for an age division on this line
if couple is not None:
age_div = self.get_age_division(line.strip())
if age_div is not None:
self.add_age_division(age_div)
couple.add_age_division(age_div)
dancer.add_age_division(age_div)
# return the name of the dancer, so the calling GUI can display it.
return dancer_name
def complete_processing(self):
'''This method completes the processing of the Comp Manager heatlist,
by closing the file and sorting the lists.'''
self.fhand.close()
self.formations.sort()
self.solos.sort()
self.age_divisions.sort()
self.multi_dance_heat_numbers.sort()
|
Java
|
UTF-8
| 19,880 | 2.578125 | 3 |
[] |
no_license
|
package common.jsp;
import common.databean.GenericSortableTable;
import common.databean.GenericTable;
import common.jsp.databean.GenericStringData;
import java.util.Hashtable;
import java.util.Vector;
public class HTMLGenerator
{
public static final int iJAVASCRIPT_IN_CATEGORY_SUBCATEGORY_DEPENDENCY = 0;
public static final int iCATEGORY_IN_CATEGORY_SUBCATEGORY_DEPENDENCY = 1;
public static final int iSUBCATEGORY_IN_CATEGORY_SUBCATEGORY_DEPENDENCY = 2;
public static final int iJAVASCRIPT_IN_CATEGORY_MASTER_DEPENDENCY = 3;
public HTMLGenerator()
{
}
public static String buildJS2DArray(String v1, String v2)
{
return new String("new Array('" + v1 + "', '" + v2 + "')") ;
}
// =====
public static String generatePulldownList ( String[] arrValue,
String[] arrDesc,
String listName,
String selectedValue,
String addOnText,
String emptyChoiceAtBeginning) {
/*
String str = generatePolldownList (arrValue, arrDesc, listName, selectedValue, addOnText) ;
if (str == null) return "" ;
str = str.substring(0, str.indexOf('>') +1) + emptyChoiceAtBeginning + str.substring(str.indexOf('>') +1) ;
return str ;
*/
String strPollDown = "";
if (arrValue.length != arrDesc.length) {
return strPollDown;
}
// if (selectedValue == null)
// selectedValue = "";
strPollDown += "<select name=\"" + GenericStringData.escapeDataInHtml(listName) + "\"" + addOnText + ">\n" + emptyChoiceAtBeginning;
for (int i=0; i<arrValue.length; i++) {
strPollDown += "<option value=\"" + GenericStringData.escapeDataInHtml(arrValue[i]) + "\"" ;
if (selectedValue != null && arrValue[i].equals(selectedValue))
{
strPollDown += " selected";
}
strPollDown += ">" + GenericStringData.escapeDataInHtml(arrDesc[i]) + "</option>\n";
}
strPollDown += "</select>";
return strPollDown;
}
public static String generatePulldownListInOneLine ( String[] arrValue,
String[] arrDesc,
String listName,
String selectedValue,
String addOnText,
String emptyChoiceAtBeginning) {
String strPollDown = "";
if (arrValue.length != arrDesc.length) {
return strPollDown;
}
// if (selectedValue == null)
// selectedValue = "";
strPollDown += "<select name='" + GenericStringData.escapeDataInHtml(listName) + "'" + addOnText + ">" + emptyChoiceAtBeginning;
for (int i=0; i<arrValue.length; i++) {
strPollDown += "<option value='" + GenericStringData.escapeDataInHtml(arrValue[i]) + "'" ;
if (selectedValue != null && arrValue[i].equals(selectedValue))
{
strPollDown += " selected";
}
strPollDown += ">" + GenericStringData.escapeDataInHtml(arrDesc[i]) + "</option>";
}
strPollDown += "</select>";
return strPollDown;
}
/*
public static String generatePolldownList(String[] arrValue, String[] arrDesc, String listName, String selectedValue, String addOnText)
{
String strPollDown = "";
if (arrValue.length != arrDesc.length) {
return strPollDown;
}
// if (selectedValue == null)
// selectedValue = "";
strPollDown += "<select name=\"" + listName + "\"" + addOnText + ">\n";
for (int i=0; i<arrValue.length; i++) {
strPollDown += "<option value=\"" + arrValue[i] + "\"";
if (selectedValue != null && arrValue[i].equals(selectedValue))
{
strPollDown += " selected";
}
strPollDown += ">" + arrDesc[i] + "</option>\n";
}
strPollDown += "</select>";
return strPollDown;
}
*/
public static String generatePulldownList ( String[] arrValue,
String[] arrDesc,
String listName,
String[] arrSelectedValue,
String addOnText,
String emptyChoiceAtBeginning) {
String strPollDown = "";
if (arrValue.length != arrDesc.length) {
return strPollDown;
}
strPollDown += "<select name=\"" + GenericStringData.escapeDataInHtml(listName) + "\"" + addOnText + ">\n" + emptyChoiceAtBeginning ;
for (int i=0; i<arrValue.length; i++) {
strPollDown += "<option value=\"" + GenericStringData.escapeDataInHtml(arrValue[i]) + "\"";
for (int j=0; arrSelectedValue!= null && j<arrSelectedValue.length; j++) {
if (arrValue[i].equals(arrSelectedValue[j]))
{
strPollDown += " selected";
}
}
strPollDown += ">" + GenericStringData.escapeDataInHtml(arrDesc[i]) + "</option>\n";
}
strPollDown += "</select>";
return strPollDown;
}
/*
public static String generatePolldownList(String[] arrValue, String[] arrDesc, String listName, String[] arrSelectedValue, String addOnText)
{
String strPollDown = "";
if (arrValue.length != arrDesc.length) {
return strPollDown;
}
strPollDown += "<select name=\"" + listName + "\"" + addOnText + ">\n";
for (int i=0; i<arrValue.length; i++) {
strPollDown += "<option value=\"" + arrValue[i] + "\"";
for (int j=0; arrSelectedValue!= null && j<arrSelectedValue.length; j++) {
if (arrValue[i].equals(arrSelectedValue[j]))
{
strPollDown += " selected";
}
}
strPollDown += ">" + arrDesc[i] + "</option>\n";
}
strPollDown += "</select>";
return strPollDown;
}
*/
public static String generateTable (GenericSortableTable gst, int colSeq[], String bodyRowAddition, boolean unEscape[], int colWidth[]) {
String[] keys = gst.getKeyInArray() ;
String sSumWidth="" ;
int sumWidth=0 ;
if (colWidth != null) {
for (int cntWid = 0 ; cntWid < colWidth.length ; cntWid ++ )
sumWidth += colWidth[cntWid] ;
sSumWidth = "" + sumWidth ;
}
else
sSumWidth = "100%" ;
StringBuffer sb = new StringBuffer("<table width='"+sSumWidth+"' border='0' class='border'>\n") ;
// if (keys.length >0) {
// build column header
Vector tblHead = gst.getColumnHead() ;
sb.append("<tr align='left' class='columnhead'>") ;
for (int colCnt = 0 ; tblHead!=null && colCnt < colSeq.length ; colCnt ++) {
String widthStr="" ;
if (colWidth!=null && colWidth.length > colCnt && colWidth[colCnt] > -1)
widthStr += " width='" + colWidth[colCnt] + "'" ;
sb.append("<th align='left'"+widthStr+">") ;
if ((String)tblHead.elementAt(colSeq[colCnt])!=null)
sb.append((colSeq[colCnt] < tblHead.size()) ? (String)tblHead.elementAt(colSeq[colCnt]) : " <!--Invalid column:"+(String)tblHead.elementAt(colCnt)+"-->") ;
sb.append("</th>\n" );
}
sb.append("</tr>") ;
if (keys.length >0) {
for (int rowCnt = 0 ; rowCnt < keys.length ; rowCnt ++) {
sb.append("<tr"+bodyRowAddition+">") ;
Vector aRow = (Vector)gst.getRowByKeyId(keys[rowCnt]) ;
for (int rowCntCol = 0 ; rowCntCol < colSeq.length ; rowCntCol ++) {
sb.append("<td valign='top' align='left'>") ;
if ((String)aRow.elementAt(colSeq[rowCntCol])!=null)
sb.append((colSeq[rowCntCol] < aRow.size()) ? ((unEscape[colSeq[rowCntCol]])? (String)aRow.elementAt(colSeq[rowCntCol]): GenericStringData.escapeDataInHtml((String)aRow.elementAt(colSeq[rowCntCol]))) : " ") ;
sb.append("</td>\n") ;
}
sb.append("</tr>\n") ;
}
}
sb.append("</table>\n") ;
return sb.toString();
}
public static String generateTableSlow (GenericSortableTable gst, int colSeq[], String bodyRowAddition, boolean unEscape[], int colWidth[]) {
String[] keys = gst.getKeyInArray() ;
String sSumWidth="" ;
int sumWidth=0 ;
if (colWidth != null) {
for (int cntWid = 0 ; cntWid < colWidth.length ; cntWid ++ )
sumWidth += colWidth[cntWid] ;
sSumWidth = "" + sumWidth ;
}
else
sSumWidth = "100%" ;
String str = "<table width=\""+sSumWidth+"\" border=\"0\" class=\"border\">\n" ;
// if (keys.length >0) {
// build column header
Vector tblHead = gst.getColumnHead() ;
str += "<tr align=\"left\" class=\"columnhead\">" ;
for (int colCnt = 0 ; tblHead!=null && colCnt < colSeq.length ; colCnt ++) {
String widthStr="" ;
if (colWidth!=null && colWidth.length > colCnt && colWidth[colCnt] > -1)
widthStr += " width=\"" + colWidth[colCnt] + "\"" ;
str += "<th align=\"left\""+widthStr+">" ;
if ((String)tblHead.elementAt(colSeq[colCnt])!=null)
str += (colSeq[colCnt] < tblHead.size()) ? (String)tblHead.elementAt(colSeq[colCnt]) : " <!--Invalid column:"+(String)tblHead.elementAt(colCnt)+"-->" ;
str += "</th>\n" ;
}
str += "</tr>" ;
if (keys.length >0) {
for (int rowCnt = 0 ; rowCnt < keys.length ; rowCnt ++) {
str += "<tr"+bodyRowAddition+">" ;
Vector aRow = (Vector)gst.getRowByKeyId(keys[rowCnt]) ;
for (int rowCntCol = 0 ; rowCntCol < colSeq.length ; rowCntCol ++) {
str += "<td valign=\"top\" align=\"left\">" ;
if ((String)aRow.elementAt(colSeq[rowCntCol])!=null)
str += (colSeq[rowCntCol] < aRow.size()) ? ((unEscape[colSeq[rowCntCol]])? (String)aRow.elementAt(colSeq[rowCntCol]): GenericStringData.escapeDataInHtml((String)aRow.elementAt(colSeq[rowCntCol]))) : " " ;
str += "</td>\n" ;
}
str += "</tr>\n" ;
}
}
str += "</table>\n" ;
return str;
}
public static String generateTableSlow (GenericTable gt, int colSeq[], String bodyRowAddition, boolean unEscape[], int colWidth[]) {
String [][]tblBody = gt.getTableBody() ;
String sSumWidth="" ;
int sumWidth=0 ;
if (colWidth != null) {
for (int cntWid = 0 ; cntWid < colWidth.length ; cntWid ++ )
sumWidth += colWidth[cntWid] ;
sSumWidth = "" + sumWidth ;
}
else
sSumWidth = "100%" ;
String str = "<table width=\""+sSumWidth+"\" border=\"0\" class=\"border\" cellpadding=2 cellspacing=2>\n" ;
// if (tblBody.length >0) {
// build column header
String [] tblHead = gt.getTableColumnHeader() ;
str += "<tr align=\"left\" class=\"columnhead\">" ;
for (int colCnt = 0 ; colCnt < colSeq.length ; colCnt ++) {
String widthStr="" ;
if (colWidth!=null && colWidth.length > colCnt && colWidth[colCnt] > -1)
widthStr += " width=\"" + colWidth[colCnt] + "\"" ;
str += "<th align=\"left\""+widthStr+">" ;
if (tblHead[colSeq[colCnt]] != null)
str += (colSeq[colCnt] < tblHead.length) ? tblHead[colSeq[colCnt]] : " <!--Invalid column:"+tblHead[colCnt]+"-->" ;
str += "</th>\n" ;
}
str += "</tr>" ;
if (tblBody.length >0) {
for (int rowCnt = 0 ; rowCnt < tblBody.length ; rowCnt ++) {
str += "<tr"+bodyRowAddition+">" ;
String aRow[] = tblBody[rowCnt] ;
for (int rowCntCol = 0 ; rowCntCol < colSeq.length ; rowCntCol ++) {
String widthStr="" ;
if (colWidth!=null && colWidth.length > rowCntCol && colWidth[rowCntCol] > -1)
widthStr += " width=\"" + colWidth[rowCntCol] + "\"" ;
str += "<td valign=\"top\" align=\"left\""+widthStr+">" ;
if (aRow[colSeq[rowCntCol]] != null)
str += (colSeq[rowCntCol] < aRow.length) ? ((unEscape[colSeq[rowCntCol]])? aRow[colSeq[rowCntCol]] : GenericStringData.escapeDataInHtml(aRow[colSeq[rowCntCol]])) : " " ;
str += "</td>\n" ;
}
str += "</tr>\n" ;
}
}
else {
str += "<tr><td colspan="+tblHead.length+" align=left valign=top>\n No record.</td></tr>\n" ;
}
str += "</table>\n" ;
return str;
}
public static String generateTable (GenericTable gt, int colSeq[], String bodyRowAddition, boolean unEscape[], int colWidth[]) {
String [][]tblBody = gt.getTableBody() ;
String sSumWidth="" ;
int sumWidth=0 ;
if (colWidth != null) {
for (int cntWid = 0 ; cntWid < colWidth.length ; cntWid ++ )
sumWidth += colWidth[cntWid] ;
sSumWidth = "" + sumWidth ;
}
else
sSumWidth = "100%" ;
StringBuffer sb = new StringBuffer("<table width=\""+sSumWidth+"\" border=\"0\" class=\"border\" cellpadding=2 cellspacing=2>\n" ) ;
// if (tblBody.length >0) {
// build column header
String [] tblHead = gt.getTableColumnHeader() ;
sb.append("<tr align=\"left\" class=\"columnhead\">") ;
for (int colCnt = 0 ; colCnt < colSeq.length ; colCnt ++) {
String widthStr="" ;
if (colWidth!=null && colWidth.length > colCnt && colWidth[colCnt] > -1)
widthStr += " width=\"" + colWidth[colCnt] + "\"" ;
sb.append("<th align=\"left\""+widthStr+">") ;
if (tblHead[colSeq[colCnt]] != null)
sb.append((colSeq[colCnt] < tblHead.length) ? tblHead[colSeq[colCnt]] : " <!--Invalid column:"+tblHead[colCnt]+"-->") ;
sb.append("</th>\n") ;
}
sb.append("</tr>") ;
if (tblBody.length >0) {
for (int rowCnt = 0 ; rowCnt < tblBody.length ; rowCnt ++) {
sb.append("<tr"+bodyRowAddition+">") ;
String aRow[] = tblBody[rowCnt] ;
for (int rowCntCol = 0 ; rowCntCol < colSeq.length ; rowCntCol ++) {
String widthStr="" ;
if (colWidth!=null && colWidth.length > rowCntCol && colWidth[rowCntCol] > -1)
widthStr += " width=\"" + colWidth[rowCntCol] + "\"" ;
sb.append("<td valign=\"top\" align=\"left\""+widthStr+">") ;
if (aRow[colSeq[rowCntCol]] != null)
sb.append((colSeq[rowCntCol] < aRow.length) ? ((unEscape[colSeq[rowCntCol]])? aRow[colSeq[rowCntCol]] : GenericStringData.escapeDataInHtml(aRow[colSeq[rowCntCol]])) : " " );
sb.append("</td>\n") ;
}
sb.append("</tr>\n") ;
}
}
else {
sb.append( "<tr><td colspan="+tblHead.length+" align=left valign=top>\n No record.</td></tr>\n" );
}
sb.append("</table>\n") ;
return sb.toString();
}
public static String generatePopupPageHeader (String strDynamicName)
{
return "<table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n" +
"<tr>\n" +
"<td><h1>"+strDynamicName+"</h1></td>\n" +
"</tr>\n" +
"</table>\n" ;
}
public static String generateTable (GenericTable newTable, String attribute)
{
return newTable.toHtml(attribute);
}
public static String generateSelectionBox (SelectionBox newSelectionBox)
{
return newSelectionBox.toHtml();
}
public static String getHtmlUnicodeCurrencySymbol (String currencyCode) {
if ( currencyCode == null ) return null ;
else if ( currencyCode.equals("HKD") || currencyCode.equals("USD") ) return "$" ;
else if ( currencyCode.equals("EUR") ) return "€" ;
else if ( currencyCode.equals("GBP") ) return "£" ;
else if ( currencyCode.equals("YEN") ) return "¥" ;
else if ( currencyCode.equals("RMB") ) return "¥" ;
else return "$" ;
}
public String emptyIfNull(String obj)
{
if (obj == null) return "" ;
else return GenericStringData.escapeDataInHtml(obj) ;
}
/* Generate a table that hightlights table entries that contain an active matrix package */
public static String generateTableWithHighlight (GenericTable gt, int colSeq[], String bodyRowAddition, boolean unEscape[], int colWidth[]) {
String [][]tblBody = gt.getTableBody() ;
String sSumWidth="" ;
int sumWidth=0 ;
if (colWidth != null) {
for (int cntWid = 0 ; cntWid < colWidth.length ; cntWid ++ )
sumWidth += colWidth[cntWid] ;
sSumWidth = "" + sumWidth ;
}
else
sSumWidth = "100%" ;
StringBuffer sb = new StringBuffer("<table width=\""+sSumWidth+"\" border=\"0\" class=\"border\" cellpadding=2 cellspacing=2>\n" ) ;
String [] tblHead = gt.getTableColumnHeader() ;
sb.append("<tr align=\"left\" class=\"columnhead\">") ;
for (int colCnt = 0 ; colCnt < colSeq.length ; colCnt ++) {
String widthStr="" ;
if (colWidth!=null && colWidth.length > colCnt && colWidth[colCnt] > -1)
widthStr += " width=\"" + colWidth[colCnt] + "\"" ;
sb.append("<th align=\"left\""+widthStr+">") ;
if (tblHead[colSeq[colCnt]] != null)
sb.append((colSeq[colCnt] < tblHead.length) ? tblHead[colSeq[colCnt]] : " <!--Invalid column:"+tblHead[colCnt]+"-->") ;
sb.append("</th>\n") ;
}
sb.append("</tr>") ;
if (tblBody.length >0) {
for (int rowCnt = 0 ; rowCnt < tblBody.length ; rowCnt ++) {
String aRow[] = tblBody[rowCnt] ;
//check if the matrix package is active or not, if it is then highlight the entire row.
if (aRow[colSeq.length].equals("N"))
sb.append("<tr "+bodyRowAddition+">");
else if (aRow[colSeq.length].equals("Y"))
sb.append("<tr "+bodyRowAddition+" bgColor=\"#FFFF99\">");
else
sb.append(aRow[colSeq.length]);
for (int rowCntCol = 0 ; rowCntCol < colSeq.length ; rowCntCol ++) {
String widthStr="" ;
if (colWidth!=null && colWidth.length > rowCntCol && colWidth[rowCntCol] > -1)
widthStr += " width=\"" + colWidth[rowCntCol] + "\"" ;
sb.append("<td valign=\"top\" align=\"left\""+widthStr+">") ;
if (aRow[colSeq[rowCntCol]] != null)
sb.append((colSeq[rowCntCol] < aRow.length) ? ((unEscape[colSeq[rowCntCol]])? aRow[colSeq[rowCntCol]] : GenericStringData.escapeDataInHtml(aRow[colSeq[rowCntCol]])) : " " );
sb.append("</td>\n") ;
}
sb.append("</tr>\n") ;
}
}
else {
sb.append( "<tr><td colspan="+tblHead.length+" align=left valign=top>\n No record.</td></tr>\n" );
}
sb.append("</table>\n") ;
return sb.toString();
}
public static void main(String[] args)
{
HTMLGenerator hTMLGenerator = new HTMLGenerator();
/*
String aValue[] = {"1","2","3","4","5"};
String aDesc[] = {"One","Two","Three","Four","Five"};
String ListName = "Testing";
String selValue[] = {"1","4"};
String strAdd = " size=3 onchange=\"javascript:alert('hello');\"";
String testing = generatePolldownList(aValue, aDesc, ListName, selValue, strAdd);
System.out.println (testing);
*/
Hashtable ht = new Hashtable () ;
Vector dh = new Vector (), db = new Vector (), db1 = new Vector (), db2 = new Vector () ;
dh.addElement((String)"aa3"); dh.addElement((String)"bb3");
ht.put (new String("2"), (Vector)dh) ;
db1.addElement((String)"aa2"); db1.addElement((String)"bb1");
ht.put (new String("1"), (Vector)db1) ;
db2.addElement((String)"aa1"); db2.addElement((String)"bb2");
ht.put (new String("3"), (Vector)db2) ;
GenericSortableTable tmp = new GenericSortableTable(ht, true);
String s[] = {"col1", "col2"} ;
tmp.setColumnHead(s);
int ii[] = {1 } ;
String htmlstr = hTMLGenerator.generateTable(tmp, ii, " onMouseOut=\"cbar(this)\" onMouseOver=\"sbar(this)\"", new boolean[2], ii);
int i = 1 ;
}
}
|
C
|
UTF-8
| 606 | 3.453125 | 3 |
[] |
no_license
|
/*
* David Rubý
* fakulta informačních technologií Vysokého učení technického v Brně
* příklad 2
*25. 04. 2019
*/
#include"io.h"
int get_word(char *str, int max, FILE *file) {
int return_value;
//reading one word
return_value = fscanf(file, "%s", str);
//if the word is too long, the length will be edited
if(strlen(str) >= (unsigned)max)
{
str[max] = '\n';
}
//if the algorithm reaches end of file, function will return EOF
if(return_value == EOF)
{
return EOF;
}
//else it return length of the word
return strlen(str);
}
|
JavaScript
|
UTF-8
| 1,601 | 3.0625 | 3 |
[] |
no_license
|
function setup() {
//create a canvas to draw on
createCanvas( 700, 700 );
}
// starting to draw the portrait
function draw() {
//background
background( 'rgb(137, 247, 201)' );
//arm1
push();
fill( 'rgb(231, 127, 198)' );
rotate( radians(-40) );
rect( -35, 375, 30, 110);
pop();
//arm2
push();
fill( 'rgb(231, 127, 198)' );
rect( 400, 370, 110, 30);
pop();
//hands
push();
ellipse( 219, 290, 40, 40 );
ellipse( 520, 385, 40, 40 );
pop();
// drawing the body
push();
fill( 'rgb(231, 127, 198)' );
triangle( 350, 275, 220, 500, 480, 500 );
pop();
//legs
push();
fill( 'rgb(69, 192, 215)' );
rect( 270, 500, 60, 150 );
rect( 370, 500, 60, 150 );
pop();
//feet
push();
ellipse( 300, 660, 70, 35 );
ellipse( 400, 660, 70, 35 );
pop();
//start of the head
push();
fill( 'rgb(248, 250, 196)' );
ellipse( 350, 230, 175, 175 );
pop();
//hair
push();
noStroke();
fill( 'rgb(255, 212, 5)' );
rect( 250, 140, 180, 40 );
rect( 250, 140, 30, 200 );
rect( 420, 140, 30, 200 );
pop();
//Mouth
push();
arc( 350, 265, 75, 75, 0, PI );
pop();
//eye1
push();
fill( 'white' );
ellipse( 310, 210, 50, 40 );
pop();
//eye pupil1
push();
fill( 'rgb(32, 107, 13)' );
ellipse( 310, 210, 20, 30 );
push();
fill( 'black' );
ellipse( 310, 210, 10, 20 );
pop();
pop();
//eye2
push();
fill( 'white' );
ellipse( 390, 210, 50, 40 );
pop();
//eye pupil2
push();
fill( 'rgb(32, 107, 13)' );
ellipse( 390, 210, 20, 30 );
push();
fill( 'black' );
ellipse( 390, 210, 10, 20 );
pop();
pop();
//nose
push();
line( 350, 210, 370, 240 );
line( 370, 240, 350, 240 );
pop();
}
|
C++
|
UTF-8
| 2,872 | 3.359375 | 3 |
[] |
no_license
|
/*
2. Да се направи програма која ќе ја користи класата Штедач и ќе овозможи:
a) Внесување на нов штедач во системот
b) Приказ на податоците
c) Уплата на средства
d) Исплата на средства (со контрола дали е можна таква исплата)
e) Приказ на салдото за даден штедач
*/
#include <iostream>
using namespace std;
class Stedac
{
public:
void vnesi_podatoci();
void prikazi_podatoci();
void uplata(unsigned long i);
void isplata(unsigned long i);
long sostojba();
private:
int broj;
char imeprezime[30], adresa[50];
long saldo;
};
void Stedac::vnesi_podatoci(){
cout<<"Broj: ";cin>>broj;
cout<<"Ime i prezime:";cin>>imeprezime;
cout<<"Adresa: "; cin>>adresa;
cout<<"Saldo: ";cin>>saldo;
}
void Stedac::prikazi_podatoci(){
cout<<"Broj: "<<broj<<" Ime i prezime: "<<imeprezime<<" Adresa: "<<adresa<<" Saldo "<<saldo;
}
void Stedac::uplata(unsigned long i){
saldo=saldo+i;
}
void Stedac::isplata(unsigned long i){
if(i>saldo){cout<<"Ne e vozmozhno da se izvrshi isplata\n";}
else
saldo=saldo-i;
}
long Stedac::sostojba(){
return saldo;
}
int main(){
int n;
cout<<"Vnesi broj na shtedachi";
cin>>n;
Stedac *s;
s=new Stedac[n];
int choice;
int temp;
while(choice !=6){
cout<<"Meni:"<<endl;
cout<<"1. Vnesi nov shtedach vo sistemot\n";
cout<<"2. Prikaz na podatocite\n";
cout<<"3.Uplata na sredstva\n";
cout<<"4.Isplata na sredstva\n";
cout<<"5. Prikaz na saldo za daden shtedach\n";
cin>>choice;
switch (choice)
{
case 1:
s[temp].vnesi_podatoci();
temp++;
break;
case 2:
for(int i=0;i<n;i++){
s[i].prikazi_podatoci();
}
s[temp].prikazi_podatoci();
temp++;
break;
case 3:
int num,suma;
cout<<"Vnesi broj na shtedach koj saka da izvshi uplata: ";
cin>>num;
cout<<"Vnesi iznos na uplatata:";
cin>>suma;
s[num].uplata(suma);
break;
case 4:
int num,suma;
cout<<"Vnesi broj na shtedach koj saka da izvshi isplata: ";
cin>>num;
cout<<"Vnesi iznos na isplatata:";
cin>>suma;
s[num].isplata(suma);
break;
case 5:
int num;
cout<<"Vnesi broj na shtedach koj saka da ja proveri svojata sostojba:";
cin>>num;
cout<<"Sostojba: "<<s[num].sostojba();
break;
default:
break;
}
}
}
|
Markdown
|
UTF-8
| 5,150 | 3.140625 | 3 |
[] |
no_license
|
---
title: "正規表現の例: 日付形式の変更"
description: "正規表現の例: 日付形式の変更"
keywords: .NET, .NET Core
author: stevehoag
ms.author: shoag
ms.date: 07/28/2016
ms.topic: article
ms.prod: .net
ms.technology: dotnet-standard
ms.devlang: dotnet
ms.assetid: 3e196697-981c-4c1d-93dd-c3b236ef36dd
translationtype: Human Translation
ms.sourcegitcommit: fb00da6505c9edb6a49d2003ae9bcb8e74c11d6c
ms.openlocfilehash: 65cdec2c8bc8caf44329ee44bd574e612723be11
---
# <a name="regular-expression-example-changing-date-formats"></a>正規表現の例: 日付形式の変更
次のコード例では、[Regex.Replace](xref:System.Text.RegularExpressions.Regex.Replace(System.String,System.String)) メソッドを使用して、*/mm/dd/yy* 形式の日付を *dd-mm-yy* 形式の日付に置き換えます。
## <a name="example"></a>例
```csharp
static string MDYToDMY(string input)
{
try {
return Regex.Replace(input,
"\\b(?<month>\\d{1,2})/(?<day>\\d{1,2})/(?<year>\\d{2,4})\\b",
"${day}-${month}-${year}", RegexOptions.None,
TimeSpan.FromMilliseconds(150));
}
catch (RegexMatchTimeoutException) {
return input;
}
}
```
```vb
Function MDYToDMY(input As String) As String
Try
Return Regex.Replace(input, _
"\b(?<month>\d{1,2})/(?<day>\d{1,2})/(?<year>\d{2,4})\b", _
"${day}-${month}-${year}", RegexOptions.None,
TimeSpan.FromMilliseconds(150))
Catch e As RegexMatchTimeoutException
Return input
End Try
End Function
```
次のコードは、アプリケーションで `MDYToDMY` メソッドを呼び出す方法を示しています。
```csharp
using System;
using System.Globalization;
using System.Text.RegularExpressions;
public class Class1
{
public static void Main()
{
string dateString = DateTime.Today.ToString("d",
DateTimeFormatInfo.InvariantInfo);
string resultString = MDYToDMY(dateString);
Console.WriteLine("Converted {0} to {1}.", dateString, resultString);
}
static string MDYToDMY(string input)
{
try {
return Regex.Replace(input,
"\\b(?<month>\\d{1,2})/(?<day>\\d{1,2})/(?<year>\\d{2,4})\\b",
"${day}-${month}-${year}", RegexOptions.None,
TimeSpan.FromMilliseconds(150));
}
catch (RegexMatchTimeoutException) {
return input;
}
}
}
// The example displays the following output to the console if run on 8/21/2007:
// Converted 08/21/2007 to 21-08-2007.
```
```vb
Imports System.Globalization
Imports System.Text.RegularExpressions
Module DateFormatReplacement
Public Sub Main()
Dim dateString As String = Date.Today.ToString("d", _
DateTimeFormatInfo.InvariantInfo)
Dim resultString As String = MDYToDMY(dateString)
Console.WriteLine("Converted {0} to {1}.", dateString, resultString)
End Sub
Function MDYToDMY(input As String) As String
Try
Return Regex.Replace(input, _
"\b(?<month>\d{1,2})/(?<day>\d{1,2})/(?<year>\d{2,4})\b", _
"${day}-${month}-${year}", RegexOptions.None,
TimeSpan.FromMilliseconds(150))
Catch e As RegexMatchTimeoutException
Return input
End Try
End Function
End Module
' The example displays the following output to the console if run on 8/21/2007:
' Converted 08/21/2007 to 21-08-2007.
```
## <a name="comments"></a>コメント
この正規表現パターン `\b(?<month>\d{1,2})/(?<day>\d{1,2})/(?<year>\d{2,4})\b` の解釈を次の表に示します。
パターン | 説明
------- | -----------
`\b` | ワード境界から照合を開始します。
`(?<month>\d{1,2})` | 1 桁または 2 桁の 10 進数と一致します。 これは、`month` キャプチャ グループです。
`/` | スラッシュ マークと一致します。
`(?<day>\d{1,2})` | 1 桁または 2 桁の 10 進数と一致します。 これは、`day` キャプチャ グループです。
`/` | スラッシュ マークと一致します。
`(?<year>\d{2,4})` | 2 ~ 4 の 10 進数と一致します。 これは、`year` キャプチャ グループです。
`\b` | ワード境界で照合を終了します。
パターン `${day}-${month}-${year}` は、次の表に示すように置換文字列を定義します。
パターン | 説明
------- | -----------
`$(day)` | `day` キャプチャ グループによってキャプチャされた文字列を追加します。
`-` | ハイフンを追加します。
`$(month)` | `month` キャプチャ グループによってキャプチャされた文字列を追加します。
`-` | ハイフンを追加します。
`$(year)` | `year` キャプチャ グループによってキャプチャされた文字列を追加します。
## <a name="see-also"></a>関連項目
[.NET 正規表現](regular-expressions.md)
[正規表現の例](regex-examples.md)
<!--HONumber=Nov16_HO3-->
|
Python
|
UTF-8
| 481 | 3.328125 | 3 |
[
"MIT"
] |
permissive
|
import urllib.request, urllib.parse, urllib.error
import xml.etree.ElementTree as ET
while True:
url = input('Enter location: ')
if len(url) < 1: break
print('Retrieving', url)
uh = urllib.request.urlopen(url)
data = uh.read()
print('Retrieved', len(data), 'characters')
tree = ET.fromstring(data.decode())
counts = tree.findall('.//count')
print('Count:', len(counts))
print('Sum:', sum(int(counts[i].text) for i in range(len(counts))))
|
C#
|
UTF-8
| 2,018 | 2.625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Shadows
{
public partial class FormPrizma : Form
{
/// <summary>
/// Положение объекта
/// </summary>
internal double[] position;
/// <summary>
/// Индекс цвета в RGB
/// </summary>
internal int color;
/// <summary>
/// Диаметр
/// </summary>
internal double D;
/// <summary>
/// Высота
/// </summary>
internal double H;
/// <summary>
/// Количество граней призмы
/// </summary>
internal int N;
public FormPrizma()
{
InitializeComponent();
}
/// <summary>
/// Завершение редактирования и выход
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
position = new double[3];
position[0] = ShadowsForm.GetNumber(textX);
if (double.IsNaN(position[0]))
return;
position[1] = ShadowsForm.GetNumber(textY);
if (double.IsNaN(position[1]))
return;
position[2] = ShadowsForm.GetNumber(textZ);
if (double.IsNaN(position[2]))
return;
D = ShadowsForm.GetNumber(textD);
if (double.IsNaN(position[0]))
return;
H = ShadowsForm.GetNumber(textH);
if (double.IsNaN(position[0]))
return;
N = comboN.SelectedIndex + 3;
color = comboColor.SelectedIndex;
Close();
}
}
}
|
JavaScript
|
UTF-8
| 437 | 2.921875 | 3 |
[] |
no_license
|
'use strict';
var number_map_to_word_over_26 = function(collection){
return collection.map(a=>convert(a));
function convert(number){
if (number <= 26){
return String.fromCharCode(96 + number);
}
else if(number % 26 == 0){
return convert((number / 26) - 1) + convert(26);
}
else {
return convert((number / 26)) + convert(number % 26);
}
}
};
module.exports = number_map_to_word_over_26;
|
Shell
|
UTF-8
| 3,308 | 4.03125 | 4 |
[
"BSD-3-Clause"
] |
permissive
|
#!/bin/bash
# Copyright 2020 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Specify the version of the tools to download
if [[ "$1" == "" ]]; then
VER_FUCHSIA_SDK="latest"
else
VER_FUCHSIA_SDK="$1"
fi
set -eu # Error checking
err_print() {
cleanup
echo "Error on line $1"
}
trap 'err_print $LINENO' ERR
DEBUG_LINE() {
"$@"
}
SCRIPT_SRC_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
# Common functions.
# shellcheck disable=SC1090
source "${SCRIPT_SRC_DIR}/common.sh" || exit $?
THIRD_PARTY_DIR="$(get_third_party_dir)" # finds path to //third_party
FUCHSIA_SDK_DIR="${THIRD_PARTY_DIR}/fuchsia-sdk" # finds path to //third_party/fuchsia-sdk
TMP_SDK_DOWNLOAD_DIR=$(mktemp -d)
DOWNLOADED_SDK_PATH="${TMP_SDK_DOWNLOAD_DIR}/gn-sdk.tar.gz"
TMP_SDK_DIR=$(mktemp -d)
cleanup() {
# Remove the SDK downloads directory
if [ -f "${TMP_SDK_DOWNLOAD_DIR}" ]; then
rm -rf "${TMP_SDK_DOWNLOAD_DIR}"
fi
if [ -d "${TMP_SDK_DIR}" ]; then
rm -rf "${TMP_SDK_DIR}"
fi
}
if is-mac; then
PLATFORM="mac"
else
PLATFORM="linux"
fi
ARCH="${PLATFORM}-amd64"
# You can browse the GCS bucket from here to look for builds https://console.cloud.google.com/storage/browser/fuchsia/development
# You can get the instance ID with the following curl commands:
# Linux: `curl -sL "https://storage.googleapis.com/fuchsia/development/LATEST_LINUX`
# Mac: `curl -sL "https://storage.googleapis.com/fuchsia/development/LATEST_MAC`
# You can use the gsutil command-line tool to browse and search as well:
# Get the instance ID:
# Linux: `gsutil cat gs://fuchsia/development/LATEST_LINUX`
# Mac: `gsutil cat gs://fuchsia/development/LATEST_MAC`
# List the SDKs available for the instance ID
# `gsutil ls -r gs://fuchsia/development/$INSTANCE_ID/sdk`
# Download a SDK from GCS to your current directory:
# Linux: `gsutil cp gs://fuchsia/development/$INSTANCE_ID/sdk/linux-amd64/gn.tar.gz .`
# Mac: `gsutil cp gs://fuchsia/development/$INSTANCE_ID/sdk/mac-amd64/gn.tar.gz .`
# If specified version is "latest" get the latest version number
if [ "${VER_FUCHSIA_SDK}" == "latest" ]; then
PLATFORM_UPPER="$(echo "${PLATFORM}" | tr '[:lower:]' '[:upper:]')"
VER_FUCHSIA_SDK="$(curl -sL "https://storage.googleapis.com/fuchsia/development/LATEST_${PLATFORM_UPPER}")"
fi
echo "Downloading Fuchsia SDK ${VER_FUCHSIA_SDK} ..."
# Example URL: https://storage.googleapis.com/fuchsia/development/8888449404525421136/sdk/linux-amd64/gn.tar.gz
curl -sL "https://storage.googleapis.com/fuchsia/development/${VER_FUCHSIA_SDK}/sdk/${ARCH}/gn.tar.gz" -o "${DOWNLOADED_SDK_PATH}"
echo "complete."
echo
echo "Extracting Fuchsia SDK..."
tar -xf "${DOWNLOADED_SDK_PATH}" -C "${TMP_SDK_DIR}"
echo "complete."
echo
# Delete existing SDK
if [ -d "${FUCHSIA_SDK_DIR}" ]; then
echo "Removing existing SDK..."
# Remove entire folder and remake folder of the same name to remove hidden files
# e.g. third_party/fuchsia-sdk/.build-id/
rm -rf "${FUCHSIA_SDK_DIR}"
mkdir "${FUCHSIA_SDK_DIR}"
echo "complete."
echo
fi
# Copy new SDK to SDK dir
cp -r "${TMP_SDK_DIR}/." "${FUCHSIA_SDK_DIR}"
cleanup
echo "New SDK downloaded and extracted successfully to ${FUCHSIA_SDK_DIR}."
|
Java
|
UTF-8
| 843 | 2.84375 | 3 |
[] |
no_license
|
import java.sql.*;
public class PreparedStatement{
public static void main(String args[]){
try{
Connection con = null;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String path = "D:\\person.mdb";
con =DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ="+path+";DriverID=22;READONLY=true");
String query = "UPDATE person SET address = ? WHERE name = ? ";
PreparedStatement pst = con.prepareStatement(query);
String addVar = args[0];
String name = args[1];
pst.getString(1,addVar);
pst.getString(2,name);
int num = pst.executeUpdate();
System.out.println(num+" Record Updated");
con.close();
}catch(Exception e){
System.out.println(e);
}
}//end of main
}
|
PHP
|
UTF-8
| 17,332 | 2.53125 | 3 |
[] |
no_license
|
<?php
/**
* <p>Survey endpoiints</p>
*
* @package Ssmart
* @subpackage endpoint
*/
class Ssmart_Panelist_SurveyEndpoint extends Ssmart_GlobalController
{
/**
* Gets survey data
*
* <p><b>required params: </b>
* survey_id
* send_questions
* send_question_choices</p>
*
* @param Ssmart_EndpointRequest $request
* @return \Ssmart_EndpointResponse
*/
public function getSurvey(Ssmart_EndpointRequest $request)
{
$validators = array(
"starbar_id" => "int_required_notEmpty",
"survey_id" => "int_required_notEmpty",
"send_questions" => "required_allowEmpty",
"send_question_choices" => "required_allowEmpty"
);
$filters = array(
"send_questions" => "bool",
"send_question_choices" => "bool"
);
$response = new Ssmart_EndpointResponse($request, $filters, $validators);
//logic
$starbarId = (int)$request->getParam("starbar_id");
$surveyId = (int)$request->getParam("survey_id");
$sendQuestions = $request->getParam("send_questions");
$sendQuestionChoices = $request->getParam("send_question_choices");
$userId = $request->getUserId();
$surveyResponse = new Survey_Response();
$surveyResponse->loadDataByUniqueFields(array("user_id" => $userId, "survey_id" => $surveyId));
if (!$surveyResponse->id) {
// Failed... might be because it's a new user. Try to find new surveys of the same type for that user
$survey = new Survey();
$survey->loadData($surveyId);
if ($survey->id) {
Survey_ResponseCollection::markUnseenSurveysNewForStarbarAndUser($starbarId, $userId, $survey->type);
// try again
$surveyResponse->loadDataByUniqueFields(array("user_id" => $userId, "survey_id" => $surveyId));
}
}
if (!$surveyResponse->id) {
throw new Exception("SURVEY_UNAVAILABLE");
}
if ($surveyResponse->status == "completed" || $surveyResponse->status == "disqualified") {
throw new Exception("SURVEY_COMPLETED");
}
$survey = new Survey();
$survey->loadData($surveyId);
//add surveyResponseId
$surveyResponse = new Survey_Response();
$surveyResponse->loadDataByUniqueFields(["survey_id" => $surveyId, "user_id" => $userId]);
$survey->setRewardPoints($surveyResponse->status);
$surveyData = $survey->getData();
$surveyData["id"] = $surveyId;
$surveyData['survey_response_id'] = $surveyResponse->id;
//check for mission or trailer data
switch ($survey->type)
{
case "mission":
$missionInfo = new Survey_MissionInfo();
$missionInfo->loadDataBySurveyId($surveyId);
$missionInfoData = $missionInfo->getData();
$surveyData["mission_info"] = $missionInfoData;
break;
case "trailer":
$trailerInfo = new Survey_TrailerInfo();
$trailerInfo->loadDataBySurveyId($surveyId);
$trailerInfoData = $trailerInfo->getData();
$surveyData["trailer_info"] = $trailerInfoData;
break;
default:
}
if ($sendQuestionChoices) {
$choices = new Survey_QuestionChoiceCollection();
$choices->loadAllChoicesForSurvey($surveyId);
} else {
$choices = null;
}
//add questions and answer choices
if ($sendQuestions)
{
$i = 0;
$questions = new Survey_QuestionCollection();
$questions->loadAvailableQuestionsForSurvey($surveyId);
$questionData = [];
/** @var $question Survey_Question */
foreach ($questions as $question) {
$questionData[$i] = $question->toArray();
$questionData[$i]['id'] = $question->id;
if ($sendQuestionChoices) {
$choiceData = [];
$j = 0;
/** @var $choice Survey_QuestionChoice */
foreach ($choices as $choice) {
if ($choice->survey_question_id == $question->id) {
$choiceData[$j] = $choice->toArray();
$choiceData[$j]['id'] = $choice->id;
$j++;
}
}
$questionData[$i]['choices'] = $choiceData;
$i++;
}
}
$surveyData["questions"] = $questionData;
}
$cleanSurveyData = $this->_cleanSurveyResponse($surveyData, $surveyId);
$response->setResultVariable('survey', $cleanSurveyData);
return $response;
}
/**
* Gets multiple surveys.
*
* <p><b>required params: </b>
* starbar_id
* survey_type
* <b>optional params
* page_number
* results_per_page</p>
*
* @param Ssmart_EndpointRequest $request
* @return \Ssmart_EndpointResponse
*/
public function getSurveys(Ssmart_EndpointRequest $request)
{
$validators = array(
"starbar_id" => "int_required_notEmpty",
"survey_type" => "alpha_required_notEmpty",
"survey_status" => "alpha_required_notEmpty"
);
$filters = array();
$response = new Ssmart_EndpointResponse($request, $filters, $validators);
//logic
$starbarId = $request->getParam("starbar_id");
$userId = $request->getUserId();
$type = $request->getParam("survey_type");
$surveyUserStatus = $request->getParam("survey_status");
$pageNumber = (int) $request->getParam("page_number", 1);
$resultsPerPage = (int) $request->getParam("results_per_page", 50);
// used by trailers (though can be used by any type)
$chosenSurveyId = (int) $request->getParam("chosen_survey_id");
$alwaysChoose = $request->getParam("always_choose");
$type = str_replace("surveys", "survey", $type);
$type = str_replace("polls", "poll", $type);
$type = str_replace("trailers", "trailer", $type);
$type = str_replace("quizzes", "quiz", $type);
if ($type == "trailer")
$surveyUserStatus = "new";
if (in_array($surveyUserStatus, ["new", "archived"])) {
if (in_array($type, ["poll", "survey"])) {
Survey_ResponseCollection::markOldSurveysArchivedForStarbarAndUser($starbarId, $userId, $type);
}
Survey_ResponseCollection::markUnseenSurveysNewForStarbarAndUser($starbarId, $userId, $type);
}
$surveyCollection = new SurveyCollection();
$offset = $this->_calculateOffset($pageNumber, $resultsPerPage);
$surveyCollection->loadSurveysForStarbarAndUser ($starbarId, $userId, $type, $surveyUserStatus, $resultsPerPage, $offset);
$surveyIds = "";
foreach ($surveyCollection as $survey) {
if ($alwaysChoose === "true" && !$chosenSurveyId)
$chosenSurveyId = $survey->id;
if ($surveyIds) $surveyIds .= ",";
$surveyIds .= $survey->id;
$survey->setRewardPoints($surveyUserStatus);
if ($survey->id === $chosenSurveyId) {
$otherEndpointParams = array("survey_id" => $chosenSurveyId, "send_question_choices" => true, "send_questions" => true, "starbar_id" => $starbarId);
$response->addFromOtherEndpoint("getSurvey", get_class(), $otherEndpointParams, $this->request_name);
}
}
if ($type == "trailer" && $surveyIds) {
$sql = "SELECT survey_id, video_key FROM survey_trailer_info WHERE survey_id IN ($surveyIds)";
$results = Db_Pdo::fetchAll($sql);
$trailerInfo = [];
foreach ($results as $result) {
$trailerInfo[$result['survey_id']] = $result;
}
$response->setResultVariable("trailer_info", $trailerInfo);
}
if ($type == "mission" && $surveyIds) {
$sql = "SELECT survey_id, short_name, number_of_stages, preview_image FROM survey_mission_info WHERE survey_id IN ($surveyIds)";
$results = Db_Pdo::fetchAll($sql);
$missionInfo = [];
foreach ($results as $result) {
$missionInfo[$result['survey_id']] = $result;
}
$response->setResultVariable("mission_info", $missionInfo);
}
$response->addRecordsFromCollection($surveyCollection);
return $response;
}
/**
* Gets the count of how many surveys a user has.
*
* <p><b>required params: </b>
* starbar_id
* survey_type
* <b>optional params
* survey_status</p>
*
* @param Ssmart_EndpointRequest $request
* @return \Ssmart_EndpointResponse
*/
public function getSurveyCounts(Ssmart_EndpointRequest $request)
{
$validators = array(
"starbar_id" => "int_required_notEmpty",
"survey_type" => "alpha_required_notEmpty",
"survey_status" => "alpha_required_notEmpty"
);
$filters = array();
$response = new Ssmart_EndpointResponse($request, $filters, $validators);
//logic
$surveyType = $request->getParam("survey_type"); //TODO: make this optional [Why? -- Hamza]
$starbarId = $request->getParam("starbar_id");
$userId = $request->getUserId();
$status = $request->getParam("survey_status");
$count = Survey_ResponseCollection::countUserSurveys($userId, $starbarId, $surveyType, $status);
$response->setResultVariable("count", $count);
return $response;
}
/**
* Updates a survey response
*
* <p><b>required params: </b>
* starbar_id
* survey_id
* survey_response_id
* survey_data</p>
* <p>The ontents of survey_data are question_id question_choice_id pairs</p>
*
* @param Ssmart_EndpointRequest $request
* @return \Ssmart_EndpointResponse
* @throws Exception
* @see /applications/models/Surey/Response.php updateResponse()
*/
public function updateSurveyResponse(Ssmart_EndpointRequest $request)
{
$validators = array(
"starbar_id" => "int_required_notEmpty",
"survey_id" => "int_required_notEmpty",
"survey_response_id" => "int_required_notEmpty"
);
$filters = array();
$response = new Ssmart_EndpointResponse($request, $filters, $validators);
//logic
$surveyId = $request->getParam("survey_id");
$starbarId = $request->getParam("starbar_id");
$surveyResponseId = $request->getParam("survey_response_id");
$userId = $request->getUserId();
$survey = new Survey();
$survey->loadData($surveyId);
$surveyResponse = new Survey_Response();
$surveyResponse->loadData($surveyResponseId);
if (!$surveyResponse->id || $surveyResponse->user_id != $userId || ($surveyResponse->status != "new" && $surveyResponse->status != "archived"))
throw new Exception('Invalid survey (already completed?).');
//add to $data based on $response->submitted_parameters["survey_data"]
if ($surveyData = $request->getParam("survey_data"))
{
if (!is_object($surveyData) && !is_array($surveyData))
throw new Exception('Invalid $surveyData.');
}
$updatedStatus = $surveyResponse->updateResponse($surveyData);
// run the right transaction
if ($updatedStatus == "completed")
Game_Transaction::completeSurvey($userId, $starbarId, $survey);
else if ($updatedStatus == "disqualified")
Game_Transaction::disqualifySurvey($userId, $starbarId, $survey);
$response->setResultVariable("success", TRUE);
//add game data to the response
$economyId = Economy::getIdforStarbar($starbarId);
$commonDataParams = array("user_id" => $userId, "economy_id" => $economyId);
$response->addCommonData("game", $commonDataParams);
return $response;
}
/**
* Updates the status of a survey.
*
* <p><b>required params: </b>
* survey_response_id
* survey_status
* processing_status
* downloaded</p>
*
* @param Ssmart_EndpointRequest $request
* @return \Ssmart_EndpointResponse
* @throws \Ssmart_EndpointError | Exception
*
* @todo add options for next survey and results
*/
public function updateSurveyStatus(Ssmart_EndpointRequest $request)
{
//TODO: validate survey_status and processing_status against the enum in the db
$validators = array(
"starbar_id" => "int_required_notEmpty",
"survey_id" => "int_required_notEmpty",
"survey_response_id" => "int_required_notEmpty",
"survey_status" => "alpha_required_notEmpty",
);
$filters = array(
"downloaded" => "bool"
);
$response = new Ssmart_EndpointResponse($request, $filters, $validators);
//logic
$surveyId = $request->getParam("survey_id");
$surveyResponseId = $request->getParam("survey_response_id");
$surveyStatus = $request->getParam("survey_status");
$starbarId = $request->getParam("starbar_id");
$userId = $request->getUserId();
$survey = new Survey();
$survey->loadData($surveyId);
$surveyResponse = new Survey_Response();
$surveyResponse->loadData($surveyResponseId);
if (
!$survey->id
|| !$surveyResponse->id
|| ($surveyResponse->status != "new" && $surveyResponse->status != "archived") // survey should currently be new or archived
|| ($surveyStatus != "completed" && $surveyStatus != "disqualified") // and should change to completed or disqualified
|| $surveyResponse->survey_id != $survey->id // someone is guessing survey response id?
|| $surveyResponse->user_id != $userId
) {
throw new Exception('Access denied to update survey status');
}
// before saving the new status, get the next survey
$nextSurvey = Survey::getNextSurveyForUser($survey, $userId);
$nextSurveyData = new stdClass();
$nextSurveyData->id = $nextSurvey->id;
$nextSurveyData->title = $nextSurvey->title;
$nextSurveyData->size = $nextSurvey->size;
$surveyResponse->status = $surveyStatus;
if ($survey->origin == "SurveyGizmo")
$surveyResponse->processing_status = "pending";
else
$surveyResponse->processing_status = "not required";
$surveyResponse->completed_disqualified = new Zend_Db_Expr('now()');
$surveyResponse->save();
// run the right transaction
if ($surveyStatus == "completed")
Game_Transaction::completeSurvey($userId, $starbarId, $survey);
else
Game_Transaction::disqualifySurvey($userId, $starbarId, $survey);
$response->setResultVariable("success", true);
$response->setResultVariable("next_survey", $nextSurveyData);
//add game data to the response
$economyId = Economy::getIdforStarbar($starbarId);
$commonDataParams = array("user_id" => $userId, "economy_id" => $economyId);
$response->addCommonData("game", $commonDataParams);
return $response;
}
public function updateMissionProgress(Ssmart_EndpointRequest $request) {
$validators = array(
"starbar_id" => "int_required_notEmpty",
"top_frame_id" => "int_required_notEmpty",
"mission_short_name" => "alnum_required_notEmpty",
"mission_data" => "required_notEmpty",
);
$filters = array();
$response = new Ssmart_EndpointResponse($request, $filters, $validators);
$result = Survey_MissionProgress::update($request->getUserId(), $request->getParam("starbar_id")
, $request->getParam("top_frame_id"), $request->getParam("mission_short_name")
, $request->getParam("mission_data"));
if( Game_Transaction::wasTransactionExecuted() ) {
//add game data to the response
$economyId = Economy::getIdforStarbar($request->getParam("starbar_id"));
$commonDataParams = array("user_id" => $request->getUserId(), "economy_id" => $economyId);
$response->addCommonData("game", $commonDataParams);
}
$response->setResultVariable("success", $result);
return $response;
}
/**
* Performs actions for when a user shares a survey.
*
* <p><b>required params: </b>
* survey_id
* starbar_id
* shared_type
* network</p>
*
* @param Ssmart_EndpointRequest $request
* @return \Ssmart_EndpointResponse
*/
public function shareSurvey(Ssmart_EndpointRequest $request)
{
$validators = array(
"survey_id" => "int_required_notEmpty",
"starbar_id" => "int_required_notEmpty",
"shared_type" => "alpha_required_notEmpty",
"network" => "alpha_required_notEmpty"
);
$filters = array();
$response = new Ssmart_EndpointResponse($request, $filters, $validators);
//logic
$surveyId = $request->getParam("survey_id");
$starbarId = $request->getParam("starbar_id");
$userId = $request->getUserId();
$sharedType = $request->getParam("shared_type");
$network = $request->getParam("network");
$transactionId = Game_Transaction::share($userId, $starbarId, $sharedType, $network, $surveyId);
if ($transactionId)
{
$response->setResultVariable("success", TRUE);
$response->setResultVariable("transaction_id", $transactionId);
} else {
$response->setResultVariable("success", FALSE);
}
//add game data to the response
$economyId = Economy::getIdforStarbar($starbarId);
$commonDataParams = array("user_id" => $userId, "economy_id" => $economyId);
$response->addCommonData("game", $commonDataParams);
return $response;
}
//////////Helper functions/////////////
/**
* Removes unecessary fields field names
* on the survey object.
*
* @param array $survey
* @param int $surveyId
* @return type
*/
private function _cleanSurveyResponse($survey, $surveyId)
{
//remove fields not needed
$surveyFieldsToRemove = array(
"user_id" => "",
"starbar_id" => "",
"premium" => "",
"ordinal" => "",
"start_after" => "",
"start_at" => "",
"end_at" => "",
"processing_status" => "",
"start_day" => "",
"status" => "",
"last_response" => "",
"report_cell_id" => ""
);
$questionFieldsToRemove = array(
"survey_id" => "",
);
$questionChoiceFieldsToRemove = array(
"survey_question_id" => ""
);
$newSurvey = array_diff_key($survey, $surveyFieldsToRemove);
//step through each of the possible layers of the survey array
if (isset($survey["questions"]))
{
$i = 0;
foreach ($survey["questions"] as $value)
{
$newSurvey["questions"][$i] = array_diff_key($value, $questionFieldsToRemove);
if (isset($value["choices"]))
{
$newSurvey["questions"][$i]["choices"] = [];
foreach ($value["choices"] as $choiceValue)
{
$newSurvey["questions"][$i]["choices"][] = array_diff_key($choiceValue, $questionChoiceFieldsToRemove);
}
}
$i++;
}
}
return $newSurvey;
}
}
|
Java
|
UTF-8
| 1,051 | 2.25 | 2 |
[
"Apache-2.0"
] |
permissive
|
package me.zuichu.staticlib.core;
import android.app.Activity;
import me.zuichu.staticlib.manager.StaticEvent;
/**
* Created by office on 2018/4/16.
* 数据统计核心类
*/
public class StaticCore {
/**
* 统计页面浏览时长:开始
*
* @param activity
*/
public static void resume(Activity activity) {
}
/**
* 统计页面浏览时长:结束
*
* @param activity
*/
public static void pause(Activity activity) {
}
/**
* 统计页面浏览路径:结束
*
* @param activity
*/
public static void onDestroy(Activity activity) {
}
/**
* 事件点击统计
*
* @param eventId
* @param label
*/
public static void onEvent(String eventId, String label) {
StaticEvent staticEvent = new StaticEvent();
staticEvent.setEventId(eventId);
staticEvent.setLabel(label);
staticEvent.setTime(System.currentTimeMillis());
StaticApplication.events.add(staticEvent);
}
}
|
Java
|
UTF-8
| 1,644 | 3.078125 | 3 |
[] |
no_license
|
/**
* @author chaycao
* @description
* @date 2018-05-22 19:25.
*/
public class Solution_304 {
static class NumMatrix {
private int[][] temp;
private int n = 0;
private int m = 0;
public NumMatrix(int[][] matrix) {
if (matrix == null || matrix.length == 0)
return;
n = matrix.length; //row
m = matrix[0].length; //col
temp = new int[n][(1+m)*m/2];
for (int i = 0; i < n; i++) {
int index = 0;
for (int j = 0; j < m; j++) {
temp[i][index++] = matrix[i][j];
int sum = matrix[i][j];
for (int k = j+1; k < m; k++) {
sum += matrix[i][k];
temp[i][index++] = sum;
}
}
}
}
public int sumRegion(int row1, int col1, int row2, int col2) {
if (row2 >= n || col2 >= m)
return 0;
int res = 0;
for (int i = row1; i <= row2; i++) {
res += temp[i][(2*m-col1+1)*(col1)/2 + col2 - col1];
}
return res;
}
}
public static void main(String[] args) {
// int[][] matrix = {
// {3, 0, 1, 4, 2},
// {5, 6, 3, 2, 1},
// {1, 2, 0, 1, 5},
// {4, 1, 0, 1, 7},
// {1, 0, 3, 0, 5}
// };
int[][] matrix = {};
NumMatrix obj = new NumMatrix(matrix);
int param_1 = obj.sumRegion(1,2,2,4);
System.out.println(param_1);
}
}
|
Python
|
UTF-8
| 313 | 3.21875 | 3 |
[] |
no_license
|
if __name__ == '__main__':
i = 10
while i <= 10000000:
n = len(str(i))
j = 1
sumValue = 0
while j <= n:
cell = (i % (10 ** j)) // (10 ** (j - 1))
sumValue += cell ** n
j += 1
if sumValue == i:
print(i)
i += 1
|
JavaScript
|
UTF-8
| 6,791 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
function changebegindate(date) {
var datef = $.cookie("EZDATE1");
var datet = $.cookie("EZDATE2");
if (datef && datef != '') {
var hayfechas = 1;
var newdate = date;
} else {
var datef = date;
var datet = '';
var newdate = '';
var hayfechas = 0;
}
if (window.appmobile && window.appmobile == "yes") {
var url = "https://myezplan.com/data_ajax/mapcity_content3.cfm?rnu=5131616516651";
}else{
var url = "data_ajax/mapcity_content3.cfm?rnu=5131616516651";
}
var urlconfig = {
action: "updatebegindate",
datef: datef,
datet: datet,
datenew: newdate,
type: hayfechas,
useddays: useddays
};
$("#funcsparaadddates").load(url, urlconfig, function(response, status, xhr) {
switch (status) {
case "success":
$('.sortable.grid li').on('click', function(e) {
var num = $(this).data("num");
addtoday(num);
});
}
});
}
function addday() {
var datef = $.cookie("EZDATE1");
if (!datef || datef == '') {
var numdaystoadd = prompt('Number of days to Add', 1);
if (!numdaystoadd || numdaystoadd < 1 || isNaN(numdaystoadd)) {
alert('Please Type a valid number of days');
return false;
}
var totaldays = useddays + parseInt(numdaystoadd);
$('.sortable').empty();
$.cookie("NUMDAYS", totaldays);
useddays = totaldays;
var tabla = '';
for (d = 1; d <= totaldays; d++) {
var tabla = tabla + '<li id="order_' + d + '" data-num="' + d + '"><dl><dd> </dd><dd><span id="spandia_' + d + '" style="font-weight:bold;">Day ' + d + '</span></dd><dd><span id="spandia2_' + d + '" style="font-size:18px; font-weight:bold;"></span></dd></dl></li>'
}
$('.sortable').html(tabla);
for (d2 = 1; d2 <= totaldays; d2++) {
checkdaycontent_('' + d2);
}
$('.sortable.grid li').on('click', function(e) {
var num = $(this).data("num");
addtoday(num);
});
return false;
}
$('#addadate, #datetoadd').show();
}
function delday() {
if (useddays == 1) {
alert("You can't eliminate last day");
return false;
}
var datef = $.cookie("EZDATE1");
if (!datef || datef == '') {
datef = '';
}
var daytodelete = prompt('Type the number of the day you want to delete(For multiple days 4-7)', useddays);
var esrango = 0;
if (daytodelete) {
var donde = daytodelete.indexOf('-');
if (donde > 0) {
var esrango = 1;
var days = daytodelete.split('-');
for (d = 0; d < days.length; d++) {
if (days[d] < 1 || days[d] > useddays || isNaN(days[d])) {
alert('Please try with a valid day number');
return false;
}
}
}
}
if (esrango == 0) {
if (!daytodelete || daytodelete < 1 || daytodelete > useddays || isNaN(daytodelete)) {
alert('Please try with a valid day number');
return false;
}
}
if (esrango == 1) {
var toloop = daytodelete.split('-');
toloop.sort();
var tienealgo = false;
var daytienen = [];
for (x = toloop[0]; x <= toloop[1]; x++) {
var loads = $.cookie("EZMAPCITYPLACES_day" + x);
if (loads && loads != '') {
var tienealgo = true;
daytienen.push(x);
}
var loads = $.cookie("EZTRANSPORT_day" + x);
if (loads && loads != '') {
var tienealgo = true;
daytienen.push(x);
}
var loads = $.cookie("EZSERVICES_day" + x);
if (loads && loads != '') {
var tienealgo = true;
daytienen.push(x);
}
}
if (tienealgo) {
var conf = confirm('Are you sure you want to delete this days, days ' + daytienen.join(',') + ' have places added');
if (!conf) {
return false;
}
}
} else {
var tienealgo = false;
var loads = $.cookie("EZMAPCITYPLACES_day" + daytodelete);
if (loads && loads != '') {
var tienealgo = true;
}
var loads = $.cookie("EZTRANSPORT_day" + daytodelete);
if (loads && loads != '') {
var tienealgo = true;
}
var loads = $.cookie("EZSERVICES_day" + daytodelete);
if (loads && loads != '') {
var tienealgo = true;
}
if (tienealgo) {
var conf = confirm('Are you sure you want to delete day ' + daytodelete + ',it have places added');
if (!conf) {
return false;
}
}
}
var url = "https://myezplan.com/mobile/appdata/data_ajax/mapcity_content3.cfm?rnu=5131616516651";
var urlconfig = {
action: "delfullday",
date1: datef,
useddays: useddays,
num: daytodelete,
esrango: esrango
};
$("#funcsparaadddates").load(url, urlconfig, function(response, status, xhr) {
switch (status) {
case "success":
$('.sortable.grid li').on('click', function(e) {
var num = $(this).data("num");
addtoday(num);
});
}
});
}
function adddate(newdate) {
$('#addadate').hide();
var date1 = $.cookie('EZDATE1');
var date2 = $.cookie('EZDATE2');
if (window.appmobile && window.appmobile == "yes") {
var url = "https://myezplan.com/data_ajax/mapcity_content3.cfm?rnu=5131616516651";
}else{
var url = "data_ajax/mapcity_content3.cfm?rnu=5131616516651";
}
var urlconfig = {
action: "adddatestofull",
date1: date1,
date2: date2,
datenew: newdate,
useddays: useddays
};
$("#funcsparaadddates").load(url, urlconfig, function(response, status, xhr) {
switch (status) {
case "success":
$('.sortable.grid li').on('click', function(e) {
var num = $(this).data("num");
addtoday(num);
});
}
});
}
function fecha(cadena) {
var separador = "/"
if (cadena.indexOf(separador) != -1) {
var posi1 = 0
var posi2 = cadena.indexOf(separador, posi1 + 1)
var posi3 = cadena.indexOf(separador, posi2 + 1)
this.mes = cadena.substring(posi1, posi2)
this.dia = cadena.substring(posi2 + 1, posi3)
this.anio = cadena.substring(posi3 + 1, cadena.length)
} else {
this.dia = 0
this.mes = 0
this.anio = 0
}
}
/*$(document).ready(function(e) {
$('#DateToBegin').datepicker({
onSelect: function(date) {changebegindate(date);},
minDate: Date.now(),
changeMonth: true,
changeYear: true
});
$('#datetoadd').datepicker({
onSelect: function(date) {adddate(date);},
minDate: Date.now(),
changeMonth: true,
changeYear: true
});
$('.sortable.grid li').on('click', function(e){
var num=$(this).data("num");
addtoday(num);
});
});*/
console.log("calendar")
/*$('#DateToBegin').datepicker({
onSelect: function(date) {
changebegindate(date);
var _input = $('#'+$(this).attr('name'));
_input.attr('value', date);
$(this).hide();
},
minDate: 0,
changeMonth: true,
changeYear: true
});
$('#datetoadd').datepicker({
onSelect: function(date){
adddate(date);
var _input = $('#'+$(this).attr('name'));
_input.attr('value', date);
$(this).hide();
},
minDate: 0,
changeMonth: true,
changeYear: true
});*/
$("#DateToBegin").hide();
$('.sortable.grid li').on('click', function(e) {
var num = $(this).data("num");
addtoday(num);
});
$(window).load(function(e) {
$('.sortable.grid li').on('click', function(e) {
var num = $(this).data("num");
addtoday(num);
});
});
|
PHP
|
UTF-8
| 4,049 | 2.90625 | 3 |
[] |
no_license
|
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
/**
* Easy Web Service creation
*
* PHP 5
*
* LICENSE: This source file is subject to version 3.0 of the PHP license
* that is available through the world-wide-web at the following URI:
* http://www.php.net/license/3_0.txt. If you did not receive a copy of
* the PHP License and are unable to obtain it through the web, please
* send a note to license@php.net so we can mail you a copy immediately.
*
* @category Services
* @package Services_Webservice
* @author Manfred Weber <weber@mayflower.de>
* @author Philippe Jausions <Philippe.Jausions@11abacus.com>
* @copyright 2005 The PHP Group
* @license http://www.php.net/license/3_0.txt PHP License 3.0
* @version CVS: $Id$
* @link http://pear.php.net/package/Services_Webservice
*/
/**
* PEAR::Services_Webservice
*
* The PEAR::Services_Webservice class creates web services from your classes
*
* @author Manfred Weber <weber@mayflower.de>
* @author Philippe Jausions <Philippe.Jausions@11abacus.com>
* @package Services_Webservices
* @version @version@
*/
abstract class Services_Webservice
{
/**
* Namespace of the web service
*
* @var string
* @access public
*/
public $namespace;
/**
* Protocol of the web service
*
* @var string
* @access public
*/
public $protocol;
/**
* Name of the class from which to create a web service from
*
* @var string
* @access protected
*/
protected $_classname;
/**
* Class instance used by the web service
*
* @var object
* @access protected
*/
protected $_classnameInstance = null;
/**
* Parameter for the user's web service class
*
* @var array
* @access protected
*/
protected $_initParams = null;
/**
* Constructor
*
* @var object|string $class
* @var string $namespace
* @var array $options
* @access protected
* @throws Services_Webservice_NotClassException
*/
protected function __construct($class, $namespace, $options = null)
{
if (is_object($class)) {
$this->_classname = $class->get_class();
$this->_classnameInstance =& $class;
} elseif (is_string($class)) {
$this->_classname = $class;
} else {
throw new Services_Webservice_NotClassException(
'Expected a class name or instance.');
}
if (trim($namespace) == '') {
$namespace = 'http://example.org/';
}
$this->namespace = $namespace;
$this->protocol = 'http';
}
/**
* Returns a Services_Webservice server instance to handle incoming
* requests.
*
* @param string $driver backend service type (for now only SOAP)
* @var object|string $class
* @var string $namespace
* @var array $options
* @access public
* @throws Services_Webservice_UnknownDriverException
* @throws Services_Webservice_NotClassException
*/
public function &factory($driver, $class, $namespace, $options = null)
{
$backend = 'Services_Webservice_' . $driver;
include_once 'Services/Webservice/' . basename($driver) . '.php';
if (!class_exists($backend)) {
require_once 'Services/Webservice/Exception.php';
throw Services_Webservice_UnknownDriverException('Unknown backend driver: ' . $driver);
}
$instance = new $backend($class, $namespace, $options);
return $instance;
}
/**
* Initializes web service
*
* The parameters passed to this method will be passed to your class
* constructor
*
* @access public
*/
public function init()
{
$this->_initParams = func_get_args();
}
/**
* Automatically handles the incoming request
*
* The result depends on how the service was called and which backend
* is used.
* @access public
*/
abstract public function handle();
}
?>
|
Markdown
|
UTF-8
| 8,572 | 2.53125 | 3 |
[] |
permissive
|
# Streaming replication protocol
EPGSQL supports PostgreSQL streaming replication protocol.
See https://www.postgresql.org/docs/current/static/protocol-replication.html
## Use cases
***Consistent cache***
Erlang application uses in read-only mode data from PostgreSql DB tables
(e.g. some configuration, rate/price plans, subscriber’s profiles)
and needs to store the data in some internal structure (e.g. ETS table).
The data in PostgreSql DB is updated by some third party applications.
Erlang application needs to know about modifications in a near real-time mode.
During start Erlang application uploads initial data from the tables
and subscribes to receive any modifications for data in these tables and update internal ETS tables accordingly.
Using special output plugins for replication slots (for example: pglogical_output)
we can filter tables and receive only changes for some particular tables.
***Consistent internal DB***
This case is similar to previous “Consistent cache”,
but the difference is that amount of data in the table is huge
and it is inefficient and takes too much time to upload data every time on startup,
so Erlang application stores copy of data in some persistent internal storage(mnesia, riak, files).
In this case application uploads initial data from the table only once during the first start.
Afterwards it receives modifications and apply it in it’s storage.
Even if application is down it will not lose any changes from DB
and will receive all changes when it starts again.
## Usage
1. Initiate connection in replication mode.
To initiate streaming replication connection, `replication` parameter with
the value "database" should be set in the `epgsql:connect`.
Only simple queries `squery` can be used in replication mode and
only special commands accepted in this mode
(e.g DROP_REPLICATION_SLOT, CREATE_REPLICATION_SLOT, IDENTIFY_SYSTEM).
Replication commands as well as replication connection mode available only in epgsql and not in epgsqla, epgsqli.
2. Create replication slot.
Replication slot will be updated as replication progresses so that the PostgreSQL server knows
which WAL segments are still needed by the standby.
Use `epgsql:squery` to send CREATE_REPLICATION_SLOT command.
When a new replication slot is created, a snapshot is exported,
which will show exactly the state of the database
after which all changes will be included in the change stream.
This snapshot can be used to create a new replica by using SET TRANSACTION SNAPSHOT
to read the state of the database at the moment the slot was created.
Note: you have to create new connection with the not-replciation mode to select initial state of tables,
since you cannot run SELECT in replication mode connection.
3. Start replication.
Use `epgsql:start_replication` to start streaming.
```erlang
ok = epgsql:start_replication(Connection, ReplicationSlot, Callback, CbInitState,
WALPosition, PluginOpts, Opts).
```
- `Connection` - connection in replication mode
- `ReplicationSlot` - the name of the replication slot to stream changes from
- `Callback` - callback module which should have the callback functions
or a process which should be able to receive replication messages.
- `CbInitState` - initial state of callback module.
- `WALPosition` - the WAL position XXX/XXX to begin streaming at.
"0/0" to let the server determine the start point.
- `PluginOpts` - optional options passed to the slot's logical decoding plugin.
For example: "option_name1 'value1', option_name2 'value2'"
- `Opts` - options of logical replication.
See Logical replication options section for details.
On success, PostgreSQL server responds with a CopyBothResponse message, and then starts to stream WAL records.
PostgreSQL sends CopyData messages which contain:
- Keepalive message. *epgsql* answers with standby status update message, to avoid a timeout disconnect.
- XLogData message. *epgsql* calls `CallbackModule:handle_x_log_data` for each XLogData
or sends async messages `{epgsql, self(), {x_log_data, StartLSN, EndLSN, WALRecord}}`.
In case of async mode, the receiving process should report last processed LSN by calling
`standby_status_update(Connection, FlushedLSN, AppliedLSN)`.
```erlang
%% Handles a XLogData Message (StartLSN, EndLSN, WALRecord, CbState).
%% Return: {ok, LastFlushedLSN, LastAppliedLSN, NewCbState}
-callback handle_x_log_data(lsn(), lsn(), binary(), cb_state()) -> {ok, lsn(), lsn(), cb_state()}.
```
Example:
```erlang
start_replication() ->
{ok, C} = epgsql:connect("localhost", "username", "psss", [
{database, "test_db"},
{replication, "database"}
]),
Res = epgsql:squery(C, "CREATE_REPLICATION_SLOT ""epgsql_test"" LOGICAL ""test_decoding"""),
io:format("~p~n", [Res]),
ok = epgsql:start_replication(C, "epgsql_test", ?MODULE, [], "0/0").
handle_x_log_data(StartLSN, EndLSN, Data, CbState) ->
io:format("~p~n", [{StartLSN, EndLSN, Data}]),
{ok, EndLSN, EndLSN, CbState}.
```
##Logical replication options
* **align_lsn** - Default - false.
During shutdown PG server waits to exit until XLOG records have been sent to the standby,
up to the shutdown checkpoint record and sends `Primary keepalive message`
with the special flag (which means that the client should reply to this message as soon as possible)
to get the last applied LSN from the standby.
If epgsql uses for replication a decoding plugin which filter some WAL records
(for example pgoutput and PG publications with some tables)
then epgsql will not receive all WAL records and keep in the state not the latest LSN.
In such case it is not be possible to stop PG server if epgsql replication is running,
because epgsql is not able to report latest LSN.
To overcome this problem use option `align_lsn = true`.
If this option enabled when epgsql gets `Primary keepalive message` with the reply required flag
it will send back to PG server LSN received in `Primary keepalive message`.
PG server will stop normally after receiving this latest LSN.
If during PG server shutdown epgsql has some replication delay
then there is a risk to skip not yet received wal segments,
i.e. after restart PG server will send only new wal segments.
However if you use epgsql replication to implement a case 'Consistent cache'
and re-create replication slots (or use temporary slots)
and load all data from tables on an application startup
then you do not have any risk to lose data.
Otherwise (if you do not load all data from tables during erlang app startup)
it is not recommended to set align_lsn to true. In this case to stop PG server stop epgsql replication first.
## Flow control
It is possible to set `{socket_active, N}` on a [TCP](https://www.erlang.org/doc/man/inet.html#setopts-2)
or [SSL](https://www.erlang.org/doc/man/ssl.html#setopts-2) (since OTP 21.3) socket. E.g. for SSL:
```erlang
Opts = #{host => "localhost",
username => "me",
password => "pwd",
database => "test",
ssl => require,
socket_active => 10
},
{ok, Conn} = epgsql:connect(Opts).
```
Its main purpose is to control the flow of replication messages from Postgresql database.
If a database is under a high load and a process, which
handles the message stream, cannot keep up with it then setting this option gives the handling process
ability to get messages on-demand.
When the connection is in the asynchronous mode, a process which owns a connection will receive
```erlang
{epgsql, Connection, socket_passive}
```
as soon as underlying socket received N messages from network.
The process decides when to activate connection's socket again. To do that it should call:
```erlang
epgsql:activate(Connection).
```
The `active` parameter of the socket will be set to the same value as it was configured in
the connection's options.
In the case of synchronous handler for replication messages `epgsql` will handle `socket_passive`
messages internally.
See [Active socket README section](../#active-socket) for more details.
|
Python
|
UTF-8
| 332 | 3.359375 | 3 |
[] |
no_license
|
a=int(input("enter 1st num:"))
b=int(input("enter 2nd num:"))
c=int(input("enter 3rd num:"))
sum=a+b+c
avg=(a+b+c)/3
print("sum:",sum)
print("average:",avg)
'''
expected out put
enter 1st num:1
enter 2nd num:2
enter 3rd num:3
sum:6
average:2
'''
#output
#enter 1st num:1
#enter 2nd num:2
#enter 3rd num:3
#sum:6
#average:2
|
C++
|
UTF-8
| 3,675 | 2.703125 | 3 |
[] |
no_license
|
#include <stdexcept>
#include <vector>
#include <random>
#include "andres/marray.hxx"
#include "andres/ml/decision-trees.hxx"
inline void test(const bool& x) {
if(!x) throw std::logic_error("test failed.");
}
template<class T>
void
printLiteral2D(andres::Marray<T> arr, const size_t shape[]) {
std::cout << "{";
for(size_t i = 0; i < shape[0]; ++i) {
if (i) std::cout << ",";
std::cout << "{";
for(size_t j = 0; j < shape[1]; ++j) {
if (j) std::cout << ",";
std::cout << arr(i, j);
}
std::cout << "}";
}
std::cout << "}; " << std::endl;
}
int main() {
const size_t numberOfSamples = 100;
const size_t numberOfFeatures = 2;
const size_t numberOfLabels = 2;
// define random feature matrix
std::default_random_engine RandomNumberGenerator;
typedef double Feature;
std::uniform_real_distribution<double> randomDistribution(0.0, 1.0);
const size_t shape[] = {numberOfSamples, numberOfFeatures};
const size_t label_shape[] = {numberOfSamples, numberOfLabels};
andres::Marray<Feature> features(shape, shape + 2);
for(size_t sample = 0; sample < numberOfSamples; ++sample)
for(size_t feature = 0; feature < numberOfFeatures; ++feature) {
features(sample, feature) = randomDistribution(RandomNumberGenerator);
}
// define labels
typedef unsigned char Label;
andres::Marray<Label> labels(shape, shape + 1);
for(size_t sample = 0; sample < numberOfSamples; ++sample) {
if((features(sample, 0) <= 0.5 && features(sample, 1) <= 0.5)
|| (features(sample, 0) > 0.5 && features(sample, 1) > 0.5)) {
labels(sample) = 0;
}
else {
labels(sample) = 1;
}
}
// learn decision forest
typedef double Probability;
andres::ml::DecisionForest<Feature, Label, Probability> decisionForest;
const size_t numberOfDecisionTrees = 10;
decisionForest.learn(features, labels, numberOfLabels, numberOfDecisionTrees);
// predict probabilities for every label and every training sample
andres::Marray<Probability> probabilities(label_shape, label_shape + 2);
decisionForest.predict(features, probabilities, false);
// TODO: test formally
// printLiteral2D(probabilities, label_shape);
const Probability reference[numberOfSamples][numberOfFeatures] = {{0.1,0.9},{0.8,0.2},{1,0},{0.9,0.1},{0.9,0.1},{0.1,0.9},{0.9,0.1},{0.8,0.2},{1,0},{0,1},{0.2,0.8},{0.4,0.6},{0.6,0.4},{0.4,0.6},{0.2,0.8},{0.9,0.1},{1,0},{0.7,0.3},{0,1},{1,0},{1,0},{1,0},{0.1,0.9},{0.8,0.2},{0.2,0.8},{0.1,0.9},{0.2,0.8},{0.9,0.1},{0.9,0.1},{0.7,0.3},{0.4,0.6},{1,0},{0.3,0.7},{0.3,0.7},{0.9,0.1},{0.3,0.7},{0.3,0.7},{0.7,0.3},{0.7,0.3},{0.9,0.1},{0,1},{0.2,0.8},{0.8,0.2},{0.9,0.1},{0.7,0.3},{1,0},{0.1,0.9},{0,1},{0.7,0.3},{0.9,0.1},{1,0},{0.2,0.8},{0.9,0.1},{0.1,0.9},{0.7,0.3},{0.8,0.2},{0.1,0.9},{0.9,0.1},{1,0},{0.8,0.2},{0,1},{0.8,0.2},{0.9,0.1},{0.6,0.4},{0.8,0.2},{0.9,0.1},{0.3,0.7},{0.6,0.4},{0.2,0.8},{0.7,0.3},{0.3,0.7},{0.2,0.8},{0.8,0.2},{0.2,0.8},{0.1,0.9},{0.8,0.2},{0.7,0.3},{0.1,0.9},{0.1,0.9},{0.4,0.6},{0.1,0.9},{0.8,0.2},{0.2,0.8},{0.8,0.2},{0.7,0.3},{0.8,0.2},{0.4,0.6},{0.9,0.1},{0.2,0.8},{1,0},{0.2,0.8},{0.9,0.1},{0.8,0.2},{0.6,0.4},{0.1,0.9},{0.9,0.1},{0.9,0.1},{1,0},{0.2,0.8},{1,0}};
for(size_t i = 0; i < label_shape[0]; ++i) {
for(size_t j = 0; j < label_shape[1]; ++j) {
test( probabilities(i, j) == reference[i][j] );
}
}
decisionForest.predict(features, probabilities, true);
// TODO: test formally
printLiteral2D(probabilities, label_shape);
return 0;
}
|
Java
|
UTF-8
| 4,097 | 2.703125 | 3 |
[] |
no_license
|
package com.example.eunoia.user_profile3.healthyfoodsuggestion.course.aa;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.example.eunoia.user_profile3.R;
public class aa1 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_aa1);
final TextView textView = (TextView)findViewById(R.id.textView12);
final Button button1 = (Button)findViewById(R.id.button4);
final Button button2 = (Button)findViewById(R.id.button5);
if (button1 != null)
{
button1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
if (textView != null)
{
textView.setText("A yummy way to start the day with very little fat and lots of flavor!\n" +
"\n" +
"Calories:\t\t93.2 per serving\n" +
"Total Fat:\t\t0.5 g\n" +
"Total Carbohydrate:\t\t23.6 g\n" +
"Protein:\t\t3.0 g");
}
}
});
}
if (button2 != null)
{
button2.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
if (textView != null)
{
textView.setText("Introduction\n" +
"\n" +
"Minutes to Prepare: 5\n" +
"Minutes to Cook: 25\n" +
"Number of Servings: 12\n" +
"\n" +
"Ingredients\n" +
"\n" +
"1 cup old fashioned oats (not instant)\n" +
"1 cup skim milk\n" +
"1 cup whole wheat flour\n" +
"1/2 cup brown sugar\n" +
"1/2 cup unsweetened applesauce\n" +
"2 egg whites \n" +
"1 teaspoon baking powder\n" +
"1/2 teaspoon baking soda\n" +
"1/2 teaspoon salt\n" +
"1 teaspoon cinnamon\n" +
"1 teaspoon sugar\n" +
"raisins or nuts (optional)\n" +
"\n" +
"Directions\n" +
"\n" +
"Soak the oats in milk for about one hour. \n" +
"Preheat the oven to 400 degrees. \n" +
"Spray muffin pan with cooking spray. \n" +
"Combine the oat mixture with the applesauce and egg whites, and mix until combined. \n" +
"In a separate bowl measure and whisk the dry ingredients together. \n" +
"Add wet ingredients to dry and mix until just combined. Add nuts or raisins if desired. \n" +
"Do not over mix the batter or the muffins will be tough. Spoon muffin mixture into muffin pan. \n" +
"Combine the cinnamon and sugar and top each muffin with some of the mixture. \n" +
"Bake for 20-25 minutes or until done. \n" +
"Remove from pan, cool and enjoy. \n" +
"These can be frozen and reheated in the microwave for a quick breakfast.");
}
}
});
}
}
}
|
Python
|
UTF-8
| 2,635 | 3.0625 | 3 |
[
"MIT"
] |
permissive
|
import unittest
import gdalhelpers.checks.values_checks as values_check
import math
class ValuesCheckTests(unittest.TestCase):
def test_check_value_is_zero_or_positive(self):
with self.assertRaisesRegex(TypeError, "must be either `int` or `float`"):
values_check.check_value_is_zero_or_positive("test", "val")
with self.assertRaisesRegex(ValueError, "must be higher than 0"):
values_check.check_value_is_zero_or_positive(-5, "val")
self.assertIsInstance(values_check.check_value_is_zero_or_positive(5, "val"),
type(None))
def test_check_return_value_is_angle(self):
with self.assertRaisesRegex(TypeError, "must be either `int` or `float`"):
values_check.check_return_value_is_angle("test", "val")
self.assertAlmostEqual(values_check.check_return_value_is_angle(math.pi*1.1, "val"),
-math.pi*0.9, places=6)
self.assertAlmostEqual(values_check.check_return_value_is_angle(-math.pi*1.5, "val"),
math.pi*0.5, places=6)
self.assertAlmostEqual(values_check.check_return_value_is_angle(0, "val"),
0, places=6)
self.assertAlmostEqual(values_check.check_return_value_is_angle(0.2345, "val"),
0.2345, places=6)
self.assertAlmostEqual(values_check.check_return_value_is_angle(-1.2345, "val"),
-1.2345, places=6)
def test_check_return_value_is_angle_degrees(self):
with self.assertRaisesRegex(TypeError, "must be either `int` or `float`"):
values_check.check_return_value_is_angle_degrees("test", "val")
self.assertEqual(values_check.check_return_value_is_angle_degrees(0, "val"), 0)
self.assertEqual(values_check.check_return_value_is_angle_degrees(90, "val"), 90)
self.assertEqual(values_check.check_return_value_is_angle_degrees(180, "val"), 180)
self.assertEqual(values_check.check_return_value_is_angle_degrees(360, "val"), 360)
self.assertEqual(values_check.check_return_value_is_angle_degrees(370, "val"), 10)
self.assertEqual(values_check.check_return_value_is_angle_degrees(-10, "val"), 350)
def test_check_number(self):
self.assertIsNone(values_check.check_number(5, "val"))
self.assertIsNone(values_check.check_number(3.5, "val"))
self.assertIsNone(values_check.check_number(4e-5, "val"))
with self.assertRaisesRegex(TypeError, "must be either `int` or `float`"):
values_check.check_number("test", "val")
|
Python
|
UTF-8
| 679 | 3.375 | 3 |
[] |
no_license
|
class Solution:
# @param {int[]} nums an integer array
# @param {int} target an integer
# @return {int} the difference between the sum and the target
def twoSumClosest(self, nums, target):
if not nums or len(nums) < 2:
return -1
nums.sort()
min_diff = sys.maxint
left, right = 0, len(nums) - 1
while left < right:
diff = nums[left] + nums[right] - target
if abs(diff) < min_diff:
min_diff = abs(diff)
if diff == 0:
break
elif diff > 0:
right -= 1
else:
left += 1
return min_diff
|
Java
|
UTF-8
| 1,105 | 2.4375 | 2 |
[] |
no_license
|
package dev.feldmann.redstonegang.wire.game.base.addons.both.shopintegration.cmds;
import dev.feldmann.redstonegang.common.RedstoneGang;
import dev.feldmann.redstonegang.common.utils.Cooldown;
import dev.feldmann.redstonegang.wire.base.cmds.arguments.Arguments;
import dev.feldmann.redstonegang.wire.base.cmds.arguments.StringArgument;
import dev.feldmann.redstonegang.wire.base.cmds.types.PlayerCmd;
import dev.feldmann.redstonegang.wire.utils.msgs.C;
import org.bukkit.entity.Player;
public class AtivarCodigo extends PlayerCmd {
private static final StringArgument CODIGO = new StringArgument("Código", false);
public AtivarCodigo() {
super("ativar", "Ativa um código de vip ou cash", CODIGO);
setAlias("codigo");
setCooldown(new Cooldown(5000));
}
@Override
public void command(Player player, Arguments args) {
String codigo = args.get(CODIGO);
boolean activated = RedstoneGang.instance().shop().tryToActivateCode(getUser(player), codigo);
if (!activated) {
C.error(player, "Código inválido!");
}
}
}
|
C#
|
UTF-8
| 1,308 | 3.40625 | 3 |
[] |
no_license
|
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace TaskParallel
{
class Program
{
static void Main(string[] args)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
Parallel.Invoke(
() => ExecutThreadZero(),
() => ExecutThreadUm(),
() => ExecutThreadDot()
);
stopwatch.Stop();
Console.WriteLine("Tarefa finalizada! {0}s", stopwatch.ElapsedMilliseconds / 1000.0);
}
private static void ExecutThreadDot()
{
for (int i = 0; i < 300; i++)
{
TaskSleep();
Console.Write(".");
}
}
private static void ExecutThreadUm()
{
for (int i = 0; i < 300; i++)
{
TaskSleep();
Console.Write("1");
}
}
private static void ExecutThreadZero()
{
for (int i = 0; i < 300; i++)
{
TaskSleep();
Console.Write("0");
}
}
private static void TaskSleep()
{
Thread.Sleep(10);
}
}
}
|
Go
|
UTF-8
| 512 | 3.28125 | 3 |
[] |
no_license
|
package main
import (
"fmt"
"net/http"
"os"
)
func main() {
links := []string{
"https://www.google.com",
"https://www.facebook.com",
"https://www.stackoverflow.com",
"https://golang.org",
}
c := 0
for _, link := range links {
go checkLink(link, &c)
}
}
func checkLink(link string, c *int) {
res, err := http.Get(link)
printError(err)
if res.StatusCode >= 200 && res.StatusCode < 400 {
*c++
}
}
func printError(e error) {
if e != nil {
fmt.Println("Error:", e)
os.Exit(0)
}
}
|
Java
|
UTF-8
| 7,760 | 2.03125 | 2 |
[] |
no_license
|
package mitrais.com.clinicapp.activities.mainmenu;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.TimePicker;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import mitrais.com.clinicapp.R;
import mitrais.com.clinicapp.rest.models.CoreModel;
import mitrais.com.clinicapp.rest.models.StatusResponseModel;
import mitrais.com.clinicapp.rest.services.WebServices;
import mitrais.com.common.utils.TimePickerUtil;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* Created by mtmac20 on 3/22/17.
*/
interface IAppointmentCreateListener {
void onConfirmData(ConfirmationData data);
}
public class AppointmentCreateFragment extends DialogFragment implements CalendarView.OnDateChangeListener, TimePicker.OnTimeChangedListener, IDoctorListListener {
Button btnDate;
Button btnTime;
Button btnSelectDoctor;
CalendarView calendarView;
TimePicker timePicker;
DoctorListFragment doctorListFragment;
DoctorListItem selectedDoctor;
IAppointmentCreateListener listener;
TimePickerUtil timePickerUtil;
@Override
public void onStart() {
super.onStart();
Dialog dialog = getDialog();
if (dialog != null)
{
int width = ViewGroup.LayoutParams.MATCH_PARENT;
int height = ViewGroup.LayoutParams.MATCH_PARENT;
dialog.getWindow().setLayout(width, height);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.popup_appointment_create, container, false);
timePickerUtil = new TimePickerUtil(15);
timePicker = (TimePicker) rootView.findViewById(R.id.timepicker);
timePicker.setOnTimeChangedListener(this);
timePicker.setDescendantFocusability(TimePicker.FOCUS_BLOCK_DESCENDANTS);
timePickerUtil.setTimePickerInterval(timePicker);
calendarView = (CalendarView) rootView.findViewById(R.id.calendar);
calendarView.setOnDateChangeListener(this);
//btn for opening up the calendar view
btnDate = (Button) rootView.findViewById(R.id.btn_date);
btnDate.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View view) {
timePicker.setVisibility(View.GONE);
calendarView.setVisibility(View.VISIBLE);
}
}
);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
btnDate.setText(sdf.format(calendarView.getDate()));
//btn for opening up the timepicker
btnTime = (Button) rootView.findViewById(R.id.btn_time);
btnTime.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View view) {
calendarView.setVisibility(View.GONE);
timePicker.setVisibility(View.VISIBLE);
}
}
);
btnTime.setText(timePicker.getCurrentHour()+":45");
Button btnClose = (Button) rootView.findViewById(R.id.btn_close);
btnClose.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View view) {
dismiss();
}
}
);
doctorListFragment = new DoctorListFragment();
doctorListFragment.setDoctorListListener(this);
btnSelectDoctor = (Button) rootView.findViewById(R.id.btn_select_doctor);
btnSelectDoctor.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View view) {
doctorListFragment.show(getActivity().getFragmentManager(), "doclist");
doctorListFragment.doGetDoctorList();
}
}
);
Button btnCreateAppt = (Button) rootView.findViewById(R.id.btn_create_appt);
btnCreateAppt.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View view) {
createAppointment();
}
}
);
return rootView;
}
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
// add one because month starts at 0
month = month + 1;
String newDate = String.format("%02d",dayOfMonth)+"/"+String.format("%02d",month)+"/"+year;
btnDate.setText(newDate);
}
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
String newTime = hourOfDay + ":" + String.format("%02d", minute * timePickerUtil.Interval);
btnTime.setText(newTime);
}
public void onDoctorItemSelected(DoctorListItem item) {
selectedDoctor = item;
btnSelectDoctor.setText(selectedDoctor.Name);
}
private String getCompiledDate() {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm");
Date apptDate = new Date();
String curDate = btnDate.getText() + " " + btnTime.getText();
try {
apptDate = sdf.parse(curDate);
} catch (ParseException e) {
e.printStackTrace();
}
String formattedDate = new SimpleDateFormat("yyyy-MM-dd hh:mm").format(apptDate);
return formattedDate;
}
public void createAppointment() {
final ProgressDialog progress = new ProgressDialog(getActivity());
progress.setTitle("Loading");
progress.setMessage("Logging in...");
progress.setCancelable(false);
progress.show();
boolean canCreate = true;
if (canCreate) {
WebServices ws = new WebServices();
Call<StatusResponseModel> call = ws.getServices().doCreateAppointment(
getCompiledDate()
, CoreModel.getInstance().getLoginModel().Credentials.Id
, Integer.parseInt(selectedDoctor.Id)
);
final ConfirmationData confData = new ConfirmationData(
CoreModel.getInstance().getLoginModel().Credentials.Name
, selectedDoctor.Name
, btnDate.getText().toString()
, btnTime.getText().toString()
);
call.enqueue(new Callback<StatusResponseModel>() {
@Override
public void onResponse(Call<StatusResponseModel> call, Response<StatusResponseModel> response) {
progress.dismiss();
if (response.body().Status) {
listener.onConfirmData(confData);
dismiss();
}
}
@Override
public void onFailure(Call<StatusResponseModel> call, Throwable t) {
progress.dismiss();
}
}
);
}
}
public void setListener(IAppointmentCreateListener l) {
listener = l;
}
}
|
C++
|
UTF-8
| 1,842 | 2.75 | 3 |
[] |
no_license
|
/**
* Number:uva156
* Title:Ananagrams
* Status:AC
* Tag:[模拟, map]
**/
#include <cstdio>
#include <iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <vector>
#include <string>
#include <map>
using namespace std;
#define INF 0x3f3f3f3f
typedef long long ll;
typedef unsigned long long ull;
inline int readi(int& i1) { return scanf("%d", &i1); }
inline int readi(int& i1, int& i2) { return scanf("%d %d", &i1, &i2); }
inline int readi(int& i1, int& i2, int& i3) { return scanf("%d %d %d", &i1, &i2, &i3); }
inline int readi(int& i1, int& i2, int& i3, int& i4) { return scanf("%d %d %d %d", &i1, &i2, &i3, &i4); }
inline int reads(char* s1) { return scanf("%s", s1); }
#define clr(mem, val) memset(mem, val, sizeof(mem))
#define rep(i, begin, end) for (register int i = (begin); i <= (end); i++)
#define rep2(i1, begin1, end1, i2, begin2, end2) rep(i1, begin1, end1) rep(i2, begin2, end2)
#define repne(i, begin, end) for (register int i = (begin); i < (end); i++)
#define repne2(i1, begin1, end1, i2, begin2, end2) repne(i1, begin1, end1) repne(i2, begin2, end2)
int main()
{
#ifdef __DEBUG__
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
ios::sync_with_stdio(false); cin.tie(nullptr);
map<string,string> dict;
string word;
while(cin>>word && word!="#")
{
string norm=word;
transform(norm.begin(),norm.end(),norm.begin(),[](char ch){
return tolower(ch);
});
sort(norm.begin(),norm.end());
auto it=dict.find(norm);
if(it!=dict.end())it->second="#";
else dict[norm]=word;
}
vector<string> ans;
for(auto it:dict)
{
if(it.second!="#")ans.push_back(it.second);
}
sort(ans.begin(),ans.end());
for(auto it:ans)cout<<it<<endl;
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.