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,528
3.578125
4
[]
no_license
from StrukturePodataka.Skup import * class TrieNode(): def __init__(self, char): self.char = char # karakter u cvoru self.children = {} # pokazivac na decu u cvoru self.endOfWord = False # oznaka kraja reci self.stranice = Skup() # polje koje ima Skup stranica koje sadrze odredjenu rec i cuva broj ponavljanja date reci (file,broj_ponavljanja) class Trie(): def __init__(self): self.root = TrieNode("*") # inicijalizacija head-a def add_word(self, word,file): curr_node = self.root for char in word: if char not in curr_node.children: curr_node.children[char] = TrieNode(char) curr_node = curr_node.children[char] curr_node.endOfWord = True curr_node.stranice.add(file, 1) # ako stavi true da se rec zavrsila nju unosi u skup stranica, ako vec postoji u skupu kljuc file # onda ce u Skupu samo inkrementirati da se drugi put pojavila rec u datom fajlu! def search(self, word): """if word == "": # proveriti return "False",0, None""" curr_node = self.root for char in word: if char not in curr_node.children: return "False",None curr_node = curr_node.children[char] return str(curr_node.endOfWord), curr_node.stranice def __bool__(self): # vraca podatak da li postoji neki unos u Trie ili ne return bool(self.root.char != "*" or self.root.children)
Markdown
UTF-8
365
2.5625
3
[]
no_license
# Mobile App Recommendation An app created using ReactJS. Used to recommend mobile apps. Features: - Recommends Mobile apps based on different categories. View App: [Mobile App Recommendation](https://lo2bu.csb.app/) ## Technologies and Frameworks: - ReactJS - HTML - CSS - CodeSandBox <h3>Preview: </h3> ![image](/src/images/Mobile_Apps_Recommendation.PNG)
Markdown
UTF-8
1,083
2.765625
3
[ "CC-BY-4.0", "MIT" ]
permissive
### <a name="prerequisites"></a>Pré-requisitos * Um [RSS](https://wikipedia.org/wiki/RSS) conta Antes de poder utilizar a conta RSS numa aplicação lógica, tem de autorizar a aplicação lógica para ligar à sua conta RSS. Felizmente, pode fazê-facilmente na sua aplicação lógica no Portal do Azure. Eis os passos para autorizar a aplicação lógica para ligar à sua conta do RSS: 1. Para criar uma ligação para RSS, no designer de aplicação lógica, selecione **Mostrar Microsoft APIs geridas** na lista pendente, em seguida, introduza *RSS* na caixa de pesquisa. Selecione o acionador ou ação que irá gostar a utilizar: ![Passo de criação de ligação de RSS](./media/connectors-create-api-rss/rss-1.png) 2. Selecione **criar ligação** : ![Passo de criação de ligação de RSS](./media/connectors-create-api-rss/rss-2.png) 3. Repare a ligação foi criada e está agora livre para continuar com os outros passos da sua aplicação lógica: ![Passo de criação de ligação de RSS](./media/connectors-create-api-rss/rss-3.png)
PHP
UTF-8
329
2.515625
3
[]
no_license
<?php /** * Classe de ligação com o bando do Pé Na Estrada. */ class DB { public function __construct() { pg_connect("host=localhost user=postgres password=senha5 dbname=penaestrada port=5432") or die("Erro ao conectar com o servidor."); } public function __destruct() { //pg_close(); } } ?>
Python
UTF-8
182
3.0625
3
[]
no_license
def add2(n1,n2): s=n1+n2 return s def add3(n1,n2,n3): s=n1+n2+n3 return s def add4(n1,n2,n3,n4): s=n1+n2+n3+n4 return s print add2(3,4) print add3(1,2,3) print add4(1,2,3,4)
Python
UTF-8
434
3.234375
3
[]
no_license
from data import question_data from question_model import Question from quiz_brain import QuizBrain question_bank = [] for i in question_data: q = Question(i["text"], i["answer"]) question_bank.append(q) score = 0 qb = QuizBrain(question_bank) while qb.still_has_questions(): qb.next_question() print("\n") print("Congratulations on finishing the quiz !") print(f"Your final score was: {qb.score}/{qb.question_number}")
Java
UTF-8
502
3.6875
4
[]
no_license
//Time complexity : O(logn) class Solution { public double myPow(double x, int n) { //base if( n == 0) return 1; double temp = myPow(x, n/2); if(n % 2 == 0){ // when the power to the number is even return temp*temp; }else{ if( n < 0){ // case when power is negative return (temp * temp) * 1/x; }else{ return (temp * temp) * x; // pwer is +ve and n is odd } } } }
Python
UTF-8
5,441
2.890625
3
[]
no_license
#!/usr/bin/env python import sys import os import getopt from Bio.SeqIO.QualityIO import FastqGeneralIterator OPT_INPUT_FILE="" OPT_OUTPUT_FILE=False OPT_MIN_LENGTH=0 OPT_MAX_LENGTH=False def Usage(): print "\nFastQ_ReadFilterByLength.py is a program that read a FASTQ file and filter the sequences according to their length. \n" print "Usage:" print "\tFastQ_ReadFilterByLength.py -i [FASTQ file]\n" print "\nMandatory options:" print "\t-i, --input=FILE" print "\t\tThe input FASTQ file to be filtered." print "\nOther options:" print "\t-h, --help" print "\t\tShow the options of the program." print "\t-m, --minimum=THRESHOLD" print "\t\tThis option set the minimum length that all sequences must have. By default is 0." print "\t-M, --maximum=THRESHOLD" print "\t\tThis option set the maximum length that all sequences must have. By default is not defined which means that the is not an upper length limit." print "\t-o, --output=FILE" print "\t\tWrite the output to the given file in FASTQ format. By default this option is not set and the ouput is written to the STDOUT." print "\n" sys.exit(1) # Function that read and parse the command line arguments. def SetOptions(argv): if len(argv) == 0: Usage() options, remaining = getopt.getopt(argv, 'i:m:M:o:h', ['input=','minimum=','maximum=','output=','help']) opt_flag = {'i': False, 'm':False, 'M':False, 'o':False} global OPT_INPUT_FILE, OPT_OUTPUT_FILE, OPT_MIN_LENGTH, OPT_MAX_LENGTH for opt, argu in options: if opt in ('-i', '--input'): if not opt_flag['i']: if os.path.exists(argu): OPT_INPUT_FILE = argu opt_flag['i'] = True else: print >> sys.stderr , "\n[ERROR]: File or path of the input file does not exist. ", argu, "\n" sys.exit(1) else: print >> sys.stderr , "\n[ERROR]: Trying to redefine the input file. Option -i / --input was already set.\n" sys.exit(1) elif opt in ('-o', '--output'): if not opt_flag['o']: if not os.path.dirname(argu): # Empty path means the current directory. OPT_OUTPUT_FILE = argu opt_flag['o'] = True else: if os.path.exists(os.path.dirname(argu)): OPT_OUTPUT_FILE = argu opt_flag['o'] = True else: print >> sys.stderr , "\n[ERROR]: Path to write the output does not exist. ", os.path.dirname(argu), "\n" sys.exit(1) else: print >> sys.stderr , "\n[ERROR]: Trying to redefine the output file. Option -o / --output was already set.\n" sys.exit(1) elif opt in ('-h', '--help'): Usage() elif opt in ('-m', '--minimum'): if not opt_flag['m']: OPT_MIN_LENGTH = int(argu) opt_flag['m'] = True if OPT_MIN_LENGTH < 0: print >> sys.stderr , "\n[ERROR]: The minimum sequence length must be an integer greater or equal than 0. See option -m / --minimum.\n" sys.exit(1) else: print >> sys.stderr , "\n[ERROR]: Trying to redefine the minimum sequence length. Option -m / --minimum was already set.\n" sys.exit(1) elif opt in ('-M', '--maximum'): if not opt_flag['M']: OPT_MAX_LENGTH = int(argu) opt_flag['M'] = True if OPT_MAX_LENGTH < 0: print >> sys.stderr , "\n[ERROR]: The maximum sequence length must be an integer greater or equal than 0. See option -M / --maximum.\n" sys.exit(1) else: print >> sys.stderr , "\n[ERROR]: Trying to redefine the maximum sequence length. Option -M / --maximum was already set.\n" sys.exit(1) if not opt_flag['i']: print >> sys.stderr , "\n[ERROR]: Input file not defined. Option -i / --input.\n" sys.exit(1) if opt_flag['M'] and (OPT_MAX_LENGTH < OPT_MIN_LENGTH): print >> sys.stderr , "\n[ERROR]: The threshold for the maximum sequence length must be greater or equal than the threshold for the minimum sequence length. (max >= min): "+str(OPT_MAX_LENGTH)+" >= "+str(OPT_MIN_LENGTH)+"\n" sys.exit(1) # Parse command line SetOptions(sys.argv[1:]) # Setting the output if OPT_OUTPUT_FILE: OPT_OUTPUT_FILE=open(OPT_OUTPUT_FILE,"w") else: OPT_OUTPUT_FILE=sys.stdout # The option -M / --maximum was not set if not OPT_MAX_LENGTH: for read in FastqGeneralIterator(open(OPT_INPUT_FILE)): # Reading the FASTQ. if len(read[1]) >= OPT_MIN_LENGTH: print >> OPT_OUTPUT_FILE , "@"+read[0] print >> OPT_OUTPUT_FILE , read[1] print >> OPT_OUTPUT_FILE , "+" print >> OPT_OUTPUT_FILE , read[2] else: for read in FastqGeneralIterator(open(OPT_INPUT_FILE)): # Reading the FASTQ. if (len(read[1]) >= OPT_MIN_LENGTH) and (len(read[1]) <= OPT_MAX_LENGTH): print >> OPT_OUTPUT_FILE , "@"+read[0] print >> OPT_OUTPUT_FILE , read[1] print >> OPT_OUTPUT_FILE , "+" print >> OPT_OUTPUT_FILE , read[2]
Markdown
UTF-8
1,148
3.890625
4
[]
no_license
**函數** **內容 :** 傳回值型態 函數名稱(型態 參數1, 型態 參數2, \....) { // 變數宣告 // 程式碼 return 傳回值; } 其中 return 語法的功能是讓函數把一個值傳回給呼叫它的程式,也就是說如果函數執行到這一行,後面的程式碼就不會再執行了。 ![](./img/media/image1.png) 上例我們自訂了一個函式f1,並傳入一個參數a給n,f1計算後傳回return n\*9/5+32; 請仿照上例,寫一個BMI計算程式。 身高體重指數(又稱身體質量指數,英文為Body Mass Index,簡稱BMI)是一個計算值,主要用於統計用途。 「身高體重指數」這個概念,是由19世紀中期的比利時通才凱特勒(Lambert Adolphe Jacques Quetelet)最先提出。它的定義如下: ![](./img/media/image2.png) w = 體重,單位:千克; h = 身高,單位:米; BMI = 身高體重指數,單位:千克/平方米 **輸入說明 :** 男性的身高及體重 **輸出說明 :** BMI數值 **範例輸入 :**![help](./img/media/image3.png) 60 1.55 73 1.62 **範例輸出 :** 24.974 27.8159 ![](./img/media/image4.png)
JavaScript
UTF-8
807
2.515625
3
[]
no_license
app.controller('ordersCtrl', function($scope, $location, restSrv, authSrv){ if (!authSrv.isAutorized()){ $location.path('/auth'); return; } restSrv.getOrders().then( function(response) { if (response.data && response.data.success) { $scope.orders = response.data.data; } }, function(response) { if (response.data && !response.data.success) { if (response.data.error == "There are no orders!") $scope.orders = []; else alert("Что-то пошло не так, попробуйте еще раз!"); } } ); $scope.pageSize = 10; $scope.currentPage = 1; $scope.numberOfPages = function(){ return new Array(Math.ceil($scope.orders.length/$scope.pageSize)); }; $scope.setPage = function(page) { $scope.currentPage = page; }; });
Java
UTF-8
22,904
2.359375
2
[]
no_license
package Util; import android.content.Context; import android.content.SharedPreferences; import org.jsoup.Connection; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.Map; import Database.DB; import Model.CourseModel; import Model.GradeModel; //网络请求类 public class HttpUtil { //主页面网址 private final static String url_index = "http://jw1.wucc.cn:2222/default2.aspx"; //验证码网址 private final static String url_checkcode = "http://jw1.wucc.cn/CheckCode.aspx"; //存放cookie private static Map<String, String> cookies = null; //存放viewstate private static String viewstate = null; //学生学号 private static String xsxh; //学生姓名 private static String xsxm; private static HttpUtil httpUtil; private static Thread connection, getCourseThread, downGradeViewstateThread, getGradeThread, getGradeViewstateThread; private static Context context; private static String TAG = "HttpUtil"; //私有构造函数 private HttpUtil() { } //获得HttpUtil实例 private static HttpUtil getInstance() { if (httpUtil == null) { synchronized (HttpUtil.class) { if (httpUtil == null) { httpUtil = new HttpUtil(); } } } return httpUtil; } //获得连接,并保存cookie和viewstate在内存中 private void _getConnection(Utility.GetConnectionCallBack callback) { try { Connection conn = Jsoup.connect(url_index) .timeout(20000) .method(Connection.Method.GET); Connection.Response response = conn.execute(); if (response.statusCode() == 200) { cookies = response.cookies(); LogUtil.d(TAG, "cookies = " + cookies.toString()); } else { callback.connectionError(); } Document document = Jsoup.parse(response.body()); viewstate = document.select("input").first().attr("value"); LogUtil.d(TAG, "viewstate = " + viewstate); } catch (IOException e) { e.printStackTrace(); } } //下载验证码并调用回调函数。若成功,则显示验证码,否则提示错误 private void _getCheckcode(final Utility.GetCheckcodeCallBack callback) { try { Connection.Response resultImageResponse = Jsoup.connect(url_checkcode) .cookies(cookies) .ignoreContentType(true) .execute(); File file = new File(context.getFilesDir(), "checkcode.png"); LogUtil.d(TAG, "验证码储存路径: " + context.getFilesDir()); FileOutputStream fos = new FileOutputStream(file); fos.write(resultImageResponse.bodyAsBytes()); fos.flush(); fos.close(); callback.doSuccess(); } catch (Exception e) { callback.doError(); e.printStackTrace(); } } //post发送数据登录,并储存学生的姓名、学号 private void _login(final Map<String, String> data, final Utility.LoginCallBack callback) { data.put("__VIEWSTATE", viewstate); data.put("RadioButtonList1", "学生"); data.put("Button1", ""); Connection conn = Jsoup.connect(url_index) .cookies(cookies) .header("Origin", "http://jw1.wucc.cn") .data(data) .method(Connection.Method.POST) .timeout(20000); try { Connection.Response response = conn.execute(); if (Utility.isLoginSuccess(response)) { xsxh = data.get("txtUserName"); xsxm = Utility.getStudentName(response); LogUtil.d(TAG, "学生学号: " + xsxh + ", 学生姓名: " + xsxm); callback.loginSuccess(); } else { callback.loginError(); } } catch (IOException e) { e.printStackTrace(); } } //下载课程信息保存到本地 private void _getCourse(){ String url_course = null; try { url_course = "http://jw1.wucc.cn:2222/xskbcx.aspx?" + "xh=" + xsxh + "&" + "xm=" + URLEncoder.encode(xsxm, "gb2312") + "&" + "gnmkdm=N121603"; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } String referer = "http://jw1.wucc.cn:2222/xs_main.aspx?xh=" + xsxh; InputStream is = null; OutputStream os = null; try { URL url = new URL(url_course); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setConnectTimeout(2*1000); conn.setRequestProperty("Cookie", cookies.toString().replace("{", "").replace("}", "").trim()); conn.setRequestProperty("Referer", referer); conn.setRequestMethod("GET"); is = conn.getInputStream(); File file = new File(context.getFilesDir(), "html_" + xsxh + ".txt"); os = new FileOutputStream(file); int len = 0; byte[] buffer = new byte[1024]; while ((len = is.read(buffer)) != -1) { os.write(buffer, 0, len); } os.flush(); } catch (Exception e) { e.printStackTrace(); }finally{ try { if (is != null) is.close(); if (os != null) os.close(); } catch (Exception e) { e.printStackTrace(); } } } //保存课程到数据库 private void _saveCourse(Context context){ File file = new File(context.getFilesDir(), "html_" + xsxh + ".txt"); Document document = null; try { document = Jsoup.parse(file, "gb2312"); } catch (IOException e) { e.printStackTrace(); } Elements trs = document.select("table").get(1).select("tr"); //删除最上面两列 trs.remove(0); trs.remove(0); //上午、中午、晚上 标记 trs.get(0).select("td").get(0).remove(); trs.get(4).select("td").get(0).remove(); trs.get(8).select("td").get(0).remove(); //删除 第一节 标记 for (int i = 0; i < trs.size(); i++) { trs.get(i).select("td").get(0).remove(); } //trs.size()表示一个有几节课 for (int i = 0; i < trs.size(); i++) { //trs.select("td").size()表示有几列 for (int j = 0; j < trs.get(i).select("td").size(); j++) { CourseModel course = new CourseModel(); Element element = trs.get(i).select("td").get(j); if(element.hasAttr("rowspan")){ course.setRowspan(element.attr("rowspan")); }else{ course.setRowspan("0"); } course.setCourseInfo(element.text()); course.setRow(i+1); course.setCol(j+1); course.setNumber(xsxh); DB.getInstance(context).saveCourse(course); } } } //更新数据库的课程 private int _updateCourse(Context context){ int result = 0; File file = new File(context.getFilesDir(), "html_" + xsxh + ".txt"); Document document = null; try { document = Jsoup.parse(file, "gb2312"); } catch (IOException e) { e.printStackTrace(); } Elements trs = document.select("table").get(1).select("tr"); //删除最上面两列 trs.remove(0); trs.remove(0); //上午、中午、晚上 标记 trs.get(0).select("td").get(0).remove(); trs.get(4).select("td").get(0).remove(); trs.get(8).select("td").get(0).remove(); //删除 第一节 标记 for (int i = 0; i < trs.size(); i++) { trs.get(i).select("td").get(0).remove(); } //trs.size()表示一个有几节课 for (int i = 0; i < trs.size(); i++) { //trs.select("td").size()表示有几列 for (int j = 0; j < trs.get(i).select("td").size(); j++) { CourseModel course = new CourseModel(); Element element = trs.get(i).select("td").get(j); if(element.hasAttr("rowspan")){ course.setRowspan(element.attr("rowspan")); }else{ course.setRowspan("0"); } course.setCourseInfo(element.text()); course.setRow(i+1); course.setCol(j+1); course.setNumber(xsxh); result = DB.getInstance(context).updateCourse(course); } } return result; } //下载成绩查询页面的viewstate,保存当前页面内容到文件 private void _downGradeViewstate(){ String url_grade = null; try { url_grade = "http://jw1.wucc.cn:2222/xscjcx.aspx?" + "xh=" + xsxh + "&xm=" + URLEncoder.encode(xsxm, "gb2312")+ "&gnmkdm=N121605"; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } String referer = "http://jw1.wucc.cn:2222/xs_main.aspx?xh=" + xsxh; InputStream is = null; OutputStream os = null; try { URL url = new URL(url_grade); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setConnectTimeout(2*1000); conn.setRequestProperty("Cookie", cookies.toString().replace("{", "").replace("}", "").trim()); conn.setRequestProperty("Referer", referer); conn.setRequestMethod("GET"); is = conn.getInputStream(); File file = new File(context.getFilesDir(), "gradeviewstate_" + xsxh + ".txt"); os = new FileOutputStream(file); int len = 0; byte[] buffer = new byte[1024]; while ((len = is.read(buffer)) != -1) { os.write(buffer, 0, len); } os.flush(); } catch (Exception e) { e.printStackTrace(); }finally{ try { if (is != null) is.close(); if (os != null) os.close(); } catch (Exception e) { e.printStackTrace(); } } } //从文件中读取成绩查询的viewstate private void _getGradeViewstate(Context context){ File file = new File(context.getFilesDir(), "gradeviewstate_" + xsxh + ".txt"); Document document = null; try { document = Jsoup.parse(file, "gb2312"); } catch (IOException e) { e.printStackTrace(); } Element element = document.select("input[name=__VIEWSTATE]").first(); SharedPreferences.Editor editor = context.getSharedPreferences("data", Context.MODE_PRIVATE) .edit(); editor.putString("viewstate", element.attr("value")); editor.commit(); } //下载成绩内容到文件中 private void _getGrade(Context context){ SharedPreferences sharedPreferences = context.getSharedPreferences("data", Context.MODE_PRIVATE); String url_grade = null; String btn_zcj_str = null; String gradeViewstate = null; try { url_grade = "http://jw1.wucc.cn:2222/xscjcx.aspx?" + "xh=" + xsxh + "&xm=" + URLEncoder.encode(xsxm, "gb2312")+ "&gnmkdm=N121605"; gradeViewstate = URLEncoder.encode(sharedPreferences.getString("viewstate", ""), "gb2312"); btn_zcj_str = URLEncoder.encode("历年成绩", "gb2312"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } String referer = url_grade; InputStream is = null; OutputStream os = null; try { URL url = new URL(url_grade); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setConnectTimeout(2*1000); conn.setRequestProperty("Cookie", cookies.toString().replace("{", "").replace("}", "").trim()); conn.setRequestProperty("Referer", referer); conn.setRequestMethod("POST"); conn.setDoOutput(true); StringBuffer params = new StringBuffer(); params.append("__VIEWSTATE").append("=") .append(gradeViewstate) .append("&") .append("btn_zcj").append("=").append(btn_zcj_str) .append("&") .append("__EVENTTARGET").append("=").append("") .append("&") .append("__EVENTARGUMENT").append("=").append("") .append("&") .append("hidLanguage").append("=").append("") .append("&") .append("ddlXN").append("=").append("") .append("&") .append("ddlXQ").append("=").append("") .append("&") .append("ddl_kcxz").append("=").append(""); byte[] bypes = params.toString().getBytes(); conn.getOutputStream().write(bypes); is = conn.getInputStream(); File file = new File(context.getFilesDir(), "grade_" + xsxh + ".txt"); os = new FileOutputStream(file); int len = 0; byte[] buffer = new byte[1024]; while ((len = is.read(buffer)) != -1) { os.write(buffer, 0, len); } os.flush(); } catch (Exception e) { e.printStackTrace(); }finally{ try { if (is != null) is.close(); if (os != null) os.close(); } catch (Exception e) { e.printStackTrace(); } } } //保存成绩内容到数据库 private void _saveGrade(Context context){ File file = new File(context.getFilesDir(), "grade_" + xsxh + ".txt"); Document document = null; try { document = Jsoup.parse(file, "gb2312"); } catch (IOException e) { e.printStackTrace(); } Elements trs = document.select("table").get(1).select("tr"); //删除最上面一列 trs.remove(0); //trs.size()表示一共有多少项 for (int i = 0; i < trs.size(); i++) { GradeModel gradeModel = new GradeModel(); Elements elements = trs.get(i).select("td"); gradeModel.setXn(elements.get(0).text()); gradeModel.setXq(elements.get(1).text()); gradeModel.setKcdm(elements.get(2).text()); gradeModel.setKcmc(elements.get(3).text()); gradeModel.setKcxz(elements.get(4).text()); gradeModel.setKcgs(elements.get(5).text()); gradeModel.setXf(elements.get(6).text()); gradeModel.setJd(elements.get(7).text()); gradeModel.setCj(elements.get(8).text()); gradeModel.setBkcj(elements.get(10).text()); gradeModel.setCxcj(elements.get(11).text()); gradeModel.setKkxy(elements.get(12).text()); gradeModel.setNumber(xsxh); DB.getInstance(context).saveGrade(gradeModel); } } private int _deleteGrade(Context context){ return DB.getInstance(context).deleteGrade(xsxh); } /*******************************对外方法******************************/ //获得连接 public static void getConnection(final Utility.GetConnectionCallBack callback) { connection = new Thread() { @Override public void run() { super.run(); getInstance()._getConnection(callback); LogUtil.e(TAG, "getConnection执行"); } }; connection.start(); } //连接后,下载验证码 public static void getCheckcode(final Utility.GetCheckcodeCallBack callback) { new Thread() { @Override public void run() { super.run(); try { connection.join(); } catch (InterruptedException e) { e.printStackTrace(); } getInstance()._getCheckcode(callback); LogUtil.e(TAG, "getCheckcode执行"); } }.start(); } //登陆 public static void login(final Map<String, String> data, final Utility.LoginCallBack callback) { new Thread() { @Override public void run() { super.run(); getInstance()._login(data, callback); LogUtil.e(TAG, "login执行"); } }.start(); } //下载课程页面内容到文件 public static void getCourse(){ getCourseThread = new Thread(){ @Override public void run() { super.run(); getInstance()._getCourse(); LogUtil.e(TAG, "getCourse执行"); } }; getCourseThread.start(); } //下载课程页面内容到文件后,保存课程信息到数据库 public static void saveCourse(final Context context, final Utility.SaveCourseCallback callback){ new Thread(){ @Override public void run() { super.run(); try { getCourseThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } getInstance()._saveCourse(context); callback.saveCourseSuccess(); LogUtil.e(TAG, "saveCourse执行"); } }.start(); } //下载课程页面内容到文件后,更新数据库的课程信息 public static void updateCourse(final Context context, final Utility.UpdateCourseCallback callback){ new Thread(){ @Override public void run() { super.run(); try { getCourseThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } getInstance()._updateCourse(context); callback.updateCourseSuccess(); LogUtil.e(TAG, "updateCourse执行"); } }.start(); } //下载成绩查询的viewstate页面内容到文件 public static void downGradeViewstate(){ downGradeViewstateThread = new Thread(){ @Override public void run() { super.run(); getInstance()._downGradeViewstate(); LogUtil.e(TAG, "downGradeViewstate执行"); } }; downGradeViewstateThread.start(); } //在成绩查询的viewstate下载完成后,获取viewstate public static void getGradeViewstate(final Context context){ getGradeViewstateThread = new Thread(){ @Override public void run() { super.run(); try { downGradeViewstateThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } getInstance()._getGradeViewstate(context); LogUtil.e(TAG, "getGradeViewstate执行"); } }; getGradeViewstateThread.start(); } //成绩查询的viewstate获得后,下载成绩页面内容到文件 public static void getGrade(final Context context){ getGradeThread = new Thread(){ @Override public void run() { super.run(); try { getGradeViewstateThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } getInstance()._getGrade(context); LogUtil.e(TAG, "getGrade执行"); } }; getGradeThread.start(); } //成绩下载完成后,保存成绩到数据库 public static void saveGrade(final Context context, final Utility.SaveGradeCallback callback){ new Thread(){ @Override public void run() { super.run(); try { getGradeThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } getInstance()._saveGrade(context); callback.saveGradeSuccess(); LogUtil.e(TAG, "saveGrade执行"); } }.start(); } //删除数据库内成绩信息 public static int deleteGrade(Context context){ LogUtil.e(TAG, "deleteGrade执行"); return getInstance()._deleteGrade(context); } //获得学生学号 public static String getXSXH() { return xsxh; } //获得学生姓名 public static String getXSXM() { return xsxm; } public static void setContext(Context context) { HttpUtil.context = context; } }
Java
UTF-8
1,969
2.65625
3
[]
no_license
package vcluster.elements; /** *A class represents plug-in */ public class Plugin extends Element{ /** * */ private static final long serialVersionUID = 1L; private String pluginName; private String pluginStatus; private String pluginType; private Object instance; /** *Get the name of the plug-in *@return pluginName, the name of the plug-in. */ public String getPluginName() { return pluginName; } /** * Set the name of the plug-in * @param pluginName, the name of the plug-in */ public void setPluginName(String pluginName) { this.pluginName = pluginName; } /** *Get the plug-in status,loaded or unloaded into vcluster. *@return pluginStatus. */ public String getPluginStatus() { return pluginStatus; } /** *Set the plug-in status *@param pluginStatus, the plug-in loaded/unloaded status. */ public void setPluginStatus(String pluginStatus) { this.pluginStatus = pluginStatus; } /** *Get the plug-in type, There are three types of plug-in, cloud,batch system and load balancer. *@return pluginType, the type of the plug-in. */ public String getPluginType() { return pluginType; } /** *Set the type of the plug-in, There are three types of plug-in, cloud,batch system and load balancer. *@param pluginType, the type of the plug-in. */ public void setPluginType(String pluginType) { this.pluginType = pluginType; } /** *Get the instance that this class represents. *@return instance, cloud be an instance of cloud plug-in, batch system plug-in or load balancer plug-in. */ public Object getInstance() { return instance; } /** *Set the instance that this class represents. * @param instance, cloud be an instance of cloud plug-in, batch system plug-in or load balancer plug-in. */ public void setInstance(Object instance) { this.instance = instance; } }
Markdown
UTF-8
5,790
3.015625
3
[]
no_license
杭州市房屋租赁合同       房租(  )号      甲方(出租人):___________________     乙方(承租人):___________________     根据国家、省有关法律、法规和本市的有关规定,甲、乙双方在自愿、公平、诚实信用、等价有偿原则的基础上,经充分协商,同意就下列房屋租赁事项,订立本合同,并共同遵守。    一、 甲方自愿将座落在本市___区__房屋,使用面积___平方米,出租给乙方使用。乙方已对甲方所要出租的房屋做了充分了解,愿意承租该房屋。    二、 该房屋租赁期自___年___月___日起至___年___月___日止。    三、 该房屋每月每平方米使用面积租金___元,月租金总额(大写)___,¥___元。    四、 该房屋租金___年内不变。自第___年起,月租金每年递增___%。    五、 乙方必须按时向甲方缴纳租金。付款的时间及方式___。    六、 乙方保证所租赁的房屋权作为___房使用。    七、 租赁期内,乙方未事先征得甲方的书面同意,并按规定报经有关部门核准,不得擅自改变房屋的使用性质。    八、 甲方应保证出租房屋的使用安全,并负责对房屋及其附着物的定期检查,承担正常的房屋维修费用。因甲方延误房屋维修而使乙方或第三人遭受损失的,甲方负责赔偿。如因乙方使用不当造成房屋或设施损坏的,乙方应立即负责修复或予以经济赔偿。    九、 甲方维修房屋及其附着设施,应提前___天书面通知乙方,乙方应积极协助和配合。因甲方不及时履行合同约定的维修、养护责任,致使该房屋发生损坏,造成乙方财产损失或人身伤害的,甲方应承担赔偿责任。因乙方阻挠甲方进行维修而产生的后果,则概由乙方负责。    十、 乙方如需对房屋进行改装修或增扩设备时,应事先征得甲方的书面同意,并按规定向有关部门办理申报手续后,方可进行。    十一、 如因不可抗力的原因而使所租房屋及其设备损坏的,双方互不承担责任。    十二、 租赁期内,甲方如需转让或抵押该房屋,应提前___个月通知乙方。同等条件下,乙方有优先受让权。    十三、 租赁期内,乙方有下列行为之一的,甲方有权终止本合同,收回该房屋,由此而造成甲方损失的,乙方应予以赔偿;     1.擅自改变本合同规定的租赁用途,或利用该房屋进行违法违章活动的;     2.未经甲方同意,擅自拆改变动房屋结构,或损坏房屋,且经甲方书面通知,在限定时间内仍未纠正并修复的;     3.未经甲方同意,擅自将房屋转租、转让、转借他人或调换使用的;     4.拖欠租金累计___个月以上的;    十四、 自本合同签订之日___天内,甲方将出租的房屋交乙方使用。如甲方逾期不交房屋的,则每逾期一天应向乙方支付原日租金___倍的违约金。    十五、 租赁期内,甲方无正当理由,提前收回该房屋的,甲方应按月租金的___倍向乙方支付违约金。乙方未经甲方同意中途擅自退租的,乙方应按月租金的___倍向甲方支付违约金。    十六、 租赁期满,甲方有权收回全部出租房屋。乙方如需继续租用的,应提前___个月向甲方提出书面意向,经甲方同意后,重新签订租赁合同,并按规定重新办理房屋租赁登记。    十七、 租赁期满,乙方应如期归还该房屋。如乙方逾期不归还的,则每逾期一天应向甲方支付原日租金___倍的违约金。    十八、 本合同经甲、乙双方签署后,双方应按规定向杭州市房地产管理局申请登记,领取《房屋租赁证》。    十九、 租赁期内,乙方在征得甲方书面同意的基础上,可将租赁房屋的部分或全部转租给他人,并应签订转租合同,该合同经甲方签署同意意见,按有关规定办理登记手续,领取《房屋租赁证》后,方可转租。    二十、 变更或解除本合同,要求变更或解除合同的一方应主动向另一方提出,应及时到杭州市房地产管理局办理变更登记或注销手续。    二十一、 合同发生争议,解决方式由当事人约定从下列两种方式中选择一种(即在1或2中打“√”,未打“√”的,按选择1对待):     1.因履行本合同发生的争议,由当事人协商解决,协商不成的,提交杭州仲裁委员会仲裁;     2.因履行本合同发生的争议,由当事人协商解决,协商不成的,依法向人民法院起诉。    二十二、 本合同未尽事宜,经甲、乙双方协商一致,可订立补充条款。但补充条款应符合国家、省、市有关房屋租赁管理规定。    二十三、 本合同一式___份,甲、乙双方各执___份。将合同副本贰份送杭州房地产管理局。    二十四、 双方约定的其他事项:     甲方(签章):           乙方(签章):     法定代表人:            法定代表人:     地 址:              地 址:     联系电话:             联系电话:     委托代理人:            委托代理人:      年 月 日   
Go
UTF-8
14,891
2.5625
3
[ "MIT" ]
permissive
package core import ( "bytes" "encoding/binary" "encoding/hex" "encoding/json" "reflect" "sort" "sync" "github.com/covrom/gonec/names" ) const ChunkVMSlicePool = 64 // globalVMSlicePool используется виртуальной машиной для переиспользования в регистрах и параметрах вызова var globalVMSlicePool = sync.Pool{ New: func() interface{} { return make(VMSlice, 0, ChunkVMSlicePool) }, } func GetGlobalVMSlice() VMSlice { sl := globalVMSlicePool.Get() if sl != nil { return sl.(VMSlice) } return make(VMSlice, 0, ChunkVMSlicePool) } func PutGlobalVMSlice(sl VMSlice) { if cap(sl) <= ChunkVMSlicePool { sl = sl[:0] globalVMSlicePool.Put(sl) } } type VMSlice []VMValuer var ReflectVMSlice = reflect.TypeOf(make(VMSlice, 0)) func (x VMSlice) vmval() {} func (x VMSlice) Interface() interface{} { return x } func (x VMSlice) Slice() VMSlice { return x } func (x VMSlice) BinaryType() VMBinaryType { return VMSLICE } func (x VMSlice) Args() []interface{} { ai := make([]interface{}, len(x)) for i := range x { ai[i] = x[i] } return ai } func (x *VMSlice) Append(a ...VMValuer) { *x = append(*x, a...) } func (x VMSlice) Length() VMInt { return VMInt(len(x)) } func (x VMSlice) IndexVal(i VMValuer) VMValuer { if ii, ok := i.(VMInt); ok { return x[int(ii)] } panic("Индекс должен быть целым числом") } func (x VMSlice) Hash() VMString { b, err := x.MarshalBinary() if err != nil { panic(err) } h := make([]byte, 8) binary.LittleEndian.PutUint64(h, HashBytes(b)) return VMString(hex.EncodeToString(h)) } func (x VMSlice) SortDefault() { sort.Sort(VMSliceUpSort(x)) } func (x VMSlice) MethodMember(name int) (VMFunc, bool) { // только эти методы будут доступны из кода на языке Гонец! switch names.UniqueNames.GetLowerCase(name) { case "сортировать": return VMFuncMustParams(0, x.Сортировать), true case "сортироватьубыв": return VMFuncMustParams(0, x.СортироватьУбыв), true case "обратить": return VMFuncMustParams(0, x.Обратить), true case "скопировать": return VMFuncMustParams(0, x.Скопировать), true case "найти": return VMFuncMustParams(1, x.Найти), true case "найтисорт": return VMFuncMustParams(1, x.НайтиСорт), true case "вставить": return VMFuncMustParams(2, (&x).Вставить), true case "удалить": return VMFuncMustParams(1, (&x).Удалить), true case "скопироватьуникальные": return VMFuncMustParams(0, x.СкопироватьУникальные), true } return nil, false } func (x VMSlice) Сортировать(args VMSlice, rets *VMSlice, envout *(*Env)) error { x.SortDefault() return nil } // Найти (значение) (индекс, найдено) - находит индекс значения или места для его вставки (конец списка), если его еще нет // возврат унифицирован с возвратом функции НайтиСорт func (x VMSlice) Найти(args VMSlice, rets *VMSlice, envout *(*Env)) error { y := args[0] p := 0 fnd := false for p < len(x) { if EqualVMValues(x[p], y) { fnd = true break } p++ } rets.Append(VMInt(p)) rets.Append(VMBool(fnd)) return nil } // НайтиСорт (значение) (индекс, найдено) - находит индекс значения или места для его вставки, если его еще нет // поиск осуществляется в отсортированном по возрастанию массиве // иначе будет непредсказуемый ответ func (x VMSlice) НайтиСорт(args VMSlice, rets *VMSlice, envout *(*Env)) error { y := args[0] p := sort.Search(len(x), func(i int) bool { return !SortLessVMValues(x[i], y) }) //data[i] >= x if p < len(x) && EqualVMValues(x[p], y) { // y is present at x[p] rets.Append(VMInt(p)) rets.Append(VMBool(true)) } else { // y is not present in x, // but p is the index where it would be inserted. rets.Append(VMInt(p)) rets.Append(VMBool(false)) } return nil } // Вставить (индекс, значение) - вставляет значение по индексу. // Индекс может быть равен длине, тогда вставка происходит в последний элемент. // Обычно используется в связке с НайтиСорт, т.к. позволяет вставлять значения с сохранением сортировки по возрастанию func (x *VMSlice) Вставить(args VMSlice, rets *VMSlice, envout *(*Env)) error { p, ok := args[0].(VMInt) if !ok { return VMErrorNeedInt } if int(p) < 0 || int(p) > len(*x) { return VMErrorIndexOutOfBoundary } y := args[1] *x = append(*x, VMNil) copy((*x)[p+1:], (*x)[p:]) (*x)[p] = y return nil } func (x *VMSlice) Удалить(args VMSlice, rets *VMSlice, envout *(*Env)) error { p, ok := args[0].(VMInt) if !ok { return VMErrorNeedInt } if int(p) < 0 || int(p) >= len(*x) { return VMErrorIndexOutOfBoundary } copy((*x)[p:], (*x)[p+1:]) (*x)[len(*x)-1] = nil *x = (*x)[:len(*x)-1] return nil } func (x VMSlice) СортироватьУбыв(args VMSlice, rets *VMSlice, envout *(*Env)) error { sort.Sort(sort.Reverse(VMSliceUpSort(x))) return nil } func (x VMSlice) Обратить(args VMSlice, rets *VMSlice, envout *(*Env)) error { for left, right := 0, len(x)-1; left < right; left, right = left+1, right-1 { x[left], x[right] = x[right], x[left] } return nil } func (x VMSlice) CopyRecursive() VMSlice { rv := make(VMSlice, len(x)) for i, v := range x { switch vv := v.(type) { case VMSlice: rv[i] = vv.CopyRecursive() case VMStringMap: rv[i] = vv.CopyRecursive() default: rv[i] = v } } return rv } // Скопировать - помимо обычного копирования еще и рекурсивно копирует и слайсы/структуры, находящиеся в элементах func (x VMSlice) Скопировать(args VMSlice, rets *VMSlice, envout *(*Env)) error { //VMSlice { rv := make(VMSlice, len(x)) copy(rv, x) for i, v := range rv { switch vv := v.(type) { case VMSlice: rv[i] = vv.CopyRecursive() case VMStringMap: rv[i] = vv.CopyRecursive() } } rets.Append(rv) return nil } func (x VMSlice) СкопироватьУникальные(args VMSlice, rets *VMSlice, envout *(*Env)) error { //VMSlice { rv := make(VMSlice, len(x)) seen := make(map[VMValuer]bool) for i, v := range x { if _, ok := seen[v]; ok { continue } switch vv := v.(type) { case VMSlice: rv[i] = vv.CopyRecursive() case VMStringMap: rv[i] = vv.CopyRecursive() default: rv[i] = x[i] } seen[v] = true } rets.Append(rv) return nil } func (x VMSlice) EvalBinOp(op VMOperation, y VMOperationer) (VMValuer, error) { switch op { case ADD: switch yy := y.(type) { case VMSlice: // добавляем второй слайс в конец первого return append(x, yy...), nil case VMValuer: return append(x, yy), nil } return append(x, y), nil // return VMNil, VMErrorIncorrectOperation case SUB: // удаляем из первого слайса любые элементы второго слайса, встречающиеся в первом switch yy := y.(type) { case VMSlice: // проходим слайс и переставляем ненайденные в вычитаемом слайсе элементы rv := make(VMSlice, len(x)) il := 0 for i := range x { fnd := false for j := range yy { if EqualVMValues(x[i], yy[j]) { fnd = true break } } if !fnd { rv[il] = x[i] il++ } } return rv[:il], nil } return VMNil, VMErrorIncorrectOperation case MUL: return VMNil, VMErrorIncorrectOperation case QUO: return VMNil, VMErrorIncorrectOperation case REM: // оставляем только элементы, которые есть в первом и нет во втором и есть во втором но нет в первом // эквивалентно (С1 | С2) - (С1 & С2), или (С1-С2)|(С2-С1), или С2-(С1-С2), внешнее соединение switch yy := y.(type) { case VMSlice: rvx := make(VMSlice, len(x)) rvy := make(VMSlice, len(yy)) // С1-С2 il := 0 for i := range x { fnd := false for j := range yy { if EqualVMValues(x[i], yy[j]) { fnd = true break } } if !fnd { // оставляем rvx[il] = x[i] il++ } } rvx = rvx[:il] // С2-(С1-C2) il = 0 for j := range yy { fnd := false for i := range x { if EqualVMValues(x[i], yy[j]) { fnd = true break } } if !fnd { // оставляем rvy[il] = yy[j] il++ } } rvy = rvy[:il] return append(rvx, rvy...), nil } return VMNil, VMErrorIncorrectOperation case EQL: // равенство по глубокому равенству элементов switch yy := y.(type) { case VMSlice: if len(x) != len(yy) { return VMBool(false), nil } for i := range x { for j := range yy { if !EqualVMValues(x[i], yy[j]) { return VMBool(false), nil } } } return VMBool(true), nil } return VMNil, VMErrorIncorrectOperation case NEQ: switch yy := y.(type) { case VMSlice: if len(x) != len(yy) { return VMBool(true), nil } for i := range x { for j := range yy { if !EqualVMValues(x[i], yy[j]) { return VMBool(true), nil } } } return VMBool(false), nil } return VMNil, VMErrorIncorrectOperation case GTR: return VMNil, VMErrorIncorrectOperation case GEQ: return VMNil, VMErrorIncorrectOperation case LSS: return VMNil, VMErrorIncorrectOperation case LEQ: return VMNil, VMErrorIncorrectOperation case OR: // добавляем в конец первого слайса только те элементы второго слайса, которые не встречаются в первом switch yy := y.(type) { case VMSlice: rv := x[:] for j := range yy { fnd := false for i := range x { if EqualVMValues(x[i], yy[j]) { fnd = true break } } if !fnd { rv = append(rv, yy[j]) } } return rv, nil } return VMNil, VMErrorIncorrectOperation case LOR: return VMNil, VMErrorIncorrectOperation case AND: // оставляем только те элементы, которые есть в обоих слайсах switch yy := y.(type) { case VMSlice: rv := make(VMSlice, 0, len(x)) for i := range x { fnd := false for j := range yy { if EqualVMValues(x[i], yy[j]) { fnd = true break } } if fnd { rv = append(rv, x[i]) } } return rv, nil } return VMNil, VMErrorIncorrectOperation case LAND: return VMNil, VMErrorIncorrectOperation case POW: return VMNil, VMErrorIncorrectOperation case SHR: return VMNil, VMErrorIncorrectOperation case SHL: return VMNil, VMErrorIncorrectOperation } return VMNil, VMErrorUnknownOperation } func (x VMSlice) ConvertToType(nt reflect.Type) (VMValuer, error) { switch nt { case ReflectVMString: // сериализуем в json b, err := json.Marshal(x) if err != nil { return VMNil, err } return VMString(string(b)), nil // case ReflectVMInt: // case ReflectVMTime: // case ReflectVMBool: // case ReflectVMDecNum: case ReflectVMSlice: return x, nil // case ReflectVMStringMap: } return VMNil, VMErrorNotConverted } func (x VMSlice) MarshalBinary() ([]byte, error) { var buf bytes.Buffer //количество элементов binary.Write(&buf, binary.LittleEndian, uint64(len(x))) for i := range x { if v, ok := x[i].(VMBinaryTyper); ok { bb, err := v.MarshalBinary() if err != nil { return nil, err } //тип buf.WriteByte(byte(v.BinaryType())) //длина binary.Write(&buf, binary.LittleEndian, uint64(len(bb))) //байты buf.Write(bb) } else { return nil, VMErrorNotBinaryConverted } } return buf.Bytes(), nil } func (x *VMSlice) UnmarshalBinary(data []byte) error { buf := bytes.NewBuffer(data) var l, lv uint64 //количество элементов if err := binary.Read(buf, binary.LittleEndian, &l); err != nil { return err } var rv VMSlice if x == nil || len(*x) < int(l) { rv = make(VMSlice, int(l)) } else { rv = (*x)[:int(l)] } for i := 0; i < int(l); i++ { //тип if tt, err := buf.ReadByte(); err != nil { return err } else { //длина if err := binary.Read(buf, binary.LittleEndian, &lv); err != nil { return err } //байты bb := buf.Next(int(lv)) vv, err := VMBinaryType(tt).ParseBinary(bb) if err != nil { return err } rv[i] = vv } } *x = rv return nil } func (x VMSlice) GobEncode() ([]byte, error) { return x.MarshalBinary() } func (x *VMSlice) GobDecode(data []byte) error { return x.UnmarshalBinary(data) } func (x VMSlice) String() string { b, err := json.Marshal(x) if err != nil { panic(err) } return string(b) } func (x VMSlice) MarshalText() ([]byte, error) { b, err := json.Marshal(x) if err != nil { return nil, err } return b, nil } func (x *VMSlice) UnmarshalText(data []byte) error { sl, err := VMSliceFromJson(string(data)) if err != nil { return err } *x = sl return nil } func (x VMSlice) MarshalJSON() ([]byte, error) { var err error rm := make([]json.RawMessage, len(x)) for i, v := range x { rm[i], err = json.Marshal(v) if err != nil { return nil, err } } return json.Marshal(rm) } func (x *VMSlice) UnmarshalJSON(data []byte) error { if string(data) == "null" { return nil } sl, err := VMSliceFromJson(string(data)) if err != nil { return err } *x = sl return nil } // VMSliceUpSort - обертка для сортировки слайса по возрастанию type VMSliceUpSort VMSlice func (x VMSliceUpSort) Len() int { return len(x) } func (x VMSliceUpSort) Swap(i, j int) { x[i], x[j] = x[j], x[i] } func (x VMSliceUpSort) Less(i, j int) bool { return SortLessVMValues(x[i], x[j]) } // NewVMSliceFromStrings создает слайс вирт. машины []VMString из слайса строк []string на языке Го func NewVMSliceFromStrings(ss []string) (rv VMSlice) { for i := range ss { rv = append(rv, VMString(ss[i])) } return }
Python
UTF-8
395
2.71875
3
[]
no_license
import pygame from pygame.locals import * import UI import spritesheet class Lifes(): def __init__(self, window, lifes): self.window = window self.lifes = lifes self.template = spritesheet.spritesheet("ui/lifes.png") self.image = self.template.image_at((0, 0, 200, 100)) def update(self, lifes): self.image = self.template.image_at((lifes * 200, 0, 200, 100)) return self.image
C++
UTF-8
890
2.703125
3
[]
no_license
#include "inputmanager.h" InputManager::InputManager() { } InputManager::~InputManager() { } void InputManager::addKeyboardListener(KeyboardListener* listener) { keyboardlistener_.push_back(listener); } void InputManager::removeKeyboardListener(KeyboardListener* listener) { std::vector<KeyboardListener*>::iterator it; for (it = keyboardlistener_.begin(); it != keyboardlistener_.end(); ) { if (*it == listener) { it = keyboardlistener_.erase(it); } else { ++it; } } } void InputManager::addMouseListener(MouseListener* listener) { mouselistener_.push_back(listener); } void InputManager::removeMouseListener(MouseListener* listener) { std::vector<MouseListener*>::iterator it; for (it = mouselistener_.begin(); it != mouselistener_.end(); ) { if (*it == listener) { it = mouselistener_.erase(it); } else { ++it; } } }
SQL
UTF-8
1,220
3.421875
3
[]
no_license
DELIMITER ;; CREATE PROCEDURE `sp_listaTipo`() BEGIN SELECT * from tipo; END ;; DELIMITER ;; CREATE PROCEDURE `sp_listaMercaderia`() BEGIN SELECT * from mercaderia; END ;; DELIMITER ;; CREATE PROCEDURE `sp_listaMercaderiaExt`() BEGIN SELECT A.idmercaderia AS 'id',A.nombre,A.stock,A.precio,B.idtipo,B.nombre AS 'tipo' from mercaderia A INNER JOIN tipo B ON A.idtipo=B.idtipo; END ;; ALTER TABLE mercaderia AUTO_INCREMENT=0; ALTER TABLE tipo AUTO_INCREMENT=9; DELIMITER ;; CREATE PROCEDURE `sp_regMercaderia`(nom VARCHAR(45),stk int,pre DOUBLE, idTip int) BEGIN insert into mercaderia values(null,nom,stk,pre,idTip); END ;; DELIMITER ; DELIMITER ;; CREATE PROCEDURE `sp_upMercaderia`(id int,nom VARCHAR(45),stk int,pre DOUBLE, idTip int) BEGIN update mercaderia SET nombre=nom,stock=stk,precio=pre,idtipo=idTip WHERE idmercaderia=id; END ;; DELIMITER ; DELIMITER ;; CREATE PROCEDURE `sp_delMercaderia`(id int) BEGIN delete from mercaderia WHERE idmercaderia=id; END ;; DELIMITER ; call sp_regMercaderia ('jane_doe',20,40.50,2); call sp_listaMercaderiaExt; SELECT Auto_increment FROM information_schema.tables WHERE TABLE_NAME='mercaderia'; SHOW VARIABLES LIKE 'auto_inc%'; SET @@auto_increment_increment=1;
Java
UTF-8
2,073
3.65625
4
[]
no_license
/** * @author Bang * @date 2019/8/27 16:15 */ public class Str_01_06 { public static int aoti(String str){ //字符串不为空时并且字符串不全是空白字符串时才转换 //去除掉前后的空格 String str1 = str.trim(); //存储最终过滤出来的字符串 String resStr = null; //字符串不为空时并且字符串不全是空白字符串时才转换 if (str1 != null || str1.isEmpty() == false){ char first = str1.charAt(0); if (first >= '0' && first <= '9' || first == '+' || first == '-'){ resStr = str1.substring(0,1); // 把第一位放进去(只能是数字、正负号) //这时候循环只要数字,因为正负号只能出现在第一位 for (int i = 1; i < str1.length(); i++) { if (str1.charAt(i) >= '0' && str1.charAt(i) <= '9'){ resStr = str1.substring(0,i+1); }else { //这是遇到不符合要求的字符,直接忽略剩余元素 break; } } } } //判断最终字符串是否为空或则只有一个正负号 if (resStr == null || resStr.equals("+") || resStr.equals("-")){ //此时strrr是String对象,如果使用==比较则比较的时内存地址 return 0; } //最终转换成的数字 int resNum = 0; //使用异常机制打印结果 try { resNum = Integer.parseInt(resStr); }catch (Exception e){ if (resStr.charAt(0) == '-'){ return Integer.MIN_VALUE; }else { return Integer.MAX_VALUE; } } return resNum; } public static void main(String[] args) { String str = "-91283472332"; String str1 = "4193 with words"; System.out.println(aoti(str)); System.out.println(aoti(str1)); } }
Markdown
UTF-8
3,274
2.546875
3
[ "MIT", "LicenseRef-scancode-public-domain" ]
permissive
--- title: The explanation for $1,000,000 fee on a single Ethereum transaction description: Why somebody transferred $100 worth of ETH with $2,500,000 fee longDescription: Why somebody transferred $100 worth of ETH with $2,500,000 fee. One fee mistake could be explained by a programming error. But now it has happened more than once, it is likely that it is no longer a mistake. ## Sharing info ## author: Mikko Ohtamaa date: 2020-06-12 page_logo: /static/img/content/src/ethereum.jpg page_facebook_type: article page_twitter_creator: moo9000 layout: layouts/post.njk header: ethereum.jpg headerImageModeClass: header-image-mode-cover-image header-image-mode-700 header-image-text-white headerImageBackgrondColor: #eeeeee postListImageClass: post-list-image-cover # Discussion twitterDiscussionLink: https://mobile.twitter.com/moo9000/status/1271507454711476225 --- <div><p>Somebody is repeatedly sending out Ethereum transactions worth of <a href="https://cointelegraph.com/news/vitalik-buterin-comments-on-strange-transaction-fees?utm_source=Telegram&amp;utm_medium=social" target="_blank">$100 with $2,500,000 fee</a>. The most likely explanation, by Occam's razor, is that an exchange has a broken hardware wallet device or custody solution.</p><p>When checking the address on EtherScan <a href="https://twitter.com/GBSavant/status/1271149824646221825" target="_blank">it seems to be associated with Bithumb, a Korean exchange based on the To: address of the transaction that seems to be a user deposit address to Bithumb hot wallet</a>. One fee mistake could be explained by a programming error. But now it has happened more than once, it is likely that it is no longer a mistake.</p><p>It is not anti-money laundering as a crook would not want to draw the attention of all the Ethereum world to the transactions with the highest fees ever. Also the transactions were broadcasted to the Ethereum public mempool, not privately broadcasted to a miner. Different mining pools picked up the transactions, mined them and received the fees.</p><p>Then the next likely explanation is that the exchange has lost access to its wallet, either by stupidy or by malice. Often exchanges use special devices or custody providers to ensure the security of their wallet, from provides like Ledger Vault or BitGo. In this case, it sounds like the wallet has been either partially hacked or misconfigured. Also it would not be the first time the exchange loses their paper backups, it also happened with New Zealand Cryptopia exchange that could not restore the access to their own wallet after a hack.</p><ol><li>A malicious party has control over the exchange hardware wallet and is draining with super fee transactions and trying to blackmail the exchange</li><li>The exchange itself programmed the device permanently to have a too low withdrawal limit. These hardware devices have a way to lock the admin out if you are not careful - that makes them secure. If this happened the only way for the exchange to get money our from their wallet is to make super high transaction fee transactions and then beg Ethereum mining pools to give back their money.</li></ol><p>Pick your favourite with Hanlon's razor: Never attribute to malice that which is adequately explained by stupidity.
SQL
UTF-8
1,428
3.53125
4
[ "MIT" ]
permissive
COPY ( SELECT pd.id ,pd.created ,pd.modified ,'[deleted]' AS title ,'[deleted]' AS full_name -- remove last two characters of postcode so as to not uniquely ID anyone ,left(replace(upper(pd.postcode), ' ', ''), -2) AS postcode ,'[deleted]' AS street ,'[deleted]' AS mobile_phone ,'[deleted]' AS home_phone ,pd.reference ,'[deleted]' AS email ,pd.date_of_birth ,'[deleted]' AS ni_number ,pd.contact_for_research ,pd.vulnerable_user ,pd.safe_to_contact ,pd.case_count ,pd.safe_to_email ,pd.diversity_modified ,trim((dv.diversity->'gender')::text, '"') AS diversity_gender ,trim((dv.diversity->'sexual_orientation')::text, '"') AS diversity_sexual_orientation ,trim((dv.diversity->'disability')::text, '"') AS diversity_disability ,trim((dv.diversity->'ethnicity')::text, '"') AS diversity_ethnicity ,trim((dv.diversity->'religion')::text, '"') AS diversity_religion FROM legalaid_personaldetails AS pd JOIN (select id, {diversity_expression} as diversity from legalaid_personaldetails) as dv on pd.id = dv.id WHERE (pd.modified >= %(from_date)s::timestamp AND pd.modified <= %(to_date)s::timestamp) OR (pd.created >= %(from_date)s::timestamp AND pd.created <= %(to_date)s::timestamp) ) TO STDOUT CSV HEADER;
Python
UTF-8
1,200
3.828125
4
[ "MIT" ]
permissive
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next # 使用递归来实现 class Solution: def reverseList(self, head: ListNode) -> ListNode: # 用于存储新链表的头部 self.head def recur(head): if head: # 如果本节点不为空,创建新的节点 new_node = ListNode(head.val) # 递归 res = recur(head.next) if res: # 如果递归结果不为空,说明下一个节点不为空 res.next = new_node return res.next else: # 递归返回空。说明当前节点是最后一个节点 self.head = new_node return new_node else: # 如果节点为空,就返回空 return recur(head) return self.head if __name__ == '__main__': head = NodeList(1) head.next = NodeList(2) head.next.next = NodeList(3) head.next.next.next = NodeList(4) Solution.reverseList(head)
C
UTF-8
399
3.71875
4
[]
no_license
#include<stdio.h> int main(){ int point; int sum = 0; float avg; for(int i=0;i<5;i++){ for(int k=0;k<3;k++){ printf("please enter the point of each Bowler :"); scanf("%d",&point); sum = sum+point; } avg = sum/3; printf("%d st Bowler's average point is : %f \n",i+1,avg); sum = 0; } return 0; }
Java
UTF-8
10,752
2.65625
3
[]
no_license
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class PokedexMethods { String query = ""; public Connection connection = MSAccessDatabaseConnection.getConnection("pokedex.accdb");; public ResultSetTable tblPrimary; public ResultSetTable tblSecondary; boolean booleanResultSet; ResultSet resultSet = null; FileReader fileReader; public ArrayList<Integer> IDSList = new ArrayList<Integer>(); public ArrayList<Integer> pokemonMovesIDSList = new ArrayList<Integer>(); public ArrayList<Integer> getIdsList(boolean primaryRecord) { if (primaryRecord) { query = "SELECT ID FROM Pokemon"; } else { query = "SELECT ID FROM Moves"; } try { resultSet = DatabaseUtilities.runQuery(connection, query); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { while (resultSet.next()) { IDSList.add(resultSet.getInt(1)); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return IDSList; } public ArrayList<Integer> getRelationshipIDS(Object ID) { query = "SELECT MovesID FROM PokemonMoves WHERE PokemonID='" + ID + "';"; try { resultSet = DatabaseUtilities.runQuery(connection, query); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { while (resultSet.next()) { IDSList.add(resultSet.getInt(1)); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return IDSList; } public boolean isType1(int ID, Object Type1) { query = "SELECT Type2 FROM Pokemon" + "WHERE ID='" + ID + "';"; boolean type1IsType2 = false; try { resultSet = DatabaseUtilities.runQuery(connection, query); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { if (resultSet.getObject(ID) == Type1) { type1IsType2 = true; } else { type1IsType2 = false; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return type1IsType2; } public Object getAllPrimaryID() { query = "SELECT ID FROM Pokemon"; try { resultSet = DatabaseUtilities.runQuery(connection, query); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } return DatabaseUtilities.printResultSet(resultSet); } public Object getAllSecondaryID() { query = "SELECT ID FROM Moves"; try { booleanResultSet = DatabaseUtilities.execute(connection, query); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } return booleanResultSet; } public Object getPokemon(int iD) //e.g. Student getStudent(String studentID) { query = "SELECT Name FROM POKEMON" + "WHERE ID='" + iD +"';"; try { booleanResultSet = DatabaseUtilities.execute(connection, query); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } return booleanResultSet; } public Object getHP(int iD) //e.g. Class getCourse(String classID) { query = "SELECT HP FROM Moves" + "WHERE ID='" + iD + "';"; try { booleanResultSet = DatabaseUtilities.execute(connection, query); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } return booleanResultSet; } public Object getAllSecondaryRecords(String primaryID) { return null; } public void modifyPrimaryRecord(Object ID, String name, Object type1, Object type2, String height, String weight) //e.g. modifyStudent(Student student) { query = "UPDATE Pokemon"; if (name != null) { query += " SET Name='" + name + "'" + "WHERE ID='" + ID +"';"; } else if (type1 != null) { System.out.println("TYPE1 NOT NULL: CHANGE COMMENCE"); query += " SET Type='" + type1 + "'" + "WHERE ID='" + ID +"';"; } else if (type2 != null) { query += " SET Type2='" + type2 + "'" + "WHERE ID='" + ID +"';"; } else if (height != null) { query += " SET Height='" + height + "'" + "WHERE ID='" + ID +"';"; } else { query += " SET Weight='" + weight + "'" + "WHERE ID='" + ID +"';"; } System.out.println(query); try { booleanResultSet = DatabaseUtilities.execute(connection, query); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } public void modifySecondaryRecord(Object ID, String name, Object type, String power, String pp, Object effect) //e.g. modifyCourse(Course course) { query = "UPDATE Moves"; if (name != null) { query += " SET Name = '" + name + "'" + "WHERE ID = '" + ID +"';"; } else if (type != null) { query += " SET Type='" + type + "'" + "WHERE ID='" + ID +"';"; } else if (power != null) { query += " SET Power='" + power + "'" + "WHERE ID='" + ID +"';"; } else if (pp != null) { query += " SET PP='" + pp + "'" + "WHERE ID='" + ID +"';"; } else { query += " SET Effect='" + effect + "'" + "WHERE ID='" + ID +"';"; } System.out.println(query); try { booleanResultSet = DatabaseUtilities.execute(connection, query); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } public void deletePrimaryRecord(Object primaryID) { query = "DELETE FROM Pokemon WHERE ID='" + primaryID + "';"; System.out.println(query); try { booleanResultSet = DatabaseUtilities.execute(connection, query); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } public void deleteSecondaryRecord(Object secondaryID) { query = "DELETE FROM Moves WHERE ID='" + secondaryID + "';"; System.out.println(query); try { booleanResultSet = DatabaseUtilities.execute(connection, query); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } public void addPrimaryRecord(String name, Object type1, Object type2, double height, double weight) { query = "INSERT INTO Pokemon (Name, Type, Type2, Height, Weight)" + "VALUES ('" + name + "', '" + type1 + "', '" + type2 + "', '" + height + "', '" + weight + "');"; System.out.println(query); try { booleanResultSet = DatabaseUtilities.execute(connection, query); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } public void addSecondaryRecord(String string, Object type, double power, Object pp, Object effect) { query = "INSERT INTO Moves (Name, Type, Power, PP, Effect)" + "VALUES ('" + string + "', '" + type + "', '" + power + "', '" + pp + "', '" + effect + "');"; System.out.println(query); try { booleanResultSet = DatabaseUtilities.execute(connection, query); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } public void addRelationship(Object primaryID, Object secondaryID) //creates a relationship between the two records { query = "INSERT INTO PokemonMoves (PokemonID, MovesID)" + "VALUES ('" + primaryID + "', '" + secondaryID + "');"; System.out.println(query); try { booleanResultSet = DatabaseUtilities.execute(connection, query); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } public void deleteRelationship(Object primaryID, Object secondaryID) //removes a relationship between the two records { query = "DELETE FROM PokemonMoves WHERE PokemonID='" + primaryID + "' AND MovesID='" + secondaryID + "';"; System.out.println(query); try { booleanResultSet = DatabaseUtilities.execute(connection, query); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } /** * Must import correct file for database in the form: Name, Type, Type2, Height, Weight * Do not include the names for the columns * @param fileName */ public void importPrimaryRecords(String fileName) { String text = ""; String[] fields = null; int count = 0; //ArrayList<Pokemon> csvPokemon = new ArrayList<Pokemon>(); BufferedReader inputStream = null; if (fileName != null) { try { inputStream = new BufferedReader(new FileReader(fileName)); String l; while ((l = inputStream.readLine()) != null) { if (text == "") { text = l; fields = l.split(","); this.addPrimaryRecord(fields[0], fields[1], fields[2], Double.parseDouble(fields[3]), Double.parseDouble(fields[4])); count++; } else { text += "\r\n" + l; fields = l.split(","); this.addPrimaryRecord(fields[0], fields[1], fields[2], Double.parseDouble(fields[3]), Double.parseDouble(fields[4])); } } } catch (FileNotFoundException e) { text = ""; e.printStackTrace(); } catch (IOException e) { text = ""; e.printStackTrace(); } if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * Must import correct file for database in the form: Name, Type, Power, PP, Effect * @param fileName */ public void importSecondaryRecords(String fileName) { String text = ""; String[] fields = null; int count = 0; //ArrayList<Pokemon> csvPokemon = new ArrayList<Pokemon>(); BufferedReader inputStream = null; if (fileName != null) { try { inputStream = new BufferedReader(new FileReader(fileName)); String l; while ((l = inputStream.readLine()) != null) { if (text == "") { text = l; fields = l.split(","); this.addSecondaryRecord(fields[0], fields[1], Double.parseDouble(fields[2]), Double.parseDouble(fields[3]), fields[4]); count++; } else { text += "\r\n" + l; fields = l.split(","); this.addSecondaryRecord(fields[0], fields[1], Double.parseDouble(fields[2]), Double.parseDouble(fields[3]), fields[4]); } } } catch (FileNotFoundException e) { text = ""; e.printStackTrace(); } catch (IOException e) { text = ""; e.printStackTrace(); } if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
Go
UTF-8
15,474
2.53125
3
[]
no_license
package server import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" "net/http/httputil" "net/url" "strconv" "strings" "testing" "time" "github.com/AlekSi/pointer" serverClient "github.com/percona/pmm/api/serverpb/json/client" "github.com/percona/pmm/api/serverpb/json/client/server" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/grpc/codes" pmmapitests "github.com/Percona-Lab/pmm-api-tests" ) func TestAuth(t *testing.T) { t.Run("AuthErrors", func(t *testing.T) { for user, code := range map[*url.Userinfo]int{ nil: 401, url.UserPassword("bad", "wrong"): 401, } { user := user code := code t.Run(fmt.Sprintf("%s/%d", user, code), func(t *testing.T) { t.Parallel() // copy BaseURL and replace auth baseURL, err := url.Parse(pmmapitests.BaseURL.String()) require.NoError(t, err) baseURL.User = user uri := baseURL.ResolveReference(&url.URL{ Path: "v1/version", }) t.Logf("URI: %s", uri) resp, err := http.Get(uri.String()) require.NoError(t, err) defer resp.Body.Close() //nolint:errcheck b, err := httputil.DumpResponse(resp, true) require.NoError(t, err) assert.Equal(t, code, resp.StatusCode, "response:\n%s", b) require.False(t, bytes.Contains(b, []byte(`<html>`)), "response:\n%s", b) }) } }) t.Run("NormalErrors", func(t *testing.T) { for grpcCode, httpCode := range map[codes.Code]int{ codes.Unauthenticated: 401, codes.PermissionDenied: 403, } { grpcCode := grpcCode httpCode := httpCode t.Run(fmt.Sprintf("%s/%d", grpcCode, httpCode), func(t *testing.T) { t.Parallel() res, err := serverClient.Default.Server.Version(&server.VersionParams{ Dummy: pointer.ToString(fmt.Sprintf("grpccode-%d", grpcCode)), Context: pmmapitests.Context, }) assert.Empty(t, res) pmmapitests.AssertAPIErrorf(t, err, httpCode, grpcCode, "gRPC code %d (%s)", grpcCode, grpcCode) }) } }) } func TestSetup(t *testing.T) { // make a BaseURL without authentication baseURL, err := url.Parse(pmmapitests.BaseURL.String()) require.NoError(t, err) baseURL.User = nil // make client that does not follow redirects client := &http.Client{ CheckRedirect: func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }, } t.Run("WebPage", func(t *testing.T) { t.Parallel() uri := baseURL.ResolveReference(&url.URL{ Path: "/setup", }) t.Logf("URI: %s", uri) req, err := http.NewRequestWithContext(pmmapitests.Context, "GET", uri.String(), nil) require.NoError(t, err) req.Header.Set("X-Test-Must-Setup", "1") resp, b := doRequest(t, client, req) assert.Equal(t, 200, resp.StatusCode, "response:\n%s", b) assert.True(t, strings.HasPrefix(string(b), `<!doctype html>`), string(b)) }) t.Run("Redirect", func(t *testing.T) { paths := map[string]int{ "graph": 303, "graph/": 303, "prometheus": 303, "prometheus/": 303, "swagger": 200, "swagger/": 301, "v1/readyz": 200, "v1/AWSInstanceCheck": 405, // only POST is expected "v1/version": 401, // Grafana authentication required } for path, code := range paths { path, code := path, code t.Run(fmt.Sprintf("%s=%d", path, code), func(t *testing.T) { t.Parallel() uri := baseURL.ResolveReference(&url.URL{ Path: path, }) t.Logf("URI: %s", uri) req, err := http.NewRequestWithContext(pmmapitests.Context, "GET", uri.String(), nil) require.NoError(t, err) req.Header.Set("X-Test-Must-Setup", "1") resp, b := doRequest(t, client, req) assert.Equal(t, code, resp.StatusCode, "response:\n%s", b) if code == 303 { assert.Equal(t, "/setup", resp.Header.Get("Location")) } }) } }) t.Run("API", func(t *testing.T) { t.Parallel() uri := baseURL.ResolveReference(&url.URL{ Path: "v1/AWSInstanceCheck", }) t.Logf("URI: %s", uri) b, err := json.Marshal(server.AWSInstanceCheckBody{ InstanceID: "123", }) require.NoError(t, err) req, err := http.NewRequestWithContext(pmmapitests.Context, "POST", uri.String(), bytes.NewReader(b)) require.NoError(t, err) req.Header.Set("X-Test-Must-Setup", "1") resp, b := doRequest(t, client, req) assert.Equal(t, 200, resp.StatusCode, "response:\n%s", b) assert.Equal(t, "{\n\n}", string(b), "response:\n%s", b) }) } func TestSwagger(t *testing.T) { for _, path := range []string{ "swagger", "swagger/", "swagger.json", "swagger/swagger.json", } { path := path t.Run(path, func(t *testing.T) { t.Run("NoAuth", func(t *testing.T) { t.Parallel() // make a BaseURL without authentication baseURL, err := url.Parse(pmmapitests.BaseURL.String()) require.NoError(t, err) baseURL.User = nil uri := baseURL.ResolveReference(&url.URL{ Path: path, }) t.Logf("URI: %s", uri) req, err := http.NewRequestWithContext(pmmapitests.Context, "GET", uri.String(), nil) require.NoError(t, err) resp, _ := doRequest(t, http.DefaultClient, req) require.NoError(t, err) assert.Equal(t, 200, resp.StatusCode) }) t.Run("Auth", func(t *testing.T) { t.Parallel() uri := pmmapitests.BaseURL.ResolveReference(&url.URL{ Path: path, }) t.Logf("URI: %s", uri) req, err := http.NewRequestWithContext(pmmapitests.Context, "GET", uri.String(), nil) require.NoError(t, err) resp, _ := doRequest(t, http.DefaultClient, req) require.NoError(t, err) assert.Equal(t, 200, resp.StatusCode) }) }) } } func TestPermissions(t *testing.T) { ts := strconv.FormatInt(time.Now().Unix(), 10) none := "none-" + ts viewer := "viewer-" + ts editor := "editor-" + ts admin := "admin-" + ts noneID := createUser(t, none) defer deleteUser(t, noneID) viewerID := createUserWithRole(t, viewer, "Viewer") defer deleteUser(t, viewerID) editorID := createUserWithRole(t, editor, "Editor") defer deleteUser(t, editorID) adminID := createUserWithRole(t, admin, "Admin") defer deleteUser(t, adminID) viewerAPIKeyID, viewerAPIKey := createAPIKeyWithRole(t, "api-"+viewer, "Viewer") defer deleteAPIKey(t, viewerAPIKeyID) editorAPIKeyID, editorAPIKey := createAPIKeyWithRole(t, "api-"+editor, "Editor") defer deleteAPIKey(t, editorAPIKeyID) adminAPIKeyID, adminAPIKey := createAPIKeyWithRole(t, "api-"+admin, "Admin") defer deleteAPIKey(t, adminAPIKeyID) type userCase struct { userType string login string apiKey string statusCode int } tests := []struct { name string url string method string userCase []userCase }{ {name: "settings", url: "/v1/Settings/Get", method: "POST", userCase: []userCase{ {userType: "default", login: none, statusCode: 401}, {userType: "viewer", login: viewer, apiKey: viewerAPIKey, statusCode: 401}, {userType: "editor", login: editor, apiKey: editorAPIKey, statusCode: 401}, {userType: "admin", login: admin, apiKey: adminAPIKey, statusCode: 200}, }}, {name: "alerts-default", url: "/alertmanager/api/v2/alerts", method: "GET", userCase: []userCase{ {userType: "default", login: none, statusCode: 401}, {userType: "viewer", login: viewer, apiKey: viewerAPIKey, statusCode: 401}, {userType: "editor", login: editor, apiKey: editorAPIKey, statusCode: 401}, {userType: "admin", login: admin, apiKey: adminAPIKey, statusCode: 200}, }}, {name: "platform-sign-up", url: "/v1/Platform/SignUp", method: "POST", userCase: []userCase{ {userType: "default", login: none, statusCode: 401}, {userType: "viewer", login: viewer, apiKey: viewerAPIKey, statusCode: 401}, {userType: "editor", login: editor, apiKey: editorAPIKey, statusCode: 401}, {userType: "admin", login: admin, apiKey: adminAPIKey, statusCode: 400}, // We send bad request, but have access to endpoint }}, {name: "platform-sign-in", url: "/v1/Platform/SignIn", method: "POST", userCase: []userCase{ {userType: "default", login: none, statusCode: 401}, {userType: "viewer", login: viewer, apiKey: viewerAPIKey, statusCode: 401}, {userType: "editor", login: editor, apiKey: editorAPIKey, statusCode: 401}, {userType: "admin", login: admin, apiKey: adminAPIKey, statusCode: 400}, // We send bad request, but have access to endpoint }}, {name: "platform-sign-out", url: "/v1/Platform/SignOut", method: "POST", userCase: []userCase{ {userType: "default", login: none, statusCode: 401}, {userType: "viewer", login: viewer, apiKey: viewerAPIKey, statusCode: 401}, {userType: "editor", login: editor, apiKey: editorAPIKey, statusCode: 401}, {userType: "admin", login: admin, apiKey: adminAPIKey, statusCode: 400}, // We send bad request, but have access to endpoint }}, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { for _, user := range test.userCase { user := user t.Run(fmt.Sprintf("Basic auth %s", user.userType), func(t *testing.T) { // make a BaseURL without authentication u, err := url.Parse(pmmapitests.BaseURL.String()) require.NoError(t, err) u.User = url.UserPassword(user.login, user.login) u.Path = test.url req, err := http.NewRequestWithContext(pmmapitests.Context, test.method, u.String(), nil) require.NoError(t, err) resp, err := http.DefaultClient.Do(req) require.NoError(t, err) defer resp.Body.Close() //nolint:errcheck assert.Equal(t, user.statusCode, resp.StatusCode) }) t.Run(fmt.Sprintf("API Key auth %s", user.userType), func(t *testing.T) { if user.apiKey == "" { t.Skip("API Key is not exist") } // make a BaseURL without authentication u, err := url.Parse(pmmapitests.BaseURL.String()) require.NoError(t, err) u.User = nil u.Path = test.url req, err := http.NewRequestWithContext(pmmapitests.Context, test.method, u.String(), nil) require.NoError(t, err) req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", user.apiKey)) resp, err := http.DefaultClient.Do(req) require.NoError(t, err) defer resp.Body.Close() //nolint:errcheck assert.Equal(t, user.statusCode, resp.StatusCode) }) t.Run(fmt.Sprintf("API Key Basic auth %s", user.userType), func(t *testing.T) { if user.apiKey == "" { t.Skip("API Key is not exist") } // make a BaseURL without authentication u, err := url.Parse(pmmapitests.BaseURL.String()) require.NoError(t, err) u.User = url.UserPassword("api_key", user.apiKey) u.Path = test.url req, err := http.NewRequestWithContext(pmmapitests.Context, test.method, u.String(), nil) require.NoError(t, err) resp, err := http.DefaultClient.Do(req) require.NoError(t, err) defer resp.Body.Close() //nolint:errcheck assert.Equal(t, user.statusCode, resp.StatusCode) }) } }) } } func doRequest(t testing.TB, client *http.Client, req *http.Request) (*http.Response, []byte) { resp, err := client.Do(req) require.NoError(t, err) defer resp.Body.Close() //nolint:errcheck b, err := ioutil.ReadAll(resp.Body) require.NoError(t, err) return resp, b } func createUserWithRole(t *testing.T, login, role string) int { userID := createUser(t, login) setRole(t, userID, role) return userID } func deleteUser(t *testing.T, userID int) { u, err := url.Parse(pmmapitests.BaseURL.String()) require.NoError(t, err) u.Path = "/graph/api/admin/users/" + strconv.Itoa(userID) req, err := http.NewRequestWithContext(pmmapitests.Context, http.MethodDelete, u.String(), nil) require.NoError(t, err) resp, b := doRequest(t, http.DefaultClient, req) require.Equalf(t, http.StatusOK, resp.StatusCode, "failed to delete user, status code: %d, response: %s", resp.StatusCode, b) } func createUser(t *testing.T, login string) int { u, err := url.Parse(pmmapitests.BaseURL.String()) require.NoError(t, err) u.Path = "/graph/api/admin/users" // https://grafana.com/docs/http_api/admin/#global-users data, err := json.Marshal(map[string]string{ "name": login, "email": login + "@percona.invalid", "login": login, "password": login, }) require.NoError(t, err) req, err := http.NewRequestWithContext(pmmapitests.Context, http.MethodPost, u.String(), bytes.NewReader(data)) require.NoError(t, err) req.Header.Set("Content-Type", "application/json; charset=utf-8") resp, b := doRequest(t, http.DefaultClient, req) require.Equalf(t, http.StatusOK, resp.StatusCode, "failed to create user, status code: %d, response: %s", resp.StatusCode, b) var m map[string]interface{} err = json.Unmarshal(b, &m) require.NoError(t, err) return int(m["id"].(float64)) } func setRole(t *testing.T, userID int, role string) { u, err := url.Parse(pmmapitests.BaseURL.String()) require.NoError(t, err) u.Path = "/graph/api/org/users/" + strconv.Itoa(userID) // https://grafana.com/docs/http_api/org/#updates-the-given-user data, err := json.Marshal(map[string]string{ "role": role, }) require.NoError(t, err) req, err := http.NewRequestWithContext(pmmapitests.Context, http.MethodPatch, u.String(), bytes.NewReader(data)) require.NoError(t, err) req.Header.Set("Content-Type", "application/json; charset=utf-8") resp, b := doRequest(t, http.DefaultClient, req) require.Equalf(t, http.StatusOK, resp.StatusCode, "failed to set role for user, response: %s", b) } func deleteAPIKey(t *testing.T, apiKeyID int) { // https://grafana.com/docs/grafana/latest/http_api/auth/#delete-api-key u, err := url.Parse(pmmapitests.BaseURL.String()) require.NoError(t, err) u.Path = "/graph/api/auth/keys/" + strconv.Itoa(apiKeyID) req, err := http.NewRequestWithContext(pmmapitests.Context, http.MethodDelete, u.String(), nil) require.NoError(t, err) resp, b := doRequest(t, http.DefaultClient, req) require.Equalf(t, http.StatusOK, resp.StatusCode, "failed to delete API Key, status code: %d, response: %s", resp.StatusCode, b) } func createAPIKeyWithRole(t *testing.T, name, role string) (int, string) { u, err := url.Parse(pmmapitests.BaseURL.String()) require.NoError(t, err) u.Path = "/graph/api/auth/keys" // https://grafana.com/docs/grafana/latest/http_api/auth/#create-api-key data, err := json.Marshal(map[string]string{ "name": name, "role": role, }) require.NoError(t, err) req, err := http.NewRequestWithContext(pmmapitests.Context, http.MethodPost, u.String(), bytes.NewReader(data)) require.NoError(t, err) req.Header.Set("Content-Type", "application/json; charset=utf-8") resp, b := doRequest(t, http.DefaultClient, req) require.Equalf(t, http.StatusOK, resp.StatusCode, "failed to create API key, status code: %d, response: %s", resp.StatusCode, b) var m map[string]interface{} err = json.Unmarshal(b, &m) require.NoError(t, err) apiKey := m["key"].(string) u.User = nil u.Path = "/graph/api/auth/key" req, err = http.NewRequestWithContext(pmmapitests.Context, http.MethodGet, u.String(), bytes.NewReader(data)) require.NoError(t, err) req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", apiKey)) resp, b = doRequest(t, http.DefaultClient, req) require.Equalf(t, http.StatusOK, resp.StatusCode, "failed to get API key, status code: %d, response: %s", resp.StatusCode, b) var k map[string]interface{} err = json.Unmarshal(b, &k) require.NoError(t, err) apiKeyID := int(k["id"].(float64)) return apiKeyID, apiKey }
Markdown
UTF-8
3,601
2.640625
3
[]
no_license
## Описание проекта Телеграм бот для получения задач и их обновлений с аккаунта Яндекс.Трекера. ## Как установить Для начала устанавливаме сам код. Для этого в командной строке, в нужной нам папке вводим `git clone https://github.com/Glicher-wp/Telegram_bot_by_startrack.git`. Предварительно убедитесь, что у вас установлен **git**. после этого, создаем виртуальное окружение и вводим команду `pip install -r rquirements.txt`. После чего будут установлены все необходимые библиотеки. Дальше нам нужно получить необходимые для работы **токены** ### Получение токена Telegram Здесь все просто, идем в наш Telegram (предварительно не забыв его установить) и находим там **@BotFather**. ![куда-то делось изображение](https://png.cmtt.space/paper-media/24/a0/9c/1b28d2e0b91a8e.png) Далее следуем инстркциям и получаем от него **токен** для своего бота. Подставляем его в `TELEGRAM_TOKEN = os.environ.get("TELEGRAM_TOKEN")`. ### Получение задач После этого нам остается только настроить фильтр на нужную очередь, **ключ** которой мы подставим в строку поиска `issue_filter = 'issues?filter=queue:<**ключ очереди**>&' \ f'filter=assignee:me()&' \ f'filter=status:open&'`. Переменная нахдится в модуле **config.py** и по-умолчанию там стоит очередь **PCR**. Сам ключ находится в адрессной строке, либо его можно увидеть при создании задачи. Он представляет из себя заглавные латинские буквы. Теперь бот готов. Остается только запустить его: `python telegram_bot_logic.py` ## Как пользоваться Бот использует api СтарТрека поэтому для работы требуетс только **token** очереди. Получить его можно зайдя из под соответвствующего аккаунта (т.е. из под аккаунта, который подключен к их системе и у которого есть доступ к этому токену). Бот принимает **token** пользователя Яндекс.Трекера и возвращает ему список текущих задача, после чего предлагает каждые 20 минут получать собщения об обновленных задачах, если таковые появляются. Для командного взаимодействия с ботом используются команды: `/start`, `/status`, `/cancel`. Которые запускают работу бота, возвращают всю статистику по задачам, и завершают работу бота, соответственно. Остальные данные бот получает из текстовых сообщений.
Markdown
UTF-8
9,642
3.1875
3
[]
no_license
--- layout: blog title: "Week 7: Advanced models 1, part b" --- ## Character-based RNN with convolution This week, we spent some more time working on that character RNN model after adding a convolution layer (with max pooling) on all the cells' hidden states. With the added convolution, the model now actually trains, and seems to perform about as well as the word RNN model. The model seems to overfit much more than before, so we experimented with adding dropout to the RNN. **No dropout:** | Accuracy | Precision | Recall | F1 | ROC | Spearman | | -------- | --------- | ------ | -- | --- | -------- | | 0.9315 | 0.8542 | 0.7980 | 0.8228 | 0.9251 | 0.6499 | Confusion matrix: ``` [[19858 547] [ 1039 1716]] ``` **0.1 dropout:** | Accuracy | Precision | Recall | F1 | ROC | Spearman | | -------- | --------- | ------ | -- | --- | -------- | | 0.9369 | 0.8676 | 0.8136 | 0.8376 | 0.9369 | 0.6791 | Confusion matrix: ``` [[19902 503] [ 959 1796]] ``` **0.2 dropout:** | Accuracy | Precision | Recall | F1 | ROC | Spearman | | -------- | --------- | ------ | -- | --- | -------- | | 0.9372 | 0.8810 | 0.7977 | 0.8323 | 0.9384 | 0.6735 | Confusion matrix: ``` [[20014 391] [ 1062 1693]] ``` We also tried reducing the size of the hidden state; results seem mixed; it seems likely that the reduced size performs just as well and that the difference is just normal variance, but it's a little hard to say. **0.2 dropout, 50 hidden state size (down from 120)** | Accuracy | Precision | Recall | F1 | ROC | Spearman | | -------- | --------- | ------ | -- | --- | -------- | | 0.9367 | 0.8892 | 0.7852 | 0.8265 | 0.9367 | 0.6664 | Confusion matrix: ``` [[20079 326] [ 1139 1616]] ``` ### Error analysis Based on a few comments from the dev set, the character RNN does seem to do a better job at detecting slightly altered versions of profanity and such: for the comment > ' JEFFREY MALL IS A NIG GER' The char RNN output 0.9891 probability of attack, whereas the word RNN only had 0.2256. Incidentally, the actual proportion of human reviews who thought this was an attack was 0.3333, which brings up the first issue of borderline attacks. As expected, when even humans don't have consensus on whether a given comment is an attack, it's a little unreasonable to expect the model to do much better, but the model has a tendency to give borderline attacks a much higher attack probability than the proportion of human reviews. (Note: for all following examples, the left number is the proportion of reviewers who voted for attack in the dataset, and the right is the probability of attack output from the model) 0.444444 0.856087 ' Hahahahahaha you blocked me from Wikipedia because I hurt your feelings LOL' 0.500000 0.997663 ' == WikiDicks == Nothing any of you old scholarly wannabe fucks can say about my article will negatively affect me more than this case has. Have fun with your lame old selves.' For many of these borderline cases, it definitely feels like the model's output is closer to the expected value than the reviewers', suggesting that perhaps we should be thresholding attacks vs. non-attacks from the proportion of reviewers a little lower, maybe at 30% instead of the current 50%. Beyond that, there are many cases of the model being over-eager to classify short comments as attacks. For some of these, it seems that the model might be fabricating some context, or perhaps reading things sarcastically, since it's not too difficult to imagine some context where the comments could be interpreted as attacks. The high confidence it has that they are attacks is a little concerning, though. 0.000000 0.966435 " : You're such a wise woman " 0.000000 0.918345 ' oops ill give u the pass to mine if u get on yours' 0.000000 0.982325 ' == Yo. 2 == *Currently hitting up*' 0.000000 0.763677 ' ==DO NOT ERASE MY WORK UNTIL I AM FINISHED==' 0.000000 0.587889 ' You missed one. We can play this game all night' And then there are some examples of the model treating some ordinarily neutral words as bad since they are often used that way (e.g. race, wiki edits/revisions) 0.000000 0.649757 b' He looks very Jewish also if you can imagine him with a shaggy beard and some dark hair. ' Or failing to pick up that bad words are used neutrally. 0.500000 0.985445 b" == Guys I'm fucking bored give me something to do == Guys I'm fucking bored give me something to do" 0.000000 0.906188 b' ==Thats my name== You have blocked me but Kshitij is a Indian name. How can i change my name?? ( )' Also, the model might be associating unknown characters with attacks (since only the most frequent 100 characters in the training set are recognized). 0.000000 0.661663 b'` :Looks like it was here. By the way, your Mandarin pinyin is a bit off, \xe6\xb0\x91 is m\xc3\xadn, not ming. \xc2\xa0 `' On a bit of a side note, the model does some weird things with repeated characters or sequences of characters, but these numbers don't mean much on their own since, as mentioned already, the model doesn't work as well on short comments: 1.0 "fuck" 0.99999952 "fu ck" 0.78159362 "fu ck" 0.99647254 "fu ck" ## Additional Word RNN Improvements We also continued to work on improving the accuracy of our word RNN model, this time trying to specifically decrease the rate of false negatives. In particular, we wanted to see if we could try and more accurately classify attacks at the expense of sometimes misclassifying non-aggressive comments. As before, we had only incremental improvement -- our best results are still our baseline model: | Accuracy | Precision | Recall | F1 | ROC | Spearman | | -------- | --------- | ------ | -- | --- | -------- | | 0.9272 | 0.8236 | 0.8354 | 0.8294 | 0.9175 | 0.6589 | Here is the corresponding confusion matrix: | | Predicted OK | Predicted Attack | | | ----------- | ---------- | | **Actual OK** | 19503 | 902 | | **Actual Attack** | 785 | 1970 | We also attempted to merge all of the output states of our RNN instead of just looking at the last result, but that yielded in worse performance -- our model more or less became incapable of accurately categorizing attacks. This was not a terribly surprising result: | Accuracy | Precision | Recall | F1 | ROC | Spearman | | -------- | --------- | ------ | -- | --- | -------- | | 0.9144 | 0.8133 | 0.7384 | 0.7687 | 0.8767 | 0.5465 | Confusion matrix: | | Predicted OK | Predicted Attack | | | ----------- | ---------- | | **Actual OK** | 19779 | 626 | | **Actual Attack** | 1357 | 1398 | ## Aggression removal We also experimented with the "remove aggression" filter we discussed last week. To recap, our idea was to try and rewrite existing comments to try and remove aggression. To do this, our idea was to: Train an autoencoder on comments Modify the loss function so it tries to simultaneously minimize the softmax sequence loss against the aggression or attack score (which is computed by one of our pre-trained model) See what happens (??) Currently, we're obtaining suboptimal results -- we decided to start by training just the auto-encoder as a sanity measure, but our model ultimately generates gibberish results -- a string of mostly repeated and gibberish text. Our loss is also relatively flat/not improving, which is unfortunate. This may partially be because we're training on a small subset of our dataset for debugging purposes (1 epoch takes around 22 mins when using the full dataset), partially due to implementation errors, and partially because we haven't implemented attention yet. ## Feature inspection and error analysis Out of curiosity, we also decided to try cracking open our bag-of-words model to analyze which unigrams and bigrams were most associated with positivity and negativity. The results were mostly predictable -- attacks focused around profanity. One somewhat interesting thing was that the most positive results tended to be focused around meta-discussion of wikipedia itself -- for example, see the bigram table below: | Unigram | Probability OK | Probability Attack | | Bigram | Probability OK | Probability Attack | | ------- | -------------- | -------------------| | ------ | -------------- | ------------------ | | thank | 0.9952 | 0.0047 || redirect talk | 0.9965 | 0.0034 | | article | 0.9950 | 0.0049 || the article | 0.9963 | 0.0036 | | thanks | 0.9950 | 0.0049 || this article | 0.9949 | 0.0050 | | could | 0.9944 | 0.0055 || thanks for | 0.9939 | 0.0060 | | please | 0.9943 | 0.0056 || that there | 0.9917 | 0.0082 | | section | 0.9930 | 0.0069 || but not | 0.9912 | 0.0087 | | agree | 0.9930 | 0.0069 || for the | 0.9910 | 0.0089 | | welcome | 0.9923 | 0.0076 || article for | 0.9907 | 0.0092 | | there | 0.9922 | 0.0077 || thank you | 0.9906 | 0.0093 | | but | 0.9922 | 0.0077 || agree with | 0.9905 | 0.0094 | | ...snip... | N/A | N/A || ...snip... | N/A | N/A | | suck | 0.0203 | 0.9796 || bitch fuck | 0.0033 | 0.9966 | | bitch | 0.0145 | 0.9854 || you fuck | 0.0031 | 0.9968 | | you | 0.0121 | 0.9878 || fuck yourself | 0.0030 | 0.9969 | | asshole | 0.0095 | 0.9904 || fucking asshole | 0.0019 | 0.9980 | | ass | 0.0071 | 0.9928 || go fuck | 0.0011 | 0.9988 | | shit | 0.0041 | 0.9958 || you fucking | 9.2084e-04 | 9.9907e-01 | | stupid | 0.0011 | 0.9988 || fuck fuck | 6.7426e-04 | 9.9932e-01 | | idiot | 7.4736e-04 | 9.9925e-01 || fuck off | 6.6430e-04 | 9.9933e-01 | | fucking | 8.3943e-05 | 9.9991e-01 || the fuck | 5.1976e-04 | 9.9948e-01 | | fuck | 1.9916e-05 | 9.9998e-01 || fuck you | 5.8870e-05 | 9.9994e-01 |
Markdown
UTF-8
1,213
2.9375
3
[]
no_license
## About This package was made in preparation for the clas INFO 550. It stores a data rda object named "trachoma_data", several functions that clean data and make figures, as well as a vignette. The tidyverse and rmarkdown packages were used to build this package. You will need to install the devtools package to download this package using the code below. ## Install To install the package, please run the following code. This code was specifically tailored to download the vignette as well because this does not happen by default. When prompted to enter a number to continue, please enter the number that makes the most sense to you. More than likely, your tidyverse is already updated so you can enter **3** which skips this updating step. **devtools::install_github("pahongle/tfreport", build_vignettes = TRUE)** ## Functions There are two functions in this package. The first one is **tf_clean()**. This will clean the included **trachoma_data**. The second function is **tf_fig()**. This makes a figure based on the clean data. ## Vignette To see the vignette with the associated report, please run the following code after installing the package. **vignette("trachoma_report", package="tfreport")**
Java
UTF-8
2,171
2.578125
3
[]
no_license
package krk.smog.entity; import org.springframework.data.annotation.Id; import java.time.Instant; import krk.smog.external.airly.model.IndexLevel; import krk.smog.external.airly.model.IndexName; /** * Entity object for persisting AirQuality info in MongoDB. */ public class AirQuality { @Id public String id; /** * Left bound of the time period over which average measurements were calculated, inclusive, * always UTC. */ public Instant fromDateTime; /** * Right bound of the time period over which average measurements were calculated, exclusive, * always UTC. */ public Instant tillDateTime; /** * Name of this index. */ public IndexName indexName; /** * Index numerical value. */ public Double value; /** * Index level indexName. */ public IndexLevel level; /** * Text describing this air quality level. Text translation is returned according to language * specified in the request (English being default). */ public String description; /** * Piece of advice from Airly regarding air quality. Text translation is returned according to * language specified in the request (English being default). */ public String advice; /** * Color representing this index level, given by hexadecimal css-style triplet. */ public String color; public AirQuality() { } @Override public String toString() { return "AirQuality{" + "id='" + id + '\'' + ", fromDateTime=" + fromDateTime + ", tillDateTime=" + tillDateTime + ", indexName=" + indexName + ", value=" + value + ", level=" + level + ", description='" + description + '\'' + ", advice='" + advice + '\'' + ", color='" + color + '\'' + '}'; } }
Markdown
UTF-8
4,616
2.734375
3
[]
no_license
--- description: "Recipe of Quick Perfect Lobster!" title: "Recipe of Quick Perfect Lobster!" slug: 213-recipe-of-quick-perfect-lobster date: 2020-09-19T09:49:12.634Z image: https://img-global.cpcdn.com/recipes/5477302191259648/751x532cq70/perfect-lobster-recipe-main-photo.jpg thumbnail: https://img-global.cpcdn.com/recipes/5477302191259648/751x532cq70/perfect-lobster-recipe-main-photo.jpg cover: https://img-global.cpcdn.com/recipes/5477302191259648/751x532cq70/perfect-lobster-recipe-main-photo.jpg author: Elmer Howard ratingvalue: 3.8 reviewcount: 10 recipeingredient: - "4 Lobster Tails I use frozen thaw according to directions" - "4 tbsp butter" - "1/2 tsp paprika" - "1/8 tsp garlic powder" - "1 pinch of cayenne pepper" - "1/4 tsp salt" recipeinstructions: - "Microwave butter and seasonings for about 1 minute until butter is melted. Stir. Preheat oven to 400." - "Use a pair of shears/scissors and cut a straight line down the top of the tail shell until you reach the fan-shaped portion of the tail. (its ok if some of the meat is cut)" - "Fold a paper towel in half. Lay the lobster tail on its side and wrap the other half of the paper towel over the top of the lobster. Press down on the shell with your palm until the tail cracks." - "Open the shell of the tail like a book and using your fingers pull the meat up and out of the shell. Keep the meat near the tail still attached." - "Push the sides of shell back together and lay the meat ontop of the shell. Use shears/knive to finish butterflying the top of the meat." - "Cut two pieces of foil a bit larger than the tails. Place tails on foil and brush marinade on top of meat." - "Lift one layer of lobster up and fold to create a pocket around the lobster and repeat with second sheet of foil. Place on baking sheet according to chart above!" categories: - Recipe tags: - perfect - lobster katakunci: perfect lobster nutrition: 154 calories recipecuisine: American preptime: "PT25M" cooktime: "PT54M" recipeyield: "3" recipecategory: Dinner --- ![Perfect Lobster!](https://img-global.cpcdn.com/recipes/5477302191259648/751x532cq70/perfect-lobster-recipe-main-photo.jpg) Hey everyone, hope you're having an amazing day today. Today, I will show you a way to make a distinctive dish, perfect lobster!. It is one of my favorites food recipes. For mine, I'm gonna make it a bit unique. This will be really delicious. Perfect Lobster! is one of the most well liked of current trending meals on earth. It's simple, it is fast, it tastes yummy. It is enjoyed by millions every day. Perfect Lobster! is something that I have loved my entire life. They're fine and they look wonderful. To get started with this particular recipe, we must first prepare a few components. You can have perfect lobster! using 6 ingredients and 7 steps. Here is how you cook it. <!--inarticleads1--> ##### The ingredients needed to make Perfect Lobster!: 1. Prepare 4 Lobster Tails (I use frozen) thaw according to directions 1. Make ready 4 tbsp butter 1. Take 1/2 tsp paprika 1. Take 1/8 tsp garlic powder 1. Prepare 1 pinch of cayenne pepper 1. Prepare 1/4 tsp salt <!--inarticleads2--> ##### Instructions to make Perfect Lobster!: 1. Microwave butter and seasonings for about 1 minute until butter is melted. Stir. Preheat oven to 400. 1. Use a pair of shears/scissors and cut a straight line down the top of the tail shell until you reach the fan-shaped portion of the tail. (its ok if some of the meat is cut) 1. Fold a paper towel in half. Lay the lobster tail on its side and wrap the other half of the paper towel over the top of the lobster. Press down on the shell with your palm until the tail cracks. 1. Open the shell of the tail like a book and using your fingers pull the meat up and out of the shell. Keep the meat near the tail still attached. 1. Push the sides of shell back together and lay the meat ontop of the shell. Use shears/knive to finish butterflying the top of the meat. 1. Cut two pieces of foil a bit larger than the tails. Place tails on foil and brush marinade on top of meat. 1. Lift one layer of lobster up and fold to create a pocket around the lobster and repeat with second sheet of foil. Place on baking sheet according to chart above! So that's going to wrap it up for this exceptional food perfect lobster! recipe. Thank you very much for reading. I'm sure you can make this at home. There's gonna be interesting food in home recipes coming up. Don't forget to bookmark this page on your browser, and share it to your loved ones, colleague and friends. Thanks again for reading. Go on get cooking!
Markdown
UTF-8
40,457
2.90625
3
[ "MulanPSL-2.0", "LicenseRef-scancode-mulanpsl-2.0-en", "LicenseRef-scancode-unknown-license-reference" ]
permissive
--- --- --- title: 现代教育机构的出现,1898—1928年 --- 为了便于分析,我们将依次考察人员培训,某些主要教育机构的形成,以及研究和财政资助。对每一情况,我们的探讨都试图从尚未充分考察的领域把有代表性的例证提供出来。省办和市办的教育机构以及技术、职业教育机构大都处于我们的视界之外。[4] 人员:海外培训的精英 高等教育建设的领导者们是真正杰出的一群,他们对非常时代的需要作出了反应。当中国的现代变革需要创立一个可以与出现在其他国家的新制度相比的高等教育制度时,这意味着培养学贯中西的新的学者阶层——一种对悠久传统的真正革命性的决裂。中国人能够而且确实必须向外国人学习,这一观点极富革命性,但与日本和印度等国相比,1860年后中国在这一方面的努力,却显得比较少而收效不大。清政府无法在国内提供现代学校,也无力控制派往东京的中国留学生,事实上这成为清朝覆灭的一个主要原因。新的教育精英从而在这个变革的时代里成熟起来。在建立新学校的过程中,他们感到自己是新世界的创造者,决不是现有机构的维护者。当缠足作为保持妇女顺从的一种古老方法,仍在中国广泛流行时,不难想象那些涉足高等教育的中国妇女的冒险精神和决心。 多种因素塑造了这些教育家。首先,他们一般都是在外国受教育的男子和妇女。以梁启超(1873—1929年)为代表的一代到日本寻求西学,以胡适(1891—1962年)为代表的一代则到西欧和美国。这次留学的规模有多大还不完全知道,因为,举例来说,在日本院校注册的中国学生大大超过毕业生。据估计,1900—1937年的注册生为13.6万人,而1901—1939年从日本各类学校毕业的中国学生的最适当数字是1.2万人。[5]留日学生所作的政治贡献在1911年的革命史中极为突出;他们在学术上的贡献却普遍受到忽视。1915年后日本的扩张政策导致反日运动日益高涨以及中国的民族主义日益上升,都掩盖了中国在学术上受惠于日本;今后的研究无疑会发掘这一问题并予以评价。[6] 中日对抗有助于共和中国的学者转向西欧和美国。中国学生长途跋涉来到西方,需要更多的经费,因此选拔得更加仔细,具有更明确的义务,也更有可能完成学业。有一个估计数字是1854—1953年一个世纪内中国留美学生达2.1万人。[7] 然而,这些数字可能需要进一步推敲和分析,很明显,20世纪从西方回国的两万左右中国留学生是一个人数甚少但颇有能量的群体。他们在大约四亿人口中所占的比例与旧政权的进士一样少。他们的前辈三年一次在北京考试,习惯地接受对皇帝——他名义上主持殿试——效忠的人身约束,而这些民国的学者们则觉得,他们的国外经验坚定了他们对中华民族的忠诚。这些新的“留学生”精英更加铭记宋代改革家范仲淹的格言:“先天下之忧而忧,后天下之乐而乐。”[8]留学生涉足政府、工业、自由职业、艺术和教育等领域的比例尚不清楚,但显然他们都享有从旧习俗和现代革命得来的特殊地位。他们在广泛的人际关系网中发挥作用。那些选择从事建立高等教育制度的人坚持传统,认为学者并非仅仅是技术专家,他必须像政治家那样代表整个社会——亦官亦民——去思考。这种社会责任感有助于从欧美回来的新的领导者建立起来早期共和国的学术机构——一个20世纪的国家所需的学院、大学、图书馆、实验室和研究所。 他们是遴选出来的(或自我选拔出来的)少数在学术上达到了最高水平的人,然而他们的这种特殊地位并非完全是幸事。他们的国外经历——为了获得博士学位,通常需要几年时间——导致了这些自由化的知识分子陷入世界性不可避免的矛盾心理状态。[9]同所有在国外学习的人一样,他们在某种程度上具有双重文化,既熟悉中国的精英文化,也熟悉外部世界的精英文化。他们作为学者的精英地位,加上熟悉异国方式,使他们与乡村中国愈加格格不入。他们建立了与西方人文学科传统的共同纽带,这一事实保证了新文化运动在教育方面不仅促进传播技术,而且它尖锐地引出了一些问题,即在事实上,也在(同等重要)中国的军政要人的眼中,如何使他们在外国受到的训练发挥作用,并切合中国的实际。正是这些要人被要求给予教育家们以不断的支持。[10]同时,有些学者感到他们的外国倾向有使他们脱离自己背景的危险,即一种游离于祖国社会的失落感,简言之,即精神上的颓废和情感上的疏远。双重文化的经历能搅乱一个人的个性。这一问题的程度有多深尚不清楚。它对于许多“五四”运动的一代人可能更为突出,他们事实上具有三重教育背景:中国的(传统的和早期现代的),日本的和欧美的。 因此,引进外国知识(技术方面的和价值观方面的)的任务无论在内还是在外都很复杂。在内,他是受过外国训练的教育家,必须设计出如何作出最大贡献的自我形象。同时,处于他的环境,他可能面对他应该如何作为的十分不同的期望。[11]现代教育的一个新特点是行政负担。住宿学校和不久出现的男女同校是一种新现象,有一种能诱发导致罢课和政治运动的学生舆论和组织的无限能量。共和国的新学生与教师一样关心民族命运并负有责任感。他们时常要求采取政治行动。教育精英们从事的活动从注表可略见一斑。只有极少数人能够潜心追求纯学术。维持学校运转始终是个问题。 教育家作为一个群体迟早也会面临他们与政府当局的关系问题。持续了1200年的政府考试制度到1905年才被废除,受西方训练的教育家在它的阴影下劳动,他们继承了多少代以来困扰着中国旧学者的价值观和问题,同时他们又有在国外遇到的新的价值观和新模式。到30年代,他们成功地创造了较为自主的和多样化的高等教育体系,较少直接受到政府和官方正统观念的控制。然而这只是军阀混战年代既无中央政府也无正统观念的暂时情况。由于学者一政府的传统,中国的教育一直与政治纠缠在一起。高等教育过去一直是为统治阶层的,不是为平民百姓的。要使它从国家的正统观念解脱出来是不容易的。这就不难理解脱离政治的较为独立的教育形式的成长为什么时断时续,游移不定了。 此外,民国初年教育不仅得益于中央政权的软弱,也得益于帝国主义列强的多元化影响。外国人在华利益包括通过基督教教会院校以及设立自主的教育基金二者来扶植现代教育,二者都受治外法权保护。1912年至1949年中国的学术发展可以被看作世界范围的现代知识兴起的一部分,南北美洲人、俄国人、日本人和印度人或迟或早全转向西欧寻求启蒙。然而受过教育的中国精英们涉足国际世界的一个副作用是他们易遭排外者的攻击,被指责为受外国指挥。这些在外国受过教育的接受双重文化、能讲两种语言的精英所付出的代价是,在祖国有时感到或显得是陌生人,甚至像是受雇于外国的人。 归国留学生在中国和国外的经历所形成的心理上和知识上的压力,使他们一代中某些有政治头脑的一翼转向马克思主义。倾向于学术的一翼也需要新的信仰体系、新的指导原则。许多教育家强烈地信仰科学的功效。确实,19世纪90年代和新文化运动时期,“科学”的普遍真理在改革家的思想中曾占重要地位,这种真理成为中国赶上外部世界的法宝。中国的教育家寻求通过运用“科学方法”解救祖国,这种方法不仅存在于自然科学和社会科学之中,而且也存在于人文科学和中国历史研究之中。对某些人来说,它是几乎具有宗教色彩的信条。一位教育家王风喈教授,表达了20年代颇为流行的态度,声称: 旧的教育体系和旧的民族习惯被破坏了,新的教育——根据科学的教育——已经开始……我们必须知道教育制度不能通过模仿得来,必须从思考与实践中得来。西洋教育不能整个的搬到中国来;必须斟酌中国国情,作出适当的选择。所以我的结论是,新的教育必须以科学为指导,理论要有科学的依据和证明,实践要遵循科学的方法,结果要有科学的统计。[12] 民国初年作为教育现代化基础的主要命题是:随着帝制的崩溃,旧秩序已经无可挽回地失去作用;中国必须着手建立自己的新的教育制度;以及——随着新文化运动的兴起——“科学”和“科学方法”将证明是新制度得以建立的最坚固的基础。[13] 大学:机构的建立 让男女青年进入由系里职员管理的公共宿舍,不亚于工业中出现工厂制度。同样,这在中国漫长的教育史中不乏先例,虽然其连贯性还缺乏研究。那些建立高等教育的人常常有意识地要模仿外国模式。然而选择哪种模式恐怕要受制于外国模式能否与中国的传统或需要共鸣。遗憾的是,传记材料虽很丰富,但校史却至今不多。下面我们将先看北京大学,然后是私立学校、技术学校和教会学校,最后是外国基金所起的作用。 北京大学 1912年新共和国从退位的清王朝继承的事物中,有一座规模小而且颇不稳定的称为京师大学堂的机构。京师大学堂诞生于1898年的改良运动。它在很大程度上依靠现代化的日本模式,试图满足创办者们所察觉的中国的迫切需要:让清朝的某些学者—官吏进修,使他们对现代世界的事务和状况有适当的了解。在1898年慈禧政变中,京师大学堂得以幸免。1902年这所学堂经改组增加了师资培训部,同时合并了同文馆,并在原有的课程中又增加了基础科学和五门外语。[14] 20世纪初,北京大学的学生主要是官吏,授予极为有限的现代课程,但在辛亥革命前,对他们的成就评价极低。[15]学生质量参差不齐。有些人的思想仍牢固地扎根在旧式文官考试制度中,他们把在新学堂的学历当作通向另一种资格的台阶,从而使学堂以颓废闻名。另一些人则在观点上较为进步和大胆,虽在轻薄和放荡的环境里,他们真正关心当前的问题,并在校园内展开生动活泼的讨论。[16]然而政府这一层次仍缺乏一致的高等教育政策,因此在建立教育体系的各级相应机构方面没取得进展。 1912年蔡元培被任命为教育总长后,他召开了全国临时教育会议,作为“国家教育改革的起点”。各省代表于7月在北京开会,制定了新的政策和相应的法规。[17]他们得出结论,中国教育有三个方面的问题有待解决:需将它建成一个完整的系统,扩展到全国各个角落,以及提高到现代水平。高等教育第一次成为完整的国家体制的一部分(至少在纸上)。 在以后的20年内,在中国普遍出现了一批国立、省立和原来私立的各种学院和大学,目标各不相同。然而,这些学校呈现的经历显示它们具有某些共同的特点。一般认为高等教育构成了国家建设这一重大任务的不可缺少的一部分,因为它是未来领导者的训练基地;同时,那些积极参加发展高等教育的人都是年富力强的知识分子,他们曾在晚清现代学校读过书,并曾与政治运动有联系。作为一个整体,他们一般都出身于书香门第。许多人为共和革命工作过。他们开始相互视为不仅是昔日的同窗,而且是追求民族目标的同志。因此,没有人反对1912年正式发布的管理院校的《大学令》中的第一款:“大学以教授高深学术,养成硕学闳材,应国家需要为宗旨。”[18] 1912年的《大学令》规定,大学里的高等教育由文学院和理学院实施,另设商、法、医、农、工等职业学科。一个机构要取得大学资格,必须有文、理两学院,或文学院和法学院和/或商学院,或理学院和/或医学院、农学院或工学院。京师大学堂在严复任校长时改名国立北京大学,从1912年至1916年底是教育部直属的唯一的国立大学。[19] 处于新的地位的国立北京大学——简称北大——并非一帆风顺。事实上,五年间学潮迭起,校长频繁更换,而校园生活普遍不安定。所有这些反映了整个国家政治环境的不稳定。[20]蔡元培就任校长是北大的转折点。蔡身为清末进士和翰林院编修,出于坚定的信念,在20世纪初与革命党人共命运,由于他学贯中西,并坚定地献身于自由化的理想,他受到广泛的尊敬。1916年末蔡元培应召从法国辍学回国,1917年1月就职。在50岁时,他得以实施早年在欧洲学习和参加革命活动时期即已设想的蓝图。[21] 蔡元培上任伊始,就得到教育总长范源濂——蔡元培的老友和革命同志——的支持,精力充沛地改造北大,此外当时大学校长有相当大的行政权。[22]他首先提高教学人员的质量,聘请教师只根据学术能力,不论其政治观点或学术倾向;结果许多蔡元培时代的青年教师在以后若干年内成为学术和职业圈内的知名人士,同时他们也提高了北大的学术水平。 蔡元培其次处理的问题是学生的态度和生活方式。他在就职演说中激励学生接受“世界上和生活中的新观点”。在校期间他们应当“把致力于学习当做不容推卸的责任,不应把学校当做升官发财的垫脚石”。[23]他还支持娱乐和学术社团以及校园刊物,认为这些都是可取的课外活动。第三,北大结构合理化。到1923年北大完全摆脱了从过去时代承袭下来的“预科学校”的基调。它的三个主要部分现在是自然科学、社会科学和语言文学。1919年开始采用选修课程,1922年由教育部批准在全国推广。1920年北大还率先准许女生来到一向是清一色男生的校园。[24]公立小学曾于1911年录取女生,到1920年已成为全国性潮流。据中国国立大学报告,截至1922年,在10535名学生中有405名女生。[25] 其他革新还包括1918年起草的几项计划,这些计划旨在制定人文科学、自然科学、社会科学和法律等方面的本科教学计划。蔡元培不得不使这些新的教学计划与有效的方法相适应。例如,组建法律系时,当时中国的司法制度正在着手修订,高质量的教师非常难得,蔡决定以“比较法律”为起点。首先应聘的两位讲师是王亮畴和罗文干,他们都是司法部的成员,不能受聘为专职教授。如蔡元培后来所讲的那样,所有这些因素使开设每一门法学课都极为困难。只是好几年后,出现了王世杰和周鲠生这样的法学家,一个合格的法律系才得以建立。[26]在注意研究生的学习和研究时,蔡元培深受他在德国的经历的影响,在那里他受到柏林大学和它的创始人威尔海姆·冯·洪堡的鼓舞。在北大他的努力得到了热情的支持,部分由于新的教师质量高,部分也由于师生有讨论学术问题的传统,这种传统可追溯到京师大学堂时代,当时大部分学生都是有一定学识的成年人。[27] 北大在“五四”运动中所起的领导作用,似乎再次肯定了青年学者和国家命运之间的联系。20年代初,北大作为一所大学,可以代表中国高等教育发展的大方向:课程是按照现代西方普遍实施的训练方针设置的,教师队伍具有学贯中西的背景,能超出本科课程继续进行学习和研究。北大作为第一所国立大学的地位,明显地标志着高等教育与国家建设的关系。更全面地进行研究时,南京的国立东南大学(后改名中央大学)等其他主要大学的发展应能提供有启发性的比较和对照。 私立学校:南开 并不是所有的著名大学都与政府有关系。各种类型和性质的私立学校纷纷成立,特别是在北京和上海以及一些省城。最著名的教育家的活动例子是南开,这是张伯苓(1876—1951)领导下在天津成长起来的中等学校和高等教育的联合体。与晚清的许多现代教育先驱者相比,张伯苓不是古典学者,而是一所现代学校——北洋水师学堂的优秀毕业生,当时他只有18岁。然而1898年中国海军基地威海卫成为英国的租借地,张目睹中国国旗降落和英国国旗升起,断然结束了他的海军生涯。极度的羞辱给予他以创伤性的打击。离开海军时,他发誓要献身于教育这条“自强之路”。[28]如他在回忆录中谈到的那样:“南开学校诞生于灾难深重的中国,所以它的目标就是要改变旧的生活习惯,培养救国青年。”教育家的任务就是清除中国衰败的五大弊端:体弱多病,迷信和缺乏科学知识,经济贫困,由缺乏集体生活和活动而出现的涣散,自私自利。张后来在南开制度中所订的综合教育计划,就是为适应中国在这五个方面的需要而设计的。[29] 张伯苓漫长的教育历程,开始于谦逊地担任严修——一位杰出的天津绅士,与蔡元培一样也是一位思想进步的翰林——孩子的家庭教师。张也曾在天津另一位著名绅士王益孙家任教。在这两个关系的基础上,张伯苓得以建立他的第一所学校。1904年,严、王二人联合资助建立一所中学和一所师范学校。第一届师范学校学生毕业于1906年,第一届中学学生毕业于1908年。虽然当地士绅子弟大量出现在第一批学生中——韩、严、陶、卞和郑等姓在最初的学生名册中都很突出——但学校的新课程很快吸引了越来越多的人前来注册。1908年当地第三个捐助人郑菊如慷慨地捐献了土地,而严修又再度捐款,学校得以迁入“南开洼”的永久校舍,南开学校因此得名。[30] 清末政治动荡,然而张伯苓思想专一,不允许他和他的学校卷入革命活动。他集中精力进一步发展学校。1917—1918年张在哥伦比亚大学师范学院学习一年后,得到严修和范源濂的赞助,他们支持他办大学的计划。通过发动他与天津上层社会(如严家和郑家)和国内知识界(范源濂是前任教育总长,蔡元培的密友)的关系,还有与国际教育团体(张于1909年皈依基督教,并与基督教青年会建立联系)的关系,他筹集了足够的资金,得以建造南开大学的第一座校舍。第一批四十余名新生于1919年秋入学。[31]南开大学开设了三科:文科、理科和商科。第一届学生于1923年毕业后,南开大学迁入八里台的更为宽敞的校园直至今日。当南开大学迁到这处郊外的校园时,一座新的科学大楼同时启用,这是一位私人捐助者的另一件礼物。[32] 张伯苓曾几度赴美考察高等教育制度和筹集资金。1928—1929年出访归来后,他将南开大学改组为三个学院:文学院由政治、历电和经济三系组成;理学院设数学、物理、化学和生物四系;而商学院包括财务管理、银行、统计和商业四系。[33] 张伯苓的双重文化的业绩是来自天津上层社会、留学归国教育家的国内知识界和国际(特别是英美)教育团体的支持的结合。其他教育活动家的成就尽管不那么著称,但可相提并论。例如,另一所私立大学——上海复旦大学,是由一所天主教学校的退学生于1905年建立的一所学校发展起来的;这所天主教学校便是震旦大学。在这些发展中一位感人的人物是天主教徒马良(马相伯,1840—1939年,见后)。还有另一所私立学校厦门大学是华侨实业家和慈善家陈嘉庚于1921年建立的,他已经成为新加坡橡胶、菠萝和海运业的百万富翁。从1921年到1937年,厦门大学在第一任校长林文庆的主持下发展起来。林文庆是一位颇具天赋的新加坡医生,在爱丁堡获得医学学位,并且也成为一位古典学者和记者。[34]中国私人赞助教育具有悠久的历史传统,值得进一步研究,更不用说近代海外华人对教育的影响了。厦门确实曾经是中国与东南亚贸易的一个主要货物集散地,“海上中国”的一个焦点。这在第12卷中讨论过。 技术学校 教育在应用科学和工程方面的发展是缓慢的,这在早期大学的课程中可以看出。长期以来考生是凭书本知识鉴别的,铁路建筑之类的实用技能,无论多么引人注意,都不能很快获得书本知识那样的声誉。然而清代末年,随着现代教育运动的兴起,一些专门技术学校和职业学校确实出现了,其中许多学校达到学院或大学水平。下面几个例子可以表明现代中国一些最著名的技术学校有不同的起源。1895年盛宣怀赞助建立天津中西学堂(亦称北洋西学堂),课程偏重于电气、矿业和机械工程等领域的专业。八年后重新评价国家教育制度时,这所学堂被改组为北洋大学堂,并迁到天津城外的新校园。[35]另一所盛宣怀赞助建立的学校是上海的南洋公学,开始时偏重政治学,但最终发展成声誉卓著的交通大学,[36]在工程教育方面被视为天津北洋大学堂在南方的对手。 除公立技术学校外,现代教育的倡导者们在私人资助下,偶尔也能建立这样的机构。工业和社区的开发者张謇顺应时代潮流,于1906年在江苏建立了南通大学,试图将课堂教学与实际经验结合起来。该校提供的课程包括农业、纺织技术、工程和医学,并与一个纺织厂、一所医院以及供农业实验用的1.6万亩土地挂钩。[37]技术学校的另一资金来源是外国在华现代工业部门内获得的商业利润:1909年一英国公司——河南福中公司——在焦作这一正在发展的现代煤炭工业所在地开办了焦作路矿学堂。在1912年政治动荡中短期关闭后,于1914年恢复,改名福中矿务学堂。1928年后在国民政府管辖下学校又改组为焦作工学院,[38]声誉日隆,直到1937年中国的学术进展因战争再次中断。上述例证只是加速走向技术和工程教育的一部分,在民国时期这类教育将受到进一步重视。 教会学校它们大多数是从中学水平开始的,原来的目的是帮助传播基督教。然而,后来它们在人文科学方面作出主要贡献。有记载的最早一所中国境内的教会学校可追溯到1845年。19世纪60年代和70年代,在早期自强运动中,又出现了几所教会学校。19世纪末旧秩序在中国的崩溃不可避免地给教会学校一个机会,在科学和外语等几个非传统教学领域采取主动。这些学校从而展示了新型的学识。1900年后,由于对现代教育的需求增长,一些教会学校通过扩设课程和合并这一复杂过程逐步演变成具有学院水平的学校。1906年新教传教士拥有2000多所小学和近400所中等水平的学校,而到20世纪20年代已有12所(最后是16所)学院或大学逐渐从其中出现。[39]然而,在中国扩大和深化基督教事业仍一直居优先地位。例如,上海圣约翰大学校长卜舫济认为:学校应保持小规模,这不仅为了保持教员与学生接触的质量,而且因为“不信教学生成分过大会冲淡学校的基督教气氛”。他还把宗教课程和礼拜定为必修,并辩解说,如果学生不想信教,他不必进这所学校。[40] 天主教高等教育是在上海郊区徐家汇(明末著名教徒徐光启的老家)特别设立的耶稣会奖学基金之上建立的。一位富有朝气同时不乏权力的人物马良长期任耶稣会传教士,他是一名清政府官员,又是一位改革家。他于1903年建立震旦学院,这所学校后来成为一所天主教大学。1905年他建立复旦公学,这所学校后来成为一所私立大学。这在前面已经提到。[41] 教会学校学术质量参差不齐。[42]有些大学在教学、计划改革和教员业务成就方面成效卓著。其中有些教员是国内或国际上的知名人士。如北京燕京大学有个新闻系,它从全国各地招生,而这个系的教员包括下列著名学者,如中国史方面的洪业(威廉·洪),顾颉刚(民俗学),徐淑希(政治学),吴文藻(社会学),文学方面的许地山、谢婉莹(冰心)和熊佛西,以及宗教方面的赵紫宸。燕京由于地处北京,知名度高。当然同时还有其他教会学校,如金陵大学和岭南大学(前身为广州格致书院),也取得许多真实成就。 然而,无论这些教会学校的学术成就如何,它们都会发现自己处于矛盾状态。虽然传教士的最初目的是传教,但有些传教士很早就发现传播世俗学识也是可取的。中国的现代化运动使他们的学校超越了改宗的界限,并使他们逐渐致力于有利国家发展的一般世俗计划。对于大多数在教会院校注册的学生来说,这些学校仅仅是现代高等教育的中心。学生们改信基督教的为数不多,不足以引起注意;[43]他们也不会让自己脱离横扫全国的“新潮流”。事实上,其中有些人,特别是那些在北京和上海的,[44]常常站在学生运动的前沿。[45] 表3 中国主要学院与大学及其分布,1922年 续表 注:37所大学有40个校园。 资料来源:《晚清三十五年来之中国教育,1897—1931》,第99—100页;卢茨:《基督教院校》,第531—533页;中国基督教院校一览表。 *交通大学属交通部,向不列入国立大学。——译者 **原文如此,疑为武昌高等师范学校。——译者 ***系哈同设在爱俪园内规模很小的大学。——译者 ****30年代并入岭南大学医学院。——译者 到20年代早期基督教学院和大学曾达到顶峰。如表3所示,1922年它们建成了将近一半的主要高等学府。这正是新文化运动蓬勃发展时期,因此甚至在教会学校数目增长时,它们也不得不面临来自中国社会的新的挑战。“五四”运动使中国知识分子与基督教改宗发生冲突。1922年在北京举行的世界基督教学生联合会,在全中国青年学生中触发了一场反宗教和反基督教运动。如胡适于1925年在燕京讲话时指出的那样,基督教在华教育面临三种新的困难。首先是第一次世界大战以来中国人的新的民族主义精神,“对列强的恐惧消失了,而自我意识已逐渐增强”,因此出现了恢复主权的运动,同时相信“帝国主义列强在文化侵略上采用的方法是传播宗教和开办学校”。第二,青年知识分子的“新认识的理性主义”会向基督教信条本身提出挑战,要求“拿证据来!”[46]最后,胡适认为整个传教事业充满内在弱点。(中国的爱国者们注意到,从学院的历史发展中看,它们是由一批有时主要资格是在宗教方面而不是在学术方面的人员创办的。)因此胡适极力主张教会的教育家要有办法回答两个问题:他们是否不能集中人力和物力发展少数真正优秀的高质量的院校,而不是发展大量平庸的或低劣的院校?他认为北京协和医学院是一个杰出的范例。其次,教会学校能否放弃传道,用全力办好教育?胡适认为宗教和教育二者不可得兼。[47] 胡适和与他气味相投的其他学者直言不讳地反对传统的教会教育,他们认为宗教宣传危险地缺乏理性,并为之困扰。在这方面,他们与西方理性主义以科学的名义对天启教的攻击相一致,并且也与儒家不可知论的学术传统相一致。然而,与此同时,那些接受了马克思主义,并视之为新“社会科学”的中国人,也参加了爱国反基督教运动,把它作为一般反对帝国主义活动的一部分。到1920年,在某些教会的圈子里仍将排外和反基督教情绪的增长归咎于孙逸仙和他在广东的“激进分子的温床”[48]。 科学与研究的开端 1900年前后的几十年,中国开始发生了急剧的变化,多种现代科学机构的发展在世界范围内也大步前进。参与发展中国高等教育的中外人士于是参加到一个极其复杂的过程中去,这个过程需要与世界其他地区相比较。1916年农商部地质调查所的建立,无疑是一个里程碑(见后)。开始强调科学知识则是另一个里程碑。1918年12月蔡元培宣称:“我们所说的‘大学’并非仅仅是个按照课程表授课,培养出大学毕业生的地方;它实际上是在共同关心的知识领域里从事研究……从而创造出新知识,以便提供给国内外学者的地方。”[49] 一般都同意,新知识要通过科学方法取得。到20年代这已成为一种信仰,即视科学观点为粉碎传统秩序,并为中国达到现代国家开辟道路的利器。青年知识分子有感于中国在国际上缺乏成就,开始相信科学是解决这一问题的关键。这一信仰如此深刻而广泛,以致几十年后他们仍然真诚地说:“科学是西方文明的源泉。”[50]“如果我们真地希望发展新文化,我们就应该特别注意发展科学。”[51] 民国初年科学教育水平普遍低下,大多认为是由于许多教师在日本接受的训练不充分。除了少数例外,总体条件直至20年代早期才有所改进。[52]20年代中期,有几个因素导致了比较大的进步:一些大学,如南开、清华和交通,开设了较有分量的科学课程,由欧美留学生任教;其他组织形式也促进了科学,并随之建立起高级的研究机构。 第一次世界大战期间海外的中国学生中出现了许多组织,其中最积极或最有影响的莫过于科学社。它是由为数不多的中国学生于1914年在康奈尔建立的。[53]它的英文全称为“ChineseAssociationfortheAchievementofScience”,以便与类似的美国组织相应,但其中文名称为“中国科学社”。“社”是一种志愿的组合,一种由活动家、精英分子领导的团体。过去士绅们常常组织这样的团体以建立地方学校或灌溉工程,或征集民兵抵抗太平军或广州的美国侵略军,后来着手“自治政府”的各项计划。科学社的目标不仅在于“促进科学,鼓励工业,统一翻译术语,传播知识”,而且它希望用十字军的热情通过科学最终再造中国的整个社会和文化。[54]科学社在美国草创时期有成员55人,1918年随主要创建人回国而迁至上海,到1930年成员曾增加到千人以上。社员包括留学欧美和日本的归国学生和在中国培养的青年科学家。科学社的活动范围也扩大了:除1915年创办刊物《科学》外,科学社还召开会议宣读研究论文,出版科学译著,并建立科学图书馆;1931年这家图书馆从初址南京迁至上海,它一直是那里的一份主要财富。同时在1922年,科学社曾在南京建立生物实验室。 促进科学在中国面临着两线作战:既要复制和扩大从国外获得的知识,又要让它适合中国的现状。中国青年科学家不可避免地要依赖国际学术界,他们也试图对国际学术界作出贡献。同时。他们又面临将科学思想与实践引入中国人民生活的任务,以减轻中国的落后程度。依赖和落后二者后来都有可能被污蔑为殖民地的症状。[55] 提供基金与美国的影响:清华 考虑到中国古代强调高等教育要为国家服务,1916—1928年军阀混战时期对中国高等教育的主要影响来自美国,当时联邦政府在教育方面所起的作用还微不足道(农学例外,它受到拨土地给各州立农学院的补助),这是具有讽刺意味的。美国高等教育当时仍由私立大学而不是由州立大学领导,实际上新英格兰和中西部的教派学院曾经是在华传教士主办的教会学校的样本。但美国的影响是通过一些不寻常事件的结合而形成的,远远超过了基督教会的努力。 1901年自清政府强索的庚子赔款中,美国要求从中分到2500万美元,当时美国负责官员私下认为数量过大,可能比正当数目高出一倍。然而它只占整个赔款33000万美元的一小部分。[56]这是一个使中国政府一蹶不振的过高的数目,而且几乎从任何角度看,这个数目都可以被视为帝国主义掠夺顶峰的可耻标志。1908年美国国会对中国减免了赔款中超出实际损失的那一部分,计11961121.76美元。这笔款子将被用于在美国教育中国人,而且它创造了一个支持中国高等教育的有效机制。1909年中国政府向美国派送了第一批庚子赔款学生47名,1910年70名。到1929年总数达1268名。[57]领取庚子赔款奖学金的学生名单中不乏才华洋溢的青年。 同时,政府也拟订了训练计划,为学生赴美学习作准备。1909年一个配备外国人员的大学预科被建立起来,1910年举行了入学考试,后来成为清华大学的清华学堂于1911年正式开学。[58]它成功的秘诀在于每年的预算有保证,当时其他院校则依赖军阀政权,毫无保障,此外,直至1929年它一直强调要为在美国大学学习做好专门的准备。一个通过入学考试的11—13岁的小学生必须学习五年初级部课程和三年高级部课程,以后才会被送往美国院校学习。第一批学生是1912年入校的,经学习八年标准现代中学课程(如英语、法语、德语、历史、地理、生理、物理、化学以及一些音乐、美术和体育课)后于1920年毕业。[59]1926年清华的预科地位结束,改组为达到学士学位的四年制的清华大学。 至此美国对中国教育的影响已达到顶峰,在很大程度上这是通过哥伦比亚大学师范学院的渠道实现的。许多有能力的攻读博士学位的中国人曾经在那里与约翰·杜威教授以及其他人一起工作。杜威在华讲学的两年(1919年5月至1921年7月)恰与英国数学哲学家和社会主义者罗素的访问(1920年10月至1921年7月)重合。杜威在11个省讲演大约70场,由胡适翻译,但是他提倡的实验主义对狂热的中国爱国者来说并不是政治上的灵丹妙药。后来他的同事孟禄教授也访问了中国,而主要大学的校长们——北大的蒋梦麟,国立东南大学(后为中央大学)的郭秉文——都自称是杜威的信徒。然而杜威的通过教育自我完善的典型美国式的教谕,很少提供在寻找中国教育道路的过程中能立竿见影的东西。留美归国学者从1919年到1924年领导了一场教育改革运动,他们既利用最初由蒋梦麟主编的《新教育》等主要刊物,也利用中国国家教育促进会;但这些计划和希望不久即在政治动荡中烟消云散。郭秉文被夹在反杜威保守派的民族主义浪潮与国民党在江苏与军阀的对抗之间,他被迫于1925年1月辞职。独立于执政者的自主的高等教育尚难预见。在军阀时代,高等教育只能在当地军阀的支配下发挥作用。[60] 然而,就清华而言,这株美国移植的植物生了根。1928年北伐胜利结束后,国民政府将清华定名为“国立清华大学”[61],罗家伦——北大校友,曾留学英国和美国——被任命为第一任校长。1928年9月他在就职演说中,赞扬清华取得国立大学地位是国民政府“在华北建立新的文化力量”的结果。[62]他提出在文、理、法三院上增加工学院,并加强研究生学习和高等研究。他还建议从国外邀请有成绩的学者担任较长时期的客座教授,“不要一时轰动,而要教学”;不要“像前几年那样,将国外著名学者(显然是指杜威和罗素)请来只讲课几个月或一年”,因为那个时代已经过去了。[63]在罗家伦和他的继任者梅贻琦的管理下,清华在规模和实质上都稳步发展,成为以后十年中杰出的高等学校之一。 美国影响的另一方面是以1925年中华教育文化基金董事会(中华基金会)的出现为序幕的,这是一件具有历史意义的大事。1924年美国国会根据联合决议,将庚子赔款余额归还在中国使用。于是两国政府达成协议,将这笔大约12545000美元的款项交给一个基金会掌管,用于中国的教育文化事业。几个月内中国政府任命了由10名*中国人和5名美国人组成的第一任董事会,中华基金会于1925年6月正式成立。[65]10名中国董事中有3人是高级外交官(颜惠庆、顾维钧和施肇基),其余的是著名的科学家或现代教育界的知名人士:范源濂(范静生),黄炎培(江苏省教育界领袖),蒋梦麟(北大校长),张伯苓(南开校长),周贻春(清华校长)和丁文江(农商部地质调查所主任)。5个美国董事是与中国教育界有关的著名人士:杜威,孟禄(两人都是哥伦比亚的),顾临(洛克菲勒基金资助的北京协和医学院代理院长),贝克(中国华洋义赈会)和贝纳德(花旗银行)。[66]董事会任命范源濂为基金会第一任干事长,他邀请中国科学的热情倡导者任鸿隽担任行政秘书。[67] 中华基金会执掌的不仅有1924年归还的庚子赔款,还有1908年归还的供奖学金和清华大学使用的款项。它又被授权掌管静生生物调查所的基金以及其他学术捐款。它的主要任务第一是资助学术机构的高质量活动,如黄炎培领导的中华职业教育社;其次,支持公私机构的新项目,如合作事业;第三,基金会本身开发新项目,[68]所有申请项目必须按现代方式得到董事会或专门委员会的批准。[69]范源濂和任鸿隽意识到中华基金会的革新任务,认为它不应仅仅是基金管理办公室,也应是现代科学的强有力的推动者。[70]基金会坐落在北京一所以前的亲王府内,1926—1927年批准把研究补助金给予13所院校、3所研究所、5个文化教育组织以及一个未归类的领款单位,总金额达419906元。[71]当有人责备基金会不通过政府当局而由少数几个人处理大宗款项时,任回答说,这正是中华基金会的力量所在:它杜绝了政府滥用基金去打内战。[72]总有一天,当日、英、加、法、德和其他西方国家在华教育活动经过较为充分的研究时,[73]人们可能在较为宽阔的范围内评价美国的影响,这种影响将包括洛克菲勒基金会对中国医学和其他科学的支持。英、法、意退还的庚子赔款部分也用于教育。
Java
UTF-8
2,171
3.28125
3
[]
no_license
package com.example.demo.io; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.attribute.PosixFilePermission; import java.util.HashSet; import java.util.Set; /** * @package: com.example.demo.io * @author: * @email: * @createDate: 2019-06-12 11:21 * @description: Java File class has the ability to set the file permissions but it’s not versatile. * <p> * The biggest drawback is that you can divide file permissions into two set of users – owner and * everybody else only. You can’t set different file permissions for group and other users. * <p> * Java 7 has introduced PosixFilePermission Enum and java.nio.file.Files includes a method * setPosixFilePermissions(Path path, Set<PosixFilePermission> perms) that can be used to set file permissions easily. */ public class FilePermissions { public static void main(String[] args) throws IOException { File file = new File("D:\\dl\\TeamViewer_Setup.exe"); //set application user permissions to 455 file.setExecutable(false); file.setReadable(false); file.setWritable(true); //change permission to 777 for all the users //no option for group and others file.setExecutable(true, false); file.setReadable(true, false); file.setWritable(true, false); //using PosixFilePermission to set file permissions 777 Set<PosixFilePermission> perms = new HashSet<>(); //add owners permission perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_WRITE); perms.add(PosixFilePermission.OWNER_EXECUTE); //add group permissions perms.add(PosixFilePermission.GROUP_READ); perms.add(PosixFilePermission.GROUP_WRITE); perms.add(PosixFilePermission.GROUP_EXECUTE); //add others permissions perms.add(PosixFilePermission.OTHERS_READ); perms.add(PosixFilePermission.OTHERS_WRITE); perms.add(PosixFilePermission.OTHERS_EXECUTE); Files.setPosixFilePermissions(Paths.get("D:\\dl\\TeamViewer_Setup.exe"), perms); } }
C
UTF-8
3,660
2.71875
3
[ "MIT" ]
permissive
/* * Copyright (C) 2019-2020 BiiLabs Co., Ltd. and Contributors * All Rights Reserved. * This is free software; you can redistribute it and/or modify it under the * terms of the MIT license. A copy of the license can be found in the file * "LICENSE" at the root of this distribution. */ #ifndef UTILS_BUNDLE_ARRAY_H_ #define UTILS_BUNDLE_ARRAY_H_ #ifdef __cplusplus extern "C" { #endif #include "common/model/bundle.h" #include "common/ta_errors.h" #include "utarray.h" /** * @file utils/bundle_array.h * @brief Implementation of bundle array object. This object would be used when we fetch multiple * `bundle_transactions_t` objects. It provides an easier way to save and traverse all the bundles. */ /** * @brief Renew the given bundle * * @param[in,out] bundle The bundle that will be renewed * */ static inline void bundle_transactions_renew(bundle_transactions_t **bundle) { bundle_transactions_free(bundle); bundle_transactions_new(bundle); } typedef UT_array bundle_array_t; // We should synchronize this implementation as to the implementation in the IOTA library static UT_icd bundle_transactions_icd = {sizeof(iota_transaction_t), 0, 0, 0}; static inline void bundle_array_copy(void *_dst, const void *_src) { bundle_transactions_t *bdl_dst = (bundle_transactions_t *)_dst; bundle_transactions_t *bdl_src = (bundle_transactions_t *)_src; iota_transaction_t *txn = NULL; utarray_init(bdl_dst, &bundle_transactions_icd); BUNDLE_FOREACH(bdl_src, txn) { bundle_transactions_add(bdl_dst, txn); } } static UT_icd bundle_array_icd = {sizeof(bundle_transactions_t), 0, bundle_array_copy, 0}; /** * @brief Allocate memory of bundle_array_t */ static inline void bundle_array_new(bundle_array_t **const bundle_array) { utarray_new(*bundle_array, &bundle_array_icd); } /** * @brief The bundle array iterator. */ #define BUNDLE_ARRAY_FOREACH(bundles, bdl) \ for (bdl = (bundle_transactions_t *)utarray_front(bundles); bdl != NULL; \ bdl = (bundle_transactions_t *)utarray_next(bundles, bdl)) /** * @brief Gets the number of bundles in the bundle_array. * * @param[in] bundle_array The bundle array object. * @return An number of bundles. */ static inline size_t bundle_array_size(bundle_array_t const *const bundle_array) { if (bundle_array == NULL) { return 0; } return utarray_len(bundle_array); } /** * @brief Adds a bundle to the bundle_array. * * @param[in] bundle_array The bundle array object. * @param[in] bundle A bundle object. * @return #retcode_t */ static inline status_t bundle_array_add(bundle_array_t *const bundle_array, bundle_transactions_t const *const bundle) { if (!bundle || !bundle_array) { return SC_NULL; } utarray_push_back(bundle_array, bundle); return SC_OK; } /** * @brief Gets a bundle from the bundle_array by index. * * @param[in] bundle_array The bundle array object. * @param[in] index The index of a bundle. * @return #bundle_transactions_t */ static inline bundle_transactions_t *bundle_array_at(bundle_array_t *const bundle_array, size_t index) { if (index < utarray_len(bundle_array)) { return (bundle_transactions_t *)(utarray_eltptr(bundle_array, index)); } return NULL; } /** * @brief Free memory of bundle_array_t */ static inline void bundle_array_free(bundle_array_t **const bundle_array) { // TODO set dtor and use utarray_free() instead. bundle_transactions_t *bundle = NULL; BUNDLE_ARRAY_FOREACH(*bundle_array, bundle) { utarray_done(bundle); } utarray_free(*bundle_array); *bundle_array = NULL; } #ifdef __cplusplus } #endif #endif // UTILS_BUNDLE_ARRAY_H_
Java
UTF-8
821
2.15625
2
[]
no_license
package com.spier.service; import java.util.List; import java.util.Map; import com.spier.common.bean.db.ScriptInfo; import com.spier.common.bean.db.task.TaskInfo; /** * 业务方面的公共方法 * @author Administrator */ public interface BussinessCommonService { /** * 根据国家名称获取简称 * @param str * @return 可能为null */ public String getCountryAbb(String str); /** * 根据国家简称和运营商字符串信息获取运营商名称 * @param mcc 国家简称 * @param opTxt 运营商字符串信息 * @return 可能为null */ public String getOperatorNameByCountryAbbAndOpText(String abb, String opTxt) ; /** * 根据任务查找所有脚本 * @param tasks * @return 可能为null */ public Map<String, ScriptInfo> getScriptsByTasks(List<TaskInfo> tasks) ; }
Java
UTF-8
322
3.125
3
[]
no_license
package Java; import java.util.Scanner; public class reverse_number { public static void main(String[] args) { int n,reverse=0; Scanner input = new Scanner(System.in); n= input.nextInt(); while(n!=0) { reverse =reverse* 10; reverse =reverse+n%10; n=n/10; } System.out.print(+reverse); } }
Python
UTF-8
1,654
2.6875
3
[]
no_license
import pandas as pd import numpy as np def load_data(x_path='data/task9_train_x.csv', y_path='data/task9_train_y.csv'): train_x = pd.read_csv(x_path, header=None) train_y = pd.read_csv(y_path, header=None) np_train_x = train_x.values # [1000, 10] # np_train_x[1] [ 1.24925374 -1.3495958 4.13685968 4.5149551 3.75611164 1.80277989 # 4.48090841 -3.65859769 4.87159557 -0.69982146] np_train_y = train_y.values # [1000, 10] np_train_xy = np.append(np_train_x[:,:,np.newaxis], np_train_y[:,:,np.newaxis],2) # 其中的2说的是在第二个维度上append [1000,10,1]*2 -> [1000,10,2] # [[ 1.24925374 1.23647908] # [-1.3495958 1.15841264] # [ 4.13685968 -2.27545424] # [ 4.5149551 -0.69555445] # [ 3.75611164 -3.54115764] # [ 1.80277989 -1.20486861] # [ 4.48090841 -0.84536699] # [-3.65859769 -3.97096198] # [ 4.87159557 0.888881 ] # [-0.69982146 3.53269976]] return np_train_x, np_train_y, np_train_xy def load_test_data(x_path='data/task9_evaluate_finetune_x.csv', y_path='data/task9_evaluate_finetune_y.csv'): train_x = pd.read_csv(x_path, header=None) train_y = pd.read_csv(y_path, header=None) np_train_x = train_x.values # [100, 5] np_train_y = train_y.values # [100, 5] np_train_xy = np.append(np_train_x[:, :, np.newaxis], np_train_y[:, :, np.newaxis], 2) return np_train_x, np_train_y, np_train_xy def load_result_data(x_path='data/task9_evaluate_x.csv'): train_x = pd.read_csv(x_path, header=None) np_train_x = train_x.values # [100, 5] return np_train_x
Python
UTF-8
134
2.8125
3
[]
no_license
def house_numbers_sum(inp): sum = 0 for x in inp: if (x == 0): break sum = sum + x return sum
C#
UTF-8
2,471
2.921875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using Balta.ContentContext; using Balta.NotificationContext; using Balta.SubscriptionContext; namespace Balta { class Program { static void Main(string[] args) { var articles = new List<Article>(); articles.Add(new Article("Artigo sobre POO", "Programação orientada a objetos")); articles.Add(new Article("Artigo sobre C#", "Linguagem de programação")); articles.Add(new Article("Artigo sobre .NET", "Framework")); // foreach (var article in articles) // { // System.Console.WriteLine("-----------------------------------------"); // System.Console.WriteLine(article.Title); // System.Console.WriteLine(article.Url); // System.Console.WriteLine(article.Id); // } var courses = new List<Course>(); var coursePOO = new Course("Artigo sobre POO", "POO"); var courseAspNet = new Course("Artigo sobre AspNet", "AspNet"); courses.Add(courseAspNet); courses.Add(coursePOO); var careers = new List<Career>(); var careerPOO = new Career("Especialista POO", "Especialista-POO"); var careerItem = new CareerItem(1, "Começando por aqui.", "aqui", coursePOO); var careerItem2 = new CareerItem(2, "Terminando por aqui", "null", courseAspNet); careerPOO.Items.Add(careerItem2); careerPOO.Items.Add(careerItem); careers.Add(careerPOO); foreach (var career in careers) { System.Console.WriteLine(career.Title); foreach (var item in career.Items.OrderBy(x => x.Order)) { System.Console.WriteLine($"{item.Order} - {item.Title}"); System.Console.WriteLine(item.Course?.Title); System.Console.WriteLine(item.Course?.Level); foreach (var notification in item.Notifications) { Console.WriteLine($"{notification.Property} - {notification.Message}"); } } var payPalSubscription = new PayPalSubscription(); var studente = new Student(); studente.CreateSubscription(payPalSubscription); } } } }
Python
UTF-8
1,930
2.578125
3
[]
no_license
# -*- coding: utf-8 -*- from FileClient import FileClient import os import jieba import jieba.analyse import json withWeight = True def get_inputfile(): return os.path.join(os.getcwd(),'inputfile','tlong.txt') def get_outputfile(filename="jiebalong.txt"): return os.path.join(os.getcwd(),'outputfile',filename) def read_tianlong(): fileobj = FileClient(get_inputfile()) return fileobj.read() def seg_txt(txt): jieba.load_userdict(os.path.join(os.getcwd(),'customdict',"mydict.txt")) jieba.analyse.set_stop_words(os.path.join(os.getcwd(),'customdict',"stop_words.txt")) jieba.analyse.set_idf_path(os.path.join(os.getcwd(),'customdict',"idf.txt.big")) return jieba.analyse.extract_tags(txt,topK=45,withWeight=withWeight,allowPOS=(),withFlag=True) def txt_filter(txt): txt.replace(' ','') txt.replace('\n','') return txt def read_result(): json_obj = FileClient(get_outputfile('words.json')) tag_lists = [] result = json_obj.readLine() while result != "": tag_lists.append(json.loads(result)) result = json_obj.readLine() return tag_lists def main(): tianlong = read_tianlong() # tianlong = txt_filter(tianlong) tags = seg_txt(tianlong) saveobj = FileClient(get_outputfile()) singal_words = FileClient(get_outputfile('singal_words.txt')) json_obj = FileClient(get_outputfile('words.json')) totle_w = 0.0 for tag in tags: saveobj.writeLine(str(tag)) singal_words.writeLine(str(tag[0])) tag_dict = {} tag_dict["name"] = tag[0] tag_dict["value"] = tag[1] # ensure_ascii默认为True,会造成unicode编码错误 json_obj.writeLine(json.dumps(tag_dict,ensure_ascii=False)) totle_w += tag[1] print("Totle W: %f ." % totle_w) saveobj.close() json_obj.close() singal_words.close() if __name__ == "__main__": # main() read_result()
PHP
UTF-8
773
2.515625
3
[]
no_license
<?php include 'initialize.php'; if ($_SESSION['user_id']){ header("Location: account.php?user_id={$_SESSION['user_id']}"); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Sign in Form</title> </head> <body> <?php include 'header.php';?> <h3>Please log in to continue</h3> <form action = "verify.php" method = "POST"> <br> Email <input type = "text" name = "email"><br><br> Password <input type = "password" name = "password"><br><br> <button type = "submit">Submit</button> </form> <br><br> <h3>New user? <button onclick="window.location.href='signup.php'">Sign up!</button></h3> <!-- <p class = "error"> <?php echo $error_string ?> </p> --> </body> </html>
PHP
UTF-8
1,147
2.640625
3
[]
no_license
<?php namespace PM\GBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity */ class Coordinate { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * @ORM\Column(type="string") */ protected $lon; /** * @ORM\Column(type="string") */ protected $lat; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set lon * * @param string $lon * @return Coordinate */ public function setLon($lon) { $this->lon = $lon; return $this; } /** * Get lon * * @return string */ public function getLon() { return $this->lon; } /** * Set lat * * @param string $lat * @return Coordinate */ public function setLat($lat) { $this->lat = $lat; return $this; } /** * Get lat * * @return string */ public function getLat() { return $this->lat; } }
Java
UTF-8
2,427
3.5
4
[]
no_license
package leetcode.aug; import java.util.HashSet; import java.util.Set; public class GoatLatin { public String toGoatLatin(String S) { if (S == null || S.length() == 0) { return S; } String[] words = S.split(" "); Set<Character> vowels = new HashSet<>(); vowels.add('a'); vowels.add('e'); vowels.add('i'); vowels.add('o'); vowels.add('u'); vowels.add('A'); vowels.add('E'); vowels.add('I'); vowels.add('O'); vowels.add('U'); StringBuilder addA = new StringBuilder(); StringBuilder resultBuffer = new StringBuilder(); for (int i = 0; i < words.length; i++) { addA.append('a'); StringBuilder sb = new StringBuilder(words[i]); char ch = sb.charAt(0); if (vowels.contains(ch)) { sb.append("ma"); } else { if (sb.length() == 1) { sb.append("ma"); } else { sb.append(ch).append("ma"); sb.deleteCharAt(0); } } sb.append(addA); resultBuffer.append(sb); if (i != words.length - 1) { resultBuffer.append(' '); } } return resultBuffer.toString(); } public String toGoatLatinOpt(String s) { StringBuilder sb = new StringBuilder(); String[] split = s.split(" "); int aCount = 1; for (String w : split) { if (isVowel(w.charAt(0))) { sb.append(w); } else { sb.append(w.substring(1, w.length())); sb.append(w.charAt(0)); } sb.append("ma"); for (int i = 0; i < aCount; i++) { sb.append("a"); } if (aCount != split.length) { sb.append(" "); } aCount++; } return sb.toString(); } public boolean isVowel(char c) { return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U'; } public static void main(String[] args) { GoatLatin obj = new GoatLatin(); String S = "I speak Goat Latin"; System.out.println(obj.toGoatLatin(S)); } }
Python
UTF-8
597
3.40625
3
[]
no_license
relation_count = int(input()) parents = {} for _ in range(relation_count): query = input().split() parents[query[0]] = [] if len(query) == 1 else query[2:] exceptions_count = int(input()) exceptions = [] def is_parent(child, parent): return child == parent or any(map(lambda item: is_parent(item, parent), parents[child])) print(parents) for i in range(exceptions_count): exceptions.append(input()) print('searching ', exceptions[i], 'parents in ', exceptions[:i]) if any(map(lambda item: is_parent(exceptions[i], item), exceptions[:i])): print(exceptions[i])
C++
UTF-8
447
2.59375
3
[]
no_license
#pragma once #include "../System/Window.hpp" #include "../ResourceManager/ResourceManager.hpp" class Background { private: sf::Texture *mTexture; sf::RectangleShape mBackground; public: Background(std::string tPath, sf::Vector2f tSize); ~Background(); void SetSize(sf::Vector2f tSize){mBackground.setSize(tSize);} void SetPos(sf::Vector2f tPos){mBackground.setPosition(tPos);} void Update(); void Render(Window *tWindow); };
Swift
UTF-8
632
2.734375
3
[]
no_license
// // SecondViewController.swift // DisplayRgb-iOS // // Created by Muhsin Etki on 16.07.2020. // Copyright © 2020 Muhsin Etki. All rights reserved. // import UIKit class SecondViewController: UIViewController { var red: Float = 0.0 var green: Float = 0.0 var blue: Float = 0.0 override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.init(red: CGFloat(red/255.0), green: CGFloat(green/255.0), blue: CGFloat(blue/255.0), alpha: 1.0) } @IBAction func newColorButtonPressed(_ sender: UIButton) { self.dismiss(animated: true, completion: nil) } }
JavaScript
UTF-8
6,863
3.390625
3
[]
no_license
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); console.log('hello typescript'); //ts compile to es5 var str = "hello ts"; var str1 = "hello typescript"; //boolean var flag = true; flag = false; //number var a = 123; console.log(a); // a = "string"; //错误 // var arr = [1, "233", false]; // 第一种定义数组的方式 var arr = [1, 2, 34, 534]; console.log(arr); //第二种定义方式 var arr1 = [1, 2, 3, 4, 2]; //3 var arr2 = [1, "de", true]; //元祖类型 tuple 属于数组的一种 var arr3 = ["ts", 2.42, true]; /* enum 枚举名{ 标示符[=整型常数], 标示符[=整型常数], 标示符[=整型常数] } pay_status 0 未支付 1支付 2交易成功 */ var Flag; (function (Flag) { Flag[Flag["success"] = 1] = "success"; Flag[Flag["error"] = -1] = "error"; })(Flag || (Flag = {})); var f = Flag.success; var Color; (function (Color) { Color[Color["red"] = 0] = "red"; Color[Color["blue"] = 5] = "blue"; Color[Color["orange"] = 6] = "orange"; })(Color || (Color = {})); ; var c = Color.blue; console.log(c); console.log("red", Color.red); console.log("orange", Color.orange); //任意类型 // var num: any = 123; // num = "str"; // window.onload =function(){ // var oBox:any = document.getElementById("box"); // oBox.style.color = "red"; // } //null 和 undefined 其他 never类型 // var num2:number; // console.log(num2);//报错 // var num2:undefined; // console.log(num2); var num2; console.log(num2); num2 = 4; console.log(num2); var num3 = null; console.log(num3); function run() { console.log("run"); } //never 类型 是其他类型( 包括 null 和 undefined )的子类型,代表不会出现的值 //意味着变量只能被never类型所fu zhi var aa; aa = undefined; var bb = null; // var cc: never; // aa = (() => { // throw new Error('err'); // })(); //函数声明法 function run1() { return "h"; } var fun2 = function () { return "jj"; }; function getInfo(name, age) { return name + " --- " + age; } var getInfo2 = function (name, age) { return name + " --- " + age; }; //可选参数必须在末尾 function getInfo3(name, age) { if (age) return name + " --- " + age; else return name + " --- age unkown"; } function getInfo4(name, age) { if (age === void 0) { age = 30; } return name + " --- " + age; } function sum(a) { var nums = []; for (var _i = 1; _i < arguments.length; _i++) { nums[_i - 1] = arguments[_i]; } return a + nums.reduce(function (prev, cur) { return prev + cur; }, 0); } console.log(sum(1, 3, 3, 4, 5)); function getInfo5(str) { if (typeof str === "string") { return 'i am ' + str; } else { return 'my age is' + str; } } var Person = /** @class */ (function () { function Person(name) { this.name = name; } Person.prototype.getName = function () { return this.name; }; Person.prototype.setName = function (name) { this.name = name; }; return Person; }()); var p = new Person("zhangsan"); console.log(p.getName); var Web = /** @class */ (function (_super) { __extends(Web, _super); function Web(name) { var _this = _super.call(this, name) || this; _this.age = 12; return _this; } Web.prototype.setName = function (name) { this.name = name; }; Web.print = function () { console.log('print'); //静态方法 }; return Web; }(Person)); //类里 三个修饰符 public private protected 默认public var web = new Web('haha'); web.setName('aa'); console.log(web.getName()); // console.log(web.age);//不能拿到 var Human = /** @class */ (function () { function Human(name) { this.name = name; } Human.prototype.work = function () { console.log('work'); }; return Human; }()); var Male = /** @class */ (function (_super) { __extends(Male, _super); function Male(name) { return _super.call(this, name) || this; } Male.prototype.run = function () { console.log(this.name, ' is running'); }; return Male; }(Human)); /*ts 自定义方法传入参数 对json进行约束 */ function printLabel(labelInfo) { console.log('printLabel'); } // printLabel('hehe'); //错误 // printLabel({name:'zs'})//err printLabel({ label: 'label' }); function printName(name) { //必须传入对象 firstName lastName console.log(name.firstName + "--" + name.lastName); } var name2 = { firstName: 'hehe', lastName: 'he', age: 34 }; printName(name2); function ajax(config) { var xhr = new XMLHttpRequest(); xhr.open(config.type, config.url, true); // xhr.setRequestHeader("Access-Control-Allow-Origin","*"); xhr.send(config.data); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { console.log('success'); if (config.dataType.toLowerCase() === 'json') { console.log(JSON.parse(xhr.responseText)); } console.log(xhr.responseText); } }; } ajax({ type: "get", url: "http://a.itying.com/api/productlist", dataType: "JSON", data: "name=zhangsan" }); var md5 = function (key, value) { return key + value; }; console.log(md5('name', 'zhangsan')); var arr11 = ['aaa', 'vbb']; var userObj = { name: 'zz', age: '12' }; var Dog = /** @class */ (function () { function Dog(name) { this.name = name; } Dog.prototype.eat = function (str) { throw new Error("Method not implemented."); }; return Dog; }()); var d = new Dog('beibei'); function func1(val) { return val; } // T表示泛型 具体什么类型是调用这个方法的时候决定的 function getData(value) { return value; } getData(123); getData('hh2'); var MinClass = /** @class */ (function () { function MinClass() { this.list = []; } MinClass.prototype.add = function (num) { this.list.push(num); }; MinClass.prototype.min = function () { var minNum = this.list[0]; for (var i = 0; i < this.list.length; i++) { if (minNum > this.list[i]) { minNum = this.list[i]; } } return minNum; }; return MinClass; }());
TypeScript
UTF-8
668
2.828125
3
[ "MIT" ]
permissive
// import { BookState } from '@interfaces/book'; import { ReduxAction } from '@interfaces/redux'; import { actionTypes } from './actionTypes'; import { BooksStoreState } from './types'; const initialState: BooksStoreState = { loading: false, books: [], } const reducer = (state = initialState, action: ReduxAction) => { const { type } = action switch (type) { case actionTypes.SET_BOOKS: return { ...state, books: action.payload.book, } case actionTypes.BOOKS_STORE_LOADING: return { ...state, loading: action.payload.loading, } default: return state } }; export default reducer;
PHP
UTF-8
1,785
2.625
3
[]
no_license
<?php class UserController extends GenericController { public $names = 'users'; public $name = 'user'; public function __construct(User $user) { $this->db = $user; } public function useredit() { $id = @Auth::user()->id; return parent::edit($id); } public function userupdate() { $id = @Auth::user()->id; $input = Input::all(); $pass = Input::get('password'); $name = $this->name; $$name = $this->db->find($id); $old = $$name->password; if (! $$name->fill($input)->isValidEdit('update', Input::all())) { return Redirect::back()->withInput()->withErrors($$name->errors); } if (!empty($pass)) $$name->password = Hash::make($pass); else $$name->password = $old; $$name->save(); return Redirect::to('user/profile')->with('alert', studly_case($this->name).' updated'); } public function store() { $input = Input::all(); $pass = Input::get('password'); if (! $this->db->fill($input)->isValid()) { return Redirect::back()->withInput()->withErrors($this->db->errors); } if (!empty($pass)) $this->db->password = Hash::make($pass); $this->db->save(); return Redirect::route('admin.'.$this->names.'.index')->with('alert', studly_case($this->name).' created'); } public function update($id) { $input = Input::all(); $pass = Input::get('password'); $name = $this->name; $$name = $this->db->find($id); $old = $$name->password; if (! $$name->fill($input)->isValidEdit('update', Input::all())) { return Redirect::back()->withInput()->withErrors($$name->errors); } if (!empty($pass)) $$name->password = Hash::make($pass); else $$name->password = $old; $$name->save(); return Redirect::route('admin.'.$this->names.'.index')->with('alert', studly_case($this->name).' updated'); } }
JavaScript
UTF-8
1,163
2.6875
3
[]
no_license
var help = require('./help.json'); var commands = { "say": { execute: function(args, msg, bot) { var prompt = args.join(" ").slice(4); return prompt; }}, "help": { execute: function(args, msg, bot) { var page; if(args.length > 1){ if (help[args[1]].length >= 1){ page = help[args[1]].join("\n"); } } else { page = help[""].join("\n"); } return page; }}, "verbose": { execute: function(args, msg, bot) { var authorPerm = msg.channel.permissionsOf(msg.author); if(authorPerm.hasPermission("kickMembers")){ if(args[1] === "true"){ bot.verbose = true; bot.sendMessage(msg.channel, "`How may I assist you...?`"); }else { bot.verbose = false; bot.sendMessage(msg.channel, "`I'm muted? How...unfortunate.`"); } return "`...`"; } else { return "`I'm afraid I can't let you do that, `" + msg.author.mention() + "`...`"; } }} }; module.exports.commands = commands;
Java
UTF-8
3,798
2.015625
2
[ "Apache-2.0" ]
permissive
package org.fugerit.java.doc.freemarker.process; import java.io.OutputStream; import java.io.Reader; import java.io.Serializable; import java.util.Set; import org.fugerit.java.core.cfg.xml.ListMapConfig; import org.fugerit.java.core.util.filterchain.MiniFilterChain; import org.fugerit.java.core.util.filterchain.MiniFilterMap; import org.fugerit.java.core.xml.sax.SAXParseResult; import org.fugerit.java.doc.base.config.DocInput; import org.fugerit.java.doc.base.config.DocOutput; import org.fugerit.java.doc.base.config.DocTypeHandler; import org.fugerit.java.doc.base.facade.DocFacade; import org.fugerit.java.doc.base.facade.DocHandlerFacade; import org.fugerit.java.doc.base.model.DocBase; import org.fugerit.java.doc.base.process.DocProcessConfig; import org.fugerit.java.doc.base.process.DocProcessContext; import org.fugerit.java.doc.base.process.DocProcessData; import org.fugerit.java.doc.base.xml.DocValidator; import lombok.Getter; import lombok.extern.slf4j.Slf4j; @Slf4j public class FreemarkerDocProcessConfig implements Serializable, MiniFilterMap { private static final long serialVersionUID = -6761081877582850120L; @Getter private ListMapConfig<DocChainModel> docChainList; @Getter private DocHandlerFacade facade; private DocProcessConfig docProcessConfig; protected FreemarkerDocProcessConfig() { super(); this.docChainList = new ListMapConfig<>(); this.facade = new DocHandlerFacade(); this.docProcessConfig = new DocProcessConfig(); } private DefaultChainProvider defaultChain; protected void setDefaultChain( DefaultChainProvider defaultChain ) { this.defaultChain = defaultChain; } protected DefaultChainProvider getDefaultChain() { return this.defaultChain; } public void process( String chainId, DocProcessContext context, DocProcessData data ) throws Exception { MiniFilterChain chain = this.getChainCache( chainId ); log.info( "chain list {}", this.docProcessConfig.getIdSet() ); chain.apply( context , data ); } public void process( String chainId, DocProcessContext context, DocProcessData data, DocTypeHandler handler, DocOutput docOutput ) throws Exception { this.process(chainId, context, data); handler.handle( DocInput.newInput( handler.getType() , data.getCurrentXmlReader() ) , docOutput ); } public SAXParseResult process( String chainId, String type, DocProcessContext context, OutputStream os, boolean validate ) throws Exception { SAXParseResult result = null; MiniFilterChain chain = this.getChainCache( chainId ); DocProcessData data = new DocProcessData(); chain.apply(context, data); if ( validate ) { result = DocValidator.validate( data.getCurrentXmlReader() ); if ( !result.isPartialSuccess() ) { DocValidator.logResult(result, log ); } } DocBase docBase = null; try ( Reader reader = data.getCurrentXmlReader() ) { docBase = DocFacade.parse( reader ); } DocInput input = DocInput.newInput( type, docBase, data.getCurrentXmlReader() ); DocOutput output = DocOutput.newOutput( os ); this.getFacade().handle(input, output); return result; } @Override public MiniFilterChain getChain(String id) throws Exception { return this.docProcessConfig.getChain( id ); } @Override public MiniFilterChain getChainCache(String id) throws Exception { MiniFilterChain chain = null; if ( this.docProcessConfig.getKeys().contains( id ) ) { chain = this.docProcessConfig.getChain(id); } else if ( this.defaultChain != null ) { chain = this.defaultChain.newDefaultChain(id); this.setChain(id, chain); } return chain; } @Override public Set<String> getKeys() { return this.docProcessConfig.getKeys(); } @Override public void setChain(String id, MiniFilterChain chain) { this.docProcessConfig.setChain(id, chain); } }
PHP
UTF-8
3,092
2.578125
3
[]
no_license
<?php namespace App\Service; use App\Entity\Produto; use Doctrine\ORM\EntityManager; class ProdutoService { private $em; public function __construct(EntityManager $em) { $this->em = $em; } public function insert(array $dados) { $entity = new Produto(); $entity->setNome($dados['nome']); $entity->setDescricao($dados['descricao']); $entity->setImagem($dados['imagem']); $valor = str_replace(',', '.',str_replace('.', '', $dados['valor'])); $entity->setValor( $valor ); $categoria = $this->em->getReference('App\Entity\Categoria', $dados['categoria']); $entity->setCategoria($categoria); if (key_exists('tags', $dados) ){ foreach ($dados['tags'] as $tag) { $tag = $this->em->getReference('App\Entity\Tag', $tag); $entity->addTag($tag); } } $res = $this->em->persist($entity); $this->em->flush(); return $entity; } public function update($id, array $dados) { $entity = $this->em->getReference( 'App\\Entity\\Produto', $id); $entity->setNome($dados['nome']); $entity->setDescricao($dados['descricao']); $entity->setImagem($dados['imagem']); $valor = str_replace(',', '.',str_replace('.', '', $dados['valor'])); $entity->setValor( $valor ); $categoria = $this->em->getReference('App\Entity\Categoria', $dados['categoria']); $entity->setCategoria($categoria); if (key_exists('tags', $dados) ){ $entity->setTags( new \Doctrine\Common\Collections\ArrayCollection() ); foreach ($dados['tags'] as $tag) { $tag = $this->em->getReference('App\Entity\Tag', $tag); $entity->addTag($tag); } } $res = $this->em->persist($entity); $this->em->flush(); return $entity; } public function fetchAll($firstResults = 0, $maxResults = 100) { return $this->em ->getRepository("App\\Entity\\Produto") ->findAllPaginator($firstResults, $maxResults); } public function find($id) { return $this->em->getRepository("App\\Entity\\Produto")->find($id); } public function delete($id) { $entity = $this->em->getReference( 'App\\Entity\\Produto', $id); $res = $this->em->remove($entity); $this->em->flush(); return true; } public function search($termo, $firstResults = 0, $maxResults = 100) { return $this->em ->getRepository("App\\Entity\\Produto") ->search($termo, $firstResults, $maxResults); } public function total($termo = null) { return $this->em->getRepository("App\\Entity\\Produto")->total($termo); } public function findAllArray() { return $this->em ->getRepository("App\\Entity\\Produto") ->findAllArray(); } }
C++
UTF-8
1,806
2.59375
3
[]
no_license
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> using namespace std; #define maxm 2000005 #define maxn 2005 struct Edge { int v, next; } edge[maxm]; int m, n; int count, head[maxn]; int q[maxn], front, rear; int sex[maxn]; void addedge(int a, int b) { edge[count].next = head[a]; edge[count].v = b; head[a] = count; count++; edge[count].next = head[b]; edge[count].v = a; head[b] = count; count++; } void input() { scanf("%d%d", &n, &m); for (int i = 0; i < m; i++) { int a, b; scanf("%d%d", &a, &b); a--; b--; addedge(a, b); } } bool bfs(int s) { q[0] = s; front = 0; rear = 1; sex[s] = 0; while (front != rear) { int a = q[front++]; if (front == maxn) front = 0; for (int i = head[a]; i != -1; i = edge[i].next) { int v = edge[i].v; if (sex[v] == -1) { sex[v] = 1 - sex[a]; q[rear++] = v; if (rear == maxn) rear = 0; continue; }else if (sex[v] == sex[a]) return false; } } return true; } int main() { //freopen("t.txt", "r", stdin); int t, s = 0; scanf("%d", &t); while (t--) { memset(head, -1, sizeof(head)); memset(sex, -1, sizeof(sex)); count = 0; s++; printf("Scenario #%d:\n", s); input(); bool ans = true; for (int i = 0; i < n && ans; i++) if (sex[i] == -1) ans = bfs(i); if (ans) printf("No suspicious bugs found!\n\n"); else printf("Suspicious bugs found!\n\n"); } return 0; }
Java
UTF-8
404
1.914063
2
[]
no_license
package com.accp.dao; import com.accp.pojo.Supplieras; public interface SupplierasMapper { int deleteByPrimaryKey(Integer supplierasid); int insert(Supplieras record); int insertSelective(Supplieras record); Supplieras selectByPrimaryKey(Integer supplierasid); int updateByPrimaryKeySelective(Supplieras record); int updateByPrimaryKey(Supplieras record); }
Java
UTF-8
3,460
2.046875
2
[]
no_license
package nyamori.moe.tmdbx.collection; import android.content.DialogInterface; import android.content.Intent; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import nyamori.moe.tmdbx.obj.CurrentUser; import nyamori.moe.tmdbx.DetailActivity; import nyamori.moe.tmdbx.R; import nyamori.moe.tmdbx.obj.TVDetailActivity; import nyamori.moe.tmdbx.adapter.CollectionAdapter; public class CollectionList extends AppCompatActivity { RecyclerView rv; CollectionLab collectionLab; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_collection_list); rv = (RecyclerView) findViewById(R.id.collectioRecyclerview); collectionLab = CollectionLab.get(getApplicationContext()); final CollectionAdapter collectionAdapter = new CollectionAdapter(getApplicationContext(),collectionLab.getCollectionsOfUser(CurrentUser.getUuid())); collectionAdapter.setOnItemClickListener(new CollectionAdapter.OnItemClickListener() { @Override public void onClick(int position) { CollectionObj collectionObj = collectionAdapter.getCollection(position); if(collectionObj.getCollectionType().equals("movie")){ Intent intent = new Intent(CollectionList.this, DetailActivity.class); Bundle bundle = new Bundle(); bundle.putSerializable("id", Long.valueOf(collectionObj.getMovieId())); intent.putExtras(bundle); startActivity(intent); } else{ Intent intent = new Intent(CollectionList.this, TVDetailActivity.class); Bundle bundle = new Bundle(); bundle.putSerializable("id", Long.valueOf(collectionObj.getMovieId())); intent.putExtras(bundle); startActivity(intent); } } @Override public void onLongClick(final int position) { final CollectionObj collectionObj = collectionAdapter.getCollection(position); AlertDialog.Builder dialog = new AlertDialog.Builder(CollectionList.this); dialog.setPositiveButton("YES",new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialog, int which) { collectionLab.deleteCollection(collectionObj); collectionAdapter.removeCollection(position); collectionAdapter.notifyDataSetChanged(); dialog.dismiss(); } }).setNegativeButton("NO", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).setMessage("Delete or not?"); } }); rv.setAdapter(collectionAdapter); LinearLayoutManager layoutManager = new LinearLayoutManager(this); layoutManager.setOrientation(LinearLayoutManager.VERTICAL); rv.setLayoutManager(layoutManager); } }
TypeScript
UTF-8
128
2.671875
3
[ "MIT" ]
permissive
function* iterate <T> (iterable: Iterable<T>) { for (const value of iterable) { yield value } } export default iterate
C++
UTF-8
758
3.53125
4
[]
no_license
//int sqrt(int t) //求一个整数的平方根,且平方根也是整数,直接用二分搜索吧。。。 //也可以用牛顿迭代法,求任何一个数的开m方根,详见sqrtm.cc class Solution { public: int mySqrt(int x) { if(x <= 0) return 0; else if(x < 4) return 1; int b = 0, e = x / 2 + 1; //b < e, b*b <= x < e*e while(b + 1 != e){ int m = (b+e)/2; if(m >= 46341){ //46341 == sqrt(2**31) e = m; continue; } unsigned long long t = m*m; if(t == x) return m; else if(t < x) b = m; else e = m; } return b; } };
Python
UTF-8
379
3.375
3
[]
no_license
# use this function to fetch the recent news of a certain country from the database and save it to a csv file import sqlite3 import pandas as pd def fetcher(country_code): conn = sqlite3.connect("world news.db") df = pd.read_sql_query(f"SELECT * FROM {country_code}", conn) df.to_csv(f"{country_code} sites") # using Deutschland code as an example fetcher("de")
C
UTF-8
1,610
3.15625
3
[]
no_license
/* * A template for the 2016 MPI lab at the University of Warsaw. * Copyright (C) 2016, Konrad Iwanicki * Further modifications by Krzysztof Rzadca 2018 */ #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <time.h> #include <mpi.h> int main(int argc, char * argv[]) { struct timespec spec; MPI_Init(&argc,&argv); /* intialize the library with parameters caught by the runtime */ clock_gettime(CLOCK_REALTIME, &spec); srand(spec.tv_nsec); // use nsec to have a different value across different processes int numProcesses, myRank; MPI_Status *status; MPI_Comm_size(MPI_COMM_WORLD, &numProcesses); MPI_Comm_rank(MPI_COMM_WORLD, &myRank); int buf_send[1] = {1}; int buf_recv[1] = {0}; if (myRank == 0) { printf("Hello world from main process. There are %d", numProcesses); MPI_Send(buf_send, 1, MPI_INT, 1, 13, MPI_COMM_WORLD); MPI_Recv(buf_recv, 1, MPI_INT, numProcesses - 1, 13, MPI_COMM_WORLD, status); printf("Main node. Received %d\n", buf_recv[0]); } else { printf("Hello world from %d sub process.", myRank); MPI_Recv(buf_recv, 1, MPI_INT, myRank - 1, 13, MPI_COMM_WORLD, status); buf_send[0] = buf_recv[0] + myRank; printf("Subprocess %d, received %d, sending %d to %d\n", myRank, buf_recv[0], buf_send[0], (myRank + 1)%numProcesses); MPI_Send(buf_send, 1, MPI_INT, (myRank + 1)%numProcesses, 13, MPI_COMM_WORLD); } //unsigned t = rand() % 5; //sleep(t); //printf("Hello world from %d/%d (slept %u s)!\n", 0, 1, t); MPI_Finalize(); /* mark that we've finished communicating */ return 0; }
Java
UTF-8
2,926
2.25
2
[]
no_license
package com.example.joke.notificationLamp.service; import android.service.notification.NotificationListenerService; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.service.notification.StatusBarNotification; import android.util.Log; /** * Created by Joke on 2/04/2017. */ public class NotifService extends NotificationListenerService { private String TAG = this.getClass().getSimpleName(); private NLServiceReceiver nlservicereciver; @Override public void onCreate() { super.onCreate(); nlservicereciver = new NLServiceReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction("com.example.joke.bletest.NOTIFICATION_LISTENER_SERVICE_EXAMPLE"); registerReceiver(nlservicereciver,filter); } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(nlservicereciver); } @Override public void onNotificationPosted(StatusBarNotification sbn) { Log.i(TAG,"********** onNotificationPosted"); Log.i(TAG,"ID :" + sbn.getId() + "\t" + sbn.getNotification().tickerText + "\t" + sbn.getPackageName()); Intent i = new Intent("com.example.joke.bletest.NOTIFICATION_LISTENER_EXAMPLE"); i.putExtra("notification_event","onNotificationPosted :" + sbn.getPackageName() + "\n"); sendBroadcast(i); } @Override public void onNotificationRemoved(StatusBarNotification sbn) { Log.i(TAG,"********** onNotificationRemoved"); Log.i(TAG,"ID :" + sbn.getId() + "\t" + sbn.getNotification().tickerText +"\t" + sbn.getPackageName()); Intent i = new Intent("com.example.joke.bletest.NOTIFICATION_LISTENER_EXAMPLE"); i.putExtra("notification_event","onNotificationRemoved :" + sbn.getPackageName() + "\n"); sendBroadcast(i); } class NLServiceReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Intent i1 = new Intent("com.example.joke.bletest.NOTIFICATION_LISTENER_EXAMPLE"); i1.putExtra("notification_event", "====================="); sendBroadcast(i1); int i = 1; for (StatusBarNotification sbn : NotifService.this.getActiveNotifications()) { Intent i2 = new Intent("com.example.joke.bletest.NOTIFICATION_LISTENER_EXAMPLE"); i2.putExtra("notification_event", i + " " + sbn.getPackageName() + "\n"); sendBroadcast(i2); i++; } Intent i3 = new Intent("com.example.joke.bletest.NOTIFICATION_LISTENER_EXAMPLE"); i3.putExtra("notification_event", "===== Notification List ===="); sendBroadcast(i3); } } }
Java
UTF-8
571
2.078125
2
[]
no_license
package features.api.blog; import common.ApiUtil; import common.CoreConstant; import io.restassured.response.Response; import static net.serenitybdd.rest.SerenityRest.given; public class Authen { public Response authenUser(models.features.blog.Authen authen){ return given().baseUri(CoreConstant.BLOG_HOST + CoreConstant.BLOG_API_AUTHEN) .header("Content-Type", "application/json") .body(ApiUtil.parseObjectToJSON(authen, models.features.blog.Authen.class)) .when() .post(); } }
Java
UTF-8
509
1.609375
2
[]
no_license
package web; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.ComponentScan; /** * Created by EGBoldyr on 14.03.18. */ @SpringBootApplication @ComponentScan("web") @EnableCaching public class SandboxClientBoot { public static void main(String[] args) { SpringApplication.run(SandboxClientBoot.class, args); } }
Go
UTF-8
729
2.640625
3
[]
no_license
package postmark // GetThisServer gets details for the server associated // with the currently in-use server API Key func (client *Client) GetThisServer() (Server, error) { res := Server{} err := client.doRequest(parameters{ Method: "GET", Path: "server", TokenType: server_token, }, &res) return res, err } /////////////////////////////////////// /////////////////////////////////////// // EditThisServer updates details for the server associated // with the currently in-use server API Key func (client *Client) EditThisServer(server Server) (Server, error) { res := Server{} err := client.doRequest(parameters{ Method: "PUT", Path: "server", TokenType: server_token, }, &res) return res, err }
TypeScript
UTF-8
1,282
2.65625
3
[ "0BSD", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
import { AgChart, AgChartOptions } from "ag-charts-community" const options: AgChartOptions = { container: document.getElementById("myChart"), title: { text: "Number of Cars Sold", }, subtitle: { text: "(double click a column for details)", }, data: [ { month: "March", units: 25, brands: { BMW: 10, Toyota: 15 } }, { month: "April", units: 27, brands: { Ford: 17, BMW: 10 } }, { month: "May", units: 42, brands: { Nissan: 20, Toyota: 22 } }, ], series: [ { type: "column", xKey: "month", yKey: "units", listeners: { nodeDoubleClick: (event: any) => { var datum = event.datum window.alert( "Cars sold in " + datum[event.xKey] + ": " + String(datum[event.yKey]) + "\n" + listUnitsSoldByBrand(datum["brands"]) ) }, }, }, ], axes: [ { type: "category", position: "bottom", }, { type: "number", position: "left", }, ], } var chart = AgChart.create(options) function listUnitsSoldByBrand(brands: Record<string, number>) { var result = "" for (var key in brands) { result += key + ": " + brands[key] + "\n" } return result }
Python
UTF-8
1,348
2.5625
3
[ "MIT" ]
permissive
from humans import Anastasis import urllib2, bs4, subprocess, random, time # concepts borrowed from artybollocks.com concepts = [ "postmodern discourse", "unwanted gifts", "Critical theory", "copycat violence", "Pre-raphaelite tenets", "daytime TV", "multiculturalism", "midlife subcultures", "consumerist fetishism", "the Military-Industrial Complex", "the tyranny of ageing", "counter-terrorism", "gender politics", "new class identities", "recycling culture", "vegetarian ethics", "emotional memories", "emerging sexualities", "UFO sightings", "consumerist fetishism", "football chants", "acquired synesthesia", "life as performance", "urban spaces", "romance tourism" ] def generate_art_critique(): concept1, concept2 = random.sample(concepts, 2) return "This piece is about the relationship between %s and %s" % (concept1, concept2) def give_art_critiques(): for i in range(5): art_piece = Anastasis.vision.search("art piece") Anastasis.movement.turn_towards(art_piece) Anastasis.movement.start_walking() time.sleep(5) Anastasis.movement.stop_walking() critique = generate_art_critique() Anastasis.voice.say(critique) if __name__ == '__main__': give_art_critiques()
Ruby
UTF-8
446
2.671875
3
[]
no_license
########################################################### # this file contains different implementations for reading # data from *.yaml file (e.g. with environment configs) ########################################################### require 'yaml' def read_config_yaml(filename, env) config = YAML.load_file filename config[env] if config.keys.include?(env) end filename = 'data_file.yml' env = 'qa' puts read_config_yaml(filename, env)
Markdown
UTF-8
2,354
3.375
3
[]
no_license
# FindMyCar A Hackthon project, android application to helper users find where they parked their cars. # Author Jessica Zeng, Zephyr Yao and Edwin Angkasa. # What it does Our android app, Find My Car can help people find where they park their cars, no matter it is an outdoor parking lot or huge parking structure. Find My Car applies to car with bluetooth connection. User needs to turn on the bluetooth on his cell phone. When the bluetooth connects to the car device, our app will recognize the connection. When user stop the car engine, the disconnection of the bluetooth and cell phone will trigger our app to mark the altitude, latitude, longitude of that location, which is where the car parks. And when the user needs to find his car, he will turn on Find My Car. There are two selections he can choose. If he is unaware of where the parking structure is, he can select Direction, which uses google map to direct use to the parking structure/parking lot. And inside the parking space, he can switch the mode to walking route, then there will be an compass tells user which direction his car is at now using a compass. There also will be an instruction telling the user should go up or go down to reach the floor he parked. # How we built it 1. We use android studio to develop the application. 2. We use the disconnect of the bluetooth and the car to active our program. 3. We have different options to get the parking location of the car: the top selection is GPS, if GPS is not available, we use the nearby network's physical address to determine the user. 4. We use google map to direct the user from where he is to the parking structure/parking lot. 5. Whe the user enters the parking structure/parking lot, we will instruct the user go up or down to reach the car's parking level. 6. When the user is in the parking structure/parking lot, we use the current location of the phone, and the car's location to determine which direction the user walk would approach the car. We calculate the angular displacement analyzing the azimuth. # What's next for FindMyCar 1. Improve the user interface by styling the button and fonts. 2. Improve the accuracy of the car's location. 3. Implement our own map to displace the closest route. 4. Apply the application on other platforms, such as ios and smart watch. 5. Apply voice interaction function to our app.
Python
UTF-8
3,475
2.9375
3
[]
no_license
# ########################################################################### # Portfolio classes from .defaults import ib_comission from quant_testing.core.events import ExecutionType, OrderEvent import logging logger = logging.Logger('portfolio.log') class Portfolio: pass class SingleSharePortfolio(Portfolio): """Base class for a simple portfolio containing shares and cash """ def __init__(self, events, cash, shares, tick_data, commission_calc=ib_comission): self.events = events self.cash = cash self.shares = shares self.tick_data = tick_data self.commission = commission_calc @property def value(self): # First we need the current share price current_data = self.tick_data.get_latest_bars(1) share_price = current_data['share_price'].iloc[0] if not current_data.empty else 0 return self.cash + self.shares*share_price def determine_move(self, signal_event): # First we need the current share price current_data = self.tick_data.get_latest_bars(1) share_price = current_data['share_price'].iloc[0] # Get approximate transaction_costs - always buy roughly half the portfolio approx_shares = int(0.5*(self.cash // share_price)) approx_costs = self.commission(approx_shares) if signal_event.signal_type == ExecutionType.buy and self.shares == 0: # Get the number of shares we can buy, and send the order shares_to_buy = max(int(self.cash // share_price - approx_costs), 0) if shares_to_buy: return OrderEvent(None, 'MKT_ORDER', shares_to_buy, ExecutionType.buy) if signal_event.signal_type == ExecutionType.sell and self.shares > 0: return OrderEvent(None, 'MKT_ORDER', self.shares, ExecutionType.sell) def generate_order(self, signal_event): order_event = self.determine_move(signal_event) if order_event is not None: self.events.put(order_event) def buy_instrument(self, number_shares, share_price, transaction_costs): total_cost = number_shares * share_price + transaction_costs if total_cost > self.cash: logger.warning("Not possible to execute strategy" " - insufficient funds!") return self.cash -= total_cost self.shares += number_shares def sell_instrument(self, number_shares, share_price, transaction_costs): if number_shares > self.shares: logger.warning("Not possible to execute stragety" " - insufficient shares!") return elif transaction_costs > number_shares*share_price: logger.warning("Not possible to execute stragety" " - insufficient funds!") return self.shares -= number_shares self.cash += number_shares * share_price - transaction_costs def update_portfolio(self, fill_order): """Update the portfolio """ qnty = fill_order.quantity price = fill_order.price costs = fill_order.commission if fill_order.direction == ExecutionType.buy: self.buy_instrument(qnty, price, costs) elif fill_order.direction == ExecutionType.sell: self.sell_instrument(qnty, price, costs) else: raise ValueError("Unknown direction {}".format(fill_order.direction))
Python
UTF-8
812
3.59375
4
[]
no_license
"""We are the captains of our ships, and we stay 'till the end. We see our stories through. """ """https://practice.geeksforgeeks.org/problems/subset-sum-problem/0 [Top Down] """ def subset_sum_helper(arr, s, n, dp): if s == 0: return True if n == 0: return False if dp[n][s]: return dp[n][s] if s >= arr[n-1]: dp[n][s] = subset_sum_helper(arr, s - arr[n-1], n-1, dp) or subset_sum_helper(arr, s, n-1, dp) return dp[n][s] elif s < arr[n-1]: dp[n][s] = subset_sum_helper(arr, s, n-1, dp) return dp[n][s] def isSubsetSum(arr, s): length = len(arr) dp = [[None] * (s+1)] * (length + 1) return subset_sum_helper(arr, s, length, dp) if __name__ == "__main__": arr = [3, 34, 4, 12, 5, 2] print(isSubsetSum(arr, 30))
Python
UTF-8
1,534
2.609375
3
[ "MIT" ]
permissive
from unittest import TestCase from django.db.models import Q from binder.views import prefix_q_expression from binder.permissions.views import is_q_child_equal from .testapp.models import Animal class TestPrefixQExpression(TestCase): def test_simple_prefix(self): self.assertTrue(is_q_child_equal( prefix_q_expression(Q(foo=1), 'prefix'), Q(prefix__foo=1), )) def test_nested_prefix(self): self.assertTrue(is_q_child_equal( prefix_q_expression(Q(foo=1) & ~Q(bar=2) | Q(baz=3), 'prefix'), Q(prefix__foo=1) & ~Q(prefix__bar=2) | Q(prefix__baz=3), )) def test_prefix_identity(self): self.assertTrue(is_q_child_equal( prefix_q_expression(Q(pk__in=[]), 'prefix'), Q(pk__in=[]), )) def test_antiprefix_field(self): self.assertTrue(is_q_child_equal( prefix_q_expression(Q(name='Apenheul', animals__name='Bokito'), 'zoo', 'animals', Animal), Q(zoo__name='Apenheul', name='Bokito'), )) def test_antiprefix_no_field(self): self.assertTrue(is_q_child_equal( prefix_q_expression(Q(name='Apenheul', animals=1), 'zoo', 'animals', Animal), Q(zoo__name='Apenheul', pk=1), )) def test_antiprefix_pk(self): self.assertTrue(is_q_child_equal( prefix_q_expression(Q(name='Apenheul', animals__pk=1), 'zoo', 'animals', Animal), Q(zoo__name='Apenheul', pk=1), )) def test_antiprefix_modifier(self): self.assertTrue(is_q_child_equal( prefix_q_expression(Q(name='Apenheul', animals__in=[1, 2, 3]), 'zoo', 'animals', Animal), Q(zoo__name='Apenheul', pk__in=[1, 2, 3]), ))
Python
UTF-8
470
3.421875
3
[]
no_license
a = \ '(asciitree (sometimes you) (just (want to draw)) trees (in (your terminal)))' def mover(inp): b = inp.replace('(', '( ').replace(')', ' )').split(' ')[1:-1] count = 0 cort = [] description = False for el in b: if el != '(' and el != ')' and not description: cort.append((count, el)) description = True count += 1 elif el == '(': count += 1 elif el == ')': count -= 1 else: cort.append((count, el)) return cort print(mover(a))
Markdown
UTF-8
6,860
2.96875
3
[ "MIT" ]
permissive
# Convey **Version**: v0.0.2 **Editors**: - [Haardik](https://www.linkedin.com/in/haardikkk/) **Contributors**: --- This specification describes the Convey Chat messaging protocol, which can be used with any decentralized ledger system which has the concept of addresses, to create an interoperable messaging network. Implementations of the protocol can be uniquely designed based on their underlying decentralized ledger. ## Overview Blockchains and the rise of dApps have introduced new problems around communication. Consider the example of buying a domain. Traditionally, buying a domain involves entering your email address and/or phone number, allowing the registrar to contact you when the domain is about to expire. However, in the case of something like ENS, where the dApp owners only know the buyer's Ethereum address and nothing else, sending a renewal reminder is not possible with the current technology being used. By implementing fully decentralized address based messaging, two major use case areas are enabled - dApp to Peer(s) (D2P) communication - e.g. renewal reminders from ENS, community announcements - Peer to Peer (P2P) communication - e.g. discussing an NFT trade Convey is not an Ethereum-specific protocol, but can be used across various decentralized ledgers to create cross-blockchain communication platforms. ## Glossary | _Term_ | _Definition_ | | ------------------------ | ----------------------------------------------------------------------------------------------------- | | Sender | The address creating the blockchain transaction to send a message | | Receiver | Address included as a recipient of a message | | DCAS | Decentralized Content Addressable Storage e.g. IPFS | | Transaction | A blockchain transaction that published the Message Identifier to the chain | | Message | Data being sent to one or multiple receivers | | Message Hash | The DCAS hash returned for the message object | | Message Identifier (MID) | A unique identifier for every message which describes the message type and other specific information | | Message Object | The data structure representing a message | | Blockchain Identifier | A string representation of a blockchain and network e.g. `ethereum@ropsten`, `algorand@testnet` | ## Message Identifier (MID) A message identifier is a unique identifier for every message which describes the message type and other specific information. It contains the following parameters: | _Parameter_ | _Description_ | | ----------------------- | ------------------------------------------------------- | | `MESSAGE_HASH` | DCAS hash of the message object | | `RECEIVER_TYPE` | Blockchain external account address or contract address | | `BLOCKCHAIN_IDENTIFIER` | Blockchain identifier for the receiver type | **Syntax** `mid:<MESSAGE_HASH>:<RECEIVER_TYPE>:<BLOCKCHAIN_IDENTIFIER>` e.g. `mid:QmbyizSHLirDfZhms75tdrrdiVkaxKvbcLpXzjB5k34a31:0x9d46038705501f8cb832e5a18492517538b636f3:ethereum@ropsten` e.g. `mid:QmbyizSHLirDfZhms75tdrrdiVkaxKvbcLpXzjB5k34a31:broadcast#0xd0a6E6C54DbC68Db5db3A091B171A77407Ff7ccf:ethereum@mainnet` ## Message Hash A message hash is the hash returned from the DCAS when you upload the Message Object. E.g. In the case of IPFS, it will look something like `QmbyizSHLirDfZhms75tdrrdiVkaxKvbcLpXzjB5k34a31` ## Receiver Types Receiver Types define the different categories of receivers that messages can be sent to. - P2P (Receiver type `<address>` e.g. `0x9d46038705501f8cb832e5a18492517538b636f3`) - D2P (Receiver type `broadcast#<contractAddress>` e.g. `broadcast#QmbyizSHLirDfZhms75tdrrdiVkaxKvbcLpXzjB5k34a31`) ## Blockchain Identifier A blockchain identifier is used to specify what blockchain and network the sender and receivers are using. It is represented by the `<blockchain name> + @ + <network name>` E.g. `ethereum@ropsten` , `algorand@testnet` ## Message Object The message object is what gets uploaded to the CAS and it's hash is put on chain. It has the following syntax ```json { "payload": "<compressed encrypted digitally signed message>", "timestamp": "<timestamp>" } ``` where `payload` is a string representation of the following **Intermediate Message Object** encrypted with the receiver's public key and then compressed ```json { "message": { "body": { "title": "<message title>", "text": "<text message>", "image": "<image base64 data>", "html": "<html message>" }, "sender": { "address": "<sender address>", "blockchainIdentifier": "<blockchain identifier>" } }, "signature": "<signed message with sender private key>" } ``` ## Messaging Security 1. An intermediate message object is generated from the client application 2. The intermediate message object is signed using the sender's private key and the `signature` is added as a property to the message object 3. The new message object is encrypted with the receiver's public key 4. The encrypted message object is compressed and converted to a string 5. A message object is generated with the payload being the encrypted compressed string along with a unix timestamp 6. The message object is uploaded to the DCAS and a blockchain transaction is made to anchor the hash on chain as a Message Identifier 7. Reciever client listener will parse the message, and decrypt it using their private key 8. Receiver client will verify signature to ensure it's coming from the correct sender ## Lifecycle TODO: sender convey client > ipfs > blockchain > receiver convey client ## Anti-Spam Protections // TODO: blacklist ## REST API Backend // TODO: subscriptions Backend - Open Source - Run it locally - OR, you can use our hosted version - NOTE: Third parties are free to host our API and provide it as a service Metamask, Trust Wallet, Argent Wallet (Integrated with Convey) - "Convey API URL" - http://localhost:3000 OR https://api.convey.chat/ OR https://competitor.api.com - YOu receive a new message id `mid:d2p:whatever:broadcast#ensSmartContract` - GET /subscriptions from API (http://localhost:3000 OR https://api.convey.chat/ OR https://competitor.api.com) - if ensSmartContract in subscriptions: - parse - else - dont
C#
UTF-8
971
2.875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using AgilePrinciplesPractice.Ch21; using NUnit.Framework; namespace AgilePrinciplesPracticeTests.Ch21 { [TestFixture] public class TestSleepCommand { public void TestSleep() { WakeUpCommand wakeup = new WakeUpCommand(); ActiveObjectEngine e = new ActiveObjectEngine(); SleepCommand c = new SleepCommand(1000, e, wakeup); e.AddCommand(c); DateTime start = DateTime.Now; e.Run(); DateTime stop = DateTime.Now; double sleepTime = (stop - start).TotalMilliseconds; Assert.IsTrue(sleepTime >= 1000, "SleepTime" + sleepTime + "exepected > 1000"); Assert.IsTrue(sleepTime <= 1100, "SleepTime " + sleepTime + "expected < 1100"); Assert.IsTrue(wakeup.executed, "Command Executed"); } } }
TypeScript
UTF-8
1,792
2.828125
3
[ "MIT" ]
permissive
import { ERROR_TYPE } from "../enums"; import { IError } from "../interfaces"; export class ErrorHelper implements IError { type: ERROR_TYPE; message: string; constructor(type: ERROR_TYPE, info?) { this.type = type; this.message = this.getMsg_(info); } throw() { throw this.get(); } get() { return { message: this.message, type: this.type } as IError; } private getMsg_(info) { let errMsg: string; switch (this.type) { case ERROR_TYPE.AllowedOnChild: errMsg = `The action ${info} is allowed only on child token.`; break; case ERROR_TYPE.AllowedOnRoot: errMsg = `The action ${info} is allowed only on root token.`; break; case ERROR_TYPE.AllowedOnMainnet: errMsg = `The action is allowed only on mainnet chains.`; break; case ERROR_TYPE.ProofAPINotSet: errMsg = `Proof api is not set, please set it using "setProofApi"`; break; case ERROR_TYPE.BurnTxNotCheckPointed: errMsg = `Burn transaction has not been checkpointed as yet`; break; case ERROR_TYPE.EIP1559NotSupported: errMsg = `${info ? 'Root' : 'Child'} chain doesn't support eip-1559`; break; case ERROR_TYPE.NullSpenderAddress: errMsg = `Please provide spender address.`; break; default: if (!this.type) { this.type = ERROR_TYPE.Unknown; } errMsg = this.message; break; } return errMsg; } }
Shell
UTF-8
1,450
2.609375
3
[ "MIT" ]
permissive
#!/bin/bash # Bash script to set environment variables for provisioning. # NOTE: Please do a change-all on this script to change "cjoakim" to YOUR ID! # # Chris Joakim, Microsoft, August 2021 export primary_region="eastus" export primary_rg="cjoakimcsl" # csl = Cosmos-Synapse-Link # export cosmos_sql_region=$primary_region export cosmos_sql_rg=$primary_rg export cosmos_sql_acct_name="cjoakimcslcosmos" export cosmos_sql_acct_consistency="Session" # {BoundedStaleness, ConsistentPrefix, Eventual, Session, Strong} export cosmos_sql_acct_kind="GlobalDocumentDB" # {GlobalDocumentDB, MongoDB, Parse} export cosmos_sql_dbname="demo" export cosmos_sql_cname="travel" export cosmos_sql_pk_path="/pk" export cosmos_sql_db_throughput="4000" export cosmos_sql_sl_ttl="220903200" # 7-years, in seconds (60 * 60 * 24 * 365.25 * 7) # export synapse_region=$primary_region export synapse_rg=$primary_rg export synapse_name="cjoakimcslsynapse" export synapse_stor_kind="StorageV2" # {BlobStorage, BlockBlobStorage, FileStorage, Storage, StorageV2}] export synapse_stor_sku="Standard_LRS" # {Premium_LRS, Premium_ZRS, Standard_GRS, Standard_GZRS, , Standard_RAGRS, Standard_RAGZRS, Standard_ZRS] export synapse_stor_access_tier="Hot" # Cool, Hot export synapse_fs_name="synapse_acct" export synapse_spark_pool_name="poolspark3s" export synapse_spark_pool_count="3" export synapse_spark_pool_size="Small"
JavaScript
UTF-8
3,267
3.046875
3
[]
no_license
var x = [], y = [], insectNum = 20, insectBody = 20; var LightBullOn; var LightBullOff; var LightSign; var k = 0; for (var i = 0; i < insectNum; i++) { x[i] = 0; y[i] = 0; } function setup() { createCanvas(windowWidth, windowHeight); strokeWeight(20); stroke(0); textFont('Helvetica'); frameRate(60); } function mouseClicked() { if(k==1){ k=0; }else if(k==0){ k=1; } console.log(k); } function draw() { if (k == 0) { background('#044389'); dragInsect(0, mouseX, mouseY); for (var i = 0; i < x.length - 1; i++) { dragInsect(i + 1, x[i], y[i]); LightBullOn = new lightBull(mouseX, mouseY, 50, color(240, 195,15), color(242, 155, 18), color(229, 126, 34)); LightSign = new light(mouseX, mouseY, 7); } } else if (k == 1) { background('#29335C'); randomInsect(0, random(), random()); for (var i = 0; i < x.length - 1; i++) { randomInsect(i + 1, x[i], y[i]); LightBullOff = new lightBull(mouseX, mouseY, 50, color(20, 206, 237), color(24, 170, 234), color(36, 139, 244)); } } fill('white'); noStroke();   textSize(16);   text('click to turn on and off the light',windowWidth-250, windowHeight-20); } function dragInsect(i, xin, yin) { var dx = xin - x[i]; var dy = yin - y[i]; var angle = atan2(dy, dx); x[i] = xin - cos(angle) * random(0,100); y[i] = yin - sin(angle) * random(0,100); Insect(x[i], y[i], angle); } function randomInsect(i, xin, yin) { var dx = xin - x[i]; var dy = yin - y[i]; var angle = atan2(dy, dx); x[i] = random(0, width); y[i] = random(0, height); Insect(x[i], y[i], angle); } function Insect(x, y, a) { push(); translate(x - 30, y - 30); rotate(70); fill('#14ceff'); ellipse(-2, 0, 17, 6); rotate(-70); ellipse(-2, 0, 17, 6); pop(); angleMode(DEGREES); push(); translate(x - 30, y - 30); noStroke(); rotate(a); fill(0); ellipse(0, 0, 14, 10); fill('white'); noStroke(); ellipse(+5, -2, 2, 2); ellipse(+5, +2, 2, 2); stroke('yellow'); strokeWeight(2); noFill(); line(-1, 3.5, -1, -3.5) pop(); } function lightBull(x, y, diameter, color1 , color2, color3) { angleMode(DEGREES); noStroke(); fill(color2); arc(x, y, diameter, diameter, 90, 270, PIE); quad(x,y,x-25,y,x-13,y+30, x,y+30); fill(color1); arc(x, y, diameter, diameter, 270, 90, PIE); quad(x,y,x+25,y,x+13,y+30, x,y+30); noFill(); strokeWeight(2); stroke(color3); line(x+4,y+30,x+14,y); line(x-4,y+30,x-14,y); line(x-14,y,x-6,y+6); line(x,y,x-6,y+6); line(x+14,y,x+6,y+6); line(x,y,x+6,y+6); noStroke(); fill(127, 140, 141); arc(x,y+40,20,20,0,180,PIE); rect(x - 13, y + 30, 13, 3); rect(x - 13, y + 36, 13, 3); fill(149, 164, 165); rect(x - 13, y + 33, 13, 3); rect(x - 13, y + 39, 13, 3); rect(x, y + 30, 13, 3); rect(x, y + 36, 13, 3); fill(189, 194, 197); rect(x, y + 33, 13, 3); rect(x, y + 39, 13, 3); } function light(x, y){ noFill(); strokeWeight(4); stroke(240, 195,15, 90); arc(x, y, 80, 80, 130, 50); stroke(240, 195,15, 20); arc(x, y, 115, 115, 130, 50); stroke(240, 195,15, 10); arc(x, y, 150, 150, 130, 50); } function windowResized() { resizeCanvas(windowWidth, windowHeight); }
SQL
UTF-8
441
2.953125
3
[]
no_license
-- script that prepares a MySQL server for the project: -- A database hbnb_test_db -- A new user hbnb_test (in localhost) -- The password of hbnb_test is: hbnb_test_pwd CREATE DATABASE IF NOT EXISTS hbnb_test_db; CREATE USER IF NOT EXISTS 'hbnb_test'@'localhost' IDENTIFIED BY 'hbnb_test_pwd'; GRANT ALL PRIVILEGES ON hbnb_test_db.* TO 'hbnb_test'@'localhost'; GRANT SELECT ON performance_schema.* TO 'hbnb_test'@'localhost'; FLUSH PRIVILEGES;
JavaScript
UTF-8
631
3.140625
3
[]
no_license
const axios = require('axios'); const url = 'https://swapi.co/api/people' const characters = [] const fetchCharacters = apiURL => { axios.get(apiURL).then(response => { return response }) } // //PROMISE PENDING // fetchCharacters() //PROMISE PENDING const parseCharacters = data => { data.results.forEach(character => characters.push(character.name)) console.log(characters) } const getCharacters = apiURL => { axios.get(apiURL).then(response => { // parseCharacters(response) // parseCharacters(response.data) parseCharacters(response.data); }); } getCharacters(url)
Java
UTF-8
11,285
2.109375
2
[]
no_license
package clayburn.familymap.app.ui; import android.app.ActivityManager; import android.content.Context; import android.content.Intent; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.NavUtils; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; import clayburn.familymap.app.R; import clayburn.familymap.app.network.DataFetchTask; import clayburn.familymap.app.ui.menuItems.MenuFragment; import clayburn.familymap.app.ui.menuItems.SpinnerFragment; import clayburn.familymap.app.ui.menuItems.SpinnerSwitchFragment; import clayburn.familymap.model.Model; import static clayburn.familymap.model.Model.LineName.*; public class SettingsActivity extends AppCompatActivity implements MenuFragment.OnFragmentInteractionListener, DataFetchTask.DataFetchCaller{ private static final String TAG = "SettingsActivity"; private static final String LINE_OPTIONS_HAVE_CHANGED = "clayburn.familymap.app.ui.line_options"; private static final String MAP_OPTIONS_HAVE_CHANGED ="clayburn.familymap.app.ui.map_options"; private static final String DATA_WAS_SYNCED = "clayburn.familymap.app.ui.data_options"; private static final String LOG_OUT_OCCURRED = "clayburn.familymap.app.ui.log_out_occurred"; private Fragment mLifeStoryFragment; private Fragment mFamilyTreeFragment; private Fragment mSpouseFragment; private Fragment mMapTypeFragment; private Fragment mSyncDataFragment; private Fragment mLogOutFragment; private FragmentManager mFM; private boolean mLineOptionsHaveChanged = false; private boolean mMapOptionsHaveChanged = false; private boolean mDataWasSynced = false; public static Intent newIntent(Context packageContext){ return new Intent(packageContext,SettingsActivity.class); } /** * Check if the options pertaining to lines were changed during the SettingsActivity * @param intent The intent returned as a result from the SettingsActivity * @return True if line option were changed, false otherwise */ public static boolean lineOptionsHaveChanged(Intent intent){ return intent != null && intent.getBooleanExtra(LINE_OPTIONS_HAVE_CHANGED, false); } /** * Check if the options pertaining to the map were changed during the SettingsActivity * @param intent The intent returned as a result from the SettingsActivity * @return True if map option were changed, false otherwise */ public static boolean mapOptionsHaveChanged(Intent intent){ return intent != null && intent.getBooleanExtra(MAP_OPTIONS_HAVE_CHANGED, false); } /** * Check if the data was synced during the SettingsActivity * @param intent The intent returned as a result from the SettingsActivity * @return True if data was synced, false otherwise */ public static boolean dataWasSynced(Intent intent){ return intent != null && intent.getBooleanExtra(DATA_WAS_SYNCED, false); } /** * Check if the user logged out in the SettingsActivity * @param intent The intent returned as a result from the SettingsActivity * @return True if the user logged out, false otherwise */ public static boolean logOutOccurred(Intent intent){ return intent != null && intent.getBooleanExtra(LOG_OUT_OCCURRED,false); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); mFM = getSupportFragmentManager(); mLifeStoryFragment = mFM.findFragmentById(R.id.life_story_fragment); mFamilyTreeFragment = mFM.findFragmentById(R.id.family_tree_fragment); mSpouseFragment = mFM.findFragmentById(R.id.spouse_fragment); mMapTypeFragment = mFM.findFragmentById(R.id.map_type_fragment); mSyncDataFragment = mFM.findFragmentById(R.id.sync_data_fragment); mLogOutFragment = mFM.findFragmentById(R.id.log_out_fragment); if (mLifeStoryFragment == null) { mLifeStoryFragment = new SpinnerSwitchFragment(); mFM.beginTransaction() .add(R.id.life_story_fragment,mLifeStoryFragment) .commit(); /* */ } if (mFamilyTreeFragment == null) { mFamilyTreeFragment = new SpinnerSwitchFragment(); mFM.beginTransaction() .add(R.id.family_tree_fragment, mFamilyTreeFragment) .commit(); } if (mSpouseFragment == null) { mSpouseFragment = new SpinnerSwitchFragment(); mFM.beginTransaction() .add(R.id.spouse_fragment,mSpouseFragment) .commit(); } if (mMapTypeFragment == null) { mMapTypeFragment = new SpinnerFragment(); mFM.beginTransaction() .add(R.id.map_type_fragment,mMapTypeFragment) .commit(); } if (mSyncDataFragment == null) { mSyncDataFragment = new MenuFragment(); mFM.beginTransaction() .add(R.id.sync_data_fragment,mSyncDataFragment) .commit(); } if (mLogOutFragment == null) { mLogOutFragment = new MenuFragment(); mFM.beginTransaction() .add(R.id.log_out_fragment,mLogOutFragment) .commit(); } } /** * This is the fragment-orientated version of {@link #onResume()} that you * can override to perform operations in the Activity at the same point * where its fragments are resumed. Be sure to always call through to * the super-class. */ @Override protected void onResumeFragments() { super.onResumeFragments(); SpinnerSwitchFragment ssFragment; SpinnerFragment sFragment; MenuFragment mFragment; Model model = Model.get(); //Life story options ssFragment = (SpinnerSwitchFragment) mLifeStoryFragment; ssFragment.setOptionName(R.string.option_name_life_story); ssFragment.setOptionDetail(R.string.option_detail_life_story); ssFragment.setSource(LINE_OPTIONS_HAVE_CHANGED); ssFragment.setOptionSwitchState(model.isLineDrawn(lifeStoryLines)); ssFragment.setOptionSwitchListener((buttonView, isChecked) -> model.setLineDrawn(lifeStoryLines,isChecked) ); ssFragment.setOptionSpinnerList( R.array.line_color_names, model.getLineColorSelection(lifeStoryLines) ); ssFragment.setOptionSpinnerAction(position -> model.setLineColorSelection(lifeStoryLines,position) ); //Family tree options ssFragment = (SpinnerSwitchFragment) mFamilyTreeFragment; ssFragment.setOptionName(R.string.option_name_family_tree); ssFragment.setOptionDetail(R.string.option_detail_family_tree); ssFragment.setSource(LINE_OPTIONS_HAVE_CHANGED); ssFragment.setOptionSwitchState(model.isLineDrawn(familyTreeLines)); ssFragment.setOptionSwitchListener((buttonView, isChecked) -> model.setLineDrawn(familyTreeLines,isChecked) ); ssFragment.setOptionSpinnerList( R.array.line_color_names, model.getLineColorSelection(familyTreeLines) ); ssFragment.setOptionSpinnerAction(position -> model.setLineColorSelection(familyTreeLines,position) ); //Spouse options ssFragment = (SpinnerSwitchFragment) mSpouseFragment; ssFragment.setOptionName(R.string.option_name_spouse); ssFragment.setOptionDetail(R.string.option_detail_spouse); ssFragment.setSource(LINE_OPTIONS_HAVE_CHANGED); ssFragment.setOptionSwitchState(model.isLineDrawn(spouseLines)); ssFragment.setOptionSwitchListener((buttonView, isChecked) -> model.setLineDrawn(spouseLines,isChecked) ); ssFragment.setOptionSpinnerList( R.array.line_color_names, model.getLineColorSelection(spouseLines) ); ssFragment.setOptionSpinnerAction(position -> model.setLineColorSelection(spouseLines, position) ); //Map Type options sFragment = (SpinnerFragment) mMapTypeFragment; sFragment.setOptionName(R.string.option_name_map_type); sFragment.setOptionDetail(R.string.option_detail_map_type); sFragment.setSource(MAP_OPTIONS_HAVE_CHANGED); sFragment.setOptionSpinnerList(R.array.map_types, model.getCurrentMapTypeIndex()); sFragment.setOptionSpinnerAction(model::setCurrentMapType); //Re-sync options mFragment = (MenuFragment) mSyncDataFragment; mFragment.setOptionName(R.string.option_name_sync_data); mFragment.setOptionDetail(R.string.option_detail_sync_data); mFragment.setSource(DATA_WAS_SYNCED); mFragment.setClickAction(() ->{ new DataFetchTask(this, Model.get().getServerHost(), Model.get().getServerPort()) .execute(Model.get().getAuthToken()); }); //Log out options mFragment = (MenuFragment) mLogOutFragment; mFragment.setOptionName(R.string.option_name_log_out); mFragment.setOptionDetail(R.string.option_detail_log_out); mFragment.setClickAction(() ->{ Model.reset(); Intent data = new Intent(); data.putExtra(LOG_OUT_OCCURRED,true); setResult(RESULT_OK,data); finish(); }); } @Override public void onOptionChanged(@Nullable String source) { if (source == null) { source = ""; } switch (source){ case LINE_OPTIONS_HAVE_CHANGED: mLineOptionsHaveChanged = true; break; case MAP_OPTIONS_HAVE_CHANGED: mMapOptionsHaveChanged = true; break; case DATA_WAS_SYNCED: mDataWasSynced = true; break; } Intent data = new Intent(); data.putExtra(LINE_OPTIONS_HAVE_CHANGED, mLineOptionsHaveChanged); data.putExtra(MAP_OPTIONS_HAVE_CHANGED,mMapOptionsHaveChanged); data.putExtra(DATA_WAS_SYNCED,mDataWasSynced); setResult(RESULT_OK,data); } /** * This method will be called by the DataFetchTask on the object that created it when the * transaction with the server is completed Successfully. */ @Override public void onDataFetchSuccess() { Toast.makeText(this, R.string.sync_success,Toast.LENGTH_LONG).show(); } /** * This method will be called by the DataFetchTask on the object that created it if the * transaction with the server fails * * @param message A message describing the error */ @Override public void onDataFetchFailure(String message) { Toast.makeText(this, message, Toast.LENGTH_LONG).show(); } }
C++
UTF-8
2,537
3.234375
3
[ "WTFPL" ]
permissive
///////////////////////////////////////////////// /// \file ScoreManager.cpp /// \brief Implementation of the ScoreManager class. /// \author Benjamin Ganty /// \date 22nd November 2011 /// \version 1.0 ///////////////////////////////////////////////// #include "ScoreManager.hpp" #include <fstream> ///////////////////////////////////////////////// ScoreManager::ScoreManager(unsigned int nbScores) : m_nbScores(nbScores) {} ///////////////////////////////////////////////// ScoreManager::~ScoreManager() {} ///////////////////////////////////////////////// void ScoreManager::loadFromFile(std::string fileName) { m_scores.clear(); // Opens the file std::ifstream file; file.open(fileName.c_str()); // File reading while(!file.eof() && m_scores.size() < m_nbScores) { Score s; file >> s.player; file >> s.score; m_scores.push_back(s); } file.close(); } ///////////////////////////////////////////////// void ScoreManager::write(std::string fileName) { std::ofstream file; file.open(fileName.c_str()); file.clear(); // Writing into the file for(unsigned int i = 0; i < m_scores.size() && i < m_nbScores; i++) { if(i > 0) file << std::endl; file << m_scores[i].player << " " << m_scores[i].score; } file.close(); } ///////////////////////////////////////////////// bool ScoreManager::isNewScore(unsigned int score) { if(m_scores.size() < m_nbScores) return true; for(unsigned int i = 0; i < m_nbScores; i++) { if(score >= m_scores[i].score) return true; } return false; } ///////////////////////////////////////////////// void ScoreManager::addScore(std::string player, unsigned int score) { bool added = false; for(std::vector<Score>::iterator it = m_scores.begin(); it != m_scores.end(); it++) { if(score >= it->score) { m_scores.insert(it, Score{player, score}); added = true; break; } } if(!added) m_scores.push_back(Score{player, score}); if(m_scores.size() > m_nbScores) m_scores.erase(m_scores.begin() + m_nbScores); } ///////////////////////////////////////////////// unsigned int ScoreManager::getNbScores() { return m_scores.size(); } ///////////////////////////////////////////////// Score ScoreManager::getScore(unsigned int index) { if(index < m_scores.size()) return m_scores[index]; return Score{"", 0}; }
C#
UTF-8
1,362
3.734375
4
[]
no_license
// helper classes which compiles a fast, type-safe delegate for writing various types static class MyBinaryWriterHelper<T> { public static readonly Action<MyBinaryWriter, T> WriteAction; static { // find the existing Write(T) on the MyBinaryWriter type var writeMethod = typeof(MyBinaryWriter).GetMethods() .FirstOrDefault(m => m.Name == "Write" && m.GetArguments().All(p => p.ParameterType == typeof(T)); // if there is no such method, fail if (writeMethod == null) { throw ... } // build up an expression (writer, t) => writer.Write(t) var writerParam = Expression.Parameter(typeof(MyBinaryWriter)); var tParam = Expression.Parameter(typeof(T)); var call = Expression.Call(writerParam, writeMethod, tParam); var lambda = Expression.Lambda<Action<MyBinaryWriter, T>>(call, new[] { writerParam, tParam }); // compile the expression to a delegate, caching the result statically in the // readonly WriteAction field WriteAction = lambda.Compile(); } } // then in your writer class public void Write<T>(IEnumerable<T> collection) { foreach (var t in collection) { MyBinaryWriterHelper<T>.WriteAction(this, t); } }
Markdown
UTF-8
796
3.109375
3
[ "MIT" ]
permissive
# Graph-Edge-Coloring An implementation of a Graph Edge Coloring algorithm. Colors the graph in delta or delta + 1 max colors. Read the graph-theory-report-final.pdf for more information. Graph must be a connected graph for the algorithm to work. To add your test graphs: - You can put them in `test_graphs` folder - The code works for only one graph at a time, so you will manually update the `fileName` in the Main class for each graph, and run them one by one. The format for graphs must be like this: ``` graphName numberOfVertices Edges 0 ``` For example, ``` Simple 4 <- number of vertices -1 2 3 4 <- edges from vertex 1 -2 3 <- edges from vertex 2 -3 4 <- edges from vertex 3 0 ``` Note that it must include a `0` at the last row, and all rows describing edges must begin with a `-`
Python
UTF-8
4,183
2.71875
3
[ "Apache-2.0", "LicenseRef-scancode-generic-cla", "MIT" ]
permissive
from pathlib import Path import rasa.shared.constants from rasa.shared.core.training_data.story_reader.markdown_story_reader import ( MarkdownStoryReader, ) from rasa.shared.core.training_data.story_writer.yaml_story_writer import ( YAMLStoryWriter, ) from rasa.shared.utils.cli import print_success, print_warning from rasa.utils.converter import TrainingDataConverter class StoryMarkdownToYamlConverter(TrainingDataConverter): @classmethod def filter(cls, source_path: Path) -> bool: """Checks if the given training data file contains Core data in `Markdown` format and can be converted to `YAML`. Args: source_path: Path to the training data file. Returns: `True` if the given file can be converted, `False` otherwise """ return MarkdownStoryReader.is_stories_file( source_path ) or MarkdownStoryReader.is_test_stories_file(source_path) @classmethod async def convert_and_write(cls, source_path: Path, output_path: Path) -> None: """Converts the given training data file and saves it to the output directory. Args: source_path: Path to the training data file. output_path: Path to the output directory. """ from rasa.shared.core.training_data.story_reader.yaml_story_reader import ( KEY_ACTIVE_LOOP, ) # check if source file is test stories file if MarkdownStoryReader.is_test_stories_file(source_path): reader = MarkdownStoryReader(is_used_for_training=False, use_e2e=True) output_core_path = cls._generate_path_for_converted_test_data_file( source_path, output_path ) else: reader = MarkdownStoryReader(is_used_for_training=False) output_core_path = cls.generate_path_for_converted_training_data_file( source_path, output_path ) steps = reader.read_from_file(source_path) if YAMLStoryWriter.stories_contain_loops(steps): print_warning( f"Training data file '{source_path}' contains forms. " f"Any 'form' events will be converted to '{KEY_ACTIVE_LOOP}' events. " f"Please note that in order for these stories to work you still " f"need the 'FormPolicy' to be active. However the 'FormPolicy' is " f"deprecated, please consider switching to the new 'RulePolicy', " f"for which you can find the documentation here: " f"{rasa.shared.constants.DOCS_URL_RULES}." ) writer = YAMLStoryWriter() writer.dump( output_core_path, steps, is_test_story=MarkdownStoryReader.is_test_stories_file(source_path), ) print_success(f"Converted Core file: '{source_path}' >> '{output_core_path}'.") @classmethod def _generate_path_for_converted_test_data_file( cls, source_file_path: Path, output_directory: Path ) -> Path: """Generates path for a test data file converted to YAML format. Args: source_file_path: Path to the original file. output_directory: Path to the target directory. Returns: Path to the target converted training data file. """ if cls._has_test_prefix(source_file_path): return ( output_directory / f"{source_file_path.stem}{cls.converted_file_suffix()}" ) return ( output_directory / f"{rasa.shared.constants.TEST_STORIES_FILE_PREFIX}" f"{source_file_path.stem}{cls.converted_file_suffix()}" ) @classmethod def _has_test_prefix(cls, source_file_path: Path) -> bool: """Checks if test data file has test prefix. Args: source_file_path: Path to the original file. Returns: `True` if the filename starts with the prefix, `False` otherwise. """ return Path(source_file_path).name.startswith( rasa.shared.constants.TEST_STORIES_FILE_PREFIX )
Python
UTF-8
1,171
3.75
4
[]
no_license
from unittest import TestCase, main def formatar_nome(nome): palavras = nome.split() if len(palavras) == 1: return palavras[0].upper() if palavras[-1].upper() in ["FILHO", "FILHA", "NETO", "NETA", "SOBRINHO", "SOBRINHA", "JUNIOR"]: restante = " ".join(palavras[:-2]) maiusculo = " ".join([palavras[-2].upper(), palavras[-1].upper()]) return "{}, {}".format(maiusculo, restante) restante = " ".join(palavras[:-1]) return "{}, {}".format(palavras[-1].upper(), restante) class SobreNomeAutorTestCase(TestCase): def test_formatar_nome_simples(self): resposta = formatar_nome("João Silva") self.assertEqual("SILVA, João", resposta) def test_formatar_nome_simples_rezende(self): resposta = formatar_nome("Élysson Mendes Rezende") self.assertEqual("REZENDE, Élysson Mendes", resposta) def test_formatar_nome_uma_palavra(self): resposta = formatar_nome("Guimaraes") self.assertEqual("GUIMARAES", resposta) def test_formatar_nome_sobrenome_filho(self): resposta = formatar_nome("Élysson Mendes Rezende Filho") self.assertEqual("REZENDE FILHO, Élysson Mendes", resposta) if __name__ == "__main__": main()
Python
UTF-8
371
3.171875
3
[ "MIT" ]
permissive
s = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can." words = s.split(" ") foo = [(words[idx - 1][0], idx) for idx in [1, 5, 6, 7, 8, 9, 15, 16, 19]] bar = [(words[idx - 1][:2], idx) for idx in [2, 3, 4, 10, 11, 12, 13, 14, 17, 18, 20]] foobar = {x: y for (x, y) in foo + bar} print(foobar)
Markdown
UTF-8
1,166
2.640625
3
[]
no_license
--- title: Shoe Dog author: Phil Knight vote: 9/10 read_in: English created_at: 2018-11-24 tags: ['review'] --- This book is the story of Nike, told by its founder. A very powerful tale, and a highly fascinating person. The story focuses mostly on the years 1962 to 1980 when the company was finally incorporated. Like all the good life stories, it starts with a trip around the world at a young age. We learn that Onitsuka is not a recent company turned famous because of the shoes of Uma Thurman in Kill Bill, but a very old one, actually older than Nike itself, and the first supplier of the American company. We follow Phil in his tormented journey along which he found his calling (that he encourages everyone to look for), a beautiful wife, and his tribe (in Seth Godin’s sense: the people that share his vision and empower him to pursue it). Very classical American setting of young entrepreneur that goes through Hell and manages to fulfill his project, the underdog coming from the small city (Portland, OR) and draws the attention of the big investors and a wide public with his passion and persistence. Lots of teachings along the way. Highly recommended.
SQL
UTF-8
2,373
3.921875
4
[]
no_license
SET search_path TO first, public; --- Table creation CREATE TABLE first.films ( id serial PRIMARY KEY, title text NOT NULL, country varchar(256), box_office bigint, release_year timestamp ); CREATE TABLE first.persons ( id serial PRIMARY KEY, fio text ); CREATE TABLE first.persons2content ( films_id integer references first.films(id), persons_id integer references first.persons(id), person_type varchar(256) ); CREATE UNIQUE INDEX title_country_uniqueness ON first.films (title, country); CREATE UNIQUE INDEX persons_fio_uniqueness ON first.persons (fio); --- Insertions INSERT INTO films (title, country, box_office, release_year) VALUES ('Test film1', 'Russia', 114344555, to_timestamp('2009-01-01 00:00:00', 'YYYY-MM-DD hh24:mi:ss')::timestamp), ('Test film2', 'Brazil', 1144555, to_timestamp('2015-01-01 00:00:00', 'YYYY-MM-DD hh24:mi:ss')::timestamp), ('Test film3', 'Canada', 1144334555, to_timestamp('2011-01-01 00:00:00', 'YYYY-MM-DD hh24:mi:ss')::timestamp), ('Test film4', 'Republic of Moldova', 11444555, to_timestamp('2015-01-01 00:00:00', 'YYYY-MM-DD hh24:mi:ss')::timestamp), ('Test film5', 'USA', 114444555, to_timestamp('2015-01-01 00:00:00', 'YYYY-MM-DD hh24:mi:ss')::timestamp); INSERT INTO persons (fio) VALUES ('Какой-то мужик1'), ('Какой-то мужик2'), ('Какой-то мужик3'), ('Какая-то тётка1'), ('Какой-то мужик4'); INSERT INTO persons2content VALUES (1,1,'Свет держал'), (2,2,'"Мотор" кричал'), (3,3,'Площадку охранял'), (4,4,'Кофе подавала'), (5,5,'Инспектор постельных сцен'); --- Tables from slides 15, 17 CREATE SCHEMA first_2; SET search_path TO first_2, public; CREATE TABLE first_2.films_15 ( title text, editor varchar(256), has_oscar boolean NOT NULL, IMDB_rating integer CONSTRAINT is_IMDB_rating CHECK ( IMDB_rating >0 AND IMDB_rating < 11 ), PRIMARY KEY (title, editor) ); CREATE TABLE first_2.films17 ( title text PRIMARY KEY, has_oscar boolean NOT NULL, country varchar(256) );
Java
UTF-8
287
1.789063
2
[]
no_license
package assinmenttsc; import javax.swing.JOptionPane; public class MathOlympiad implements Fest{ @Override public void reserveTSC() { // } @Override public void publish() { JOptionPane.showMessageDialog(null,"Connected to Media"); } }
Java
UTF-8
1,095
3.671875
4
[]
no_license
/* // Definition for a Node. class Node { public int val; public Node next; public Node random; public Node() {} public Node(int _val,Node _next,Node _random) { val = _val; next = _next; random = _random; } }; */ class Solution { public Node copyRandomList(Node head) { // Here the key in the hashmap is "Node", actually the address of each node, so even though the value of nodes in the list is not unique, it does not matter, because there address is unique -- they are unique nodes // deep copy all nodes Map<Node, Node> map = new HashMap<>(); Node node = head; while (node != null) { map.put(node, new Node(node.val)); node = node.next; } // assign the next and random to each node node = head; while (node != null) { map.get(node).next = map.get(node.next); map.get(node).random = map.get(node.random); node = node.next; } return map.get(head); } }
Java
UTF-8
1,732
2.5
2
[ "Apache-2.0" ]
permissive
package org.lin.http; import org.lin.controller.AnimeController; import org.lin.util.OSUtil; import org.lin.websocket.WebSocketServer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Lin = ̄ω ̄= * @date 2021/8/2 */ public abstract class AbstractApplication { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractApplication.class); private static final int REST_PORT = 23333; private static final int WEBSOCKET_PORT = 9090; private HttpServer httpServer; private WebSocketServer webSocketServer; public void setup() throws Exception { doCheck(); setupServer(); } protected abstract void setupServer() throws Exception; public void startServer() throws Exception { Runtime.getRuntime().addShutdownHook(new Thread(() -> { try { stopServer(); } catch (Exception e) { } })); if (httpServer != null) { LOGGER.info("http server starting up..."); httpServer.start(); // httpServer.join(); } if (webSocketServer != null) { LOGGER.info("websocket server starting up..."); webSocketServer.start(); // webSocketServer.join(); } } public void stopServer() throws Exception { if (httpServer != null) { httpServer.stopServer(); } if (webSocketServer != null) { webSocketServer.closeServer(); } } protected void setupHttpServer() { httpServer = new HttpServer(REST_PORT); httpServer.addController(new AnimeController()); } protected void setupWebSocketServer() { webSocketServer = new WebSocketServer("127.0.0.1", WEBSOCKET_PORT); } private static void doCheck() { if (OSUtil.isBusyPort(REST_PORT) || OSUtil.isBusyPort(WEBSOCKET_PORT)) { LOGGER.error("port is occupied"); System.exit(0); } } }
Markdown
UTF-8
849
2.8125
3
[ "MIT" ]
permissive
# Ember Hearth Ember Hearth is an application used to manage Ember projects. **Warning: Ember Hearth is alpha software and may misbehave.** ## Features * Installs all needed tools automatically ([node.js](http://nodejs.org), [NPM](http://npmjs.com), [Bower](http://bower.io), [PhantomJS](http://phantomjs.org), [Ember-CLI](http://ember-cli.com)) * Create new Ember projects * Manage existing Ember projects * Run a local server * Create development and release builds ## Installing Go to [ember.town/ember-hearth](http://ember.town/ember-hearth) and download Hearth from there. Double click to extract and move Ember Hearth.app to your Applications folder. ## Goals Ember Hearth aspires to allow new users to do all they need to do to run Ember projects without touching the command line. ## Contributing See [CONTRIBUTING.md](CONTRIBUTING.md)
Java
UTF-8
1,471
2.4375
2
[]
no_license
package com.zzw.thinkpad.thear.weight; import android.os.CountDownTimer; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import pl.droidsonroids.gif.GifImageView; public class CountdownImage extends CountDownTimer { private ImageView ImageView; private GifImageView imageView; private TextView textView; private TextView textView1; int grow; int en; public CountdownImage(long millisInFuture, long countDownInterval, ImageView ImageView, GifImageView imageView, TextView textView, TextView textView1) { super(millisInFuture, countDownInterval); this.ImageView=ImageView; this.imageView=imageView; this.textView=textView; this.textView1=textView1; } @Override public void onTick(long l) { imageView.setVisibility(View.VISIBLE); ImageView.setClickable(false); grow= Integer.parseInt(textView.getText().toString())+10; textView.setText(String.valueOf(grow)); en= Integer.parseInt(textView1.getText().toString())-10; textView1.setText(String.valueOf(en)); } @Override public void onFinish() { if (Integer.parseInt(textView1.getText().toString())<20) { ImageView.setClickable(false); imageView.setVisibility(View.INVISIBLE); } else { ImageView.setClickable(true); imageView.setVisibility(View.INVISIBLE); } } }
Java
UTF-8
1,823
2.265625
2
[]
no_license
package ss.client.ui.Listeners; import java.util.Hashtable; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.widgets.Text; import ss.client.event.SendCreateAction; import ss.client.ui.MessagesPane; import ss.client.ui.SupraSphereFrame; public class SendFieldModifyListener extends CommonInputTextPaneListener implements ModifyListener , KeyListener { @SuppressWarnings("unused") private static final org.apache.log4j.Logger logger = ss.global.SSLogger .getLogger(SendFieldModifyListener.class); private final Hashtable session; public SendFieldModifyListener(SupraSphereFrame sF, MessagesPane mp) { super(sF, mp); this.session = mp.getRawSession(); } public void modifyText(ModifyEvent e) { final String text = ((Text)e.getSource()).getText(); if(text!=null && !text.trim().equals("")) { if ( logger.isDebugEnabled() ) { logger.debug( "notifyUserTyped " + text ); } notifyUserTyped(); } else { if ( logger.isDebugEnabled() ) { logger.debug( "skip modify event " + text ); } } } /* (non-Javadoc) * @see org.eclipse.swt.events.KeyListener#keyPressed(org.eclipse.swt.events.KeyEvent) */ public void keyPressed(KeyEvent e) { if (e.keyCode == 13) { sendMessage(); e.doit = false; } } private void sendMessage() { SendCreateAction sca = new SendCreateAction( this.messagesPaneOwner ); sca.doSendCreateAction( super.getSupraSphereFrame(), this.session ); notifyMessageSent(); } /* (non-Javadoc) * @see org.eclipse.swt.events.KeyListener#keyReleased(org.eclipse.swt.events.KeyEvent) */ public void keyReleased(KeyEvent e) { //NOOP } }
Python
UTF-8
1,327
3.828125
4
[]
no_license
import random #the list with cards cards = ["1", "2", "3", "4", "5", "6", "7", "8", "9"] colors = ['blue', 'green', 'red', 'yellow'] special = ['+2', 'skip a turn', 'reverse'] colorless = ["+4", "choose a color"] deck = [] playerCards = [] aiCards = [] pile = [] #generates the deck of cards for x in range(4): color = colors[x] deck.append(color + " 0") for z in range(2): for y in range(9): deck.append(color +" "+ cards[y]) for c in range(3): deck.append(color + " " + special[c]) for x in range(4): for y in range(2): deck.append(colorless[y]) random.shuffle(deck) def startGame(): input("Press ENTER to start UNO") startTurn = random.randint(0, 1) for x in range(7): aiCards.append(deck[0]) deck.pop(0) playerCards.append(deck[0]) deck.pop(0) pile.append(deck[0]) deck.pop(0) if startTurn == 0: print("Player begins.") if startTurn == 1: print("Opponent begins.") def showDevinfo(): # print("the list of cards currently playable: "+ ", ".join(thelist)) print("the pile in the middle of the table: "+ ", ".join(pile)) print("your current hand: "+ ", ".join(playerCards)) print("the enemy's current hand: " + ", ".join(aiCards)) startGame() showDevinfo()
Java
UTF-8
1,609
2.046875
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2016 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.apiman.manager.api.es.util; /** * @author ewittman */ public class FilterBuilders { public static TermsFilterBuilder termsFilter(String name, String... values) { return new TermsFilterBuilder(name, values); } public static TermFilterBuilder termFilter(String term, String value) { return new TermFilterBuilder(term, value); } public static TermFilterBuilder termFilter(String term, boolean value) { return new TermFilterBuilder(term, value); } public static TermFilterBuilder termFilter(String term, Long value) { return new TermFilterBuilder(term, value); } public static AndFilterBuilder andFilter(QueryBuilder ... filters) { return new AndFilterBuilder(filters); } public static MissingFilterBuilder missingFilter(String name) { return new MissingFilterBuilder(name); } public static OrFilterBuilder orFilter(QueryBuilder ... filters) { return new OrFilterBuilder(filters); } }
Java
UTF-8
4,248
2.421875
2
[]
no_license
package states; import java.awt.Font; import org.lwjgl.input.Mouse; import org.newdawn.slick.Color; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Input; import org.newdawn.slick.Music; import org.newdawn.slick.SlickException; import org.newdawn.slick.Sound; import org.newdawn.slick.TrueTypeFont; import org.newdawn.slick.geom.Rectangle; import org.newdawn.slick.state.BasicGameState; import org.newdawn.slick.state.StateBasedGame; import org.newdawn.slick.Image; import ui_components.Button; /** * * @author Z * */ public class StartScreen extends BasicGameState { private Music music; private int id; private Button playGame; private Button howToPlay; private Button about; private final String s1 = "Play Game"; private final String s2 = "How to play"; private final String s3 = "About"; // fonts from Matt private Font titleFont; private TrueTypeFont tTitleFont; private Font turnFont; private TrueTypeFont h1; private Font categoryFont; private TrueTypeFont h2; private Font teamIndex; private TrueTypeFont h3; private String imageDir = "/resources/images/town/titleImg.png"; private Image img; public StartScreen(int id) { this.id = id; } /** * initializes all variables and objects * * @param arg0 * @param arg1 * @throws SlickException * * Initializes buttons and values */ public void init(GameContainer arg0, StateBasedGame arg1) throws SlickException { music = new Music("resources/Music/MuleMusic.ogg"); music.setVolume(0.2f); music.loop(); titleFont = new Font("Arial", Font.PLAIN, 15); tTitleFont = new TrueTypeFont(titleFont, true); turnFont = new Font("Impact", Font.BOLD, 40); h1 = new TrueTypeFont(turnFont, true); categoryFont = new Font("Impact", Font.PLAIN, 60); h2 = new TrueTypeFont(categoryFont, true); teamIndex = new Font("Arial", Font.PLAIN, 25); h3 = new TrueTypeFont(teamIndex, true); playGame = new Button(300, 250, 220, 50, s1); howToPlay = new Button(300, 350, 220, 50, s2); about = new Button(300, 450, 220, 50, s3); img = new Image(imageDir); } /** * Update loop that will be called constantly. Use this for things you * always want to be checking or running in this state. * * @param container * @param sbg * @param arg2 * @throws SlickException * **/ public void update(GameContainer container, StateBasedGame sbg, int arg2) throws SlickException { if (container.getInput().isMousePressed(Input.MOUSE_LEFT_BUTTON)) { if (playGame.checkClick(container.getInput().getMouseX(), container .getInput().getMouseY())) { sbg.enterState(getID() + 1); } else if (howToPlay.checkClick(container.getInput().getMouseX(), container.getInput().getMouseY())) { // howToPlay.getActionListener().onAction(howToPlay.getButtonName()); } else if (about.checkClick(container.getInput().getMouseX(), container.getInput().getMouseY())) { // about.getActionListener().onAction(about.getButtonName()); } } } /** * @param gc * @param arg1 * @param g * @throws SlickException * * Used to generate the graphics and what to display. * **/ public void render(GameContainer arg0, StateBasedGame arg1, Graphics g) throws SlickException { g.drawImage(img, 0, 0); // title panel g.setColor(Color.darkGray); g.fillRect(0, 0, arg0.getWidth(), 50); // title label g.setColor(Color.white); g.setFont(tTitleFont); g.drawString("Start Screen", ((arg0.getWidth() / 2) - 50), 25); // project name g.setColor(Color.yellow); g.setFont(h2); g.drawString("M.U.L.E.", 330, 100); // team name g.setColor(Color.yellow); g.setFont(h3); g.drawString("by team 25", 430, 170); // set button color g.setColor(Color.white); // button "play game" g.fill(playGame.getButtonShape()); // button "how to play" g.fill(howToPlay.getButtonShape()); // button "about" g.fill(about.getButtonShape()); // labels for three buttons g.setColor(Color.blue); g.setFont(h1); g.drawString(s1, 315, 250); g.setFont(h1); g.drawString(s2, 305, 350); g.setFont(h1); g.drawString(s3, 355, 450); } @Override public int getID() { return id; } }
Java
UTF-8
11,257
2.28125
2
[]
no_license
package application; import java.awt.Toolkit; import java.awt.image.BufferedImage; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.Socket; import java.nio.ByteBuffer; import javax.imageio.ImageIO; import org.apache.http.util.ByteArrayBuffer; import javafx.application.Platform; import javafx.scene.Scene; import javafx.scene.canvas.GraphicsContext; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.StackPane; import javafx.stage.Stage; class ClientReader extends Thread { Socket clientSocket = null; int readBannerBytes = 0; int bannerLength = 2; int readFrameBytes = 0; int frameBodyLength = 0; int frameReadLength = 0; ByteArrayBuffer frameBody = null; byte testLength[]; Banner banner = null; Stage primaryStage = null; boolean firstRead = true; //int testLength = 0; int picNum = 0; GraphicsContext graphicsContext = null; ClientReader(Socket clientSocket, Stage primaryStage, GraphicsContext graphicsContext) { readBannerBytes = 0; bannerLength = 2; readFrameBytes = 0; frameBodyLength = 0; //initialize frameBody frameBody = new ByteArrayBuffer(0); testLength = new byte[4]; //banner = new Banner(); this.clientSocket = clientSocket; this.primaryStage = primaryStage; this.graphicsContext = graphicsContext; } @Override public void run() { try { InputStream inputStream = clientSocket.getInputStream(); BufferedInputStream bis = new BufferedInputStream(inputStream); banner = getBanner(bis); while(true){ byte[] byteArray = getScreenShot(bis); // toByteArray("testpicture" + (picNum++) + ".jpg", byteArray); // if (frameBody.byteAt(0) != 0xFF || frameBody.byteAt(1) != 0xD8) { // // } // else displayImage(byteArray); } } catch (Exception e) { e.printStackTrace(); } } public void displayImage(byte img[]){ StackPane sp = new StackPane(); Platform.runLater(() -> { Image im = new Image( new ByteArrayInputStream(img) ); //Image img = Toolkit.getDefaultToolkit().createImage(bufferedImage.getSource()); graphicsContext.drawImage(im, 0, 0, 720, 1280); primaryStage.show(); }); } public Banner getBanner(BufferedInputStream bis){ byte byteArray[] = new byte[24]; Banner banner = new Banner(); int chunk = 0; try { chunk = bis.read(byteArray); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } for (int cursor = 0; chunk > cursor ; ) { if (readBannerBytes < bannerLength) { switch (readBannerBytes) { case 0: // version System.out.println( "version, cur " + cursor); banner.setVersion(byteArray[cursor] & 0xFF); break; case 1: // length bannerLength = byteArray[cursor]& 0xFF; banner.setLength(bannerLength); System.out.println( "bannerLength " + bannerLength); break; case 2: case 3: case 4: case 5: System.out.println( "before pid, chunk cur " + byteArray[cursor]); System.out.println( "pid, cur " + cursor); System.out.println( "pid, chunk cur " + byteArray[cursor]); System.out.println( "pid, chunk cur1 (readBannerBytes - 2) = " + (readBannerBytes - 2)); System.out.println( "pid, chunk cur2 " + ((byteArray[cursor] << ((readBannerBytes - 2) * 8)))); System.out.println( "pid, chunk cur3 " + ((byteArray[cursor] << ((readBannerBytes - 2) * 8)) >>> 0)); // pid banner.setPid(banner.getPid() + (((byteArray[cursor]& 0xFF) << ((readBannerBytes - 2) * 8)) >>> 0)); break; case 6: case 7: case 8: case 9: System.out.println( "before real width, chunk cur " + byteArray[cursor]); System.out.println( "real width, cur " + cursor); System.out.println( "real width, chunk cur " + byteArray[cursor]); System.out.println( "real width, chunk cur1 (readBannerBytes - 6) = " + (readBannerBytes - 6)); System.out.println( "real width, chunk cur2 " + ((byteArray[cursor] << ((readBannerBytes - 6) * 8)))); System.out.println( "real width, chunk cur3 " + ((byteArray[cursor] << ((readBannerBytes - 6) * 8)) >>> 0)); // real width banner.setRealWidth(banner.getRealWidth() + (((byteArray[cursor]& 0xFF) << ((readBannerBytes - 6) * 8)) >>> 0)); break; case 10: case 11: case 12: case 13: System.out.println( "before real height, chunk cur " + byteArray[cursor]); System.out.println( "real height, cur " + cursor); System.out.println( "real height, chunk cur " + byteArray[cursor]); System.out.println( "real height, chunk cur1 (readBannerBytes - 10) = " + (readBannerBytes - 10)); System.out.println( "real height, chunk cur2 " + ((byteArray[cursor] << ((readBannerBytes - 10) * 8)))); System.out.println( "real height, chunk cur3 " + ((byteArray[cursor] << ((readBannerBytes - 10) * 8)) >>> 0)); // real height banner.setRealHeight(banner.getRealHeight() + (((byteArray[cursor]& 0xFF) << ((readBannerBytes - 10) * 8)) >>> 0)); break; case 14: case 15: case 16: case 17: System.out.println( "before virtual width, chunk cur " + byteArray[cursor]); System.out.println( "virtual width, cur " + cursor); System.out.println( "virtual width, chunk cur " + byteArray[cursor]); System.out.println( "virtual width, chunk cur1 (readBannerBytes - 14) = " + (readBannerBytes - 14)); System.out.println( "virtual width, chunk cur2 " + ((byteArray[cursor] << ((readBannerBytes - 14) * 8)) )); System.out.println( "virtual width, chunk cur3 " + ((byteArray[cursor] << ((readBannerBytes - 14) * 8)) >>> 0)); // virtual width banner.setVirtualWidth( banner.getVirtualWidth() + (((byteArray[cursor]& 0xFF) << ((readBannerBytes - 14) * 8)) >>> 0) ); break; case 18: case 19: case 20: case 21: System.out.println( "before virtual height, chunk cur " + byteArray[cursor]); System.out.println( "virtual height, cur " + cursor); System.out.println( "virtual height, chunk cur " + byteArray[cursor]); System.out.println( "virtual height, chunk cur1 (readBannerBytes - 18) = " + (readBannerBytes - 18)); System.out.println( "virtual height, chunk cur2 " + ((byteArray[cursor] << ((readBannerBytes - 18) * 8)) )); System.out.println( "virtual height, chunk cur3 " + ((byteArray[cursor] << ((readBannerBytes - 18) * 8)) >>> 0)); // virtual height banner.setVirtualHeight( banner.getVirtualHeight() + (((byteArray[cursor]& 0xFF) << ((readBannerBytes - 18) * 8)) >>> 0) ); break; case 22: System.out.println( "before orientation, chunk cur " + byteArray[cursor]); System.out.println( "orientation, cur " + cursor); System.out.println( "orientation, chunk cur " + byteArray[cursor]); System.out.println( "orientation, chunk cur2 " + (byteArray[cursor] * 90)); // orientation banner.setOrientation(banner.getOrientation() + ((byteArray[cursor]& 0xFF) * 90) ); break; case 23: System.out.println( "quirks, cur " + cursor); // quirks banner.setQuirks(byteArray[cursor]& 0xFF); break; } cursor += 1; readBannerBytes += 1; if (readBannerBytes == bannerLength) { System.out.println("banner = " + banner); } } } return banner; } public byte[] getScreenShot(BufferedInputStream bis){ byte imageDataLength[] = new byte[4]; byte imageData[] = null; int chunk = 0; try { chunk = bis.read(imageDataLength); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } int frameBodyLength = 0; for (int readFrameBytes = 0; chunk > readFrameBytes ; readFrameBytes ++ ) { frameBodyLength += (((imageDataLength[readFrameBytes]& 0xFF) << (readFrameBytes * 8)) >>> 0); } System.out.println("headerbyte" + readFrameBytes +"(val=" + frameBodyLength + ")"); imageData = new byte[frameBodyLength]; int readImageData = 0; while(true){ try { chunk = bis.read(imageData, readImageData, frameBodyLength - readImageData); readImageData += chunk; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(readImageData == frameBodyLength) break; } return imageData; } public static byte[] toByteArray(String name, byte[] data) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); boolean threw = true; FileOutputStream outfile = new FileOutputStream(new File(name)); try { out.write(data, 0, data.length); out.writeTo(outfile); } finally { try { out.close(); outfile.close(); } catch (IOException e) { if (threw) { System.out.println("IOException thrown while closing, " + e); } else { throw e; } } } return out.toByteArray(); } }
Ruby
UTF-8
178
3.546875
4
[]
no_license
def average(arr) total = 0 arr.each do |num| total += num end total / arr.length.to_f end puts average([1, 5, 87, 45, 8, 8]) puts average([9, 47, 23, 95, 16, 52])
Java
UTF-8
808
2.734375
3
[]
no_license
package ejercicioPlatos; import java.util.concurrent.TimeUnit; public class Colocador implements Runnable { PilaDePlatos pilaPlatosSecos; PilaDePlatos alacena; public Colocador(PilaDePlatos pilaPlatosSecos, PilaDePlatos alacena) { this.pilaPlatosSecos = pilaPlatosSecos; this.alacena = alacena; } @Override public void run() { Plato plato; for (int i = 0; i < 50; i++) { plato = pilaPlatosSecos.removePlato(Thread.currentThread().getName()); try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } plato.setEstado(Estado.GUARGADO); alacena.addPlato(plato, Thread.currentThread().getName()); } } }
Markdown
UTF-8
2,149
2.765625
3
[]
no_license
# Questions: If LT member submit form, does it need approval by another LT member? # HR Action Form React app that allows leaders within CCB to post an HR action form. ## Tech learned/practiced in this project: * React * Redux * Firebase * Material UI * Formik * Yup * Jest & Enzyme * day.js (replaces moment.js) * Styled Components * memoize * axios (removed as not needed) * React Context API (removed in favor of Redux) ## Tech to Add * TypeScript * Slack API ## TODO * Setup chain logic for notifications * Add more options for responses based on the various forms * Change alerts to notification banner. * Send notification on form submission to Slack. * Get response from Slack, save to Firebase DB. * Send additional notifications to Slack based on previous Slack responses. ## Chain Logic 1) If HR has not approved, hide from everyone else 2) If HR has approved, FIN is required response but has not responded, hide from everyone else 3) If HR & FIN have approved, LT is a required response but has not responded, hide from everyone else 4) If HR, FIN, and/or LT have approved, show to CEO ## Notifications General rules: If any responder denies, send the submitter a notification Process (assuming all responders are needed): When a new form is submitted, notify HR When HR approves, send FIN a notification When FIN approves, if the submitter is not LT, send the selected LT member a notification If submitter is LT & FIN approves, or LT approves, and CEO needs to respond, send CEO notification. If CEO approves, send submitter notification. ## Responses The responses change based on the type form submitted. Every form needs to responses from HR and the Leadership Team. ### CEO Response The CEO needs to respond to these requests: * Talent Acquisition - New Position * Add Role * Transfer/Promotion ### Finance Response Finance needs to respond to these requests: * All Employment types * Talent Acquisition - New Position * Add Role * Leave Requests ### Notifications IT and Facilities needs to be notified about some requests, but just require limited information, like the employee name and start date.
Java
UTF-8
2,201
2.0625
2
[]
no_license
package jfox.platform.function.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import jfox.platform.infrastructure.LocalNamingAndRefInspectableEntityObject; /** * @author <a href="mailto:jfox.young@gmail.com">Young Yang</a> */ @Entity @Table(name="T_FUNC_NODE") public class Node extends LocalNamingAndRefInspectableEntityObject { public static final int TYPE_MENU = 0; public static final int TYPE_BUTTON = 1; public static final int CRUD_C = 0; public static final int CRUD_R = 1; public static final int CRUD_U = 2; public static final int CRUD_D = 3; @Column(name="BIND_ACTION") private String bindAction; @Column(name="MODULE_ID") private long moduleId; @Column(name="PARENT_ID") private long parentId; @Column(name="NODE_GROUP") private String nodeGroup; @Column(name="ICON") private String icon; @Column(name="TYPE") private int type; @Column(name="CRUD") private int crud; public String getBindAction() { return bindAction; } public void setBindAction(String bindAction) { this.bindAction = bindAction; } public long getModuleId() { return moduleId; } public void setModuleId(long moduleId) { this.moduleId = moduleId; } public long getParentId() { return parentId; } public void setParentId(long parentId) { this.parentId = parentId; } public String getNodeGroup() { return nodeGroup; } public void setNodeGroup(String nodeGroup) { this.nodeGroup = nodeGroup; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public int getType() { return type; } public void setType(int type) { this.type = type; } public boolean isMenu(){ return getType() == TYPE_MENU; } public int getCrud() { return crud; } public void setCrud(int crud) { this.crud = crud; } }
TypeScript
UTF-8
3,045
2.671875
3
[ "Apache-2.0" ]
permissive
import * as Calendars from '../test/data/Calendars'; import * as Weekdays from '../test/data/Weekdays'; import { getWeekdaySpan } from './WeekdayUtils'; test('Sample normal openings return appropriate current openings', () => { const OPENINGS = Calendars.SUMMER_SP_1_2.normalHours; expect(getWeekdaySpan(OPENINGS[0])).toStrictEqual([Weekdays.Saturday]); expect(getWeekdaySpan(OPENINGS[1])).toStrictEqual([ Weekdays.Monday, Weekdays.Tuesday, ]); expect(getWeekdaySpan(OPENINGS[2])).toStrictEqual([Weekdays.Tuesday]); expect(getWeekdaySpan(OPENINGS[3])).toStrictEqual([Weekdays.Wednesday]); expect(getWeekdaySpan(OPENINGS[4])).toStrictEqual([Weekdays.Thursday]); expect(getWeekdaySpan(OPENINGS[5])).toStrictEqual([Weekdays.Friday]); expect(getWeekdaySpan(OPENINGS[6])).toStrictEqual([Weekdays.Friday]); }); test('Long range normal openings return appropriate spans', () => { expect( getWeekdaySpan({ startDay: Weekdays.Monday, startTime: '07:00', endDay: Weekdays.Friday, endTime: '23:00', }) ).toStrictEqual([ Weekdays.Monday, Weekdays.Tuesday, Weekdays.Wednesday, Weekdays.Thursday, Weekdays.Friday, ]); expect( getWeekdaySpan({ startDay: Weekdays.Thursday, startTime: '07:00', endDay: Weekdays.Tuesday, endTime: '23:00', }) ).toStrictEqual([ Weekdays.Thursday, Weekdays.Friday, Weekdays.Saturday, Weekdays.Sunday, Weekdays.Monday, Weekdays.Tuesday, ]); }); test('247 ranges return expected spans', () => { expect( getWeekdaySpan({ startDay: Weekdays.Sunday, startTime: '00:00', endDay: Weekdays.Saturday, endTime: '23:59', }) ).toStrictEqual([ Weekdays.Sunday, Weekdays.Monday, Weekdays.Tuesday, Weekdays.Wednesday, Weekdays.Thursday, Weekdays.Friday, Weekdays.Saturday, ]); expect( getWeekdaySpan({ startDay: Weekdays.Wednesday, startTime: '00:00', endDay: Weekdays.Tuesday, endTime: '23:59', }) ).toStrictEqual([ Weekdays.Wednesday, Weekdays.Thursday, Weekdays.Friday, Weekdays.Saturday, Weekdays.Sunday, Weekdays.Monday, Weekdays.Tuesday, ]); expect( getWeekdaySpan({ startDay: Weekdays.Wednesday, startTime: '12:00', endDay: Weekdays.Wednesday, endTime: '11:59', }) ).toStrictEqual([ Weekdays.Wednesday, Weekdays.Thursday, Weekdays.Friday, Weekdays.Saturday, Weekdays.Sunday, Weekdays.Monday, Weekdays.Tuesday, Weekdays.Wednesday, ]); }); test('247-ish with mid-day gap normal openings return appropriate span', () => { expect( getWeekdaySpan({ startDay: Weekdays.Wednesday, startTime: '23:00', endDay: Weekdays.Wednesday, endTime: '07:59', }) ).toStrictEqual([ Weekdays.Wednesday, Weekdays.Thursday, Weekdays.Friday, Weekdays.Saturday, Weekdays.Sunday, Weekdays.Monday, Weekdays.Tuesday, Weekdays.Wednesday, ]); });