language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Python
UTF-8
1,957
4.375
4
[]
no_license
""" Given a string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000. Example 1: Input: "abab" Output: True Explanation: It's the substring "ab" twice. Example 2: Input: "aba" Output: False Example 3: Input: "abcabcabcabc" Output: True Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.) """ def is_substring_helper (data): print('original string: {}'.format(data)) # max substr length is half of the length of the string max_sub_str_len = int(len(data)/2) for window in range(1, max_sub_str_len+1): # if the string length is not a multiple of the window, move on if len(data)%window != 0: continue # get letters in window substr = data[0:window] # get number of multiples of window needed to create data multiples = int(len(data)/window) # create the substring new_str = ''.join([substr for i in range(multiples)]) # see if it is the same as data if new_str == data: return True # if no matches, return False return False #DON NOT CHANGE THIS FUNCTION def is_substring (string_input): return is_substring_helper(string_input) #test case def main(): TEST_CASE1 = "abab" TEST_CASE2 = "aba" TEST_CASE3 = "abcabcabcabc" print ("Testing your code with TEST_CASE1, the expected output is True, your output is {}".format(is_substring(TEST_CASE1))) print ("Testing your code with TEST_CASE2, the expected output is False, your output is {}".format(is_substring(TEST_CASE2))) print ("Testing your code with TEST_CASE3, the expected output is True, your output is {}".format(is_substring(TEST_CASE3))) if __name__ == "__main__": main()
C++
UTF-8
3,045
2.8125
3
[ "BSD-3-Clause", "LicenseRef-scancode-free-unknown", "MIT" ]
permissive
// MemPool.h // Created by Robin Rowe on 12/2/2015 // Copyright (c) 2015 Robin.Rowe@CinePaint.org #ifndef AtomicMemPool_h #define AtomicMemPool_h #include <memory> #include <atomic> #include <mutex> namespace Atomic { // Usage: HiddenMemPool intended for internal use class HiddenMemPool { std::unique_ptr<char[]> data; std::atomic<unsigned> bytes; const unsigned size; static void SetBlockSize(char* block,unsigned blockSize) { memcpy(block,&blockSize,sizeof(blockSize)); } public: HiddenMemPool(unsigned size) : size(size) { data=std::unique_ptr<char[]>(new char[size]); } bool IsEmpty() const { return 0==bytes; } static unsigned GetBlockSize(char* block) { if(!block) { return 0; } unsigned blockSize; memcpy(&blockSize,block-sizeof(blockSize),sizeof(blockSize)); return blockSize; } char* NewBlock(unsigned blockSize) { blockSize+=sizeof(blockSize); const unsigned end=bytes.fetch_add(blockSize,std::memory_order_relaxed); if(end>=size) { return 0; } char* rawBlock=data.get()+end-blockSize; SetBlockSize(rawBlock,blockSize); return rawBlock+sizeof(blockSize); } void FreeBlock(char* block) { const int blockSize=GetBlockSize(block); bytes.fetch_sub(blockSize,std::memory_order_relaxed); } bool IsMyBlock(char* block) { block-=sizeof(size); if(block<data.get() || block>=data.get()) { return false; } return true; } }; // Usage: Atomic::MemPool memPool(memoryBufferSize); // const unsigned size=200; // char* block=memPool.NewBlock(size); // memPool.FreeBlock(block); // Note: size==memPool.BlockSize(block); class MemPool { HiddenMemPool a; HiddenMemPool b; HiddenMemPool* activePool; typedef std::lock_guard<std::mutex> LockGuard; std::mutex switchMutex; bool SwitchPools() { if(&a==activePool) { if(!b.IsEmpty()) { return false; } activePool=&b; return true; } if(!a.IsEmpty()) { return false; } activePool=&a; return true; } public: MemPool(unsigned size) : a(size/2) , b(size/2) { activePool=&a; } char* NewBlock(unsigned blockSize) { char* data=activePool->NewBlock(blockSize); if(data) { return data; } LockGuard lockGuard(switchMutex);//Lock only on wrap-around data=activePool->NewBlock(blockSize);//re-entrant if(data) { return data; } if(!SwitchPools()) { return 0; } data=activePool->NewBlock(blockSize); return data; } bool FreeBlock(char* block) { if(a.IsMyBlock(block)) { a.FreeBlock(block); return true; } if(b.IsMyBlock(block)) { b.FreeBlock(block); return true; } return false; } unsigned GetBlockSize(char* block) { return HiddenMemPool::GetBlockSize(block); } }; // Usage: Atomic::MemPoolBlock memPoolBlock(memPool,packetQueue.Pop()); // char* p=memPoolBlock.get(); // Note: Destructor will automatically free block class MemPoolBlock { MemPool& memPool; char* block; public: ~MemPoolBlock() { memPool.FreeBlock(block); } MemPoolBlock(MemPool& memPool,char* block) : memPool(memPool) , block(block) {} char* get() { return block; } }; } #endif
C++
UTF-8
1,350
2.71875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #define WHITE 0 #define BLACK 2 #define GREY 1 #define MAX 100000 void dfs(int s); void reset(); vector <int> graph[10000]; int n,m,t=0,d[200],f[200],vis[200],task[200]; int main() { //freopen("Ordering-Task.txt","r",stdin); int i,j,x,y; n=200; while(1) { reset(); cin >> n >> m; if(n==0 && m==0) return 0; for(i=0;i<m;i++) { cin >> x >> y; graph[x].push_back(y); } dfs(1); for(i=1;i<=n;i++) { for(j=i+1;j<=n;j++) { if(f[j] > f[i]) { swap(f[j],f[i]); swap(task[i],task[j]); } } } for(i=1;i<=n;i++) cout << task[i] << " "; cout << endl; } } void dfs(int s) { int i; t++; d[s] = t; vis[s] = GREY; for(i=0;i<graph[s].size();i++) { if(vis[graph[s][i]] == WHITE) { dfs(graph[s][i]); } } vis[s] = BLACK; t++; f[s] = t; } void reset() { int i; for(i=0;i<=n;i++) { graph[i].clear(); vis[i] = WHITE; d[i] = MAX; f[i] = MAX; task[i] = i; } }
JavaScript
UTF-8
787
3.109375
3
[]
no_license
var fn1 = function(){ return async function(next){ console.log('go1'); await next(); console.log('back1'); } } var fn2 = function(){ return async function(next){ console.log('go2'); await next(); console.log('back2'); } } var fn3 = function(){ return async function(next){ console.log('go3'); await next(); console.log('back3'); } } function compose(middleware){ var index = -1; return function(){ return dispatch(0) function dispatch(i){ if(i>=middleware.length) return Promise.resolve(); if(i<=index) throw new error('next 不能调用多次'); index = i; var fn = middleware[i]; return Promise.resolve(fn(function(){ dispatch(++i); })) } } } compose([fn1(),fn2(),fn3()])()
Python
UTF-8
417
4.1875
4
[]
no_license
#functions: def gcd(x,y): if (x==y): ans=x else: if(x>y): ans=gcd((x-y),y) else: ans=gcd(x,(y-x)) return ans #code: print("I will give you the Greatest Common Divisor of two int. numbers") a=int(input("give me the first number: ")) b=int(input("give me the second number: ")) rgcd= gcd(a,b) print("the Greatest Common Divisor of ",a," and ",b," is: ",rgcd)
SQL
ISO-8859-9
303
3.46875
3
[]
no_license
--4. 01.02.2007 - 05.03.2014 tarihleri arasnda hangi rnden ka adet sipari edildiini bulan SQL kodunu yaznz. use Dukkan select u.urunKod, u.urunAd, sd.adet, s.siparisTarih from tblUrun u,tblSiparisDetay sd, tblSiparis s where s.siparisTarih between '2007-02-01' and '2014-03-05'
PHP
UTF-8
1,285
3.4375
3
[]
no_license
<?php $str1 = 'aabbaa'; $str2 = 'race a car'; function checkpalimdronie($str){ $str2 = (strrev(preg_replace("/[^A-Za-z0-9]/", '', str_replace(' ', '', strtolower($str))))); return ($str2 == $str) ? TRUE : FALSE; } echo'<pre>';var_dump( (checkpalimdronie($str1)) );echo'</pre>'; $arrValues = [1, 1, 2, 2, 3, 4, 4, 5, 5, 99, 99, 55, 55]; function isDuplicate($arr){ $data = array_count_values($arr); foreach($data as $key => $v){ if($v == 1) return $key; } } echo isDuplicate($arrValues ); /*============================*/ /* */ /*============================*/ $intReverse = -978683475; function reverseinteger($int){ $type = ($int > 0) ? '+' : '-'; $data = ''; $int = abs($int); while(($int) > 0){ $temp = $int%10; $data .= $temp; $int = floor($int/10); } return ($type == '+') ? $data : -$data; } echo reverseinteger($intReverse); /*============================*/ /* */ /*============================*/ function reverseVouwls($str){ $vouwels = ['a' , 'e' , 'i' , '0' , 'u']; $char = str_split($str); $replacement = array_intersect($char , $vouwels); $replacement = array_combine(array_keys($replacement) , array_reverse($replacement)); $char = array_replace($char , $replacement); return implode('' , $char); } echo reverseVouwls('stackoverflow');
Java
UTF-8
1,018
2.8125
3
[]
no_license
package com.astontech.bo; import java.time.LocalDate; import java.util.Date; public class Vehicle extends BaseBO{ //Params private int VehicleId; private VehicleModel Model; private LocalDate Year; private String VIN; //Constructors public Vehicle() {} public Vehicle(LocalDate year, String vin, VehicleModel model) { this.setYear(year); this.setVIN(vin); this.setModel(model); } //Setters and Getters public int getVehicleId() { return VehicleId; } public void setVehicleId(int vehicleId) { VehicleId = vehicleId; } public LocalDate getYear() { return Year; } public void setYear(LocalDate year) { Year = year; } public String getVIN() { return VIN; } public void setVIN(String VIN) { this.VIN = VIN; } public VehicleModel getModel() { return Model; } public void setModel(VehicleModel model) { Model = model; } }
JavaScript
UTF-8
3,213
2.578125
3
[]
no_license
import React from 'react' import Post from './component/Post' import './scss/App.scss' import Input from '@material-ui/core/Input' import Button from '@material-ui/core/Button' import { filtersPosts } from './shared/utils' import * as _ from 'lodash' function App() { const [ data, setData ] = React.useState([]) const [ sortSwitch, setSortSwitch ] = React.useState(false) const [ sortValue, setSortValue ] = React.useState('По возрастанию') const [ inputValue, setInputValue ] = React.useState('') const [ loaded, setLoaded ] = React.useState(false) const [ renderData, setRenderData ] = React.useState([]) React.useEffect(() => { // Получение данных fetch('https://api.stackexchange.com/2.2/search?intitle=react&site=stackoverflow') .then((post) => post.json()) .then((post) => { const dataPosts = post.items.filter((el) => { return el.is_answered && el.owner.reputation >= 50 // фильтруем нужные данные }) setData(dataPosts) setLoaded(true) // устанавливаем флаг true, после получения постов }) .catch((r) => console.log(r)) }, []) React.useEffect( // меняем текст кнопки в зависимости от значения переключателя () => { if (!sortSwitch) setSortValue('По возрастанию') else setSortValue('По убыванию') }, [ sortSwitch ] ) React.useEffect( () => { // после загрузки данных добавлем их в массив, который будет рендериться if (loaded) { setRenderData([ ...filtersPosts(data, inputValue) ]) } }, [ inputValue, loaded, data ] ) // так же если мы будет набирать текст, то будет происходить фильтрация const handlerOnChange = (e) => { setInputValue(e.target.value) } const handlerOnckicksort = () => { const sort = _.sortBy(data, function(item) { // сортируем по возрастанию return item.creation_date }) if (!sortSwitch) { // если перекоючаталь true отправляем в состояния рендера массив по возрастанию setRenderData(sort) } else { setRenderData(_.reverse(sort)) // иначе переворачиваем его } setSortSwitch(!sortSwitch) // после нажатия меняем флаг сортировки } return ( <div> <Button className="sort-btn" onClick={handlerOnckicksort} variant="contained" color="primary" style={{fontSize: 'calc(6px + 6 * (100vw/1800))'}}> {sortValue} </Button> <div className="container"> <Input className="container__input" onChange={handlerOnChange} value={inputValue} placeholder="Search" inputProps={{ 'aria-label': 'description' }} /> <div className="container__post"> {!loaded ? ( <div className="container__loading">Loading...</div> ) : ( renderData.map(el=> ( <Post key={el.question_id} post={el} /> )) )} </div> </div> </div> ) } export default App
C
UTF-8
1,166
3.3125
3
[]
no_license
#include "case.h" int main(int argc, char* argv[]) { case1(); case2(); case3(); case4(); case5(); case6(); case7(); case8(); case9(); case10(); return 0; } void case1() { int i = add(1, 2); } int __fastcall add(int i, int j) { return i + j; } void case2() { int i = 1; int a[4]; a[0] = 6; a[1] = 7; a[i + 1] = 8; } typedef struct _Rec { int i; char c; int j; }Rec; void case3() { Rec x; x.j = 1; x.c = x.j; x.i = x.j; } typedef struct _TreeNode { int val; struct _TreeNode *lchild, *rchild; }TreeNode; void case4() { TreeNode* p = (TreeNode*)malloc(sizeof(TreeNode)); p->lchild = p; p = p->rchild; } void case5() { int x, y; if(x > y) y++; else x--; } void case6(){ int i = 1; int a[3][3]; a[0][0] = 6; a[1][1] = 7; a[1][i+1] = 8; } typedef struct _Cub{ int i; union{ char c; int j; }u; }Cub; void case7(){ Cub x; x.i = 1; x.u.c = x.i; x.u.j = x.i; } void case8(){ TreeNode* p = (TreeNode*)malloc(sizeof(TreeNode)); TreeNode** pp = &p; (*pp) -> val = 1; } void case9(){ int x,y; while (x < y){ y -= x; } } void case10(){ int x,y; x = 1; y = 3; x = ((x < y) || ((y = x > y) == 0)); }
JavaScript
UTF-8
2,569
2.65625
3
[]
no_license
const Course = require('../models/Course'); const { mongooseToObject } = require('../../utils/mongoose'); class CourseController { // [GET] /courses/:slug show(req, res, next) { const slug = req.params.slug; Course.findOne({ slug: slug }) .then((course) => res.render('courses/show', { course: mongooseToObject(course) })) .catch(next); } // [GET] courses/create create(req, res, next) { res.render('courses/create'); } // [GET] courses/:id/edit edit(req, res, next) { const { id } = req.params; Course.findById(id) .then((course) => res.render('courses/edit', { course: mongooseToObject(course) })) .catch(next); } // [PUT] /courses/:id update(req, res, next) { const { id } = req.params; const data = req.body; Course.updateOne({ _id: id }, data) .then(() => res.redirect('/me/stored/courses')) .catch(next); } // [DELETE] /courses/:id destroy(req, res, next) { const { id } = req.params; // Sử dụng soft delete với lib (trong db sẽ thêm trường deleted: true) Course.delete({ _id: id }) .then(() => res.redirect('back')) .catch(next); } // [DELETE] /courses/:id/force forceDestroy(req, res, next) { const { id } = req.params; // Xóa thật trong mongodb Course.deleteOne({ _id: id }) .then(() => res.redirect('back')) .catch(next); } // [PATCH] /courses/:id/restore restore(req, res, next) { const { id } = req.params; // Sử dụng soft delete với lib (trong db sẽ thêm trường deleted: true) Course.restore({ _id: id }) .then(() => res.redirect('back')) .catch(next); } // [POST] courses/store store(req, res, next) { const formData = req.body; formData.image = `https://img.youtube.com/vi/${formData.videoId}/sddefault.jpg`; const course = new Course(formData); course .save() .then(() => res.redirect('/me/stored/courses')) .catch(next); // res.send('COURSE SAVED!'); } // [POST] /courses/handle-form-actions handleFormActions(req, res, next) { const action = req.body.action; const listCourseIds = req.body.courseIds; switch (action) { case 'delete': // Xóa khóa học mà có _id nằm trong listCourseIds Course.delete({ _id: { $in: listCourseIds } }) .then(() => res.redirect('back')) .catch(next); break; default: res.json({ message: 'Action invalid!!!' }); } } } module.exports = new CourseController();
Markdown
UTF-8
1,522
2.671875
3
[ "Apache-2.0" ]
permissive
--- layout: post title: "开发者可通过 Google Analytics 来跟踪自己扩展的使用率了" date: 2010-09-10 07:40 author: Eyon comments: true tags: [Chrome, Chrome扩展, Chrome新闻, Chromium] --- Google 的软件工程师 Qian Huang(中国人?)今天在 Chromium 官方博客上[宣布](http://blog.chromium.org/2010/09/get-more-data-about-your-extensions.html) Chrome 扩展开发者可以使用 Google Analytics 来对自己扩展的流量进行监控了,该功能可以帮助开发者更好的了解有多少用户访问过自己的扩展页面、他们从哪里来、是否带走了一片云彩等等… <a href="http://img.chromi.org/2010/09/AnalyticsImageBlogPost.png">![](http://img.chromi.org/2010/09/AnalyticsImageBlogPost.png "AnalyticsImageBlogPost")</a> 从今天起,开发者可以为每个具体的扩展指定一个 Google Analytics 配置文件,然后就可以通过 Google Analytics 帐号跟踪你扩展页面的访问量了。最强大的是,你还可以跟踪你的扩展在用户的电脑上安装之后的使用率,[点击这里](http://code.google.com/chrome/extensions/tut_analytics.html)了解详细信息。 如果在使用过程中还遇到了什么问题的话,可以去 Google 官方的[开发者讨论组](https://groups.google.com/a/chromium.org/group/chromium-extensions/topics)发贴求助,当然也可以到Chrome迷论坛问问看有没有人知道。 via [Chromium Blog](http://blog.chromium.org/2010/09/get-more-data-about-your-extensions.html)
Java
UTF-8
202
2
2
[]
no_license
package com.hoolai.Service; public class TestService { public static int num = 1; public static int getNum() { return num; } public static void setNum(int num) { TestService.num = num; } }
TypeScript
UTF-8
2,309
3.296875
3
[]
no_license
/** * Get the user logged from the local storage */ export function getUserLogged() { return JSON.parse(localStorage.getItem('userLogged') || 'null'); } /** * Remove the user logged from the local storage */ export function removeUserLogged() { localStorage.removeItem('userLogged'); } /** * Set the user logged on the local storage */ export function setUserLogged(userLogged: object) { if (process.env.NODE_ENV === 'development') { // console.tron.log('userLogged ^'); // console.tron.log(userLogged); } localStorage.setItem('userLogged', JSON.stringify(userLogged)); } /** * Get some value from the local storage */ export function getLocalStorage(key: string, defaultValue: any) { if (typeof defaultValue === 'string') { return localStorage.getItem(key) ? JSON.parse(localStorage.getItem(key) || '') : defaultValue; } if (typeof defaultValue === 'number') { return localStorage.getItem(key) ? JSON.parse(localStorage.getItem(key) || '0') : defaultValue; } return JSON.parse(localStorage.getItem(key) || JSON.stringify(defaultValue)); } /** * Remove some value from the local storage */ export function removeLocalStorage(key: string) { localStorage.removeItem(key); } /** * Set some value on the local storage */ export function setLocalStorage(key: string, value: any) { if (typeof value === 'number') { localStorage.setItem(key, `${value}`); } else { localStorage.setItem(key, JSON.stringify(value)); } } /** * Check if str is not empty */ export function notEmpty(str: string | undefined) { return typeof str !== 'undefined' && str !== null && str !== ''; } /** * Check if str is not empty */ export function isEmpty(str: string | undefined) { return typeof str === 'undefined' || str === null || str === ''; } /** * Checks if a string is empty (including containing several empty spaces) * @param str string to check * @returns boolean */ export function isEmptyWithTrim(str: string) { return isEmpty(str.trim()); } /* * Return a value from .env file if key given exists. Default value otherwise */ export const getEnvVar = (envKey: string, defaultValue: string): string => { return isEmpty(process.env[envKey]) ? (defaultValue as string) : (process.env[envKey] as string); };
C
UTF-8
261
2.96875
3
[]
no_license
//hashing function for use in assignment int hashName(char *string) { int i = 0; int value = 0; while(*(string + i) != '\0') { value = value + *(string + i) - 64; i = i + 1; } return value % 1000000; } int hashID(int id) { return id % 1000000; }
C++
UTF-8
1,362
3.046875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; vector<vector<int>> dir ={{-2,1} , {-1,2} , {1,2} , {2,1} , {2,-1}, {1,-2} , {-1,-2} ,{-2,-1}}; // bool isValid(int x, int y, vector<vector<int>> ans) // { //cout<<"a"<<isVisited[0].size(); // //cout<<"b"<<isVisited.size(); // if( x >= 0 && y >= 0 && x < ans.size() && y < ans[0].size() && ans[x][y] == 0) // { // return true; // } // return false; // } void knightPath_Fill(int sr,int sc,int count,int Boxes,vector<vector<int>> ans) { if(count == Boxes ) { ans[sr][sc] = count; for(auto arr : ans) { for(int ele : arr) cout<<ele<<" "; cout<<endl; } cout<<endl; ans[sr][sc] = 0; return ; } ans[sr][sc] = count; for(int d = 0 ; d < dir.size() ; d++) { int x = sr + dir[d][0]; int y = sc + dir[d][1]; if( x >= 0 && y >= 0 && x < ans.size() && y < ans[0].size() && ans[x][y] == 0) { knightPath_Fill(x , y , count + 1 , Boxes , ans ); } } ans[sr][sc] = 0; return ; } int main(){ int n , r , c; cin >> n >> r >> c; vector<vector<int>>ans(n , vector<int>( n , 0 )); knightPath_Fill( r,c, 1 , n*n , ans ); cout << endl; return 0; }
JavaScript
UTF-8
221
2.859375
3
[]
no_license
function firstDuplicate(a) { let obj = {} let duplicate = -1; for (let num of a) { obj[num] = (obj[num]|| 0) + 1; duplicate = obj[num] > 1 && duplicate < 0 ? num : duplicate; } return duplicate; }
Java
UTF-8
476
3.046875
3
[]
no_license
package com.umbertoloria.integrates; import com.umbertoloria.bitting.Bit; import com.umbertoloria.interfaces.Clockable; public class AND implements Clockable { private Bit[] in; private Bit out; public AND(int size) { in = new Bit[size]; } public void set(int index, Bit val) { in[index] = val; } public void clock() { for (Bit b : in) { if (!b.get()) { out.disable(); return; } } out.enable(); } public Bit get() { return out; } }
PHP
UTF-8
1,277
2.6875
3
[]
no_license
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); function stringShort($title,$limitLengthTitle){ $length_title=strlen($title); if($length_title>$limitLengthTitle) { $title_new=array(); unset($title_new); $title_new=$title; $title_new = explode(" ", $title_new); $title_print=" "; for($i=0; $i<$length_title; $i++) { $title_print=$title_print.$title_new[$i]." "; if(strlen(trim($title_print))>=$limitLengthTitle) { $title_album=trim($title_print)."..."; break;} } } else { $title_album=trim($title);} return $title_album; } function img_local($type_image,$size,$name_image){ switch ($type_image) { case 'L': switch ($size) { case 1024:$resource='resource/image/body/images/image-1024/'.$name_image;break; case 600:$resource='resource/image/body/images/image-600/'.$name_image;break; case 400:$resource='resource/image/body/images/image-400/'.$name_image;break; } break; case 'I':$resource=$name_image;break; } return $resource; }
Python
UTF-8
882
3.75
4
[]
no_license
#! /usr/bin/env python # -*- coding:utf-8 -*- # @Time : 2017/6/17 22:46 # @Author : xiongyaokun # @Site : # @File : practice36.py # @Software: PyCharm # 'and' example print "'and'example:" print "False and 12 is:", False and 12 # 'del' example, 'del'只是删除引用, if __name__ == "__main__": a = 1 b = a c = b del b, c print "'del'example:" print a # lists 中保存的是变量 lists[0],lists[1..., 而不是真实的数据 0,1,2,3,4,5 if __name__ == "__main__": lists = [0, 1, 2, 3, 4, 5] a = lists[0] del lists[0] print "'del'example:" print a # 'assert' example, assert是声明其断言值必须为真的语法,如果发生异常就说明表达式为假 # assert 2 == 1, '2不等于1' #会报异常 # assert 2 == 2 #不会报异常 # 'isinstance' example, isinstance('Hello', str)
C#
UTF-8
1,069
2.890625
3
[]
no_license
using Microsoft.AspNetCore.Http; using System; using System.Threading.Tasks; namespace MyWebsite.Middlewares { public class FirstMiddleware { private readonly RequestDelegate _next; public FirstMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { if (context.Request.Path.Value.IndexOf("/error/middleware/before-action", StringComparison.CurrentCultureIgnoreCase) != -1) { throw new Exception($"Exception from {GetType().Name} in. \r\n"); } await context.Response.WriteAsync($"{GetType().Name} in. \r\n"); await _next(context); if (context.Request.Path.Value.IndexOf("/error/middleware/after-action", StringComparison.CurrentCultureIgnoreCase) != -1) { throw new Exception($"Exception from {GetType().Name} out. \r\n"); } await context.Response.WriteAsync($"{GetType().Name} out. \r\n"); } } }
Markdown
UTF-8
6,285
3.4375
3
[]
no_license
# day_1 1. 引擎: 负责整个js程序的编译和执行过程 2. 编译器: 负责语法分析和代码生成 3. 作用域: 负责收集并维护由所有声明的标识符(变量)组成的一系列查询,并且实施一套非常严格的规则,确定当前执行的代码对这些标志符有访问权限。 分析:`var a = 1;` - 声明a: 当前作用域是否有a,如果有,跳过声明,如果没有声明a - 给a赋值: 从作用域查找是否有a,如果有,给a赋值,如果没有继续查找 ## LHS,RHS 当变量出现在赋值操作的左侧时进行LHS查询,出现在右侧时进行RHS查询。 **RHS: 查找某个变量的值, 谁是赋值操作的源头** **LHS: 找到变量的容器, 赋值操作的目标是谁** LHS: 对谁赋值 RHS: 把谁的值赋值给变量 ```js function foo(a){ console.log(a); } foo(2); ``` RHS: foo LHS: a RHS: console RHS: a ```js function foo(a){ var b = a; // 找到a的值 return a + b; // 找到a的值,找到b的值 } var c = foo(2); // 找到foo的值 ``` LHS: c RHS: foo LHS: a LHS: b RHS: a RHS: a RHS: b LHS:3 RHS:4 ??不知道是不是对 描述上面代码的LHS和RHS: LHS: - 查找foo - 查找a - 查找b RHS: - 找到a的值 - 找到a的值 - 找到b的值 - 找到foo的值 ## 词法作用域 词法作用域就是定义在词法阶段的作用域。换句话说,词法作用域是由你在写代码时将变量和块作用域写在哪里来决定的,因此当词法分析器处理代码时会保持作用域不变(大部分情况下是这样的)。 作用域查找会在找到第一个匹配的标识符时停止。在多层的嵌套作用域中可以定义同名的标识符,这叫作“遮蔽效应”(内部的标识符“遮蔽”了外部的标识符)。 无论函数在哪里被调用,也无论它如何被调用,它的词法作用域都只由函数被声明时所处的位置决定。 词法作用域查找只会查找一级标识符,比如a、b和c。如果代码中引用了foo.bar.baz,词法作用域查找只会试图查找foo标识符,找到这个变量后,对象属性访问规则会分别接管对bar和baz属性的访问。 欺骗词法作用域会导致性能下降。 JavaScript中的eval(..)函数可以接受一个字符串为参数,并将其中的内容视为好像在书写时就存在于程序中这个位置的代码。 在执行eval(..)之后的代码时,引擎并不“知道”或“在意”前面的代码是以动态形式插入进来,并对词法作用域的环境进行修改的。引擎只会如往常地进行词法作用域查找 在严格模式的程序中,eval(..)在运行时有其自己的词法作用域,意味着其中的声明无法修改所在的作用域。 JavaScript中还有其他一些功能效果和eval(..)很相似。setTimeout(..)和setInterval(..)的第一个参数可以是字符串,字符串的内容可以被解释为一段动态生成的函数代码。这些功能已经过时且并不被提倡。不要使用它们!new Function(..)函数的行为也很类似,最后一个参数可以接受代码字符串,并将其转化为动态生成的函数(前面的参数是这个新生成的函数的形参)。这种构建函数的语法比eval(..)略微安全一些,但也要尽量避免使用。 JavaScript中另一个难以掌握(并且现在也不推荐使用)的用来欺骗词法作用域的功能是with关键字。 with通常被当作重复引用同一个对象中的多个属性的快捷方式,可以不需要重复引用对象本身。 ```js var obj = { a: 1, b: 2, c: 3 }; obj.a = 2; obj.b = 3; obj.c = 4; with (obj) { a = 3; b = 4; c = 5; } ``` with可以将一个没有或有多个属性的对象处理为一个完全隔离的词法作用域,因此这个对象的属性也会被处理为定义在这个作用域中的词法标识符。 尽管with块可以将一个对象处理为词法作用域,但是这个块内部正常的var声明并不会被限制在这个块的作用域中,而是被添加到with所处的函数作用域中。 eval(..)函数如果接受了含有一个或多个声明的代码,就会修改其所处的词法作用域,而with声明实际上是根据你传递给它的对象凭空创建了一个全新的词法作用域。 JavaScript中有两个机制可以“欺骗”词法作用域:eval(..)和with。前者可以对一段包含一个或多个声明的“代码”字符串进行演算,并借此来修改已经存在的词法作用域(在运行时)。后者本质上是通过将一个对象的引用当作作用域来处理,将对象的属性当作作用域中的标识符来处理,从而创建了一个新的词法作用域(同样是在运行时)。 ## 函数作用域和块作用域 无论标识符声明出现在作用域中的何处,这个标识符所代表的变量或函数都将附属于所处作用域的气泡。 函数作用域的含义是指,属于这个函数的全部变量都可以在整个函数的范围内使用及复用(事实上在嵌套的作用域中也可以使用) 为什么“隐藏”变量和函数是一个有用的技术? 有很多原因促成了这种基于作用域的隐藏方法。它们大都是从最小特权原则中引申出来的,也叫最小授权或最小暴露原则。这个原则是指在软件设计中,应该最小限度地暴露必要内容,而将其他内容都“隐藏”起来,比如某个模块或对象的API设计。 “隐藏”作用域中的变量和函数所带来的另一个好处,是可以避免同名标识符之间的冲突,两个标识符可能具有相同的名字但用途却不一样,无意间可能造成命名冲突。冲突会导致变量的值被意外覆盖。 首先,包装函数的声明以(function...而不仅是以function...开始。尽管看上去这并不是一个很显眼的细节,但实际上却是非常重要的区别。函数会被当作函数表达式而不是一个标准的函数声明来处理。 区分函数声明和表达式最简单的方法是看function关键字出现在声明中的位置(不仅仅是一行代码,而是整个声明中的位置)。如果function是声明中的第一个词,那么就是一个函数声明,否则就是一个函数表达式。
Java
UTF-8
321
1.773438
2
[]
no_license
package com.defysope.service; import java.util.List; import java.util.Map; import com.defysope.model.DeliveryMethod; public interface DeliveryMethodSettingsManager { List<Map<String, Object>> getDelivery(); DeliveryMethod saveMethod(DeliveryMethod delivery); void removeDelivery(int id); }
Markdown
UTF-8
4,061
3.75
4
[]
no_license
# 필드 이름 바꾸기 > 이름은 중요하다. 그리고 프로그램 곳곳에서 쓰이는 레코드 구조체의 필드 이름들은 특히 더 중요하다. 프로그램을 이해하는데 큰 역할을 한다. > 데이터 구조가 중요한 만큼 반드시 깔끔하게 관리해야 한다. 다른요소와 마찬가지로 개발을 진행할수록 데이터를 더 잘이해하게 된다. 따라서 그 깊어진 이해를 프로그램에 반드시 반영해야 한다. ex:) ```js class Organization { get name() {...} } //Refactoring class Organization { get title() {...} } ``` #### 절차 1. 레코드의 유효범위가 제한적이라면 필드에 접근하는 모든 코드를 수정한 후 테스트한다. 이후 단계는 필요없다. 2. 레코드가 캡슐화되지 않았다면 우선 레코드를 캡슐화 한다. 3. 캡슐화된 객체 안의 private 필드명을 변경하고, 그에 맞게 내부 메서드들을 수정한다. 4. 테스트 5. 생성자의 매개변수 중 필드와 이름이 겹치는게 있다면 함수 선언 바꾸기로 변경 6. 접근자들의 이름도 바꿔준다. #### 예시 ```js //다음의 상수가 하나 있다. const organization = {name: "애크미 구스베리", country: "GB"}; 여기서 "name"을 "title"로 바꾸고 싶다고 해보자, 이 객체는 코드베이스 곳곳에서 사용되며, 그중 이 제목을 변경하는 곳도 있다. 2.그래서 우선 organization 레코드를 클래스로 캡슐화 한다. class Organization { constructor(data) { this._name = data.name; this._country = data.country; } get name() {return this._name;} set name(aString) {this._name = aString;} get country() {return this._country;} set country(aCountryCode) {this._country = aCountryCode;} } const organization = new Organization({name: "애크미 구스베리", country: "GB"}); 입력 데이터 구조를 내부 데이터 구조로 복제했으므로 둘을 구분해야 독립적으로 작업할수 있다. 3.별도의 필드를 정의하고 생성자와 접근자에서 둘을 구분해 사용하도록 하자 //Organization class class Organization { constructor(data) { this._title = data.name; this._country = data.country; } get name() {return this._title;} set name(aString) {this._title = aString;} get country() {return this._country;} set country(aCountryCode) {this._country = aCountryCode;} } 다음으로 생성자에서 "title"도 받아들일 수 있도록 조치한다. class Organization { constructor(data) { this._title = (data.title !== undefined) ? data.title : data.name; this._country = data.country; } get name() {return this._title;} set name(aString) {this._title = aString;} get country() {return this._country;} set country(aCountryCode) {this._country = aCountryCode;} } 이제 이생성자를 호출하는 곳을 모두 찾아서 새로운 이름인 "title"을 사용하도록 하나씩 수정 const organization = new Organization({title: "애크미 구스베리",country: "GB"}); 모두 수정했다면 생성자에서 "name"을 사용할 수 있게 하던 코드를 제거한다. //Organization class class Organization { constructor(data) { this._title = data.title; this._country = data.country; } get name() {return this._title;} set name(aString) {this._title = aString;} get country() {return this._country;} set country(aCountryCode) {this._country = aCountryCode;} } 6.이제 생성자와 데이터가 새로운 이름을 사용하게 됬으니 접근자도 수정할 수 있게되었다. 단순히 접근자 각각의 이름을 바꿔주면 된다.(함수이름 바꾸기) class Organization { constructor(data) { this._title = data.title; this._country = data.country; } get title() {return this._title;} set title(aString) {this._title = aString;} get country() {return this._country;} set country(aCountryCode) {this._country = aCountryCode;} } ```
Java
UTF-8
271
1.84375
2
[]
no_license
package com.htc.day3; public class EmployeeTest { public static void main(String[] args) { // TODO Auto-generated method stub Employee ram = new Employee(); // ram.readInputs(); ram.display(); // ram.tryThis(); wont work } }
Java
UTF-8
1,109
2.4375
2
[ "Apache-2.0" ]
permissive
/* * Taken from https://bitbucket.org/atlassian/jira-testkit * which is licenced under Apache 2.0 */ package com.corefiling.jira.plugins.workflowdata; public class CacheControl { private static final int ONE_YEAR = 60 * 60 * 24 * 365; /** * Returns a CacheControl with noStore and noCache set to true. * * @return a CacheControl */ public static javax.ws.rs.core.CacheControl never() { javax.ws.rs.core.CacheControl cacheNever = new javax.ws.rs.core.CacheControl(); cacheNever.setNoStore(true); cacheNever.setNoCache(true); return cacheNever; } /** * Returns a CacheControl with a 1 year limit. Effectively forever. * * @return a CacheControl */ public static javax.ws.rs.core.CacheControl forever() { javax.ws.rs.core.CacheControl cacheForever = new javax.ws.rs.core.CacheControl(); cacheForever.setPrivate(false); cacheForever.setMaxAge(ONE_YEAR); return cacheForever; } // prevent instantiation private CacheControl() { // empty } }
Python
UTF-8
677
3.40625
3
[]
no_license
import sqlite3 conn = sqlite3.connect("sqlite3-python/my_friends.db") """ to check if connection is working do: sqlite3 my_friends.db check: .tables check. schema + table_name the db most already be creat inorder for code to run; first run learning_to_insert.py """ # create cursor object c = conn.cursor() people = [ ("Roald","Amundsen", 5), ("Rosa", "Parks", 8), ("Henry", "Hudson", 7), ("Neil","Armstrong", 7), ("Daniel", "Boone", 3)] # for person in people: # c.execute("INSERT INTO friends VALUES (?,?,?)", person) # Insert all at once c.executemany("INSERT INTO friends VALUES (?,?,?)", people) # commit changes conn.commit() conn.close()
C#
UTF-8
4,533
3.078125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HumaneSocietyApp { class HumaneSociety { public double money; Kennel kennel; Adopter adopter; public Adopter nina = new Adopter(); public HumaneSociety() { kennel = new Kennel(); adopter = new Adopter(); } public void enterChoiceToAdmitOrAdopt () { Console.WriteLine("Would you like to admit a new Animal, enter adoption information, or record animal maintence?"); Console.WriteLine("Enter 1 to admit a new animal" ); Console.WriteLine("Enter 2 to adoption information"); Console.WriteLine("Enter 3 to record animal maintence"); int response = Convert.ToInt32(Console.ReadLine()); if (response == 1) { inputAnimalInfo(); } else if (response == 2) { getAdopterName(); } else if (response == 3) { kennel.performAnimalMaintence(); } else { Console.WriteLine("You can only enter 1,2, or 3"); enterChoiceToAdmitOrAdopt(); } } public string enterType() { Console.WriteLine("Please enter the type of the animal?"); return Console.ReadLine(); } public string enterAnimalName() { Console.WriteLine("What is the name of the animal?"); return Console.ReadLine(); } public string enterBreed() { Console.WriteLine("What is the breed of the animal?"); return Console.ReadLine(); } public bool enterShotStatus() { Console.WriteLine("Are the animal's shots up todate?"); string shotsStatus = Console.ReadLine(); if (shotsStatus == "yes") { return true; } else if (shotsStatus == "no") { return false; } else { enterShotStatus(); return false; } } public string enterFoodType() { Console.WriteLine("What type of food does the animal eat?"); return Console.ReadLine(); } public int enterFoodAmount() { Console.WriteLine("How many cups of food does the animal eat in a feeding?"); return Convert.ToInt32(Console.ReadLine()); } public int enterNumberOfFeedingsPerDay() { Console.WriteLine("How many times a day does the animal eat?"); return Convert.ToInt32(Console.ReadLine()); } public Animal inputAnimalInfo() { if (enterType() == "dog") { Dog animalName = new Dog(enterAnimalName(),enterBreed(), enterShotStatus(), enterFoodType(), enterFoodAmount(), enterNumberOfFeedingsPerDay(), true); kennel.assignCageNumber(animalName); return animalName; } else if (enterType() == "cat") { Cat animalName = new Cat(enterAnimalName(), enterBreed(), enterShotStatus(), enterFoodType(), enterFoodAmount(), enterNumberOfFeedingsPerDay(), true); kennel.assignCageNumber(animalName); return animalName; } else { return inputAnimalInfo(); } } public void beginAdoptionProcess () { getAdopterName(); createAdopterProfile(); } public string getAdopterName() { Console.WriteLine("Enter the name of the adopter!"); return Console.ReadLine(); } public Adopter createAdopterProfile() { Adopter adopter = new Adopter(); return adopter; } public void adoptAnimal(Adopter adopter, Animal animal) { //adopter.money -= 50; money += 50; kennel.removeAnimal(animal); } public void feedAnimal () { Console.WriteLine("Do you want to feed an animal?"); } } }
Python
UTF-8
498
2.59375
3
[ "MIT" ]
permissive
#!/usr/bin/env python import cv2 import numpy as np cap = cv2.VideoCapture(0) def sketch(image): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # gray_blur = cv2.GaussianBlur(gray, (3,3), 0) edges = cv2.Canny(gray, 100, 200) ret, thresh1 = cv2.threshold(edges, 20, 255, cv2.THRESH_BINARY_INV) return thresh1 while(True): ret, frame = cap.read() cv2.imshow('sketch-app', sketch(frame)) if cv2.waitKey(1) == 13: break cap.release() cv2.destroyAllWindows()
Java
UTF-8
3,682
1.960938
2
[]
no_license
package org.power_systems_modelica.psm.dd; /* * #%L * Dynamic Data * %% * Copyright (C) 2017 - 2018 RTE (http://rte-france.com) * %% * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * #L% */ import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Stream; import org.power_systems_modelica.psm.modelica.ModelicaUtil; import com.powsybl.iidm.network.Identifiable; /** * @author Luma Zamarreño <zamarrenolm at aia.es> */ public class ModelProvider { public ModelProvider(AssociationProvider associations) { this.associations = associations; } public Model getModel(Identifiable<?> e) { List<Model> mdefs = getModels(e); if (mdefs.isEmpty()) return null; return mdefs.get(0); } public List<Model> getModels(Identifiable<?> e) { Optional<Model> idMdef = getDynamicModelForId(ModelicaUtil.normalizedIdentifier(e.getId())); Stream<Optional<Model>> assocs = getDynamicModelForAssociation(e); List<Model> assocMdefs = new ArrayList<>(); assocs.forEach(a -> { if (a.isPresent()) assocMdefs.add(a.get()); }); Optional<Model> typeMdef = getDynamicModelForStaticType(StaticType.from(e)); List<Model> mdefs = new ArrayList<>(); if (idMdef.isPresent()) mdefs.add(idMdef.get()); mdefs.addAll(assocMdefs); if (typeMdef.isPresent()) mdefs.add(typeMdef.get()); return mdefs; } public ModelForEvent getModelForEvent(String e) { return dynamicModelsForEvent.get(e); } public Collection<String> getEvents() { return dynamicModelsForEvent.keySet(); } public Optional<Model> getDynamicModelForId(String id) { return Optional.ofNullable(dynamicModelsForElement.get(id)) .map(m -> m.stampOrigin("id")); } public Optional<Model> getDynamicModelForStaticType(StaticType type) { return Optional.ofNullable(dynamicModelsForType.get(type)) .map(m -> m.stampOrigin("staticType")); } public Stream<Optional<Model>> getDynamicModelForAssociation(Identifiable<?> e) { Stream<Association> association = associations.findAssociations(e); Stream<Optional<Model>> mdefs = association.map(a -> Optional.ofNullable(dynamicModelsForAssociation.get(a.getId()))); return mdefs.map(opt -> opt.map(m -> m.stampOrigin("association"))); } public Model getDynamicModelForAssociation(String associationId) { return dynamicModelsForAssociation.get(associationId); } public void add(Model m) { // We index each model added explicitly index(m); } private void index(Model m) { if (m instanceof ModelForElement) dynamicModelsForElement.put(((ModelForElement) m).getStaticId(), (ModelForElement) m); else if (m instanceof ModelForAssociation) { dynamicModelsForAssociation.put( ((ModelForAssociation) m).getAssociation(), (ModelForAssociation) m); } else if (m instanceof ModelForType) dynamicModelsForType.put(((ModelForType) m).getType(), (ModelForType) m); else if (m instanceof ModelForEvent) dynamicModelsForEvent.put(((ModelForEvent) m).getEvent(), (ModelForEvent) m); } private final AssociationProvider associations; private final Map<String, ModelForElement> dynamicModelsForElement = new HashMap<>(); private final Map<String, ModelForAssociation> dynamicModelsForAssociation = new HashMap<>(); private final Map<StaticType, ModelForType> dynamicModelsForType = new HashMap<>(); private final Map<String, ModelForEvent> dynamicModelsForEvent = new HashMap<>(); }
Java
UTF-8
7,065
1.96875
2
[]
no_license
package com.example.patricia.matrix.Notifications; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.BitmapFactory; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.provider.Settings; import android.support.v7.app.NotificationCompat; import com.example.patricia.matrix.Activities.VideoActivity; import com.example.patricia.matrix.R; @SuppressWarnings("deprecation") public class Notifications { private Context context; private NotificationManager notificationManager; private PendingIntent pendingIntent; private Intent intent; private NotificationCompat.Builder builder; private android.app.Notification notifications; private final int ID_NOTIFICATION_STATUS_WIFI_GOPRO = 100; private final int ID_NOTIFICATION_CONNECT_WIFI_GOPRO = 175; private final int ID_NOTIFICATION_ERROR_CONNECTION = 110; private final int ID_NOTIFICATION_ERROR_SEND_DATA_GPS = 548; public Notifications(Context context) { this.context = context; notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); } public void sendNotificationStatusWifiGoPro() { intent = new Intent(context, VideoActivity.class); pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); builder = new NotificationCompat.Builder(context); builder.setTicker("Matrix"); builder.setContentTitle("Status Wifi"); builder.setSmallIcon(R.drawable.wifi); builder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.wifi)); builder.setContentIntent(pendingIntent); NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle(); String [] descs = new String[]{"O wifi da sua câmera GoPro está desconectado.", "O serviço será encerrado.", "Se estiver gravando, encerre a gravação manualmente.", "Conecte-se ao wifi novamente e reabra o aplicativo."}; for(int i = 0; i < descs.length; i++){ style.addLine(descs[i]); } builder.setStyle(style); notifications = builder.build(); notifications.vibrate = new long[] {150, 400, 150, 600}; notifications.flags = Notification.FLAG_AUTO_CANCEL; notificationManager.notify(ID_NOTIFICATION_STATUS_WIFI_GOPRO, notifications); try{ Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); Ringtone ringtone = RingtoneManager.getRingtone(context, sound); ringtone.play(); } catch(Exception exception){ exception.printStackTrace(); } } public void connectWifiGoPro() { intent = new Intent(Settings.ACTION_WIFI_SETTINGS); pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); builder = new NotificationCompat.Builder(context); builder.setTicker("Matrix"); builder.setContentTitle("Wifi GoPro"); builder.setSmallIcon(R.drawable.wifi); builder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.wifi)); builder.setContentIntent(pendingIntent); NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle(); String [] descs = new String[]{"O wifi da sua câmera está desconectado.", "Clique sobre a notificação para conectar-se."}; for(int i = 0; i < descs.length; i++){ style.addLine(descs[i]); } builder.setStyle(style); notifications = builder.build(); notifications.vibrate = new long[] {150, 400, 150, 600}; notifications.flags = Notification.FLAG_AUTO_CANCEL; notificationManager.notify(ID_NOTIFICATION_CONNECT_WIFI_GOPRO, notifications); try{ Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); Ringtone ringtone = RingtoneManager.getRingtone(context, sound); ringtone.play(); } catch(Exception exception){ exception.printStackTrace(); } } public void errorConnection() { intent = new Intent(context, VideoActivity.class); pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); builder = new NotificationCompat.Builder(context); builder.setTicker("Matrix"); builder.setContentTitle("Conexão GoPro"); builder.setSmallIcon(R.drawable.warning); builder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.warning)); builder.setContentIntent(pendingIntent); NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle(); String [] descs = new String[]{"Erro ao enviar comando para câmera GoPro.", "Verifique sua conexão Wi-Fi."}; for(int i = 0; i < descs.length; i++){ style.addLine(descs[i]); } builder.setStyle(style); notifications = builder.build(); notifications.vibrate = new long[] {150, 600, 150, 900}; notifications.flags = Notification.FLAG_AUTO_CANCEL; notificationManager.notify(ID_NOTIFICATION_ERROR_CONNECTION, notifications); try{ Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); Ringtone ringtone = RingtoneManager.getRingtone(context, sound); ringtone.play(); } catch(Exception exception){ exception.printStackTrace(); } } public void errorSendDataGPS() { intent = new Intent(context, VideoActivity.class); pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); builder = new NotificationCompat.Builder(context); builder.setTicker("Matrix"); builder.setContentTitle("Envio de dados GPS"); builder.setSmallIcon(R.drawable.gps); builder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.gps)); builder.setContentIntent(pendingIntent); NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle(); String [] descs = new String[]{"Ocorreu um erro na transferência dos dados de GPS."}; for(int i = 0; i < descs.length; i++){ style.addLine(descs[i]); } builder.setStyle(style); notifications = builder.build(); notifications.vibrate = new long[] {150, 600, 150, 900}; notifications.flags = Notification.FLAG_AUTO_CANCEL; notificationManager.notify(ID_NOTIFICATION_ERROR_SEND_DATA_GPS, notifications); try{ Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); Ringtone ringtone = RingtoneManager.getRingtone(context, sound); ringtone.play(); } catch(Exception exception){ exception.printStackTrace(); } } }
Markdown
UTF-8
1,080
2.6875
3
[]
no_license
# Isometric-GPU-Voxel-Raytracer ![pic](cool_parking_lot_occ.PNG) A parking lot looking building rendered from my engine. [Video demo with voxel selection via raycasting the mouse](https://youtu.be/5lf5ftyHCI8) ![pic](simple_noise.PNG) Simple noise. Algorithm found from [scratchapixel](https://scratchapixel.com); Using: - ModernGL for the OpenGL interface - PyGame for window and context creation Design decisions: Q: Why Python? A: It is a simple high-level language. My output is much faster when I code in Python, which is important for keeping me motivated on larger projects. If this graphics engine starts developing into an actual game, I'll start porting it over to C++ (Oct 25, 2018: I have now ported it to C++ in hopes of making a full game out of this. Because of this I will no longer update this repo, but I will keep it up for those who want to see a simple voxel raytracing shader). Also, the big meat of the code is in GLSL, so the slowness of Python is not really a bottleneck. Q: Why Isometric? A: It looks better for the type of game I'm trying to make.
JavaScript
UTF-8
4,270
2.625
3
[]
no_license
const SouthAfricanIdNumberValidation = require("../lib/southafricanidnumbervalidation.js"); const assertions = require("../lib/assertions.js"); module.exports = { when_asking_a_south_african_client_for_their_id_number_given_on_site_and_it_is_thirteen_digits_it_should_pass: () =>{ //arrange let idNumberValidation = new SouthAfricanIdNumberValidation("9101059236080"); //act & //assert assertions.AssertPassingSpec(idNumberValidation.isThirteenDigits); }, when_asking_a_south_african_client_for_their_id_number_given_on_site_and_it_is_too_long_it_should_fail: () =>{ //arrange let idNumberValidation = new SouthAfricanIdNumberValidation(12345678901231); //act & //assert assertions.AssertFailingSpec(idNumberValidation.isThirteenDigits); }, when_asking_a_south_african_client_for_their_id_number_given_on_site_and_it_is_too_short_it_should_fail: () =>{ //arrange let idNumberValidation = new SouthAfricanIdNumberValidation(123456789012); //act & //assert assertions.AssertFailingSpec(idNumberValidation.isThirteenDigits); },when_asking_a_south_african_client_for_their_id_number_given_on_site_and_the_first_six_digits_is_a_valid_date_it_should_pass: () =>{ //arrange let idNumberValidation = new SouthAfricanIdNumberValidation("9101059236080"); //act & //assert assertions.AssertPassingSpec(idNumberValidation.isSixDigitsDate); }, when_asking_a_south_african_client_for_their_id_number_given_on_site_and_the_first_six_digits_is_not_a_valid_date_it_should_fail: () =>{ //arrange let idNumberValidation = new SouthAfricanIdNumberValidation("9113459236080"); //act & //assert assertions.AssertFailingSpec(idNumberValidation.isSixDigitsDate); }, when_asking_a_south_african_client_for_their_id_number_given_on_site_and_the_7th_to_10th_digits_are_over_5000_it_should_determine_male_gender: () =>{ //arrange let idNumberValidation = new SouthAfricanIdNumberValidation("7607046305087"); //act & //assert assertions.AssertPassingSpec(idNumberValidation.isMale); }, when_asking_a_south_african_client_for_their_id_number_given_on_site_and_the_7th_to_10th_digits_are_below_5000_it_should_determine_female_gender: () =>{ //arrange let idNumberValidation = new SouthAfricanIdNumberValidation("7607042654082"); //act & //assert assertions.AssertPassingSpec(idNumberValidation.isFemale); }, when_asking_a_south_african_client_for_their_id_number_given_on_site_it_should_determine_if_you_are_a_south_african_citizen: () =>{ //arrange let idNumberValidation = new SouthAfricanIdNumberValidation("9101059236080"); //act & //assert assertions.AssertPassingSpec(idNumberValidation.isSouthAfricanCitizen); }, when_asking_a_south_african_client_for_their_id_number_given_on_site_it_should_determine_if_you_are_a_foreign_citizen: () =>{ //arrange let idNumberValidation = new SouthAfricanIdNumberValidation(8602026186184); //act & //assert assertions.AssertFailingSpec(idNumberValidation.isSouthAfricanCitizen); }, when_asking_a_south_african_client_for_their_id_number_given_on_site_and_it_is_valid_it_should_run_a_sequence_check: () =>{ //arrange let idNumberValidation = new SouthAfricanIdNumberValidation(8602026186184); //act & //assert assertions.AssertPassingSpec(idNumberValidation.isValidSequence); }, when_asking_a_south_african_client_for_their_id_number_given_on_site_and_it_is_not_valid_it_should_run_a_sequence_check: () =>{ //arrange let idNumberValidation = new SouthAfricanIdNumberValidation(8602026186111); //act & //assert assertions.AssertFailingSpec(idNumberValidation.isValidSequence); }, when_asking_a_south_african_client_for_their_id_number_given_on_site_and_it_is_valid_it_should_pass: () =>{ //arrange let idNumberValidation = new SouthAfricanIdNumberValidation("8602026911086"); //act & //assert assertions.AssertPassingSpec(idNumberValidation.isValid); } }
Java
UTF-8
1,051
4.0625
4
[]
no_license
/** * LeetCode * Problem_04.java */ package com.deepak.leetcode.Arrays; /** * <br> Problem Statement : * * Given a non-empty integer array of size n, find the minimum number of moves * required to make all array elements equal, where a move is incrementing n - 1 elements by 1. * * Example: * Input: [1,2,3] * Output: 3 * * Explanation: Only three moves are needed (remember each move increments two elements): * [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4] * * </br> * * @author Deepak */ public class Problem_04 { /** * Method to find minimum moves needed to make array elements same * Approach : Adding 1 to (n - 1) elements is same as subtracting 1 from one element, * w.r.t the goal of making all equal * * @param nums * @return {@link int} */ public static int minMoves(int[] nums) { if (nums == null || nums.length == 0) { return 0; } int res = 0; int min = nums[0]; for (int n : nums) { min = Math.min(min, n); } for (int n : nums) { res += n - min; } return res; } }
JavaScript
UTF-8
3,096
2.59375
3
[]
no_license
var lands=[]; var buleMap={}; var money=10000; var wood=1000; var v_wood=$("#wood"); updateWoodView(wood); function updateWoodView(amount){ v_wood.html("wood:"+amount); } var v_money=$("#money"); updateMoneyView(money); function updateMoneyView(amount){ v_money.html("money:"+amount); } function isEmptyObject(obj){ for(var n in obj){return false} return true; } var building=function(){ var level=0; }; building.prototype.upgrade=function(){ console.log("check ...upgrade"); console.log("beforeUpgrad:"+wood); console.log("beforeLevel:"+this.level); if(this.updateWood[this.level]!=undefined){ if(wood>this.updateWood[this.level]){ wood=wood-this.updateWood[this.level]; updateWoodView(wood); this.level=this.level+1; console.log("afterUpgrad:"+wood); console.log("afterLevel:"+this.level); }else{ alert("need more wood"); } }else{ } }; building.prototype.getRent=function(){ if(this.rentMoney[this.level]!=undefined){ money=money+this.rentMoney[this.level]; updateMoneyView(money); }else{ } }; var EnglandBuilding={ level:0, name:"England", rentMoney:[100,150,200], needWood:300, updateWood:[100,200,300] }; EnglandBuilding.upgrade=building.prototype.upgrade; EnglandBuilding.getRent=building.prototype.getRent; var land=function(){ var building=null; var build=function(buildType){ //if there is no building on this land... if(building==null){ if(wood>buildType.needWood){ console.log("yes...>"); wood=wood-buildType.needWood; updateWoodView(wood); this.building=buildType; }else{ } }//End of building is nulll... } return { building:building, build:build } };//End of land...... //=================================================== $(".land").click(function(){ var that=$(this); var data=that.data(); if(isEmptyObject(data)){ console.log("Empty Land...."); var a=new land(); a.build(EnglandBuilding); if(a.building!=null){ that.html(a.building.name+"--level "+a.building.level); that.data(a.building); }else{ alert("need more Matirals"); } }else{ console.log(data); data.upgrade(); that.html(data.name+"--level "+data.level); } }); $("#buy").click(function(){ money=money-1000; updateMoneyView(money); wood=wood+200; updateWoodView(wood); }); var update=setInterval(function(){ $(".land").each(function(){ var that=$(this); var data=that.data(); if(isEmptyObject(data)){ }else{ data.getRent(); } });//End of foreach land.... },3000);
Java
UTF-8
2,210
2.234375
2
[ "MIT" ]
permissive
package springfive.cms.domain.resources; import java.util.Arrays; import java.util.List; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import springfive.cms.domain.models.News; import springfive.cms.domain.models.Review; import springfive.cms.domain.service.NewsService; import springfive.cms.domain.vo.NewsRequest; /** * @author claudioed on 29/10/17. Project cms */ @RestController @RequestMapping("/api/news") public class NewsResource { private final NewsService newsService; public NewsResource(NewsService newsService) { this.newsService = newsService; } @GetMapping(value = "/{id}") public ResponseEntity<News> findOne(@PathVariable("id") String id){ return ResponseEntity.ok(new News()); } @GetMapping public ResponseEntity<List<News>> findAll(){ return ResponseEntity.ok(Arrays.asList(new News(),new News())); } @PostMapping public ResponseEntity<News> newNews(NewsRequest news){ return new ResponseEntity<>(new News(), HttpStatus.CREATED); } @DeleteMapping("/{id}") @ResponseStatus(HttpStatus.NO_CONTENT) public void removeNews(@PathVariable("id") String id){ } @PutMapping("/{id}") public ResponseEntity<News> updateNews(@PathVariable("id") String id,NewsRequest news){ return new ResponseEntity<>(new News(), HttpStatus.OK); } @GetMapping(value = "/{id}/review/{userId}") public ResponseEntity<Review> review(@PathVariable("id") String id,@PathVariable("userId") String userId){ return ResponseEntity.ok(new Review()); } @GetMapping(value = "/revised") public ResponseEntity<List<News>> revisedNews(){ return ResponseEntity.ok(Arrays.asList(new News(),new News())); } }
Ruby
UTF-8
234
3.515625
4
[]
no_license
total_letter_array = ('a' .. 'z').to_a vowel_array = ['a','e','i','o','u','y'] vowel_hash = {} total_letter_array.each_with_index do |value, index| vowel_hash[value] = index + 1 if vowel_array.include?(value) end puts vowel_hash
C++
UTF-8
8,708
3.109375
3
[ "MIT" ]
permissive
/**************************************************************** memoizer.h Template library for generic "memoization"/caching structures. Created by Mark A. Caprio, 2/23/11. - 6/9/17 (mac): Move into namespace mcutils. ****************************************************************/ #ifndef MCUTILS_MEMOIZER_H_ #define MCUTILS_MEMOIZER_H_ #include <cstddef> #include <algorithm> #include <iostream> #include <map> #include <vector> // MEMOIZE(m,x,y) applies Memoizer m to key given by expression x // - if x already exists as key, a const reference to the stored "y" // value for key x is returned // - else expression y is evaluated, stored as the "y" value for key x, // and the "y" value is returned // Optimization: Note key expression x is evaluated twice by the macro. // On the other hand, it cannot be saved within m, because of possible // reentrance problems if m is invoked in evaluating y. #define MEMOIZE(m,x,y) ( (m.Seek(x)) ? m.GetValue() : m.SetValue(x,y) ) namespace mcutils { //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// template<typename Key, typename T, typename Compare = std::less<Key> , typename Alloc = std::allocator<std::pair<const Key, T> > > class Memoizer{ public: //////////////////////////////// // type definitions //////////////////////////////// // underlying map type typedef typename std::map<Key,T,Compare,Alloc> map_type; // standard map type definitions typedef typename map_type::key_type key_type; typedef typename map_type::mapped_type mapped_type; typedef typename map_type::value_type value_type; typedef typename map_type::key_compare key_compare; typedef typename map_type::allocator_type allocator_type; typedef typename map_type::reference reference; typedef typename map_type::const_reference const_reference; typedef typename map_type::iterator iterator; typedef typename map_type::const_iterator const_iterator; typedef typename map_type::size_type size_type; typedef typename map_type::difference_type difference_type; typedef typename map_type::pointer pointer; typedef typename map_type::const_pointer const_pointer; typedef typename map_type::reverse_iterator reverse_iterator; typedef typename map_type::const_reverse_iterator const_reverse_iterator; typedef typename map_type::value_compare value_compare; // vector type for key-value pair dump typedef typename std::vector<value_type> vector_type; //////////////////////////////// // constructors //////////////////////////////// // default // default-initialize empty map // enable or disable caching // provide current_reference_ with useless but syntactically-required // initial value (to a temporary object) Memoizer() : cache_enabled_(true) {}; Memoizer(bool b) {cache_enabled_ = b;}; // copy -- synthesized constructor copies members //////////////////////////////// // accessors //////////////////////////////// // Seek(x) seeks entry for key x, returns true if found // as side effect, saves reference to "y" value for subsequent rapid // access by GetValue() bool Seek(const Key& x); // GetValue() returns the "y" value for // the most recently sought key // note: this requires that no recursive call be made // before GetValue() invoked T GetValue() const; // SetValue(y) stores y value // and returns a copy of this value T SetValue(const Key& x, const T& y); // Known(x) determines whether or not a value for x is already stored // for debugging and diagnostic use -- not part of MEMOIZE call bool Known(const Key& x) const {return (values_.count(x) == 1);} //////////////////////////////// // iterators //////////////////////////////// // iterators for read access only are defined const_iterator begin() const {return values_.begin();}; const_iterator end() const {return values_.end();}; const_reverse_iterator rbegin() const {return values_.rbegin();}; const_reverse_iterator rend() const {return values_.rend();}; //////////////////////////////// // bulk access //////////////////////////////// size_type size() const {return values_.size();}; void clear() {return values_.clear();}; //////////////////////////////// // ostream output //////////////////////////////// // output operator -- friend declaration for access to delimiters template<typename KeyX, typename TX, typename CompareX, typename AllocX> friend std::ostream& operator<< (std::ostream&, const Memoizer<KeyX, TX, CompareX, AllocX>&); //////////////////////////////// // configuration //////////////////////////////// // mode flags void EnableCaching(bool b) {cache_enabled_ = b;}; // configuring delimiter strings // static member function sets delimiters for *all* Memoizer // instances with the given template parameters // EX: Memoizer<...>::SetDelimiters(" ( ", " -> ", " )\n"); static void SetDelimiters(const std::string&, const std::string&, const std::string&); private: //////////////////////////////// // configuration data //////////////////////////////// // ostream delimiters (static) static std::string delimiter_left_; static std::string delimiter_middle_; static std::string delimiter_right_; // mode variables bool cache_enabled_; //////////////////////////////// // caching data //////////////////////////////// // cache map container map_type values_; // current entry access // Key current_key_; T current_result_; }; template<typename Key, typename T, typename Compare, typename Alloc> inline bool Memoizer<Key,T,Compare,Alloc>::Seek(const Key& x) { if (cache_enabled_) // cache enabled { // look for key in map iterator it = values_.find(x); // process key result if ( it != values_.end()) // key found { // store associated "y" value for rapid access current_result_ = it->second; return true; } else // key not found return false; } else // cache not enabled return false; } template<typename Key, typename T, typename Compare, typename Alloc> inline T Memoizer<Key,T,Compare,Alloc>::GetValue() const { // return "y" value return current_result_; } template<typename Key, typename T, typename Compare, typename Alloc> inline T Memoizer<Key,T,Compare,Alloc>::SetValue(const Key& x, const T& y) { if (cache_enabled_) { values_.insert(value_type(x,y)); } return y; }; //////////////////////////////// // stream output //////////////////////////////// // initialize delimiter variables template<typename Key, typename T, typename Compare, typename Alloc> std::string Memoizer<Key,T,Compare,Alloc>::delimiter_left_(" "); template<typename Key, typename T, typename Compare, typename Alloc> std::string Memoizer<Key,T,Compare,Alloc>::delimiter_middle_("->"); template<typename Key, typename T, typename Compare, typename Alloc> std::string Memoizer<Key,T,Compare,Alloc>::delimiter_right_("\n"); // delimiter configuration template<typename Key, typename T, typename Compare, typename Alloc> void Memoizer<Key,T,Compare,Alloc>::SetDelimiters( const std::string& left, const std::string& middle, const std::string& right ) { Memoizer<Key,T,Compare,Alloc>::delimiter_left_ = left; Memoizer<Key,T,Compare,Alloc>::delimiter_middle_ = middle; Memoizer<Key,T,Compare,Alloc>::delimiter_right_ = right; }; // output operator template<typename Key, typename T, typename Compare, typename Alloc> std::ostream& operator<< (std::ostream& os, const Memoizer<Key,T,Compare,Alloc>& m) { for( typename Memoizer<Key,T,Compare,Alloc>::const_iterator i = m.begin(); i != m.end(); ++i ) { os << Memoizer<Key,T,Compare,Alloc>::delimiter_left_; os << i->first; os << Memoizer<Key,T,Compare,Alloc>::delimiter_middle_; os << i->second; os << Memoizer<Key,T,Compare,Alloc>::delimiter_right_; } return os; } } // namespace // legacy support for global definitions #ifdef MCUTILS_ALLOW_LEGACY_GLOBAL using mcutils::Memoizer; #endif #endif
Python
UTF-8
611
3.671875
4
[]
no_license
""" Decorator Recipe #1: Easy Event Binding (version 1) """ from Tkinter import * class MyButton(Button): def command(self, func): self['command'] = func return func if __name__ == '__main__': frame = Frame() frame.master.title("Event binding with decorators") frame.pack() btn1 = MyButton(frame, text="One") btn1.pack() btn2 = MyButton(frame, text="Two") btn2.pack() @btn1.command @btn2.command def onclick(): print 'You clicked on a button' frame.mainloop()
C#
UTF-8
515
2.71875
3
[]
no_license
using System; namespace Rivet.Broker.Impl { public class WaitForSpecificMessage : IConversation { public WaitForSpecificMessage(Type type) { _type = type; _complete = false; } private bool _complete; private Type _type; public void Peek(object message) { if (message.GetType().Equals(_type)) _complete = true; } public bool Complete() { return _complete; } } }
Java
UTF-8
3,159
2.328125
2
[]
no_license
package tw.iii.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Transient; import org.springframework.stereotype.Component; @Entity @Table(name="product") @Component public class Product { @Id @Column(name="productid") @GeneratedValue(strategy = GenerationType.IDENTITY) private int productID; @Column(name = "productName") private String productName; @Column(name = "stock") private int stock; @Column(name = "price") private int price; @Column(name = "species") private String species; @Column(name = "classification") private String classification; @Column(name = "brand") private String brand; @Column(name = "descripton") private String descripton; @Column(name = "img") private String img; @Column(name="status") private String status; @Transient private Long sum; public Product() { } public Long getSum() { return sum; } public void setSum(Long sum) { this.sum = sum; } public Product(String productName, int stock, int price, String species, String classification, String brand, String descripton, String img,String status) { this.productName = productName; this.stock = stock; this.price = price; this.species = species; this.classification = classification; this.brand = brand; this.descripton = descripton; this.img = img; this.status=status; } public Product(String productName, int stock, int price, String species, String classification, String brand, String descripton,String status) { this.productName = productName; this.stock = stock; this.price = price; this.species = species; this.classification = classification; this.brand = brand; this.descripton = descripton; this.status = status; } public int getProductID() { return productID; } public void setProductID(int productID) { this.productID = productID; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public int getStock() { return stock; } public void setStock(int stock) { this.stock = stock; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public String getSpecies() { return species; } public void setSpecies(String species) { this.species = species; } public String getClassification() { return classification; } public void setClassification(String classification) { this.classification = classification; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getDescripton() { return descripton; } public void setDescripton(String descripton) { this.descripton = descripton; } public String getImg() { return img; } public void setImg(String img) { this.img = img; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
SQL
ISO-8859-1
13,435
3.0625
3
[]
no_license
-------------------------------------------------------- -- DDL for Package Body PAC_IAX_MARCAS -------------------------------------------------------- CREATE OR REPLACE EDITIONABLE PACKAGE BODY "AXIS"."PAC_IAX_MARCAS" AS /****************************************************************************** NOMBRE: PAC_MD_MARCAS PROPSITO: Funciones para gestionar las marcas REVISIONES: Ver Fecha Autor Descripcin --------- ---------- ------ ------------------------------------ 1.0 01/08/2016 HRE 1. Creacin del package. ******************************************************************************/ e_object_error EXCEPTION; e_param_error EXCEPTION; /************************************************************************* FUNCTION f_get_marcas Permite obtener la informacion de las marcas param in pcempres : codigo de la empresa param out mensajes : mesajes de error return : ref cursor *************************************************************************/ FUNCTION f_get_marcas(pcempres IN NUMBER, mensajes IN OUT t_iax_mensajes) RETURN sys_refcursor IS cur sys_refcursor; vpasexec NUMBER(8) := 1; vparam VARCHAR2(2000) := 'pcempres=' || pcempres; vobject VARCHAR2(200) := 'pac_iax_marcas.f_get_marcas'; BEGIN cur := pac_md_marcas.f_get_marcas(pcempres, mensajes); RETURN cur; EXCEPTION WHEN OTHERS THEN pac_iobj_mensajes.p_tratarmensaje(mensajes, vobject, 1000001, vpasexec, vparam, psqcode => SQLCODE, psqerrm => SQLERRM); IF cur%ISOPEN THEN CLOSE cur; END IF; RETURN cur; END f_get_marcas; FUNCTION f_obtiene_marcas(pcempres IN NUMBER, psperson IN NUMBER, mensajes IN OUT t_iax_mensajes) RETURN t_iax_marcas IS t_marcas t_iax_marcas; vpasexec NUMBER(8) := 1; vparam VARCHAR2(2000) := 'pcempres=' || pcempres; vobject VARCHAR2(200) := 'pac_iax_marcas.f_get_marcas'; BEGIN t_marcas := pac_md_marcas.f_obtiene_marcas(pcempres, psperson, mensajes); RETURN t_marcas; EXCEPTION WHEN OTHERS THEN pac_iobj_mensajes.p_tratarmensaje(mensajes, vobject, 1000001, vpasexec, vparam, psqcode => SQLCODE, psqerrm => SQLERRM); RETURN t_marcas; END f_obtiene_marcas; /************************************************************************* FUNCTION f_get_marcas_per Permite obtener la informacion de las marcas asociadas a una persona param in pcempres : codigo de la empresa param in psperson : codigo de la persona param out mensajes : mesajes de error return : ref cursor *************************************************************************/ FUNCTION f_get_marcas_per(pcempres IN NUMBER, psperson IN NUMBER, mensajes IN OUT t_iax_mensajes) RETURN sys_refcursor IS cur sys_refcursor; vpasexec NUMBER(8) := 1; vparam VARCHAR2(2000) := 'pcempres=' || pcempres||' psperson='||psperson; vobject VARCHAR2(200) := 'pac_iax_marcas.f_get_marcas_per'; BEGIN p_tab_error(f_sysdate, f_user, 'PAC_IAX_MARCAS. F_GET_MARCAS', 777, vparam, 'PASO 1, pcempres:'||pcempres||' psperson:'||psperson); cur := pac_md_marcas.f_get_marcas_per(pcempres, psperson, mensajes); RETURN cur; EXCEPTION WHEN OTHERS THEN pac_iobj_mensajes.p_tratarmensaje(mensajes, vobject, 1000001, vpasexec, vparam, psqcode => SQLCODE, psqerrm => SQLERRM); IF cur%ISOPEN THEN CLOSE cur; END IF; RETURN cur; END f_get_marcas_per; /************************************************************************* FUNCTION f_get_marcas_perhistorico Permite obtener la informacion de todos los movimientos de una marca asociada a la persona param in pcempres : codigo de la empresa param in psperson : codigo de la persona param out mensajes : mesajes de error return : ref cursor *************************************************************************/ FUNCTION f_get_marcas_perhistorico(pcempres IN NUMBER, psperson IN NUMBER, pcmarca IN VARCHAR2, mensajes IN OUT t_iax_mensajes) RETURN sys_refcursor IS cur sys_refcursor; vpasexec NUMBER(8) := 1; vparam VARCHAR2(2000) := 'pcempres=' || pcempres||' psperson='||psperson; vobject VARCHAR2(200) := 'pac_iax_marcas.f_get_marcas_perhistorico'; BEGIN cur := pac_md_marcas.f_get_marcas_perhistorico(pcempres, psperson, pcmarca, mensajes); RETURN cur; EXCEPTION WHEN OTHERS THEN pac_iobj_mensajes.p_tratarmensaje(mensajes, vobject, 1000001, vpasexec, vparam, psqcode => SQLCODE, psqerrm => SQLERRM); IF cur%ISOPEN THEN CLOSE cur; END IF; RETURN cur; END f_get_marcas_perhistorico; /************************************************************************* FUNCTION f_set_marcas_per Permite asociar marcas a la persona de forma manual param in pcempres : codigo de la empresa param in psperson : codigo de la persona param in pcmarca : codigo de la marca param in pparam : parametros de roles param out mensajes : mesajes de error return : number *************************************************************************/ FUNCTION f_set_marcas_per(pcempres IN NUMBER, psperson IN NUMBER, t_marcas IN T_IAX_MARCAS, mensajes IN OUT t_iax_mensajes) RETURN NUMBER IS ob_marcas ob_iax_marcas; vpasexec NUMBER(8) := 1; vparam VARCHAR2(2000) := 'pcempres=' || pcempres||' psperson='||psperson; vobject VARCHAR2(200) := 'pac_iax_marcas.f_set_marcas_per'; vnumerr NUMBER (8):=0; BEGIN vnumerr := pac_md_marcas.f_set_marcas_per(pcempres, psperson, t_marcas, mensajes); IF vnumerr<>0 THEN RAISE e_object_error; END IF; COMMIT; RETURN 0; EXCEPTION WHEN e_param_error THEN pac_iobj_mensajes.p_tratarmensaje (mensajes, vobject, 1000005, vpasexec, vparam); ROLLBACK; RETURN 1; WHEN e_object_error THEN pac_iobj_mensajes.p_tratarmensaje (mensajes, vobject, 1000006, vpasexec, vparam); ROLLBACK; RETURN 1; WHEN OTHERS THEN pac_iobj_mensajes.p_tratarmensaje (mensajes, vobject, 1000001, vpasexec, vparam, psqcode=>SQLCODE, psqerrm=>SQLERRM); ROLLBACK; RETURN 1; END f_set_marcas_per; /************************************************************************* FUNCTION f_set_marca_automatica Permite asociar marcas a la persona en procesos del Sistema param in pcempres : codigo de la empresa param in psperson : codigo de la persona param in pcmarca : codigo de la marca param in pparam : parametros de roles param out mensajes : mesajes de error return : number *************************************************************************/ FUNCTION f_set_marca_automatica(pcempres IN NUMBER, psperson IN NUMBER, pcmarca IN VARCHAR2, mensajes IN OUT t_iax_mensajes) RETURN NUMBER IS vpasexec NUMBER(8) := 1; vparam VARCHAR2(2000) := 'pcempres=' || pcempres||' psperson='||psperson||' pcmarca:'||pcmarca; vobject VARCHAR2(200) := 'pac_iax_marcas.f_set_marca_automatica'; vnumerr NUMBER (8):=0; BEGIN vnumerr := pac_md_marcas.f_set_marca_automatica(pcempres, psperson, pcmarca, mensajes); IF vnumerr<>0 THEN RAISE e_object_error; END IF; COMMIT; RETURN 0; EXCEPTION WHEN e_param_error THEN pac_iobj_mensajes.p_tratarmensaje (mensajes, vobject, 1000005, vpasexec, vparam); ROLLBACK; RETURN 1; WHEN e_object_error THEN pac_iobj_mensajes.p_tratarmensaje (mensajes, vobject, 1000006, vpasexec, vparam); ROLLBACK; RETURN 1; WHEN OTHERS THEN pac_iobj_mensajes.p_tratarmensaje (mensajes, vobject, 1000001, vpasexec, vparam, psqcode=>SQLCODE, psqerrm=>SQLERRM); ROLLBACK; RETURN 1; END f_set_marca_automatica; /************************************************************************* FUNCTION f_del_marca_automatica Permite desactivar marcas a la persona param in pcempres : codigo de la empresa param in psperson : codigo de la persona param in pcmarca : codigo de la marca param out mensajes : mesajes de error return : number *************************************************************************/ FUNCTION f_del_marca_automatica(pcempres IN NUMBER, psperson IN NUMBER, pcmarca IN VARCHAR2, mensajes IN OUT t_iax_mensajes) RETURN NUMBER IS BEGIN RETURN 0; END f_del_marca_automatica; -- /************************************************************************* FUNCTION f_get_marcas_poliza Permite obtener la informacion de las marcas asociadas a una persona param in pcempres : codigo de la empresa param in psseguro : codigo del seguro param in ptablas : EST o POL param out mensajes : mesajes de error return : ref cursor *************************************************************************/ FUNCTION f_get_marcas_poliza(pcempres IN NUMBER, psseguro IN NUMBER, ptablas IN VARCHAR2, mensajes IN OUT t_iax_mensajes) RETURN sys_refcursor IS cur sys_refcursor; vpasexec NUMBER(8) := 1; vparam VARCHAR2(2000) := 'pcempres=' || pcempres||' psseguro='||psseguro||' ptablas:'||ptablas; vobject VARCHAR2(200) := 'pac_iax_marcas.f_get_marcas_per'; BEGIN cur := pac_md_marcas.f_get_marcas_poliza(pcempres, psseguro, ptablas, mensajes); RETURN cur; EXCEPTION WHEN OTHERS THEN pac_iobj_mensajes.p_tratarmensaje(mensajes, vobject, 1000001, vpasexec, vparam, psqcode => SQLCODE, psqerrm => SQLERRM); IF cur%ISOPEN THEN CLOSE cur; END IF; RETURN cur; END f_get_marcas_poliza; /************************************************************************* FUNCTION f_get_accion_poliza Permite obtener la maxima accion de las marcas asociadas a tomadores, asegurados o beneficiarios de una poliza param in pcempres : codigo de la empresa param in psseguro : codigo del seguro param in ptablas : EST o POL param out mensajes : mesajes de error return : number *************************************************************************/ FUNCTION f_get_accion_poliza(pcempres IN NUMBER, psseguro IN NUMBER, ptablas IN VARCHAR2, mensajes IN OUT t_iax_mensajes) RETURN NUMBER IS v_accion NUMBER; vpasexec NUMBER(8) := 1; vparam VARCHAR2(2000) := 'pcempres=' || pcempres||' psseguro='||psseguro||' ptablas:'||ptablas; vobject VARCHAR2(200) := 'pac_iax_marcas.f_get_accion_poliza'; BEGIN v_accion := pac_md_marcas.f_get_accion_poliza(pcempres, psseguro, ptablas, mensajes); RETURN v_accion; EXCEPTION WHEN OTHERS THEN pac_iobj_mensajes.p_tratarmensaje(mensajes, vobject, 1000001, vpasexec, vparam, psqcode => SQLCODE, psqerrm => SQLERRM); RETURN -1; END f_get_accion_poliza; END pac_iax_marcas; / GRANT EXECUTE ON "AXIS"."PAC_IAX_MARCAS" TO "R_AXIS"; GRANT EXECUTE ON "AXIS"."PAC_IAX_MARCAS" TO "CONF_DWH"; GRANT EXECUTE ON "AXIS"."PAC_IAX_MARCAS" TO "PROGRAMADORESCSI";
Java
UTF-8
825
2.453125
2
[ "MIT" ]
permissive
package link.infra.jdwp; public class TypeSizeManager { // Default to long (8 bytes) private int fieldID = 8; private int methodID = 8; private int objectID = 8; private int referenceTypeID = 8; private int frameID = 8; public synchronized void setSizes(int fieldID, int methodID, int objectID, int referenceTypeID, int frameID) { this.fieldID = fieldID; this.methodID = methodID; this.objectID = objectID; this.referenceTypeID = referenceTypeID; this.frameID = frameID; } public synchronized int getFieldID() { return fieldID; } public synchronized int getMethodID() { return methodID; } public synchronized int getObjectID() { return objectID; } public synchronized int getReferenceTypeID() { return referenceTypeID; } public synchronized int getFrameID() { return frameID; } }
Java
UTF-8
5,306
2.5
2
[]
no_license
package com.zipcodewilmington.froilansfarm.storage; import com.zipcodewilmington.froilansfarm.mammal.Chicken; import com.zipcodewilmington.froilansfarm.mammal.Horse; import com.zipcodewilmington.froilansfarm.mammal.Person; import com.zipcodewilmington.froilansfarm.crop.CornStalk; import com.zipcodewilmington.froilansfarm.crop.Crop; import com.zipcodewilmington.froilansfarm.crop.GenericVegetation; import com.zipcodewilmington.froilansfarm.crop.TomatoPlant; import com.zipcodewilmington.froilansfarm.edible.Edible; import com.zipcodewilmington.froilansfarm.edible.EdibleEgg; import com.zipcodewilmington.froilansfarm.storage.field.CropRow; import com.zipcodewilmington.froilansfarm.storage.field.Field; import com.zipcodewilmington.froilansfarm.vehicle.CropDuster; import com.zipcodewilmington.froilansfarm.vehicle.Tractor; import com.zipcodewilmington.froilansfarm.vehicle.interfaces.Aircraft; import com.zipcodewilmington.froilansfarm.vehicle.interfaces.Vehicle; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.function.Supplier; import java.util.stream.Collectors; public class Farm { Field field; List<Stable> stables = new ArrayList<Stable>(); List<ChickenCoop> chickenCoops = new ArrayList<ChickenCoop>(); FarmHouse farmHouse; List<Vehicle> vehicles = new ArrayList<Vehicle>(); List<Edible> harvestedEgg = new ArrayList<>(); public Farm(){ farmHouse = new FarmHouse(); field = new Field(); } public void addChickenCoop(ChickenCoop chickenCoop) { chickenCoops.add(chickenCoop); } public void addVehicles(Vehicle vehicle){ vehicles.add(vehicle); } public <T extends Crop> void CreateCropRowInField(Supplier<T> cropSupplier, int numberOfCrops) { CropRow cropRow = new CropRow(); cropRow.addCropRow(cropSupplier, numberOfCrops); field.add(cropRow); } public <H extends ChickenCoop, A extends Chicken> void addChickenCoopToFarm(Supplier<H> houseSupplier, Supplier<A> animalSupplier, int numberOfCoops, int numberOfChickens) { for (int i = 0; i < numberOfCoops; i++) { ChickenCoop chickenCoop = houseSupplier.get(); addChickenCoop(chickenCoop); } for (int i = 0; i < numberOfChickens; i++) { chickenCoops.get(i%numberOfCoops).add(animalSupplier.get()); } } public <H extends Stable, A extends Horse> void addStablesToFarm(Supplier<H> houseSupplier, Supplier<A> animalSupplier, int numberOfStables, int numberOfHorses) { for (int i = 0; i < numberOfStables; i++) { Stable stable = houseSupplier.get(); stables.add(stable); } for (int i = 0; i < numberOfHorses; i++) { stables.get(i%numberOfStables).add(animalSupplier.get()); } } public void addFarmerToFarmHouse(Person person) { farmHouse.add(person); } public FarmHouse getFarmHouse() { return farmHouse; } public List<Horse> getHorses() { return stables.stream() .flatMap(horses-> horses.getItems().stream()) .collect(Collectors.toList()); } public List<Chicken> getChickens() { return chickenCoops.stream() .flatMap(chickens-> chickens.getItems().stream()) .collect(Collectors.toList()); } public Field getField() { return field; } public CropDuster getCropDuster(){ Optional<Vehicle> filteredVehicle = vehicles.stream() .filter(vehicle -> vehicle instanceof CropDuster) .findFirst(); return (CropDuster)filteredVehicle.orElse(null); } public Tractor getTractor(){ Optional<Vehicle> filteredVehicle = vehicles.stream() .filter(vehicle -> vehicle instanceof Tractor) .findFirst(); return (Tractor) filteredVehicle.orElse(null); } public List<CropRow> getCropRows(){ return field.getItems(); } public CornStalk getHarvestedCornStalk(){ return getTractor().popEarCorn(); } public TomatoPlant getHarvestedTomatoPlant(){ return getTractor().popTomatoPlant(); } public GenericVegetation getHarvestedGenericVegetation(){ return getTractor().popGenericVegetation(); } public EdibleEgg popEdibleEgg(){ EdibleEgg egg = (EdibleEgg)harvestedEgg.get(0); harvestedEgg.remove(egg); return egg; } public void harvest(){ field.getItems().forEach(cropRow -> cropRow.getItems() .forEach(crop->getTractor().harverst(crop))); getChickens().stream() .forEach(chicken -> harvestedEgg.add(chicken.yield())); } public void fertilise(){ CropDuster cropDuster = getCropDuster(); cropDuster.operate(this); } public List<Vehicle> getVehicles(){ return vehicles; } public List<Vehicle> getAircrafts() { return vehicles.stream() .filter(vehicle -> vehicle instanceof Tractor) .collect(Collectors.toList()); } }
Markdown
UTF-8
3,529
3.328125
3
[ "MIT" ]
permissive
## Arduino Computer Vision Finger Counter By using serial communication it's possible to combine the power of a pc with a low cost Arduino micro-controller. This opens up a world of possibilities to experiment with building your own Ai powered devices and robotics products. This project demonstrates how to send data between a python script (running on a laptop) and an Arduino. It takes just a few lines of code to get the serial communication working. <br> <img src="https://github.com/vbookshelf/Arduino-Computer-Vision-Finger-Counter/blob/main/images/project-images.png" width="500"></img> <br> This is what this project does: A person holds up one or two fingers in front of a laptop webcam. A cpu based computer vision hand keypoint detector (from Google Mediapipe) is used to detect how many fingers are being held up. This count is displayed on the screen. The LED_BUILTIN is an LED that is built into the Arduino.<br> The python code, running on the laptop, sends the count to the Arduino. If one finger is being held up then the Arduino turns the LED_BUILTIN on. If two fingers are being held up then the Arduino turns the LED_BUILTIN off. The code is written for the right hand only. The voltage that the Arduino uses to turn on the LED could be used to perform many other actions - open a door, control the position of a robot arm, apply the brakes on a self driving car, set off an alarm and more. In this project hand images are fed from a webcam to a machine learning model. The model then predicts hand keypoints. The python program uses these keypoints to determine whether a finger is up or down. However, because we are using an Ardunio, the input could also be sensor data like temperature and pressure. This data could be continuously fed to a model to predict, for example, if a machine will break down in the next 24 hours. <br> ## Reference Resources These tutorials will help you understand what the code is doing. You could watch these tutorials and implement this project yourself. Arduino - Send Commands with Serial Communication<br> https://www.youtube.com/watch?v=utnPvE8hN3o Arduino - Bidirectional Serial Communication with Raspberry Pi<br> (It doesn't have to be a Raspberry Pi. It could also be a pc or laptop.)<br> https://www.youtube.com/watch?v=OJtpA_qTNL0 Hand Tracking 30 FPS using CPU | OpenCV Python (2021) | Computer Vision<br> https://www.youtube.com/watch?v=NZde8Xt78Iw&t=1603s Also, if you have never used OpenCV with a webcam then I suggest watching this tutorial:<br> https://www.youtube.com/watch?v=WQeoO7MI0Bs&t=305s <br> ## How to run this project These instructions are for Mac OSX but the process to run a python file in Windows should be similar. 1- Connect your Arduino to a USB port on your laptop.<br> 2- Upload the arduino-sketch folder to your Arduino.<br> 3- Change the port variable in the arduino-finger-counter.py file to match the port you are using. The steps to do this are described in the arduino-finger-counter.py file.<br> 4- On the command line: Navigate to the folder containing the arduino-finger-counter.py file.<br> 5- On the command line type: python arduino-finger-counter.py<br> 6- A window will open showing what your webcam is seeing.<br> 7- Hold up your right hand in front of your webcam.<br> 8- Show one finger to turn the Arduino LED on.<br> 9- Show two fingers to turn the Arduino LED off. ## Packages These are the packages that I used: - Python 3.7.0 - OpenCV - numpy==1.21.2 - mediapipe==0.8.7.3 - pyserial==3.5
Markdown
UTF-8
577
2.609375
3
[ "LicenseRef-scancode-generic-cla", "MIT" ]
permissive
# How to run your first project ## Steps 1. Upload your source dataset (raw) to AzureML Datasets 2. Upload your dependencies to AzureML Datasets (stopwords, custom ner) 3. Customize custom.py with any required pre-processing steps 4. Create a *.config.json where * = project name 5. Run deploy/training.py 6. Run deploy/inference.py ## Requirements To make the NLP kit work flawlessly, there are some naming requirements and best practices. - Use language short froms (eg. German = de, French = fr) - Naming - stopword list: stopwords-<language>.txt (tab delimited, utf-8)
Java
UTF-8
1,062
3.859375
4
[]
no_license
package com.note.design_patterns.creational; /** * @Classname SimpleFactory * @Date 2019-09-16 13:59 * @Created by chenpan * @Description 简单工厂模式 */ public class SimpleFactory { enum Type { A, B } public AB create(Type type) { switch (type) { case A: return new A(); case B: return new B(); default: return () -> System.out.println("ab:ab"); } } public static void main(String[] args) { AB a = new SimpleFactory().create(Type.A); AB b = new SimpleFactory().create(Type.B); a.ab(); b.ab(); } } interface AB { public void ab(); } class A implements AB { @Override public void ab() { System.out.println("a:ab"); } public void a() { System.out.println("AAAAA"); } } class B implements AB { @Override public void ab() { System.out.println("b:ab"); } public void b() { System.out.println("BBBBB"); } }
Java
UTF-8
7,381
1.703125
2
[]
no_license
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.discover.cls.processors.cls; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.nifi.annotation.behavior.EventDriven; import org.apache.nifi.annotation.behavior.InputRequirement; import org.apache.nifi.annotation.behavior.ReadsAttribute; import org.apache.nifi.annotation.behavior.ReadsAttributes; import org.apache.nifi.annotation.behavior.SideEffectFree; import org.apache.nifi.annotation.behavior.SupportsBatching; import org.apache.nifi.annotation.behavior.WritesAttribute; import org.apache.nifi.annotation.behavior.WritesAttributes; import org.apache.nifi.annotation.documentation.CapabilityDescription; import org.apache.nifi.annotation.documentation.SeeAlso; import org.apache.nifi.annotation.documentation.Tags; import org.apache.nifi.components.PropertyDescriptor; import org.apache.nifi.flowfile.FlowFile; import org.apache.nifi.processor.AbstractProcessor; import org.apache.nifi.processor.ProcessContext; import org.apache.nifi.processor.ProcessSession; import org.apache.nifi.processor.Relationship; import org.apache.nifi.processor.exception.ProcessException; import org.apache.nifi.processor.util.StandardValidators; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; @EventDriven @SideEffectFree @SupportsBatching @Tags({"json", "attributes", "flowfile"}) @InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED) @CapabilityDescription("This processor will parse a JSON document and extract all first level keys from the JSON object. It will put all these attributes to the attribute, 'attribute-list.'") @WritesAttributes({ @WritesAttribute(attribute = "attribute-list", description = "This attribute will contain all first level keys separated by the define separator.") }) @ReadsAttributes({ @ReadsAttribute(attribute = "X", description = "X is defined in JSON Attribute Name. It is not required. If it is then this processor will read this attribute's value to create " + "the attribute list.") }) @SeeAlso({AttributesToTypedJSON.class, JSONToAttributes.class}) public class JSONKeysToAttributeList extends AbstractProcessor { static final String ATTRIBUTE_LIST_ATTRIBUTE = "attribute-list"; static final PropertyDescriptor ATTRIBUTE_LIST_SEPARATOR = new PropertyDescriptor.Builder() .name("Attribute List Separator") .displayName("Attribute List Separator") .description("The separator that will be used separate the keys of the parsed JSON.") .required(true) .addValidator(StandardValidators.NON_EMPTY_VALIDATOR) .defaultValue(",") .build(); static final PropertyDescriptor JSON_ATTRIBUTE = new PropertyDescriptor.Builder() .name("JSON Attribute Name") .displayName("JSON Attribute Name") .description("If this value is populated then this processor will read JSON from attribute named in this property. For example, if this property is X, it will try to read " + "JSON from a flow file's X attribute instead of its content.") .required(false) .expressionLanguageSupported(true) .addValidator(StandardValidators.ATTRIBUTE_KEY_VALIDATOR) .build(); static final Relationship REL_SUCCESS = new Relationship.Builder() .name("success") .description("Successfully converted JSON to attributes.") .build(); static final Relationship REL_FAILURE = new Relationship.Builder() .name("failure") .description("Failed converting JSON to attributes.") .build(); private static final Set<Relationship> RELATIONSHIPS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(REL_SUCCESS, REL_FAILURE))); private static final List<PropertyDescriptor> PROPERTY_DESCRIPTORS = Collections.unmodifiableList(Arrays.asList(ATTRIBUTE_LIST_SEPARATOR, JSON_ATTRIBUTE)); private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); @Override public Set<Relationship> getRelationships() { return RELATIONSHIPS; } @Override public final List<PropertyDescriptor> getSupportedPropertyDescriptors() { return PROPERTY_DESCRIPTORS; } @Override public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException { FlowFile flowFile = session.get(); if (flowFile == null) { return; } final String attributeName = context.getProperty(JSON_ATTRIBUTE).evaluateAttributeExpressions().getValue(); final String attributeContent = flowFile.getAttribute(attributeName); final byte[] content = attributeContent == null ? FlowFileUtils.extractMessage(flowFile, session) : attributeContent.getBytes(); final String separator = context.getProperty(ATTRIBUTE_LIST_SEPARATOR).getValue(); try { if (content == null || Arrays.equals(content, new byte[0])) { flowFile = session.putAttribute(flowFile, ATTRIBUTE_LIST_ATTRIBUTE, ""); session.transfer(flowFile, REL_SUCCESS); } else { final JsonNode jsonNode = OBJECT_MAPPER.readTree(content); final String attributeList = createAttributeList(jsonNode, separator); flowFile = session.putAttribute(flowFile, ATTRIBUTE_LIST_ATTRIBUTE, attributeList); session.getProvenanceReporter().modifyAttributes(flowFile); session.transfer(flowFile, REL_SUCCESS); } } catch (IOException e) { getLogger().error("Failed parsing JSON.", new Object[]{e}); session.transfer(flowFile, REL_FAILURE); } } private String createAttributeList(JsonNode jsonNode, String separator) { final List<String> jsonKeys = new ArrayList<>(); Iterator<Map.Entry<String, JsonNode>> fields = jsonNode.fields(); while (fields.hasNext()) { Map.Entry<String, JsonNode> current = fields.next(); jsonKeys.add(current.getKey()); } boolean isFirst = true; String attributeList = ""; for (String key : jsonKeys) { attributeList += isFirst ? key : separator + key; isFirst = false; } return attributeList; } }
Markdown
UTF-8
5,568
2.625
3
[]
no_license
--- title: The Next Step author: Justin Lascek type: post date: 2013-01-10T16:04:37+00:00 url: /blog/2013/01/the-next-step/ categories: - Programming --- Last Friday you were tasked with pulling your balls out from between your legs and committing to a competition. The day you sign up will be one of the greatest days of your life because your training will suddenly have new meaning. You won&#8217;t understand this until the end of the competition. You&#8217;ll either walk away from the competition&#8217;s last effort thinking, &#8220;This was one of the best experiences of my life and I can&#8217;t wait to do it again,&#8221; or &#8220;I could have been better, I _should_ have been better, next time I will reach my full potential.&#8221; Either way, you will be of the mindset that your life craves competition, _needs_ it. If you haven&#8217;t signed up for something: do it. There&#8217;s no better time to sign up. It&#8217;s like cleaning a toilet; the longer you wait, the more it stinks and the less likely you will be to do anything about it. Assuming you&#8217;ve signed up, it&#8217;s now time to ensure your training is efficient so that you have a fun and successful first competition. Most likely you can just keep doing whatever program you&#8217;re doing now, but just do it better. Increase your bar speed on every rep. It&#8217;s easy to go through the motions, but when you actually grit your teeth, clench your B-hole, and attack every rep like it owes you money/sex/bacon/chocolate, you&#8217;ll accomplish much more. Make the bar go fast; make the weights go boom. <div id="attachment_8274" style="width: 370px" class="wp-caption aligncenter"> <a href="/2013/01/one-does-not-simply-enter-my-b-hole.jpg"><img aria-describedby="caption-attachment-8274" data-attachment-id="8274" data-permalink="/blog/2013/01/the-next-step/one-does-not-simply-enter-my-b-hole/" data-orig-file="/2013/01/one-does-not-simply-enter-my-b-hole.jpg" data-orig-size="551,325" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;}" data-image-title="one-does-not-simply-enter-my-b-hole" data-image-description="" data-medium-file="/2013/01/one-does-not-simply-enter-my-b-hole-200x117.jpg" data-large-file="/2013/01/one-does-not-simply-enter-my-b-hole-450x265.jpg" class=" wp-image-8274 " title="one-does-not-simply-enter-my-b-hole" src="/2013/01/one-does-not-simply-enter-my-b-hole-450x265.jpg" alt="" width="360" height="212" srcset="/2013/01/one-does-not-simply-enter-my-b-hole-450x265.jpg 450w, /2013/01/one-does-not-simply-enter-my-b-hole-150x88.jpg 150w, /2013/01/one-does-not-simply-enter-my-b-hole-200x117.jpg 200w, /2013/01/one-does-not-simply-enter-my-b-hole-500x294.jpg 500w, /2013/01/one-does-not-simply-enter-my-b-hole.jpg 551w" sizes="(max-width: 360px) 100vw, 360px" /></a> <p id="caption-attachment-8274" class="wp-caption-text"> I found this when Googling &#8220;B-hole&#8221; </p> </div> If your program has a lot of dicking around &#8212; activities that will not improve your performance in the competition &#8212; then cut them out. This is, of course, an individualistic and circumstantial thing, but you don&#8217;t need to do conditioning or irrelevant assistance exercises in the six weeks before your lifting meet (other competitions may have different guidelines). Let this be a time where you train primarily for something, and you&#8217;ll be rewarded with good progress. Especially if you put a premium on spending all of your recovery resources on specific training (i.e. recovering from compound strength lifts instead chest flyes and wiener lifts). Next, pay attention to the &#8220;outside the gym recovery&#8221;. Improve your <a href="/blog/2011/10/protein/" target="_blank">daily protein requirement</a>, <a href="/blog/2011/09/water-and-protein/" target="_blank">hydrate</a>, <a href="/blog/2012/12/importance-of-sleep/" target="_blank">sleep</a>, do your <a href="/blog/2011/06/mobility-basics/" target="_blank">mobility </a>(this post is a little dated, I&#8217;ll write a new one), and <a href="/blog/2012/02/garbage-in-garbage-out/" target="_blank">eat well</a>. If you do any of these things poorly, you will not be as prepared for your competition as you could be. If you don&#8217;t go 9/9 in powerlifting or 6/6 in weightlifting with PR&#8217;s, then you could have done something better. To be clear, PR&#8217;s are not necessarily the goal in competition because competition lifts are different than gym lifts. But, if you walk away from a good or bad competition thinking you could have done better, chances are that these &#8220;outside the gym recovery&#8221; variables could have been improved. And they can&#8217;t just be worked on a few times a week like lifting &#8212; they have to be done well every day. **Summary** Commit to something. Bash the shit out of quality reps in training and then start good habits outside of the gym. Eliminate the fluff in your program. Have a week of reduced training leading into the competition and be smart with weight choices (there are many resources on this site pertaining to meets), and you&#8217;ll walk away knowing that you busted your ass for something, and it paid off. Is there a better feeling? &nbsp;
Java
UTF-8
1,579
2.828125
3
[ "Apache-2.0" ]
permissive
package BULMADependences; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class GenerateShapes { private static final String FILE_SEPARATOR = ","; public static void main(String[] args) { String inputPath = args[0]; String outputPath = args[1]; BufferedReader brShapes = null; String lineShapes = ""; try { brShapes = new BufferedReader(new FileReader(inputPath)); FileWriter output = null; PrintWriter printWriter = null; String shapeId = ""; brShapes.readLine(); while ((lineShapes = brShapes.readLine()) != null) { String[] data = lineShapes.split(FILE_SEPARATOR); String routeId = data[0]; String currentShapeId = data[1]; Double lat = Double.valueOf(data[2]); Double lng = Double.valueOf(data[3]); if (!shapeId.equals(currentShapeId)) { //new shape shapeId = currentShapeId; String newOutputPath = outputPath + "shape" + routeId + "-" + currentShapeId + ".csv"; if(output != null && printWriter != null) { output.close(); printWriter.close(); } output = new FileWriter(newOutputPath); printWriter = new PrintWriter(output); printWriter.println("latitude,longitude"); } printWriter.println(lat + FILE_SEPARATOR + lng); } System.out.println("Done!"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
Markdown
UTF-8
947
3.015625
3
[ "Apache-2.0" ]
permissive
--- title: "Lesson 8: Overview" module: "dagster_essentials" lesson: "8" --- # Overview In the previous lesson, you learned about schedules and running your pipelines regularly. Going back to the cookie analogy, imagine that your cookie business is blossoming, and you’ve started taking orders in advance. Making every cookie right as each order came in would create problems. For example, an order for today is more urgent than an order for next week. Meanwhile, on some days, you would receive 100 orders, but you may receive zero orders on other days. Therefore, you batch your orders by the day they’re expected to be picked up. Every morning, you look at the orders to be fulfilled that day and only make the cookies for those orders. By looking at each day at a time, you are **partitioning** the orders. In this lesson, you’ll learn why to partition your data assets and how to do it in Dagster by partitioning the taxi trip data.
Java
UTF-8
2,430
2.265625
2
[ "BSD-3-Clause" ]
permissive
package dyvil.tools.compiler.ast.access; import dyvil.reflect.Opcodes; import dyvil.tools.compiler.ast.classes.IClass; import dyvil.tools.compiler.ast.context.IContext; import dyvil.tools.compiler.ast.expression.IValue; import dyvil.tools.compiler.ast.generic.ITypeContext; import dyvil.tools.compiler.ast.member.Name; import dyvil.tools.compiler.ast.parameter.IParameter; import dyvil.tools.compiler.ast.structure.IClassCompilableList; import dyvil.tools.compiler.ast.type.IType; import dyvil.tools.compiler.backend.MethodWriter; import dyvil.tools.compiler.backend.exception.BytecodeException; import dyvil.tools.compiler.lexer.marker.MarkerList; public final class ClassParameterSetter implements IValue { private IClass theClass; private IParameter parameter; public ClassParameterSetter(IClass theClass, IParameter param) { this.theClass = theClass; this.parameter = param; } @Override public void writeStatement(MethodWriter writer) throws BytecodeException { writer.writeVarInsn(Opcodes.ALOAD, 0); writer.writeVarInsn(this.parameter.getType().getLoadOpcode(), this.parameter.getIndex()); writer.writeFieldInsn(Opcodes.PUTFIELD, this.theClass.getInternalName(), this.parameter.getName().qualified, this.parameter.getDescription()); } @Override public void toString(String prefix, StringBuilder buffer) { Name name = this.parameter.getName(); buffer.append("this.").append(name).append(" = ").append(name); } // ----- Ignore ----- @Override public int valueTag() { return 0; } @Override public IType getType() { return null; } @Override public IValue withType(IType type, ITypeContext typeContext, MarkerList markers, IContext context) { return null; } @Override public boolean isType(IType type) { return false; } @Override public void resolveTypes(MarkerList markers, IContext context) { } @Override public IValue resolve(MarkerList markers, IContext context) { return this; } @Override public void checkTypes(MarkerList markers, IContext context) { } @Override public void check(MarkerList markers, IContext context) { } @Override public IValue foldConstants() { return this; } @Override public IValue cleanup(IContext context, IClassCompilableList compilableList) { return this; } @Override public void writeExpression(MethodWriter writer) throws BytecodeException { this.writeStatement(writer); } }
Markdown
UTF-8
972
2.671875
3
[]
no_license
--- title: 存到多少錢才敢退休?學習投資理財才是退休無慮之道 date: '2017-10-05 00:00:00' layout: page categories: finance --- 「 存到多少才敢退休?」這個問題幾乎可說是所有投資理財行為的最終目標。學習錢滾錢就是為了當自己沒有薪資收入時,能拿出之前省吃儉用加上投資獲利所得的儲蓄,讓生活過著和退休之前同樣水平的日子。 依照近年來的幾項調查指出,台灣人民普遍認為存到1,000萬至1,500萬,才讓自己的退休生活游刃有餘,這數字說高不高,說低也不算低,但國人最常使用的理財商品是以儲蓄險為主的保險工具,以目前預定利率在歷史低點徘徊的情況來看,若在退休金累積階段就將大量資金轉入此類商品,將造成每月要存下的資金額度增加,並且讓複利效果大打折扣。 舉例來說......[詳閱全文](https://www.thenewslens.com/article/80279)
PHP
UTF-8
3,511
2.65625
3
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
<?php namespace lav45\behaviors\traits; use yii\helpers\ArrayHelper; /** * Trait WatchAttributesTrait * @package lav45\behaviors\traits */ trait WatchAttributesTrait { /** * @var array * [ * [ * - watch: string|array|true => watch for changes in a few fields, * - field: string => set value in this relation attribute, * - value: string|array|\Closure => get value from the attribute or path, * ], * ] */ private $attributes = []; /** * The method converts the value of the attributes field to a common form * @param array $attributes * Example: [ * 'id', * 'login' => 'user_login', * 'login' => [ * 'field' => 'user_login', * // 'watch' => 'login', * // 'value' => 'login', * ], * [ * 'watch' => 'status', * // 'watch' => true, // always send this data * // 'watch' => ['status', 'username'], * * 'field' => 'statusName', * * 'value' => 'status', * // 'value' => 'array.key', * // 'value' => ['array', 'key'], * // 'value' => function($owner) { * // return $owner->array['key']; * // }, * ], * ] */ public function setAttributes(array $attributes) { $this->attributes = []; foreach ($attributes as $key => $val) { if (is_int($key) && is_string($val)) { $key = $val; } if (empty($val['watch'])) { $watch = $key; } else { $watch = $val['watch']; } if (is_string($val)) { $field = $val; } elseif (empty($val['field'])) { $field = $key; } else { $field = $val['field']; } if (empty($val['value'])) { $value = $key; } else { $value = $val['value']; } $this->attributes[] = [ 'watch' => $watch, 'field' => $field, 'value' => $value, ]; } } /** * @param object $model * @param array $attributes */ private function updateModel($model, $attributes) { foreach ($attributes as $attribute) { $model->{$attribute['field']} = ArrayHelper::getValue($this->owner, $attribute['value']); } } /** * @param array $changedAttributes * @return array */ private function getChangedAttributes($changedAttributes) { $result = []; foreach ($this->attributes as $attribute) { $watch = $attribute['watch']; if (true === $watch) { $result[] = $attribute; continue; } if (is_array($watch)) { foreach ($watch as $item) { if (isset($changedAttributes[$item]) || array_key_exists($item, $changedAttributes)) { $result[] = $attribute; break; } } continue; } if (isset($changedAttributes[$watch]) || array_key_exists($watch, $changedAttributes)) { $result[] = $attribute; } } return $result; } }
JavaScript
UTF-8
8,846
2.671875
3
[]
no_license
(function(){ function onload (moment) { (function(){ moment.lang('en', { longDateFormat : { LT : "h:mma", L : "MM/DD/YYYY", LL : "MM/DD", LLL : "MMMM D, LT", LLLL : "MMMM D YYYY, LT" } }); })(); (function(){ // moment.js language configuration // language : spanish (es) // author : Julio Napurí : https://github.com/julionc moment.lang('es', { months : "enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre".split("_"), monthsShort : "ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.".split("_"), weekdays : "domingo_lunes_martes_miércoles_jueves_viernes_sábado".split("_"), weekdaysShort : "dom._lun._mar._mié._jue._vie._sáb.".split("_"), weekdaysMin : "Do_Lu_Ma_Mi_Ju_Vi_Sá".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM", LL : "DD/MM/YYYY", LLL : "D \\de MMMM, LT", LLLL : "D \\de MMMM \\de YYYY, LT" }, calendar : { sameDay : function () { return '[hoy a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, nextDay : function () { return '[mañana a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, nextWeek : function () { return 'dddd [a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, lastDay : function () { return '[ayer a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, lastWeek : function () { return '[el] dddd [pasado a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, sameElse : 'L' }, relativeTime : { future : "en %s", past : "hace %s", s : "unos segundos", m : "un minuto", mm : "%d minutos", h : "una hora", hh : "%d horas", d : "un día", dd : "%d días", M : "un mes", MM : "%d meses", y : "un año", yy : "%d años" }, ordinal : '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })(); (function(){ // moment.js language configuration // language : french (fr) // author : John Fischer : https://github.com/jfroffice moment.lang('fr', { months : "janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre".split("_"), monthsShort : "janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.".split("_"), weekdays : "dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi".split("_"), weekdaysShort : "dim._lun._mar._mer._jeu._ven._sam.".split("_"), weekdaysMin : "Di_Lu_Ma_Me_Je_Ve_Sa".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: "[Aujourd'hui à] LT", nextDay: '[Demain à] LT', nextWeek: 'dddd [à] LT', lastDay: '[Hier à] LT', lastWeek: 'dddd [dernier à] LT', sameElse: 'L' }, relativeTime : { future : "dans %s", past : "il y a %s", s : "quelques secondes", m : "une minute", mm : "%d minutes", h : "une heure", hh : "%d heures", d : "un jour", dd : "%d jours", M : "un mois", MM : "%d mois", y : "un an", yy : "%d ans" }, ordinal : function (number) { return number + (number === 1 ? 'er' : 'ème'); }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })(); (function(){ // moment.js language configuration // language : italian (it) // author : Lorenzo : https://github.com/aliem moment.lang('it', { months : "Gennaio_Febbraio_Marzo_Aprile_Maggio_Giugno_Luglio_Agosto_Settembre_Ottobre_Novembre_Dicembre".split("_"), monthsShort : "Gen_Feb_Mar_Apr_Mag_Giu_Lug_Ago_Set_Ott_Nov_Dic".split("_"), weekdays : "Domenica_Lunedì_Martedì_Mercoledì_Giovedì_Venerdì_Sabato".split("_"), weekdaysShort : "Dom_Lun_Mar_Mer_Gio_Ven_Sab".split("_"), weekdaysMin : "D_L_Ma_Me_G_V_S".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay: '[Oggi alle] LT', nextDay: '[Domani alle] LT', nextWeek: 'dddd [alle] LT', lastDay: '[Ieri alle] LT', lastWeek: '[lo scorso] dddd [alle] LT', sameElse: 'L' }, relativeTime : { future : "in %s", past : "%s fa", s : "secondi", m : "un minuto", mm : "%d minuti", h : "un'ora", hh : "%d ore", d : "un giorno", dd : "%d giorni", M : "un mese", MM : "%d mesi", y : "un anno", yy : "%d anni" }, ordinal: '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })(); (function(){ // moment.js language configuration // language : brazilian portuguese (pt-br) // author : Caio Ribeiro Pereira : https://github.com/caio-ribeiro-pereira moment.lang('pt-br', { months : "Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro".split("_"), monthsShort : "Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez".split("_"), weekdays : "Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado".split("_"), weekdaysShort : "Dom_Seg_Ter_Qua_Qui_Sex_Sáb".split("_"), weekdaysMin : "Dom_2ª_3ª_4ª_5ª_6ª_Sáb".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D \\de MMMM \\de YYYY", LLL : "D \\de MMMM \\de YYYY LT", LLLL : "dddd, D \\de MMMM \\de YYYY LT" }, calendar : { sameDay: '[Hoje às] LT', nextDay: '[Amanhã às] LT', nextWeek: 'dddd [às] LT', lastDay: '[Ontem às] LT', lastWeek: function () { return (this.day() === 0 || this.day() === 6) ? '[Último] dddd [às] LT' : // Saturday + Sunday '[Última] dddd [às] LT'; // Monday - Friday }, sameElse: 'L' }, relativeTime : { future : "em %s", past : "%s atrás", s : "segundos", m : "um minuto", mm : "%d minutos", h : "uma hora", hh : "%d horas", d : "um dia", dd : "%d dias", M : "um mês", MM : "%d meses", y : "um ano", yy : "%d anos" }, ordinal : '%dº' }); })(); (function(){ // moment.js language configuration // language : portuguese (pt) // author : Jefferson : https://github.com/jalex79 moment.lang('pt', { months : "Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro".split("_"), monthsShort : "Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez".split("_"), weekdays : "Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado".split("_"), weekdaysShort : "Dom_Seg_Ter_Qua_Qui_Sex_Sáb".split("_"), weekdaysMin : "Dom_2ª_3ª_4ª_5ª_6ª_Sáb".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D \\de MMMM \\de YYYY", LLL : "D \\de MMMM \\de YYYY LT", LLLL : "dddd, D \\de MMMM \\de YYYY LT" }, calendar : { sameDay: '[Hoje às] LT', nextDay: '[Amanhã às] LT', nextWeek: 'dddd [às] LT', lastDay: '[Ontem às] LT', lastWeek: function () { return (this.day() === 0 || this.day() === 6) ? '[Último] dddd [às] LT' : // Saturday + Sunday '[Última] dddd [às] LT'; // Monday - Friday }, sameElse: 'L' }, relativeTime : { future : "em %s", past : "%s atrás", s : "segundos", m : "um minuto", mm : "%d minutos", h : "uma hora", hh : "%d horas", d : "um dia", dd : "%d dias", M : "um mês", MM : "%d meses", y : "um ano", yy : "%d anos" }, ordinal : '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })(); moment.lang('en') } if (typeof define === "function" && define.amd) { define(["moment"], onload); } if (typeof window !== "undefined" && window.moment) { onload(window.moment); } })();
PHP
UTF-8
1,754
2.96875
3
[ "MIT" ]
permissive
<?php namespace Boscho87\ChangelogChecker\Checkers; use Boscho87\ChangelogChecker\Options\Option; /** * Class DefaultChecker */ class DefaultChecker extends AbstractChecker { public function __construct() { $options = new Option(true, false, true, []); parent::__construct($options); } protected function check(): void { $contents = preg_replace('/\n{2,}/', PHP_EOL.PHP_EOL, $this->file->getContents()); if ($contents !== $this->file->getContents()) { $this->addErrorMessage('There should never been more than one linebreak'); } foreach ($this->file as $line) { $replacement = preg_replace('/\w\s{2,}/', ' ', $line); if ($line !== $replacement) { $this->addErrorMessage(sprintf( '"%s" has > 1 space on line %s', $line, $this->file->lineNumber() )); } } } protected function fix(): void { $contents = preg_replace('/\n{2,}/', PHP_EOL.PHP_EOL, $this->file->getContents()); if ($contents !== $this->file->getContents()) { $this->file->setNewContent($contents); $this->addFixedMessage('Replaced all double line breaks with only one'); } foreach ($this->file as $line) { $replacement = preg_replace('/\s{2,}/', ' ', $line); if ($line !== $replacement) { $this->file->setLine($replacement); $this->addFixedMessage(sprintf( '"%s" replaced all spaces > 1 on line %s', $line, $this->file->lineNumber() )); } } } }
Markdown
UTF-8
2,886
2.703125
3
[ "MIT" ]
permissive
# [REST2MERN-Book-API-Refactor](https://github.com/SmithBWare89/MERN-Book-API-Refactor) -- [Deployed](https://rest2mern-movieapi-refactor.herokuapp.com/) ## Description This project is intended to be a demonstration of a MERN (Mongo, Express, REACT, and Node) application. I've taken the source code provided for the project and converted the RESTful API that was originally in place into one that connects all of the aforementioned modalities together. This has been accomplished by creating a working REACT server using the Apollo package as well as using GraphQL to write queries and mutations that return data from the MongoDB database. Bridging the gap between all of the aforementioned packages proved to be a really difficult challenge as there was more files to manage than in my previous projects but it's something that I've definitely learned from. ![MERN Application Photo](./assets/book-api-image.PNG) ## User Story ``` AS AN avid reader I WANT to search for new books to read SO THAT I can keep a list of books to purchase ``` ## Table of Contents * [Installation](#installation) * [License](#license) * [Languages](#languages) * [Packages](#packages) * [Contributing](#contributing) * [Questions](#questions) ## Installation You can visit the deployed [web application](https://rest2mern-movieapi-refactor.herokuapp.com/) which is in it's development phase or by cloning the repository, installing the node packages using the `npm i` in your command line, then navigating to the `client` AND `server` packages running `npm i` again, and then going back to the root directory to run `npm run start:dev` to start your connection in the development environment. ## License [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) ## Languages ![Javascript Badge](https://img.shields.io/badge/Language-Javascript-blue) ![Node Badge](https://img.shields.io/badge/Language-Node-blue) ![HTML Badge](https://img.shields.io/badge/Language-HTML-blue) ![CSS Badge](https://img.shields.io/badge/Language-CSS-blue) ## Packages ![Express Badge](https://img.shields.io/badge/Node%20Package-Express-blue) ![Mongoose Badge](https://img.shields.io/badge/Node%20Package-Mongoose-blue) ![MongoDB Badge](https://img.shields.io/badge/Node%20Package-MongoDB-blue) ![Apollo Badge](https://img.shields.io/badge/Node%20Package-Apollo-blue) ![REACT Badge](https://img.shields.io/badge/Node%20Package-REACT-blue) ![IF-ENV Badge](https://img.shields.io/badge/Node%20Package-IF--ENV-blue) ![JSON Web Token Badge](https://img.shields.io/badge/Node%20Package-JSON--Web--Token-blue) ![Concurrently Badge](https://img.shields.io/badge/Node%20Package-Concurrently-blue) ## Contributing Create a pull request on the repository. ## Questions All questions can be directed to [my email](smithwrestling89@gmail.com) or [github](https://www.github.com/SmithBWare89).
Markdown
UTF-8
3,949
3.359375
3
[]
no_license
## 什麼是 Ajax? #### 前情提要 網頁能夠動態的產生資料給使用者看,是瀏覽器在 client 端與 server 端之間不停地交換資訊訊所造就的成果。透過使用者在網頁上觸發了某種事件(例如點擊按鈕),透過瀏覽器發送 Request 到 server,server 收到後再回傳 Response 給瀏覽器,瀏覽器再根據收到東西重新渲染(render)出使用者看到的頁面。 早期的網頁,還沒發展出非同步的方式,要傳送資料給 server,通常是用 `<form>` 來發送 Request。在這種方式下,每一個跟 Javascript 相關的動作,對於使用者來說,都要等待很久很久才會有回應出現在網頁上。 為了改善這種情況,有位大師 Jesse James Garrett 提出了 AJAX 的方式,讓網頁在頁面沒有重新整理的狀態下,也能即時地更新網頁內容,大大改善了使用者體驗。 #### 到底什麼是 Ajax 全名是 Asynchronous Javascript and XML,AJAX 不是指單一個技術,而是有機的利用了一系列相關的技術,讓網頁透過 Javascript 以特定格式來回傳資料,讓網頁能夠非同步更新網頁內容。 非同步的概念就是,當用戶端發送 Request 的時候,不用等待 Response 回來才能繼續做事,等收到 Response 之後,瀏覽器會自己幫我們把結果送過來。舉生活上的例子來幫助理解,就像是去摩斯漢堡內用的時候,你點完餐會拿到一個號碼牌,就可以離開櫃檯去找位置),等餐點好了,店員就會幫你把餐點送過來。而不是必須得待在原地等餐點好了才能去找位置。 ## 用 Ajax 與我們用表單送出資料的差別在哪? 最大的差別在於收到 Response 之後不用重新渲染(render)出一個頁面。 用表單送出資料,所收到的 Response 會由瀏覽器重新渲染(render)出一個新的頁面,但前後兩個頁面中的大部分程式碼其實是相同的,這麼做浪費了許多頻寬。 而使用 AJAX,可以只向伺服器傳送並取回必要的資訊,瀏覽器收到 Response 時,不會重新 render 一個頁面,而是把這個 Response 丟給 Javascript 來處理,只更新需要更新的部分。 ## JSONP 是什麼? 是另一種前後端交換資料的方式,目前已經比較少人用了。JSONP 利用了有些 HTML 標籤不受同源政策束縛的特性 (像是`<img> <script>`),把需要交換的資訊,透過這些標籤來向伺服器要到資料。 ## 要如何存取跨網域的 API? server 必須在發送 Response 時,在 header 帶上允許跨域瀏覽的資訊,開啟 Access-Control-Allow-Origin 的設定。 ## 為什麼我們在第四週時沒碰到跨網域的問題,這週卻碰到了? 因為在第四週時是用電腦發送 Request,這週是使用瀏覽器發送 Request。 使用瀏覽器發送的 Request 基本上都必須受到同源政策的束縛,只要 client 端跟 server 端是不同網域,就不能接收到 Response。 但在實際的應用上,大部分的 client 端與 server 端都是不同的網域,因此有 CORS 這個規範產生,如果 server 需要回應不同網域的 Request,就必須在 Response 的 header 上開啟 "Access-Control-Allow-Origin " 的設定。 基於資訊安全考量,我們對伺服器發送的 Request,如果沒有被對方伺服器允許,是收不到 Response 的。 否則所有人都能看到 google 資料庫裡的所有東西,包含帳號、密碼、個資等等。 瀏覽器可以說是 client、server 之間資料交換的管理員,幫忙加了很多規範。 #### 參考資料 [輕鬆理解 Ajax 與跨來源請求](https://blog.huli.tw/2017/08/27/ajax-and-cors/) [[JS] AJAX 筆記](https://medium.com/%E9%A6%AC%E6%A0%BC%E8%95%BE%E7%89%B9%E7%9A%84%E5%86%92%E9%9A%AA%E8%80%85%E6%97%A5%E8%AA%8C/js-ajax-%E7%AD%86%E8%A8%98-b9a57976fa60) [維基百科](https://zh.wikipedia.org/wiki/AJAX)
Python
UTF-8
1,086
3.234375
3
[]
no_license
#AlgoPrak2_Cherinda Maharani print (" /$$ /$$ /$$ ") print (" | $$ |__/ | $$ ") print (" /$$$$$$$| $$$$$$$ /$$$$$$ /$$$$$$ /$$ /$$$$$$$ /$$$$$$$ /$$$$$$ ") print (" /$$_____/| $$__ $$ /$$__ $$ /$$__ $$| $$| $$__ $$ /$$__ $$ |____ $$") print ("| $$ | $$ \ $$| $$$$$$$$| $$ \__/| $$| $$ \ $$| $$ | $$ /$$$$$$$") print ("| $$ | $$ | $$| $$_____/| $$ | $$| $$ | $$| $$ | $$ /$$__ $$") print ("| $$$$$$$| $$ | $$| $$$$$$$| $$ | $$| $$ | $$| $$$$$$$| $$$$$$$") print (" \_______/|__/ |__/ \_______/|__/ |__/|__/ |__/ \_______/ \_______/") from math import sqrt a, b, c = ( int(input('Masukkan angka pertama: ')), int(input('Masukkan angka kedua: ')), int(input('Masukkan angka ketiga: ')) ) if a > b and a > c: print('Angka terbesar adalah angka pertama: ', a) elif b > a and b > c: print('Angka terbesar adalah angka kedua: ', b) else: print('Angka terbesar adalah angka ketiga: ', c)
JavaScript
UTF-8
1,468
3.25
3
[]
no_license
//comments' page script var input = document.getElementById("userInput"); var firstName = document.getElementById("firstn"); var lastName = document.getElementById("lastn"); var email = document.getElementById("email"); var post = document.getElementById("post"); var ul = document.querySelector(".cmt ul"); var isEven = true; function isEmpty() { if(input.value.length==0 || firstName.value.length==0 || lastName.value.length==0 || email.value.length==0) return true; return false; } function addComment() { var div1 = document.createElement("div"); var div2 = document.createElement("div"); var li = document.createElement("li"); div1.appendChild(document.createTextNode(firstName.value+" "+lastName.value+": ")); div2.appendChild(document.createTextNode(input.value)); div1.className="nameInput"; div2.setAttribute("style","margin-left:20px;color:white;"); li.appendChild(div1); li.appendChild(div2); if(isEven) { li.className="even"; isEven=false; } else isEven=true; ul.appendChild(li); firstName.value=""; lastName.value=""; email.value=""; input.value=""; } function addItem() { if(!isEmpty()) addComment(); else alert("You can't comment with missing value(s)."); } function postWithEnter(event) { if(event.keyCode === 13) addItem(); } post.addEventListener("click",addItem); ul.addEventListener("keypress",postWithEnter); //join.html script
Markdown
UTF-8
1,124
2.5625
3
[]
no_license
--- title: Art Home School - Perspective 1, Week 4 --- <div class="ahs-update"> # Perspective 1, Week 4* Week of July 25 \ 5h 7m of drawing This week wasn't very productive due to an expected traumatic event that occurred Tuesday evening. Took me most of the week to get back in the groove. <div class="ahs-pics"> ![0](../img/art-home-school/perspective-1/week-4/mon-1.jpg) ![1](../img/art-home-school/perspective-1/week-4/mon-2.jpg) ![2](../img/art-home-school/perspective-1/week-4/sat-1.jpg) ![3](../img/art-home-school/perspective-1/week-4/sat-2.jpg) ![4](../img/art-home-school/perspective-1/week-4/tue-1.jpg) </div> Week of August 1 \ 3h 14m of drawing Another slow week for drawing progress. Most of my time got sucked up by moving out of my SF apartment, but I should start waking up early in the morning and drawing for an hour to start off the day to make sure every week is moving me forward <div class="ahs-pics"> ![0](../img/art-home-school/perspective-1/week-4/mon2-1.jpg) ![1](../img/art-home-school/perspective-1/week-4/tue2-1.jpg) ![2](../img/art-home-school/perspective-1/week-4/mon2-2.jpg) </div>
C++
UTF-8
935
3.078125
3
[]
no_license
#include "stdafx.h" #include "Stats.h" //Default constructor FStats::FStats() { Strength = 0; Dexterity = 0; Wisdom = 0; Charisma = 0; } /* Constructor with parameters */ FStats::FStats(int strength, int dexterity, int wisdom, int charisma) { Strength = strength; Dexterity = dexterity; Wisdom = wisdom; Charisma = charisma; } //Deconstructor FStats::~FStats() { } /*-------------------------------------- Setters and getters --------------------------------------*/ void FStats::SetStrength(int strength) { Strength = strength; } int FStats::GetStrength() { return Strength; } void FStats::SetDexterity(int dexterity) { Dexterity = dexterity; } int FStats::GetDexterity() { return Dexterity; } void FStats::SetWisdom(int wisdom) { Wisdom = wisdom; } int FStats::GetWisdom() { return Wisdom; } void FStats::SetCharisma(int charisma) { Charisma = charisma; } int FStats::GetCharisma() { return Charisma; }
Java
UTF-8
771
2.171875
2
[]
no_license
package mobile.project.dtos; import java.time.LocalDate; import java.time.LocalTime; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter @NoArgsConstructor public class CommentDto { private Integer commentId; private String content; private LocalDate postDate; private LocalTime postTime; private int likeNumber; private Integer userId; private Integer shopId; public CommentDto(Integer commentId, String content, LocalDate postDate, LocalTime postTime, int likeNumber, Integer userId, Integer shopId) { super(); this.commentId = commentId; this.content = content; this.postDate = postDate; this.postTime = postTime; this.likeNumber = likeNumber; this.userId = userId; this.shopId = shopId; } }
C#
UTF-8
949
2.625
3
[]
no_license
using System; using CoreApp.Models.Authentication; using CoreApp.Models.Repositories; using CoreApp.Repositories; namespace CoreApp.Services { public interface ITokenService { TokenModel Get(string Token); string Create(string UserId); string Delete(string Token); } public class TokenService : ServiceBase, ITokenService { private IRepository<SessionDto> sessionRepo; public TokenService(IContext context, IRepository<SessionDto> sessionRepo) : base(context) { this.sessionRepo = sessionRepo; } public string Create(string UserId) { var token = Guid.NewGuid().ToString(); sessionRepo.Create(new SessionDto(){ Id = token, UserId = UserId, SetTime = DateTime.Now.ToUniversalTime() }); return token; } public string Delete(string Token) { sessionRepo.Delete(Token); return Token; } public TokenModel Get(string Token) { return sessionRepo.Get(Token).ToModel(); } } }
PHP
UTF-8
2,802
2.59375
3
[]
no_license
<?php include("include/appTop.inc.php"); $explodeHeure = explode("-", $_POST['heure'], 2); $heure = explode("-", substr($explodeHeure[1], 1)); $d = explode("/",$_POST["date"]); $heure = new DateTime($d[2]."-".$d[1]."-".$d[0]." ".$heure[0].":".$heure[1].":00"); $dateTravail = substr($explodeHeure[0], 1); // $d[0] == date selectionnée $diff = $d[0]-$dateTravail; $newD = new DateTime($d[2]."-".$d[1]."-".$d[0]); if($diff <= 6 && $diff >= 0){ $newD->modify("-".abs($diff)." day"); } else if($diff < 0 && $diff >= -6){ $newD->modify("+".abs($diff)." day"); } else if($diff > 6){ $diff2 = $d[0] - $diff; $newD->modify("+1 month"); $newD->setDate($newD->format("Y"), $newD->format("m"), $diff2); } else if($diff < -6){ $diff2 = $d[0] - $diff; $newD->modify("-1 month"); $newD->setDate($newD->format("Y"), $newD->format("m"), $diff2); } //echo $diff; $quart1 = ["08:30:00", "09:00:00", "09:30:00", "10:00:00"]; $quart2 = ["10:30:00", "11:00:00", "11:30:00", "12:00:00"]; $quart3 = ["13:30:00", "14:00:00", "14:30:00"]; $quart4 = ["15:00:00", "15:30:00", "16:00:00"]; switch(true){ case in_array($heure->format("H:i:s"), $quart1): $quart = $quart1; break; case in_array($heure->format("H:i:s"), $quart2): $quart = $quart2; break; case in_array($heure->format("H:i:s"), $quart3): $quart = $quart3; break; case in_array($heure->format("H:i:s"), $quart4): $quart = $quart4; break; default: $quart = [$heure->format("H:i:s")]; break; } foreach ($quart as $horaire) { $AllParams[] = [":Salle_id"=> $_POST['salle'], ":Formation_id"=>$_POST['formation'], ":Reservation_date"=>$newD->format("Y-m-d"), ":Reservation_heure"=>$horaire, ":User_id"=>1, ":Reservation_motif"=>NULL, ":Reservation_creation"=>date("y-m-d G:i:s")]; } $resultToReturn = []; foreach ($AllParams as $Params) { # code... $result = reservation::doReservation($Params, $userInLine["User_statut"]); if(gettype($result) == "boolean"){ if($result){ $resultToReturn[] = "ok"; } else { $resultToReturn[] = "ko"; } } else { $resultToReturn[] = $result; } } $return = "ok"; foreach ($resultToReturn as $result) { if($result != "ok" && $result != "ko"){ $return = $result; break(1); } else if($result == "ko"){ $return = $result; break(1); } } echo $return; //$Params = [":Salle_id"=> $_POST['salle'], ":Formation_id"=>$_POST['formation'], ":Reservation_date"=>$newD->format("Y-m-d"), ":Reservation_heure"=>$heure->format("H:i:s"), ":User_id"=>1, ":Reservation_motif"=>NULL, ":Reservation_creation"=>date("y-m-d G:i:s")]; //print_r($Params);// //$result = reservation::doReservation($Params, $userInLine["User_statut"]); //var_dump($result); // if(gettype($result) == "boolean"){ // if($result){ // echo "ok"; // } else { // echo "ko"; // } // } else { // echo $result; // }
C++
UTF-8
7,783
3.90625
4
[]
no_license
//Coded by Username77177 //C++ Basics in a week challenge /// Day 1 - Conditions, Cycles, Switch operator(Topic: 2 of 10) ////1 #include <iostream> #include <string> using namespace std; int main(int argc, char *argv[]) { bool new_bool; // Новая переменная, которая принимает только два значения: true или false ( Правда или Ложь ) new_bool = true; new_bool = false; /* ▄█ ▄████████ ███ ███ ███ ███▌ ███ █▀ ███▌ ▄███▄▄▄ ███▌ ▀▀███▀▀▀ ███ ███ ███ ███ █▀ ███ ▄████████ ▄█ ▄████████ ▄████████ ███ ███ ███ ███ ███ ███ ███ ███ █▀ ███ ███ █▀ ███ █▀ ▄███▄▄▄ ███ ███ ▄███▄▄▄ ▀▀███▀▀▀ ███ ▀███████████ ▀▀███▀▀▀ ███ █▄ ███ ███ ███ █▄ ███ ███ ███▌ ▄ ▄█ ███ ███ ███ ██████████ █████▄▄██ ▄████████▀ ██████████ ▀ ▄████████ ▄█ ▄████████ ▄████████ ▄█ ▄████████ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ █▀ ███ ███ █▀ ███ █▀ ███▌ ███ █▀ ▄███▄▄▄ ███ ███ ▄███▄▄▄ ███▌ ▄███▄▄▄ ▀▀███▀▀▀ ███ ▀███████████ ▀▀███▀▀▀ ███▌ ▀▀███▀▀▀ ███ █▄ ███ ███ ███ █▄ ███ ███ ███ ███ ███▌ ▄ ▄█ ███ ███ ███ ███ ███ ██████████ █████▄▄██ ▄████████▀ ██████████ █▀ ███ */ // if - оператор сравнения. Он сравнивает два операнда, и если сравнение прошло успешно, то он возвращает true (правда), и выполняет блок кода, что находится ниже него // В противном случае, он возвращает false (ложь), и ничего не делает со своим блоком кода // Также существуют операторы сравнения, которые отдают такие же логические значения ( true or false ) // >, <, == (равно), != (не равно), <=, >= (меньше либо равно, больше либо равно) if (3 > 5) { cout << "Этот текст не выведется" ; } if (3 != 3) { cout<< "Этот текст тоже не выведется"; } if (77177 == 77177) { cout << "А вот этот текст уже выведется" << endl; } // Если условие верно, то оно выполнится, если нет - не выполнится if (true) { cout << "Hello, World!" << endl; } // Если значение переменной не содержит только 0, то оно интерпретируется как правда (true) int null_element = 0; if (null_element) { cout << "Этот текст тоже никогда не выведется" << endl; } if (123) { cout << "cout'у все равно что за цифра в скобках, лишь бы не 0" << endl; } ////2 // Вложенные функции if if (true) { if (2 == 2) { cout << "Пример вложенного условия if" << endl; } } // if else // Else - оператор, который говорит программе что делать, если условие не прошло проверку // (Вернуло ложь (False)) if (false) { } else { cout << "Выведется этот cout" << endl; } // Разработаем легкую игру, которая будет говорить нам, больше ли введённое число тысячи или нет // SCORE RATER GAME int score; cin >> score; if (score > 1000) { cout<< "Ваше число " << score << " больше, чем 1000!" << endl; } else { cout << "Ваше число определённо меньше 1000" << endl; } // SCORE RATER GAME END ////3 // Ветвление с Else if (будем называть его elif) // Else if - "в остальном, если", то есть проверка на это условие будет проверяться, только если главная проверка (if) прошла и завершилась результатом false if (false) { cout<< "if - вернул false (сообщение не выведется)"; } else if (true) { cout << "А вот это сообщение выведется" << endl; } else { cout << "Это сообщение тоже не выведется, просто потому, что условие выше вернуло true"; } // Switch - оператор выбора // Объявляем новую переменную и вводим в неё значения cout << "Добрейший вечерочек, введите значение:\n0 - Добрейший вечерочек\n1 - привет\n2 - Здравствуйте\n"; int New_String; cin >> New_String; switch (New_String) { case 0: cout << "Как вы вежливы!" << endl; break; case 1: cout << "Можно как-то вежливее?"<< endl; break; case 2: cout << "Я футбольный мячик, бом-бом"<< endl; break; default: cout << "Вы не ввели цифру, как это оговаривалось выше, бунтарь" << endl; } return 0; }
TypeScript
UTF-8
3,286
2.515625
3
[]
no_license
import { Injectable } from '@angular/core'; import { Crawler } from '../classes/crawler'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import 'rxjs/add/operator/toPromise'; @Injectable() export class CrawlerService { private CrawlersUrl = '/queen/crawler'; constructor (private http: Http) {} generateBacklog(crawler: Crawler): Promise<any | void> { return this.http.post(this.CrawlersUrl + "/generateBacklog", crawler) .toPromise() .then(response => response.json() as any) .catch(this.handleError); } commenceProbing(): Promise<String[] | void> { return this.http.get(this.CrawlersUrl) .toPromise() .then(response => response.json() as String[]) .catch(this.handleError); } // post("/Crawler/Crawlers") runCode(crawler: Crawler): Promise<Crawler | void> { console.log("data"); return this.http.post(this.CrawlersUrl + '/run', crawler) .toPromise() .then(response => response.json() as Crawler) .catch(this.handleError); } // get("/Crawler/Crawlers") getCrawlers(): Promise<Crawler[] | void> { return this.http.get(this.CrawlersUrl) .toPromise() .then(response => response.json() as Crawler[]) .catch(this.handleError); } // get("/Crawler/Crawlers") getCrawlersBySite(siteName: String): Promise<Crawler[] | void> { return this.http.get(this.CrawlersUrl + '/site/' + siteName) .toPromise() .then(response => response.json() as Crawler[]) .catch(this.handleError); } // get("/Crawler/Crawlers/:id") getCrawler(CrawlerId: String): Promise<Crawler | void> { return this.http.get(this.CrawlersUrl + '/' + CrawlerId) .toPromise() .then(response => response.json() as Crawler) .catch(this.handleError); } // post("/Crawler/Crawlers") createCrawler(newCrawler: Crawler): Promise<Crawler | void> { var data = newCrawler; return this.http.post(this.CrawlersUrl, data) .toPromise() .then(response => response.json() as Crawler) .catch(this.handleError); } // delete("/Crawler/Crawlers/:id") deleteCrawler(delCrawlerId: String): Promise<String | void> { return this.http.delete(this.CrawlersUrl + '/' + delCrawlerId) .toPromise() .then(response => response.json() as String) .catch(this.handleError); } // put("/Crawler/Crawlers/:id") updateCrawler(putCrawler: Crawler): Promise<Crawler | void> { var putUrl = this.CrawlersUrl + '/' + putCrawler._id; return this.http.put(putUrl, putCrawler) .toPromise() .then(response => response.json() as Crawler) .catch(this.handleError); } private handleError (error: any) { let errMsg = (error.message) ? error.message : error.status ? `${error.status} - ${error.statusText}` : 'Server error'; console.error(errMsg); // log to console instead } }
Python
UTF-8
1,188
4.3125
4
[]
no_license
# Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits: # 1634 = 1**4 + 6**4 + 3**4 + 4**4 # 8208 = 8**4 + 2**4 + 0**4 + 8**4 # 9474 = 9**4 + 4**4 + 7**4 + 4**4 # As 1 = 1**4 is not a sum it is not included. # The sum of these numbers is 1634 + 8208 + 9474 = 19316. # Find the sum of all the numbers that can be written as the sum of fifth powers of their digits. from math import floor, log10 import timeit start = timeit.default_timer() def digit(n): digitArr = [] length = floor(log10(n)) + 1#number of digits in n for i in range(length): digitArr.append(n//10**i % 10)#makes an array of the digits of n return digitArr def digitpower(n): digitArr = digit(n) digitpowerArr = [] for num in digitArr: digitpowerArr.append(num**5) return digitpowerArr def digitpowersum(n): return(sum(digitpower(n))) def checker(): arr = [] for i in range(999,500000): if digitpowersum(i) == i: arr.append(i) return sum(arr) print(checker()) stop = timeit.default_timer() print('Time:',stop-start) #output is 443839, time 2.0152123 seconds
PHP
UTF-8
1,507
2.765625
3
[]
no_license
<?php require_once 'connect.php'; $id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT); $stmt = $pdo->prepare('SELECT * FROM books WHERE id=:id'); $stmt->execute(['id' => $id]); $book = $stmt->fetch(); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title><?php echo $book['title']; ?></title> </head> <body> <h1><?php echo $book['title']; ?></h1> <img src="<?php echo $book['cover_path']; ?>"> <table> <tr> <td>Aasta:</td> <td><?php echo $book['release_date']; ?></td> </tr> <tr> <td>Kirjeldus:</td> <td><?php echo $book['summary']; ?></td> </tr> <tr> <td>Hind:</td> <td><?php echo str_replace('.', ',', round($book['price'], 2)); ?> &euro;</td> </tr> <tr> <td>Lehekülgi:</td> <td><?php echo $book['pages']; ?></td> </tr> <tr> <td>Laos:</td> <td><?php echo $book['stock_saldo'] > 0 ? 'Jah' : 'Ei'; ?></td> </tr> <tr> <td>Tüüp:</td> <td><?php echo $book['type'] == 'ebook' ? 'E-raamat' : $book['type'] == 'used' ? 'Kasutatud' : 'Uus'; ?></td> </tr> </table> <div style="margin-top: 2em;"> <span><a href="editform.php">muuda</a></span> <span><a href="delete.php? id=5">kustuta</a></span> </div> </body> </html>
Rust
UTF-8
8,240
2.953125
3
[ "BSD-3-Clause" ]
permissive
use openexr_sys as sys; use crate::core::error::Error; type Result<T, E = Error> = std::result::Result<T, E>; /// A KeyCode object uniquely identifies a motion picture film frame. /// The following fields specifiy film manufacturer, film type, film /// roll and the frame's position within the roll. /// /// # Fields /// /// * `film_mfc_code` - Film manufacturer code. /// Range: `[0, 99]` /// * `filmType` - Film type code. /// Range: `[0, 99]` /// * `prefix` - Prefix to identify film roll. /// Range: `[0, 999999]` /// * `count` - Count, increments once every perfs_per_count perforations. /// Range: `[0, 9999]` /// * `perf_offset` - Offset of frame, in perforations from zero-frame reference mark /// Range: `[0, 119]` /// * `perfs_per_frame` - Number of perforations per frame. Typical values are 1 for 16mm film; 3, 4 or 8 for 35mm film; 5, 8 or 15 for 65mm film. /// Range: `[1, 15]` /// * `perfs_per_count` - Number of perforations per count. Typical values are 20 for 16mm film, 64 for 35mm film, 80 or 120 for 65mm film. /// Range: `[20, 120]` /// /// # Further Reading /// For more information about the interpretation of those fields see /// the following standards and recommended practice publications: /// * SMPTE 254 Motion-Picture Film (35-mm) - Manufacturer-Printed /// Latent Image Identification Information /// * SMPTE 268M File Format for Digital Moving-Picture Exchange (DPX) /// (section 6.1) /// * SMPTE 270 Motion-Picture Film (65-mm) - Manufacturer- Printed /// Latent Image Identification Information /// * SMPTE 271 Motion-Picture Film (16-mm) - Manufacturer- Printed /// Latent Image Identification Information /// #[repr(transparent)] pub struct KeyCode(sys::Imf_KeyCode_t); impl KeyCode { /// Get the film manufacturer code. Valid range `[0, 99]` /// pub fn film_mfc_code(&self) -> i32 { let mut v = 0i32; unsafe { sys::Imf_KeyCode_filmMfcCode(&self.0, &mut v) .into_result() .expect("Unexpected exception from Imf_KeyCode_filmMfcCode"); } v } /// Set the film manufacturer code. Valid range `[0, 99]` /// /// # Errors /// * [`Error::InvalidArgument`] - If `code` is not in the range `[0, 99]` /// /// TODO: Do we want to implement a bounded integer here to specify the range? pub fn set_film_mfc_code(&mut self, code: i32) -> Result<()> { unsafe { sys::Imf_KeyCode_setFilmMfcCode(&mut self.0, code).into_result()?; } Ok(()) } /// Get the film type code. Valid range `[0, 99]` /// pub fn film_type(&self) -> i32 { let mut v = 0i32; unsafe { sys::Imf_KeyCode_filmType(&self.0, &mut v) .into_result() .expect("Unexpected exception from Imf_KeyCode_filmType"); } v } /// Set the film type code. Valid range `[0, 99]` /// /// # Errors /// * [`Error::InvalidArgument`] - If `code` is not in the range `[0, 99]` /// pub fn set_film_type(&mut self, code: i32) -> Result<()> { unsafe { sys::Imf_KeyCode_setFilmType(&mut self.0, code).into_result()?; } Ok(()) } /// Get the prefix code which identifies the film roll. /// Valid range `[0, 999999]` /// pub fn prefix(&self) -> i32 { let mut v = 0i32; unsafe { sys::Imf_KeyCode_filmType(&self.0, &mut v) .into_result() .expect("Unexpected exception from Imf_KeyCode_filmType"); } v } /// Set the prefix code which identifies the film roll. /// Valid range `[0, 999999]` /// /// # Errors /// * [`Error::InvalidArgument`] - If `code` is not in the range `[0, 999999]` /// pub fn set_prefix(&mut self, v: i32) -> Result<()> { unsafe { sys::Imf_KeyCode_setPrefix(&mut self.0, v).into_result()?; } Ok(()) } /// Get the count, which increments every `perfs_per_count` perforations. /// Valid range [0, 9999] /// pub fn count(&self) -> i32 { let mut v = 0i32; unsafe { sys::Imf_KeyCode_filmType(&self.0, &mut v) .into_result() .expect("Unexpected exception from Imf_KeyCode_filmType"); } v } /// Set the count, which increments every `perfs_per_count` perforations. /// Valid range [0, 9999] /// /// # Errors /// * [`Error::InvalidArgument`] - If `count` is not in the range `[0, 9999]` /// pub fn set_count(&mut self, count: i32) -> Result<()> { unsafe { sys::Imf_KeyCode_setCount(&mut self.0, count).into_result()?; } Ok(()) } /// Get the offset of the frame in perforations from the zero-frame reference mark. /// Valid range [0, 119] /// pub fn perf_offset(&self) -> i32 { let mut v = 0i32; unsafe { sys::Imf_KeyCode_filmType(&self.0, &mut v) .into_result() .expect("Unexpected exception from Imf_KeyCode_filmType"); } v } /// Set the offset of the frame in perforations from the zero-frame reference mark. /// Valid range [0, 119] /// /// # Errors /// * [`Error::InvalidArgument`] - If `offset` is not in the range `[0, 119]` /// pub fn set_perf_offset(&mut self, offset: i32) -> Result<()> { unsafe { sys::Imf_KeyCode_setPerfOffset(&mut self.0, offset) .into_result()?; } Ok(()) } /// Get the number of perforations per frame. /// Valid range [1, 15] /// /// Typical values: /// * 1 for 16mm film /// * 3, 4 or 8 for 35mm film /// * 5, 8, or 15 for 65mm film /// pub fn perfs_per_frame(&self) -> i32 { let mut v = 0i32; unsafe { sys::Imf_KeyCode_filmType(&self.0, &mut v) .into_result() .expect("Unexpected exception from Imf_KeyCode_filmType"); } v } /// Set the number of perforations per frame. /// Valid range [1, 15] /// /// Typical values: /// * 1 for 16mm film /// * 3, 4 or 8 for 35mm film /// * 5, 8, or 15 for 65mm film /// /// # Errors /// * [`Error::InvalidArgument`] - If `perfs` is not in the range `[1, 15]` /// pub fn set_perfs_per_frame(&mut self, perfs: i32) -> Result<()> { unsafe { sys::Imf_KeyCode_setPerfsPerFrame(&mut self.0, perfs) .into_result()?; } Ok(()) } /// Get the number of perforations per count. /// Valid range [2, 120] /// /// Typical values: /// * 20 for 16mm film /// * 64 for 35mm film /// * 80 or 120 for 65mm film /// pub fn perfs_per_count(&self) -> i32 { let mut v = 0i32; unsafe { sys::Imf_KeyCode_filmType(&self.0, &mut v) .into_result() .expect("Unexpected exception from Imf_KeyCode_filmType"); } v } /// Set the number of perforations per count. /// Valid range [2, 120] /// /// Typical values: /// * 20 for 16mm film /// * 64 for 35mm film /// * 80 or 120 for 65mm film /// /// # Errors /// * [`Error::InvalidArgument`] - If `perfs` is not in the range `[2, 120]` /// pub fn set_perfs_per_count(&mut self, perfs: i32) -> Result<()> { unsafe { sys::Imf_KeyCode_setPerfsPerCount(&mut self.0, perfs) .into_result()?; } Ok(()) } } impl Default for KeyCode { fn default() -> Self { let mut inner = sys::Imf_KeyCode_t::default(); unsafe { sys::Imf_KeyCode_ctor(&mut inner, 0, 0, 0, 0, 0, 4, 64) .into_result() .expect("Unexpected exception from Imf_KeyCode_ctor"); } KeyCode(inner) } } #[cfg(test)] #[test] fn test_keycode() { let mut k = KeyCode::default(); assert!(k.set_film_mfc_code(-1).is_err()); assert!(k.set_film_mfc_code(1).is_ok()); assert_eq!(k.film_mfc_code(), 1); }
Python
UTF-8
1,646
3.109375
3
[]
no_license
import unittest from main.question22 import my1, book1, my2 class MSTestCase(unittest.TestCase): def setUp(self): self.nums = list(range(10)) def test_my1_create_linklist(self): head = my1.create_linklist(nums=self.nums) self.assertEqual(self.nums, my1.display_linklist(head)) def test_my1_last_index_from_linklist(self): head = my1.create_linklist(self.nums) self.assertEqual(8, my1.last_index_from_linklist(head, 2)) # 头节点为空的情况 with self.assertRaises(TypeError): my1.last_index_from_linklist(None, 3) # k大于长度的情况 with self.assertRaises(IndexError): my1.last_index_from_linklist(head, 20) # 0的情况 with self.assertRaises(ValueError): my1.last_index_from_linklist(head, 0) def test_book1_find_k_to_tail(self): head = my1.create_linklist(self.nums) self.assertEqual(8, book1.find_k_to_tail(head, 2)) # 头节点为空的情况 with self.assertRaises(TypeError): book1.find_k_to_tail(None, 3) # k大于长度的情况 with self.assertRaises(IndexError): book1.find_k_to_tail(head, 20) # 0的情况 with self.assertRaises(ValueError): book1.find_k_to_tail(head, 0) def test_my2_mid_node(self): head = my1.create_linklist(self.nums) self.assertTrue(my2.mid_node(head).value in (4, 5)) head = my1.create_linklist(list(range(1, 6))) self.assertEqual(3, my2.mid_node(head).value) if __name__ == '__main__': unittest.main()
C++
UTF-8
457
2.5625
3
[]
no_license
#include <LiquidCrystal.h> int x,i ; LiquidCrystal lcd(4,5,6,7,8,9); void setup() { // put your setup code here, to run once: lcd.begin(16,2); lcd.clear(); } void loop() { // put your main code here, to run repeatedly: x = analogRead(A0); i=x/205; lcd.setCursor(1, 0); lcd.print(x); lcd.setCursor(1, 1); lcd.print(i); lcd.setCursor(4,1); lcd.print ("volts"); delay(1000); if (x > 1000 || x <= 0) { lcd.clear(); } }
Go
UTF-8
387
2.609375
3
[]
no_license
package utils import ( "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" "testing" ) func TestInitLogger(t *testing.T) { w := InitLogger() field := Log.WithField("test", "test") assert.Equal(t, "test", field.Data["test"]) assert.IsType(t, Log.Formatter, &logrus.JSONFormatter{}) assert.Equal(t, Log.GetLevel(), logrus.InfoLevel) assert.NoError(t, w.Close()) }
Java
UTF-8
5,121
2.765625
3
[]
no_license
package my_collection; import java.util.ArrayList; import java.util.EnumMap; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; public class Main { public static void main(String[] args) { workWithCollection(); sortHashMapByKey(); sortHashMapByEntity(); workWithUser(); } public static void workWithCollection(){ Human artur = new Human("Smirnov Artur Arsenevich", 20, "Kovernino, ulitza Akademika Krilova, dom 1, kv 678"); Human arturArsenevich = new Human("Smirnov Artur Arsenevich", 20, "Kovernino, ulitza Akademika Krilova, dom 1, kv 678"); Human adam = new Human("Grishin Adam Vsevolodovich", 12, "Kargopol, Teatralny proezd, dom 66, kv 615"); Human adamVsevolodovich = new Human("Grishin Adam Vsevolodovich", 12, "Kargopol, Teatralny proezd, dom 66, kv 615"); Human lavr = new Human("Lihachev Lavr Grigorievich", 34, "Sarov, ulitza Yasenevaya, dom 158, kv 780"); Human lavrGrigorievich = new Human("Lihachev Lavr Grigorievich", 34, "Sarov, ulitza Yasenevaya, dom 158, kv 780"); Human ilya = new Human("Kulagin Ilya Lukyanovich", 28, "Ostashkov, ulitza Mariinskaya, dom 40, kv 689"); Human ivan = new Human("Aksenov Ivan Konstantinovich", 18, "Doneck, Monetchikovsky pereulok, dom 141, kv 333"); Human velor = new Human("Ivanov Velor Michailovich", 42, "Zalari, ulitza Beringa, dom 181, kv 361"); Human yury = new Human("Melnikov Yury Filatovich", 64, "Kornevo, ulitza Dmitry Donskogo, dom 97, kv 571"); List<Human> humans = new ArrayList<>(); humans.add(artur); humans.add(arturArsenevich); humans.add(adam); humans.add(adamVsevolodovich); humans.add(lavr); humans.add(lavrGrigorievich); humans.add(ilya); humans.add(ivan); humans.add(velor); humans.add(yury); Set<Human> duplicates = findDuplicates(humans); System.out.println("The list of duplicates:"); System.out.println(duplicates); Set<Human> uniqes = deleteDuplicates(humans); System.out.println("The list of uniqes:"); System.out.println(uniqes); List<Human> uniqesHumans = new ArrayList<>(uniqes); //сортировка по ФИО uniqesHumans.sort(new HumanNameComparator()); System.out.println("Sorted List by Name: " + uniqesHumans); //сортировка по возрасту uniqesHumans.sort(new HumanAgeComparator()); System.out.println("Sorted List by Age:" + uniqesHumans); //сортировка по адресу uniqesHumans.sort(new HumanAddressComparator()); System.out.println("Sorted List by Address" + uniqesHumans); } public static Set<Human> findDuplicates(List<Human> collection) { Set<Human> uniqes = new HashSet<>(); Set<Human> duplicates = new HashSet<>(); for (Human h: collection){ if(!uniqes.add(h)){ duplicates.add(h); } } return duplicates; } public static Set<Human> deleteDuplicates(List<Human> collection){ return new HashSet<>(collection); } public static void workWithUser() { User user1 = new User("Administrator", Roles.ADMIN); User user2 = new User("Vasya", Roles.USER); User user3 = new User("Ivan", Roles.MODERATOR); welcomeUserMessage(user1); welcomeUserMessage(user2); welcomeUserMessage(user3); } public static void welcomeUserMessage(User user) { Map<Roles, String> rolesDescription = new EnumMap<>(Roles.class); rolesDescription.put(Roles.ADMIN, "(полные права)"); rolesDescription.put(Roles.USER, "(просмотр, написание комментариев)"); rolesDescription.put(Roles.MODERATOR, "(модерация комментариев)"); System.out.println("Приветствуем " + user.getName() + " с ролью " + user.getRole() + " " + rolesDescription.get(user.getRole())); } public static void sortHashMapByKey() { Map<String, Integer> hashMap = new HashMap<>(); hashMap.put("Anna", 18); hashMap.put("Maria", 19); hashMap.put("Darya", 20); hashMap.put("Elena", 21); hashMap.put("Vera",22); System.out.println("HashMap: " + hashMap); Map<String, Integer> sortedHashMap = new TreeMap<>(hashMap); System.out.println("HashMap sorted by key: " + sortedHashMap); } public static void sortHashMapByEntity(){ Map<String, Integer> hashMap = new HashMap<>(); hashMap.put("Anna", 18); hashMap.put("Maria", 19); hashMap.put("Darya", 20); hashMap.put("Elena", 21); hashMap.put("Vera",22); System.out.println("HashMap: " + hashMap); List<Map.Entry<String,Integer>> sorted = new ArrayList<>(hashMap.entrySet()); sorted.sort(Map.Entry.comparingByValue()); Map<String, Integer> result = new LinkedHashMap<>(); for(Map.Entry<String, Integer> entry: sorted){ result.put(entry.getKey(), entry.getValue()); } System.out.println("HashMap sorted by entity: " + result); } }
Java
UTF-8
98
1.851563
2
[]
no_license
package Oppgave1; public class KlasseEn { public double tall() { return 2.0; } }
C#
UTF-8
2,519
3.140625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; using System.IO; namespace PhraseSet { class Tool { public static Stopwatch watch; public static double basetime = 0; public static int getTime() { return (int)((basetime+watch.Elapsed.TotalMilliseconds)/1000); } public static void start() { watch = new Stopwatch(); FileInfo file = new FileInfo("time.txt"); if (file.Exists) { try { StreamReader srd = file.OpenText(); basetime = Convert.ToDouble(srd.ReadLine()); srd.Close(); } catch { Console.WriteLine("error while load time state! waiting key ..."); Console.ReadKey(); } } else { basetime = 0; saveState(); } watch.Start(); } public static void stop() { watch.Stop(); saveState(); } public static void loadState() { /* FileInfo file = new FileInfo("time.txt"); try { StreamReader srd = file.OpenText(); basetime = Convert.ToInt32(srd.ReadLine()); srd.Close(); } catch { Console.WriteLine("error while load time state! waiting key ..."); Console.ReadKey(); }*/ } public static void saveState() { StreamWriter sw; try { sw = new StreamWriter("time.txt"); double savetime = basetime + watch.Elapsed.TotalMilliseconds; sw.WriteLine(savetime); sw.Close(); } catch { Console.WriteLine("error while save time state! waiting key ..."); Console.ReadKey(); } } public static void showTime() { int left = Console.CursorLeft; int top = Console.CursorTop; Console.SetCursorPosition(52, top); Console.Write("== Time: {0} s ==", getTime()); Console.SetCursorPosition(left, top); } } }
Java
UTF-8
4,728
2.9375
3
[]
no_license
package com.sps.game.sprites; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Vector2; import com.sps.game.animation.NpcAnimation; import com.sps.game.maps.MapFactory; import java.util.ArrayList; import java.util.Random; /** * This class creates the Interactive NPC * @author Miraj Shah, Miguel Abaquin, Devin Shingadia and Mahamuda Akhter * @version 1.0 */ public class InteractiveNPC extends AbstractNPC{ /** * Stores the NPC character's x co-ordinate * @see */ private int x; /** * Stores the NPC character's y co-ordinate * @see */ private int y; /** * Uses Tick to break down movement into a number of iterations so that it doesnt move too fast * @see */ private int tick = 0; /** * Stores the random variable so it can be used for the movement * @see */ private Random random; /** * Changes the speed of the NPC. * @see */ private Vector2 velocity; /** * Holds the different animations of the different types of NPCs. */ private NpcAnimation lindaAnimation, muffinAnimation, tropicalAnimation, enemyAnimation, otherAnimation; /** * Holds the type of the map. */ private MapFactory.MapType world; /** * Holds the name of the InteractiveNPC. */ private String name; /** * Creates and holds all the locations of all the interactive npc. */ public static ArrayList<Location> allInteractiveNPCLocations = new ArrayList<Location>(); public InteractiveNPC(int x, int y,MapFactory.MapType world, SpriteBatch sb, String name){ this.x = x; this.y = y; location = new Location(x,y); allInteractiveNPCLocations.add(location); lindaAnimation = new NpcAnimation(sb,this,"cryingNPC.atlas",1/2f); muffinAnimation = new NpcAnimation(sb,this,"interactiveCandy.atlas",1/2f); tropicalAnimation = new NpcAnimation(sb, this, "interactiveTropical.atlas", 1/2f); enemyAnimation = new NpcAnimation(sb, this, "interactiveEnemy.atlas", 1/2f); otherAnimation = new NpcAnimation(sb, this, "interactiveHome.atlas", 1/2f); this.world = world; this.name = name; } /** * Gets the current animation of the NPC. * @return NpcAnimation */ public NpcAnimation getAnimation() { if (getWorld().equals(MapFactory.MapType.HomeWorldMap1) || getWorld().equals(MapFactory.MapType.HomeWorldMap2)) { if (name.equals("Linda")) { otherAnimation = lindaAnimation; } } else if(getWorld().equals(MapFactory.MapType.CandyWorld1) || getWorld().equals(MapFactory.MapType.CandyWorld2)){ if(name.contains("Muffin")) { otherAnimation = muffinAnimation; } } else if (getWorld().equals(MapFactory.MapType.TropicalWorld1) || getWorld().equals(MapFactory.MapType.TropicalWorld2)){ if(name.contains("Tropical")){ otherAnimation = tropicalAnimation; } } else if (getWorld().equals(MapFactory.MapType.GraveyardWorld1) || getWorld().equals(MapFactory.MapType.GraveyardWest)){ if(name.contains("Grave")){ otherAnimation = enemyAnimation; } } return otherAnimation; } /** * Gets the world the NPC is in * @return MapFactory.MapType world */ public MapFactory.MapType getWorld () { return world; } /** * Get the name of the NPC. * @return String name */ public String getName () { return name; } /** * Gets the type of the NPC. * @return String */ public String getType () { return "InteractiveNPC"; } /** * Returns the NPC x Axis */ @Override public int getX() { return x; } /** * Returns the NPC Y Axis */ @Override public int getY() { return y; } /** * Returns the velocity of the NPC. */ @Override public Vector2 getVelocity() { return velocity; } /** * Sets the value of the Y coordinate. * @param float newY */ @Override public void setY(float newY) { } /** * Sets the value of the X coordinate. * @param float newX */ @Override public void setX(float newX) { } /** * Gets the current Location of the NPC * @return */ public Location getLocation() { return location; } /** * Changes the state of the NPC. * @param String newState */ @Override public void changeState(String newState) { } }
Java
UTF-8
1,176
1.710938
2
[]
no_license
package com.jf.dao; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import java.util.List; import com.jf.entity.CombineOrderExtendExt; import com.jf.entity.CombineOrderExtendExtExample; @Repository public interface CombineOrderExtendExtMapper { // ----------------------------------------------------------------------------------------------------------------- // 基本方法 // ----------------------------------------------------------------------------------------------------------------- CombineOrderExtendExt findById(int id); CombineOrderExtendExt find(CombineOrderExtendExtExample example); List<CombineOrderExtendExt> list(CombineOrderExtendExtExample example); List<Integer> listId(CombineOrderExtendExtExample example); int count(CombineOrderExtendExtExample example); long sum(@Param("field") String field, @Param("example") CombineOrderExtendExtExample example); int max(@Param("field") String field, @Param("example") CombineOrderExtendExtExample example); int min(@Param("field") String field, @Param("example") CombineOrderExtendExtExample example); }
Java
UTF-8
20,732
2.546875
3
[]
no_license
package com.googlecode.n_orm; import java.io.Serializable; import java.lang.reflect.Field; import java.util.Collection; import java.util.Date; import java.util.List; import com.googlecode.n_orm.PropertyManagement.PropertyFamily; import com.googlecode.n_orm.cf.ColumnFamily; import com.googlecode.n_orm.consoleannotations.Continuator; import com.googlecode.n_orm.storeapi.Store; /** * Persisting elements are elements that can be stored and retrieved from a {@link com.googlecode.n_orm.storeapi.SimpleStore}. * To make a class persisting, do not implement this interface, but rather declare the annotation {@link Persisting}. * @see Persisting */ public interface PersistingElement extends Comparable<PersistingElement>, Serializable { public static final long serialVersionUID = 3339697263519532988L; /** * The list of possible types for simple properties (including keys). * Other possible types are array of a possible type, persisting elements and classes with only keys. */ public static final Class<?>[] PossiblePropertyTypes = new Class[] { Date.class, String.class, Boolean.class, int.class, byte.class, short.class, long.class, float.class, double.class, boolean.class, char.class, Integer.class, Byte.class, Short.class, Long.class, Float.class, Double.class, Boolean.class, Character.class }; /** * The store used for this persisting element. */ public Store getStore(); /** * Sets the store used for this persisting element. Note that in most case, you do not need to use this method as stores are automatically discovered. * @param store the store to be used * @throws IllegalStateException in case this persisting element already has a store * @see Persisting */ public void setStore(Store store) throws IllegalStateException; /** * The table used to store this persisting element as declared by the {@link Persisting#table()} annotation. * If the persisting element inherits another persisting element, only the table for the instanciated class is shown. */ public String getTable(); /** * The list of keys for this persisting element. * A key is a property annotated with {@link Key}. * The result is sorted in the order declared by {@link Key#order()}. */ public List<Field> getKeys(); /** * The {@link ColumnFamily} used to store properties. * A property is a non static, non final, non transient field whose type is one of {@link #PossiblePropertyTypes} plus persisting elements plus classes with only key properties and no column family, plus arrays of such types. * Keys are also readable from this family. * The values stored in this column families are the last activated. * @see #activate(String...) */ public PropertyFamily getPropertiesColumnFamily(); /** * The list of all {@link ColumnFamily} held by this persisting element. */ public Collection<ColumnFamily<?>> getColumnFamilies(); //Can't be a java.util.Set as CFs are either Sets or Maps whose equals or hashCode must compare collection contents only /** * The the {@link ColumnFamily} held by this persisting element with the given name. * The name is the name of the property for the column family, i.e. the non static, non final , non transient {@link java.util.Map} or {@link java.util.Set} field. * @see ColumnFamily#getName() */ @Continuator public ColumnFamily<?> getColumnFamily(String columnFamilyName) throws UnknownColumnFamily; /** * The the {@link ColumnFamily} held by this persisting element corresponding to the object stored by the object as a column family. * Typical use is myPe.getColumnFamily(myPe.myCf) * @param collection the value for the property stored as a column family. */ public ColumnFamily<?> getColumnFamily(Object collection) throws UnknownColumnFamily; /** * The identifier for this persisting element. * The identifier is computed from a string representation of all keys of this persisting element separated with {@link KeyManagement#KEY_SEPARATOR}. * Moreover, the identifier ends with {@link KeyManagement#KEY_END_SEPARATOR}. * @throws IllegalStateException in case all keys have not been set * @see com.googlecode.n_orm.conversion.ConversionTools#convertToString(Object) */ public String getIdentifier(); /** * Same result as {@link #getIdentifier()}, but postfixed with the name of the class instanciated by this persisting element. * @see Object#getClass() */ public String getFullIdentifier(); /** * Checks whether this persisting has changed since its last activation. * In case this object has not changed, a {@link #store()} will not trigger any data store request. * @see #activate(String...) */ public boolean hasChanged(); /** * Stores the object into the data store designated by {@link #getStore()}. * All non static final or transient fields will be stored into the datastore. * All keys have to be set before invoking this operation * <p>This object is stored as a row in table designated by {@link #getTable()} using the key computed from {@link #getIdentifier()}. * Properties are stored in a column family whose name is given by {@link PropertyManagement#PROPERTY_COLUMNFAMILY_NAME}. * Column families are stored using their own name (see {@link #getColumnFamily(String)}), that is the name of the {@link java.util.Map} or {@link java.util.Set} fields. * Properties and column families which have not changed since last activation of this element are not sent to the store as they are supposed to be already stored. * </p><p>In case this persisting element inherits another persisting element class, a row with the full identifier is created in the tables for the ancestor class (see {@link Persisting#table()}). * Properties and column families are not stored in those rows unless stated by the {@link Persisting#storeAlsoInSuperClasses()} annotation in the actual class of this persisting element. * </p><p>To choose a store, you need to supply in the classpath a properties file depending on the nature of the data store you want to use. * This property file is to be found in the class path. For a persisting element of a class in package foo.bar, the property file is searched as foo/bar/store.propetries in the complete classpath (in the declared order), then as foo/store.properties, and then directly store.properties. * To know how to define the properties file, please refer to your data store supplier. An (naive) example is the {@link com.googlecode.n_orm.memory.Memory} data store. * </p> * <p> * <b>WARNING:</b> any column family change would raise a {@link java.util.ConcurrentModificationException} during this period in case application is multi-threaded and this element is explicitly shared by threads. * In the latter case, the store is retried at most 0.5s per problematic column family. * Simplest solution is to search this element in each thread using {@link StorageManagement#getElement(Class, String)}.<br> * A cleaner mean to solve this issue store calls should be performed within a synchronized section on this or on changed column family: * <blockquote><pre> * synchronized(element.myFamily) { //or merely synchronized(element) * element.myFamily.add(something); * } * </pre></blockquote> * Another way to avoid such problem is to use an instance of {@link ColumnFamily} as a column family (but then this cannot be serialized): * <blockquote><pre> * {@literal @}Persisting class Foo { * ... * public java.util.Map{@literal <}BarK,BarV{@literal >} element = new MapColumnFamily(); * } * </pre></blockquote> * * @throws DatabaseNotReachedException in case the store cannot store this persisting object (e.g. cannot connect to database) * @see #getIdentifier() * @see com.googlecode.n_orm.storeapi.SimpleStore */ @Continuator public void store() throws DatabaseNotReachedException; /** * Store this persisting element as {@link #store()} but ignoring any {@link com.googlecode.n_orm.cache.write.WriteRetentionStore write cache}. * Actually, in case this element has a write cache, request is still sent to the cache, but then flushed immediately so that previous requests regarding this element are merged and sent. * @throws DatabaseNotReachedException */ @Continuator public void storeNoCache() throws DatabaseNotReachedException; /** * Deletes rows representing this persisting element in the store. * @see #store() */ @Continuator public void delete() throws DatabaseNotReachedException; /** * Deletes rows representing this persisting element in the store. * Actually, in case this element has a write cache, request is still sent to the cache, but then flushed immediately so that previous requests regarding this element are merged and sent. * @see #store() */ @Continuator public void deleteNoCache() throws DatabaseNotReachedException; /** * If an element with the same id as this element exists in the cache, returns the element from the cache, otherwise returns this element which will be placed in the cache. * Advantage of this method is to use as much as possible the internal cache, which makes possible to get a possibly already activated object, and get results faster using {@link #exists()}, {@link #activateIfNotAlready(String...)}, {@link #activateColumnFamilyIfNotAlready(String)}, or {@link #activateColumnFamilyIfNotAlready(String, Object, Object)}.<br> * Typically, this method is used just after the object construction, as soon as keys are valued. An example is the following:<br> * <code> * &#64;Persisting public class Element {<br> * &nbsp;&nbsp;&nbsp;&nbsp;&#64;Key private String key;<br> * &nbsp;&nbsp;&nbsp;&nbsp;&#64;Key publi Element(String key) {<br> * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.key = key;<br> * &nbsp;&nbsp;&nbsp;&nbsp;}<br> * } * </code><br> * <br> * <code>Element elt = new Element("key").getCachedVersion();</code> * @see com.googlecode.n_orm.cache.perthread.Cache */ public PersistingElement getCachedVersion(); /** * Checks whether the row representing this persisting element is known to exist in the store avoiding as much as possible to query the data store. * A persisting element is said to exist if it has been stored, if it was successfully activated, or if a previous invocation of {@link #exists()} or {@link #existsInStore()} returned true. * A persisting element is said not to exist if it has never been stored, if it has been unsuccessfully activated (i.e. the data store didn't return any information about the element), or if a previous invocation of {@link #exists()} or {@link #existsInStore()} returned false. * In other situations, the data store is queried using {@link #existsInStore()}. * @see #getCachedVersion() */ public boolean exists() throws DatabaseNotReachedException; /** * Checks whether the row representing this persisting element exists in the store. * Rows used to store this element in table for its super-classes are not tested. * @see #store() */ @Continuator public boolean existsInStore() throws DatabaseNotReachedException; /** * Retrieves information from the store and put it into this persisting element. * Erases changes done in properties and column families. * Properties that are persisting elements are also activated. * Column families annotated with {@link ImplicitActivation} are also activated. * Use {@link #activateIfNotAlready(String...)} in case you want to avoid re-activating already activated elements of this persisting elements. * @param families names of the families to activate even if they are not annotated with {@link ImplicitActivation} (see {@link #getColumnFamily(String)}) * @throws IllegalArgumentException in case a given column family does not exists */ public void activate(String... families) throws DatabaseNotReachedException; /** * Retrieves information that have not been activated yet from the store and put it into this persisting element. * Column families (the set of simple properties is considered as a column family) that have already been activated by whatever mean (e.g. {@link #activateColumnFamily(String, Object, Object)}) will not be activated. * This means that if a constraint were passed at a previous activation time, it will be preserved. * @param families names of the families to activate even if they are not annotated with {@link ImplicitActivation} (see {@link #getColumnFamily(String)}) * @throws IllegalArgumentException in case a given column family does not exists * @see #getCachedVersion() */ public void activateIfNotAlready(String... families) throws DatabaseNotReachedException; /** * Retrieves information that have not been activated yet from the store and put it into this persisting element. * Column families (the set of simple properties is considered as a column family) that have already been activated by whatever mean (e.g. {@link #activateColumnFamily(String, Object, Object)}) will not be activated. * This means that if a constraint were passed at a previous activation time, it will be preserved. * @param families names of the families to activate even if they are not annotated with {@link ImplicitActivation} (see {@link #getColumnFamily(String)}) * @param lastActivationTimeoutMs the maximum duration (in ms) at which last actual activation was performed. E.g. if last activation happened at 12:00 and method is called at 12:10 while this parameter is set to 3600000 (1 min), activation will happen anyway ; if parameter is set to 40000000, activation will not be performed * @throws IllegalArgumentException in case a given column family does not exists * @see #getCachedVersion() */ public void activateIfNotAlready(long lastActivationTimeoutMs, String... families) throws DatabaseNotReachedException; /** * Activates a given column family (does not activate included persisting elements). * @param name name of the column family * @throws UnknownColumnFamily in case this column family does not exist * @throws DatabaseNotReachedException * @see #getColumnFamily(String) */ @Continuator public void activateColumnFamily(String name) throws UnknownColumnFamily, DatabaseNotReachedException; /** * Activates a given column family (does not activate included persisting elements). * @param name name of the column family * @param from the minimal (inclusive) value for the activation (a key for a {@link java.util.Map} column family or a value for a {@link java.util.Set} column family) * @param to the maximal (inclusive) value for the activation (a key for a {@link java.util.Map} column family or a value for a {@link java.util.Set} column family) * @throws UnknownColumnFamily in case this column family does not exist * @throws DatabaseNotReachedException * @see #getColumnFamily(String) */ public void activateColumnFamily(String name, Object from, Object to) throws UnknownColumnFamily, DatabaseNotReachedException; /** * Activates a given column family (does not activate included persisting elements) in case it was not done before (with any possible activation method). * The column family won't be loaded if a previous activation was done, even if a constraint was given by {@link #activateColumnFamily(String, Object, Object)} or {@link #activateColumnFamilyIfNotAlready(String, Object, Object)}. * @param name name of the column family * @throws UnknownColumnFamily in case this column family does not exist * @throws DatabaseNotReachedException * @see #getColumnFamily(String) * @see #getCachedVersion() */ public void activateColumnFamilyIfNotAlready(String name) throws UnknownColumnFamily, DatabaseNotReachedException; /** * Activates a given column family (does not activate included persisting elements) in case it was not done before (with any possible activation method). * The column family won't be loaded if a previous activation was done, even if a constraint was given by {@link #activateColumnFamily(String, Object, Object)} or {@link #activateColumnFamilyIfNotAlready(String, Object, Object)}. * @param lastActivationTimeoutMs the maximum duration (in ms) at which last actual activation was performed. E.g. if last activation happened at 12:00 and method is called at 12:10 while this parameter is set to 3600000 (1 min), activation will happen anyway ; if parameter is set to 40000000, activation will not be performed * @param name name of the column family * @throws UnknownColumnFamily in case this column family does not exist * @throws DatabaseNotReachedException * @see #getColumnFamily(String) * @see #getCachedVersion() */ public void activateColumnFamilyIfNotAlready(String name, long lastActivationTimeoutMs) throws UnknownColumnFamily, DatabaseNotReachedException; /** * Activates a given column family (does not activate included persisting elements) in case it was not done before (with any possible activation method). * The column family won't be loaded if a previous activation was done, even if a constraint was given by {@link #activateColumnFamily(String, Object, Object)} or {@link #activateColumnFamilyIfNotAlready(String, Object, Object)}. * @param name name of the column family * @param from the minimal (inclusive) value for the activation (a key for a {@link java.util.Map} column family or a value for a {@link java.util.Set} column family) * @param to the maximal (inclusive) value for the activation (a key for a {@link java.util.Map} column family or a value for a {@link java.util.Set} column family) * @throws UnknownColumnFamily in case this column family does not exist * @throws DatabaseNotReachedException * @see #getColumnFamily(String) * @see #getCachedVersion() */ public void activateColumnFamilyIfNotAlready(String name, Object from, Object to) throws UnknownColumnFamily, DatabaseNotReachedException; /** * Activates a given column family (does not activate included persisting elements) in case it was not done before (with any possible activation method). * The column family won't be loaded if a previous activation was done, even if a constraint was given by {@link #activateColumnFamily(String, Object, Object)} or {@link #activateColumnFamilyIfNotAlready(String, Object, Object)}. * @param lastActivationTimeoutMs the maximum duration (in ms) at which last actual activation was performed. E.g. if last activation happened at 12:00 and method is called at 12:10 while this parameter is set to 3600000 (1 min), activation will happen anyway ; if parameter is set to 40000000, activation will not be performed * @param name name of the column family * @param from the minimal (inclusive) value for the activation (a key for a {@link java.util.Map} column family or a value for a {@link java.util.Set} column family) * @param to the maximal (inclusive) value for the activation (a key for a {@link java.util.Map} column family or a value for a {@link java.util.Set} column family) * @throws UnknownColumnFamily in case this column family does not exist * @throws DatabaseNotReachedException * @see #getColumnFamily(String) * @see #getCachedVersion() */ public void activateColumnFamilyIfNotAlready(String name, long lastActivationTimeoutMs, Object from, Object to) throws UnknownColumnFamily, DatabaseNotReachedException; /** * Flushes any outgoing request pending on a {@link com.googlecode.n_orm.cache.write.WriteRetentionStore write-retention store}. */ @Continuator public void flush(); /** * To be equal, two persisting elements must implement the same class and have the same identifier, no matter they have same values for properties and column families. * @see Object#equals(Object) */ public boolean equals(Object rhs); /** * The hash code for {@link #getIdentifier()}. * This method make possible to use persisting elements in {@link java.util.Hashtable}s, {@link java.util.HashMap}s or {@link java.util.HashSet}s. * @see Object#hashCode() */ @Continuator public int hashCode(); /** * If instanciated classes are different, class names are compared, in the other case, the result of {@link #getIdentifier()} are compared. * This method make possible to use persisting elements in {@link java.util.TreeMap}s or {@link java.util.TreeSet}s. * @see Comparable#compareTo(Object) */ public int compareTo(PersistingElement rhs); /** * Adds a listener to this persisting element. */ public void addPersistingElementListener(PersistingElementListener listener); /** * Removes a listener to this persisting element. */ public void removePersistingElementListener(PersistingElementListener listener); }
PHP
UTF-8
2,468
3.109375
3
[ "MIT" ]
permissive
<?php /** * @copyright A. Forster, 2014 * @link http://www.forster.io **/ declare(strict_types=1); namespace Acfo\Validation\Form\FormField; /** * Number * * http://www.w3.org/TR/html-markup/input.number.html */ class Number extends FormFieldImpl { const STEP_ANY = 'any'; // the value of 'any' on the HTML5 step attribute is needed to allow any float values /** * min * * @var mixed */ private $min; /** * max * * @var mixed */ private $max; /** * step * * @var mixed */ private $step; /** * @param float $min * @param float $max * @param mixed $step 'any' or float value * @param string $required * @param string $error */ public function __construct( float $min = PHP_INT_MIN, float $max = PHP_INT_MAX, $step = self::STEP_ANY, string $required = Requirement::OPTIONAL, string $error = Error::NONE ) { parent::__construct($required, $error); $this->min = $min; $this->max = $max; $this->step = $step; } /** * @param string $value * * @return bool */ public function isValid(string $value): bool { if (!is_numeric($value) || $value < $this->min || $value > $this->max || $this->step !== self::STEP_ANY && !$this->isValueMultipleOfStep($value, $this->step) ) { return false; } return parent::isValid($value); } /** * @return string min value or empty string */ public function getMin() { return (string)$this->min; } /** * @return string max value or empty string */ public function getMax() { return (string)$this->max; } /** * @return mixed if step is not set to STEP_ANY, setValue only accepts multiples of step */ public function getStep() { return $this->step; } /** * @param mixed $value * @param mixed $step * * @return bool */ private function isValueMultipleOfStep($value, $step) { $offset = $value - $this->min; if ($offset == (int)$offset && is_int($step)) { return ($offset % $step) == 0; } // TODO decide if 4 digit accuracy is sufficient. Use step size? return abs(($offset / $step) - round($offset / $step, 0)) < 0.0001; } }
C#
UTF-8
2,192
3.40625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Veterinaria { enum EspeciePajaro { Canario, Periquito, Agapornis // canario: 0 } class Pajaro : Animal { // Atributos private EspeciePajaro especie; private bool cantor; // Constructor /// <summary> /// Crea un nuevo objeto de la clase Pajaro. /// </summary> /// <param name="nombre">Nombre del pájaro.</param> /// <param name="fechaNacimiento">Fecha de nacimiento del pájaro.</param> /// <param name="peso">Peso del pájaro.</param> /// <param name="especie">Especie del pájaro.</param> /// <param name="cantor">"true" si el pájaro canta mucho, "false" si no</param> public Pajaro(string nombre, DateTime fechaNacimiento, double peso, EspeciePajaro especie, bool cantor) : base(nombre, fechaNacimiento, peso) { this.especie = especie; this.cantor = cantor; } // Propiedades /// <summary> /// Devuelve la especie del pájaro. /// </summary> public EspeciePajaro Especie { get { return this.especie; } } /// <summary> /// Devuelve "true" si el pájaro canta mucho, "false" si no. /// </summary> public bool Cantor { get { return this.cantor; } } // Métodos /// <summary> /// Crea una cadena con los atributos del pájaro. /// </summary> /// <returns>Cadena formateada para su impresión (un atributo por línea).</returns> public override string ToString() { string atributospajaro; atributospajaro = "Nombre: " + this.nombre + "\n" + "Fecha de nacimiento: " + this.fechaNacimiento + "\n" + "Peso: " + this.peso + "\n" + "Especie: " + this.especie + "\n" + "¿Es cantor? " + this.cantor + "\n" + "Comentarios: " + this.comentarios; return atributospajaro; } } }
Python
UTF-8
82
3.015625
3
[]
no_license
words = str(input("Your words: ")) probel = (words.count(' ') + 1) print(probel)
Shell
UTF-8
540
3.53125
4
[]
no_license
#!/bin/bash # # dmine uninstaller for linux. # # Remove recursively the install dir. install_dir="/opt/dmine" if [[ ! -d $install_dir ]]; then echo "Error: The install directory '$install_dir' is not found. "\ "Uninstallation failed." 1&>2 fi rm -rf "/opt/dmine" # Remove the sym link. sym_link_path="/usr/local/bin/dmine" if [[ ! -L $sym_link_path ]]; then echo "Error: The symbolic link '$sym_link_path' is not found. "\ "Uninstallation failed." 1&>2 fi rm $sym_link_path echo "Finished uninstalling dmine."
Python
UTF-8
15,296
3.84375
4
[]
no_license
import tkinter from tkinter import* #clase que realiza validaciones de fechas de calendario #Atributos: mensaje: sirve para guardar algun mensaje de error class ValidatorTipoDatosCalendario: #Funcion es_numero #Entradas: un string #Salidas: Booleano que determina si string es unicamente numerico #Proceso: recorre caracter por caracter a ver si es numero def es_numero(self,num): if len(num) == 0: return False for i in num: if i not in "1234567890": return False return True #Funcion: es_dato_de_calendario #Entradas: Un numero #Salidas un booleano que determina si el numero puede ser un dia, mes o anio #Proceso: revisa si dato es un numero entero y positivo y esta dentro de los rangos de dias, mese y anios def es_dato_de_calendario(self,num): if num < 0: return False elif num in range (1,13) or num in range (1,32) or num >= 1582: return True else: return False ################################################################################### #Clase Calendario #Hace consultas y calculos sobre fechas de un calendario class Calendario: mensajeError = "" #Funcion: bisiesto #Entradas: un anio #Salidas: un booleano #Proceso: se hace validacion de datos y luego se usa el modulo 4 para ver # si es divisible por 4 def bisiesto(self, anio): return anio % 4 == 0 #Funcion: fecha_es_valida #Entradas: una tupla (anio,mes,dia) #Salidas: un booleano #Proceso: Se toma en consideracion los siguientes aspectos: # -El mes debe estar entre 1 y 12 # -El dia depende del mes y anio # -Febrero tiene 29 dias en un anio bisiesto y sino 28 # -Meses con 31 dias: Enero, marzo, mayo, julio, agosto, octubre y # diciembre # -Mese con 30 dias: Abril, junio, setiembre y noviembre def fecha_es_valida(self,fecha): anio = fecha[0] mes = fecha[1] dia = fecha[2] if mes != 2: if mes in [1,3,5,7,8,10,12] and dia in range(1,32): return True elif mes in [4,6,9,11] and dia in range(1,31): return True else: self.mensajeError = "Dia y mes invalido" return False else: if self.bisiesto(anio): if dia in range(1,30): return True else: self.mensajeError = "Febrero tiene 29 dias en un anio bisiesto" return False else: if dia in range(1,29): return True else: self.mensajeError = "Febrero tiene 28 dias en un anio no bisiesto" return False #Funcion dia_siguiente #Entradas: una tupla (anio,mes,dia) #Salidas: una tupla con la fecha del siguiente dia #Proceso: se usa la funcion fecha_es_valida y su estructura para ver si dia + 1 aun es valido def dia_siguiente(self, fecha): anio = fecha[0] mes = fecha[1] dia = fecha[2] if self.fecha_es_valida(fecha): if mes == 12 and dia == 31: return (anio + 1, 1, 1) if self.fecha_es_valida((anio, mes, dia+1)): return (anio, mes, dia + 1) else: return (anio, mes + 1, 1) else: return () #Funcion dias_desde_primero_de_enero #Entradas: una tupla fecha (anio, mes, dia) #Salidas: un entero con la cantidad de dias desde el primero de enero #Proceso: se va incrementando dias desde la fecha primero de enero de 2018 hasta la ingresada usando dia_siguiente def dias_desde_primero_de_enero(self,fecha): anio = fecha[0] mes = fecha[1] dia = fecha[2] dias = 0 fechaActual = (anio,1,1) if not self.fecha_es_valida(fecha): return else: while fechaActual != fecha: fechaActual = self.dia_siguiente(fechaActual) dias = dias + 1 return dias #Funcion dia_de_hoy #Entradas: una tupla fecha (anio,mes,dia) #Salidas: Un digito representando dia de semana 0:domingo...6:sabado #Proceso: tomado de: http://code.activestate.com/recipes/266464-date-to-day-of-the-week/ def dia_de_hoy(self,fecha): anio = fecha[0] mes = fecha[1] dia = fecha[2] if mes < 3: z = anio - 1 else: z = anio diaSemana = ( 23*mes//9 + dia + 4 + anio + z//4 - z//100 + z//400 ) if mes >= 3: diaSemana -= 2 diaSemana = diaSemana % 7 return diaSemana #funcion dia primero de enero #Entradas un anio #Salidas: un digito representado dia de semana 0:domingo..6:sabado #Proceso: se usa la funcion dia_de_hoy con el primero de enero def dia_primero_enero(self,anio): return self.dia_de_hoy((anio,1,1)) ######################################################## #clase CalendarController #Clase que interactua con la interfaz y las clases de Calendario y ValidatorTipoDatosCalendario class CalendarController: validator = ValidatorTipoDatosCalendario() calendario = Calendario() vista = None #funcion __init__ #Esta funcion asigna la interfaz inicializada al atributo vista, asi se puede llamar # los atributos de la interfaz y modificarlos def __init__(self,app): self.vista= app #funcion esBiciesto #Entradas: un anio #Salidas: un string de si es o no biciesto o un mensaje de error #Proceso: Hace validacion de datos con el validator y luego llama a la funcion de Calendario de bisiesto def esBiciesto(self,anio): if self.validator.es_numero(anio): anio = int(anio) if self.validator.es_dato_de_calendario(anio): resultado = self.calendario.bisiesto(anio) if resultado: self.vista.lResultado.config(text="Si es bisiesto") else: self.vista.lResultado.config(text="No es bisiesto") else: self.vista.lResultado.config(text= "Debe ingresar un anio mayor a 1582") else: self.vista.lResultado.config(text="Debe ingresar un numero entero") #funcion verificarFecha #Entradas: un anio,mes y dia #Salidas: un string de si es o no una fecha valida o u mensaje de error #Proceso: Hace validacion de datos con el validator y luego llama a la funcion de fecha_es_valida del Calendario def verificarFecha(self,anio,mes,dia): if not self.validator.es_numero(anio): self.vista.lResultado.config(text="Debe ingresar un anio entero") elif not self.validator.es_numero(mes): self.vista.lResultado.config(text="Debe ingresar un mes entero entre 1 y 12") elif not self.validator.es_numero(dia): self.vista.lResultado.config(text="Debe ingresar un dia entero entre 1 y 31") else: anio = int(anio) mes = int(mes) dia = int(dia) if not self.validator.es_dato_de_calendario(anio): self.vista.lResultado.config(text= "Debe ingresar un anio mayor a 1582") elif not self.validator.es_dato_de_calendario(mes): self.vista.lResultado.config(text="Debe ingresar un mes entero entre 1 y 12") elif not self.validator.es_dato_de_calendario(dia): self.vista.lResultado.config(text="Debe ingresar un dia entero entre 1 y 31") else: resultado = self.calendario.fecha_es_valida((anio,mes,dia)) if resultado: self.vista.lResultado.config(text="Fecha ingresada es valida") else: self.vista.lResultado.config(text="Fecha ingresada no valida: \n" + self.calendario.mensajeError) #funcion diaSiguiente #Entradas: un anio,mes y dia #Salidas: un string del dia siguiente a la fecha o un mensaje de error #Proceso: Hace validacion de datos con el validator y luego llama a la funcion de Calendario de dia_siguiente def diaSiguiente(self,anio,mes,dia): if not self.validator.es_numero(anio): self.vista.lResultado.config(text="Debe ingresar un anio entero") elif not self.validator.es_numero(mes): self.vista.lResultado.config(text="Debe ingresar un mes entero entre 1 y 12") elif not self.validator.es_numero(dia): self.vista.lResultado.config(text="Debe ingresar un dia entero entre 1 y 31") else: anio = int(anio) mes = int(mes) dia = int(dia) if not self.validator.es_dato_de_calendario(anio): self.vista.lResultado.config(text= "Debe ingresar un anio mayor a 1582") elif not self.validator.es_dato_de_calendario(mes): self.vista.lResultado.config(text="Debe ingresar un mes entero entre 1 y 12") elif not self.validator.es_dato_de_calendario(dia): self.vista.lResultado.config(text="Debe ingresar un dia entero entre 1 y 31") else: resultado = self.calendario.dia_siguiente((anio,mes,dia)) if len(resultado) == 0: self.vista.lResultado.config(text=self.calendario.mensajeError) else: self.vista.lResultado.config(text="Dia siguiente: " + str(resultado[2]) + " del mes " + str(resultado[1]) + " del " + str(resultado[0])) #funcion diasDesdePrimeroEnero #Entradas: un anio,mes y dia #Salidas: un string con los dias desde el primero de enero de 2018 o un mensaje de error #Proceso: Hace validacion de datos con el validator y luego llama a la funcion de Calendario de dias_desde_primero_enero def diasDesdePrimeroEnero(self,anio,mes,dia): if not self.validator.es_numero(anio): self.vista.lResultado.config(text="Debe ingresar un anio entero") elif not self.validator.es_numero(mes): self.vista.lResultado.config(text="Debe ingresar un mes entero entre 1 y 12") elif not self.validator.es_numero(dia): self.vista.lResultado.config(text="Debe ingresar un dia entero entre 1 y 31") else: anio = int(anio) mes = int(mes) dia = int(dia) if not self.validator.es_dato_de_calendario(anio): self.vista.lResultado.config(text= "Debe ingresar un anio mayor a 1582") elif not self.validator.es_dato_de_calendario(mes): self.vista.lResultado.config(text="Debe ingresar un mes entero entre 1 y 12") elif not self.validator.es_dato_de_calendario(dia): self.vista.lResultado.config(text="Debe ingresar un dia entero entre 1 y 31") else: resultado = self.calendario.dias_desde_primero_de_enero((anio,mes,dia)) if resultado == None: self.vista.lResultado.config(text=self.calendario.mensajeError) else: self.vista.lResultado.config(text="Han pasado " + str(resultado) + " dias desde el 1ero de enero de ese anio") def diaPrimeroDeEnero(self,anio): if not self.validator.es_numero(anio): self.vista.lResultado.config(text="Debe ingresar un anio entero") else: anio = int(anio) if not self.validator.es_dato_de_calendario(anio): self.vista.lResultado.config(text= "Debe ingresar un anio mayor a 1582") else: resultado = self.calendario.dia_primero_enero(anio) dias = { 0:"Domingo", 1: "Lunes", 2: "Martes", 3: "Miercoles", 4: "Jueves", 5: "Viernes", 6: "Sabado" } self.vista.lResultado.config(text="Dia " + str(resultado)+ ":" + str(dias[resultado])) ####################################################### #Clase CalendarApp #Clase de GUI que interactua con clase CalendarController class CalendarApp: def llamarBiciesto(self): anio = self.eAnio.get() self.controlador.esBiciesto(anio) def llamarValidarFecha(self): anio = self.eAnio.get() mes = self.eMes.get() dia = self.eDia.get() self.controlador.verificarFecha(anio,mes,dia) def llamarDiaSiguiente(self): anio = self.eAnio.get() mes = self.eMes.get() dia = self.eDia.get() self.controlador.diaSiguiente(anio,mes,dia) def llamarDiasEnero(self): anio = self.eAnio.get() mes = self.eMes.get() dia = self.eDia.get() self.controlador.diasDesdePrimeroEnero(anio,mes,dia) def llamarPrimeroDeEnero(self): anio = self.eAnio.get() mes = self.eMes.get() dia = self.eDia.get() self.controlador.diaPrimeroDeEnero(anio) def __init__(self,app): self.controlador = CalendarController(self) self.app = app app.geometry("400x600") self.controlador.vista = self self.anio = StringVar() self.mes = StringVar() dia = StringVar() self.lTitulo = Label(app,text="CalendarioTec",font=("Times New Roman",24)) self.lTitulo.place(x=150,y=10) self.lOpcion = Label(app,text="Seleccione una opcion") self.lOpcion.place(x=150,y=50) self.bBiciesto = Button(app,text="Bisiesto",command=self.llamarBiciesto) self.bBiciesto.config(height=4, width=10) self.bBiciesto.place(x=30,y=90) self.bFechaValida = Button(app,text="Fecha valida",command=self.llamarValidarFecha) self.bFechaValida.config(height=4, width=10) self.bFechaValida.place(x=150,y=90) self.bDiaSiguiente = Button(app,text="Dia siguiente",command=self.llamarDiaSiguiente) self.bDiaSiguiente.config(height=4,width=10) self.bDiaSiguiente.place(x=280,y=90) self.bDiasEnero = Button(app,text="Dias desde\n 1ero de \nenero",command=self.llamarDiasEnero) self.bDiasEnero.config(height=4,width=10) self.bDiasEnero.place(x=30,y=200) self.bDiaPrimero = Button(app,text="Dia primero\n de\n enero",command=self.llamarPrimeroDeEnero) self.bDiaPrimero.config(height=3,width=10) self.bDiaPrimero.place(x=150,y=200) self.lAnio = Label(app,text="Anio").place(x=60,y=280) self.eAnio = Entry(app) self.eAnio.config(width=8) self.eAnio.place(x=30,y=300) self.lMes = Label(app,text="Mes").place(x=180,y=280) self.eMes = Entry(app) self.eMes.config(width=8) self.eMes.place(x=150,y=300) self.lDia = Label(app,text="Dia").place(x=300,y=280) self.eDia = Entry(app) self.eDia.config(width=8) self.eDia.place(x=280,y=300) self.lResultado = Label(app) self.lResultado.place(x=30,y=450) root = tkinter.Tk() myCalendar = CalendarApp(root) root.mainloop()
C
UTF-8
7,695
2.875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "LicenseRef-scancode-public-domain", "CC-BY-3.0", "X11", "Zlib" ]
permissive
/* * one.c * * Hey! This was the original file where freeglut development started. Just * note what I have written here at the time. And see the creation date :) * * : This is a wrapper. I still have to figure out * : how to build shared libraries under *nix :) * * Copyright (c) 1999 by Pawel W. Olszta * Written by Pawel W. Olszta, <olszta@sourceforge.net> * Creation date: czw gru 2 11:58:41 CET 1999 */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <stdio.h> #include <stdlib.h> #include <GL/freeglut.h> int g_LeaveGameMode = 0; int g_InGameMode = 1; /* * Call this function to have some text drawn at given coordinates */ void PrintText( int nX, int nY, char* pszText ) { int lines; char *p; /* * Prepare the OpenGL state */ glDisable( GL_LIGHTING ); glDisable( GL_DEPTH_TEST ); glMatrixMode( GL_PROJECTION ); glPushMatrix(); glLoadIdentity(); /* * Have an orthogonal projection matrix set */ glOrtho( 0, glutGet( GLUT_WINDOW_WIDTH ), 0, glutGet( GLUT_WINDOW_HEIGHT ), -1, +1 ); /* * Now the matrix mode */ glMatrixMode( GL_MODELVIEW ); glPushMatrix(); glLoadIdentity(); /* * Now the main text */ glColor3ub( 0, 0, 0 ); glRasterPos2i( nX, nY ); for( p=pszText, lines=0; *p; p++ ) { if( *p == '\n' ) { lines++; glRasterPos2i( nX, nY-(lines*18) ); } glutBitmapCharacter( GLUT_BITMAP_HELVETICA_18, *p ); } /* * Revert to the old matrix modes */ glMatrixMode( GL_PROJECTION ); glPopMatrix(); glMatrixMode( GL_MODELVIEW ); glPopMatrix(); /* * Restore the old OpenGL states */ glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); glEnable( GL_DEPTH_TEST ); glEnable( GL_LIGHTING ); } /* * This is the display routine for our sample FreeGLUT windows */ static float g_fTime = 0.0f; void SampleDisplay( void ) { /* * Clear the screen */ glClearColor( 0, 0.5, 1, 1 ); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); /* * Have the cube rotated */ glMatrixMode( GL_MODELVIEW ); glPushMatrix(); glRotatef( g_fTime, 0, 0, 1 ); glRotatef( g_fTime, 0, 1, 0 ); glRotatef( g_fTime, 1, 0, 0 ); /* * And then drawn... */ glColor3f( 1, 1, 0 ); /* glutWireCube( 20.0 ); */ glutWireTeapot( 20.0 ); /* glutWireSpher( 15.0, 15, 15 ); */ /* glColor3f( 0, 1, 0 ); */ /* glutWireCube( 30.0 ); */ /* glutSolidCone( 10, 20, 10, 2 ); */ /* * Don't forget about the model-view matrix */ glPopMatrix( ); /* * Draw a silly text */ if( g_InGameMode == 0 ) PrintText( 20, 20, "Hello there cruel world!" ); else PrintText( 20, 20, "Press ESC to leave the game mode!" ); /* * And swap this context's buffers */ glutSwapBuffers( ); } /* * This is a sample idle function */ void SampleIdle( void ) { g_fTime += 0.5f; if( g_LeaveGameMode == 1 ) { glutLeaveGameMode( ); g_LeaveGameMode = 0; g_InGameMode = 0; } } /* * The reshape function */ void SampleReshape( int nWidth, int nHeight ) { GLfloat fAspect = (GLfloat) nHeight / (GLfloat) nWidth; GLfloat fPos[ 4 ] = { 0.0f, 0.0f, 10.0f, 0.0f }; GLfloat fCol[ 4 ] = { 0.5f, 1.0f, 0.0f, 1.0f }; /* * Update the viewport first */ glViewport( 0, 0, nWidth, nHeight ); /* * Then the projection matrix */ glMatrixMode( GL_PROJECTION ); glLoadIdentity(); glFrustum( -1.0, 1.0, -fAspect, fAspect, 1.0, 80.0 ); /* * Move back the camera a bit */ glMatrixMode( GL_MODELVIEW ); glLoadIdentity( ); glTranslatef( 0.0, 0.0, -40.0f ); /* * Enable some features... */ glEnable( GL_CULL_FACE ); glEnable( GL_DEPTH_TEST ); glEnable( GL_NORMALIZE ); /* * Set up some lighting */ glLightfv( GL_LIGHT0, GL_POSITION, fPos ); glEnable( GL_LIGHTING ); glEnable( GL_LIGHT0 ); /* * Set up a sample material */ glMaterialfv( GL_FRONT, GL_AMBIENT_AND_DIFFUSE, fCol ); } /* * A sample keyboard callback */ void SampleKeyboard( unsigned char cChar, int nMouseX, int nMouseY ) { printf( "SampleKeyboard(): keypress '%c' at (%i,%i)\n", cChar, nMouseX, nMouseY ); } /* * A sample keyboard callback (for game mode window) */ void SampleGameModeKeyboard( unsigned char cChar, int nMouseX, int nMouseY ) { if( cChar == 27 ) g_LeaveGameMode = 1; } /* * A sample special callback */ void SampleSpecial( int nSpecial, int nMouseX, int nMouseY ) { printf( "SampleSpecial(): special keypress %i at (%i,%i)\n", nSpecial, nMouseX, nMouseY ); } /* * A sample menu callback */ void SampleMenu( int menuID ) { /* * Just print something funny */ printf( "SampleMenu() callback executed, menuID is %i\n", menuID ); } /* * The sample's entry point */ int main( int argc, char** argv ) { int menuID, subMenuA, subMenuB; glutInitDisplayString( "stencil~2 rgb double depth>=16 samples" ); glutInitDisplayMode( GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH ); glutInitWindowPosition( 100, 100 ); glutInit( &argc, argv ); subMenuA = glutCreateMenu( SampleMenu ); glutAddMenuEntry( "Sub menu A1 (01)", 1 ); glutAddMenuEntry( "Sub menu A2 (02)", 2 ); glutAddMenuEntry( "Sub menu A3 (03)", 3 ); subMenuB = glutCreateMenu( SampleMenu ); glutAddMenuEntry( "Sub menu B1 (04)", 4 ); glutAddMenuEntry( "Sub menu B2 (05)", 5 ); glutAddMenuEntry( "Sub menu B3 (06)", 6 ); glutAddSubMenu( "Going to sub menu A", subMenuA ); menuID = glutCreateMenu( SampleMenu ); glutAddMenuEntry( "Entry one", 1 ); glutAddMenuEntry( "Entry two", 2 ); glutAddMenuEntry( "Entry three", 3 ); glutAddMenuEntry( "Entry four", 4 ); glutAddMenuEntry( "Entry five", 5 ); glutAddSubMenu( "Enter sub menu A", subMenuA ); glutAddSubMenu( "Enter sub menu B", subMenuB ); glutCreateWindow( "Hello world!" ); glutDisplayFunc( SampleDisplay ); glutReshapeFunc( SampleReshape ); glutKeyboardFunc( SampleKeyboard ); glutSpecialFunc( SampleSpecial ); glutIdleFunc( SampleIdle ); glutAttachMenu( GLUT_LEFT_BUTTON ); glutInitWindowPosition( 200, 200 ); glutCreateWindow( "I am not Jan B." ); glutDisplayFunc( SampleDisplay ); glutReshapeFunc( SampleReshape ); glutKeyboardFunc( SampleKeyboard ); glutSpecialFunc( SampleSpecial ); glutIdleFunc( SampleIdle ); glutAttachMenu( GLUT_LEFT_BUTTON ); printf( "Testing game mode string parsing, don't panic!\n" ); glutGameModeString( "320x240:32@100" ); glutGameModeString( "640x480:16@72" ); glutGameModeString( "1024x768" ); glutGameModeString( ":32@120" ); glutGameModeString( "Toudi glupcze, Danwin bedzie moj!" ); glutGameModeString( "640x480:16@72" ); glutEnterGameMode(); glutDisplayFunc( SampleDisplay ); glutReshapeFunc( SampleReshape ); glutKeyboardFunc( SampleGameModeKeyboard ); glutIdleFunc( SampleIdle ); glutAttachMenu( GLUT_LEFT_BUTTON ); printf( "current window is %ix%i+%i+%i", glutGet( GLUT_WINDOW_X ), glutGet( GLUT_WINDOW_Y ), glutGet( GLUT_WINDOW_WIDTH ), glutGet( GLUT_WINDOW_HEIGHT ) ); /* * Enter the main FreeGLUT processing loop */ glutMainLoop(); printf( "glutMainLoop() termination works fine!\n" ); /* * This is never reached in FreeGLUT. Is that good? */ return EXIT_SUCCESS; } /*** END OF FILE ***/
C#
UTF-8
1,071
3.015625
3
[]
no_license
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DAL { public abstract class SerializationDA : IDataAccess { protected readonly string pathForFile; protected SerializationDA(string nameOfClassToSerialization) { pathForFile = GetPathForFile() + @"\" + nameOfClassToSerialization + ".dat"; } private string GetPathForFile() { string nameOfDirectory = @"\Data"; DirectoryInfo directoryInfo = null; string path = null; if (Directory.Exists(Directory.GetCurrentDirectory() + nameOfDirectory)) directoryInfo = Directory.CreateDirectory(Directory.GetCurrentDirectory() + nameOfDirectory); else path = Directory.GetCurrentDirectory() + nameOfDirectory; return path ?? directoryInfo.FullName; } public abstract object GetData(); public abstract void SetData(Object data); } }
C++
GB18030
3,127
3.328125
3
[]
no_license
#ifndef RBTREE_H #define RBTREE_H #include"RBNode.h" #include<vector> template<typename T> class RBTree { public: RBTree(); ~RBTree(); bool leftRotate(RBNode *node); bool rightRotate(RBNode *node); void RBInsert(const T &key); void RBInsertFixUp(RBNode *node); bool isEmpty() const; private: RBNode<T> *root; RBNode<T> *copyRoot; std::vector<RBNode<T>*> RBVec; }; template<typename T> RBTree<T>::RBTree() :root(nullptr), copyRoot(nullptr) { } template<typename T> RBTree<T>::~RBTree() { for (auto &c : RBVec) { delete c; c = nullptr; } if (copyRoot) { delete copyRoot; copyRoot = nullptr; } root = nullptr; } template<typename T> bool RBTree<T>::isEmpty() const { return root == nullptr; } template<typename T> bool RBTree<T>::leftRotate(RBNode<T> *node) { if (!node->right) { std::cout << "תڵкǿյġ" << < std::endl; return false; } RBNode<T> *rightNode = node->right; node->right = rightNode->left; if (rightNode->left) rightNode->left->parent = node; rightNode->parent = node->parent; if (!node->parent) root = rightNode; else if (node == node->parent->left) node->parent->left = rightNode; else node->parent->right = rightNode; rightNode->left = node; node->parent = rightNode; return true; } template<typename T> bool RBTree<T>::rightRotate(RBNode<T> *node) { if (!node->left) { std::cout << "ǿյġ" << std::endl; return false; } RBNode<T> *leftNode = node->left; node->left = leftNode->right; if (leftNode->right) leftNode->right->parent = node; leftNode->parent = node->parent; if (!node->parent) root = leftNode; else if (node == node->parent->left) node->parent->left = leftNode; else node->parent->right = leftNode; leftNode->right = node; node->parent = leftNode; return true; } template<typename T> void RBTree<T>::RBInsert(const T &key) { if (isEmpty()) { root = new RBNode<T>(false,key); copyRoot = root; std::cout << "root->key-----> "<<root->key << std::endl; } else { RBNode<T> *preNode = root; RBNode<T> *nextNode = nullptr; RBNode<T> *curNode = new RBNode<T>(false, key); RBVec.push_back(curNode); while (preNode) { nextNode = preNode; if (key < preNode->key) { preNode = preNode->left; } else { preNode = preNode->right; } } if (key < nextNode->key) { nextNode->left = curNode; } else { nextNode->right = curNode; } curNode->parent=nextNode; } } template<typename T> void RBTree<T>::RBInsertFixUp(RBNode<T> *node) { while (node->parent->color) { if (node->parent == node->parent->parent->left) { RBNode<T> *yNode = node->parent->parent->right; if (yNode->color) { node->parent->color = false; yNode->color = false; node->parent->parent->color = true; node = node->parent->parent; } else if (node == node->parent->right) { node = node->parent; leftRotate(node); node->parent->color = false; node->parent->parent->color = true; rightRotate(node->parent->parent); } } } } #endif
Markdown
UTF-8
935
3.34375
3
[]
no_license
### 响应 `frog` 并不像传统的控制器类框架那样,要业务逻辑调用 `res.*`之类的方法来返回结果。 `frog`要求 **handler** 导出一个 `async function`, 如: ```javascript module.exports = async (Event) => { let model = EventModel.create(Event); let saved = await model.save(true); if (saved === true) { return model; } return error.INTERNAL_ERROR.withMessage('写入数据错误'); }; ``` 业务逻辑并不感知到`response`, 只需要像一个普通函数一样,**return**它的结果就行, `frog`底层会自动处理这个返回值。 > 关于 frog 的 error 会在后面的章节讲解。 这样设计的好处是, 如果我需要测试我的 **handler**, 我只需要照着参数(例子里的Event)的结构定义去mock, 然后检查这个`async function`的值,就像测试一个普通的**function**一样。 而不需要引入整个 **http** 实现。
Markdown
UTF-8
637
2.71875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# How to contribute Thanks for considering to contribute to JSON Patch for PHP. Please follow these guidelines: - You must follow the PSR-2 coding standard. More info [here](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md). With these tweaks: - Always use spaces. - Ensure the coding standard compliance before committing or opening pull requests by running `php-cs-fixer fix .` or `composer cs-fix` in the root directory of this repository. - You must use [feature / topic branches](https://git-scm.com/book/en/v2/Git-Branching-Branching-Workflows) to ease the merge of contributions.
Python
UTF-8
1,108
3.375
3
[]
no_license
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode: if root is None: return None queue = deque() queue.append(root) parent = collections.defaultdict(list) while(queue): n = len(queue) curr_level = [] while(n): curr_node = queue.popleft() if curr_node.left: queue.append(curr_node.left) parent[curr_node.left] = curr_node if curr_node.right: queue.append(curr_node.right) parent[curr_node.right] = curr_node curr_level.append(curr_node) n -= 1 while(len(curr_level) > 1): s = set() for node in curr_level: s.add(parent[node]) curr_level = list(s) return curr_level[0]
Java
UTF-8
859
3.65625
4
[ "MIT" ]
permissive
class Example01 { Example01(){} public void printDownToUp() { for (int r=0; r<5; r++) { for (int c=0; c<r+1; c++) System.out.printf("*"); System.out.println(); } } public void printUptoDown() { for (int r=0; r<5; r++) { for (int c=4; c>=r; c--) System.out.printf("*"); System.out.println(); } } } class Book { String name, Author; int price; public Book(String name, String author, int price) { this.name= name; this.Author= author; this.price= price; } } public class java15 { public static void main(String[] args) { System.out.println("============================"); Example01 ex01= new Example01(); ex01.printDownToUp(); ex01.printUptoDown(); } }
Python
UTF-8
1,103
2.953125
3
[]
no_license
#!python3 #!从 www.xkcd.com 连续下载图片 import requests,os,bs4 url='http://xkcd.com' os.makedirs('xkcd',exist_ok=True) print('current work directory:') cwd=os.getcwd() print(cwd) while not url.endswith('#'): #下载网页 print('Downloading page %s...' %url) res=requests.get(url) res.raise_for_status() soup=bs4.BeautifulSoup(res.text,"html.parser") #找到图片所在的元素 #匹配图片的选择器? comicElem=soup.select('#comic img') if comicElem==[]: print('could not find comic image.') else: comicUrl='https:'+ comicElem[0].get('src') #下载图片 print('Downloading image %s...' % (comicUrl)) res=requests.get(comicUrl) res.raise_for_status() #将图片保存到./xkcd目录下 imageFile=open(os.path.join('xkcd',os.path.basename(comicUrl)),'wb') for chunk in res.iter_content(100000): imageFile.write(chunk) imageFile.close() #获取"下一张"按钮 prevLink=soup.select('a[rel="prev"]')[0] url='http://xkcd.com'+prevLink.get('href') print('Done')
Markdown
UTF-8
661
3.203125
3
[]
no_license
# Data Types <img src="../images/DataTypes.png" width="400"> ## Nominal Variables Intrinsic order of the labels: - Country of birth (Argentina, England, Germany) - Postcode - Vehicle make (Citroen, Peugeot, ...) ## Ordinal Variables Can be meaningfully ordered are called ordinal: - Student's grade in an exam (A, B, C or Fail) - Days of the week (Monday = 1 and Sunday = 7) ## Mixed Variables - Observations show either numbers or categories among their values - Number of credit accounts (1-100, U, T, M) U = unknown, T = unverified, M = unmatched) - Observations show both numbers and categories in their values - Cabin (Titanic) (A15, B18, ...)
Java
UTF-8
2,082
1.960938
2
[]
no_license
package com.lifeSharing.pojo; public class StoryReply { private String replyCode; private String commentsCode; private String replyToId; private String replyContext; private String replierNo; private String replierName; private String replyType; private String toId; private String toName; public String getReplyCode() { return replyCode; } public void setReplyCode(String replyCode) { this.replyCode = replyCode == null ? null : replyCode.trim(); } public String getCommentsCode() { return commentsCode; } public void setCommentsCode(String commentsCode) { this.commentsCode = commentsCode == null ? null : commentsCode.trim(); } public String getReplyToId() { return replyToId; } public void setReplyToId(String replyToId) { this.replyToId = replyToId == null ? null : replyToId.trim(); } public String getReplyContext() { return replyContext; } public void setReplyContext(String replyContext) { this.replyContext = replyContext == null ? null : replyContext.trim(); } public String getReplierNo() { return replierNo; } public void setReplierNo(String replierNo) { this.replierNo = replierNo == null ? null : replierNo.trim(); } public String getReplierName() { return replierName; } public void setReplierName(String replierName) { this.replierName = replierName == null ? null : replierName.trim(); } public String getReplyType() { return replyType; } public void setReplyType(String replyType) { this.replyType = replyType == null ? null : replyType.trim(); } public String getToId() { return toId; } public void setToId(String toId) { this.toId = toId == null ? null : toId.trim(); } public String getToName() { return toName; } public void setToName(String toName) { this.toName = toName == null ? null : toName.trim(); } }
JavaScript
UTF-8
5,072
2.828125
3
[]
no_license
// Invocar modo JavaScript 'strict' 'use strict'; // Cargar las dependencias del módulo var mongoose = require('mongoose'), Factura = mongoose.model('Factura'), Counters = mongoose.model('Counters'); // Crear un nuevo método controller para el manejo de errores var getErrorMessage = function(err) { if (err.errors) { for (var errName in err.errors) { if (err.errors[errName].message) return err.errors[errName].message; } } else { return 'Error de servidor desconocido'; } }; // Crear un nuevo método controller para crear nuevos facturas exports.create = function(req, res, next) { // Crear un nuevo objeto factura var factura = new Factura(req.body); // asignar el Schema.ObjectIdcorrespondiente, ya que req.body.tipoPago contiene solo el nombre del tipo de pago de la factura factura.tipoPago = req.tipoPago; factura.estado = 'Espera'; factura.idFacturaInterno = req.idFacturaInterno; // Intentar salvar el factura factura.save(function(err) { if (err) { // Si ocurre algún error enviar el mensaje de error return res.status(400).send({ message: getErrorMessage(err) }); } else { req.factura = factura; next(); // Enviar una representación JSON del factura // res.json(factura); } }); }; // Crear un nuevo método controller que recupera una lista de facturas exports.list = function(req, res) { // Usar el método model 'find' para obtener una lista de facturas Factura.find({}, function(err, facturas){ if(err){ // Si un error ocurre enviar un mensaje de error return res.status(400).send({ message: getErrorMessage(err) }); }else{ // usar objeto response (res) para enviar una respuesta JSON res.json(facturas); } }); }; // Crear un nuevo método controller que recupera una lista de facturas exports.listByTipoPago = function(req, res) { // Usar el método model 'find' para obtener una lista de facturas Factura.find({tipoPago: req.tipoPago}, function(err, facturas){ if(err){ // Si un error ocurre enviar un mensaje de error return res.status(400).send({ message: getErrorMessage(err) }); }else{ // usar objeto response (res) para enviar una respuesta JSON res.json(facturas); } }); }; // Crear un nuevo método controller que recupera una lista de facturas exports.listByTipoPago_estado = function(req, res) { // Usar el método model 'find' para obtener una lista de facturas Factura.find({tipoPago: req.tipoPago, estado: req.estado}, function(err, facturas){ if(err){ // Si un error ocurre enviar un mensaje de error return res.status(400).send({ message: getErrorMessage(err) }); }else{ // usar objeto response (res) para enviar una respuesta JSON res.json(facturas); } }); }; // Crear un nuevo método controller que devuelve un factura existente exports.read = function(req, res) { res.json(req.factura); }; // Crear un nuevo método controller que actualiza un factura existente exports.update = function(req, res) { // Obtener el factura usando el objeto 'request' var factura = req.factura; // Actualizar los campos factura factura.codigoPago = req.body.codigoPago; factura.estado = req.body.estado; factura.monto = req.body.monto; factura.tipoPago = req.body.tipoPago; factura.glosa = req.body.glosa; factura.condicionesPago = req.body.condicionesPago; // Intentar salvar el factura actualizado factura.save(function(err) { if (err) { // si ocurre un error enviar el mensaje de error return res.status(400).send({ message: getErrorMessage(err) }); } else { // Enviar una representación JSON del factura res.json(factura); } }); }; // método controller que borre un factura existente exports.delete = function(req, res) { // Obtener el factura usando el objeto 'request' var factura = req.factura; // Usar el método model 'remove' para borrar el factura factura.remove(function(err) { if (err) { // Si ocurre un error enviar el mensaje de error return res.status(400).send({ message: getErrorMessage(err) }); } else { // Enviar una representación JSON del factura res.json(factura); } }); }; // middleware para obtener un documento por su id // usado en las funciones read, update y delete exports.facturaByID = function(req, res, next, id){ Factura.findOne({ _id: id }, function(err, factura){ if (err) return next(err); if (!factura) return next(new Error('Fallo al cargar el factura ' + id)); // Si un factura es encontrado usar el objeto 'request' para pasarlo al siguietne middleware req.factura = factura; // Llamar al siguiente middleware next(); }); }; exports.getIdFacturaInterno = function(req, res, next){ Counters.findOneAndUpdate( { _id: 'idFacturaInterno' }, { $inc: { seq: 1 } }, function(err, counter){ if (err) return next(err); if (!counter) return next(new Error('Fallo al cargar el counter ' + id)); // Si un factura es encontrado usar el objeto 'request' para pasarlo al siguietne middleware req.idFacturaInterno = counter.seq; next(); } ); };
Ruby
UTF-8
406
3.421875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Don't forget! This file needs to be 'required' in its spec file # See README.md for instructions on how to do this def fizzbuzz(integer) if integer/15 == integer/15.0 answer = "FizzBuzz" else if integer/3 == integer/3.0 answer = "Fizz" else if integer/5 == integer/5.0 answer = "Buzz" end # if 5 end # if 3 end # if 15 end #Def
C
UTF-8
318
3.671875
4
[]
no_license
#include <stdio.h> void main () { int a, b, c, min, max; printf ("Enter two numbers\n"); scanf ("%d%d", &a, &b); max = (a > b) ? a : b; min = (a < b) ? a : b; while (min > 0) { c = min; min = max % min; max = c; } printf ("HCF of %d and %d is %d\n", a, b, c); }
Java
UTF-8
1,329
2.859375
3
[]
no_license
package Factory.Products; import Factory.Food.Food; import Factory.Ingredients.*; /** * Created by FAB3659 on 2017-07-04. */ public abstract class Pizza extends Food { private Cheese cheese; private Doe doe; private Meat meat; private SeaFood seaFood; private Vegetable[] vegetables; public Cheese getCheese() { return cheese; } public void setCheese(Cheese cheese) { this.cheese = cheese; } public Doe getDoe() { return doe; } public void setDoe(Doe doe) { this.doe = doe; } public Meat getMeat() { return meat; } public void setMeat(Meat meat) { this.meat = meat; } public SeaFood getSeaFood() { return seaFood; } public void setSeaFood(SeaFood seaFood) { this.seaFood = seaFood; } public Vegetable[] getVegetables() { return vegetables; } public void setVegetables(Vegetable[] vegetables) { this.vegetables = vegetables; } public void bake() { System.out.println("Baking..."); } public void cut() { System.out.println("Cutting..."); } public void pack() { System.out.println("Packing..."); } public void deliver() { System.out.println("Delivering Pizza..."); } }
C#
UTF-8
4,474
3
3
[]
no_license
using PinsGenerator.Repository; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace PinsGenerator { public partial class MainForm : Form { private readonly PinsRepository _pinRepo; public MainForm(PinsRepository pinRepo) { this._pinRepo = pinRepo; InitializeComponent(); } private void generatePin_Click(object sender, EventArgs e) { var isOutputLabelVisible = this.outputLabel.Visible; var isPinOutputVisible = this.pinOutput.Visible; if (isOutputLabelVisible && isPinOutputVisible) { this.outputLabel.Visible = false; this.pinOutput.Visible = false; } string strRandomPin = this.generatePinString(); while (this._pinRepo.findPin(strRandomPin)) { strRandomPin = this.generatePinString(); } if (!this._pinRepo.findPin(strRandomPin)) { this._pinRepo.insertPin(strRandomPin); this.pinOutput.Text = strRandomPin; this.outputLabel.Visible = true; this.pinOutput.Visible = true; } // if we run out of all possible combinations all user to restart the program. // 10 x 10 x 10 x 10 = 10 000 and minus obvious numbers such as 1111, 2222 and so on, // thus 9990 possible combinations. // If we want to increase the complexity of the pin we can change the condition in the // validateAndReturnNumbers() to (duplicates > 1), that would prevent numbers like 1112, 2221 and so on.. // then we need to change 9990 to 9830 ReadOnlyCollection<string> allPins = this._pinRepo.GetAllPins(); if (allPins.Count == 9990) { this.pinOutput.Text = string.Format("We run out of possible combinations.\n Number of pins:{0}.\n Click restart program.", allPins.Count.ToString()); this.restartProgram.Visible = true; this.generatePinBtn.Visible = false; } } private string generatePinString() { var randomNumbers = this.validateAndReturnNumbers(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < randomNumbers.Length; i++) { sb.Append(randomNumbers[i].ToString()); } return sb.ToString(); } private int[] validateAndReturnNumbers() { int[] generatedNumbers = this.generateRandomNumbers(); int duplicates = checkForDuplicates(generatedNumbers); while (duplicates == 3) { generatedNumbers = this.generateRandomNumbers(); duplicates = checkForDuplicates(generatedNumbers); } return generatedNumbers; } private int[] generateRandomNumbers() { Random random = new Random(); int randomOne = random.Next(9); int randomTwo = random.Next(9); int randomThree = random.Next(9); int randomFour = random.Next(9); int[] numbersArr = new int[4] { randomOne, randomTwo, randomThree, randomFour }; return numbersArr; } private int checkForDuplicates(int[] generatedNumbers) { int duplicates = 0; for (int i = 0; i < generatedNumbers.Length; i++) { for (int j = i + 1; j < generatedNumbers.Length; j++) { if (generatedNumbers[i] == generatedNumbers[j]) { duplicates++; break; } } } return duplicates; } private void restartBtn_Clicked(object sender, EventArgs e) { this._pinRepo.dropTable(); this.restartProgram.Visible = false; this.outputLabel.Visible = false; this.pinOutput.Visible = false; this.generatePinBtn.Visible = true; this._pinRepo.createTable(); } } }
C#
UTF-8
4,995
3.234375
3
[ "MIT" ]
permissive
using System; namespace StereoKit { /// <summary>A Sprite is an image that's set up for direct 2D rendering, without using /// a mesh or model! This is technically a wrapper over a texture, but it also includes /// atlasing functionality, which can be pretty important to performance! This is used /// a lot in UI, for image rendering. /// /// Atlasing is not currently implemented, it'll swap to Single for now. But here's how it /// works! /// /// StereoKit will batch your sprites into an atlas if you ask it to! This puts all the /// images on a single texture to significantly reduce draw calls when many images are /// present. Any time you add a sprite to an atlas, it'll be marked as dirty and rebuilt /// at the end of the frame. So it can be a good idea to add all your images to the atlas on /// initialize rather than during execution! /// /// Since rendering is atlas based, you also have only one material per atlas. So this is /// why you might wish to put a sprite in one atlas or another, so you can apply different</summary> public class Sprite { internal IntPtr _inst; /// <summary>The aspect ratio of the sprite! This is width/height. You may also /// be interested in the NormalizedDimensions property, which are normalized to /// the 0-1 range.</summary> public float Aspect => NativeAPI.sprite_get_aspect(_inst); /// <summary>Width of the sprite, in pixels.</summary> public int Width => NativeAPI.sprite_get_width(_inst); /// <summary>Height of the sprite, in pixels.</summary> public int Height => NativeAPI.sprite_get_height(_inst); /// <summary>Width and height of the sprite, normalized so the maximum value is 1.</summary> public Vec2 NormalizedDimensions => NativeAPI.sprite_get_dimensions_normalized(_inst); internal Sprite(IntPtr inst) { _inst = inst; if (_inst == IntPtr.Zero) Log.Err("Received an empty sprite!"); } ~Sprite() { if (_inst != IntPtr.Zero) NativeAPI.sprite_release(_inst); } /// <summary>Draw the sprite on a quad with the provided transform!</summary> /// <param name="transform">A Matrix describing a transform from model space to world space.</param> /// <param name="color">Per-instance color data for this render item.</param> public void Draw(in Matrix transform, Color32 color) { NativeAPI.sprite_draw(_inst, transform, color); } /// <summary>Create a sprite from an image file! This loads a Texture from file, and then /// uses that Texture as the source for the Sprite.</summary> /// <param name="file">The filename of the image, an absolute filename, or a filename relative /// to the assets folder. Supports jpg, png, tga, bmp, psd, gif, hdr, pic.</param> /// <param name="type">Should this sprite be atlased, or an individual image? Adding this as /// an atlased image is better for performance, but will cause the atlas to be rebuilt! Images /// that take up too much space on the atlas, or might be loaded or unloaded during runtime may /// be better as Single rather than Atlased!</param> /// <param name="atlasId">The name of which atlas the sprite should belong to, this is only /// relevant if the SpriteType is Atlased.</param> /// <returns>A Sprite asset, or null if the image failed to load!</returns> public static Sprite FromFile(string file, SpriteType type = SpriteType.Atlased, string atlasId = "default") { IntPtr inst = NativeAPI.sprite_create_file(file, type, atlasId); return inst == IntPtr.Zero ? null : new Sprite(inst); } /// <summary>Create a sprite from a Texture object!</summary> /// <param name="image">The texture to build a sprite from. Must be a valid, 2D image!</param> /// <param name="type">Should this sprite be atlased, or an individual image? Adding this as /// an atlased image is better for performance, but will cause the atlas to be rebuilt! Images /// that take up too much space on the atlas, or might be loaded or unloaded during runtime may /// be better as Single rather than Atlased!</param> /// <param name="atlasId">The name of which atlas the sprite should belong to, this is only /// relevant if the SpriteType is Atlased.</param> /// <returns>A Sprite asset, or null if the image failed when adding to the sprite system!</returns> public static Sprite FromTex(Tex image, SpriteType type = SpriteType.Atlased, string atlasId = "default") { IntPtr inst = NativeAPI.sprite_create(image._inst, type, atlasId); return inst == IntPtr.Zero ? null : new Sprite(inst); } } }