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 |
|---|---|---|---|---|---|---|---|
Java | UTF-8 | 3,793 | 2.15625 | 2 | [
"BSD-3-Clause"
] | permissive | // license-header java merge-point
/**
* This is only generated once! It will never be overwritten.
* You can (and have to!) safely modify it by hand.
*/
package com.logistics.entity.cost;
/**
* @see com.logistics.entity.cost.WlInsurance
*/
public class WlInsuranceDaoImpl
extends com.logistics.entity.cost.WlInsuranceDaoBase
{
/**
* @see com.logistics.entity.cost.WlInsuranceDao#toWlInsuranceVO(com.logistics.entity.cost.WlInsurance, com.logistics.entity.cost.WlInsuranceVO)
*/
public void toWlInsuranceVO(
com.logistics.entity.cost.WlInsurance source,
com.logistics.entity.cost.WlInsuranceVO target)
{
// @todo verify behavior of toWlInsuranceVO
super.toWlInsuranceVO(source, target);
// WARNING! No conversion for target.acceptDate (can't convert source.getAcceptDate():java.util.Date to java.util.Date
// WARNING! No conversion for target.startDate (can't convert source.getStartDate():java.util.Date to java.util.Date
// WARNING! No conversion for target.endDate (can't convert source.getEndDate():java.util.Date to java.util.Date
}
/**
* @see com.logistics.entity.cost.WlInsuranceDao#toWlInsuranceVO(com.logistics.entity.cost.WlInsurance)
*/
public com.logistics.entity.cost.WlInsuranceVO toWlInsuranceVO(final com.logistics.entity.cost.WlInsurance entity)
{
// @todo verify behavior of toWlInsuranceVO
return super.toWlInsuranceVO(entity);
}
/**
* Retrieves the entity object that is associated with the specified value object
* from the object store. If no such entity object exists in the object store,
* a new, blank entity is created
*/
private com.logistics.entity.cost.WlInsurance loadWlInsuranceFromWlInsuranceVO(com.logistics.entity.cost.WlInsuranceVO wlInsuranceVO)
{
// @todo implement loadWlInsuranceFromWlInsuranceVO
throw new java.lang.UnsupportedOperationException("com.logistics.entity.cost.loadWlInsuranceFromWlInsuranceVO(com.logistics.entity.cost.WlInsuranceVO) not yet implemented.");
/* A typical implementation looks like this:
com.logistics.entity.cost.WlInsurance wlInsurance = this.load(wlInsuranceVO.getId());
if (wlInsurance == null)
{
wlInsurance = com.logistics.entity.cost.WlInsurance.Factory.newInstance();
}
return wlInsurance;
*/
}
/**
* @see com.logistics.entity.cost.WlInsuranceDao#wlInsuranceVOToEntity(com.logistics.entity.cost.WlInsuranceVO)
*/
public com.logistics.entity.cost.WlInsurance wlInsuranceVOToEntity(com.logistics.entity.cost.WlInsuranceVO wlInsuranceVO)
{
// @todo verify behavior of wlInsuranceVOToEntity
com.logistics.entity.cost.WlInsurance entity = this.loadWlInsuranceFromWlInsuranceVO(wlInsuranceVO);
this.wlInsuranceVOToEntity(wlInsuranceVO, entity, true);
return entity;
}
/**
* @see com.logistics.entity.cost.WlInsuranceDao#wlInsuranceVOToEntity(com.logistics.entity.cost.WlInsuranceVO, com.logistics.entity.cost.WlInsurance)
*/
public void wlInsuranceVOToEntity(
com.logistics.entity.cost.WlInsuranceVO source,
com.logistics.entity.cost.WlInsurance target,
boolean copyIfNull)
{
// @todo verify behavior of wlInsuranceVOToEntity
super.wlInsuranceVOToEntity(source, target, copyIfNull);
// No conversion for target.acceptDate (can't convert source.getAcceptDate():java.util.Date to java.util.Date
// No conversion for target.startDate (can't convert source.getStartDate():java.util.Date to java.util.Date
// No conversion for target.endDate (can't convert source.getEndDate():java.util.Date to java.util.Date
}
} |
JavaScript | UTF-8 | 1,164 | 3.3125 | 3 | [] | no_license | // 并不算常用的技术
// 待渲染函数
const data = [];
// 数据项的计算函数
const datum = x => {
return x * x * 10;
};
const newData = () => {
data.push(datum);
return data;
};
function handle_bind_function_data() {
// 定时更改数据并重新渲染
setInterval(() => {
renderData();
}, 1500);
// 初始渲染
renderData();
}
/**
* 渲染可视化数据
*/
function renderData() {
const divs = d3.select('#container')
.selectAll('div') // d3 可以预选择元素,这时候页面并没这些元素, 可以理解为 声明应该有这些元素
.data(newData); // data选中已经进入可视化状态的数据
divs.enter() // enter选中了未进入可视化状态
.append('div')
.style('width', (d, i) => {
return d(i) + 'px';
})
.style('background-color', '#b37feb')
.style('color', 'white')
.style('border', '1px solid #531dab')
.style('border-radius', '4px')
.style('margin', '10px')
.style('padding', '0px 12px')
.text((d, i) => {
return d(i);
})
// exit
divs.exit()
.remove(); // remove()函数删除那些需要退出的元素
} |
Python | UTF-8 | 3,973 | 3.671875 | 4 | [] | no_license | ###
# Imports
###
# Standard Python library
import random
import types
###
# Agent Class.
# Attributes :
# - id : permits the identification of every agents
# - world_name : the name of the world which contains the agent
###
class Agent():
###
# Agent constructor
# - number : permits the identification of every agents
# - world_name : the name of the world which contains the agent
###
def __init__(self, number, world_name):
self.id = number
self.world_name = world_name
###
# Add a new attribute to the class
# - attribute_name : name of the new attribute
# - attribute_value : new value of the attribute
###
def own(cls, attribute_name, attribute_value=0) :
if hasattr(cls, attribute_name) == False :
setattr(cls, attribute_name, attribute_value)
else :
print ("\"{0}\" is already an attribute of {1}".format(attribute_name, cls.__name__))
#Declaration as a class method
own = classmethod(own)
###
# Change the value of the class attribute in parameter
# - attribute_name : attribute to change
# - attribute_value : new value of the attribute
# - random : "random" if the value is a random number
###
def set(self, attribute_name, attribute_value, rand=""):
if hasattr(self, attribute_name) == True :
if rand == "" :
setattr(self, attribute_name, attribute_value)
else :
setattr(self, attribute_name, int(attribute_value * random.random()))
else :
print("\"{0}\" is not an attribute of {1}".format(attribute_name, self.__class__.__name__))
###
# Permits to apply several methods to the agent
# - actions : list to put actions to perform.
# syntax : [("methodName",(parameter1,parameter2)), ("methodName2",(parameter1,parameter2))}
# example : [("set",("heading",10)), ("forward",(10))]
###
def execute_actions(self, actions):
for action in actions :
if action != None and action != ():
# If action case ("if", ("self.id == 1", [("forward",(1)), ("set",("heading", 2))]) )
if action[0].lower() == "if" :
if eval(action[1][0]) == True :
self.execute_actions(action[1][1])
else :
actionType = type(getattr(self.__class__, action[0]))
# If the action match a class method
if (hasattr(self.__class__, action[0]) == True) and (actionType == types.FunctionType or actionType == types.MethodType) :
method = getattr(self.__class__, action[0])
# If the function has more than one parameter, they are in a tuple. We have to unpack it to execute the method.
if type(action[1]) == tuple :
method(self, *action[1]) # * is the unpacking operator
else :
method(self, action[1])
else :
print ("\"{0}\" is not in the class \'{1}\'".format(action[0], self.__class__.__name__))
###
# Permits to apply several methods to the agent many times
# - repeat_number : how many times the method applies the actions on the agent
# - actions : list to put actions to perform.
# syntax : [("methodName",(parameter1,parameter2)), ("methodName2",(parameter1,parameter2))}
# example : [("set",("heading",10)), ("forward",(10))]
###
def repeat(self, repeat_number, actions={}):
for _ in range(0, repeat_number) :
self.execute_actions(actions)
|
C++ | UTF-8 | 2,116 | 3.859375 | 4 | [] | no_license | /*
* File: main.cpp
* Author: Branden Hitt
* Created on March 25, 2015, 10:10 AM
* Purpose: use a structure to store data
*/
//System Libraries
#include <iostream>//I/O standard
#include <iomanip>//format
using namespace std;
//User Libraries
#include "CorpData.h"
//Global Constants
//Function Prototypes
void filCorp(CorpData &);
void display(CorpData &);
//Execution Begins Here!
int main(int argc, char** argv) {
//Declare Variables
CorpData com1;
CorpData com2;
CorpData com3;
CorpData com4;
//Fill the structures
cout<<"Company Division 1 Input"<<endl;
filCorp(com1);
cout<<"Company Division 2 Input"<<endl;
filCorp(com2);
cout<<"Company Division 3 Input"<<endl;
filCorp(com3);
cout<<"Company Division 4 Input"<<endl;
filCorp(com4);
//Output
cout<<"***********************"<<endl;
cout<<endl;
display(com1);
display(com2);
display(com3);
display(com4);
//exit stage right
return 0;
}
//fill corpdata
void filCorp(CorpData &p){
cout<<"What is the division name?:"<<endl;
cin>>p.name;
do{
cout<<"What were the sales for the first quarter?:"<<endl;
cin>>p.qt1;
if(p.qt1<0)cout<<"Invalid Input"<<endl;
}while(p.qt1<0);
do{
cout<<"What were the sales for the second quarter?:"<<endl;
cin>>p.qt2;
if(p.qt2<0)cout<<"Invalid Input"<<endl;
}while(p.qt2<0);
do{
cout<<"What were the sales for the third quarter?:"<<endl;
cin>>p.qt3;
if(p.qt3<0)cout<<"Invalid Input"<<endl;
}while(p.qt3<0);
do{
cout<<"What were the sales for the fourth quarter?:"<<endl;
cin>>p.qt4;
if(p.qt4<0)cout<<"Invalid Input"<<endl;
}while(p.qt4<0);
p.annual=(p.qt1+p.qt2+p.qt3+p.qt4);
p.average=(p.annual)/4;
cin.ignore();
cout<<endl;
}
//display the structure
void display(CorpData &p){
cout<<fixed<<setprecision(2)<<showpoint;
cout<<"Division: "<<p.name<<endl;
cout<<"Annual sales: $"<<p.annual<<endl;
cout<<"Average Quarterly Sales: $"<<p.average<<endl;
cout<<endl;
} |
Python | UTF-8 | 5,851 | 2.90625 | 3 | [] | no_license | __author__="Nikhil Rayaprolu"
__version__ = "1.0.0"
__maintainer__ = "Nikhil Rayaprolu"
__email__ = "nikhil.rayaprolu@students.iiit.ac.in"
__status__ = "Development"
import pygame,random
import time
class Block(object):
"""block class for the tetris game"""
def __init__(self):
super(Block, self).__init__()
self.MOVESIDEWAYSFREQ = 0.15
self.MOVEDOWNFREQ = 0.1
self.BlockShape()
def moveLeft(self):
self.fallingPiece['x'] -=1
self.movingLeft = True
self.movingRight = False
self.lastMoveSidewaysTime = time.time()
def moveRight(self):
self.fallingPiece['x'] +=1
self.movingRight=True
self.movingLeft = False
self.lastMoveSidewaysTime= time.time()
def Rotate(self, r):
self.fallingPiece['rotation']=(self.fallingPiece['rotation']+r)% len(self.PIECES[self.fallingPiece['shape']])
def BlockShape(self):
self.S_SHAPE_TEMPLATE = [['.....',
'.....',
'..OO.',
'.OO..',
'.....'],
['.....',
'..O..',
'..OO.',
'...O.',
'.....']]
self.Z_SHAPE_TEMPLATE = [['.....',
'.....',
'.OO..',
'..OO.',
'.....'],
['.....',
'..O..',
'.OO..',
'.O...',
'.....']]
self.I_SHAPE_TEMPLATE = [['..O..',
'..O..',
'..O..',
'..O..',
'.....'],
['.....',
'.....',
'OOOO.',
'.....',
'.....']]
self.O_SHAPE_TEMPLATE = [['.....',
'.....',
'.OO..',
'.OO..',
'.....']]
self.J_SHAPE_TEMPLATE = [['.....',
'.O...',
'.OOO.',
'.....',
'.....'],
['.....',
'..OO.',
'..O..',
'..O..',
'.....'],
['.....',
'.....',
'.OOO.',
'...O.',
'.....'],
['.....',
'..O..',
'..O..',
'.OO..',
'.....']]
self.L_SHAPE_TEMPLATE = [['.....',
'...O.',
'.OOO.',
'.....',
'.....'],
['.....',
'..O..',
'..O..',
'..OO.',
'.....'],
['.....',
'.....',
'.OOO.',
'.O...',
'.....'],
['.....',
'.OO..',
'..O..',
'..O..',
'.....']]
self.T_SHAPE_TEMPLATE = [['.....',
'..O..',
'.OOO.',
'.....',
'.....'],
['.....',
'..O..',
'..OO.',
'..O..',
'.....'],
['.....',
'.....',
'.OOO.',
'..O..',
'.....'],
['.....',
'..O..',
'.OO..',
'..O..',
'.....']]
self.PIECES = {'S': self.S_SHAPE_TEMPLATE,
'Z': self.Z_SHAPE_TEMPLATE,
'J': self.J_SHAPE_TEMPLATE,
'L': self.L_SHAPE_TEMPLATE,
'I': self.I_SHAPE_TEMPLATE,
'O': self.O_SHAPE_TEMPLATE,
'T': self.T_SHAPE_TEMPLATE}
def getNewPiece(self):
# return a random new piece in a random rotation and color
self.shape = random.choice(list(self.PIECES.keys()))
newPiece = {'shape': self.shape,
'rotation': random.randint(0, len(self.PIECES[self.shape]) - 1),
'x': int(self.BOARDWIDTH / 2) - int(self.TEMPLATEWIDTH / 2),
'y': -2, # start it above the board (i.e. less than 0)
'color': random.randint(0, len(self.COLORS)-1)}
return newPiece
def isOnBoard(self,x, y):
return x >= 0 and x < self.BOARDWIDTH and y < self.BOARDHEIGHT
def drawPiece(self,piece, pixelx=None, pixely=None,PIECES={}):
shapeToDraw = self.PIECES[piece['shape']][piece['rotation']]
if pixelx == None and pixely == None:
# if pixelx & pixely hasn't been specified, use the location stored in the piece data structure
pixelx, pixely = self.convertToPixelCoords(piece['x'], piece['y'])
# draw each of the boxes that make up the piece
for x in range(self.TEMPLATEWIDTH):
for y in range(self.TEMPLATEHEIGHT):
if shapeToDraw[y][x] != self.BLANK:
self.drawBox(None, None, piece['color'], pixelx + (x * self.BOXSIZE), pixely + (y * self.BOXSIZE))
def drawNextPiece(self,piece,PIECES):
# draw the "next" text
nextSurf = self.BASICFONT.render('Next:', True, self.TEXTCOLOR)
nextRect = nextSurf.get_rect()
nextRect.topleft = (self.WINDOWWIDTH - 120, 80)
self.DISPLAYSURF.blit(nextSurf, nextRect)
# draw the "next" piece
self.drawPiece(piece, pixelx=self.WINDOWWIDTH-120, pixely=100,PIECES={})
|
Python | UTF-8 | 5,849 | 2.640625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# uTorrent cleanup script.
# Moves downloads to the proper dir, based on their label.
# Useful after assigning new labels to torrents.
#
# ** SHUT DOWN uTorrent BEFORE RUNNING **
#
# Original on: https://github.com/m000/cliutils
#
from __future__ import print_function
import os
import os.path
import sys
import shutil
import random
import tempfile
from pprint import pprint
import argparse
MIN_SAVEPATH_LENGTH = 3
SAVEPATH_SAMPLE_SIZE = 10
SAVEPATH_SAMPLE_RETRIES = 5
HR_LENGTH = 70
try:
import bencode
except ImportError:
print("Please install the bencode python module. E.g.: sudo pip install bencode", file=sys.stderr)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='uTorrent tidy script. Moves completed files to directories matching their label. Writes a new resume data file.')
parser.add_argument("-n", "--dry-run",
action="store_true", dest="dryrun", default=False,
help="only print the actions to be performed"
)
parser.add_argument("-p", "--save-path",
action="store", dest="savepath", default=None,
help="manually set the torrent save path"
)
parser.add_argument("--xfs",
action="store_true", dest="xfs", default=False,
help="allow moving files across filesystems"
)
parser.add_argument('resumedat_in', help='input utorrent resume.dat file')
parser.add_argument('resumedat_out', help='output utorrent resume.dat file')
args = parser.parse_args()
################################################
# Read resume data.
################################################
with open(args.resumedat_in, 'rb') as dat_in:
resume_dat = bencode.bdecode(dat_in.read())
print(HR_LENGTH*"*")
print("Dry Run: %s, Move Across FS: %s, Manual Savepath: %s" % (args.dryrun, args.xfs, args.savepath))
print(HR_LENGTH*"*")
################################################
# Calculate the save path for the data.
################################################
if args.savepath:
savepath = args.savepath
else:
allpaths = [ resume_dat[t]['path'] for t in resume_dat
if t.endswith('.torrent') and os.path.exists(resume_dat[t]['path'])
]
savepath = os.path.commonprefix(allpaths)
if (len(savepath) < MIN_SAVEPATH_LENGTH):
# Failed to calculate savepath from all used paths. Try sampling.
for i in xrange(SAVEPATH_SAMPLE_RETRIES):
savepath = os.path.commonprefix( random.sample(allpaths, min(SAVEPATH_SAMPLE_SIZE, len(allpaths))) )
if (len(savepath) >= MIN_SAVEPATH_LENGTH):
break
if (len(savepath) < MIN_SAVEPATH_LENGTH):
print("Could not calculate a savepath using sampling.", file=sys.stderr)
print("You may want to retry in a few secs, or manually set the savepath.", file=sys.stderr)
sys.exit(1)
print("Savepath is: %s." % (savepath))
################################################
# Check what has to be done.
################################################
actions = {}
for torrent, metadata in resume_dat.iteritems():
# not torrent
if not torrent.endswith('.torrent'):
print("Skipping '%s'. Not a torrent." % (torrent))
continue
if 'label' not in metadata:
print("Skipping '%s'. No label." % (torrent))
continue
if len(metadata['labels']) > 1:
# This isn't possible AFAIK. Add a check nevertheless.
print("Too many labels for '%s'. Don't know how to handle them." % (torrent), file=sys.stderr)
sys.exit(1)
if metadata['completed_on'] == 0:
print("Skipping '%s'. Not completed." % (torrent))
continue
if not os.path.exists(metadata['path']):
print("Skipping '%s'. Path does not exist." % (torrent))
continue
on_same_fs = lambda p1, p2: os.stat(p2).st_dev == os.stat(p2).st_dev
if not args.xfs and not on_same_fs(metadata['path'], savepath):
print("Skipping '%s'. Not on the same filesystem with savepath." % (torrent))
continue
p = metadata['path']
l = metadata['label']
d_from = os.path.dirname(p)
d_to = os.path.join(savepath, l)
p_to = os.path.join(d_to, os.path.basename(p))
if d_from == d_to:
print("Skipping '%s'. Already in the correct directory." % (torrent))
continue
# everything ok, add an action
actions[torrent] = (p, p_to, d_to)
################################################
# Execute actions.
################################################
print(HR_LENGTH*"-")
try:
for torrent in actions:
path_orig, path_dest, dir_dest = actions[torrent]
# Remove any empty path components of path_dest.
try:
os.removedirs(path_dest)
except OSError:
pass
# Create dir_dest.
try:
os.makedirs(dir_dest, mode=0o755)
print("mkdir -p '%s'" % (dir_dest))
except OSError:
pass
# Do the moving.
if not args.dryrun:
shutil.move(path_orig, dir_dest)
resume_dat[torrent]['path'] = path_dest
print("mv '%s' '%s'" % (path_orig, dir_dest))
print(HR_LENGTH*"-")
finally:
################################################
# Write updated resume data.
################################################
with open(args.resumedat_out,'wb+') as dat_out:
dat_out.write(bencode.bencode(resume_dat))
|
C++ | UTF-8 | 1,065 | 2.796875 | 3 | [
"MIT"
] | permissive | #include <unordered_map>
#include <map>
#include <cmath>
#include <string>
#include <array>
#include <Rcpp.h>
// Enable C++11 via this plugin (Rcpp 0.10.3 or later)
// [[Rcpp::plugins(cpp11)]]
// [[Rcpp::export]]
void hello()
{
// std::array< double , 2 > a = {{1e4,2}};
// std::array< std::array< double , 3 > , 2 > b = {{{1,2,3},
// {4,5,6}}};
using namespace std;
std::map< double, std::string > event_queue;
std::string output;
event_queue[1.1] = "event1";
event_queue[2.2] = "event2";
output = event_queue[1.1]; // works
std::cout << output << std::endl;
output = event_queue.begin()->second; // works
std::cout << output << std::endl;
if (event_queue.begin()->second == "event1"){ // works
output = "true";
event_queue.erase(event_queue.begin());
} else {
output = "false";
}
std::cout << output << std::endl;
if (event_queue.begin()->second == "event2"){ // works
output = "true";
} else {
output = "false";
}
std::cout << output << std::endl;
}
/*** R
# This is R code
hello()
*/
|
Java | UTF-8 | 2,800 | 1.976563 | 2 | [] | no_license | package com.jiudian.p2p.front.service.financing;
import java.math.BigDecimal;
import com.jiudian.framework.service.Service;
import com.jiudian.framework.service.query.Paging;
import com.jiudian.framework.service.query.PagingResult;
import com.jiudian.p2p.common.enums.IsPass;
import com.jiudian.p2p.front.service.financing.entity.CreditInfo;
import com.jiudian.p2p.front.service.financing.entity.InvestStatistics;
import com.jiudian.p2p.front.service.financing.entity.Rewards;
import com.jiudian.p2p.front.service.financing.entity.TenderRecord;
import com.jiudian.p2p.front.service.financing.query.InvestQuery;
/**
* 散标投资
*
*/
public interface InvestManage extends Service {
/**
* 获取散标投资列表
*
* @param query
* @param paging
* @return
* @throws Throwable
*/
public abstract PagingResult<CreditInfo> search(InvestQuery query,
Paging paging) throws Throwable;
public abstract CreditInfo[] search(int line) throws Throwable;
public abstract int searchcount() throws Throwable;
/**
* 获取投资统计信息.
*
* @return {@link InvestStatistics}
* @throws Throwable
*/
public abstract InvestStatistics getStatistics() throws Throwable;
/**
* 获取散标详细信息.
*
* @param id
* @return {@link CreditInfo}
* @throws Throwable
*/
public abstract CreditInfo get(int id) throws Throwable;
/**
* 查询机构名称
* @param jkbId
* @return
* @throws Throwable
*/
public String getJgName(int jkbId)throws Throwable;
/**
* 获取奖励信息
* @param id
* @return
* @throws Throwable
*/
public abstract Rewards getRewards(int id) throws Throwable;
/**
* 获取投标分数
*
* @param id
* @return {@link int}
* @throws Throwable
*/
public abstract BigDecimal getTbcont(int id) throws Throwable;
/**
* 获取奖励用户列表
*
* @param id
* @return {@link TenderRecord[]}
* @throws Throwable
*/
public abstract TenderRecord[] getJllb(int id) throws Throwable;
/**
* 网贷之家接口,获取当前正在进行投标中的标信息。
* @param paging
* @return
* @throws Throwable
*/
public abstract PagingResult<CreditInfo> getNowProjects(Paging paging) throws Throwable;
/**
* 网贷之家接口,获取所有在’date’这一天成功借款(即满标时间为date)的标。date格式: ‘2013-09-01’
* @param date
* @param paging
* @return
* @throws Throwable
*/
public abstract PagingResult<CreditInfo> getProjectByDate(String date,
Paging paging)throws Throwable;
/**
* 判断是否开通金账户
* @return
* @throws Throwable
*/
public abstract IsPass sfktJzh() throws Throwable;
}
|
Java | UTF-8 | 2,670 | 2.40625 | 2 | [] | no_license | package com.longrise.android.compattoast;
import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
/**
* Created by godliness on 2020/10/16.
*
* @author godliness
*/
public final class Toast implements IToast {
private final TH mTh;
private final IToastView mView;
private int mDuration;
public static IToast makeToast(String title, int duration) {
return new Toast().setText(title).setDuration(duration);
}
@Override
public IToast setText(String text) {
mView.setText(text);
return this;
}
@Override
public IToast setDuration(int duration) {
this.mDuration = duration;
return this;
}
@Override
public IToast setView(View childView) {
mView.setView(childView);
return this;
}
@Override
public View getView() {
return mView.getView();
}
@Override
public IToast setGravity(int gravity, int xOffset, int yOffset) {
mView.setGravity(gravity, xOffset, yOffset);
return this;
}
public void show(Activity binding) {
mTh.show(binding, mDuration);
}
public Toast() {
this.mView = new ToastView();
this.mTh = new TH(mView);
}
@Override
public void cancel() {
this.mTh.cancel();
}
static class TH extends Handler {
private static final int HIDE = 0;
private static final int SHOW = 1;
private final IToastView mView;
TH(IToastView toastView) {
this.mView = toastView;
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SHOW:
mView.show((ViewGroup) msg.obj);
if (msg.arg1 != -1) {
removeMessages(HIDE);
sendEmptyMessageDelayed(HIDE, msg.arg1);
}
break;
case HIDE:
mView.cancel();
break;
default:
break;
}
}
void show(Activity binding, int duration) {
final Message msg = obtainMessage();
msg.obj = (ViewGroup) binding.findViewById(Window.ID_ANDROID_CONTENT);
msg.arg1 = duration;
msg.what = SHOW;
msg.sendToTarget();
}
void cancel() {
removeMessages(HIDE);
final Message hide = obtainMessage(HIDE);
hide.sendToTarget();
}
}
}
|
Python | UTF-8 | 2,201 | 2.71875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 16 16:47:59 2019
@author: Sanjeev Narayanan
"""
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 21 11:37:51 2019
@author: Sanjeev Narayanan
"""
import os
import re
import string
from nltk.corpus import stopwords
from stop_words import get_stop_words
import pandas as pd
### Add your path here #####
path = "C:/Users/Sanjeev Narayanan/Desktop/AJ Projects/Thesis Stuff/Task 5 - NLP/Main/outs/"
#############################
filenames = []
all_files = []
title = []
for i in os.listdir(path):
filenames.append(path + '%s' %i)
with open(path+'%s' %i,'r',encoding='utf-8') as myfile:
data = myfile.read()
data = re.sub(r'([^\s\w]|_)+', '', data)
data = "".join(filter(lambda char: char in string.printable, data))
all_files.append(data)
title.append(i.replace('-',' ')[5:].title().split('.')[0])
from gensim.models.doc2vec import Doc2Vec, TaggedDocument
from nltk.tokenize import word_tokenize
tagged_data = [TaggedDocument(words=word_tokenize(_d.lower()), tags=[str(i)]) for i, _d in enumerate(all_files)]
max_epochs = 100
vec_size = 50
alpha = 0.025
model = Doc2Vec(size=vec_size,alpha=alpha, min_alpha=0.00025,min_count=1,dm =1)
model.build_vocab(tagged_data)
for epoch in range(max_epochs):
print('iteration {0}'.format(epoch))
model.train(tagged_data,total_examples=model.corpus_count,epochs=model.iter)
# decrease the learning rate
model.alpha -= 0.0002
# fix the learning rate, no decay
model.min_alpha = model.alpha
model.save("d2v.model")
print("Model Saved")
path1 = "C:/Users/Sanjeev Narayanan/Desktop/AJ Projects/Thesis Stuff/Task 7 - D2V/"
model = Doc2Vec.load(path1+"d2v.model")
str1 = "Modeling the distribution of natural images is challenging, partly because of strong statistical dependencies which can extend over hundreds of pixels. Re-current neural networks have been successful in capturing "
test_data = word_tokenize(str1.lower())
v1 = model.infer_vector(test_data, steps=20, alpha=0.025)
similar_doc = model.docvecs.most_similar(positive=[v1])
out_docs = []
for i in similar_doc:
out_docs.append(title[int(i[0])])
|
PHP | UTF-8 | 635 | 2.84375 | 3 | [] | no_license | <?php
include('db.conf.php'); //include the paremter of database
try {
$db = new PDO("mysql:host=$host_name", $db_user, $db_password); //access sql server with PDO
$db->query("SET character_set_server = 'utf8'"); //set the ecncoding type of database
$db->query("CREATE DATABASE IF NOT EXISTS $db_name"); //create the database if it don't exist
$db->query("USE $db_name"); //select database
} catch (PDOException $e) { //when ther error occur, the thread will stop and jump here to stop error thread
echo $e->getMessage(); //echo the error message about mysql database
} |
JavaScript | UTF-8 | 3,863 | 2.8125 | 3 | [] | no_license |
GameEngine.Classes.DeepFirstSearchFieldSolver = Class.create(GameEngine.Classes.MazeSolver.prototype, {
init: function() {
this.sup('init');
},
solve: function( cell_from, cell_to ) {
GameEngine.maze.unvisited();
$(GameEngine.maze.data).each(function() {
$(this).each(function() {
if (this.hasFeature('exitpath')) this.removeFeature('exitpath');
this.distance = 100000000;
});
});
cell_from.distance = 0;
this.setDistancesFrom( cell_from );
var path = new Array();
this.gatherPathFrom( cell_to, path );
$(path).each(function() {
if (!this.hasFeature('player') && !this.hasFeature('exit')) this.addFeature('exitpath');
});
$('html').trigger('GE.redraw', [ cell_from ]);
},
setDistancesFrom: function( cur_pos ) {
/* in any case after this we went through this cell */
cur_pos.visited = true;
/* if we have no non-visited cell arround, considering we're not next to the exit what's the point of life ? */
var available = GameEngine.maze.availableDirectionFrom(cur_pos, true);
if (available.length == 0) return false;
/* lets check if we have a shorter path now for all those surrounding cells */
for (var i = 0; i < available.length; i++) {
if (available[i].kind == 'field') {
if (available[i].distance > cur_pos.distance + 1) {
available[i].distance = cur_pos.distance + 1;
}
}
}
/* visit all our neighbours */
for (var i = 0; i < available.length; i++) {
/* check it again in case a path went through this one */
if (!available[i].visited && (available[i].kind == 'field')) {
/* and start over again */
this.setDistancesFrom( available[i] );
}
}
},
gatherPathFrom: function( cur_pos, path ) {
/* ok so basically we want to go to cur_pos, so it's in the path */
path.push(cur_pos);
/* Dammit ... it's the start ! */
if (cur_pos.distance == 0) return;
/* now we search for the shortest way */
var cell = new GameEngine.Classes.Cell();
cell.distance = 100000000;
var surrounding = GameEngine.maze.surroundingCells( cur_pos );
$.each(surrounding, function() {
if (this.kind == 'field') {
if (this.distance < cell.distance) cell = this;
}
});
/* apparently no connections */
if (cell.distance == 10000000) return;
this.gatherPathFrom( cell, path );
}
});
/* new feature to indicate the path */
GameEngine.CONST.CELL_FEATURE_EXITPATH = 'exitpath';
GameEngine.Classes.CellFeatureExitPath = Class.create(GameEngine.Classes.CellFeature.prototype, {
init: function() {
this.name = GameEngine.CONST.CELL_FEATURE_EXITPATH;
this.kind = GameEngine.CONST.CELL_FIELD;
this.count = 0;
this.sup('init');
},
hit: function( cell, direction ) {
cell.removeFeature(this.name);
return false;
},
draw: function( cell, celldim ) {
GameEngine.disp.drawSquare( cell, celldim, '#F00' );
}
});
GameEngine.availableFeatures.push(new GameEngine.Classes.CellFeatureExitPath());
GameEngine.mazeSolver = new GameEngine.Classes.DeepFirstSearchFieldSolver();
GameEngine.findExit = function() {
var player = GameEngine.maze.getCellsByFeature('player')[0];
var exit = GameEngine.maze.getCellsByFeature('exit')[0];
return GameEngine.mazeSolver.solve( player , exit );
}; |
Java | UTF-8 | 867 | 2.296875 | 2 | [
"Apache-2.0"
] | permissive | package com.nimbusframework.nimbusexampes.restapi;
import static org.junit.jupiter.api.Assertions.*;
import com.nimbusframework.nimbuscore.annotations.function.HttpMethod;
import com.nimbusframework.nimbuslocal.LocalNimbusDeployment;
import com.nimbusframework.nimbuslocal.deployment.http.HttpRequest;
import org.junit.jupiter.api.Test;
class GetApiTest {
@Test
public void getApiFetchesItemFromStore() {
LocalNimbusDeployment localNimbusDeployment = LocalNimbusDeployment.getNewInstance("com.nimbusframework.nimbusexampes.restapi");
Person person = new Person("test", 24);
localNimbusDeployment.getDocumentStore(Person.class).put(person);
HttpRequest httpRequest = new HttpRequest("person/test", HttpMethod.GET);
Person getPerson = (Person) localNimbusDeployment.sendHttpRequest(httpRequest);
assertEquals(person, getPerson);
}
} |
C# | UTF-8 | 828 | 2.53125 | 3 | [
"MIT"
] | permissive | using Laurus.Spex;
using Laurus.Spex.Sample;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
RunTest<AtmSample>("AnotherOne");
//RunTest(new AtmSample(), "AnotherOne");
Console.ReadKey();
}
public static void RunTest<T>(string name) where T : IFeature
{
var inst = Activator.CreateInstance<T>();
var runtime = RuntimeFactory.Initialize().WithLogger(new RuntimeLog()).Create();
runtime.Run(inst, "AnotherOne");
}
public static void RunTest(IFeature feature, string name)
{
var runtime = RuntimeFactory.Initialize().WithLogger(new ConsoleLog()).Create();
runtime.Run(feature, name);
}
}
}
|
Go | UTF-8 | 4,614 | 2.71875 | 3 | [
"MIT"
] | permissive | package firmafon
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"reflect"
"strings"
"github.com/google/go-querystring/query"
)
const (
apiVersion = "2"
defaultBaseURL = "https://app.firmafon.dk/api/v" + apiVersion + "/"
mediaTypeJSON = "application/json"
)
// A Client manages communication with the Firmafon API.
type Client struct {
AccessToken string
client *http.Client
BaseURL *url.URL
common service
// Services used for talking to different parts of the Firmafon API
Employees *EmployeesService
Calls *CallsService
}
type service struct {
client *Client
}
type CallsListOptions struct {
Endpoint string `url:"endpoint"`
Direction string `url:"direction"`
Status string `url:"status"`
Number string `url:"number"`
Limit string `url:"limit"`
StartedAtGtOrEq string `url:"started_at_gt_or_eq"`
StartedAtLtOrEq string `url:"started_at_lt_or_eq"`
EndedAtGtOrEq string `url:"ended_at_gt_or_eq"`
EndedAtLtOrEq string `url:"ended_at_lt_or_eq"`
}
type Response struct {
*http.Response
}
type ErrorResponse struct {
Response *http.Response
Status string `json:"status"` // error message returned from api
Message string `json:"message"` // error message returned from api
}
type AuthError ErrorResponse
func (r *AuthError) Error() string { return (*ErrorResponse)(r).Error() }
func (r *ErrorResponse) Error() string {
return fmt.Sprintf("%v %v: %d %v",
r.Response.Request.Method, sanitizeURL(r.Response.Request.URL),
r.Response.StatusCode, r.Message)
}
func NewClient(token string) *Client {
httpClient := http.DefaultClient
baseURL, _ := url.Parse(defaultBaseURL)
c := &Client{client: httpClient, BaseURL: baseURL, AccessToken: token}
c.common.client = c
c.Employees = (*EmployeesService)(&c.common)
callSrv := &CallsService{
service: &c.common,
Endpoint: "calls",
}
c.Calls = callSrv
return c
}
// addOptions adds the parameters in opt as URL query parameters to s. opt
// must be a struct whose fields may contain "url" tags.
func addOptions(s string, opt interface{}) (string, error) {
v := reflect.ValueOf(opt)
if v.Kind() == reflect.Ptr && v.IsNil() {
return s, nil
}
u, err := url.Parse(s)
if err != nil {
return s, err
}
qs, err := query.Values(opt)
if err != nil {
return s, err
}
u.RawQuery = qs.Encode()
return u.String(), nil
}
func (c *Client) Do(req *http.Request, v interface{}) (*Response, error) {
resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
response := newResponse(resp)
err = CheckResponse(resp)
if err != nil {
return response, err
}
defer func() {
resp.Body.Close()
}()
if v != nil {
if w, ok := v.(io.Writer); ok {
_, err = io.Copy(w, resp.Body)
if err != nil {
return nil, err
}
} else {
err = json.NewDecoder(resp.Body).Decode(v)
if err == io.EOF {
err = nil // ignore EOF errors caused by empty response body
}
}
}
return response, err
}
func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error) {
if !strings.HasSuffix(c.BaseURL.Path, "/") {
return nil, fmt.Errorf("BaseURL must have a trailing slash, but %q does not", c.BaseURL)
}
u, err := c.BaseURL.Parse(urlStr)
if err != nil {
return nil, err
}
var buf io.ReadWriter
if body != nil {
buf = new(bytes.Buffer)
enc := json.NewEncoder(buf)
enc.SetEscapeHTML(false)
err := enc.Encode(body)
if err != nil {
return nil, err
}
}
req, err := http.NewRequest(method, u.String(), buf)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.AccessToken))
req.Header.Set("Accept", "application/json")
if body != nil {
req.Header.Set("Content-Type", mediaTypeJSON)
}
req.Header.Set("Accept", mediaTypeJSON)
return req, nil
}
func CheckResponse(r *http.Response) error {
if c := r.StatusCode; 200 <= c && c <= 299 {
return nil
}
errorResponse := &ErrorResponse{Response: r}
if r.StatusCode == 401 {
data, err := ioutil.ReadAll(r.Body)
if err == nil && data != nil {
err := json.Unmarshal(data, errorResponse)
if err != nil {
return err
}
}
return (*AuthError)(errorResponse)
}
return errorResponse
}
func newResponse(r *http.Response) *Response {
response := &Response{Response: r}
return response
}
func sanitizeURL(uri *url.URL) *url.URL {
if uri == nil {
return nil
}
params := uri.Query()
if len(params.Get("access_token")) > 0 {
params.Set("access_token", "REDACTED")
uri.RawQuery = params.Encode()
}
return uri
}
|
Java | UTF-8 | 13,286 | 1.609375 | 2 | [] | no_license | /*******************************************************************************
* Copyright (c) 2013 SCI Institute, University of Utah.
* All rights reserved.
*
* License for the specific language governing rights and limitations under Permission
* is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions: The above copyright notice
* and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
* A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* Contributors:
* Yarden Livnat
* Kristi Potter
*******************************************************************************/
package edu.utah.sci.cyclist.core.ui.panels;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import javafx.application.Platform;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.Side;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.SnapshotParameters;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.control.TextField;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import edu.utah.sci.cyclist.core.event.dnd.DnD;
import edu.utah.sci.cyclist.core.model.Simulation;
import edu.utah.sci.cyclist.core.util.AwesomeIcon;
import edu.utah.sci.cyclist.core.util.GlyphRegistry;
public class SimulationsPanel extends TitledPanel {
public static final String ID = "simulations-panel";
public static final String TITLE = "Simulations";
public static final String SELECTED_STYLE = "-fx-background-color: #99ccff";
public static final String UNSELECTED_STYLE = "-fx-background-color: #f0f0f0";
public static final long ALIAS_EDIT_WAIT_TIME = 1000;
private ContextMenu _menu = new ContextMenu();
private Timer _timer = null;
VBox _vbox = null;
Boolean _entryEdit = false;
private List<Entry> _entries;
private ObservableList<Simulation> _items;
private ObjectProperty<Simulation> _simulationProperty = new SimpleObjectProperty<>();
private Entry _selected = null;
private ObjectProperty<Simulation> _editSimulationProperty = new SimpleObjectProperty<>();
private InvalidationListener _listener = new InvalidationListener() {
@Override
public void invalidated(Observable observable) {
resetContent();
}
};
public SimulationsPanel() {
super(TITLE, GlyphRegistry.get(AwesomeIcon.COGS));
setPrefSize(USE_COMPUTED_SIZE, USE_COMPUTED_SIZE);
createMenu();
}
// @Override
public void setTitle(String title) {
setTitle(title);
}
public void setItems(final ObservableList<Simulation> items) {
if (_items != items) {
if (_items != null) {
_items.removeListener(_listener);
}
items.addListener(_listener);
_items = items;
}
resetContent();
}
public ObjectProperty<Simulation> editSimulationProperty() {
return _editSimulationProperty;
}
public Simulation getEditSimulation() {
return _editSimulationProperty.get();
}
public void setEditSimulation(Simulation value) {
_editSimulationProperty.set(value);
}
/*
* In the first time of an "entry pressed" event, assign the event of pressing keyboard "esc" button to the Scene.
* If event has already been assigned - do nothing
* The event returns an entry which is in edit mode to its non-edit mode,
* and saves the new edited alias in the corresponding simulation.
*
*/
private void setKeyboardEvent(){
Scene scene = getScene();
if(scene.getOnKeyPressed() == null){
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
if (event.getCode() == KeyCode.ESCAPE || event.getCode() == KeyCode.ENTER) {
//Check If there is any entry in edit mode.
if(_entryEdit){
resetTimer();
List<Node> nodes = new ArrayList<Node>(_vbox.getChildren());
_vbox.getChildren().clear();
int index=0;
Entry entry = null;
for(Node node : nodes){
//For a node which has been edited - save the edited text and return to non-edit mode.
if (node.getClass() == TextField.class){
entry = updateEntry((TextField)node, index);
_vbox.getChildren().add(entry.title);
}else{
//Node which has not been edited - do nothing.
Label lbl = (Label)node;
_vbox.getChildren().add(lbl);
}
index++;
}
//Set edit mode to false.
_entryEdit=false;
//Let cyclicControler listener to know about the change.
if(entry != null){
setEditSimulation(entry.simulation);
}
}
}
}
});
}
}
/*
* Update an entry which has been edited with the new alias name.
*
* @param TextField txt - the text field which contains the edited text
* @param int index - the index of the entry to update.
* #return Entry - the updated entry.
*/
private Entry updateEntry(TextField txt, int index){
Entry entry = _entries.get(index);
entry.simulation.setAlias(txt.getText());
entry.title.setText(txt.getText());
return entry;
}
/*
* Resets the timer which is set on entry mouse-pressed event.
*
*/
private void resetTimer(){
if(_timer != null){
_timer.cancel();
_timer.purge();
_timer=null;
}
}
/*
* Changes a label entry to a textField entry so the text can be edited.
* @param - Node : the node to change from a non editable label to an editable textField.
*/
private void createEditableEntry(Node node){
//Remove the label from the entry
int index = _vbox.getChildren().indexOf(node);
_vbox.getChildren().remove(index);
//Create an editable text field with the same text as the label
Label lbl = (Label)node;
TextField txt = new TextField(lbl.getText());
txt.getStyleClass().add("simulation-text-entry");
txt.setPrefWidth(lbl.getWidth()*1.2);
_vbox.getChildren().add(index, txt);
}
private void resetContent() {
_vbox = (VBox) getContent();
_vbox.getChildren().clear();
if(_entries != null && _entries.size()>0){
unbindEntries();
}
_entries = new ArrayList<>();
if(_items != null && _items.size()>0){
for (Simulation simulation : _items) {
Entry entry = createEntry(simulation);
entry.title.textProperty().bindBidirectional(simulation.aliasProperty());
_entries.add(entry);
_vbox.getChildren().add(entry.title);
}
//If this is the first and only simulation in the panel - make it also the selected simulation.
if(_entries.size() == 1){
_simulationProperty.set(_items.get(0));
select(_entries.get(0));
}
}else{
//If the list has been reset - clean the last selection as well.
_simulationProperty.set(null);
}
}
private void unbindEntries(){
for(Entry entry: _entries){
entry.title.textProperty().unbind();
}
}
private void select(Entry entry) {
if (_selected != null) {
_selected.title.setStyle(UNSELECTED_STYLE);
}
_selected = entry;
_selected.title.setStyle(SELECTED_STYLE);
}
/**
* property is set each time a new simulation entry is selected.
*/
public ObjectProperty<Simulation> selectedItemProperty() {
return _simulationProperty;
}
/**
* Select a simulation entry by the code (instead of manually by the user).
* Mark the entry as selected and load the simulation tables.
* @param simulationId - the simulation to select.
*/
public void selectSimulation(String simulationId){
for(Entry entry : _entries){
if(entry.simulation.getSimulationId().toString().equals(simulationId)){
select(entry);
_simulationProperty.set(entry.simulation);
break;
}
}
}
private Entry createEntry(Simulation simulation) {
final Entry entry = new Entry();
entry.simulation = simulation;
entry.title = new Label(simulation.getAlias());
//When mouse pressed, start a timer, when timer expires- start a task to make the pressed entry editable.
entry.title.setOnMousePressed(new EventHandler<Event>(){
@Override
public void handle(Event event) {
handleEntryEditRequest(entry, ALIAS_EDIT_WAIT_TIME);
}
});
//If mouse released event is before the "mouse pressed" timer has expired -
//cancel the timer. So the timer task would not be activated.
entry.title.setOnMouseReleased(new EventHandler<Event>(){
@Override
public void handle(Event event) {
resetTimer();
}
});
entry.title.setOnMouseClicked(new EventHandler<Event>() {
@Override
public void handle(Event event) {
MouseEvent mouseEvent = (MouseEvent)event;
select(entry);
//Right click loads the "delete" simulation dialog box.
if( mouseEvent.getButton() == MouseButton.SECONDARY){
_menu.show(entry.title, Side.BOTTOM, 0, 0);
} else if( mouseEvent.getButton() == MouseButton.PRIMARY){
//Left click on the mouse - loads the simulation tables.
_simulationProperty.set(entry.simulation);
}
}
});
entry.title.setOnDragDetected(new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
resetTimer();
select(entry);
DnD.LocalClipboard clipboard = DnD.getInstance().createLocalClipboard();
clipboard.put(DnD.SIMULATION_FORMAT, Simulation.class, entry.simulation);
Dragboard db = entry.title.startDragAndDrop(TransferMode.COPY);
ClipboardContent content = new ClipboardContent();
content.put(DnD.SIMULATION_FORMAT, entry.title.getText());
SnapshotParameters snapParams = new SnapshotParameters();
snapParams.setFill(Color.TRANSPARENT);
content.putImage(entry.title.snapshot(snapParams, null));
db.setContent(content);
_simulationProperty.set(entry.simulation);
}
});
return entry;
}
/*
* Makes the specified entry in the panel editable.
* @param Entry entry - the entry to make editable.
* @param long timerWait - how much time to wait until making the entry editable
* (relevant when it is called from pressing on the entry)
*/
private void handleEntryEditRequest(Entry entry, long timerWait ){
if(!_entryEdit){
//Should be set here because need to be sure the Scene has already been created.
setKeyboardEvent();
_timer = new Timer();
_timer.schedule(
new java.util.TimerTask() {
@Override
public void run() {
//Should run later because cannot do javafx actions directly from a timer task.
Platform.runLater(new Runnable() {
@Override
public void run() {
_entryEdit = true;
for(Node node :_vbox.getChildren()){
Label lbl = (Label)node;
if(lbl.getText().equals(entry.title.getText())){
createEditableEntry(node);
break;
}
}
}
});
}
},
timerWait
);
}
}
public void removeSimulation(Entry entry) {
_items.remove(entry.simulation);
}
private void createMenu(){
MenuItem deleteSimulation = new MenuItem("Delete simulation");
deleteSimulation.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
removeSimulation(_selected);
setEditSimulation(new Simulation());
_selected = null;
}
});
MenuItem editSimulation = new MenuItem("Edit alias");
editSimulation.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
handleEntryEditRequest(_selected,0);
}
});
_menu.getItems().addAll(editSimulation, new SeparatorMenuItem(), deleteSimulation);
}
class Entry {
Label title;
Simulation simulation;
}
}
|
Markdown | UTF-8 | 5,439 | 2.921875 | 3 | [
"MIT"
] | permissive | # lemon-todaq-doc
Restfull Micro-Service to support general commerce above TodaQ block-chain technology.
# Objective
- Support general commerce payment based on [TodaQ API](https://todaqfinance.com/)
- Ready to deploy in AWS Cloud in 3 minutes.
- Provide a web based admin console for payment management.
- Agent module in nodejs, python for developer.
# Requirements

## 유저 (User)
- TYPE: `ACCOUNT`
- Master information about user(or company), which is copied via RDB.
- Encrypt TODAQ's Account Information like `<account-id>`. (Only `super` user can see).
- Can be synchronized with TODAQ Accounts.
- `total` has total amount of value of conins belonged to user.
1. `연결(link)`: Connect current user with TODAQ's Account (or create new one)
- `Account Type`: BIZ/INV
- `Account ID`: save the encrypted todaq's account-id into KMS.
1. `활성(activate)`: Change `active` state in TODAQ.
- `Active State`: ...
1. `동기화(sync)`: Synchronize information, and aggregate total value of coins.
- `Balance`: total balance of coins.
- `Sync Date`: timestamp of synchronization (including webhook callback).
1. `패스코드(passcode)`: Confirm the transaction per account/enterprise.
- `Digit Code`: 4~6 digits number.
* save in encrypted string by KMS
## 동전 (Coin)
- TYPE: `COIN`
- Like coins in real-world, it has value estimation as 10 KRW, 100 KRW
- Can be matched with TODAQ's `<file-type-id>` attribute => only possible to have hash-key.
- Only define the specifications (like 10KRW) about each coin.
1. `정의(define)`: define root/child type of coin. (role: `admin`)
- `file-type-id`: <null> for root. <id> for childs.
- `file-type`: `COIN`
- `initial-owner`: enterprise id (or bank of coin).
- `coin-code`: code like USD/SOM/KRW/... (inherit from root)
- `coin-name`: readable name. (inherit from root)
- `coin-note`: like 10/100/500/1000. (only for child)
- `hash-code`: = hash(code + intial-owner + name + note)
1. `발행(issue)`: Generate coins like exchange-bank in real world (but, enterprisor has ownership)
- `id`: same as `<file-id>`
- `file-type-id`: id of `COIN`.
- `file-type`: `COIN`
- `initial-owner`: enterprise id (or bank of coin).
- `coin-code`: code like USD/SOM/... (inherit from file-type-id)
- `coin-note`: note value (inherit from file-type-id)
- `issue-date`: <timestamp>
- `issue-reason`: ...
- `hash-code`: = hash(type-id + intial-owner + type + code + node + date)
1. `폐기(trash)`: Trash coins only by Owner.
- `Trash Account`: ...
1. `교환(exchange)`: Exchange between different conins with same value. (Use transaction api internally)
- `Exchange Rate`: 10 SOM = 10 KRW.
- `Exchange Cost`: as tax per exchange (or zero) to enterprise.
1. `전달(transfer)`: Transfer coins to other account w/ transaction.
- `Transfer Rate`: Y := X + a
- `Transfer Cost`: as tax per transfer. (or zero) to enterprise.
## 결제 (Payment)
- TYPE: `PAYMENT`
- Use coins to buy something. (and get some changes)
- Make transaction, and make sure settlement in seconds. (TBD)
1. `결제(pay)`: Transfer coins in total cost of product to seller, then get the changes.
- `meta`: save product's id.
- `transaction-id`: keep track of transaction-id in database (will be synced with todaq-api)
1. `취소(cancel)`: Cancel payment, then returns back product/coins.
- `transaction-id`: keep the original transaction-id.
1. `충전(charge)`: Buying coins with PG payment from enterprise.
- `Payment Code`: ...
1. `환불(refund)`: Refund to credit.
## 쿠폰 (Coupon)
- TYPE: `COUPON`
- Like coins in real-world, it has the benefit like 10% discount if total > 1000.
- Rule based definitions.
1. `발행(issue)`: Provider could generate.
- `Serial Code`: ...
1. `수락(accept)`: Provider could generate.
- ``: ...
--------------------
# CHECK THIS #
- [x] search files by `<file-type-id>`? or scan all files per acount in order to aggregate?
- 'Accounts - Get File Types' -> 'Accounts - Get Files by Type'
- [x] define each state of `file(coin)`, `transaction`.
- [x] size of meta data in file. purpose of meta history? -> 4MB limit of payload, or use payload-hash.
- every transation, each meta data will be appended to file's meta.
- [x] use-case of 'Files Proofs'
- [x] implementing of TodaQ app -> cupcake
- [x] search maximum limit/page number -> see `total-results`.
- [x] common error handling
- duplicated-file: fileid = Hash(payload-hash, merckle-root, first owner)
- [ ] de-nomination will come in soon.git
- [ ] synchronization concern in queue order.
- how many of available files?
- [ ] open-source and magic-key -> no way.
--------------------
# CALLBACK/WEBHOOK #
{
type: "transaction-update",
transaction-id: ...,
}
| STATUS | description | state |
|-- |-- |-- |
| PENDING | after 0~30s -> SUBMITTED | in-flight |
| SUBMITTED | in 30s -> SENDER_COMPLETE | in-flight |
| SENDER-COMPLETE | in 1s -> RECEPIENT-COMPLETE | gone |
| RECIPIENT-COMPLETE | completed tx | spendable |
| INCOMPLETE | need to re-submit transaction with same tid? | - |
- possible to add webhook in future upon request.
|
Java | UTF-8 | 7,769 | 2.171875 | 2 | [] | no_license | package com.creditharmony.fortune.deduct.entity.ext;
import java.io.Serializable;
import com.creditharmony.core.excel.annotation.ExcelField;
/**
* 线下划扣导入结果扩展类
* @Class Name ImportDeductResult
* @author 韩龙
* @Create In 2015年12月19日
*/
public class ImportDeductResult implements Serializable {
/**
* long serialVersionUID
*/
private static final long serialVersionUID = -6403407409463335114L;
// 出借编号
private String lendCode;
// 失败金额
private String deductFailMoney;
// 失败标识
private boolean deductFailFlag = true;
// 成功金额
private String deductMoney;
// 交易状态
private String status;
// 交易结果
private String ConfirmResult;
// 交易时间
private String tradingTime;
/*************好易联上传***************************/
// 备注(出借编号)
@ExcelField(title = "备注", type = 2,groups=1)
private String hylApplyCode;
// 处理状态
@ExcelField(title = "处理状态", type = 2,groups=1)
private String hylDictDeductStatus;
// 交易金额(元)
@ExcelField(title = "交易金额(元)", type = 2,groups=1)
private String hylActualDeductMoney;
// 交易结果
@ExcelField(title = "交易结果", type = 2,groups=1)
private String hylConfirmResult;
// 原因
@ExcelField(title = "原因", type = 2,groups=1)
private String hylConfirmOpinion;
/*************富有上传***************************/
// 处理状态
@ExcelField(title = "处理状态", type = 2,groups=0)
private String fdictDeductStatus;
// 返回附言
@ExcelField(title = "返回附言", type = 2,groups=0)
private String fconfirmOpinion;
// 企业流水号(出借编号)
@ExcelField(title = "企业流水号", type = 2,groups=0)
private String fapplyCode;
// 备注
@ExcelField(title = "备注", type = 2,groups=0)
private String fconfirmResult;
// 金额
@ExcelField(title = "金额", type = 2,groups=0)
private String factualDeductMoney;
/*************中金上传***************************/
// 备注信息(出借编号)
@ExcelField(title = "备注信息", type = 2,groups=2)
private String zjRemks;
// 交易状态
@ExcelField(title = "交易状态", type = 2,groups=2)
private String zjRradingStatus;
// 银行响应代码
@ExcelField(title = "银行响应代码", type = 2,groups=2)
private String zjResponseCode;
// 银行响应消息
@ExcelField(title = "银行响应消息", type = 2,groups=2)
private String zjRespInformation;
// 金额
@ExcelField(title = "金额", type = 2,groups=2)
private String zjTradingMoney;
// 交易时间
@ExcelField(title = "交易时间", type = 2,groups=2)
private String zjTradingTime;
/*************通联上传***************************/
// 备注(出借编号)
@ExcelField(title = "备注", type = 2,groups=3)
private String tlRemarks;
// 原因
@ExcelField(title = "原因", type = 2,groups=3)
private String tlReason;
// 处理状态
@ExcelField(title = "处理状态", type = 2,groups=3)
private String tlProcessingStatus;
// 交易金额
@ExcelField(title = "交易金额", type = 2,groups=3)
private String tlTradingMoney;
// 提交时间
@ExcelField(title = "提交时间", type = 2,groups=3)
private String tlTradingTime;
public String getLendCode() {
return lendCode;
}
public void setLendCode(String lendCode) {
this.lendCode = lendCode;
}
public String getDeductMoney() {
return deductMoney;
}
public void setDeductMoney(String deductMoney) {
this.deductMoney = deductMoney;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getConfirmResult() {
return ConfirmResult;
}
public void setConfirmResult(String confirmResult) {
ConfirmResult = confirmResult;
}
public String getTradingTime() {
return tradingTime;
}
public void setTradingTime(String tradingTime) {
this.tradingTime = tradingTime;
}
public boolean getDeductFailFlag() {
return deductFailFlag;
}
public void setDeductFailFlag(boolean deductFailFlag) {
this.deductFailFlag = deductFailFlag;
}
public String getHylApplyCode() {
return hylApplyCode;
}
public void setHylApplyCode(String hylApplyCode) {
this.hylApplyCode = hylApplyCode;
}
public String getHylDictDeductStatus() {
return hylDictDeductStatus;
}
public void setHylDictDeductStatus(String hylDictDeductStatus) {
this.hylDictDeductStatus = hylDictDeductStatus;
}
public String getHylActualDeductMoney() {
return hylActualDeductMoney;
}
public void setHylActualDeductMoney(String hylActualDeductMoney) {
this.hylActualDeductMoney = hylActualDeductMoney;
}
public String getHylConfirmResult() {
return hylConfirmResult;
}
public void setHylConfirmResult(String hylConfirmResult) {
this.hylConfirmResult = hylConfirmResult;
}
public String getHylConfirmOpinion() {
return hylConfirmOpinion;
}
public void setHylConfirmOpinion(String hylConfirmOpinion) {
this.hylConfirmOpinion = hylConfirmOpinion;
}
public String getFdictDeductStatus() {
return fdictDeductStatus;
}
public void setFdictDeductStatus(String fdictDeductStatus) {
this.fdictDeductStatus = fdictDeductStatus;
}
public String getFconfirmOpinion() {
return fconfirmOpinion;
}
public void setFconfirmOpinion(String fconfirmOpinion) {
this.fconfirmOpinion = fconfirmOpinion;
}
public String getFapplyCode() {
return fapplyCode;
}
public void setFapplyCode(String fapplyCode) {
this.fapplyCode = fapplyCode;
}
public String getFconfirmResult() {
return fconfirmResult;
}
public void setFconfirmResult(String fconfirmResult) {
this.fconfirmResult = fconfirmResult;
}
public String getFactualDeductMoney() {
return factualDeductMoney;
}
public void setFactualDeductMoney(String factualDeductMoney) {
this.factualDeductMoney = factualDeductMoney;
}
public String getDeductFailMoney() {
return deductFailMoney;
}
public void setDeductFailMoney(String deductFailMoney) {
this.deductFailMoney = deductFailMoney;
}
public String getZjRemks() {
return zjRemks.split("_")[1];
}
public void setZjRemks(String zjRemks) {
this.zjRemks = zjRemks;
}
public String getZjRradingStatus() {
return zjRradingStatus;
}
public void setZjRradingStatus(String zjRradingStatus) {
this.zjRradingStatus = zjRradingStatus;
}
public String getZjResponseCode() {
return zjResponseCode;
}
public void setZjResponseCode(String zjResponseCode) {
this.zjResponseCode = zjResponseCode;
}
public String getZjRespInformation() {
return zjRespInformation;
}
public void setZjRespInformation(String zjRespInformation) {
this.zjRespInformation = zjRespInformation;
}
public String getZjTradingMoney() {
return zjTradingMoney;
}
public void setZjTradingMoney(String zjTradingMoney) {
this.zjTradingMoney = zjTradingMoney;
}
public String getZjTradingTime() {
return zjTradingTime;
}
public void setZjTradingTime(String zjTradingTime) {
this.zjTradingTime = zjTradingTime;
}
public String getTlRemarks() {
return tlRemarks;
}
public void setTlRemarks(String tlRemarks) {
this.tlRemarks = tlRemarks;
}
public String getTlReason() {
return tlReason;
}
public void setTlReason(String tlReason) {
this.tlReason = tlReason;
}
public String getTlProcessingStatus() {
return tlProcessingStatus;
}
public void setTlProcessingStatus(String tlProcessingStatus) {
this.tlProcessingStatus = tlProcessingStatus;
}
public String getTlTradingMoney() {
return tlTradingMoney;
}
public void setTlTradingMoney(String tlTradingMoney) {
this.tlTradingMoney = tlTradingMoney;
}
public String getTlTradingTime() {
return tlTradingTime;
}
public void setTlTradingTime(String tlTradingTime) {
this.tlTradingTime = tlTradingTime;
}
}
|
JavaScript | UTF-8 | 3,163 | 2.6875 | 3 | [] | no_license | var dotenv = require("dotenv").config();
var keys = require("./keys.js");
var Spotify = require("node-spotify-api");
var Twitter = require("twitter");
var request = require("request");
var fs = require("fs");
var spotify = new Spotify(keys.spotify);
var client = new Twitter(keys.twitter);
var tweets = function() {
client.get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=SammyVonGinger&count=20",function(error, tweets, response) {
if(error) throw error;
for (i = 0; i < tweets.length; i++){
console.log("Tweet " + parseInt(i+1) +" Created at " + tweets[i].created_at)
console.log(tweets[i].text + "\n")
}
});
};
var WhatSong = function(song){
spotify.search({type: 'track', query: song}, function(err, data) {
if (err) {
return console.log('Error occurred: ' + err);
}
for (i = 0; i < process.argv.length; i++){
var searched = data.tracks.items[i]
console.log("Result "+ parseInt(i+1));
console.log("Artist Name: " + JSON.stringify(searched.artists[0].name).replace(/"/gi,""));
console.log("Song Name: " + JSON.stringify(searched.name).replace(/"/gi,""));
console.log("Preview Link: " + JSON.stringify(searched.preview_url).replace(/"/gi,""));
console.log("Album Name: " + JSON.stringify(searched.album.name).replace(/"/gi,""));
console.log("\n")
}
})
};
var movieThis = function(movieName){
var nodeArgs = process.argv;
// var movieName = "";
// if (nodeArgs.length > 2) {
// for (var i = 2; i < nodeArgs.length; i++) {
// if (i > 2 && i < nodeArgs.length) {
// movieName = movieName + "+" + nodeArgs[i];
// }
// else {
// movieName += nodeArgs[i];
// }
// }
// }
// else {
// movieName = "Mr+Nobody"
// }
if (nodeArgs.length = 2){
movieName = "Mr+Nobody"
}
var queryUrl = "http://www.omdbapi.com/?t=" + movieName + "&y=&plot=short&apikey=trilogy";
request(queryUrl, function(error, response, body) {
if (!error && response.statusCode === 200) {
console.log("Title: " + JSON.parse(body).Title);
console.log("Release Year: " + JSON.parse(body).Year);
console.log("IMDB Rating: " + JSON.parse(body).Ratings[0].Value);
console.log("Rotten Tomatoes Rating: " + JSON.parse(body).Ratings[1].Value);
console.log("Country Origin: " + JSON.parse(body).Country);
console.log("Language: " + JSON.parse(body).Language);
console.log("Plot: " + JSON.parse(body).Plot);
console.log("Actors: " + JSON.parse(body).Actors);
}
});
}
fs.readFile("random.txt", 'utf8', function(err, data) {
if (err) throw err;
var holder = data.split(",");
if (holder[0] == "spotify-this-song"){
WhatSong(holder[1]);
}
else if (holder[0] == "my-tweets"){
tweets();
}
else if (holder[0] == "movie-this"){
}
}); |
Java | UTF-8 | 808 | 3.5625 | 4 | [] | no_license | import java.util.Scanner;
public class ex121 {
public static int[] cloneArray(int[] oldArray){
int n = oldArray.length;
int[] newArray = new int[n];
for(int i = 0; i < n; i++){
newArray[i] = oldArray[i];
}
return newArray;
}
public static void main(String[] args) {
Scanner keyboardScanner = new Scanner(System.in);
int[] oldArray = new int[100];
System.out.print("Number of elements of the array: ");
int n = keyboardScanner.nextInt();
System.out.println("Enter the elements: ");
for(int i = 0; i < n; i++){
System.out.print("oldArray[" + i + "] = ");
oldArray[i] = keyboardScanner.nextInt();
}
cloneArray(oldArray);
}
}
|
C# | UTF-8 | 788 | 2.5625 | 3 | [
"MIT"
] | permissive | namespace OpenPokeLib.PokemonTypes
{
public class Fire : IPokemonType
{
public override Types[] SuperEffective
{
get
{
return new[]
{
Types.Water,
Types.Rock,
Types.Ground
};
}
}
public override Types[] NotEffective
{
get
{
return new[]
{
Types.Bug,
Types.Steel,
Types.Fire,
Types.Grass,
Types.Ice,
Types.Fairy
};
}
}
public Fire() : base("Fire")
{
}
}
} |
C# | UTF-8 | 1,727 | 2.75 | 3 | [] | no_license | using Bolay.Elastic.QueryDSL.MinimumShouldMatch;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Bolay.Elastic.QueryDSL.Queries.Terms
{
/// <summary>
/// http://www.elasticsearch.org/guide/en/elasticsearch/reference/1.x/query-dsl-terms-query.html
/// </summary>
[JsonConverter(typeof(TermsSerializer))]
public class TermsQuery : QueryBase
{
/// <summary>
/// The field to search against.
/// </summary>
public string Field { get; private set; }
/// <summary>
/// The values to match against.
/// </summary>
public IEnumerable<object> Values { get; private set; }
/// <summary>
/// The minimum number of the provided values that should be found in the field.
/// </summary>
public MinimumShouldMatchBase MinimumShouldMatch { get; set; }
/// <summary>
/// Create a terms query.
/// </summary>
/// <param name="field">The field to search in.</param>
/// <param name="values">The values to find.</param>
public TermsQuery(string field, IEnumerable<object> values)
{
if (string.IsNullOrWhiteSpace(field))
throw new ArgumentNullException("field", "TermsQuery requires a field.");
if (values == null || values.All(x => x == null))
throw new ArgumentNullException("values", "TermsQuery requires at least one value.");
Field = field;
Values = values.Where(x => x != null);
MinimumShouldMatch = TermsSerializer._MINIMUM_SHOULD_MATCH_DEFAULT;
}
}
}
|
Java | GB18030 | 1,973 | 2.171875 | 2 | [] | no_license | /*
* Copyright 2011 by Founder Sprint 1st, Inc. All rights reserved.
*/
package gov.nbcs.rp.queryreport.definereport.ui;
import java.util.EventObject;
import javax.swing.JFrame;
import com.foundercy.pf.reportcy.design.actions.UndoableAction;
import com.foundercy.pf.reportcy.design.gui2.core.DesignUtils;
import com.foundercy.pf.util.Tools;
import com.fr.cell.ReportPane;
import com.fr.report.CellElement;
/**
* <p>
* Title:üв
* </p>
* <p>
* Description:üв
* </p>
* <p>
*/
public class SetCalcAction extends UndoableAction {
private static final long serialVersionUID = 1L;
private JFrame jframe = null;
private CalcColumnDialog calcColumnDialog;
public SetCalcAction(ReportPane reportPane, JFrame jframe, boolean bEnable) {
// this.setEnabled(bEnable);ı䣬ɵ
this.setName("");
this.setSmallIcon(DesignUtils.getIcon("images/fbudget/a7.gif"));
this.setReportPane(reportPane);
this.jframe = jframe;
}
public boolean executeAction(EventObject evt, ReportPane reportPane) {
int col = reportPane.getCellSelection().getColumn();
int row = reportPane.getCellSelection().getRow();
CellElement cellElement = reportPane.getReport().getCellElement(col,
row);
Object value;
if (cellElement == null) {
value = new MyCalculateValueImpl("");
((MyCalculateValueImpl) value).setIsVisual(1);
cellElement = new CellElement(col, row);
cellElement.setValue(value);
reportPane.getReport().addCellElement(cellElement);
} else {
value = cellElement.getValue();
if (value == null || !(value instanceof MyCalculateValueImpl)) {
value = new MyCalculateValueImpl("");
((MyCalculateValueImpl) value).setIsVisual(1);
}
}
this.calcColumnDialog = new CalcColumnDialog(jframe);
Tools.centerWindow(calcColumnDialog);
calcColumnDialog.populate(cellElement, value);
calcColumnDialog.setVisible(true);
return false;
}
}
|
Markdown | UTF-8 | 773 | 2.8125 | 3 | [] | no_license | # Apache Supserset custom docker image
a custom single node apache superset docker image that is ready to use without any custom configs.
## Running from dockerhub
docker pull mujahid002/apache-superset:latest
and then run it by
docker run -d -p 8088:8088 --name superset mujahid002/apache-superset:latest
## How to Build:
use the following command to build the image
git clone https://github.com/mujahidniaz/apache-superset-docker.git
cd apache-superset-docker
docker build -t mujahid002/apache-superset .
Then you can run the container using:
docker run --name my_superset -d -p 8088:8088 mujahid002/apache-superset
Now finally open your browser and type
http://localhost:8088/
Use the following credentials.
Username: admin
Password: admin
|
Java | UTF-8 | 492 | 2.359375 | 2 | [] | no_license | package br.com.whatsappandroid.cursoandroid.myeasyparking.Model;
import br.com.whatsappandroid.cursoandroid.myeasyparking.Model.Usuario;
/**
* Created by root on 08/06/17.
*/
public class UsuarioSingleton {
private static Usuario usuario = null;
public Usuario getInstance() {
if (usuario == null) {
usuario = new Usuario();
}
return usuario;
}
public void setInstance(Usuario usuario){
this.usuario = usuario;
}
} |
Java | UTF-8 | 218 | 1.53125 | 2 | [
"LicenseRef-scancode-warranty-disclaimer",
"ANTLR-PD",
"CDDL-1.0",
"bzip2-1.0.6",
"Zlib",
"BSD-3-Clause",
"MIT",
"EPL-1.0",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-jdbm-1.00",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | package com.sequenceiq.cloudbreak.ha.service;
import java.util.Set;
public interface ServiceFlowLogComponent {
int purgeTerminatedResourceLogs();
Set<Long> findTerminatingResourcesByNodeId(String nodeId);
}
|
C++ | UTF-8 | 1,237 | 3.265625 | 3 | [] | no_license | /*
There are n pictures delivered for the new exhibition. The i-th painting has beauty ai. We know that a visitor
becomes happy every time he passes from a painting to a more beautiful one.
We are allowed to arranged pictures in any order. What is the maximum possible number of times the visitor
may become happy while passing all pictures from first to last. In other words, we are allowed to rearrange
elements of array a in any order.
What is the maximum possible number of indices i (1 <= i <= n - 1), such that ai + 1 > ai.
Sample Input 0
4
200 100 100 200
Sample Output 0
2
Explanation 0
Sample Ordering that gives answer 2 :
100 200 100 200
*/
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n, a[1000],b[1000],j,i,c=0,m;
cin>>n;
for(i=0;i<n;i++)
cin>>a[i];
sort(a,a+n);
for(i=0;i<n;i++)
{
if(a[i]==a[i+1])
c++;
else
{
m=max(c+1,m);
c=0;
}
}
cout<<(n-m);
return 0;
}
|
Java | UTF-8 | 787 | 2.328125 | 2 | [
"MIT"
] | permissive | package ro.msg.learning.shop.entities;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.io.Serializable;
@Entity @Data @EqualsAndHashCode(callSuper = true)
@NoArgsConstructor
@AllArgsConstructor
@Table(name="product")
public class Product extends BaseEntity implements Serializable {
@Column(name="name")
private String name;
private String description;
private long price;
private double weight;
private String imageURL;
@ManyToOne
@JoinColumn(name = "id_product_category", nullable = false)
private ProductCategory productCategory;
@ManyToOne
@JoinColumn(name="id_supplier", nullable=false)
private Supplier supplier;
}
|
Python | UTF-8 | 831 | 2.609375 | 3 | [] | no_license | import socketserver
import threading
class MyHandlerServer(socketserver.BaseRequestHandler):
def setup(self):
super().setup()
self.event = threading.Event()
def handle(self):
super().handle()
print(self.server, self.client_address, self.request)
while not self.event.is_set():
data = self.request.recv(1024)
msg = '{}'.format(data.decode()).encode()
print(data.decode())
self.request.send(msg)
def finish(self):
super().finish()
self.event.set()
addr = ('127.0.0.1', 8080)
server = socketserver.ThreadingTCPServer(addr, MyHandlerServer)
server.serve_forever() # 永久连接
server.shutdown()
server.server_close() # 调用关闭套接字之前,要调用shutdown()方法,等待停止server_forever()
|
Markdown | UTF-8 | 1,565 | 2.546875 | 3 | [] | no_license | # Article L331-7
En cas de cessation définitive de l'activité d'un établissement, d'un service ou d'un lieu de vie et d'accueil autorisé en
vertu de l'article L. 312-1 ou déclaré en vertu de l'article L. 321-1, les créances que peuvent détenir les mineurs sur ce
dernier sont garanties par un privilège général sur les meubles et par une hypothèque légale sur les immeubles appartenant à
l'organisme gestionnaire, inscrite au service chargé de la publicité foncière à la requête du représentant de l'Etat dans le
département ou du président du conseil départemental.
**Nota:**
**Liens relatifs à cet article**
_Modifié par_:
- Ordonnance n°2018-22 du 17 janvier 2018 - art. 1
_Anciens textes_:
- Code de la famille et de l'aide sociale. - art. 97 (M)
- Code de la famille et de l'aide sociale. - art. 97 (Ab)
_Cité par_:
- Code de l'action sociale et des familles - art. D331-3 (M)
- Code de l'action sociale et des familles - art. L313-11 (M)
- Code de l'action sociale et des familles - art. L313-13 (M)
- Code de l'action sociale et des familles - art. L313-14 (M)
- Code de l'action sociale et des familles - art. L313-15 (M)
- Code de l'action sociale et des familles - art. L313-18 (V)
- Code de l'action sociale et des familles - art. L321-4 (M)
- Code de l'action sociale et des familles - art. L331-8 (M)
- Code de l'action sociale et des familles - art. L543-3 (V)
_Cite_:
- Code de l'action sociale et des familles - art. L312-1
- Code de l'action sociale et des familles - art. L321-1
|
Python | UTF-8 | 2,108 | 3.6875 | 4 | [] | no_license | #########################################################
# December 11th, 2016 #
# a. Convert the IP address validation code from #
# week4-1 into a function. Take one variable #
# 'ip_adress' and return True or False. Include #
# only validation, no prompting for input. #
# b. Import the function inot the interpreter and #
# test it using both 'import x' and 'from x import #
# y' methods. #
# #
# Note: Do not run me, I'll kick back errors =) #
# Note: Functions stored in pynet_lib.py #
# #
#########################################################
# Part a
def ip_checker(ip_address):
'''
Takes one IP address and checks whether it is valid or not.
'''
# Try to convert to integers
try:
ip_addr = [int(i) for i in ip_address.split('.')]
except ValueError:
return False
# Determine how many octets were entered
if len(ip_addr) != 4:
return False
# Determine if the first octet is valid
if ((ip_addr[0] > 223) and (ip_addr[0] < 256)) or (ip_addr[0] == 0):
return False
# Determine if this is a loopback address
if ip_addr[0] == 127:
return False
# Determine if this is an APIPA address
if (ip_addr[0] == 169) and (ip_addr[1] == 254):
return False
# Determine if the last three octets are between 0-255
for octet in (ip_addr[1], ip_addr[2], ip_addr[3]):
if octet not in [i for i in range(0,256)]:
return False
else:
return True
# Part b
>>> import pynet_lib
>>> pynet_lib.ip_checker('192.168.0.1')
The IP address 192.168.0.1 is valid.
True
>>> pynet_lib.ip_checker('127.0.0.1')
I think that was a loopback address, please try again.
False
>>> from pynet_lib import ip_checker
>>> ip_checker('74.75.76.77')
The IP address 74.75.76.77 is valid.
True
>>> ip_checker('169.254.0.1')
I think that was an APIPA address, please try again.
False
|
Markdown | UTF-8 | 2,503 | 2.546875 | 3 | [] | no_license | ---
layout: post
title: Installer FAQ - Role of Essential Studio in Visual Studio | Syncfusion
description: Learn here about the role of Syncfusion Essential Studio in Visual Studio and its difference from Visual Studio.
platform: common
control: Essential Studio
documentation: ug
---
# What is the role of Essential Studio in Visual Studio?
Syncfusion Essential Studio is not a plug-in for Visual Studio or an IDE like Visual Studio. Syncfusion Essential Studio is a .NET based product which offers 800+ controls and frameworks which can be used in Visual Studio for developing stunning applications. The Essential Studio includes the samples for all the controls which provides an overview of how Syncfusion controls looks like and how it works. The platforms that comes with Syncfusion Essential Studio are as follows.
* ASP.NET
* ASP.NET Core (Essential JS 1)
* ASP.NET MVC (Essential JS 1)
* JavaScript (Essential JS 1)
* JSP
* PHP
* Universal Windows Platform
* Windows Forms
* WPF
* Xamarin
* FileFormats
* ASP.NET Core (Essential JS 2)
* ASP.NET MVC (Essential JS 2)
* JavaScript (Essential JS 2)
Syncfusion Essential Studio offers Syncfusion Control Panel from which both the online and offline samples can be viewed for all the controls. Documentation, Read Me and Release Notes can also be viewed from the dashboard itself which reduces the burden of searching over the web.

Apart from the installer for Windows, Syncfusion also provides the installer for Mac for the following Essential Studio platforms.
1. ASP.NET Core (Essential JS 1)
2. JavaScript (Essential JS 1)
3. Xamarin
4. PHP
5. Electron
6. WebKit HTML Converter
7. ASP.NET Core (Essential JS 2)
8. JavaScript (Essential JS 2)
Download and install the latest Essential Studio from [here](https://www.syncfusion.com/downloads/latest-version).
Refer [this](https://help.syncfusion.com/common/essential-studio/installation/install-using-the-offline-installer#step-by-step-installation) link for the step by step installation of Syncfusion Essential Studio.
After installing the Essential Studio, refer [this](https://help.syncfusion.com/) link for using the Syncfusion controls in Visual Studio for various platforms.
Also, refer [this](http://www.syncfusion.com/downloads/support/directtrac/185893/ze/Essential_Studio_WhitePaper-1896020245) document for the general questions which pop ups to your mind while installing the Syncfusion Essential Studio.
|
Java | UTF-8 | 115 | 1.851563 | 2 | [] | no_license | package no.hal.timers.fxui;
public interface Action<T> {
public boolean isFor(T t);
public void doFor(T t);
}
|
TypeScript | UTF-8 | 1,261 | 2.640625 | 3 | [] | no_license | import { Action, createFeatureSelector, createSelector } from '@ngrx/store'
import { Draw, equalDraw } from './../models/draw.model'
import * as DrawActions from './../actions/draw.actions'
import { DrawState, initialDrawState } from '../app.state';
var lastElement;
export function reducer(state: DrawState = initialDrawState, action: DrawActions.Actions) {
switch(action.type) {
case DrawActions.UPDATE_DRAWTYPE:
return {...state, drawType : action.payload };
case DrawActions.INIT_DRAW:
return {...state, currentDraw : action.payload };
case DrawActions.UPDATE_DRAW:
return {...state, currentDraw : {x1: state.currentDraw.x1, y1: state.currentDraw.y1, x2:action.payload.x2, y2: action.payload.y2, type: state.drawType} };
case DrawActions.SAVE_DRAW:
return {...state, myDraws: [...state.myDraws, action.payload]};
case DrawActions.UNDO_DRAW:
lastElement = state.myDraws.length > 1 ? state.myDraws[state.myDraws.length-2] : null;
return {...state , currentDraw: lastElement, myDraws : [...state.myDraws.filter(function(value, index, arr){ return !equalDraw(value,action.payload); }) ] };
default:
return state;
}
}
|
PHP | UTF-8 | 532 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php namespace App;
use App\SemesterSubject;
use Illuminate\Database\Eloquent\Model;
class Subject extends Model {
protected $fillable = [
'name',
'school',
'department',
'description'
];
public function semesters()
{
//return $this->hasMany('SemesterSubject')->with('Semester');
return $this->belongsToMany('App\Semester');
}
public function topics()
{
return $this->hasMany('App\Topic');
}
public function getSemesterListAttribute()
{
return $this->semesters->lists('id');
}
}
|
C# | UTF-8 | 1,529 | 2.75 | 3 | [] | no_license | using System;
using System.Threading;
using System.Threading.Tasks;
using Application.Common.Interfaces;
using Domain.Entities;
using Domain.Exceptions;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Application.Terrariums.Commands.UpdateTerrarium
{
public class UpdateTerrariumCommand : IRequest<int>
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public bool IsPublic { get; set; }
public class Handler : IRequestHandler<UpdateTerrariumCommand, int>
{
private readonly IAppDbContext _context;
public Handler(IAppDbContext context)
{
_context = context;
}
public async Task<int> Handle(UpdateTerrariumCommand request, CancellationToken cancellationToken)
{
var entity = await _context.TerraristicWindows
.SingleOrDefaultAsync(t => t.Id == request.Id, cancellationToken);
if (entity == null)
{
throw new NotFoundException(nameof(TerraristicWindow), request.Id);
}
entity.Name = request.Name;
entity.Description = request.Description;
entity.IsPublic = request.IsPublic;
await _context.SaveChangesAsync(cancellationToken);
return entity.Id;
}
}
}
} |
C | UTF-8 | 1,079 | 3.859375 | 4 | [] | no_license | /*Xét bàn cờ tổng quát kích thước n × n, người ta muốn đặt k quân tượng vào k ô hoàn toàn phân biệt sao cho chúng đôi một không ăn nhau.
(Quân tượng có thể ăn quân khác nằm ở những ô cùng đường chéo với ô nó đang đứng).
Nhiệm vụ của các bạn là hãy tính xem có bao nhiêu cách đặt k quân tượng này?
*/
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
int N,k;
int f(int m,int k)
{
if (k==0&&m>=0) return 1;
if (m==N-1)
{
if(k==1) return 2;
if (k>1) return 0;
}
if (m==N-2)
{
if (k==1) return 4;
if (k==2) return 2;
if (k>2) return 0;
}
if (m==0)
{
return f(m+2,k)+(N-m-k+1)*f(m+2,k-1);
}
if (k==1)
{
return f(m+2,k)+(N-m-k+1)*2*f(m+2,k-1);
}
else return f(m+2,k)+(N-m-k+1)*(2*f(m+2,k-1) + (N-m-k+2)*f(m+2,k-2));
}
int main()
{
int s=0,i,j;
scanf("%d",&N);
scanf("%d",&k);
for (i=0;i<=k;i++)
{
s+=f(0,i)*f(1,k-i);
}
printf("%d",s);
}
|
Java | UTF-8 | 785 | 2.0625 | 2 | [] | no_license | package com.isoft.crm.service;
import java.util.List;
import java.util.Set;
import com.isoft.crm.bean.MenuBean;
import com.isoft.crm.bean.UserSession;
/**
*
*@Title: LoginService.java
*@Package: com.isoft.crm.service
*@Description:
* the Login factory interface.
*@author: Nina Zhao
*@date:下午11:13:19
*/
public interface LoginService {
//Finding the user info depending on loginName, password.
public UserSession getUserSession(String loginName, String upwd);
//Getting the menu and authority
public List<MenuBean> getMenu(UserSession userSession);
//Changing the pasword
public void updatePwd(UserSession userSession, String newPwd);
//Getting user's authority id.
public Set<Integer> getFunctionIdByRoleId(Integer roleId);
}
|
Python | UTF-8 | 2,523 | 3.78125 | 4 | [
"MIT"
] | permissive | '''
Created on 23 Oct 2013
@author: Richard and Michael
'''
import copy
from game_of_life.data_structures.states import Alive, Dead
class Calculator(object):
'''
This class represents the calculation engine for the Game of Life
simulation
'''
def __init__(self, rule_set):
'''
Constructor
'''
self._rule_set = rule_set
def _find_neighbour_set(self, grid, x, y):
'''
Returns a collection of a cells neighbours
'''
grid_cells = grid.get_cells()
grid_row_length = len(grid_cells)
grid_col_length = len(grid_cells[0])
neighbour_cells = []
for x_diff in range(-1, 2):
for y_diff in range(-1, 2):
if x_diff != 0 or y_diff != 0:
xx = (x + x_diff) % grid_row_length
yy = (y + y_diff) % grid_col_length
neighbour_cells.append(grid_cells[xx][yy])
return neighbour_cells
def _next_state(self, cell, neighbour_cells):
'''
Returns the next state of the cell after calculation according to the
rule set.
'''
# checks the state of the cell being calculated.
# cycles through the neighbouring cells to find the no. of alive ones.
# checks the rule set to see which rule is applied.
# returns the correct state of the cell in the next generation.
born = self._rule_set.get_born_var()
stay_one, stay_two = self._rule_set.get_stay_var()
alive = 0
for neighbour in neighbour_cells:
if neighbour.get_state() == Alive():
alive += 1
if alive == born and (cell.get_state() == Dead()):
return Alive()
elif cell.get_state() == Alive() and \
(alive == stay_one or alive == stay_two):
return Alive()
else:
return Dead()
def calculate_generation(self, grid):
'''
Calculates the next generation of cells in a given grid.
Returns the collection of cells holding the next generation.
'''
returned_cells = []
for x, row in enumerate(grid.get_cells()):
returned_cells.append([])
for y, c in enumerate(row):
neighbours = self._find_neighbour_set(grid, x, y)
c = copy.copy(c)
c.set_state(self._next_state(c, neighbours))
returned_cells[x].append(c)
return returned_cells
|
Java | UTF-8 | 1,110 | 2.015625 | 2 | [] | no_license | package Com.pages;
import java.io.IOException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import com.excelUtility.LoginInvaliddata;
public class LoginInvalid {
WebDriver driver;
public void launch() {
System.setProperty("webdriver.chrome.driver", "D:\\projectall-master\\projectall-master\\drivers\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
}
public void Home_page() {
driver.get("https://opensource-demo.orangehrmlive.com/index.php/auth/login");
}
public void loginData(int a) throws InterruptedException, IOException {
LoginInvaliddata e=new LoginInvaliddata();
driver.findElement(By.xpath("//*[@id='txtUsername' and @name='txtUsername']")).sendKeys(e.Username(a));
driver.findElement(By.xpath("//*[@id='txtPassword' and @name='txtPassword']")).sendKeys(e.Password(a));
}
public void submit() {
driver.findElement(By.xpath("//*[@id='btnLogin' and @name='Submit']")).click();
System.out.println(driver.getTitle());
}
}
|
Java | UTF-8 | 2,809 | 4.0625 | 4 | [] | no_license | package bbb.Arrays;
import java.util.*;
public class LongestConsecutiveSequence {
/*
Time: O(N^2) for list, O(N^3) for array because of contains look up
Space: O(1)
*/
/* Worst Case: Array in Descending Order */
private static int longestConsecutiveSequenceApproach1(List<Integer> list) {
int maxLength = 0;
for(int num : list) {
int count = 0;
while(list.contains(num++)) {
count++;
}
maxLength = Math.max(maxLength, count);
}
return maxLength;
}
/* Time: O(N log N), Space: O(1) */
private static int longestConsecutiveSequenceApproach2(List<Integer> list) {
Collections.sort(list);
int maxLength = 0;
int count = 1;
for(int i = 0; i < list.size() - 1; i++) {
// IGNORE DUPLICATES
if(list.get(i).intValue() == list.get(i+1).intValue()) {
continue;
} else if(list.get(i).intValue() + 1 == list.get(i+1).intValue()) {
count++;
} else {
maxLength = Math.max(maxLength, count);
count = 1;
}
}
maxLength = Math.max(maxLength, count);
return maxLength;
}
/* Time: O(N), Space: O(N) */
private static int longestConsecutiveSequenceApproach3(List<Integer> list) {
int maxLength = 0;
// Avoids duplicates
Set<Integer> set = new HashSet<>();
for(Integer num : list) {
set.add(num);
}
for(Integer unique : set) {
if(set.contains(unique-1)) {
// current unique is a sub problem.
// Main problem might already or in future will be calculated.
continue;
}
int count = 0;
while(set.contains(unique++)) {
count++;
}
maxLength = Math.max(maxLength, count);
}
return maxLength;
}
private static void evaluate(List<Integer> dups) {
System.out.println(dups.toString());
int maxLength1 = longestConsecutiveSequenceApproach1(dups);
System.out.println("Approach1 : " + maxLength1);
int maxLength2 = longestConsecutiveSequenceApproach2(dups);
System.out.println("Approach2 : " + maxLength2);
int maxLength3 = longestConsecutiveSequenceApproach3(dups);
System.out.println("Approach3 : " + maxLength3);
}
public static void main(String[] args) {
List<Integer> dups1 = Arrays.asList(new Integer[]{4, 2, 1, 6, 5});
evaluate(dups1);
System.out.println("*********************");
List<Integer> dups2 = Arrays.asList(new Integer[]{5, 5, 3, 1});
evaluate(dups2);
}
}
|
C | UTF-8 | 1,112 | 2.828125 | 3 | [] | no_license | #include <avr/io.h>
#include <util/delay.h>
#include "settings.h"
#include "uart.h"
#include "utils.h"
/* 2^8-1 = 3 digits + 1 for string terminator */
void uint8_to_str (uint8_t val, char* target) {
for (int i = 2; i >= 0; i--) {
target [i] = val % 10 + '0';
val /= 10;
}
target[3] = '\0';
}
/* 2^16-1 = 5 digits + 1 for string terminator */
void uint16_to_str (uint16_t val, char* target) {
for (int i = 4; i >= 0; i--) {
target [i] = val % 10 + '0';
val /= 10;
}
target[5] = '\0';
}
/* 2^32-1 = 10 digits + 1 for string terminator*/
void uint32_to_str (uint32_t val, char* target) {
for (int i = 9; i >= 0; i--) {
target [i] = val % 10 + '0';
val /= 10;
}
target[10] = '\0';
}
void debug_string(char* str) {
if (global_settings_get().uart_debug)
uart_send_string(str);
}
void error_string(char* str) {
/* TODO: flash status led red */
uart_send_string(str);
}
void hardware_reset() {
/* hardware reset by pulling RESET_ low (via resistor). */
debug_string("\n\rresetting\n\r");
_delay_ms(100);
DDRD |= (1 << PD4);
PORTD &= ~(0 << PD4);
}
|
Markdown | UTF-8 | 3,678 | 2.75 | 3 | [] | no_license | # Hinweise zur C++-Programmierung
## Namenskonventionen
- Variablen/Instanzen sollten immer mit einem Kleinbuchstaben beginnen,
- Defines, Makros Ausschließlich aus Großbuchstaben bestehen und
- Klassen und Strukturen mit einem Großbuchstaben gefolgt von Kleinbuchstaben
Selbstverständlich sind "sprechende" Namen zu bevorzugen.
Häufig werden Variablen einer Klasse mit voran gestelltem "m_" gekennzeichnet. Viele IDEs enthalten Tools zur automatischen Code-Vervollständigung, hier bekommt man, nach Eingabe von "m_", direkt alle Klassenvariablen zur Auswahl.
```c
int m_identifier
```
Die CamelCase-Notation ist auch weit verbreitet und wird zum Teil in Kombination angewendet.
```c
class ObjectContainer
{
private:
int m_objectCounter;
}
```
## Header - Source Trennung
Die Trennung von code in Header- und Sourcedateien bringt nicht nur den Vorteil der Übersichtlichkeit mit sich, sondern ist in ein paar Fällen unbedingt nötig. Diese werden ich am Ende anschneiden, Sie werden diese im Verlauf der Vorlesung kennenlernen.
In vielen Fällen ist es nur interessant, den Aufbau und die Fähigkeiten einer Klasse zu kennen. Beispielsweise arbeiten Sie in einem Projekt mit mehreren Personen und erhalten Klassen oder Komponenten von Teammitgliedern, oder Sie verwenden eine Bibliothek, fügen ein neues Feature in eine existierendes Program ein, ... . In diesen Fällen liegt die Funktionalität der Klassen nicht bei Ihnen und vermutlich wollen Sie die Implementierung z.B. von std::stringstream auch nicht wissen. Mit einem Blick in den Header sollte man diese Informationen schnell und übersichtlich finden.
Als Faustformel sollte nur die Klassendeklaration und deren Dokumentation im Header stehen. Allerdings werden in der Regel noch weitere Einträge erforderlich oder hilfreich sein. Wie z.B.:
- Include-Guards / pragma once
- Inculdes verwendeter Klassen header
- namespaces
- Forward declarations (Vorwärtsdeklarationen)
- inline-Funktionen
- ggf. mehr
zu inline-Funktionen:
Funktionen, die innerhalb der Klassendeklaration definiert werden sind inline Funktionen, mit dem `ìnline` Schlüsselwort können inline Funktionen auch außerhalb der Klassen-Deklaration (aber im header!) definiert werden. Die [google-c++ Programmierrichtlinien](https://google.github.io/styleguide/cppguide.html#Header_Files) schlagen eine Obergrenze für inline-Funktionen von Zeilen vor - Keine Schleifen! Keine Rekursionen! - Allerdings ist inline nur eine Empfehlung.
### Fälle in denen Header source Trennung unbedingt nötig ist
Unter anderem bei Vorwärtsdeklarationen, diese sind nötig wenn in der Architektur ein Henne-Ei-Problem auftritt. Würde `Henne.h` `Ei.h` inkludieren und umgekehrt `Ei.h` `Henne.h` inkludieren würden dies die include-guards verhinder, bzw. ohne eine Endlosschleife entstehen. In der folgenden Lösung wird in beiden Headern per Vorwärtsdeklaration bekannt gegben, dass eine Klasse mit dem jeweiligen Namen existiert und beim Kompilieren der source-Datei zur Verfügung steht (include in cpp-Datei)
Vorwärtsdeklarationen werden auch bei Freund-Klassen und Funktionen eingesetzt
```c henne.h
#ifndef HENNE_H
#define HENNE_H
class Ei; // forawrd declaration
class Henne
{
public:
Henne();
Ei* legeEi()const;
};
#endif // HENNE_H
```
```c ei.h
#ifndef EI_H
#define EI_H
class Henne; // forawrd declaration
class Ei
{
public:
Ei();
Henne* schluepfe()const;
};
#endif // EI_H
```
Weiter müssen statische Klassenvariablen außerhalb der Klasse definiert werden. Werden diese im Header definiert und ist dieser mehrfach inkludiert, wird die Variable auch mehrfach definiert -> Linker-Fehler
|
C++ | UTF-8 | 361 | 2.96875 | 3 | [] | no_license | #pragma once
class Color
{
public:
typedef unsigned char uchar;
Color();
Color(uchar r, uchar g, uchar b, uchar a);
~Color();
static Color GetRandomColor();
public:
uchar R;
uchar G;
uchar B;
uchar A;
public:
static const Color RED;
static const Color BLUE;
static const Color GREEN;
static const Color BLACK;
static const Color WHITE;
};
|
C | UTF-8 | 2,066 | 2.90625 | 3 | [] | no_license | /*
* serijska proba.c
*
*
* Created: 26.5.2017. 04.18.09
* Author : Kovach
*
*/
#define F_CPU 16000000
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#include <string.h>
#define BAUD 9600 //baud-rate [bps]
#define mojUBR (F_CPU/16/BAUD-1) //broj koji se upisuje u UBR high i low registar, da bi se dobio zeljeni baud-rate
#define buffer_size 128
void Rx_Tx_Enable();
void addSerial(char c); //dodaje karakter u bafer
void serialWrite(char c[]); //funkcija
void serialRead(); //funkcija
char serialBuffer[buffer_size]; //bafer 128 bita
uint8_t readPozicija = 0;
uint8_t writePozicija = 0;
int main(void)
{
Rx_Tx_Enable();
serialWrite("Hello world\n\r");
//serialWrite("Dje ste Srbi\n\r");
while (1)
{
serialRead();
}
}
void Rx_Tx_Enable()
{
cli();
UCSR0B = (1<<RXEN0)|(1<<TXEN0)|(1<<TXCIE0)|(1<<RXCIE0); //Rx, Tx enable, Tx interrupt enable, Rx interrupt enable
//1 stop bit, no parity
UCSR0C = (1<<UCSZ01)|(1<<UCSZ00); //Char size = 8 bit
//UBR je podeljen u dva registra
UBRR0H = mojUBR>>8; //LSB od mojUBR
UBRR0L = mojUBR; //MSB od mojUBR
sei();
}
void addSerial(char c) //dodaje karakter u bafer
{
serialBuffer[writePozicija] = c; //upisi pristigli karakter na poziciju writePozicija
writePozicija++; //kad upises inkrementiraj "pokazivac" pozicije
if(writePozicija >= buffer_size) //kad dodjes do kraja vrati se na pocetak
writePozicija = 0;
}
void serialWrite(char c[])
{
for(uint8_t i=0; i<strlen(c); i++)
{
addSerial(c[i]);
}
if(UCSR0A & (1<<UDRE0)) //transmit buffer empty flag. ready to be written
UDR0 = 0;
}
void serialRead() //da ucitava u uC poslato sa kompa
{
if( (!(UCSR0A & (1<<UDRE0))) == 0 )
addSerial(UDR0);
}
ISR(USART_TX_vect)
{
//prekid usled transmit complete flag
if(readPozicija != writePozicija)
{
UDR0 = serialBuffer[readPozicija];
readPozicija++;
if(readPozicija >= buffer_size)
readPozicija=0;
}
}
ISR(USART_RX_vect)
{
} |
C# | UTF-8 | 2,716 | 3.453125 | 3 | [] | no_license | using System;
namespace VALIDACAO_DE_DADOS
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Validação de Dados");
Console.WriteLine("--------------------");
Console.WriteLine("Digite o nome do usuario");
string nome = Console.ReadLine();
while(nome == ""){
Console.WriteLine("O nome não popde ser vazio");
Console.WriteLine("Digite o nome de usuario");
nome = Console.ReadLine();
}
Console.WriteLine("Digite sua idade");
int idade = int.Parse(Console.ReadLine());
while (idade< 0 || idade > 150)
{
Console.WriteLine("A idade deve ser entre 0 e 150");
Console.WriteLine("Digite sua idade novamente");
idade = int.Parse(Console.ReadLine());
}
Console.WriteLine("Digite o seu salário");
float salario = float.Parse(Console.ReadLine());
while(salario <=0)
{
Console.WriteLine("O Salário deve ser maior que zero");
Console.WriteLine("Digite seu salário :");
salario = float.Parse(Console.ReadLine());
}
bool validacao = true;
do
{
Console.WriteLine("Estado Civil - Selcione uma opção abaixo");
Console.WriteLine("s - Solteiro");
Console.WriteLine("c - Casado");
Console.WriteLine("v - viuvo");
Console.WriteLine("d - Divorciado");
string opcao = Console.ReadLine();
switch (opcao.ToLower())
{
case "s":
Console.WriteLine("Você selecionou Solteiro");
validacao = true;
break;
case "c":
Console.WriteLine("Você slecionou Casado");
validacao = true;
break;
case "v":
Console.WriteLine("Você selecionou Viuvo");
validacao = true;
break;
case "d":
Console.WriteLine("Você selecionou Divorciado");
validacao = true;
break;
default:
Console.WriteLine("Você de selecinar umas das opção do menu");
validacao = false;
break;
}
} while (validacao == false);
Console.WriteLine("Estado Civil cadastrado");
}
}
}
|
Python | UTF-8 | 2,215 | 2.953125 | 3 | [] | no_license | from myList import myList
from myItem import myItem
class MB:
def __init__(self, friendship):
self.friendship = friendship
pass
def sort_people(self, sort_by_name=False, sort_by_id=False, sort_by_age=False, sort_by_book=False, reverse=False):
people_list = self.friendship.get_people_list()
if people_list.len <= 1:
return people_list
cur = people_list.start.next.next
while cur is not None:
p = people_list.start.next
x = cur.item
if sort_by_age:
while p is not cur and (p.item.age >= x.age) ^ reverse:
p = p.next
elif sort_by_name:
while p is not cur and (p.item.name <= x.name) ^ reverse:
p = p.next
elif sort_by_book:
while p is not cur and (p.item.current_book.len >= x.current_book.len) ^ reverse:
p = p.next
elif sort_by_id:
while p is not cur and (p.item.id <= x.id) ^ reverse:
p = p.next
else:
break
while p is not cur:
tmp = x
x = p.item
p.item = tmp
p = p.next
cur = cur.next
return people_list
def sort_book(self, sort_by_title=False, sort_by_author=False, reverse=False):
book_list = self.friendship.get_books_list()
if book_list.len <= 1:
return book_list
cur = book_list.start.next.next
while cur is not None:
p = book_list.start.next
x = cur.item
if sort_by_title:
while p is not cur and (p.item.title <= x.title) ^ reverse:
p = p.next
elif sort_by_author:
while p is not cur and (p.item.author <= x.author) ^ reverse:
p = p.next
else:
break
while p is not cur:
tmp = x
x = p.item
p.item = tmp
p = p.next
cur.item = x
cur = cur.next
return book_list
pass
|
Python | UTF-8 | 2,987 | 2.734375 | 3 | [] | no_license | import timeit
from pprint import pprint
import copy
import Modules.myconstants as myconst
import Modules.magnetix as mag
import Modules.genetix as gen
import Modules.writer as writer
from Classes.populationclass import *
mainLoopFlag = True
epsilonFlag = False
def evolver(queueop, mypop, application_runtime):
application_start = timeit.default_timer()
pop = Population()
#pop.individuals[0].genotype_update()
generation = 0
last_wait = 0
last_difference = 0
global mainLoopFlag
global epsilonFlag
pop.update_epsilon(gen.epsilonCalc(last_difference, generation))
while mainLoopFlag:
# Cycling the population through one evolutionary generation
pop.evolution_cycle()
if (len(pop.best_fitness) > 1):
last_difference = gen.last_difference_calc(pop.best_fitness)
generation += 1
pop.update_epsilon(gen.epsilonCalc(last_difference, generation))
# pprint(gen.coil_order(pop.individuals[0].chromosomes))
#TODO: Have parameter for fractional fitness. In other words, have best_fitness/best_accepted_fitness, where best_accepted_fitness is chosen from the best of the analytic solutions.
print('Current Generation is : ', generation)
print('Last difference was : ', last_difference)
print('Epsilon is : ' + str(Coil.epsilon))
print('Initial best fitness is : ' + str(round(Population.initial_best.fitness, 5)))
print('Best Fitness is : ' + str(round(pop.best_fitness[-1],5)))
print('Helmholtz fitness is : ' + str(round(pop.individuals[0].hh_homogeneity,5)))
print('9/4 Lee-Whiting fitness is : ' + str(round(pop.individuals[0].lwb_homogeneity,5)))
print('Lee-Whiting fitness is : ' + str(round(pop.individuals[0].lw_homogeneity,5)))
print('Solenoid fitness is : ' + str(round(pop.individuals[0].sol_homogeneity,5)))
print('Gapped Solenoid fitness is : ' + str(round(pop.individuals[0].gap_homogeneity,5)))
print('\n')
writer.genotype_writer(pop.individuals[0].genotype)
if(Coil.epsilon < 1e-7):
mainLoopFlag = False
break
application_end = timeit.default_timer()
application_runtime = application_end - application_start
pop.bestRealisticize()
print('Best Fitness is : ' + str(round(pop.best_fitness[-1],5)))
print('Realistic Fitness is : ' + str(round(pop.realistic_fitness,5)))
mypop = copy.deepcopy(pop)
queueop.put((mypop, application_runtime))
def get_input():
global mainLoopFlag
global epsilonFlag
# thread doesn't continue until key is pressed
while mainLoopFlag:
keystrk=input('Press a command then <ENTER> to modify/stop run... \n')
if (keystrk == 'q'):
print('You pressed \'q\'... Quitting')
mainLoopFlag= False
break
|
Java | UTF-8 | 363 | 2.09375 | 2 | [
"MIT"
] | permissive | package com.veben.optionalnstream.domain;
import lombok.Getter;
@Getter
public class DefaultAvatar extends Avatar {
public static final String DEFAULT_URL = "defaultUrl";
public static final String DEFAULT_WORDING = "defaultWording";
public DefaultAvatar() {
this.gravatarUrl = DEFAULT_URL;
this.wording = DEFAULT_WORDING;
}
}
|
Markdown | UTF-8 | 2,510 | 2.59375 | 3 | [
"MIT"
] | permissive | ---
title: Waarom ’n voorhangsel?
date: 01/03/2022
---
Voorhangsels het ’n dubbeldoelige funksie. Die woord wat Hebreërs hier gebruik vir voorhangsel (katepetasma) kan verwys na die afskorting in die ingang van die voorhof
(Ex. 38:18), die afskorting vir die ingang [deur] van die buite-vertrek van die heiligdom (Ex. 36:37), of die binneste voorhangsel wat die heilige afdeling van die allerheiligste afdeling geskei het (Ex. 26:31–35). Hierdie voorhangsels het gedien as ingange en grense wat slegs sommiges toegelaat was om binne of verby te gaan.
`Lees Levitikus 16:1, 2 en Levitikus 10:1–3. Waaroor gaan die waarskuwings in hierdie gedeeltes?`
Die voorhangsel het beskerming gebied aan die priester soos hulle voor ’n heilige God bedien het. Na die volk se sonde van die aanbidding van die goue kalf, het die Here Moses meegedeel dat Hy nie saam met hulle sou trek op pad na die Beloofde Land toe nie; Hy sou hule verdelg, want hulle was “ ‘’n moedswillige volk’ ” (Ex. 33:3, NLV). Dus het Moses die tent van ontmoeting ver buite die kamp gaan opslaan (Ex. 33:7). Nadat Moses egter ingetree het, het God toegestem om saam te gaan en in hulle midde te bly (Ex. 33:12–20), maar Hy het sekere maatreëls daargestel om die volk te beskerm terwyl Hy in hulle midde gewoon het.
Israel het die tabernakel byvoorbeeld, volgens streng voorskrifte opgeslaan. Daar moes ’n vierkantige ruimte in die middel wees, waar die tabernakel opgeslaan moes word. Daarby, moes die Leviete rondom die tabernakel kamp opslaan om die heiligdom en die meublement te beskerm teen die indringing van vreemdelinge (Num. 1:51, Num. 3:10). Hulle het inderdaad gedien as ’n tipe menslike voorhangsel wat die volk van Israel moes beskerm: “ ‘maar die Leviete moet hulle tente rondom die tabernakel met die getuienis opslaan, sodat my toorn nie oor die Israelietekom nie. So moet die Leviete dan vir die tabernakel met di getuienis sorg’ ” (Num. 1:53, NLV).
As ons Hoëpriester, is Jesus ook ons voorhangsel. Deur Sy vleeswording, het God Sy tent in ons midde opgeslaan en dit vir ons moontlik gemaak om Sy heerlikheid te sien en te oordenk (Joh. 1:14–18). Hy het dit moontlik gemaak vir ’n heilige God om in die midde van ’n onvolmaakte volk te woon.
`Oordenk die betekenis van ’n Skepper-God (die Een wat die heelal geskape het), wat in Sy volk se midde wil woon – nogal ’n volk wat in daardie tyd almal ontsnapte slawe was. Wat leer dit ons oor hoe naby God aan ons wil wees?` |
C++ | UTF-8 | 1,519 | 3.953125 | 4 | [] | no_license | #include <iostream>
class A{
private:
static int ogolem;
public:
A(){
++ogolem;
std::cout<<"Utworzono obiekt A. Ogolnie:"<<ogolem<<std::endl;
}
~A(){
std::cout<<"Usuwam obiekt A. Utworzonych:"<<ogolem<<std::endl;
};
};
class B{
private:
static int obecnie;
public:
B(){
++obecnie;
std::cout<<"Utworzono obiekt B. Obecnie istnieje:"<<obecnie<<std::endl;
}
~B(){
--obecnie;
std::cout<<"Usuwam obiekt B. Pozostalo:"<<obecnie<<std::endl;
};
};
class Kolo{
private:
mutable float r;
static constexpr double pi=3.14159265358;
public:
Kolo(){
this->r=3;
std::cout<<"Kolo. Domyslny konstruktor. r=3"<<std::endl;
}
Kolo(float _r){
r=_r;
std::cout<<"Kolo. Konstruktor z parametrem. r="<<this->r<<std::endl;
}
void setr(const int &_r){
this->r=_r;
}
float getr() const{
return r;
}
float area() const{
return pi*r*r;
}
float perimeter() const{
return 2*pi*r;
}
static double zwrocPi(){
return pi;
}
~Kolo(){
std::cout<<"Destruktor kola"<<std::endl;
}
};
int A::ogolem=0;
int B::obecnie=0;
int main(){
A obiektyA[10];
A *p=new A[10];
delete[] p;
B obiektyB[10];
B *b=new B[10];
delete[] b;
std::cout<<"Pi jest rowne "<<Kolo::zwrocPi()<<std::endl;
return 0;
} |
Java | UTF-8 | 590 | 2.140625 | 2 | [] | no_license | package com.blocker.gameworld.domain;
import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
public class GameWorldTypeTest {
private RobotGameWorldType gt=new RobotGameWorldType();
@Test
public void getActionsTest() {
assertEquals (gt.getActions().size(),3);
}
@Test
public void getPredicatesTest() {
assertEquals(gt.getPredicates().size(),2);
}
@Test
public void createGameWorldInstanceTest() {
assertNotEquals(gt.createGameWorldInstance(),null);
}
}
|
Java | UTF-8 | 7,324 | 2.484375 | 2 | [] | no_license | package com.keenoor.toolkit.utils.httpclient;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLInitializationException;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Author: keenor
* Date: 2018/5/31
* Description: HttpClient 工具类
*/
public class HttpClientUtil {
private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
private static final Charset UTF_8 = Charset.forName("UTF-8");
private static final int CONNECT_TIMEOUT = 5_000;
private static final int REQUEST_TIMEOUT = 5_000;
private static final int SOCKET_TIMEOUT = 20_000;
private volatile static CloseableHttpClient httpClient;
private HttpClientUtil() {
}
private static CloseableHttpClient getHttpClient(String url) {
if (httpClient == null) {
synchronized (HttpClientUtil.class) {
if (httpClient == null) {
if (url.startsWith("https://")) {
try {
httpClient = new SSLClient();
} catch (KeyManagementException | NoSuchAlgorithmException e) {
e.printStackTrace();
throw new SSLInitializationException("new SSLClient error: ", e);
}
}else{
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(CONNECT_TIMEOUT)
.setConnectionRequestTimeout(REQUEST_TIMEOUT)
.setSocketTimeout(SOCKET_TIMEOUT)
.build();
httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
}
}
}
}
return httpClient;
}
public static String get(String url) throws RequestException {
return get(url, null);
}
public static String get(String url, Map<String, Object> params) throws RequestException {
// 创建Httpclient对象
CloseableHttpClient httpclient = getHttpClient(url);
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (params != null) {
for (Map.Entry<String, Object> entry : params.entrySet()) {
builder.addParameter(entry.getKey(), String.valueOf(entry.getValue()));
}
}
URI uri = builder.build();
logger.info("HTTP GET: {}", uri.toString());
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
// 执行请求
response = httpclient.execute(httpGet);
return handleResponse(response);
} catch (URISyntaxException | IOException e) {
logger.error("", e);
throw new ParseException();
} finally {
HttpClientUtils.closeQuietly(response);
}
}
public static String post(String url) throws RequestException {
return post(url, null);
}
public static String post(String url, Map<String, Object> params) throws RequestException {
logger.info("HTTP POST: {}", url);
if (params != null) {
logger.info("HTTP POST, params: {}", params);
}
// 创建Httpclient对象
CloseableHttpClient httpClient = getHttpClient(url);
CloseableHttpResponse response = null;
String resultString = "";
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (params != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (Map.Entry<String, Object> entry : params.entrySet()) {
paramList.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, UTF_8);
httpPost.setEntity(entity);
}
try {
// 执行 http 请求
response = httpClient.execute(httpPost);
return handleResponse(response);
} catch (IOException e) {
logger.error("", e);
throw new ParseException();
} finally {
HttpClientUtils.closeQuietly(response);
}
}
public static String postJson(String url, String json) throws RequestException {
logger.info("HTTP POST: {}", url);
if (StringUtils.isEmpty(json)) {
throw new IllegalArgumentException("the param String json is empty");
}
logger.info("POST PARAMS: {}", json);
// 创建Httpclient对象
CloseableHttpClient httpClient = getHttpClient(url);
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
return handleResponse(response);
} catch (IOException e) {
logger.error("", e);
throw new ParseException();
} finally {
HttpClientUtils.closeQuietly(response);
}
}
private static String handleResponse(HttpResponse response) throws RequestException {
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String result;
try {
result = EntityUtils.toString(response.getEntity(), UTF_8);
} catch (IOException e) {
logger.error("", e);
throw new ParseException();
}
logger.info("HTTP RESPONSE: {}", result);
return result;
} else {
throw new RequestException(response.getStatusLine());
}
}
} |
C | UTF-8 | 189 | 3.296875 | 3 | [] | no_license | #include <stdio.h>
main()
{
int x,a,b,c;
for(x=100;x<=999;x++)
{
a=x/100;
b=x%100/10;
c=x%10;
if(x==a*a*a+b*b*b+c*c*c)
printf("%d\n",x);
}
} |
C++ | UTF-8 | 2,252 | 2.84375 | 3 | [
"MIT"
] | permissive | #include <PRIZM.h>
PRIZM prizm;
void setup() {
prizm.PrizmBegin();
prizm.setMotorInvert(2,1); //the motors will go in opposite directions to move forward
prizm.setServoSpeed(1,25); //set servo speed 25%
//the code doesn't loop
}
void loop() {
//stop when something is in the way
if (prizm.readSonicSensorCM(3) >=10 ){
RobotOffRoad();
} else {
prizm.setMotorPowers (0,0);
}
}
void RobotOffRoad(){
//red light blinks to signal turn
prizm.setRedLED(HIGH);
delay(500);
prizm.setRedLED(LOW);
delay(500);
prizm.setRedLED(HIGH);
delay(500);
prizm.setRedLED(LOW);
delay(500);
//move forward for 1 seconds
prizm.setMotorPowers(25,25); //turns motor 1 and 2 on at 25% power
delay(500); //wait for .5 seconds while motors are spinning
//make the servo go up to signal turning
prizm.setServoPosition(1,90); //rotate to 90 degrees
delay(1000); //wait for 1 second
//drive forward
prizm.setMotorPowers(35,35); //turns motor 1 and 2 up to 35%
delay(200); //wait for 1.5
//turn right
prizm.setMotorPowers(10,25); //motor 1 spins at 10% power, motor 2 spins at 25% power
delay(1700); //wait for 1.7 seconds while motors are spinning
//move forwards for a hot sec
prizm.setMotorPowers(15,15); //move at 15% power
delay(300); //wait for .3 seconds while motors are spinning
//turning to the left
prizm.setMotorPowers(25,10); //motor 1 spins at 25% power, motor 2 spins at 10% power
delay(1500); //wait for 1.5 seconds while motors are spinning
//move forward slowly to a stop
prizm.setMotorPowers(25,25); //motor 1 and 2 slow down to 25% power
delay(700); //wait for .7 seconds while motors spin
//stops the robot completely
prizm.setMotorPowers(0,0); //make a complete stop
delay(800); //wait .8 seconds until next code
//make servo return to the normal poition
prizm.setServoPosition(1,-90); //rotate to -90 degrees
delay(1000);
//stop the code from looping
prizm.PrizmEnd(); //code stops
}
|
C# | UTF-8 | 3,234 | 2.828125 | 3 | [] | no_license | using System;
using System.Configuration;
using CastleGrimtol.Project;
namespace CastleGrimtol.Project {
public class Program {
public static void Main (string[] args) {
bool gameOver = false;
string userInput = "";
bool itemDropped = false;
bool doughnutUsed = false;
Game game = new Game ();
game.Setup ();
System.Console.Clear ();
// game.Intro ();
game.DrawHelp ();
while (!gameOver) {
userInput = game.Prompt ();
string command = userInput;
string options = "";
if (userInput.Contains (" ")) {
var parsedInput = userInput.Split (' ');
command = parsedInput[0];
options = parsedInput[1];
}
switch (command) {
case "go":
game.Go (options);
break;
case "use":
game.UseItem (options);
if (options == "doughnut") {
doughnutUsed = true;
}
break;
case "drop":
game.DontUseItem (options);
if (options == "red_rag" || options == "doughnut") {
itemDropped = true;
}
break;
case "look":
Console.Clear ();
game.CurrentRoom.GetDescription ();
break;
case "inventory":
System.Console.WriteLine ($@"
Player's Inventory
------------------");
if (game.CurrentPlayer.Inventory.Count > 0) {
foreach (Item itm in game.CurrentPlayer.Inventory) {
System.Console.WriteLine ($@" {itm.Name}");
}
} else {
System.Console.WriteLine ("No items available for use");
}
game.Prompt ();
break;
case "help":
game.DrawHelp ();
game.Prompt ();
break;
case "quit":
System.Console.WriteLine ($@"
\~~~~~~~~~~~~~~~~~~~~~~~~~~~\
\ Thanks for Playing! \
\~~~~~~~~~~~~~~~~~~~~~~~~~~~\
");
gameOver = true;
break;
default:
game.DrawHelp();
game.Prompt();
break;
}
if ((options == "red_rag" || options == "doughnut") && (itemDropped)) {
gameOver = true;
}
if (doughnutUsed) {
gameOver = true;
}
} //Main{
}
}
} |
Python | UTF-8 | 1,228 | 3.359375 | 3 | [] | no_license | #!/bin/python3
import math
import os
import random
import re
import sys
def IsLeapYear(year, category):
if category == 1:
if year % 4 == 0:
return True
if category == 2 or category == 3:
if year % 400 == 0 or year % 4 == 0 and not year % 100 == 0:
return True
return False
def findCategory(year):
if year >= 1700 and year <= 1917:
return 1
elif year == 1918:
return 2
else:
return 3
# Complete the dayOfProgrammer function below.
def dayOfProgrammer(year):
category = findCategory(year)
if category == 1:
if IsLeapYear(year, category):
return f"12.09.{year}"
else :
return f"13.09.{year}"
elif category == 2:
if IsLeapYear(year, category):
return f"12.10.{year}"
else:
return f"13.10.{year}"
elif category == 3:
if IsLeapYear(year, category):
return f"12.09.{year}"
else:
return f"13.09.{year}"
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
year = int(input().strip())
result = dayOfProgrammer(year)
fptr.write(result + '\n')
fptr.close()
|
Go | UTF-8 | 4,294 | 2.859375 | 3 | [
"MIT"
] | permissive | package util
import (
"fmt"
"math/rand"
"time"
"strconv"
)
var rs = rand.New(rand.NewSource(time.Now().UnixNano()))
type RandStruct struct{
randslice []string
index int
}
func (r *RandStruct) GetNext()(string){
r.index++
if(r.index >= len(r.randslice)){
r.index = 0
}
return r.randslice[r.index]
}
//randConfig:初始化长度,最小长度,最大长度,模式(0:小写字母,1:大写字母,2:数字,3:字母+数字,4:大小写字母,5:汉字,6:大写开头的字母)
func InitRand(randConfig map[string][4]string) map[string]*RandStruct{
fmt.Println(randConfig)
var randValueMap = make(map[string]*RandStruct)
for name,config := range randConfig{
initsize,_ := strconv.Atoi(config[0])
randValueMap[name]= &RandStruct{make([]string,initsize,initsize),-1};
for i:=0;i< initsize; i++{
randValueMap[name].randslice[i] = RandString(config[1],config[2],config[3])
}
//fmt.Println(randValueMap[name])
}
return randValueMap
}
//由于是采用的字符串相加的方式,效率不高,此工具采用的是事先初始化好一个不太长的随机串数组,需要用时从数组里循环取
func RandString(min string,max string, mod string) string{
lowers := "abcdefghijklmnopqrstuvwxyz"
uppers := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
digits := "0123456789"
alnums := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
alphas := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
chinese := "的一是在不了有和人这中大为上个国我以要他时来用们生到作地于出就分对成会可主发年动同工也能下过子说产种面而方后多定行学法所民得经十三之进着等部度家电力里如水化高自二理起小物现实加量都两体制机当使点从业本去把性好应开它合还因由其些然前外天政四日那社义事平形相全表间样与关各重新线内数正心反你明看原又么利比或但质气第向道命此变条只没结解问意建月公无系军很情者最立代想已通并提直题党程展五果料象员革位入常文总次品式活设及管特件长求老头基资边流路级少图山统接知较将组见计别她手角期根论运农指几九区强放决西被干做必战先回则任取据处队南给色光门即保治北造百规热领七海口东导器压志世金增争济阶油思术极交受联什认六共权收证改清己美再采转更单风切打白教速花带安场身车例真务具万每目至达走积示议声报斗完类八离华名确才科张信马节话米整空元况今集温传土许步群广石记需段研界拉林律叫且究观越织装影算低持音众书布复容儿须际商非验连断深难近矿千周委素技备半办青省列习响约支般史感劳便团往酸历市克何除消构府称太准精值号率族维划选标写存候毛亲快效斯院查江型眼王按格养易置派层片始却专状育厂京识适属圆包火住调满县局照参红细引听该铁价严龙飞"
dicts := map[string]string{"lowers":lowers,"uppers":uppers,"digits":digits,"alnums":alnums,"alphas":alphas,"chinese":chinese}
EnumMap := dataConfig.EnumlistMap
Enumlist,ok := EnumMap[mod]
min_size,_ := strconv.Atoi(min)
max_size,_ := strconv.Atoi(max)
result,n := "",min_size
if max_size > min_size {
n = rs.Intn(max_size-min_size+1)+ min_size
}
switch {
case mod == "lowers" || mod =="uppers" || mod =="digits" || mod =="alnums" || mod =="alphas":
length := len(dicts[mod])
for i:=0; i<n; i++{
result = result + string(dicts[mod][rs.Intn(length)])
}
case mod == "chinese":
length := len(chinese)
for i:=0; i<n; i++{
x := rs.Intn(length/3)
result = result + chinese[x*3:x*3+3] //汉字在utf-8里是占用3个byte的
}
case ok:
length := len(Enumlist)
result = Enumlist[rs.Intn(length)]
default : //默认是首字母大写,后面字母小写的方式
result = string(uppers[rs.Intn(26)])
for i:=1; i<n; i++{
result = result + string(lowers[rs.Intn(26)])
}
}
return result
} |
C++ | UTF-8 | 513 | 3.078125 | 3 | [] | no_license | #include<stdio.h>
using namespace std;
void swap(int& a,int &b)
{
int t=a;
a=b;
b=t;
}
void insertion_sort(int a[],int n)
{
for(int i=1; i<n; i++)
{
for(int j=i-1;j>=0;j--)
{
if(a[j+1]<a[j])swap(a[j+1],a[j]);
else break;
}
}
}
int main()
{
int a[100000];
int n;
scanf("%d",&n);
for(int i=0; i<n; i++)scanf("%d",&a[i]);
insertion_sort(a,n);
for(int i=0; i<n; i++)printf("%d ",a[i]);
printf("\n");
return 0;
}
|
JavaScript | UTF-8 | 1,049 | 2.875 | 3 | [] | no_license | var express = require('express');
var todos = require('./todos');
var bodyParser = require('body-parser');
var port = process.env.PORT || 3000;
var app = express();
app.use(bodyParser.json());
var getRandomId = function() {
return Math.random()
.toString(36)
.substr(7);
};
var addTodo = function(type, description) {
var newTodo = {
id: getRandomId(),
type: type,
description: description,
};
todos.push(newTodo);
};
// Endpoints
// List of existing todos
app.get('/', function(req, res){
res.send('<h1>Hello world !</h1>')
})
app.get('/todos', function(request, response) {
response.json(todos);
});
app.get('/secret', function(req,res){
res.send('secret !')
})
// Endpoints or Routes
// create a new todo
app.post('/todos', function(req, res) {
// extract the content from the body
var type = req.body.type;
var description = req.body.description;
addTodo(type, description);
res.status(201).end();
});
app.listen(port, function() {
console.log('Server is listening on port ' + port);
});
|
Shell | UTF-8 | 968 | 3.9375 | 4 | [] | no_license | #!/bin/bash
while getopts m: OPT
do
case $OPT in
m) message="$OPTARG" ;;
\?) echo "Usage : -m 'コミットメッセージ' パス" 1>&2
exit 1 ;;
esac
done
# オプション部分を切り捨てる。
shift `expr $OPTIND - 1`
if [ "$1" ]; then
path=$@
else
path='./'
fi
if [ "$message" ]; then
addstr=`svn st $path | grep -E '^\?' | sed -e s/"^?[ ]*"//`
if [ $addstr ]; then
svn add $addstr
fi
str=`svn st $path | grep -E "(php|phtml)" | sed -e s/"^.[ ]*"//`
svn diff $str
# syntax error がないかを確認
for f in `$str | grep -E "(php|phtml)" | sed -e s/"^.[ ]*"//`;do
sudo php -l $f
done
# echo $str"をコミットしますか : "
# read y
# if [[ $y = 'y' ]]; then
# echo "svn ci -m $message `echo $str`"
# svn ci -m "$message" `echo $str`
# fi
else
echo "コミットコメントを入力してください"
exit 1
fi
|
Java | UTF-8 | 8,765 | 2.546875 | 3 | [] | no_license | package servlets;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import database.DBConnector;
public class dataSearchServlet extends HttpServlet {
///Create an ArrayList to add checked boxes to
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
PrintWriter writer = response.getWriter();
response.setContentType("text/html");
Connection conn = new DBConnector().getConn();
String[] results = request.getParameterValues("checks");
writer.println("<html><head>\n" +
" <title>SEARCH</title>\n" +
" <link rel=\"stylesheet\" type=\"text/css\" href=\"css/style.css\">\n" +
"</head><body>");
writer.print("<header id=\"main-header\">\n" +
" <div class=\"container\">\n" +
" <h1><span style=\"background-color: black\">DRAG.DATA</span></h1>\n" +
" <H4><span style=\"background-color: black\">SEARCH</span></H4>\n" +
" </div>\n" +
"</header>");
writer.print("<nav id=\"navbar\">\n" +
" <div class=\"container\">\n" +
" <ul>\n" +
" <li><a href=\"index.jsp\">Home</a></li>\n" +
" <li><a href=\"specs.jsp\">Your Specs</a></li>\n" +
" <li><a href=\"track.jsp\">Tracks</a></li>\n" +
" <li><a href=\"logRun.jsp\">Log Run</a></li>\n" +
" <li><a href=\"dataSearch.jsp\">Search Data</a></li>\n" +
" <li><a href=\"photos.html\">Photos</a></li>\n" +
" </ul>\n" +
" </div>\n" +
"</nav>");
writer.print("<section id=\"showcase2\">\n" +
" <div class=\"container\">\n" +
" <br>");
writer.println("<form action = \"/searchResultsServlet\" method = \"POST\">");
for (int i = 0; i < results.length; i++) {
try {
if (results[i].equals("TRACK NAME:")) {
String sql = "SELECT * FROM track";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
writer.println("<label><span style=\"background-color: black\">TRACK NAME:</span></label><select>");
while (rs.next()) {
String trackName = rs.getString("track_name");
writer.print("<option name=\"fields\" value = \"" + trackName + "\">" + trackName + "</option>");
}
writer.print("</select></br>");
}
if (results[i].equals("LENGTH:")) {
writer.println("<label><span style=\"background-color: black\">TRACK LENGTH:</span></label><select>");
writer.print("<option name = \"fields\" value=\"1/8m\">1/8m</option>");
writer.print("<option name \"fields\" value=\"1/4m\">1/4m</option></select></br>");
}
if (results[i].equals("JETS:")) {
writer.print("<label><span style=\"background-color: black\">JETS:</span></label>");
writer.print("<input type=\"text\" name=\"jets\"></input></br>");
}
if (results[i].equals("SHIFT POINTS:")) {
writer.print("<label><span style=\"background-color: black\">SHIFT POINTS:</span></label>");
writer.print("<input type=\"text\" name=\"shiftPoints\"></input></br>");
}
if (results[i].equals("LAUNCH RPM:")) {
writer.print("<label><span style=\"background-color: black\">LAUNCH RPM:</span></label>");
writer.print("<input type=\"text\" name=\"launchRPM\"></input></br>");
}
if (results[i].equals("BACK TIRE PRESSURE:")) {
writer.print("<label><span style=\"background-color: black\">BACK TIRE PRESSURE:</span></label>");
writer.print("<input type=\"text\" name=\"tirePressure\"></input></br>");
}
if (results[i].equals("FUEL:")) {
writer.print("<label><span style=\"background-color: black\">FUEL:</span></label>");
writer.print("<input type=\"text\" name=\"fuel\"></input></br>");
}
if (results[i].equals("REACTION TIME:")) {
writer.print("<label><span style=\"background-color: black\">REACTION TIME:</span></label>");
writer.print("<input type=\"text\" name=\"reactionTime\"></input></br>");
}
if (results[i].equals("60 FT:")) {
writer.print("<label><span style=\"background-color: black\">60 FT:</span></label>");
writer.print("<input type=\"text\" name=\"60ft\"></input></br>");
}
if (results[i].equals("330 FT:")) {
writer.print("<label><span style=\"background-color: black\">330 FT:</span></label>");
writer.print("<input type=\"text\" name=\"330ft\"></input></br>");
}
if (results[i].equals("1/8 ET:")) {
writer.print("<label><span style=\"background-color: black\">1/8 ET:</span></label>");
writer.print("<input type=\"text\" name=\"1/8et\"></input></br>");
}
if (results[i].equals("1/8 MPH:")) {
writer.print("<label><span style=\"background-color: black\">1/8 MPH:</span></label>");
writer.print("<input type=\"text\" name=\"1/8mph\"></input></br>");
}
if (results[i].equals("1000 FT:")) {
writer.print("<label><span style=\"background-color: black\">1000 FT:</span></label>");
writer.print("<input type=\"text\" name=\"1000ft\"></input></br>");
}
if (results[i].equals("1/4 ET:")) {
writer.print("<label><span style=\"background-color: black\">1/4 ET:</span></label>");
writer.print("<input type=\"text\" name=\"1/4et\"></input></br>");
}
if (results[i].equals("1/4 MPH:")) {
writer.print("<label><span style=\"background-color: black\">1/4 MPH:</span></label>");
writer.print("<input type=\"text\" name=\"1/4mph\"></input></br>");
}
if (results[i].equals("TRACK TEMP:")) {
writer.print("<label><span style=\"background-color: black\">TRACK TEMP:</span></label>");
writer.print("<input type=\"text\" name=\"trackTemp\"></input></br>");
}
if (results[i].equals("AIR TEMP:")) {
writer.print("<label><span style=\"background-color: black\">AIR TEMP:</span></label>");
writer.print("<input type=\"text\" name=\"airTemp\"></input></br>");
}
if (results[i].equals("ATMOSPHERE:")) {
writer.print("<label><span style=\"background-color: black\">ATMOSPHERE:</span></label>");
writer.print("<input type=\"text\" name=\"atmosphere\"></input></br>");
}
if (results[i].equals("WIND DIRECTION:")) {
writer.print("<label><span style=\"background-color: black\">WIND DIRECTION:</span></label>");
writer.print("<select name=\"wind direction\">");
writer.print("<option value=\"N/A\">N/A</option>");
writer.print("<option value=\"Tail\">Tail</option>");
writer.print("<option value=\"Head\">Head</option></select></br>");
}
if (results[i].equals("WIND SPEED:")) {
writer.print("<label><span style=\"background-color: black\">WIND SPEED:</span></label>");
writer.print("<input type=\"text\" name=\"windSpeed\"></input></br>");
}
} catch (SQLException s){
writer.println(s.getErrorCode());
}
}
writer.print("</br><button type=\"submit\">Submit");
writer.println("</html></body>");
}
}
|
JavaScript | UTF-8 | 769 | 3 | 3 | [] | no_license | let restaurents=[{
name:'res1',
billAmt: 77
},{
name:'res2',
billAmt: 375
},{
name:'res3',
billAmt: 110
},{
name:'res4',
billAmt: 45
}];
let avg=0;
restaurents.map((object)=>{
switch(true){
case (object.billAmt<50):
object.tip = object.billAmt*0.20;
object.total=object.billAmt+object.tip;
break;
case (object.billAmt>=50 && object.billAmt<200) :
object.tip=object.billAmt*0.15;
object.total=object.billAmt+object.tip;
break;
default :
object.tip=object.billAmt*0.10;
object.total=object.billAmt+object.tip;
}
avg += object.total;
console.log(object);
});
console.log("Average is : "+(avg/restaurents.length)) |
Java | UTF-8 | 6,368 | 2.140625 | 2 | [] | no_license | package backup;
import java.io.FileReader;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import algorithm.Settings;
import spatialindex.rtree.RTree;
import spatialindex.spatialindex.ISpatialIndex;
import spatialindex.spatialindex.Point;
import spatialindex.spatialindex.Region;
import spatialindex.storagemanager.DiskStorageManager;
import spatialindex.storagemanager.IBuffer;
import spatialindex.storagemanager.IStorageManager;
import spatialindex.storagemanager.PropertySet;
import spatialindex.storagemanager.RandomEvictionsBuffer;
public class BuildGridRtree {
public static void main(String[] args)throws Exception
{
//location_file format:
//one object per line,
//each line: id,x,y
// integer,double,double
String index_file = Settings.rtree_index_location;
int page_size = 4096;
int fanout = Settings.size;
String location_file = Settings.points_location;
LineNumberReader location_reader = new LineNumberReader(new FileReader(location_file));
// Create a disk based storage manager.
PropertySet ps = new PropertySet();
Boolean b = new Boolean(true);
ps.setProperty("Overwrite", b);
//overwrite the file if it exists.
ps.setProperty("FileName", index_file + ".grid");
// .idx and .dat extensions will be added.
Integer p = new Integer(page_size);
ps.setProperty("PageSize", p);
// specify the page size. Since the index may also contain user defined data
// there is no way to know how big a single node may become. The storage manager
// will use multiple pages per node if needed. Off course this will slow down performance.
IStorageManager diskfile = new DiskStorageManager(ps);
// Create a new, empty, RTree with dimensionality 2, minimum load 70%
PropertySet ps2 = new PropertySet();
Double f = new Double(0.7);
ps2.setProperty("FillFactor", f);
p = new Integer(fanout);
ps2.setProperty("IndexCapacity", p);
ps2.setProperty("LeafCapacity", p);
// Index capacity and leaf capacity may be different.
p = new Integer(2);
ps2.setProperty("Dimension", p);
RTree tree = new RTree(ps2, diskfile);
int count = 0;
int id = 1;
HashMap<Integer, String> hash = new HashMap<Integer, String>();
double min_lat = Settings.min_lat;
double max_lat = Settings.max_lat;
double min_lng = Settings.min_lng;
double max_lng = Settings.max_lng;
double x1, x2, y1, y2, lat, lng;
double[] f1 = new double[2];
double[] f2 = new double[2];
String line;
String[] temp;
ArrayList<Region> zordered_mbrs = new ArrayList<Region>();
ArrayList<Region> mbrs = new ArrayList<Region>();
ArrayList<Integer> order = new ArrayList<Integer>();
int j = 0;
int i = 0;
double len = 1/(double)Settings.dimension;
for (int k = 0; k < Settings.size; k++) {
order.add(0);
zordered_mbrs.add(null);
double []pLow = {i*len, 1-(j+1)*len};
double []pHigh = {(i+1)*len, 1-(j*len)};
Region tmp = new Region(pLow, pHigh);
mbrs.add(tmp);
i++;
if(i==Settings.dimension){
i = 0;
j++;
}
}
z_curve(order, 0, 0, 0, Settings.size, Settings.dimension);
for (int k = 0; k < order.size(); k++) {
zordered_mbrs.set(order.get(k)-1, mbrs.get(k));
}
/*
while ((line = location_reader.readLine()) != null)
{
temp = line.split(",");
y1 = (Double.parseDouble(temp[0]) - min_lat)/(max_lat - min_lat);
x1 = (Double.parseDouble(temp[1]) - min_lng)/(max_lng - min_lng);
f1[0] = x1; f1[1] = y1;
f2[0] = x1; f2[1] = y1;
Region r = new Region(f1, f2);
tree.insertData(null, r, id);
id++;
if ((count % 1000) == 0) System.err.println(count);
count++;
}
*/
//System.out.println("Z curve: " + zordered_mbrs.size());
int c = 0;
while ((line = location_reader.readLine()) != null)
{
temp = line.split(",");
//id = Integer.parseInt(temp[0]);
lat = Double.parseDouble(temp[0]);
lng = Double.parseDouble(temp[1]);
y1 = (lat - min_lat)/(max_lat - min_lat);
x1 = (lng - min_lng)/(max_lng - min_lng);
f1[0] = x1; f1[1] = y1;
Point p1 = new Point(f1);
for (int k = 0; k < zordered_mbrs.size(); k++) {
if(zordered_mbrs.get(k).contains(p1)){
if(hash.containsKey(k)){
String tmp = hash.get(k);
hash.put(k, tmp+","+lat+","+lng);
}
else{
hash.put(k, lat+","+lng);
}
break;
}
}
c++;
}
System.out.println("C: "+c + " Hash: "+ hash.size());
for (Map.Entry<Integer, String> entry : hash.entrySet()) {
tree.insertData(entry.getValue().getBytes(), zordered_mbrs.get(entry.getKey()), id);
id++;
if ((count % 1000) == 0) System.err.println(count);
count++;
}
System.err.println("Operations: " + count);
System.err.println(tree);
// since we created a new RTree, the PropertySet that was used to initialize the structure
// now contains the IndexIdentifier property, which can be used later to reuse the index.
// (Remember that multiple indices may reside in the same storage manager at the same time
// and every one is accessed using its unique IndexIdentifier).
Integer indexID = (Integer) ps2.getProperty("IndexIdentifier");
System.err.println("Index ID: " + indexID);
boolean ret = tree.isIndexValid();
if (ret == false) System.err.println("Structure is INVALID!");
// flush all pending changes to persistent storage (needed since Java might not call finalize when JVM exits).
tree.flush();
location_reader.close();
}
public static void z_curve(ArrayList<Integer> curve, int offset, int i, int j, int size, int dimension){
if(size == 4){
curve.set(i*dimension+j, offset+1);
curve.set(i*dimension+(j+1), offset+2);
curve.set((i+1)*dimension+j , offset+3);
curve.set((i+1)*dimension+(j+1), offset+4);
}
else{
int inc = (int)Math.sqrt(size/4);
z_curve(curve, offset, i, j, size/4, dimension);
z_curve(curve, offset + size/4, i, j+inc, size/4, dimension);
z_curve(curve, offset + size/2, i+inc, j, size/4, dimension);
z_curve(curve, offset + size*3/4, i+inc, j+inc, size/4, dimension);
}
}
}
|
Markdown | UTF-8 | 4,310 | 2.609375 | 3 | [] | no_license | ###### Bye-bye, Bouteflika
# Algeria’s ex-president is dead, but his regime lives on
##### To the dismay of many Algerians

> Sep 25th 2021
FINALLY THE rumours are true. For years Algerians whispered about the health of Abdelaziz Bouteflika, their president from 1999 to 2019. After suffering a stroke in 2013 he was rarely seen in public, often leading to speculation that he was dead. When the whispers grew too loud, officials would roll him out in his wheelchair to sit before the cameras, a vacant look in his eyes. The people wondered who was really in charge. By 2019 they had had enough of the charade and toppled the old man.
Mr Bouteflika died on September 17th, aged 84. The young people who make up most of Algeria’s population will probably remember him as that decrepit president—and lament that little has changed since his ousting. It is telling that the government buried him at a cemetery for independence fighters, with few of the honours accorded to past leaders.
Older Algerians may remember Mr Bouteflika more fondly. He was barely an adult when he joined the National Liberation Army in the war against French rule. A year after independence in 1962, he became Algeria’s first foreign minister, still in his mid-20s. He would hold the position for 16 years. Witty and dashing in his three-piece suits, Mr Bouteflika helped establish the country as an influential member of the Non-Aligned Movement and a beacon of the anti-colonial struggle, earning it the nickname “the Mecca of revolutionaries”.
Che Guevara visited Algeria hoping to stir revolutions in Africa. A young Nelson Mandela received military training from Algerian soldiers. Mr Bouteflika, in the role of president of the UN General Assembly, invited Yasser Arafat to address the body in 1974, a historic moment for the Palestinian cause. When Carlos the Jackal took oil ministers hostage in an attack on OPEC headquarters in Vienna in 1975, the terrorist demanded to be flown to Algiers. Mr Bouteflika met him and negotiated the release of some of the hostages.
Passed over for the presidency in 1979, Mr Bouteflika left Algeria to avoid corruption charges (which were eventually dropped). He returned but kept a low profile during Algeria’s civil war in the 1990s, when some 200,000 people were killed in fighting between Islamists and the army. In 1999 the ruling cabal of generals and security men, known as le pouvoir (the power), turned to him. Five months after winning a rigged presidential election, Mr Bouteflika pushed through a referendum on national reconciliation that granted amnesty to Islamists and militia members. Criticism of the army’s conduct was prohibited. Many credit him for guiding Algeria out of its “black decade”.
The regime would invoke the civil war and the need for stability whenever it wanted to justify its repression. Unfair elections were held—Mr Bouteflika won four of them. Le pouvoir siphoned off the country’s vast hydrocarbon wealth, while the young struggled to find jobs. The public’s frustration had been growing for years when the regime announced in 2019 that Mr Bouteflika would seek a fifth term. Tens of thousands of protesters took to the streets, chanting “Bye-bye, Bouteflika”. Finally the regime gave in. Slumped in his wheelchair, the president passed his letter of resignation to a colleague. It was the last time most of the public would see him.
Yet any hope that Mr Bouteflika’s resignation would bring real change has dimmed. The army remains the dominant power in Algeria. Abdelmadjid Tebboune, a former prime minister seen as the generals’ choice, was elected president in 2019. The poll was shunned by most Algerians. Meanwhile, the number of political prisoners is thought to be rising. The government has tried to sow discord in the pro-democracy movement, known as the Hirak. It blames opposition groups and Morocco, with which it recently cut diplomatic ties, for fomenting unrest.
Sometimes the government still uses Mr Bouteflika, but now as a scapegoat. Covid-19 has taken a toll and the economy continues to stall. With few answers, officials also point to the villainy of France or other foreign conspirators. Most Algerians, born after independence, are unmoved by these tired anti-colonial narratives. They wish Mr Bouteflika’s regime would expire with him. ■
|
Python | UTF-8 | 2,415 | 2.84375 | 3 | [] | no_license |
from flask import Flask
from pprint import pprint
#データの追加や更新が上手くいっているかチェックする
class CheckDatabase():
def __init__(self):
pass
@classmethod
#参加申請データの更新が上手くいっているかチェック
def is_entry_updated_correctly(cls, db, Entry, practice_id: int, member_id: int, condition_id: int):
if practice_id is None or practice_id == 0: return False
if member_id is None or member_id == 0: return False
entry = db.session.query(
Entry.condition_id
).filter(
Entry.practice_id == practice_id
).filter(
Entry.member_id == member_id
).all()
#指定したcondition_idの値と同じかどうかで判断
for item in entry:
return condition_id == item[0]
@classmethod
#参加申請データの追加が上手くいっているかチェック
def is_entry_added_correctly(cls, db, Entry, practice_id: int, member_id: int) -> bool:
if practice_id is None or practice_id == 0: return False
if member_id is None or member_id == 0: return False
entry = db.session.query(
Entry.condition_id
).filter(
Entry.practice_id == practice_id
).filter(
Entry.member_id == member_id
).first()
return not entry is None
@classmethod
#メンバー一時テーブルへの追加が上手くいっているかチェック
def is_member_tmp_added_correctly(cls, db, MemberTmp, mail: str, token: str, password: str) -> bool:
if mail is None or mail == '': return False
if token is None or token == '': return False
if password is None or password == '': return False
member_tmp = db.session.query(
MemberTmp.id
).filter(
MemberTmp.mail == mail
).filter(
MemberTmp.token == token
).filter(
MemberTmp.password == password
).first()
pprint(member_tmp)
return not member_tmp == () and not member_tmp is None
@classmethod
#メンバーテーブルへの追加が上手くいっているかチェック
def is_member_added_correctly(cls, db, Member, name: str, mail: str, password: str) -> bool:
if name is None or name == '': return False
if mail is None or mail == '': return False
if password is None or password == '': return False
member = db.session.query(
Member.id
).filter(
Member.name == name
).filter(
Member.mail == mail
).filter(
Member.password == password
).first()
return not member == () and not member is None
|
TypeScript | UTF-8 | 1,779 | 2.65625 | 3 | [] | no_license | import { Component } from "@angular/core";
import { Dice } from "../../common/dice/dice.service";
import { MagicService } from "../../common/magic/magic.service";
import { Constants } from "../../utils/constants";
import { names } from "./names.db";
@Component({
selector: "player-adventuring",
styleUrls: ["./adventuring.component.scss"],
templateUrl: "./adventuring.component.html"
})
export class AdventuringComponent {
public spell: string;
public name: string;
public lastName: string;
public domicile: string;
public numberOfRolls = Array.from(Array(10).keys())
public additions = Array.from(Array(11).keys())
public dices = Constants.dice.filter(a => a !== "None")
public rollCount = 1;
public selectedDice = "d4";
public selectedAddition = 0;
public result = 0;
public finalDice = "1d4+0"
public getSpell(): void {
this.spell = new MagicService().getMagic();
}
public getRandomName(race: string): void {
this.name = names[race][Math.floor(Math.random() * (names[race].length))];
this.lastName = names["otherLastName"][Math.floor(Math.random() * (names["otherLastName"].length))];
}
public getDomicileName(): void {
this.domicile = names["innShipTavern"][Math.floor(Math.random() * (names["innShipTavern"].length))];
}
public onNumberOfRollClick(number: number): void {
this.rollCount = number
}
public onDiceClick(dice: string): void {
this.selectedDice = dice
}
public onAdditionClick(addition: number): void {
this.selectedAddition = addition
}
public onRoll(): void {
const die = new Dice()
this.finalDice = `${this.rollCount}${this.selectedDice}+${this.selectedAddition}`
const roll = die.roll(this.finalDice)
this.result = roll.modifiedRollValue
}
}
|
C | UTF-8 | 5,227 | 3.765625 | 4 | [] | no_license | #include "List1A.h"
#include "structPCB.h"
#include <stdlib.h>
#include <stdio.h>
//Documentation: If anyone wishes to use popFront(), popBack(), getFront(), or getBack(), they must first call isEmpty() and receive a boolean true
//initialize the list with the header pointing at itself
void initializeList(List *listPtr)
{
*listPtr = (List)malloc(sizeof(NodeType));
(*listPtr)->next = *listPtr;
(*listPtr)->prev = *listPtr;
}
//return true if the only element on the list is the header
//otherwise return false
bool isEmpty(const List list)
{
if((list->next == list) && (list->prev == list))
return true;
else
return false;
}
//Remove all elements including the header from the list
//set the List to null
void clearList(List listPtr)
{
List *Ptr = &listPtr;
if(!(isEmpty(listPtr)))
freeList(Ptr);
if(isEmpty(listPtr) && (listPtr != NULL))
{
listPtr = NULL;
free(listPtr);
}
}
//Remove all elements except the header from the list
//Leave the list in an empty state.
void freeList(List *listPtr)
{
if(!isEmpty((*listPtr)))
{
while((*listPtr)->next != (*listPtr)->prev)
popFront(*listPtr);
popFront(*listPtr);
}
}
//Add the value to the front of the list
void pushFront(const List list, ListInfo value)
{
List newNode = (List)malloc(sizeof(NodeType));
newNode->info = value;
newNode->next = list->next;
newNode->prev = list;
list->next = newNode;
newNode->next->prev = newNode;
}
//Add the value to the back of the list
void pushBack(const List list, ListInfo value)
{
if(isEmpty(list))
{
pushFront(list, value);
}
else
{
List newNode = (List)malloc(sizeof(NodeType));
newNode->info = value;
newNode->next = list;
newNode->prev = list->prev;
newNode->prev->next = newNode;
newNode->next->prev = newNode;
}
}
//must use sizeOfList first to ensure position exists
//Add the value to the list at specified index
void push(const List list, int pos, ListInfo value)
{
if(isEmpty(list))
{
pushFront(list, value);
}
else
{
List newNode = (List)malloc(sizeof(NodeType));
newNode->info = value;
List temp = getElement(list, pos);
newNode->next = temp;
newNode->prev = temp->prev;
newNode->prev->next = newNode;
newNode->next->prev = newNode;
temp = NULL;
}
}
//Remove and return the value at the front of the list
ListInfo popFront(const List list)
{
ListInfo val = list->next->info;
List temp = list->next;
list->next = list->next->next;
list->next->prev = list;
free(temp);
return val;
}
//Remove and return the value at the back of the list
ListInfo popBack(const List list)
{
ListInfo val = list->prev->info;
List temp = list->prev;
list->prev = list->prev->prev;
list->prev->next = list;
free(temp);
return val;
}
//must use sizeOfList first to ensure position exists
//Remove value from list at specified index
ListInfo pop(const List list, int pos)
{
List temp = getElement(list, pos);
ListInfo val = temp->info;
temp->next->prev = temp->prev;
temp->prev->next = temp->next;
free(temp);
return val;
}
//Return true if the value appears in the list,
//otherwise return false
//bool findInList(const List list, ListInfo value)
bool findInList(const List list, int value)
{
List temp = list->next;
while(temp != list)
{
//if(temp->info == value)
if(temp->info.pid == value)
{
temp = NULL;
return true;
}
temp = temp->next;
}
temp = NULL;
return false;
}
//Return the size of the list
int sizeOfList(const List list)
{
List temp = list->next;
int count = 0;
while(temp != list)
{
//if(temp->info == value)
if(temp->info.pid != NULL)
count++;
temp = temp->next;
}
temp = NULL;
return count;
}
//Return the size of the list
int sizeOfFreeSpaceList(const List list)
{
List temp = list->next;
int count = 0;
while(temp != list)
{
//if(temp->info == value)
if(((temp->info.SA) || (temp->info.RS)) != NULL)
count++;
temp = temp->next;
}
temp = NULL;
return count;
}
//Return the value at the front of the list
ListInfo getFront(const List list)
{
return list->next->info;
}
//Return the value at the back of the list
ListInfo getBack(const List list)
{
return list->prev->info;
}
//must use sizeOfList first to ensure position exists
//Return the value at the specified index of the list
List getElement(const List list, int pos)
{
List temp = list->next;
int count = 0;
while(temp != list)
{
if(count == pos)
return temp;
count++;
temp = temp->next;
}
temp = NULL;
}
|
C++ | UTF-8 | 336 | 2.671875 | 3 | [] | no_license | #ifndef MUTANTSTACK_HPP
#define MUTANTSTACK_HPP
#include <stack>
template < typename T >
class MutantStack : public std::stack<T>{
public:
typedef typename std::stack<T>::container_type::iterator iterator;
iterator begin(){ return (std::stack<T>::c.begin()); };
iterator end(){ return (std::stack<T>::c.end()); };
};
#endif
|
Python | UTF-8 | 5,250 | 3.234375 | 3 | [] | no_license | from numpy import random
from colors import Colors
import pygame as pg
import numpy as np
import itertools
class Env(object):
def __init__(self, width, height, dim):
self.__screen = pg.display.set_mode((width, height))
self.__length = 30
self.__step = 75
self.__dim = dim
self.__n = dim - 4
self.__color = itertools.cycle((Colors.WHITE, Colors.BLACK))
self.__board_length = self.__dim * self.__step
self.__X = (width - self.__board_length) / 2
self.__Y = (height - self.__board_length) / 2
self.__pieces, self.__obst = self.__createPieces()
self.__background = self.__drawBoard()
def __drawBoard(self):
background = pg.Surface((self.__board_length, self.__board_length))
for y in range(0, self.__board_length, self.__step):
for x in range(0, self.__board_length, self.__step):
rect = (x, y, self.__step, self.__step)
pg.draw.rect(background, next(self.__color), rect)
next(self.__color)
return background
def __pos2coord(self, row, col):
x = (self.__step / 2) + row * self.__step + self.__X - self.__length / 2
y = (self.__step / 2) + col * self.__step + self.__Y - self.__length / 2
return x, y
def __createPieces(self):
rects1 = []
rects2 = []
if self.__dim - self.__n == 4:
c_range = range(self.__dim - self.__n, self.__dim)
r_range = range(0, self.__n)
for c in c_range:
for r in r_range:
x, y = self.__pos2coord(r, c)
rect = pg.rect.Rect(x, y, self.__length, self.__length)
rects1.append(rect)
k = 0
mem = []
while k < 2*self.__n:
r = random.randint(self.__dim - 1)
c = random.randint(self.__dim - 1)
if (not ((c in c_range and r in r_range) or (c in r_range and r in c_range))):
if ((r, c) not in mem):
mem.append((r, c))
x, y = self.__pos2coord(r, c)
rect = pg.rect.Rect(x, y, self.__length, self.__length)
rects2.append(rect)
k += 1
return rects1, rects2
def reset(self):
self.__pieces, self.__obst = self.__createPieces()
state = self.__get_state()
return state
def __done(self):
temp_id = 1
x = self.__pieces[temp_id].x
y = self.__pieces[temp_id].y
return (x >= self.__step*(self.__dim-self.__n) + self.__X and y <= self.__step*self.__n + self.__Y)
def move(self, id, action):
if (id < 0 or id > (2*self.__n - 1)):
return
rest_pieces = [item for i, item in enumerate(self.__pieces) if i not in [id]] + self.__obst
if action == 0:
for item in rest_pieces:
if (item.x == self.__pieces[id].x - self.__step and item.y == self.__pieces[id].y or
self.__pieces[id].x - self.__step < self.__X):
return
self.__pieces[id].x -= self.__step
elif action == 1:
for item in rest_pieces:
if (item.x == self.__pieces[id].x + self.__step and item.y == self.__pieces[id].y or
self.__pieces[id].x + self.__step > self.__board_length + self.__X):
return
self.__pieces[id].x += self.__step
elif action == 2:
for item in rest_pieces:
if (item.y == self.__pieces[id].y - self.__step and item.x == self.__pieces[id].x or
self.__pieces[id].y - self.__step < self.__Y):
return
self.__pieces[id].y -= self.__step
elif action == 3:
for item in rest_pieces:
if (item.y == self.__pieces[id].y + self.__step and item.x == self.__pieces[id].x or
self.__pieces[id].y + self.__step > self.__board_length + self.__Y):
return
self.__pieces[id].y += self.__step
def __get_state(self):
temp_id = 1
pieces_pos = [self.__pieces[temp_id].x, self.__pieces[temp_id].y]
obst_pos = np.array([[item.x, item.y] for item in self.__obst]).flatten()
state = pieces_pos + list(obst_pos)
return state
def drawPieces(self, color1, color2):
for rect in self.__pieces:
pg.draw.rect(self.__screen, color1, rect)
for rect in self.__obst:
pg.draw.rect(self.__screen, color2, rect)
def step(self, action):
temp_id = 1
reward = 0
if (action == 0 or action == 3):
reward -= 4
else:
reward += 4
self.move(temp_id, action)
state = self.__get_state()
done = self.__done()
return reward, state, done
def vars(self):
return self.__screen, self.__background, self.__X, self.__Y
@property
def state_space(self):
return self.__n*8
@property
def action_space(self):
return 4
|
PHP | UTF-8 | 2,771 | 2.53125 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
/**
* Acamar-SkeletonApplication
*
* @link https://github.com/brian978/Acamar-SkeletonApplication
* @copyright Copyright (c) 2014
* @license https://github.com/brian978/Acamar-SkeletonApplication/blob/master/LICENSE New BSD License
*/
namespace Application\Model\Table\Maps;
use Acamar\Model\Mapper\MapCollection;
/**
* Class BooksMaps
*
* @package Application\Model\Table\Maps
*/
class BooksMaps extends MapCollection
{
const MAP_BOOK = 'book';
const MAP_BOOK_DB_SAVE = 'bookDbSave';
/**
* An array representing the data in the collection
*
* @var array
*/
protected $collection = [
self::MAP_BOOK => [
'entity' => '\Application\Model\Book',
'identField' => 'id',
'specs' => [
'id' => 'id',
'title' => 'title',
'isbn' => 'isbn',
'publisherId' => [
'toProperty' => 'publisher',
'map' => 'joinedPublisher'
],
'authorId' => [
'toProperty' => 'author',
'map' => 'joinedAuthor'
]
]
],
self::MAP_BOOK_DB_SAVE => [
'entity' => '\Application\Model\Book',
'identField' => 'id',
'specs' => [
'id' => 'id',
'title' => 'title',
'isbn' => 'isbn',
'publisherId' => [
'toProperty' => 'publisher',
'map' => 'saveJoinedPublisher'
],
'authorId' => [
'toProperty' => 'author',
'map' => 'saveJoinedAuthor'
]
]
],
'joinedPublisher' => [
'entity' => '\Application\Model\Publisher',
'identField' => 'publisherId',
'specs' => [
'publisherId' => 'id',
'publisherName' => 'name'
]
],
'joinedAuthor' => [
'entity' => '\Application\Model\Author',
'identField' => 'authorId',
'specs' => [
'authorId' => 'id',
'authorFirstName' => 'firstName',
'authorLastName' => 'lastName',
]
],
'saveJoinedPublisher' => [
'entity' => '\Application\Model\Publisher',
'identField' => 'publisherId',
'specs' => [
'publisherId' => 'id',
]
],
'saveJoinedAuthor' => [
'entity' => '\Application\Model\Author',
'identField' => 'authorId',
'specs' => [
'authorId' => 'id',
]
]
];
}
|
JavaScript | UTF-8 | 824 | 2.53125 | 3 | [] | no_license | define([
'mustache',
'text!content/talks/index.html',
'text!content/talks/mastering-javascript/prototypal-inheritance.html',
'text!content/talks/classical-inheritance-vs-modular-patterns.html'
], function(mustache, html) {
var args = [].slice.call(arguments, 2),
output = {
talks: []
},
$aux = $('<div>'),
$auxTitle,
title,
content,
url;
for(var i = 0, len = args.length; i < len; i++) {
$aux.html(args[i]);
$auxTitle = $('h1:first', $aux);
title = $auxTitle.text();
url = $auxTitle.data('url');
content = [];
$('.readmore', $aux).each(function() {
content.push( $(this).html() );
});
output.talks.push({
title: title,
url: url,
content: _.clone(content)
});
}
return {
title: 'Talks',
html: mustache.render(html, output),
tpl: html,
posts: output
};
});
|
Markdown | UTF-8 | 3,229 | 3.28125 | 3 | [] | no_license | ##### Linux命令--用户、权限管理
###### whoami
- 查看当前系统当前账号的用户名。可通过 cat /etc/passwd 查看系统用户信息
###### ifconfig 查看网络状态、查看IP地址、配置网络
- windows 中使用 ipconfig
- 关闭网卡:ifconfig ens33 down
- 开启网卡:ifconfig ens33 up
- 更改IP地址:ifconfig ens33 IP地址(192.168.0.5)
###### ping
- ping 192.168.0.4 测试网络连接是否正常
###### ssh 远程登陆
- ssh ubuntu@192.168.0.4
- ssh 用户名@IP
###### who
- 查看当前登陆用户的信息
- who -m或am 只显示运行 who 命令的用户名、登陆终端和登陆时间
- who -q或--count 只显示用户的登陆账号和登陆用户的数量
- who -u或--heading 只显示列标题
###### exit
- 远程登陆退出或者终端退出或者退出超级账户
###### useradd
- 添加用户账号
- 使用格式:useradd [参数] 新建用户账号
- 常用选项:
- useradd -d 指定用户登录系统是的主目录,如果不是用此参数,系统自动在 /home 目录下建立与用户名同名目录为主目录
- useradd -m 自动建立目录
- useradd -g 指定组目录
- 例如: sudo useradd 新用户名 -m -d /home/新用户名
###### passwd
- 设置用户密码
- 在 Unix/Linux 中,**超级用户**可以使用 passwd 命令为普通用户设置或修改用户密码。用户也可以直接使用该命令来修改自己的密码,而无需在命令后面使用用户名。
###### userdel
- 删除用户
- userdel abc(用户名) 删除 abc 用户,但不会自动删除用户的主目录
- userdel -r abc(用户名) 删除 abc 用户,同时删除用户的主目录
- 例如:sudo userdel -r 用户名
###### su
- 切换用户
- 可以通过 su 命令来切换用户,su 后面可以加 “-”。su 和 su - 命令的不同之处在于,su - 切换到对应的用户时会将当前的工作目录自动转换到且皇后的用户主目录。
- su 需要切换的用户名
- su - 需要切换的用户名,切换用户后,还会主动跳转到该用户的家目录
###### sudo
- 当需要超级管理员的权限时需要添加,并且在命令行的最前面,后面需要添加空格
- sudo -s 表示:直接切换到 root 用户
- 输入 exit 命令退出到普通用户
###### 查看有那些用户组
- 方法一:cat /etc/group
- 方法二:groupmod + 三次Tab键
###### groupadd \ groupdel
- 添加、删除用户组
- groupadd 新建组账号
- groupdel 删除组账号
- cat /etc/group 查看用户组
###### usermod
- 修改用户所在组
- 使用方法:sudo usermod -g 用户组 用户名 表示:将用户名修改到用户组里面去
- 使用方法:sudo usermod -a -G 用户组 用户名 表示:将用户名添加到用户组里面去
- 注意:上面命令中 -g 后面的组一般是默认的主要组,-G 一般配合‘-a’开完成向其他组添加(表示只是这个组的成员而已)
###### 添加权限
- 为创建的普通用户添加 sudo 权限(就是给一般用户添加超级管理员权限)新创建的用户,默认不能 sudo,需要进行一下操作
- sudo usermod -a -G adm 用户名
- sudo udermod -a -G sudo 用户名
|
C# | UTF-8 | 905 | 2.8125 | 3 | [
"Apache-2.0"
] | permissive | using System.Linq;
using System.Collections.Generic;
using Sep.Git.Tfs.Core.TfsInterop;
namespace Sep.Git.Tfs.Core.BranchVisitors
{
public class BranchTreeContainsPathVisitor : IBranchTreeVisitor
{
private string searchPath;
private bool searchExactPath;
public BranchTreeContainsPathVisitor(string searchPath, bool searchExactPath)
{
this.searchPath = searchPath;
this.searchExactPath = searchExactPath;
}
public bool Found { get; private set; }
public void Visit(BranchTree childBranch, int level)
{
if (Found == false
&& ((searchExactPath && searchPath.ToLower() == childBranch.Path.ToLower())
|| (!searchExactPath && searchPath.ToLower().IndexOf(childBranch.Path.ToLower()) == 0)))
{
Found = true;
}
}
}
} |
Java | UTF-8 | 599 | 1.914063 | 2 | [] | no_license | package VoidMain;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import backEnd.BDD;
import backEnd.Usuario;
import frame_Principal.FramePrincipal;
import frames.FrameLogin;
import frames.FrameMovimentacao;
import frames.FrameNewUsuario;
public class teste {
public static void main(String[] args) {
new FrameLogin();
System.out.println(FramePrincipal.getAno());
System.out.println(FramePrincipal.getMes());
//new FramePrincipal(1);
//new FrameNewUsuario();
//new FrameMovimentacao();
}
}
|
Java | UTF-8 | 143 | 1.945313 | 2 | [] | no_license | public class ObjectiveLab1{
public static void main(String[] args){
System.out.println("Andrew Conlin"); //Using println instead of print
}
}
|
Markdown | UTF-8 | 5,199 | 2.8125 | 3 | [] | no_license | # Reproducible Research: Peer Assessment 1
This report contains the analysis of activity monitoring data obtained from wearable devices. The data is obtained from https://github.com/engr3os/RepData_PeerAssessment1.
Before processing the data we will first include the R packages required for our analysis, set the working directory and read in the data of interest.
## Loading and preprocessing the data
```r
require(lubridate)
require(lattice)
setwd("~/ML_R/RepData_PeerAssessment1")
activity_dat <- read.csv("Activity/activity.csv", colClasses = c("numeric","factor", "factor"))
```
## What is mean total number of steps taken per day?
In order to conduct basic exploratory data analysis, we will take a look at the histogram of the total number of steps taken perday.
```r
dailySteps <- tapply(activity_dat$steps, activity_dat$date, sum, na.rm = T)
hist(dailySteps, col = "red", breaks = 10)
```

```
## [1] "Figure 1. The histogram of the total daily number of steps"
```
The mean and median total number of steps taken per day can be calculated as:
```r
meandailySteps <- mean(dailySteps)
meddailySteps <- median(dailySteps)
print(meandailySteps)
```
```
## [1] 9354.23
```
```r
print(meddailySteps)
```
```
## [1] 10395
```
## What is the average daily activity pattern?
The average daily activity pattern be described by a plot of average daily steps per interval of measurement
```r
meanDailySteps <- tapply(activity_dat$steps, activity_dat$interval, mean, na.rm = T)
interval <- (as.numeric(levels(activity_dat$interval)))
dailyStepDf <- data.frame(interval,meanDailySteps)
dailyStepDf <- dailyStepDf[order(interval), ]
with(dailyStepDf, plot(interval, meanDailySteps, type = "l", col = "blue", ylab = "Number of Steps", xlab = "Interval"))
```

```
## [1] "Figure 2. The plot of average number of steps taken over 5-minute intervals"
```
The 5-minute interval, on average across all the days in the dataset, that
contains the maximum number of steps is given by
```r
with(dailyStepDf, interval[which.max(meanDailySteps)])
```
## Imputing missing values
The total number of NA in the activity data set is given by
```r
sum(is.na(activity_dat))
```
```
## [1] 2304
```
The modified data set can be easily obtained as below
```r
modActivity_dat <- merge(activity_dat,dailyStepDf, by = "interval")
NAIndex <- is.na(modActivity_dat$steps)
modActivity_dat$steps[NAIndex] <- modActivity_dat$meanDailySteps[NAIndex]
dailySteps <- tapply(modActivity_dat$steps, modActivity_dat$date, sum, na.rm = T)
hist(dailySteps, col = "red", breaks = 10)
```

```
## [1] "Figure 3. The histogram of the total daily number of steps with NAs imputed"
```
The new mean and median can then be calcuated as
```r
meandailySteps <- mean(dailySteps)
meddailySteps <- median(dailySteps)
print(meandailySteps)
```
```
## [1] 10766.19
```
```r
print(meddailySteps)
```
```
## [1] 10766.19
```
Obviously there is diffrence between the total number of steps taken daily with and wihtout data impute. Both the mean and median had increased. More importantly, the new mean and median are equal which shows that the steps measurement is now more normally distributed than it was.
## Are there differences in activity patterns between weekdays and weekends?
```r
modActivity_dat$day_type <- factor(weekdays(as.Date(modActivity_dat$date)) %in% c("Saturday", "Sunday"))
levels(modActivity_dat$day_type) = c("weekday","weekend")
meanDailySteps <- tapply(modActivity_dat$steps, list(modActivity_dat$interval, modActivity_dat$day_type), mean, na.rm = T)
interval <- as.numeric(levels(modActivity_dat$interval))
dailyStepDf <- data.frame(interval,meanDailySteps)
dailyStepDf <- dailyStepDf[order(interval), ]
temp = reshape(dailyStepDf, direction = "long", varying = c("weekday","weekend"), v.names = "steps", times = c("weekday","weekend"), sep="")
xyplot(steps ~ interval|time, data = temp, type = "l", layout = c(1,2), ylab = "Number of Steps", xlab = "Interval")
```

```
## [1] "Figure 4. The plot of average number of steps taken in weekday vs. weekend over 5-minute intervals"
```
It can be observed from the Figure 4 that high number of steps seems to occur in the morning period towards the noon but the number of walking steps reduces and remain flat for the rest of the day until the evening time with little more walking step. This observation is expected since walking around reduces once people get to work in teh morning. Also, people will then be working back to their houses or leaving the office building in the evening after work.
However, for the weekend the activity doesn't really start till after noon as people are mostly sleeping in weekends' morning. However, once they get up they seem to be actively working around till the evening.
Therefore, this activity monitoring data and the analysis seems to be able to provide information to identify which what period of the day is someone likely to be walking a lot or walking less.
|
PHP | UTF-8 | 976 | 2.546875 | 3 | [] | no_license | <?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "schooldb";
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sqlcheck = $conn->prepare('SELECT password FROM profiles WHERE name LIKE :name');
$sql = $conn->prepare('SELECT name, admin FROM profiles WHERE name LIKE :name');
$sqlcheck->bindParam(':name',$_POST["name"]);
$sql->bindParam(':name',$_POST["name"]);
$sqlcheck->execute();
$check = $sqlcheck->fetch(PDO::FETCH_ASSOC);
$hash = $check["password"];
$rows = [];
if(password_verify($_POST["password"], $hash)){
$sql->execute();
if ($sql->rowCount() > 0) {
$rows = $sql->fetch(PDO::FETCH_ASSOC);
} else {
$rows = NULL;
}
} else {
$rows = NULL;
}
header('Content-Type: application/json');
echo json_encode($rows); |
C++ | UTF-8 | 586 | 2.828125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int T, num, sum{0}, min{101}, count{0};
cin >> T;
for (int i = 1; i <= T; i++) {
for (int j = 1; j <= 7; j++) {
cin >> num;
if (num % 2 == 0) {
sum += num;
count++;
if (count == 1) {
min = num;
} else if(min > num){
min = num;
}
}
}
cout << sum << " " << min << "\n";
sum = 0;
min = 101;
}
}
|
TypeScript | UTF-8 | 2,297 | 2.59375 | 3 | [] | no_license | import { DataService } from './../data.service';
// tslint:disable: prefer-for-of
import { Component, OnInit, TemplateRef, ViewChild, ViewContainerRef } from '@angular/core';
@Component({
selector: 'app-rendering',
templateUrl: './rendering.component.html',
styleUrls: ['./rendering.component.css']
})
export class RenderingComponent {
@ViewChild('itemsContainer', { read: ViewContainerRef }) container: ViewContainerRef;
@ViewChild('item', { read: TemplateRef }) template: TemplateRef<any>;
public items = [{
id: 1,
text: 'foo'
}, {
id: 2,
text: 'bar'
}];
public data: any[] = this.dataService.data;
public tableData: any[] = [];
public trackItemById = (idx, item) => item.id;
constructor(private dataService: DataService) { }
public createItems(): void {
this.tableData = this.data;
}
public renderManually(): void {
for (let n = 0; n < this.data.length; n++) {
this.container.createEmbeddedView(this.template, { dataItem: this.data[n] });
}
}
public renderProgressively(): void {
const ITEMS_RENDERED_AT_ONCE = 500;
const INTERVAL_IN_MS = 10;
let currentIndex = 0;
const interval = setInterval(() => {
const nextIndex = currentIndex + ITEMS_RENDERED_AT_ONCE;
for (let n = currentIndex; n < nextIndex ; n++) {
if (n >= this.data.length) {
clearInterval(interval);
break;
}
const context = {
dataItem: this.data[n]
};
this.container.createEmbeddedView(this.template, context);
}
currentIndex += ITEMS_RENDERED_AT_ONCE;
}, INTERVAL_IN_MS);
}
public clearManually(): void {
this.container.clear();
}
public clearItems(): void {
this.tableData = [];
}
public add(): void {
const newItems = [];
for (const item of this.items) {
newItems.push({
id: item.id,
text: item.text
});
}
newItems.push({
id: this.items.length + 1,
text: `NEW`
});
this.items = newItems;
}
}
|
JavaScript | UTF-8 | 1,318 | 3.046875 | 3 | [] | no_license | var recent_matches = document.querySelector("#recent_matches");
var entry = document.querySelector("#entry");
var sentinel = document.querySelector("#sentinel");
const limit = 10;
let offset = 0;
function loadRecentMatches() {
fetch(`/recent_matches?limit=${limit}&offset=${offset}`)
.then((res) => res.json())
.then((data) => {
if (!data.length) {
sentinel.innerHTML = "No more matches";
return;
}
for (var i = 0; i < data.length; i++) {
let new_entry = entry.cloneNode(true);
new_entry.querySelector("#hero").innerHTML = data[i]["hero_name"];
new_entry.querySelector("#result").innerHTML = data[i]["radiant_score"] + " / " + data[i]["dire_score"];
new_entry.querySelector("#duration").innerHTML = data[i]["duration"];
new_entry.querySelector("#kda").innerHTML = "N/A";
new_entry.querySelector("#view_game").innerHTML = `<a href="${window.location.host}/match/${data[i]["match_id"]}">View</a>`
recent_matches.appendChild(new_entry);
}
offset += limit;
});
}
function alertM() {
alert('Hello');
}
var intersectionObserver = new IntersectionObserver((entries) => {
if (entries[0].intersectionRatio <= 0) {
return;
}
loadRecentMatches();
});
intersectionObserver.observe(sentinel);
|
JavaScript | UTF-8 | 1,265 | 2.765625 | 3 | [] | no_license | /**
* 需求:
* search并遍历所有customer下的invoice,如果存在invoice中的字段daysoverdue>=15天
* 则custentity1的值设置为true。如果所有的invoice中的字段daysoverdue全都<15天,则custentity1
* 的值设置为false。每天上午5点半更新一次,执行一次脚本。
* @param recType
* @param recId
*/
function scheduleUpdate(recType, recId) {
// 获取当前表单记录的ID和Type
var record = nlapiLoadRecord(recType, recId);
nlapiLogExecution('debug', 'test', recId);
nlapiLogExecution('debug', 'test', recType);
// 当付钱逾期天数在15天以内或者为空,将Stop的值改为F
nlapiLogExecution('debug', 'test', record.getFieldValue('daysoverdue'));
if (record.getFieldValue('daysoverdue') < 15
|| !record.getFieldValue('daysoverdue')) {
// 获取当前表单记录
// var record = nlapiLoadRecord(recType, recId);
record.setFieldValue('custentity1', 'F');
// 保存记录
// nlapiSubmitRecord(record);
}
// 付钱逾期天数大于等于15天,将Stop的值改为T
if (record.getFieldValue('daysoverdue') >= 15) {
// var record = nlapiLoadRecord(recType, recId);
record.setFieldValue('custentity1', 'T');
// nlapiSubmitRecord(record);
}
nlapiSubmitRecord(record);
}
|
Markdown | UTF-8 | 4,357 | 3.390625 | 3 | [] | no_license | I assure you, this is a post about programming, it'll just take a few
paragraphs to get there.
There's a biological mechanism known as _resistance_, and it plays out
in many different systems. For example, as you habitually drink more
alcohol, you gain a tolerance, which prevents you from getting drunk
as easily. This can be called *alcohol resistance*. When you
habitually run high levels of insulin, your body becomes less
sensitive to insulin, making you *insulin resistant*. When you go into
a loud room, your ears adjust down the sound, making you *noise
resistant*. And when you change enough dirty diapers, you become
*smell resistant*.
Resistance applies not just at the biological level. Consider a car
crash. The first time your car is in a crash, it is impacted in a
major way. But after repeated crashes, the damage goes down, as your
car attains *crash resistance*. The first time a baseball goes through
a window, it shatters. But further impact between the shards and balls
causes less damage. This is *impact resistance*.
Resistance isn't a term we often use in the programming world. That's
a mistake I intend to rectify today.
Imagine you're working on a Python application. Python is a memory
managed language, so you have _never_ seen a segfault. One day, you're
testing your code, and **poof**, a wild segfault appears! You will
respond to it far more strongly than a C programmer, who has built up
a healthy memory bug resistance over the years. And as a result, you
may begin to develop some of that alcohol resistance I mentioned
above.
But I'm not here to talk about Python, because no one uses Python in
the real world. Instead, let's discuss Haskell.
In Haskell, we can use strong typing techniques to great effect, such
as:
* Avoiding 404 errors in a web application with type-safe URLs
* Ensuring proper character encoding handling by differentiating
textual and binary data
* Making Software Transactional Memory safe by quarantining effects
The problem is that we use it _everywhere_. Like any system, this
overuse of typing builds up a resistance. When someone is insulin
sensitive, and you give them a small dose of insulin, they respond
quickly. When they are insulin resistant, that same dose produces
almost no impact. The same is true with typing.
Every single expression and subexpression in Haskell is typed. Sure,
there's type inference and the programmer doesn't have to spell it
out. But _it's still there_. The effects can still be felt. You cannot
escape the reality that, when you hit compile, an Abstract Syntax Tree
annotated with types is being generated. One of the intermediate
languages used by GHC—Core—type annotates *everything*!
The types are there, just like insulin. And just like insulin, whether
we realize it or not, our bodies and minds are slowly building up
resistance to it.
With insulin resistance, the body produces ever increasing amounts of
insulin to overcome the resistance, till the levels are so high that
they cause damage. So, too, with types: Haskellers end up using more
and more types in their code until they buckle under the strain. Their
minds break down, their tools break, runtime errors slip in,
performance suffers.
Types, like insulin, are not evil. But they need to be moderated.
There is no future for a language like Haskell. It dictates
overuse—nay, abuse—of types. It is inhumane and immoral to
subject our computers to such torture. We need to immediately reduce
our dependence on types, and then—when type sensitivity is
reestablished—carefully and moderately add them back in.
Python took this too far, by fully eliminating types. It's literally
impossible in Python to even get a type error, even at runtime. That's
absurd, and is just as bad as a body with no insulin production at
all. However, Python heads in the right direction. We need a blend of
Python's complete lack of a type system, and Haskell's ability to use
types in the right location.
Therefore, I'm announcing today the creation of a new language:
Paskell. It fortunately is an unused name, and sounds nothing like any
other programming language ever before created.
And for those who want to learn more, you can [watch this
video](https://www.youtube.com/watch?v=dQw4w9WgXcQ) where I describe
in more detail how I truly feel about types.
|
Python | UTF-8 | 2,662 | 4.46875 | 4 | [] | no_license |
"""
* counter
* defaultdict
* ordereddict
* namedtuple
* deque
"""
# Counter
"""
Allows us to count things. Give it a iterable or a mapping (such as a dict) and it will turn into a counter of elements.
"""
from collections import Counter
device_temperatures = [13.5, 14.0, 14.0, 14.5, 14.5, 14.5, 15.0, 16.0]
temperature_counter = Counter(device_temperatures)
print(temperature_counter[14.0])
print('\n')
# defaultdict
"""
The `defaultdict` never raises a `KeyError`. Instead, it returns the value returned by the function specified when the object was instantiated.
"""
from collections import defaultdict
coworkers = [('Rolf', 'MIT'), ('Jen', 'Oxford'), ('Rolf', 'Cambridge'), ('Charlie', 'Manchester')]
alma_maters = defaultdict(list)
for coworker, place in coworkers:
alma_maters[coworker].append(place)
print(alma_maters)
print(alma_maters['Anne'])
print(alma_maters)
print('\n')
# OrderedDict
from collections import OrderedDict
o = OrderedDict()
o['Rolf'] = 6
o['Jose'] = 10
o['Jen'] = 3
print(o) # keys are always in the order in which they were inserted
o.move_to_end('Rolf')
o.move_to_end('Jose', last=False)
print(o)
o.popitem() # Pop off the last item from the list
print(o)
print('\n')
# namedtuple
"""
A namedtuple is another object that we can use like a tuple, where each of the elements of the tuple has a name. In addition, the tuple itself also has a name.
It improves on tuples by making more explicit what it means.
Take this as an example using normal tuples:
"""
from collections import namedtuple
# Normal Tuples
account = ('checking', 1850.90)
print(account[0]) # name
print(account[1]) # balance
print('\n')
# named tuples
Account = namedtuple('Account', ['name', 'balance'])
account = Account('checking', 1850.90)
print(account.name)
print(account.balance)
print(account)
print('\n')
## Deque
"""
The last element we’ll look at today is the `deque`, which stands for “Double-ended queue”.
(Watch presentation about queues if you haven’t already).
In a `deque`, we can push elements at the start or the end, and we can also remove elements from the start or the end.
It is very efficient, performing very well, and also it’s thread-safe (we’ll be looking at threads soon!).
When we look at asynchronous development, we’ll be talking more about the `deque` as we use it. For now, just remember it’s like a list on which you do operations like a list:
"""
from collections import deque
friends = deque(('Rolf', 'Charlie', 'Jen', 'Anna'))
friends.append('Jose')
friends.appendleft('Anthony')
print(friends)
friends.pop()
print(friends)
friends.popleft()
print(friends) |
PHP | UTF-8 | 380 | 2.765625 | 3 | [] | no_license | <html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>VinaTAB EDU - Mon PHP</title>
</head>
<body>
<h1>Các hàm kiểm tra giá trị của biến</h1>
<?php
$a = 5;
if (isset($a)){
echo "Biến a = {$a}";
} else {
echo "Không tồn tại biến a";
}
?>
</body>
</html> |
Python | UTF-8 | 2,250 | 2.75 | 3 | [
"MIT"
] | permissive | #!/usr/bin/python
# -*- coding: utf-8 -*-
#author: Tianming Lu
from scipy import stats
import numpy as np
import random
def generate(D, T, I, L, N):
#generate large itemsets
correlation_level = 0.5
large_sets = []
size = 0
for i in range(L):
sz = stats.poisson.rvs(I)
if sz == 0:
sz += 1
if i == 0:
itemsets = random.sample(xrange(N), sz)
itemsets.sort()
large_sets.append(itemsets)
else:
pick_items_p = 2
while pick_items_p > 1:
pick_items_p = stats.expon.rvs(scale=correlation_level)
pick_items_count = int(pick_items_p * sz)
pick_items = random.sample(large_sets[-1], min(pick_items_count, size))
random_items = random.sample([x for x in xrange(N) if x not in pick_items],
sz - len(pick_items))
itemset = pick_items + random_items
itemset.sort()
large_sets.append(itemset)
size = sz
sets_p = stats.expon.rvs(size = L)
sets_p = np.array(sets_p)
sump = sum(sets_p)
sets_p /= sump
corruption_levels = stats.norm.rvs(0.5, 0.1, size = L)
trans = []
tran_size = stats.poisson.rvs(T, size = D)
for i in range(D):
P = np.random.rand(L)
P = sets_p * P
index = np.argmax(P)
itemset = list(large_sets[index])
c = corruption_levels[index]
set_size = len(itemset)
while stats.uniform.rvs() < c and set_size > 1:
index = stats.randint.rvs(0, set_size)
itemset.pop(index)
set_size -= 1
trans.append(itemset)
return trans
def write(transactions, filename):
with open(filename, 'w') as output:
for t in transactions:
for item in t:
output.write(str(item) + ' ')
output.write('\n')
def read(filename):
transactions = []
with open(filename, 'r') as input:
for line in input.readlines():
t = [item for item in line.split()]
transactions.append(t)
return transactions
if __name__ == "__main__":
trans = generate(10000, 20, 4, 2000, 1000)
write(trans, "test.txt")
|
Python | UTF-8 | 243 | 3.015625 | 3 | [] | no_license | n=int(input())
r=[]
for _ in range(n):
s,t=map(int,input().split())
r.append([s-t,s+t])
r=sorted(r,key=lambda x: x[1])
ans=[r[0]]
for i in range(1,n):
if r[i][0]>=ans[-1][1]:
ans.append(r[i])
print(len(ans)) |
Python | UTF-8 | 4,291 | 2.953125 | 3 | [] | no_license | from gpiozero import *
from time import *
from datetime import *
import json
file = 'record_dataHL.json'
maintenance_value = 0
def open_candispencer():
global servo
servo.max()
sleep(2)
servo.min()
sleep(2)
def open_record():
'''Deze opent de Json file aan de hand van de variabele "file" bovenaan.'''
with open(file) as f:
recorddata = json.load(f)
return recorddata
def write_record(new_recorddata):
'''Deze functie schrijft de data weg die in create_record() gemaakt word.'''
with open(file, 'w') as f:
json.dump(new_recorddata, f, indent=2)
def vandalism_alarm():
"""Laat buzzer afgaan voor aantal keer in range. """
buzzer = Buzzer(9)
for i in range(0, 1):
print("letop vandalisme")
buzzer.on()
sleep(1)
buzzer.off()
sleep(1)
def read_distance():
'''Deze functie meet de afstand.'''
distance_sensor = DistanceSensor(echo=24, trigger=23)
distance_sensor.max_distance = 0.4
# error = distance_sensor.value()
# if error >= 1:
# meting = 99
meting = (distance_sensor.distance * 100)
print("{0:.2f} Centimeter".format(meting))
return calculate_cans(meting)
def calculate_cans(meting):
'''Aan de hand van de meting word er berekend hoeveel blikken er nog in de automaat zitten. '''
if meting < 5.5:
amount_cans = 6
return amount_cans
print("De automaat zit vol")
elif meting < 11 and meting > 5.5:
amount_cans = 5
return amount_cans
print("Er zijn blikjes uit.")
elif meting > 11 and meting < 16.5:
amount_cans = 4
return amount_cans
print("Er zijn blikjes uit.")
elif meting > 16.5 and meting < 22:
amount_cans = 3
return amount_cans
print("Er zijn blikjes uit.")
elif meting > 22 and meting < 27.5:
amount_cans = 2
return amount_cans
print("Er zijn blikjes uit.")
elif meting > 27.5 and meting < 33:
amount_cans = 1
return amount_cans
print("Letop, er is nog een blikje over.")
elif meting > 33 and meting < 38.5:
amount_cans = 0
return amount_cans
print("De automaat is leeg")
else:
print("Dit was een foutieve meting")
amount_cans = 101
return amount_cans
def create_record():
'''Verzamelt alle gegevens van sensoren etc, maakt hier een dictionairy van.'''
global maintenance_value
date = str(datetime.now().strftime("%Y-%m-%d"))
time = str(datetime.now().strftime("%H:%M:%S"))
recorddata = open_record()
amount_cans = read_distance()
sold = recorddata['records'][len(recorddata['records']) - 1]['Sold']
if maintenance_value == 1:
maintenance_counter = 0
maintenance_value = 0
else:
maintenance_counter = recorddata['records'][len(recorddata['records']) - 1]['Maintenance']
print("Amount of cans {}".format(amount_cans))
print("Old data {}".format(recorddata['records'][len(recorddata['records']) - 1]))
if amount_cans < 99 and recorddata['records'][len(recorddata['records']) - 1]['Amount'] != amount_cans:
sold += 1
maintenance_counter += 1
record = {"Time": time, "Date": date, "Amount": amount_cans, "Sold": sold, "Maintenance": maintenance_counter}
print("New data {}".format(record))
recorddata["records"].append(record)
write_record(recorddata)
else:
print("De record is niet veranderd")
def start_machine():
'''Maakt loop voor knoppen indrukken etc.'''
global maintenance_value, servo
print("Programma is gestart.")
button = Button(15)
tilt = Button(10)
maintenance_button = Button(11)
servo = Servo(7, frame_width= 0.09)
servo.min()
machine_loop = True
while machine_loop:
if button.value == 1:
print("Meting word gestart.")
open_candispencer()
sleep(1)
create_record()
if maintenance_button.value == 1:
maintenance_value = 1
sleep(1)
print("Onderhoudsknop is ingedrukt.")
if tilt.value == 0:
sleep(0.3)
if tilt.value == 0:
vandalism_alarm()
start_machine()
|
C# | UTF-8 | 1,067 | 2.734375 | 3 | [
"MIT"
] | permissive | namespace LambdaCore.Core.Factories
{
using System;
using System.Linq;
using System.Reflection;
using Interfaces.Core.Factories;
using Interfaces.Models;
public class CoreFactory : ICoreFactory
{
public ICore CreateCore(char coreName, string[] args)
{
//CreateCore:@System@2000
var type = args[0];
var durability = int.Parse(args[1]);
var assembly = Assembly.GetExecutingAssembly();
var coreType = assembly.GetTypes()
.FirstOrDefault(t => t.Name == $"{type}Core");
if (coreType == null)
{
throw new InvalidOperationException($"{type}Core not found!");
}
if (!typeof(ICore).IsAssignableFrom(coreType))
{
throw new InvalidOperationException($"{type}Core is not a {nameof(ICore)}!");
}
var newCore = (ICore)Activator.CreateInstance(coreType, new string(coreName, 1), durability);
return newCore;
}
}
} |
C | UTF-8 | 854 | 3.5 | 4 | [
"Apache-2.0"
] | permissive | /*
* Author: Jhonatan Casale (jhc)
*
* Contact : jhonatan@jhonatancasale.com
* : casale.jhon@gmail.com
* : https://github.com/jhonatancasale
* : https://twitter.com/jhonatancasale
* : http://jhonatancasale.github.io/
*
* Create date Fri 12 May 15:26:40 -03 2017
*
*/
#include <stdlib.h>
#include <stdio.h>
int sum_divs_interval(int m, int n);
int sum_divs(int m);
int main (int argc, char **argv)
{
int m, n;
scanf("%d", &m);
scanf("%d", &n);
printf("Sum of divisors from %d, to %d is %d\n",
m, n, sum_divs_interval(m, n));
return (EXIT_SUCCESS);
}
int sum_divs_interval(int m, int n) {
if(m > n)
return (-1);
int sum = 0;
for(int i = m; i <= n; ++i)
sum += sum_divs(i);
return sum;
}
int sum_divs(int m) {
int sum = 0;
for(int i = 1; i <= m; ++i)
if(m % i == 0)
sum += i;
return sum;
}
|
C | UTF-8 | 12,136 | 3.515625 | 4 | [] | no_license | /*
Author: Jessica Barre
Email: barrej4@rpi.edu
Program name: "main.c"
Date Due: 10/3/2016
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
char* readfile(FILE *, size_t*);
char** parseExpression(char *, int *, size_t);
void printExpression(char**, int);
int evaluateExpression(char**, int, int);
int getResult(char, int[], int);
void testPipe(int rc);
void testFork( int pid);
void testWait(int status, int pid);
int child_result = -1;
void testPipe(int rc) {
if ( rc == -1 )
{
perror( "pipe() failed" );
exit(EXIT_FAILURE);
}
}
void testFork(int pid) {
if( pid == -1)
{
perror( "fork() failed" );
exit(EXIT_FAILURE);
}
}
void testWait(int status , int child_pid) {
if ( WIFSIGNALED( status ) )
{
printf( "PID %d: child %d terminated abnormally\n", getpid(), child_pid );
}
else if ( WIFEXITED( status ) )
{
int rc = WEXITSTATUS( status );
if(rc != 0){
printf("PID %d: child %d terminated successfully with nonzero exit status %d\n", getpid(), child_pid, rc );
exit(EXIT_FAILURE);
}
}
}
int getResult(char op, int operands[], int nth_child){
int next;
int result = 0;
if (op == '+'){
for (next = 0; next < nth_child; next++){
result = result + operands[next];
}
}
else if(op == '-'){
result = operands[0];
for (next = 1; next < nth_child; next++){
result = result - operands[next];
}
}
else if (op == '*'){
result = 1;
for (next = 0; next < nth_child; next++)
result = result * operands[next];
}
else if(op == '/'){
result = operands[0];
for (next = 1; next < nth_child; next++){
if (operands[next] == 0) {
printf("PID %d: ERROR: division by zero is not allowed; exiting\n", getpid());
int status;
wait(&status);
exit(EXIT_SUCCESS);
}
result = result/operands[next];
}
}
return result;
}
int evaluateExpression(char** elements, int count, int rp){
if (strchr("+-/*", *elements[1]) == NULL) {
printf("PID %d: ERROR: unknown \"%s\" operator; exiting\n", getpid(), elements[1]);
fflush(NULL);
exit(EXIT_FAILURE);
}
char op = *elements[1];
int numChildren = count - 3; /** where 3 takes off ( , ) and operator */
int operands[20];
int p[numChildren][2]; /** Create a pipe for each operand **/
int rc = -1;
int i = 2;
int nthChild = 0;
printf("PID %d: Starting \"%c\" operation\n", getpid(), op);
fflush(NULL);
if (numChildren < 2) {
printf("PID %d: ERROR: not enough operands; exiting\n", getpid());
fflush(NULL);
}
while (i < count) {
int num = -1;
/** Pipe and fork if the element is a positive/negative digit or a subexpression **/
if ( isdigit(*elements[i]) != 0 || strchr("(", *elements[i]) != NULL ||
(strchr("-", *elements[i]) && isdigit(elements[i][1]) != 0 ) ) {
if (op == '/' && i > 0) {
if(*elements[i] == '0') {
printf( "PID %d: ERROR: division by zero is not allowed; exiting\n", getpid());
int status;
wait(&status);
exit(EXIT_FAILURE);
}
}
/** pipe **/
rc = pipe(p[nthChild]);
testPipe(rc);
/** If element is a digit parse it **/
if ( isdigit(*elements[i]) ||
(strchr("-", *elements[i]) && isdigit(elements[i][1]) != 0 ) ) {
num = atoi(elements[i]);
}
/** fork **/
int pid = fork();
testFork(pid);
if (pid == 0) {
if ( strchr("(", *elements[i]) != NULL ) { /** This child process is a subexpression **/
int subCount = 0;
int len = strlen(elements[i]);
char** subExp = parseExpression(elements[i], &subCount, len);
/** Prints the current expression */
printf("PID %d: My expression is \"", getpid());
printExpression(subExp, subCount);
printf("\"\n");
evaluateExpression(subExp, subCount, p[nthChild][1]);
int j;
for(j = 0; j < subCount; j++){
free(subExp[j]);
}
free(subExp);
}
else { /** This child process is a digit **/
printf("PID %d: My expression is \"%d\"\n", getpid(), num);
fflush(NULL);
close(p[nthChild][0]);
p[nthChild][0] = -1;
write(p[nthChild][1], &num, sizeof(num));
printf( "PID %d: Sending \"%d\" on pipe to parent\n", getpid(), num);
}
exit(EXIT_SUCCESS);
} /** end child process **/
nthChild++;
}
i++;
} /** End while: all child processes are finished **/
/** Read and Waitpid **/
int child = 0;
while (child < numChildren) {
close (p[child][1]);
p[child][1] = -1;
int status;
pid_t child_pid = wait(&status);
testWait(status, child_pid);
read(p[child][0], &operands[child], sizeof(int));
child++;
}
/** Get the Final Result if there are enough operands **/
if (numChildren < 2) {
exit(EXIT_FAILURE);
}
int result = getResult(op, operands, numChildren);
if(rp != -1) { /** If rp = -1, we are in the top-level/parent **/
child_result = result;
write( rp, &result, sizeof(result) );
printf("PID %d: Processed \"", getpid());
printExpression(elements, count);
printf("\"; sending \"%d\" on pipe to parent\n", result);
return 0;
} else {
return result;
}
return 0;
}
void printExpression(char** elements, int count){
printf("(");
int i = 1;
while (i < count) {
if(strchr("(", *elements[i])){
printf(" %s", elements[i]);
}
else if(strchr("-", *elements[i]) && isdigit(elements[i][1]) != 0 ){
printf(" %s", elements[i]);
}
else if( isdigit(*elements[i]) != 0 ){
printf(" %s", elements[i]);
}
else if(strchr(")", *elements[i])){
printf("%s", elements[i]);
}
else{
printf("%s", elements[i]);
}
i=i+1;
}
}
char** parseExpression(char * expression, int * count, size_t len) {
int size = 3; /** The current size of the elements array **/
/** Dynamically allocate an elements array to hold 3 elements **/
char** elements = calloc (size, sizeof (char*) );
if(elements == NULL) {
perror( "calloc() failed" );
exit(EXIT_FAILURE);
}
int current = 1; /** The current index of the expression **/
/** assign opening parens and operator to first two elements **/
elements[*count] = malloc ( sizeof ( char ) * 1);
if(elements[*count] == NULL) {
perror( "malloc() failed" );
exit(EXIT_FAILURE);
}
strcpy(elements[*count],"(");
*count = *count + 1;
int next = current;
while(expression[next] != ' '){
next++;
}
elements[*count] = malloc ( sizeof ( char ) * (next - current));
strncpy(elements[*count], expression + current, next - current);
*count = *count + 1;
current = next;
/** Note that count should = 2 and the elements array should so farcontain
{'(', 'r'}, where r is an unknown operator**/
/** Now lets parse the rest of the expression **/
while(current < len) {
/** Reallocate the elements array to hold one more element if necessary **/
if (*count > size - 2) {
size = size + 1;
elements = realloc (elements, (int) size * sizeof( char * ) );
if(elements == NULL) {
perror( "realloc() failed" );
exit(EXIT_FAILURE);
}
}
/** Parse the string by digits and subexpressions, ignore white space **/
next = current + 1;
char n = (char) expression[next];
if (isdigit(expression[current])
|| (strchr("-", expression[current]) != NULL && isdigit(n) != 0) ) {
int numDigits = 1;
while(isdigit(n)){
next++;
numDigits++;
n = (char) expression[next];
}
/** allocate space for the number of digits needed **/
elements[*count] = malloc ( sizeof ( char ) * numDigits);
if(elements[*count] == NULL) {
perror( "malloc() failed" );
exit(EXIT_FAILURE);
}
elements[*count] = malloc ( sizeof ( char ) * (next - current));
strncpy(elements[*count], expression + current, next - current);
current = next;
}
else if (expression[current] == '('){
next = current + 1;
int subsize = 1;
int oParens = 1;
int cParens = 0;
/** locate the matching closing parentheses **/
while( cParens != oParens && next < len ) {
if (expression[next] == '('){
oParens++;
}
else if(expression[next] == ')'){
cParens++;
}
next++;
subsize = subsize + 1;
}
if(cParens != oParens){
perror("parentheses don't match");
exit(EXIT_FAILURE);
}
/** copy over subexpression **/
elements[*count] = malloc ( sizeof ( char ) * subsize);
if(elements[*count] == NULL) {
perror( "malloc() failed" );
exit(EXIT_FAILURE);
}
elements[*count] = malloc ( sizeof ( char ) * (next - current));
strncpy(elements[*count], expression + current, next - current);
current = next;
}else if (current == len - 1){
if (expression[current] == ')') {
elements[*count] = malloc ( sizeof ( char ) * 1);
if(elements[*count] == NULL) {
perror( "malloc() failed" );
exit(EXIT_FAILURE);
}
strcpy(elements[*count],")");
} else {
perror("This expression has mismatched parentheses");
exit(EXIT_FAILURE);
}
current++;
}else {
current++;
continue;
}
*count = *count + 1;
} /** ends while **/
return elements;
}
char* readfile(FILE * file, size_t *len){
char buff[40]; /** This will hold the expression we want parsed **/
char* expression = malloc( sizeof( char ) );;
/** Start by searching for the line with the elements **/
while ( fgets(buff, sizeof(buff), file) ) {
/** We only want an expression, ignore the lines
with comments, blanks, etc **/
if (buff[0] == '(') {
*len = strlen(buff);
/** Remove newline **/
if (*len > 0 && buff[*len-1] == '\n') buff[--*len] = '\0';
*len = strlen(buff);
expression = realloc(expression, sizeof( char ) * (1 + *len) );
strcpy(expression, buff);
} else {
continue;
}
} // End While
return expression;
}
/** MAIN **/
int main( int argc, char * argv[]){
/** Check for the proper arg count **/
if ( argc != 2 ) {
fprintf(stderr, "ERROR: Invalid arguments\nUSAGE: ./a.out <input-file>\n");
return EXIT_FAILURE;
}
/** Open the file **/
FILE * file;
if( (file = fopen(argv[1], "r") ) == NULL) {
fprintf(stderr, "unable to open file %s", argv[1]);
exit(EXIT_FAILURE);
}
size_t len = 0; /** The length of the expression **/
char* expression = readfile(file, &len);
int count = 0; /** The number of elements in the elements array **/
char** elements = parseExpression(expression, &count, len);
/** Now that all the elements of the expression are broken up,
that is, we have a dynamically allocated array of elements,
such as (+ 5 3 (* 7 -8))) = ["(", "+", "5", "3", (* 7 -8)",
we can now calculate the expression with IPC */
printf("PID %d: My expression is \"", getpid());
printExpression(elements, count);
printf("\"\n");
fflush(NULL);
int answer = evaluateExpression(elements, count, -1);
printf("PID %d: Processed \"", getpid());
printExpression(elements, count);
printf("\"; final answer is \"%d\"", answer);
fclose(file);
free(expression);
int j;
for(j = 0; j < count; j++){
free(elements[j]);
}
free(elements);
return EXIT_SUCCESS;
}
|
TypeScript | UTF-8 | 1,105 | 3.578125 | 4 | [] | no_license | // Importing and exporting Modules
import { Person } from './person';
export class Student{
// private firstName : string;
// public lastName : string;
// protected age : number;
readonly email : string = "abc@test.com"
// constructor(private firstName: string,
// public lastName : string,
// protected age : number){
// // this.firstName = firstName;
// // this.lastName = lastName;
// // this.age = age;
// }
constructor(private myObj : Person){}
sayHi() : string{
return `Hello ${this.myObj.firstName} ${this.myObj.lastName},
You are ${this.myObj.age} years old!`;
}
}
let obj : Person = {
firstName : "Foo",
lastName : "Bam",
age : new Date("Dec 21, 1984")
}
// let foo = new Student("Foo", "Bar", 32);
let fooBam = new Student(obj);
console.log(fooBam.sayHi());
// const MAGIC_NUMBER = Math.round(Math.random() * 10);
// export function getMyQuote(){
// return "Run 1000 mtr today!"
// }
// let & const
// let str : string;
// let num : number;
// let age : Date; |
Python | UTF-8 | 898 | 2.59375 | 3 | [] | no_license | from keras import models
from keras.models import model_from_json
from keras.preprocessing import image
import numpy as np
import os, tkinter, tkinter.filedialog, tkinter.messagebox
model = model_from_json(open('../../data/all/uni_predict.json').read())
model.load_weights('../../data/all/uni_predict.hdf5')
categories = ["2", "9", "10"]
while True:
root = tkinter.Tk()
root.withdraw()
iDir = '../../images/test_data/'
file = tkinter.filedialog.askopenfilename(initialdir=iDir)
img = image.load_img(file, target_size=(150, 150, 3))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
features = model.predict(x)
if features[0, 0] == 1:
tkinter.messagebox.showinfo('判定', '2号館')
elif features[0, 1] == 1:
tkinter.messagebox.showinfo('判定', '9号館')
else:
tkinter.messagebox.showinfo('判定', '10号館')
|
C++ | UTF-8 | 821 | 3.71875 | 4 | [] | no_license | /*
Multiple left rotations of the array
Given an array of integers A and multiple values in B which represents the indices of the array A around which left rotation of the array A needs to be performed.
Find the rotated array for each value and return the result in the from of a matrix where i'th row represents the rotated array for the i'th value in B.*/
vector<vector<int> > Solution::solve(vector<int> &A, vector<int> &B) {
int n = A.size();
vector<int> temp(2 * n);
for(int i = 0; i < A.size(); i++) {
temp[i] = temp[i + n] = A[i];
}
vector<vector<int>> ret;
for(int i = 0; i < B.size(); i++) {
int k = B[i] % n;
vector<int> v;
for(int i = k; i < n + k; i++) {
v.push_back(temp[i]);
}
ret.push_back(v);
}
return ret;
}
|
C# | UTF-8 | 2,943 | 3.109375 | 3 | [] | no_license | using System;
namespace Portal.StateBase
{
/// <summary>
/// Zusammenfassungsbeschreibung für StateMachine
/// </summary>
public class StateMachine
{
#region Membervariabeln.
/// <summary>
/// Regelwerk mit den übergängen zwischen den verfügbaren Stati.
/// </summary>
private RuleSet ruleSet;
/// <summary>
/// Aktuelle Status.
/// </summary>
private RuleSet.State currentState;
#endregion
# region Konstruktoren.
/// <summary>
/// Konstruktor.
/// </summary>
/// <param name="ruleSet">Regelwerk für die Übergänge zwischen den einzelnen Stati</param>
public StateMachine(RuleSet ruleSet)
: this(ruleSet, ruleSet.InitialState)
{
}
/// <summary>
/// Konstruktor, welcher den Key des aktuellen Status übernimmt.
/// </summary>
/// <param name="ruleSet">Regelwerk für die Übergänge zwischen den einzelnen Stati</param>
/// <param name="currentState">Key des aktuellen Status</param>
public StateMachine(RuleSet ruleSet, int currentState)
: this(ruleSet, ruleSet.GetState(currentState))
{
}
/// <summary>
/// Konstruktor, welcher den aktuellen Status übernimmt.
/// </summary>
/// <param name="ruleSet">Regelwerk für die Übergänge zwischen den einzelnen Stati</param>
/// <param name="currentState">Aktuellen Status</param>
public StateMachine(RuleSet ruleSet, RuleSet.State currentState)
{
this.ruleSet = ruleSet;
this.currentState = currentState;
}
#endregion
# region Öffentliche Methoden
/// <summary>
/// Setzt den Zustand der Statusmaschine zurück.
/// </summary>
public void ResetState()
{
currentState = this.ruleSet.InitialState;
}
/// <summary>
/// Signalisiert ein Event, welches den Status der Statusmaschine beeinflussen kann. Der Status wird wenn nötig
/// angepasst. Diese Methode enthält die Logik über die möglichen Statusübergänge.
/// </summary>
/// <returns>true, wenn eine Änderung erfolgt ist.</returns>
/// <param name="NewEvent">Das aufgetretene Ereignis.</param>
public virtual bool SetEvent(int transition)
{
bool changed = false;
RuleSet.State newState = currentState.GetTransitionTarget(Convert.ToInt32(transition));
if(null != newState)
{
currentState = newState;
changed = true;
}
return changed;
}
# endregion
#region Öffentliche Properties
/// <summary>
/// Ermittelt die Informationen zum aktuellen Status.
/// </summary>
/// <returns></returns>
public string CurrentCtrlPath
{
get { return currentState.ControlFile; }
}
/// <summary>
/// Ermittelt den Key des aktuellen Status.
/// </summary>
public int CurrentStateKey
{
get { return currentState.StateKey; }
}
#endregion
}
}
|
C# | UTF-8 | 26,689 | 3.171875 | 3 | [] | no_license | /************************************************************************************/
/* Contact Manager System is a free application which manage two types of contacts: */
/* Faculty staffs and Students */
/* */
/* by Tao Lu */
/* Sept.6, 2019 */
/* */
/************************************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ContactManager
{
public partial class contactManagerMainForm : Form
{
string savePath = null; // path for saving file
List<Person> personList = new List<Person>(); // create a list for person
int EditCount = 0; // count for edit and add
List<int> matchList = new List<int>(); // store match index in personList
public SelectionMode MultiSimple { get; private set; }
public contactManagerMainForm()
{
InitializeComponent();
}
// Event - open file
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
Console.WriteLine("User selected the open menu items");
// clear listbox
personListListBox.Items.Clear();
// get the file path
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Open Contact Information";
ofd.Filter = "Text File|*.txt|All files|*.*";
ofd.FilterIndex = 1;
if (ofd.ShowDialog() != DialogResult.OK)
{
return;
}
// open a stream reader on 'contactinformation.txt' on the desktop
// for each line in the file call the constructor that takes single string
// and get a object back. Add that object to my list and to the display list
// close the file
savePath = ofd.FileName; // get file path ready for saving file
Person p = null;
try
{
StreamReader input = new StreamReader(ofd.FileName);
while (!input.EndOfStream)
{
string personType = input.ReadLine();
switch (personType)
{
case "FACULTY":
p = new Faculty(input.ReadLine());
p.Type = "Faculty";
break;
case "STUDENT":
p = new Student(input.ReadLine());
p.Type = "Student";
break;
default:
MessageBox.Show("unknown person in the file");
p = null;
break;
}
if (p != null)
{
personList.Add(p);
personListListBox.Items.Add(p.ToFormattedString());
}
}
input.Close();
}
catch (Exception excp)
{
MessageBox.Show($"File did not load. {excp.Message}");
return;
}
}
// Event - show contact information for selected person ( faculty and student)
private void contactDetailsToolStripMenuItem_Click(object sender, EventArgs e)
{
Console.WriteLine("User selected the contact detail as context menu items");
// set show mode
int mode = 0; // 0 - display only
// check to see if we have something checked first, message if not
int index = personListListBox.SelectedIndex;
if (index == -1)
{
MessageBox.Show("Must select a contact information first before displaying contact details");
return;
}
// create the edit dialog, have it prepopulate the contents of the field and then
// show the dialog
Person p = personList[index];
if (p is Faculty)
{
EditFacultyPerson(index, mode);
}
else if (p is Student)
{
EditStudentPerson(index, mode);
}
else
{
MessageBox.Show("unknown person trying to be editted");
}
}
// Event - edit contact information for faculty staff
private void editContactToolStripMenuItem_Click(object sender, EventArgs e)
{
// set display mode
int mode = 2; // 0 - edit mode
// check to see if we have something checked first, message if not
int index = personListListBox.SelectedIndex;
if (index == -1)
{
MessageBox.Show("Must select a contact information first before displaying contact details");
return;
}
// create the edit dialog, have it prepopulate the contents of the field and then
// show the dialog
Person p = personList[index];
if (p is Faculty)
{
EditFacultyPerson(index, mode);
}
else if (p is Student)
{
EditStudentPerson(index, mode);
}
else
{
MessageBox.Show("unknown person trying to be editted");
}
}
private void deleteContactToolStripMenuItem_Click(object sender, EventArgs e)
{
Console.WriteLine("User selected the delete as menu items");
// check to see if we have something checked first, message if not
int index = personListListBox.SelectedIndex;
if (index == -1)
{
MessageBox.Show("Must select a contact information first before displaying contact details");
return;
}
// create the edit dialog, have it prepopulate the contents of the field and then
// show the dialog
Person p = personList[index];
if (DialogResult.Yes != MessageBox.Show($"Are you sure you wish to delete {p.FirstName}?",
"Confirmation",
MessageBoxButtons.YesNo))
{
return;
}
// so really delete the item; take it out of the personList list
// and the display list
personListListBox.Items.RemoveAt(index);
personList.RemoveAt(index);
EditCount++; // EditCount add 1 after sucessful delete
}
// Event - Add contact inforamtion for faculty staff
private void facultyToolStripMenuItem_Click(object sender, EventArgs e)
{
Console.WriteLine("User selected the add contact of faculty as context menu items");
// set mode
int mode = 1; //1 - add mode
int index = -1; // add mode set index -1
// call function for edit
EditFacultyPerson(index, mode);
}
// Function - Edit faculty staff contact information
private void EditFacultyPerson(int index, int mode)
{
// create a dialog and configure for edit or only display
AddEditFacultyDialog adfd = new AddEditFacultyDialog();
switch (mode)
{
case 0: // 0 - show mode
case 2: // 2 - edit mode
Faculty f = (Faculty)personList[index];
// assign values in personList to public properties in AddEditFacultyDialog
adfd.FacultyEditMode = mode;
adfd.FacultyFirstName = f.FirstName;
adfd.FacultyLastName = f.LastName;
adfd.FacultyAcademicDept = f.Department;
adfd.FacultyEmail = f.ContactFaculty.Email;
adfd.FacultyBuilding = f.ContactFaculty.Building;
break;
case 1: // 1 - add mode
adfd.FacultyEditMode = mode;
break;
}
// show the dialog and wait for a ok
DialogResult result = adfd.ShowDialog();
// if answer was ok update the contact information with the new values and update display
// update faculty contact information
if (result == DialogResult.OK)
{
ContactFaculty facultyInfo;
try
{
facultyInfo = new ContactFaculty(adfd.FacultyEmail, adfd.FacultyBuilding);
}
catch (Exception excp)
{
MessageBox.Show($"email address error. {excp.Message}");
return;
}
Person p = new Faculty(adfd.FacultyFirstName,
adfd.FacultyLastName,
adfd.FacultyAcademicDept,
facultyInfo);
// set mode to public property
p.Type = "Faculty";
switch (mode)
{
case 0: // show mode
break;
case 2: // edit mode
// update new values for dispaly and list
personList[index] = p;
personListListBox.Items[index] = p.ToFormattedString();
EditCount++; // EditCount add 1 after sucessful edit
break;
case 1: //add mode
// add to list
personList.Add(p);
// add to list box for display
personListListBox.Items.Add(p.ToFormattedString());
EditCount++; // EditCount add 1 after sucessful add
break;
default:
break;
}
}
else if (result == DialogResult.Cancel)
{
return;
}
else
{
MessageBox.Show("AddEditFacultyDialog not return OK ....debug");
return;
}
}
// Function - Edit student contact information
private void EditStudentPerson(int index, int mode)
{
// create a dialog and configure for edit or only display
AddEditStudentDialog adsd = new AddEditStudentDialog();
switch (mode)
{
case 0: // 0 - show mode
case 2: // 2 - edit mode
Student s = (Student)personList[index];
// assign values in personList to public properties in AddEditFacultyDialog
adsd.StudentEditMode = mode;
adsd.StudentFirstName = s.FirstName;
adsd.StudentLastName = s.LastName;
adsd.StudentAcademicDept = s.Department;
adsd.StudentEmail = s.StudentCont.Email;
adsd.StudentMail = s.StudentCont.SnailMail;
adsd.StudentGradYear = s.GraduationYear;
// change s.course list to adsd.course string
adsd.StudentCourses = stdCourseListToString(s.Course);
break;
case 1: // 1 - add mode
adsd.StudentEditMode = mode;
break;
}
// show the dialog and wait for a ok
DialogResult result = adsd.ShowDialog();
// if answer was ok update the contact information with the new values and update display
// update student contact information
if (result == DialogResult.OK)
{
ContactStudent studentInfo;
try
{
studentInfo = new ContactStudent(adsd.StudentEmail, adsd.StudentMail);
}
catch (Exception excp)
{
MessageBox.Show($"email address error. {excp.Message}");
return;
}
Person p = new Student(adsd.StudentFirstName,
adsd.StudentLastName,
adsd.StudentAcademicDept,
studentInfo,
adsd.StudentGradYear,
// change adsd.StudentCourses string to p.Course list
stdCourseStringToList(adsd.StudentCourses)
);
// set mode to public property
p.Type = "Student";
switch (mode)
{
case 0: // show mode
break;
case 2: // edit mode
// update new values for dispaly and list
personList[index] = p;
personListListBox.Items[index] = p.ToFormattedString();
EditCount++; // EditCount add 1 after sucessful edit
break;
case 1: //add mode
// add to list
personList.Add(p);
// add to list box for display
personListListBox.Items.Add(p.ToFormattedString());
EditCount++; // EditCount add 1 after sucessful add
break;
default:
break;
}
}
else if (result == DialogResult.Cancel)
{
return;
}
else
{
MessageBox.Show("AddEditFacultyDialog not return OK ....debug");
return;
}
}
// Function - student course list to course string
private string stdCourseListToString(List<string> courseList)
{
string strCourse = null;
foreach (string c in courseList)
{
strCourse = strCourse + c + ",";
}
return strCourse;
}
// Function - student course string to course list
private List<string> stdCourseStringToList(string courseString)
{
List<string> listCourse = new List<string>();
char[] delimiters = { '|', ',' };
string[] tokens = courseString.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < tokens.Length; i++)
{
listCourse.Add(tokens[i]);
}
return listCourse;
}
private void firstNameToolStripMenuItem_Click(object sender, EventArgs e)
{
// clear all selected items and clear searchResultListBox
personListListBox.ClearSelected();
searchResultListBox.Items.Clear();
// create a dialog
SearchDialog schd = new SearchDialog();
// set search mode
schd.SearchType = 0;
DialogResult result = schd.ShowDialog();
// clear list of store index of matched person
matchList.Clear();
// index number
int cnt = 0;
if (result == DialogResult.OK)
{
foreach (Person p in personList)
{
if (string.Equals(p.FirstName.ToLower(), schd.SearchFn.ToLower()))
{
personListListBox.SetSelected(cnt, true);
matchList.Add(cnt);
searchResultListBox.Items.Add(p.ToFormattedString());
}
cnt++;
}
searchResultListBox.Items.Add("");
searchResultListBox.Items.Add($" Found {matchList.Count} items");
}
else if (result == DialogResult.Cancel)
{
return;
}
else
{
MessageBox.Show("AddEditFacultyDialog not return OK ....debug");
return;
}
}
private void lastNameToolStripMenuItem_Click(object sender, EventArgs e)
{
// clear all selected items and clear searchResultListBox
personListListBox.ClearSelected();
searchResultListBox.Items.Clear();
// create a dialog
SearchDialog schd = new SearchDialog();
// set search mode
schd.SearchType = 1;
DialogResult result = schd.ShowDialog();
// clear list of store index of matched person
matchList.Clear();
// index number
int cnt = 0;
if (result == DialogResult.OK)
{
foreach (Person p in personList)
{
if (string.Equals(p.LastName.ToLower(), schd.SearchLn.ToLower()))
{
personListListBox.SetSelected(cnt, true);
matchList.Add(cnt);
searchResultListBox.Items.Add(p.ToFormattedString());
}
cnt++;
}
searchResultListBox.Items.Add("");
searchResultListBox.Items.Add($" Found {matchList.Count} items");
}
else if (result == DialogResult.Cancel)
{
return;
}
else
{
MessageBox.Show("AddEditFacultyDialog not return OK ....debug");
return;
}
}
private void firstAndLastNameToolStripMenuItem_Click(object sender, EventArgs e)
{
// clear all selected items and clear searchResultListBox
personListListBox.ClearSelected();
searchResultListBox.Items.Clear();
// create a dialog
SearchDialog schd = new SearchDialog();
// set search mode
schd.SearchType = 2;
DialogResult result = schd.ShowDialog();
// clear list of store index of matched person
matchList.Clear();
// index number
int cnt = 0;
if (result == DialogResult.OK)
{
foreach (Person p in personList)
{
if ((string.Equals(p.FirstName.ToLower(), schd.SearchFn.ToLower())) && (string.Equals(p.LastName.ToLower(), schd.SearchLn.ToLower())))
{
personListListBox.SetSelected(cnt, true);
matchList.Add(cnt);
searchResultListBox.Items.Add(p.ToFormattedString());
}
cnt++;
}
searchResultListBox.Items.Add("");
searchResultListBox.Items.Add($" Found {matchList.Count} items");
}
else if (result == DialogResult.Cancel)
{
return;
}
else
{
MessageBox.Show("AddEditFacultyDialog not return OK ....debug");
return;
}
}
// Event - save file
private void saveContactsToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
string filepath = savePath;
StreamWriter output = new StreamWriter(filepath);
foreach (Person p in personList)
{
output.WriteLine(personTypeString(p));
output.WriteLine(p.toFileString());
}
output.Close();
EditCount = 0; // EditCount reset to 0 after sucessful save
}
catch (Exception excp)
{
MessageBox.Show($"File did not write. {excp.Message}");
return;
}
MessageBox.Show($"Contact information have been saved in contactinformation.txt");
}
// Function - write person type to file
private string personTypeString(Person p)
{
if (p is Faculty)
return "FACULTY";
else if (p is Student)
return "STUDENT";
else
return "UNKNOWN";
}
// Event - Save as files
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
Console.WriteLine("User selected the save as menu items");
SaveFileDialog sfd = new SaveFileDialog();
sfd.Title = "Select File to Save Contact Information List";
sfd.Filter = "Text File| *.txt | All files | *.* ";
sfd.FilterIndex = 1;
//sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
DialogResult result = sfd.ShowDialog();
if (result != DialogResult.OK)
{
return;
}
// all inside a try/catch
//
// open a stream writer on 'contactinformation.txt' on the desktop
// foreach person in my inventory, ,run the ToFileString() method
// and write that to file
// close the file
try
{
StreamWriter output = new StreamWriter(sfd.FileName);
foreach (Person p in personList)
{
output.WriteLine(personTypeString(p));
output.WriteLine(p.toFileString());
}
output.Close();
EditCount = 0; // EditCount reset to 0 after sucessful save
}
catch (Exception excp)
{
MessageBox.Show($"File did not write. {excp.Message}");
return;
}
MessageBox.Show($"Contact Information have been save in {sfd.FileName}");
}
// Event - Exit
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Console.WriteLine("User selected the exit as menu items");
if (EditCount > 0)
{
// make sure the user has saved all the changes
if (DialogResult.Yes != MessageBox.Show($"Are you sure to Exit? Yes - exit without save",
"Confirmation",
MessageBoxButtons.YesNo))
{
return;
}
}
Application.Exit();
}
// Event - Edit Student contact Information
private void studentToolStripMenuItem_Click(object sender, EventArgs e)
{
Console.WriteLine("User selected the add contact of student as context menu items");
// set mode
int mode = 1; //1 - add mode
int index = -1; // add mode set index -1
// call function for edit
EditStudentPerson(index, mode);
}
private void contactManagerMainForm_Load(object sender, EventArgs e)
{
// delete at the end
/*// no smaller than design time size
this.MinimumSize = new System.Drawing.Size(this.Width, this.Height);
// no larger than screen size
//this.MaximumSize = new System.Drawing.Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, (int)System.Windows.SystemParameters.PrimaryScreenHeight);
this.AutoSize = true;
this.AutoSizeMode = AutoSizeMode.GrowAndShrink;*/
}
// Event - Help (About)
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
// create a dialog and configure for edit or only display
AboutDialog ad = new AboutDialog();
// show the dialog and wait for a ok
DialogResult result = ad.ShowDialog();
// if answer was ok update the contact information with the new values and update display
if (result == DialogResult.OK)
{
return;
}
else if (result == DialogResult.Cancel)
{
return;
}
else
{
MessageBox.Show("AboutDialog not return OK ....debug");
return;
}
}
// Event - Clear searchResultBox
private void clearToolStripMenuItem_Click(object sender, EventArgs e)
{
searchResultListBox.Items.Clear();
}
// Event - Double click on the item in searchResultBox to connect to personListBox
private void searchResultListBox_MouseDoubleClick(object sender, MouseEventArgs e)
{
int index = searchResultListBox.SelectedIndex;
if (index == -1)
{
MessageBox.Show("Must select a search result for furthur manipulation");
return;
}
// clear all selected items
personListListBox.ClearSelected();
searchResultListBox.SetSelected(index, true);
personListListBox.SetSelected(matchList[index], true);
}
}
}
|
PHP | UTF-8 | 3,303 | 3.15625 | 3 | [
"MIT"
] | permissive | <?php namespace Helpers;
/**
*This class resolves urls and returns the appropriate url string required
*
*@author Geoffrey Oliver <geoffrey.oliver2@gmail.com>
*@copyright Copyright (c) 2015 - 2020 Geoffrey Oliver
*@link http://libraries.gliver.io
*@category Core
*@package Core\Helpers\Url
*
*/
use Helpers\ArrayHelper;
use Drivers\Registry;
class Url {
/**
*This is the constructor class. We make this private to avoid creating instances of
*this object
*
*@param null
*@return void
*/
private function __construct(){}
/**
*This method stops creation of a copy of this object by making it private
*
*@param null
*@return void
*
*/
private function __clone(){}
/**
*This method returns the base url
*
*@param null
*@return string $url the base url for this application
*@throws this method does not throw an error
*
*/
public static function base($fileName)
{
//get the server name from global $_SERVER[] array()
$base = $_SERVER['SERVER_NAME'];
$url = Registry::getUrl();
//check if there is a uri string
if ( ! empty($url) )
{
//prepend installation folder to server name
$base .= substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], Registry::getUrl()));
}
//there is no query string,
else
{
//prepend installation folder to server name
$base .= substr($_SERVER['REQUEST_URI'], 0);
}
//use https if its defined in the $_SERVER global variable
$protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != "off") ? "https" : "http";
//compose the url string
return $protocol . '://' . $base . $fileName;
}
/**
*This method returns the assets url
*
*@param null
*@return string $url the assets url for this application
*@throws this method does not throw an error
*
*/
public static function assets($assetName)
{
//get the server name from global $_SERVER[] array()
$base = $_SERVER['SERVER_NAME'];
$url = Registry::getUrl();
//check if there is a uri string
if ( ! empty($url) )
{
//prepend installation folder to server name
$base .= substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], Registry::getUrl()));
}
//there is no query string,
else
{
//prepend installation folder to server name
$base .= substr($_SERVER['REQUEST_URI'], 0);
}
//use https if its defined in the $_SERVER global variable
$protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != "off") ? "https" : "http";
//compose the url string
return $protocol . '://' . $base . 'public/' . $assetName;
}
/**
*This method returns the assets url
*
*@param string $string the string to use to compose this url
*@return string $url the full url for this request
*@throws malformed string
*
*/
public static function link( $string = null )
{
//get the server name from global $_SERVER[] array()
$base = $_SERVER['SERVER_NAME'];
//prepend installation folder to server name
$base .= substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], Registry::getUrl()));
//use https if its defined in the $_SERVER global variable
$protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != "off") ? "https" : "http";
//compose the url string
return $protocol . '://' . $base . '<br />';
}
} |
Markdown | UTF-8 | 6,379 | 3.15625 | 3 | [] | no_license | # Nama Anggota Kelompok
Nama | NIM
------------------- | -------------
Muhammad Zein I. F. | 201810370311072
Iqlima Chairunnisa | 201810370311079
Lale Wiega A. C. | 201810370311061
Sarlita Rizka A. | 201810370311075
Tanthowi Jauhari | 201810370311054
# Readme
Disini kami membuat sebuah program implementasi algoritma clipping Liang-Barsky menggunakan OpenGL, kami disini menggunakan Bahasa Pemrograman Python 3.7
# Dokumentasi
## Inisialisasi variabel
Kami menggunakan OpenGL pada python yang disediakan oleh library PyOpenGL, pertama kita melakukan import terlebih dahulu library yang akan digunakan,
```python
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
```
Disini kami melakukan inisialisasi titik pada sebuah kotak
* variable _nx_ dan _ny_ adalah variable untuk melakukan scaling pada window agar terlihat lebih besar
* _x1,y1, x2, y2_ adalah variable titik garis yang akan di clipping
```python
# Insialisasi titik x_min, y_min, sebelum
x_min, y_min = 50, 50
x_max, y_max = 100, 100
#Inisialisasi koordinat tempat scaling kotak,
nx_min, ny_min = 200, 200
nx_max, ny_max = 350, 350
#Inisialisasi t1 dan t2
t1, t2 = 0.0, 1.0
#inisialisasi titik garis
x1, y1 = 0, 0
x2, y2 = 100, 150
```
## Method atau Function untuk cetak pixel pada window
Disini kami membuat function atau method untuk memprojeksikan titik pada window
```python
def myInit():
glLoadIdentity()
glMatrixMode(GL_PROJECTION)
gluOrtho2D(0, 500, 0, 500)
glMatrixMode(GL_MODELVIEW)
def myDisplay():
glClear(GL_COLOR_BUFFER_BIT)
draw_lineAndPort(x1, y1, x2, y2, y_max, y_min, x_max, x_min)
liangBarsky(x1, y1, x2, y2)
glFlush()
def draw_lineAndPort(x1, y1, x2, y2, y_max, y_min, x_max, x_min):
#Penggambaran pixel kotak, menggunakan GL_LINE_LOOP yang akan digunakan untuk menghubungi titik satu sama lain
glColor3d(1, 0, 0)
glBegin(GL_LINE_LOOP)
glVertex2d(x_min, y_min)
glVertex2d(x_max, y_min)
glVertex2d(x_max, y_max)
glVertex2d(x_min, y_max)
glEnd()
#Penggambaran pixel garis, menggunakan GL_LINES yang akan digunakan untuk menghubungkan titik x1,y1 dan x2,y2
glColor3d(1, 1, 1)
glBegin(GL_LINES)
glVertex2d(x1, y1)
glVertex2d(x2, y2)
glEnd()
```
## Method atau Fungsi cliptest() yang digunakan untuk cek parameter

```python
def cliptest(p, q):
t = q / p
global t1, t2
if p == 0 and q < 0:
return False
elif p < 0:
if t > t1:
t1 = t
if t > t2:
return False
elif p > 0:
if t < t2:
t2 = t
if t < t1:
return False
return True
```
## Method atau fungis liangbarsky()
```python
def liangBarsky(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
"""
-t * dx < x1 - x_min ... [1]
t * dx < x_max - x1 ... [2]
-t * dy < y1 - y_min ... [3]
t * dy < y_max - y1 ... [4]
"""
if (
cliptest(-dx, x1 - x_min)
and cliptest(dx, x_max - x1)
and cliptest(-dy, y1 - y_min)
and cliptest(dy, y_max - y1)
):
if t2 < 1:
x2 = x1 + t2 * dx
y2 = y1 + t2 * dy
if t1 > 0:
x1 = x1 + t1 * dx
y1 = y1 + t1 * dy
# Scaling to new View port
scale_x = (nx_max - nx_min) / (x_max - x_min)
scale_y = (ny_max - ny_min) / (y_max - y_min)
# Point pada kotak sebelum di Scaling (the real)
# New coordinates of the points
# Point 1
nx1_real = x1 - x_min + 50
ny1_real = y1 - y_min + 50
# Point 2
nx2_real = x2 - x_min + 50
ny2_real = y2 - y_min + 50
# Point pada Kotak yang sudah di Scaling
# Point 1
nx1 = nx_min + (x1 - x_min) * scale_x
ny1 = ny_min + (y1 - y_min) * scale_y
# Point 2
nx2 = nx_min + (x2 - x_min) * scale_x
ny2 = ny_min + (y2 - y_min) * scale_y
# Plotting new Viewport and clipped line
draw_lineAndPort(nx1, ny1, nx2, ny2, ny_max, ny_min, nx_max, nx_min)
glPointSize(5)
glColor3d(1, 5, 200)
glBegin(GL_POINTS)
glVertex2d(nx1, ny1)
print(
"Titik Bawah Berpotong Pada Atas x = {} dan y = {}".format(
nx1_real, ny1_real
)
)
glVertex2d(nx2, ny2)
print(
"Titik Bawah Berpotong Pada Bawah x = {} dan y = {}".format(
nx2_real, ny2_real
)
)
glVertex2d(nx1_real, ny1_real)
glVertex2d(nx2_real, ny2_real)
glEnd()
```
## Method main()
```python
def main():
glutInit(sys.argv)
glutInitDisplayMode(GLUT_SINGLE or GLUT_RGB)
glutInitWindowPosition(0, 0)
glutInitWindowSize(700, 700)
glutCreateWindow("Liang Barsky")
glutDisplayFunc(myDisplay)
myInit()
glutMainLoop()
return 0
if __name__ == "__main__":
main()
```
# Studi Kasus ...
Disini kami akan mencoba atau melakukan testing , antara lain sebagai berikut
1. Garis Melewati / Memotong semua kotak
2. Garis Hanya memotong sebagian dengan x1,y1 berada pada luar kotak dan x2,y2 berada dalam kotak
3. Garis Hanya memotong sebagaian dengan x1,y1 berada pada dalam kotak dan x2,y2 berada diluar kotak
4. Garis tidak memotong sama sekali
## 1. Garis Melewati / Memotong Semua Kotak
```python
x1, y1 = 0, 0
x2, y2 = 100, 150
```

Dengan titik potong berada pada

## 2. Garis Hanya memotong sebagian dengan x1,y1 berada pada luar kotak dan x2,y2 berada dalam kotak
```python
x1, y1 = 0, 0
x2, y2 = 60, 80
```

Dengan titik potong berada pada

## 3. Garis Hanya memotong sebagaian dengan x1,y1 berada pada dalam kotak dan x2,y2 berada diluar kotak
```python
x1, y1 = 80, 80
x2, y2 = 85, 120
```

Dengan titik potong berada pada

## 4. Garis tidak memotong sama sekali

|
Python | UTF-8 | 3,429 | 2.59375 | 3 | [] | no_license | import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import re
from datetime import date
import numpy as np
def getStateLevelData(startYr, endYr):
gdp = pd.read_csv('Data/SAGDP9N__ALL_AREAS_1997_2019.csv')
gdp = gdp.iloc[:-4]
states = gdp.GeoName.unique()
states = states[:-8]
stateCodes = ['US', 'AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DC', 'DE', 'FL', 'GA', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY']
print(len(stateCodes))
seriesNames = ['CAPUTLG321S', 'CAPUTLG327S', 'CAPUTLG331S', 'CAPUTLG332S', 'CAPUTLG333S', 'CAPUTLHITEK2S','CAPUTLG335S', 'CAPUTLG3361T3S', 'CAPUTLG3364T9S', 'CAPUTLG337S', 'CAPUTLG339S', 'CAPUTLG311A2S', 'CAPUTLG313A4S', 'CAPUTLG315A6S', 'CAPUTLG322S', 'CAPUTLG323S', 'CAPUTLG324S', 'CAPUTLG325S', 'CAPUTLG326S', 'CAPUTLG21S', 'CAPUTLG2211A2S']
seriesNames2 = ['IPG321S', 'IPG327S', 'IPG331S', 'IPG332S', 'IPG333S', 'IPHITEK2S', 'IPG335S', 'IPG3361T3S', 'IPG3364T9S', 'IPG337S', 'IPG339S', 'IPG311A2S', 'IPG313A4S', 'IPG315A6S', 'IPG322S', 'IPG323S', 'IPG324S', 'IPG325S', 'IPG326S', 'IPMINE', 'IPG2211A2N']
NAICS = ['321', '327', '331', '332', '333', '334', '335', '3361-3363', '3364-3369', '337', '339', '311-312', '313-314', '315-316', '322', '323', '324', '325', '326', '21', '22']
print(len(seriesNames), len(seriesNames2), len(NAICS))
uData = pd.read_csv('Data/Fred/'+seriesNames[0]+'.csv')
uData.DATE = pd.to_datetime(uData.DATE, format = '%Y-%m-%d')
uData = uData.set_index('DATE')
iData = pd.read_csv('Data/Fred/IndProduction/'+seriesNames2[0]+'.csv')
iData.DATE = pd.to_datetime(iData.DATE, format = '%Y-%m-%d')
iData = iData.set_index('DATE')
x = uData.loc[startYr+'-01-01':endYr+'-12-01']
stateCapUtilization = pd.DataFrame(index = x.index)
stateIndustrialProduction = pd.DataFrame(index = x.index)
for s in range(len(states)):
print(states[s])
capUt = []
indProd = []
GDP = gdp[gdp.GeoName == states[s]]
for y in np.linspace(int(startYr), int(endYr), int(endYr)-int(startYr)+1): #(1997, 2019, 23):
for q in range(12):
gdpNum = 0
d = 0
ip = 0
sampleDate = str(int(y))+'-'+str(q+1)+'-01'
for n in range(len(NAICS)):
g = float(GDP[GDP.IndustryClassification == NAICS[n]][sampleDate[0:4]].values)*1000000
uData = pd.read_csv('Data/Fred/'+seriesNames[n]+'.csv')
uData.DATE = pd.to_datetime(uData.DATE, format = '%Y-%m-%d')
uData = uData.set_index('DATE')
iData = pd.read_csv('Data/Fred/IndProduction/'+ seriesNames2[n]+'.csv')
iData.DATE = pd.to_datetime(iData.DATE, format = '%Y-%m-%d')
iData = iData.set_index('DATE')
gdpNum = gdpNum + g
d = d + g/(uData.loc[sampleDate].values)
ip = ip + g/(iData.loc[sampleDate].values)
capUt = np.append(capUt, gdpNum/d)
indProd = np.append(indProd, gdpNum/ip)
stateCapUtilization[stateCodes[s]] = capUt
stateIndustrialProduction[stateCodes[s]] = indProd
del(capUt)
del(indProd)
stateCapUtilization.to_csv('Data/StateCapacityUtilization.csv')
stateIndustrialProduction.to_csv('Data/stateIndustrialProductionIndex.csv')
getStateLevelData('1997', '2019') #data for 1997 - 2019
|
Markdown | UTF-8 | 948 | 3.21875 | 3 | [] | no_license | ### Chapter10 - Template - part 2
- The code in this chapter has been taken from chapter 09
- In this tutorial we will try to display the flight data in json format in a new path like **/list/json**
#### <CODE>
- First, download dependencies with `npm install`
- We added a new function to routes module:
exports.listjson = function(req, res){
var flightJsonData = [];
for (var number in flights){
flightJsonData.push(flights[number].getInformation())
}
res.json(flightJsonData);
};
- We added new get `/list/json` in *airlines/app.js* file:
app.get('/list/json',routes.listjson);
- Result will be like below:

- The incorrect way of returning json is present at <http://localhost:3000/list/incorrectjson>
 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.