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
Markdown
UTF-8
499
2.921875
3
[]
no_license
#### 1、synchronized - 1、一个线程访问一个对象的synchronized(this),其他访问该对象的的synchronized将被阻塞 - 2、当一个线程访问一个对象的synchronized(this)时,其他方法仍可以放非synchronized方法 - 3、当synchronized 修饰静态方法是,静态方法是属于类的,因为所有此类的实例将共享同一把锁,即两个不同的对象并发执行时依然要执行同步 - 4、当synchronized 修饰类是同修饰静态方法一致
C#
UTF-8
923
3.515625
4
[]
no_license
using System; namespace _1012 { class Program { static void Main(string[] args) { double triangulo, raio, trapezio, quadrado, retangulo; double.TryParse(Console.ReadLine(), out double A); double.TryParse(Console.ReadLine(), out double B); double.TryParse(Console.ReadLine(), out double C); triangulo = (A / 2) * C; Console.WriteLine("TRIANGULO: {0:F3}", triangulo); raio = C * C * 3.14159; Console.WriteLine("CIRCULO: {0:F3}", raio); trapezio = (A + B) * (C / 2); Console.WriteLine("TRAPEZIO: {0:F3}", trapezio); quadrado = B * B; Console.WriteLine("QUADRADO: {0:F3}", quadrado); retangulo = A * B; Console.WriteLine("RETANGULO: {0:F3}", retangulo); } } }
C
UTF-8
536
3.921875
4
[]
no_license
#include <stdio.h> #include <stdlib.h> float values[] = { 8.8, 5.6, 10.0, 2, 2.5 }; int cmpfunc (const void * a, const void * b) { return ( *(int*)a - *(int*)b ); } int main() { int n; printf("Before sorting the list is: \n"); for( n = 0 ; n < 5; n++ ) { printf("%.1f ", values[n]); } qsort(values, 5, sizeof(float), cmpfunc); printf("\nAfter sorting the list is: \n"); for( n = 0 ; n < 5; n++ ) { printf("<% class="1"> </%>f ", values[n]); } printf("\n"); return(0); }
Python
UTF-8
1,172
2.671875
3
[]
no_license
import lcddriver from time import sleep import requests as r CHAMBERS = 8 # Request that the Brewpi socket expects data = {"messageType": "lcd", "message": ""} lcd = lcddriver.lcd() while True: # Cycle through all of our chambers for i in xrange(0, CHAMBERS): # Start the screen out fresh lcd.lcd_clear() try: # Communicated with the brewpi script. I know...crazy setup resp = r.post("http://localhost/chamber" + str(i) + "/socketmessage.php", data=data).json() except: resp = ['Cannot receive', 'LCD text from', 'Python script', ''] for index, line in enumerate(resp): # Things to make the text less confusing for my particular setup. if "Mode" in line: line = "Chamber " + str(i) if "Fridge" in line: line = line.replace("Fridge", "Beer") if "Beer --.- --.-" in line: line = "" # Newlines make a weird symbol on the lcd if line == "\n": line = "" lcd.lcd_display_string(line.replace("&deg", ""), index+1) sleep(2)
JavaScript
UTF-8
12,587
2.859375
3
[]
no_license
//定义一个全局变量,项目的根路径 //获取当前网址,如: var curWwwPath=window.document.location.href; //获取主机地址之后的目录如:/Tmall/index.jsp var pathName=window.document.location.pathname; var pos=curWwwPath.indexOf(pathName); //获取主机地址,如://localhost:8080 var localhostPaht=curWwwPath.substring(0,pos); //获取带"/"的项目名,如:/Tmall var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1); var pageContextPath=projectName; /** * jquery中的ajax方法详解 * 1、url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址。 * 2、type: 要求为String类型的参数,请求方式(post或get)默认为get。 * 3、timeout:要求为Number类型的参数,设置请求超时时间(毫秒)。此设置将覆盖$.ajaxSetup()方法的全局设置。 * 4、async:要求为Boolean类型的参数,默认设置为true,所有请求均为异步请求。 * 如果需要发送同步请求,请将此选项设置为false。注意,同步请求将锁住浏览器, * 用户其他操作必须等待请求完成才可以执行。 * 5、cache:要求为Boolean类型的参数,默认为true(当dataType为script时,默认为false),设置为false将不会从浏览器缓存中加载请求信息。 * 6、data:要求为Object或String类型的参数,发送到服务器的数据。如果已经不是字符串,将自动转换为字符串格式。 * 例如: * {foo1:"bar1",foo2:"bar2"}转换为&foo1=bar1&foo2=bar2。 * 如果是数组,JQuery将自动为不同值对应同一个名称。 * 例如{foo:["bar1","bar2"]}转换为&foo=bar1&foo=bar2。 * 7、dataType:要求为String类型的参数,预期服务器返回的数据类型。 * 如果不指定,JQuery将自动根据http包mime信息返回responseXML或responseText, * 并作为回调函数参数传递。可用的类型如下: * xml:返回XML文档,可用JQuery处理。 * html:返回纯文本HTML信息;包含的script标签会在插入DOM时执行。 * script:返回纯文本JavaScript代码。不会自动缓存结果。 * 除非设置了cache参数。注意在远程请求时(不在同一个域下),所有post请求都将转为get请求。 * json:返回JSON数据。 * jsonp:JSONP格式。使用SONP形式调用函数时,例如myurl?callback=?, * JQuery将自动替换后一个“?”为正确的函数名,以执行回调函数。 * text:返回纯文本字符串。 * 8、beforeSend * 要求为Function类型的参数,发送请求前可以修改XMLHttpRequest对象的函数,例如添加自定义HTTP头。 * 在beforeSend中如果返回false可以取消本次ajax请求。XMLHttpRequest对象是惟一的参数。 function(XMLHttpRequest){ this; //调用本次ajax请求时传递的options参数 } * * 9、complete:要求为Function类型的参数,请求完成后调用的回调函数(请求成功或失败时均调用)。 * 参数:XMLHttpRequest对象和一个描述成功请求类型的字符串。 * function(XMLHttpRequest, textStatus){ this; //调用本次ajax请求时传递的options参数 } * 10、success:要求为Function类型的参数,请求成功后调用的回调函数,可以一个参数,也可以有两个参数。 * (1)由服务器返回,并根据dataType参数进行处理后的数据。 (2)描述状态的字符串。 function(data, textStatus){ //data可能是xmlDoc、jsonObj、html、text等等 this; //调用本次ajax请求时传递的options参数 } * 11、error:要求为Function类型的参数,请求失败时被调用的函数。 * 12、contentType:要求为String类型的参数,当发送信息至服务器时, * 内容编码类型默认为"application/x-www-form-urlencoded"。该默认值适合大多数应用场合。 * 13、dataFilter:要求为Function类型的参数,给Ajax返回的原始数据进行预处理的函数。 * 提供data和type两个参数。data是Ajax返回的原始数据, * type是调用jQuery.ajax时提供的dataType参数。函数返回的值将由jQuery进一步处理。 * function(data, type){ //返回处理后的数据 return data; } * * 14、global:要求为Boolean类型的参数,默认为true。表示是否触发全局ajax事件。设置为false将不会触发全局ajax事件,ajaxStart或ajaxStop可用于控制各种ajax事件。 * 15、ifModified:要求为Boolean类型的参数,默认为false。仅在服务器数据改变时获取新数据。服务器数据改变判断的依据是Last-Modified头信息。默认值是false,即忽略头信息。 * 16、jsonp:要求为String类型的参数,在一个jsonp请求中重写回调函数的名字。该值用来替代在"callback=?"这种GET或POST请求中URL参数里的"callback"部分,例如{jsonp:'onJsonPLoad'}会导致将"onJsonPLoad=?"传给服务器。 * 17、username:要求为String类型的参数,用于响应HTTP访问认证请求的用户名。 * 18、password:要求为String类型的参数,用于响应HTTP访问认证请求的密码。 * 19、processData:要求为Boolean类型的参数,默认为true。默认情况下,发送的数据将被转换为对象(从技术角度来讲并非字符串)以配合默认内容类型"application/x-www-form-urlencoded"。如果要发送DOM树信息或者其他不希望转换的信息,请设置为false。 * 20、scriptCharset:要求为String类型的参数,只有当请求时dataType为"jsonp"或者"script",并且type是GET时才会用于强制修改字符集(charset)。通常在本地和远程的内容编码不同时使用。 * * 案例: $(function(){ $('#send').click(function(){ $.ajax({ type: "GET", url: "test.json", data: {username:$("#username").val(), content:$("#content").val()}, dataType: "json", success: function(data){ $('#resText').empty(); //清空resText里面的所有内容 var html = ''; $.each(data, function(commentIndex, comment){ html += '<div class="comment"><h6>' + comment['username'] + ':</h6><p class="para"' + comment['content'] + '</p></div>'; }); $('#resText').html(html); } }); }); }); */ //$(function(){ // //alert('加载httpService.js后就会立刻执行该方法'); // //alert('pageContextPath='+pageContextPath); //}); /** * 使用post方式向后台发送请求 * @param url 请求的URL * @param data * 请求的参数, * 参数可以通过序列化传输:var params = $("#login").serialize(); * login为form表单的id。 * 通过form表单的name标识,控制层通过参数对应的name来接收或对象(属性同名)来接收 * @param succssFun * 加载成功后的函数,回调方法,请求返回时response返回数据时包含了dataType,如:json数据对象 */ function sendRequest(url, data, succssFun,asy) { var async = true;//默认为true,异步请求。 if(asy==undefined){ async = true; } if(asy == false) { async = false;//同步请求,必须等该请求执行完,才能在去请求其他的URL。 } $.ajax({ url:url, dataType:'json', type:'post', data:data, async:async, success: function(jsonData) {//jsonData为response数据 //alert(jsonData.result); /** * 将后台响应的数据转换成json数据,function(jsonData)返回时执行的方法,即回调方法, * result如果该jsonData对象里没有该result属性,则jsonData.result为undefined * !undefined 为true. */ if (!jsonData.result) {//result参考com.tentinet.app.util.OMSSecurityFilter.doFilter() //alert("errorCode="+jsonData.errorCode); if (jsonData.errorCode == -2000) { // 没有权限访问时就跳转到登录页面 top.location.href=pageContextPath+"/login.html"; } else if (jsonData.errorCode == 0) { //alert(0); // alert("对不起,系统正忙请您稍后重试!"); } else { //alert(1); succssFun(jsonData);//调用传递进来的参数函数。 } } else { //alert(2); succssFun(jsonData); } }, error:function(jsonData) { // alert("对不起,系统正忙请您稍后重试!"); } }); } /** * $.ajax(,async不设置默认为true * 使用get方式向后台发送请求 * @param url 请求的URL * @param data 请求的参数 * @param succssFun 加载成功后的函数 */ function sendRequestByGet(url, data, succssFun) { $.ajax({ url: url , dataType: 'json', type:'get', data:data, complete:function(jsonData){ }, success: function(jsonData) { if (!jsonData.result) { if (jsonData.errorCode == -2000) { // 没有权限访问时就跳转到登录页面 top.location.href=pageContextPath+"/login.html"; } else if (jsonData.errorCode == 0) { // alert("对不起,系统正忙请您稍后重试!"); }else { succssFun(jsonData); } } else { succssFun(jsonData); } }, error:function(jsonData) { // alert("对不起,系统正忙请您稍后重试!"); } }); } /** * 获取url中的参数值,方法1 * @param paras为?后的参数名,通过该方法能获取到该参数名对应的参数值 */ function getURLParams(paras) { // var url = location.href; //var url = "http://192.168.1.73:9220/paoms/index.html?testParam=123"; var url = window.location.href; var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&"); var paraObj = {}; for (i = 0; j = paraString[i]; i++) { paraObj[j.substring(0, j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=") + 1, j.length); } var returnValue = paraObj[paras.toLowerCase()]; if (typeof(returnValue) == "undefined") { return ""; } else { return returnValue; } } /** * 获取地址栏?后的参数值,方法2 * @param name传入?后的参数名 */ function getQueryString(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); var r = window.location.search.substr(1).match(reg); if (r != null) return unescape(r[2]); return null; } /** * 使用AJAX提交表单 */ function submitForm(formId, url, successFun, errorFun) { $(formId).formSerialize(); var options = { url:url, type:'POST', dataType:'json', success : function(jsonData) { if (!jsonData.result) { if (jsonData.errorCode == -2000) { // 没有权限访问时就跳转到登录页面 top.location.href=pageContextPath+"/login.html"; } else if (jsonData.errorCode == 0) { //alert("对不起,系统正忙请您稍后重试!"); } else { errorFun(jsonData); } } else { successFun(jsonData); } } }; $(formId).ajaxSubmit(options); return false; } /** * trim函数,重写了String的trim(),比如p=" aa ",p.trim()后可以去掉aa左右前后的空格字符。 * 空格开头或者空格结尾 * ^是开始 * \s是空白 * *表示0个或多个 * |是或者 * $是结尾 * g表示全局,g:执行全局匹配,而不是找到第一个匹配就停止。 * 匹配首尾空格的正则表达式:(^\s*)|(\s*$) */ String.prototype.trim = function() { return this.replace(/(^\s*)|(\s*$)/g, ""); };
Python
UTF-8
6,337
2.859375
3
[]
no_license
import unittest from CryptoBot.BackTest import BackTestExchange class BackTestExchangeTestCase(unittest.TestCase): test_obj = BackTestExchange( '/Users/rjh2nd/PycharmProjects/CryptoNeuralNet/CryptoBot/CryptoBotUnitTests/UnitTestData/order_book_for_back_test_unit_tests.csv') def test_can_return_top_order(self): self.test_obj.time = 0 top_bid = self.test_obj.get_top_order('bids') top_ask = self.test_obj.get_top_order('asks') self.assertEqual(top_bid, 100, 'Incorrect bid') self.assertEqual(top_ask, 101, 'Incorrect ask') def test_returns_current_order_book(self): self.test_obj.time = 3 test_book = self.test_obj.get_current_book() self.assertEqual(test_book['0'].values[0], 102) self.assertEqual(test_book['60'].values[0], 105) def test_places_bid_with_correct_price_and_size_and_removes_order(self): price = 100 size = 1 side = 'bids' self.test_obj.time = 3 self.test_obj.place_order(price, 'bids', size) self.assertEqual(price, self.test_obj.orders[side][0]['price'], 'Incorrect price') self.assertEqual(size, self.test_obj.orders[side][0]['size'], 'Incorrect size') self.assertTrue(self.test_obj.orders[side][0]['is maker'], 'Maker order placed as taker') self.test_obj.remove_order(side, 0) self.assertEqual(len(self.test_obj.orders[side]), 0, 'Did not remove order') def test_places_ask_with_correct_price_and_size_and_removes_order(self): price = 105.1 size = 1 side = 'asks' self.test_obj.time = 3 self.test_obj.place_order(price, side, size) self.assertEqual(price, self.test_obj.orders[side][0]['price'], 'Incorrect price') self.assertEqual(size, self.test_obj.orders[side][0]['size'], 'Incorrect size') self.assertTrue(self.test_obj.orders[side][0]['is maker'], 'Maker order placed as taker') self.test_obj.remove_order(side, 0) self.assertEqual(len(self.test_obj.orders[side]), 0, 'Did not remove order') def test_places_ask_as_taker_with_post_only_disabled_and_removes_order(self): post_price = 100 fill_price = 102 size = 1 side = 'asks' self.test_obj.time = 3 self.test_obj.place_order(post_price, side, size, post_only=False) self.assertEqual(fill_price, self.test_obj.orders[side][0]['price'], 'Incorrect price') self.assertEqual(size, self.test_obj.orders[side][0]['size'], 'Incorrect size') self.assertTrue(self.test_obj.orders[side][0]['filled'], 'Order placed as taker did not fill') self.assertFalse(self.test_obj.orders[side][0]['is maker'], 'Taker order placed as maker') self.test_obj.remove_order(side, 0) self.assertEqual(len(self.test_obj.orders[side]), 0, 'Did not remove order') def test_places_bid_as_taker_with_post_only_disabled_and_removes_order(self): post_price = 106 fill_price = 105 size = 1 side = 'bids' self.test_obj.time = 3 self.test_obj.place_order(post_price, side, size, post_only=False) self.assertEqual(fill_price, self.test_obj.orders[side][0]['price'], 'Incorrect price') self.assertEqual(size, self.test_obj.orders[side][0]['size'], 'Incorrect size') self.assertTrue(self.test_obj.orders[side][0]['filled'], 'Order placed as taker did not fill') self.assertFalse(self.test_obj.orders[side][0]['is maker'], 'Taker order placed as maker') self.test_obj.remove_order(side, 0) self.assertEqual(len(self.test_obj.orders[side]), 0, 'Did not remove order') def test_will_not_place_bid_on_ask_book(self): price = 110 size = 1 side = 'bids' self.test_obj.time = 3 self.test_obj.place_order(price, 'bids', size) self.assertEqual(len(self.test_obj.orders[side]), 0, 'Placed bid on ask book') def test_will_not_place_ask_on_bid_book(self): price = 90 size = 1 side = 'asks' self.test_obj.time = 3 self.test_obj.place_order(price, 'asks', size) self.assertEqual(len(self.test_obj.orders[side]), 0, 'Placed ask on bid book') def test_can_update_fill_status_for_bids(self): price = 102.5 size = 1 side = 'bids' self.test_obj.time = 1 self.test_obj.place_order(price, side, size) self.assertFalse(self.test_obj.orders[side][0]['filled'], 'Bid auto filled') self.test_obj.time = 2 self.test_obj.update_fill_status() self.assertTrue(self.test_obj.orders[side][0]['filled'], 'Bid did not fill') def test_can_update_fill_status_for_asks(self): price = 103 size = 1 side = 'asks' self.test_obj.time = 3 self.test_obj.place_order(price, side, size) self.assertFalse(self.test_obj.orders[side][0]['filled'], 'Ask auto filled') self.test_obj.time = 4 self.test_obj.update_fill_status() self.assertTrue(self.test_obj.orders[side][0]['filled'], 'Ask did not fill') def test_does_not_incorrectly_update_fill_status_for_asks(self): price = 120 size = 1 side = 'asks' self.test_obj.time = 3 self.test_obj.place_order(price, side, size) self.assertFalse(self.test_obj.orders[side][0]['filled'], 'Ask auto filled') self.test_obj.time = 4 self.test_obj.update_fill_status() self.assertFalse(self.test_obj.orders[side][0]['filled'], 'Ask auto filled on update') def test_does_not_incorrectly_update_fill_status_for_bids(self): price = 90 size = 1 side = 'bids' self.test_obj.time = 2 self.test_obj.place_order(price, side, size) self.assertFalse(self.test_obj.orders[side][0]['filled'], 'Bid auto filled') self.test_obj.time = 3 self.test_obj.update_fill_status() self.assertFalse(self.test_obj.orders[side][0]['filled'], 'Bid auto filled on update') def tearDown(self): if len(self.test_obj.orders['asks']) > 0: self.test_obj.remove_order('asks', 0) if len(self.test_obj.orders['bids']) > 0: self.test_obj.remove_order('bids', 0) if __name__ == '__main__': unittest.main()
Markdown
UTF-8
4,840
3.125
3
[]
no_license
--- layout: post title: "Guava Cache 分析" date: 2016-11-05 categories: [cache] keywords: guava,cache,expireAfterWrite,refreshAfterWrite --- ## guava的单线程回源 缓存的更新有两种方法: - 被动更新:先从缓存获取,没有则回源获取,再更新缓存; - 主动更新:发现数据改变后直接更新缓存(在分布式场景下,不容易实现) 在高并发环境,被动回源是需要注意的。 问题:高并发场景下,大量请求在同一时间回源,大量的请求同一时间穿透到后端,容易引起后端服务崩溃(也容易引起并发问题)。 guava cache解决办法: guava cache保证单线程回源,对于同一个key,只让一个请求回源load,其他线程阻塞等待结果。同时,在Guava里可以通过配置expireAfterAccess/expireAfterWrite设定key的过期时间,key过期后就单线程回源加载并放回缓存。 这样通过Guava Cache简简单单就较为安全地实现了缓存的被动更新操作。 但是如果对于同一时间大量不同的key同时过期,造成大量不同的key同时回源,这种怎么解决呢? > guava cache实现类似ConcurrentHashMap,维护segment数组,每个segment独享一个锁,ConcurrentHashMap是通过这种机制来实现分段锁,ConcurrentHashMap默认分了16个segment; > guava Cache默认是4个segment,故guava cache的并发级别默认是4个,也就是说默认情况下,即便是大量不同的key同时过期,最多只也有4个线程并发回源,理论上不会给后端造成过大的压力。 ## guava refresh和expire刷新机制 - expireAfterAccess: 当缓存项在指定的时间段内没有被读或写就会被回收。 - expireAfterWrite:当缓存项在指定的时间段内没有更新就会被回收。 - refreshAfterWrite:当缓存项上一次更新操作之后的多久会被刷新。 仅仅使用 expireAfterWrite或者expireAfterAccess就可以实现缓存定时过期,但是频繁的过期会造成频繁的单线程回源,然而guava cache回源的时候会独占一个segment的锁,对于同一个segment的其他的读操作 处于loading状态的则会继续等待,value expire或者为null的key则会阻塞等待segment的锁。 expireAfterWrite或者expireAfterAccess的实现在数据回源的时候会让请求block住,以获取最新的值。数据实时性保证的较好,但是阻塞住请求对于一些响应要求严苛的业务可能是没办法接受的。那有没有解决的办法呢? 我们且看refreshAfterWrite: refreshAfterWrite通过定时刷新可以让缓存项保持可用。缓存项只有在被检索时才会真正刷新(如果CacheLoader.refresh实现为异步,那么检索不会被刷新拖慢)。也是保证同一个segment的单线程回源,但是与expireAfterWrite不同的是:其他线程访问loading状态的key时,仅仅稍微等一会,没有等到就返回旧值,整个请求就比较平滑。 与此同时,也引入了一个问题,refreshAfterWrite策略下,如果一个key长期没有被访问,就有可能会访问到很久之前的旧值。例如refreshAfterWrite(5),5s刷新一次,如果1min内,这个key都没有被访问,那么1min之后访问这个key,仍然有可能访问到旧数据,尽管我们设置了5s刷新一次。(guava cache并没单独的线程来处理刷新的逻辑,而是通过读操作来触发清理工作) 对于这个问题有没有这种的办法呢? guava cache支持我们同时使用expireAfterWrite&refreshAfterWrite,我们既可以通过组合的策略既保证性能,又保证不要读取到太旧的数据。 比如我们有需求:要求请求必须平滑,而且不能读到5s之前的旧数据。 我们可以如下设置来满足需求: ```java LoadingCache<String, String> cache = CacheBuilder .newBuilder() .refreshAfterWrite(4L, TimeUnit.SECONDS) .expireAfterWrite(5L, TimeUnit.SECONDS) .build(loader); ``` `expireAfterWrite(5L, TimeUnit.SECONDS)`能保证不会读到5s之前的旧数据,`refreshAfterWrite(4L, TimeUnit.SECONDS)`能保证大部分请求都在4s左右被刷新,小部分访问量较少的在5s的时候通过expireAfterWrite策略重新被回源。 ## guava后台异步刷新 refreshAfterWrite的刷新调用的是reload,reload的默认实现是在当前线程里面reload,也会造成一些卡顿,如果希望异步reload,需要重载这个方法。 ```java @GwtIncompatible // Futures public ListenableFuture<V> reload(K key, V oldValue) throws Exception { checkNotNull(key); checkNotNull(oldValue); return Futures.immediateFuture(load(key));//当前线程调用load,会造成当前线程的卡顿,如果不接受卡顿,需要重载这个方法 } ```
Python
UTF-8
2,133
4.21875
4
[]
no_license
#!/usr/bin/env python3 """ s01d02 tirelire """ class Tirelire: """ models a tirelire """ def __init__(self): self.empty() def empty(self): """Set amount to null""" self.amount = 0.0 def __str__(self): if self.amount > 0.0: return "Vous avez " + str(self.amount) + "euros dans la tirelire" else: return "Vous etes pauvre" def shuffle(self): """Produce sound""" if self.amount > 0.0: print("Bing bing") def add(self, amount): """Add a positive amout to the content""" if amount > 0.0: self.amount += amount def take(self, amount): """Take a positive amout from the content and eventually empties it""" if amount > 0.0: if self.amount-amount > 0: self.amount -= amount else: self.empty() def get_solde(self, budget): """Evaluate the remaining solde of a valid budget""" if budget < 0.0: budget = 0.0 return self.amount - budget def enough_budget(self, budget): """Evaluate the possibility to spend a budget""" enough = False solde = self.get_solde(budget) if solde >= 0.0: enough = True else: solde = -solde # we return a positive value return enough, solde def main(): """test function for Tirelire""" piggy = Tirelire() piggy.shuffle() print(piggy) piggy.take(20.0) piggy.shuffle() print(piggy) piggy.add(550.0) piggy.shuffle() print(piggy) piggy.take(10.0) piggy.take(5.0) print(piggy) budget = float(input("Donnez le budget de vos vacances : ")) enough, solde = piggy.enough_budget(budget) if enough: print("Vous êtes assez riche pour partir en vacances !" + "Il vous restera " + str(solde) + " euros à la rentrée.") piggy.take(budget) else: print("Il vous manque " + str(solde) + " euros pour partir en vacances !") if __name__ == "__main__": main()
Python
UTF-8
937
3.171875
3
[]
no_license
import RPi.GPIO as GPIO #import the libraries import time import os from numpy import arange GPIO.setmode(GPIO.BCM) #set BCM mode GPIO.setup(6, GPIO.OUT) #set the servo pins as out GPIO.setup(5, GPIO.OUT) p=GPIO.PWM(5,46.51) #initialize the pwm objects p1=GPIO.PWM(6,46.51) p.start(6.4) #start the servos, forward 1 foot p1.start(7.3) time.sleep(3) p.ChangeDutyCycle(0) p1.ChangeDutyCycle(0) time.sleep(1) p.start(7.3) #reverse the directions, backward 1 foot p1.start(6.4) time.sleep(3) p.ChangeDutyCycle(0) p1.ChangeDutyCycle(0) time.sleep(1) p.start(6.4) #move in same direction, pivot left p1.start(6.4) time.sleep(1) #sleep for 1 sec p.ChangeDutyCycle(0) p1.ChangeDutyCycle(0) time.sleep(1) p.start(7.3) #pivot right p1.start(7.3) time.sleep(1.5) p.ChangeDutyCycle(0) p1.ChangeDutyCycle(0) time.sleep(1)
C#
UTF-8
2,528
2.515625
3
[]
no_license
using FluentAssertions; using Moq; using SimpleCalculator.Domain.Abstractions; using SimpleCalculator.Domain.Calculators.Constraints; using SimpleCalculator.Domain.Constants; using SimpleCalculator.Domain.Models; using SimpleCalculator.Domain.ValueObjects; using SimpleCalculator.Tests.Shared.Builders; using System.Collections.Generic; using Xunit; namespace SimpleCalculator.Domain.Tests.Unit.Calculators { public class MinimumPayableConstraintTests { private readonly OrderBuilder _orderBuilder; private readonly OrderItemBuilder _orderItemBuilder; public MinimumPayableConstraintTests() { _orderBuilder = new OrderBuilder(); _orderItemBuilder = new OrderItemBuilder(); } [Fact] public void Calculate_UnderMinimum_ShouldAddCharge() { // Arrange var chargeName = "VAT"; var orderItem = _orderItemBuilder.Build(); var order = _orderBuilder.WithOrderItems(new List<OrderItem> { orderItem }).Build(); var calculator = Mock.Of<IChargeCalculator>(); orderItem.AddCharge(new OrderCharge(chargeName, "EUR9.99", ChargeNames.Item)); var sut = new MinimumPayableConstraint(calculator, chargeName, "EUR10"); // Act sut.Calculate(order); // Assert order.GetChargeAmount(chargeName, order.Currency).Value.Should().Be(10); } [Fact] public void Calculate_UnderMinimumMultipleItems_ShouldAddCharge() { // Arrange var chargeName = "VAT"; var orderItem1 = _orderItemBuilder.Build(); var orderItem2 = _orderItemBuilder.Build(); var order = _orderBuilder.WithOrderItems(new List<OrderItem> { orderItem1, orderItem2 }).Build(); var calculator = Mock.Of<IChargeCalculator>(); orderItem1.AddCharge(new OrderCharge(chargeName, "EUR4.99", ChargeNames.Item)); orderItem1.AddCharge(new OrderCharge(chargeName, "EUR4.99", ChargeNames.Item)); var sut = new MinimumPayableConstraint(calculator, chargeName, "EUR10"); // Act sut.Calculate(order); // Assert order.GetChargeAmount(chargeName, order.Currency).Value.Should().Be(10); orderItem1.GetChargeAmount(chargeName, order.Currency).Value.Should().Be(5); orderItem2.GetChargeAmount(chargeName, order.Currency).Value.Should().Be(5); } } }
Java
UTF-8
3,181
2.5625
3
[]
no_license
package com.quiz.quizapplication.importantInformation.controller.add; import com.quiz.quizapplication.data.alerts.AlertAddGroup; import com.quiz.quizapplication.importantInformation.objects.GroupInformation; import com.quiz.quizapplication.importantInformation.scene.add.AddGroupInformationScene; import com.quiz.quizapplication.importantInformation.data.add.DataAddInformationGroup; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.control.ButtonType; import java.sql.SQLException; public class AddInformationGroupController { GroupInformation groupInformation; DataAddInformationGroup dataAddInformationGroup = new DataAddInformationGroup(); AlertAddGroup alertAddGroup = new AlertAddGroup(); public void addGroupImportantInformation() throws SQLException { String groupName = dataAddInformationGroup.downloadGroupNameToAdd().toUpperCase(); groupInformation = dataAddInformationGroup.createGroupObject(groupName); if (dataAddInformationGroup.checkIfGroupNameIsNotNull(groupName) && dataAddInformationGroup.checkIfGroupNameNotExist(groupName)) { boolean result = dataAddInformationGroup.addGroup(groupInformation); if (result) alertAddGroup.groupHasBeenAdded(); else alertAddGroup.groupWasNotAdded(); } else { alertAddGroup.groupNameIsNullOrAlreadyExists(); } AlertAddGroup.dialogInformation.show(); AddGroupInformationScene.groupTextField.clear(); } public void changeGroupName() throws SQLException { String groupName = dataAddInformationGroup.downloadGroupNameFromChoiceBox(); String newGroupName = dataAddInformationGroup.downloadNewGroupNameToChangeTitle().toUpperCase(); boolean groupNotExist = dataAddInformationGroup.checkIfGroupNameNotExist(groupName); if (groupNotExist && !newGroupName.equals("") && groupName != null) { boolean result = dataAddInformationGroup.changeGroupName(newGroupName, groupName); if (result) alertAddGroup.groupNameHasBeenChanged(); else alertAddGroup.groupNameWasNotChanged(); } else { alertAddGroup.groupNameIsNullOrAlreadyExists(); } AlertAddGroup.dialogInformation.show(); AddGroupInformationScene.newNameOfGroupTextField.clear(); } public void deleteGroup() throws SQLException { String groupName = dataAddInformationGroup.downloadGroupNameFromChoiceBox(); if (groupName != null) { AlertAddGroup.dialogConfirmation.showAndWait(); if (AlertAddGroup.dialogConfirmation.getResult() == ButtonType.OK) { boolean result = dataAddInformationGroup.deleteGroup(groupName); if (result) alertAddGroup.groupHasBeenDeleted(); else alertAddGroup.groupWasNotDeleted(); AlertAddGroup.dialogInformation.show(); } } } public ObservableList<String> createObservableListToChoiceBox() throws SQLException { return FXCollections.observableList(dataAddInformationGroup.createGroupList()); } }
TypeScript
UTF-8
1,658
3.203125
3
[ "MIT" ]
permissive
import { LoggerBase, SubLogger } from "./LoggerBase"; import { LogLevel } from "./LogLevel"; /** * Represents a logger for logging information about the configuration class. */ export class ConfigurationLogger extends SubLogger { /** * The log-level of the logger. */ private logLevel: LogLevel; /** * Initializes a new instance of the {@link ConfigurationLogger `ConfigurationLogger`} class. * * @param logLevel * The log-level of the logger. * * @param logger * The logger to use as base. * * @param category * The category of the logger. */ public constructor(logLevel: LogLevel, logger: LoggerBase, category?: string) { super(ConfigurationLogger.GetParentLogger(logger), category); this.logLevel = logLevel; } /** * @inheritdoc */ public override get LogLevel(): LogLevel { return this.logLevel; } /** * Creates a parent logger for the {@link ConfigurationLogger `ConfigurationLogger`}. * * @param logger * The logger to use as base. * * @returns * The parent logger for the {@link ConfigurationLogger `ConfigurationLogger`}. */ private static GetParentLogger(logger: LoggerBase): LoggerBase { let categoryPath: string[] = []; while (logger instanceof SubLogger) { categoryPath.push(logger.Category); logger = logger.Parent; } for (let i = categoryPath.length - 1; i >= 0; i--) { logger = new SubLogger(logger, categoryPath[i]); } return logger; } }
Java
UTF-8
2,185
2.46875
2
[]
no_license
package lk.ac.sjp.aurora.phasetwo.Dialogs; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import lk.ac.sjp.aurora.phasetwo.StateManager; public class TeamRecognizedDialog extends DialogFragment { private String message; private Context context; private Activity activity; public TeamRecognizedDialog() { context = getContext(); } public void setActivity(Activity activity) { this.activity = activity; } public String getMessaage() { return message; } public void setMessage(String message) { this.message = message; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Use the Builder class for convenient dialog construction AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setMessage(message) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { /*Intent intent = new Intent(activity, PostDetectorView.class); intent.putExtra("lk.ac.sjp.aurora.TEAM_NAME", "Team A"); startActivity(intent);*/ StateManager.setRegisteredTeam("TEAM A"); activity.recreate(); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { /*Intent intent = new Intent(activity, PostDetectorView.class); intent.putExtra("lk.ac.sjp.aurora.TEAM_NAME", "Team B"); startActivity(intent);*/ StateManager.setRegisteredTeam("TEAM B"); activity.recreate(); } }); // Create the AlertDialog object and return it return builder.create(); } }
Markdown
UTF-8
3,861
4.15625
4
[]
no_license
# JavaScript 原型到原型链 ## 构造函数创建对象 ```js function Person() {} var person = new Person() person.name = 'Dragon' console.log(person.name) // Dragon ``` Person 就是一个构造函数,使用new实例化一个对象person ## prototype 每个函数都有一个prototype属性 ```js function Person() {} Person.prototype.name = 'Dragon' var person1 = new Person() var person2 = new Person() console.log(person1.name) // 'Dragon' console.log(person2.name) // 'Dragon' ``` 从上面可以发现person1和person2打印出的值都是 'Dragon', 到底函数prototype属性指向的是什么? 每一个JavaScript对象(null除外)在创建的时候就会关联另外一个对象,这个对象就是原型,每一个对象都会从原型继承属性。所以函数的prototype属性指向了一个对象,这个对象就是调用该构造函数实例化的原型,也就是person1和person2的原型。 <img src="../img/prototype1.png" /> ## __proto__ 每一个JavaScript对象(除了null)都具有一个属性,叫__proto__,这个属性会指向该对象的原型。 ```js function Person() {} var person = new Person() console.log(person.__proto__ === Person.prototype) // true ``` <img src="../img/prototype2.png" /> 如果实例对象和构造函数都可以指向原型,那么是否有属性可以指向构造函数或者实例? ## constructor 因为一个构造函数可以生成多个实例,所以指向实例是没有的。但是原型指向构造函数是有的,每个原型都有一个constructor属性指向关联的构造函数 ```js function Person() {} console.log(Person === Person.prototype.constructor) // true ``` <img src="../img/prototype3.png" /> 所以: ```js function Person() {} var person = new Person() console.log(person.__proto__ === Person.prototype) // ture console.log(Person.prototype.constructor === Person) // true console.log(Object.getPrototypeof(person) === Person.prototype) // true ``` ## 实例和原型 当读取实例的属性时,如果找不到,就会查找与对象关联的原型中的属性,如果还找不到,就找原型中当原型,直到找到位置。 ```js function Person() {} Person.prototype.name = 'dragon' var person = new Person() person.name = 'dragon2' console.log(person.name) // dragon2 delete person.name console.log(person.name) // dragon ``` 在这里,我们给person添加name属性,当打印person.name的时候,就会出现 dragon2 当删了perosn的name的时候,读取person.name在person对象中就找不到name的属性,那么person的原型就是person.__proto__,也就是Person.prototype中查找,索性是找到了。。。 如果没找到,那就要继续找,直到找到原型的原型啦~ ## 原型的原型 ```js var obj = new Object() obj.name = 'dragon' console.log(obj.name) // dragon ``` 所以原型对象就是通过Object构造函数生成的。 <img src="../img/prototype4.png" /> ## 原型链 ```js console.log(Object.prototype.__proto__ === null) // true ``` 所以Object.prototype.__proto__的值为null和Object.prototype没有原型是一样的,所以找到Object.prototype就不用继续找了 <img src="../img/prototype5.png" /> ## 补充 ### constructor ```js function Person() {} var person = new Person() console.log(person.constructor === Person) // true ``` 当获取person.constructor时候,person里面是没有constructor的,就会从person.prototype中获取,所以: ```js Person.constructor === Person.prototype.constructor ``` ### __proto__ __proto__不存在Person.prototype中,因为他来自于Object.prototype,可以当作是一个getter/setter,当使用到obj.__proto__时,可以理解成返回了Object.getPrototypeOf(obj) ## 总结 简单的了解一下原型与原型链,还需继续深入,待续。
Python
UTF-8
3,845
2.671875
3
[]
no_license
import numpy as numpy import cv2 import os import matplotlib.pyplot as plt # # Open a vidoe # video_path=r"./vtest.mp4" # img_path =r'./images' # img_path2 =r'./equimages' # if not os.path.isdir(img_path): # mkdir(img_path) # # Divide the video into frames # vidcap = cv2.VideoCapture(video_path) # (cap,frame)= vidcap.read() # if cap==False: # print('cannot open video file') # count = 0 # # Save the frames in a folder # while cap: # cv2.imwrite(os.path.join(img_path,'%.6d.jpg'%count),frame) # count += 1 # # Every 100 frames get 1 # for i in range(1): # (cap,frame)= vidcap.read() count2 = 0 framey = [] deltay = [] deltab = [] deltab2 = [] i=0 a = 1 # previous_gray = cv2.cvtColor(cv2.imread('./images/000000.jpg'), cv2.COLOR_BGR2GRAY) previous_y = numpy.mean(cv2.cvtColor(cv2.imread('./images/000000.jpg'), cv2.COLOR_BGR2GRAY)) previous_blocky = numpy.zeros(1947) previous_blocky2 = numpy.zeros(1947) # Open frames in the folder import glob from PIL import Image for frames in glob.glob('./images/*.jpg'): img = cv2.imread(frames) gray_levels = 256 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # a = gray/previous_gray # previous_gray = gray equ = cv2.equalizeHist(gray) # cv2.imwrite(os.path.join(img_path2,'%.6d.jpg'%count2),equ) # count2 += 1 im = Image.open(frames) pix = im.load() width = im.size[0] height = im.size[1] # Define the window size windowsize_r = 32 windowsize_c = 32 # m = int(height/16) # n = int(width/16) # The average luminance component (Y) of an entire frame # for m in range(width): # for n in range(height): # r, g, b = pix[m, n] # y = (0.2126*r + 0.7152*g + 0.0722*b) # #print(m,n) # #print(y) y1 = numpy.mean(gray) framey.append(y1) biiiii = numpy.power(y1-previous_y,2) biiiiii = numpy.sum(biiiii) deltay.append(biiiiii) previous_y = y1 #print(y1) print(i) # print(framey) # print(deltay) blocky = [] blocky2 = [] # Each frame is partitioned into blocks # for r in range(0,gray.shape[0] - windowsize_r, windowsize_r): # for c in range(0,gray.shape[1] - windowsize_c, windowsize_c): # window = gray[r:r+windowsize_r,c:c+windowsize_c] # hist = numpy.histogram(window,bins=gray_levels) # # The average luminance component of each block # w = numpy.mean(window) # blocky.append (w) # # The blocks are sorted in decreasing order # w1 = numpy.sort(blocky) # #print(window) # #print(blocky) # b = numpy.array(w1)-previous_blocky # bs = numpy.power(b,2) # deltab.append(sum(numpy.power(b,2))) # # print(previous_blocky) # previous_blocky = numpy.array(w1) # # print(previous_blocky) # print(deltab) # print(b) # plt.plot(w1) # plotting by columns # plt.show() #print(blocky,w1) # Each frame is partitioned into blocks for r2 in range(0,equ.shape[0] - windowsize_r, windowsize_r): for c2 in range(0,equ.shape[1] - windowsize_c, windowsize_c): window2 = equ[r2:r2+windowsize_r,c2:c2+windowsize_c] hist2 = numpy.histogram(window2,bins=gray_levels) # The average luminance component of each block w2 = numpy.mean(window2) blocky2.append(w2) # The blocks are sorted in decreasing order w3 = numpy.sort(blocky2) #print(blocky2) b2 = numpy.array(w3)-previous_blocky2 deltab2.append(sum(numpy.power(b2,2))) # print(previous_blocky2) previous_blocky2 = numpy.array(w3) # print(previous_blocky2) # print(deltab2) # plt.plot(b2) # plotting by columns # plt.show() i = i+1 #print(hist) # print(framey) # plt.plot(framey) # plotting by columns # # plt.xticks(range(len(framey))) # plt.show() # print(y2) # print(deltay) # plt.plot(deltay) # plotting by columns # plt.show()
PHP
UTF-8
2,211
2.59375
3
[]
no_license
<?php //include vendor folder require 'D:/xampp/phpMyAdmin/vendor/autoload.php'; use \Firebase\JWT\JWT;//class within firebase folder in jwt.php //header header("Access-Control-Allow-Origin:*"); header("Access-Control-Allow-Methods:POST"); header("content-type: application/json; charset=utf-8"); include_once("../config/database.php"); include_once("../classes/Users.php"); //object $db=new Database(); $connection=$db->connect(); $user_obj=new Users($connection); if($_SERVER['REQUEST_METHOD']=== "POST") { //param from body $data=json_decode(file_get_contents("php://input")); $headers=getallheaders(); if(!empty($data->name) && !empty($data->description) && !empty($data->status) ) { try{ $jwt=$headers['Authorization']; $secret_key='owt123'; $decoded_data= JWT::decode($jwt,$secret_key,array('HS512')); $user_obj->user_id=$decoded_data->data->id; $user_obj->project_name=$data->name; $user_obj->description=$data->description; $user_obj->status=$data->status; if($user_obj->create_project()) { http_response_code(200); echo json_encode(array( 'status' => 1, 'message'=>'project created' )); } else{ http_response_code(500); echo json_encode(array( 'status' => 0, 'message'=>'failed to create project' )); } }catch(Exception $ex){ http_response_code(500);//server error echo json_encode(array( "status"=>0, "message"=>$ex->getMessage() )); } } else{ http_response_code(404); echo json_encode(array( 'status' => 0, 'message'=>'all data needed' )); } } else{ http_response_code(503); echo json_encode(array( 'status' => 0, 'message'=>'access denied' )); } ?>
Java
UTF-8
1,503
2.0625
2
[]
no_license
package com.eagle.WeChatRobot.utils; public class PubInfo { public static String HEADIMAGEURL = "http://bbsimg.ali213.net/data/attachment/forum/201501/17/1449227zqzq7qqm9tnzvjv.png";//用户头像为空时的默认图片地址 public static String ISINTERNALLHTTPURL ="http://localhost:8080/Contact/weChat/IDNumber";//调取通讯录管理系统的判断是否内部人员接口地址,查身份证号的存在 public static String CONTACTHTTPURL = "http://localhost:8080/Contact/weChat/wxGetuser";//调取通讯录管理系统的查询人员信息接口地址,根据T名字的汉字查信息 public static String CONTACTHTTPURLBYPINYIN = "http://localhost:8080/Contact/weChat/wxGetuserByPinYin";//调取通讯录管理系统的查询人员信息接口地址,根据T名字的拼音查信息 public static String OrdinaryRespons = "您的留言已经收到,我们将尽快给您回复,您也可拨打电话:0531-55721001,与我们取得联系。感谢您对易构软件的关注!";//微信用户普通留言的反馈信息 public static String AbnormalRespons = "您的留言已收到,我们将尽快给您回复,您也可拨打电话:0531-55721001,与我们取得联系。感谢您对易构软件的关注!";//微信用户发送异常留言的反馈 public static String NOTHISWXNAME= "您非已记录特殊微信名称的人员,请发送“P”加身份证号以确认是否为内部人员!";//未登记的fromUserName让其发送身份证号 }
Java
UTF-8
1,245
2.09375
2
[]
no_license
package ServiceB; import org.apache.camel.component.servlet.CamelHttpTransportServlet; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import java.util.Collections; /** * Инициализация ServiceB * на выходе полученый результат выводится в консоль */ @SpringBootApplication @ComponentScan(basePackages = "ServiceB") public class TestConnectAndReceivingJSON { public static void main(String[] args) { SpringApplication app = new SpringApplication(TestConnectAndReceivingJSON.class); app.setDefaultProperties(Collections.singletonMap("server.port", "8085")); app.run(args); } // Настройка сервлета @Bean ServletRegistrationBean servletRegistration(){ ServletRegistrationBean registrationBean = new ServletRegistrationBean(new CamelHttpTransportServlet(), "/service_b/*"); registrationBean.setName("CamelServlet"); return registrationBean; } }
C++
UTF-8
115
2.703125
3
[]
no_license
#include<iostream> using namespace std int main() { int a,b; int s=a+b; cout<"the sum of two numbers is"<<s; }
JavaScript
UTF-8
314
4
4
[]
no_license
// getter and setter // to use getter or setter start the variable name with _ const myCat = { _name :'Dotie', get name(){ return this._name; }, set name(newName){ this._name = newName; } }; console.log(myCat.name) // invokes getter myCat.name = "Yankee" // invokes setter console.log(myCat)
Java
UTF-8
1,432
2.09375
2
[ "Apache-2.0", "MIT" ]
permissive
// SPDX-License-Identifier: MIT package mealplaner.plugins.preference.proposal; import static mealplaner.plugins.preference.mealextension.CookingPreference.NO_PREFERENCE; import static mealplaner.plugins.preference.mealextension.CookingPreference.RARE; import static mealplaner.plugins.preference.mealextension.CookingPreference.VERY_POPULAR; import static mealplaner.plugins.preference.settingextension.PreferenceSettings.NORMAL; import static mealplaner.plugins.preference.settingextension.PreferenceSettings.RARE_NONE; import static mealplaner.plugins.preference.settingextension.PreferenceSettings.RARE_PREFERED; import java.util.HashMap; import java.util.Map; import mealplaner.commons.Pair; import mealplaner.plugins.preference.mealextension.CookingPreference; import mealplaner.plugins.preference.settingextension.PreferenceSettings; public final class PreferenceMap { private PreferenceMap() { } public static Map<Pair<CookingPreference, PreferenceSettings>, Integer> getPreferenceMap() { HashMap<Pair<CookingPreference, PreferenceSettings>, Integer> preferenceMap = new HashMap<>(); preferenceMap.put(Pair.of(VERY_POPULAR, NORMAL), 4); preferenceMap.put(Pair.of(VERY_POPULAR, RARE_NONE), 4); preferenceMap.put(Pair.of(NO_PREFERENCE, NORMAL), 2); preferenceMap.put(Pair.of(NO_PREFERENCE, RARE_NONE), 2); preferenceMap.put(Pair.of(RARE, RARE_PREFERED), 2); return preferenceMap; } }
PHP
UTF-8
3,435
2.78125
3
[]
no_license
<?php include_once('../includes/database.php'); include_once('../database/db_user.php'); include_once('../includes/session.php'); function getAllProperties() { $db = Database::instance()->db(); $stmt = $db->prepare('SELECT * FROM Properties'); $stmt->execute(); return $stmt->fetchAll(); } function getProperties($username) { $db = Database::instance()->db(); $user = getUser($username); $stmt = $db->prepare('SELECT * FROM Properties WHERE ownerID = ?'); $stmt->execute(array($user['id'])); return $stmt->fetchAll(); } function searchProperties($price, $location, $start, $end) { $db = Database::instance()->db(); if (empty($location)) { $stmt = $db->prepare('SELECT * FROM Properties WHERE (price <= ? AND availabilityStart <= ? AND availabilityEnd >= ?)'); $stmt->execute(array($price,$start,$end)); } else { $stmt = $db->prepare('SELECT * FROM Properties WHERE (price <= ? AND UPPER(location) = UPPER(?) AND availabilityStart <= ? AND availabilityEnd >= ?)'); $stmt->execute(array($price,$location,$start,$end)); } return $stmt->fetchAll(); } function checkIsPropertyOwner($property_id) { $db = Database::instance()->db(); $user = getUser($_SESSION['username']); $stmt = $db->prepare('SELECT * FROM Properties WHERE ownerID = ? AND id = ?'); $stmt->execute(array($user['id'], $property_id)); return $stmt->fetch()?true:false; } function addProperty($ownerID, $price, $title, $location, $description, $start, $end) { $db = Database::instance()->db(); $stmt = $db->prepare('INSERT INTO Properties VALUES(NULL, ?, ?, ?, ?, ?, ?, ?)'); $stmt->execute(array($ownerID, $price, $title, $location, $description,$start,$end)); $property_id = $db->lastInsertId(); return $property_id; } function editProperty($id, $price, $title, $location, $description, $start, $end) { $db = Database::instance()->db(); $stmt = $db->prepare('UPDATE Properties SET price = ? , title = ? , location = ? , description = ? , availabilityStart = ? , availabilityEnd = ? WHERE id = ?'); $stmt->execute(array($price, $title, $location, $description,$start,$end,$id)); return 1; } function getProperty($property_id) { $db = Database::instance()->db(); $stmt = $db->prepare('SELECT * FROM Properties WHERE id = ?'); $stmt->execute(array($property_id)); return $stmt->fetch(); } function deleteProperty($property_id) { $db = Database::instance()->db(); $stmt = $db->prepare('DELETE FROM Properties WHERE id = ?'); $stmt->execute(array($property_id)); } function addPropertyPhoto($property_id, $photo) { $db = Database::instance()->db(); $stmt = $db->prepare('INSERT INTO Photos VALUES(NULL, ?, ?)'); $stmt->execute(array($property_id,$photo)); return 1; } function removePropertyPhoto($photoID) { $db = Database::instance()->db(); $stmt = $db->prepare('DELETE FROM Photos WHERE id =?'); $stmt->execute(array($photoID)); return 1; } function getPropertyPhotos($property_id) { $db = Database::instance()->db(); $stmt = $db->prepare('SELECT * FROM Photos WHERE propertyID = ?'); $stmt->execute(array($property_id)); return $stmt->fetchAll(); }
C
UTF-8
1,380
3.09375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #define err_exit(m) \ do{ \ perror(m);\ exit(errno);\ }while(0); /*@jackwu create list inode@*/ typedef struct _inode{ struct _inode *next; int data; int cur_size; }t_inode,*t_pnode; /*@list inode end@*/ /*@jackwu realoc@*/ void *Realloc(void *mem_address, unsigned int newsize){ void *p; if((p=realloc(mem_address,newsize))==NULL){ err_exit("realloc error"); } return p; } /*@jackwu realoc@*/ /*$malloc$ */ void * Malloc(size_t sz){ void *p; if((p=malloc(sz))==NULL){ err_exit("malloc failed!"); } return p; } /*$malloc end$*/ /*@list impl@*/ void create(t_pnode *head){ if(*head==NULL){ *head=(t_pnode)Malloc(sizeof(t_inode)); (*head)->next=NULL; (*head)->cur_size=1;//not include headnode } } void * insert(t_pnode head,int lhs){ t_pnode p=NULL; p=(t_pnode)Realloc(head,sizeof(t_inode)*(head->cur_size+1)); if(head==NULL){ head=p; }else{ while(head->next!=NULL){ head=head->next; } head->next=NULL; head->data=lhs; } } /*@show listnode@*/ void show(t_pnode head){ head=head->next; while(head!=NULL) { printf("data:%d\n",head->data); head=head->next; } } /*@show end@*/ /*@list ene@*/
Java
UTF-8
617
2.078125
2
[ "Apache-2.0" ]
permissive
package com.dizzyd.coregen.scripting; import com.dizzyd.coregen.feature.Feature; import com.typesafe.config.Config; import net.minecraft.block.state.IBlockState; import org.apache.logging.log4j.Logger; import java.util.Random; public interface Context { Feature getFeature(); Random getRandom(); Config getConfig(); Logger getLogger(); Position randomPos(int cx, int cz); boolean placeBlock(double x, double y, double z); IBlockState blockFromString(String blockString); boolean placeBlock(double x, double y, double z, IBlockState block); void chatLog(String msg); }
Java
UTF-8
1,595
2.90625
3
[]
no_license
package com.example.rest.sudoku.exception.advice; import java.time.LocalDateTime; import java.util.Objects; public class SudokuException { private LocalDateTime timestamp; private int status; private String error; private String message; public SudokuException(LocalDateTime timestamp, int status, String error, String message) { this.timestamp = timestamp; this.status = status; this.error = error; this.message = message; } public LocalDateTime getTimestamp() { return timestamp; } public int getStatus() { return status; } public String getError() { return error; } public String getMessage() { return message; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null) return false; if (!(o instanceof SudokuException)) return false; SudokuException that = (SudokuException) o; return status == that.status && Objects.equals(timestamp, that.timestamp) && Objects.equals(error, that.error) && Objects.equals(message, that.message); } @Override public int hashCode() { return Objects.hash(timestamp, status, error, message); } @Override public String toString() { return "SudokuException{" + "timestamp=" + timestamp + ", status=" + status + ", error='" + error + '\'' + ", message='" + message + '\'' + '}'; } }
Java
UTF-8
208
1.695313
2
[]
no_license
package com.alipay.oceanbase.jdbc; import java.sql.SQLException; public interface ExceptionInterceptor extends Extension { SQLException interceptException(final SQLException p0, final Connection p1); }
JavaScript
UTF-8
3,869
3.28125
3
[]
no_license
var picOfHamburger = document.getElementById('hamburger'); var picOfCheese = document.getElementById('cheeseburger'); var picOfBacon = document.getElementById('baconcheese'); var picOfFries = document.getElementById('fries'); var picOfOnion = document.getElementById('onionrings'); var picOfDrink = document.getElementById('drink'); var picOfComboOne = document.getElementById('combo1'); var picOfComboTwo = document.getElementById('combo2'); var picOfComboThree = document.getElementById('combo3'); var tipToDisplay = document.getElementById('tipDisplay'); var taxToDisplay = document.getElementById('taxDisplay'); var totalToDisplay = document.getElementById('totalDisplay'); var itemsOnReceipt = document.getElementById('itemname'); var placement = document.createElement('li'); var subtotal = 0; var totalOfTax = 0; var totalBill = 0; var Product = function Product(name, price) { this.name = name; this.price = price; } var hamburger = new Product('hamburger', 1); var cheeseBurger = new Product('cheeseburger', 2); var baconCheese = new Product('baconCB', 2); var fries = new Product('fries', 1); var onionRings = new Product('onion-rings', 2); var drink = new Product('coke', 2); var comboOne = new Product('combo-one', 5); var comboTwo = new Product('combo-two', 6); var comboThree = new Product('combo-three', 7); Product.prototype.billedItems = function() { this.menuItem = placement; this.menuItem.textContent = this.name + " ==> " + this.price; itemsOnReceipt.appendChild(this.menuItem); itemsOnReceipt.scrollTop = 999999; }; Product.prototype.logic = function() { subtotal += this.price; totalOfTip = subtotal * 0.15; totalOfTax = subtotal * 0.08; totalBill = subtotal + totalOfTax + totalOfTip; tipToDisplay.textContent = totalOfTip; taxToDisplay.textContent = totalOfTax; totalToDisplay.textContent = totalBill; }; Product.prototype.display = function() { this.billedItems(); this.logic(); }; //It doesn't run now. Can't remember what was deleted, recovered what I could for later. Switch? // var compute = function() { // if (event.target == picOfHamburger) { // hamburger.display(); // } else if (event.target == picOfCheese) { // cheeseBurger.display(); // } else if (event.target == picOfBacon) { // baconCheese.display(); // } else if (event.target == picOfFries) { // fries.display(); // } else if (event.target == picOfOnion) { // onionRings.display(); // } else if (event.target == picOfDrink) { // drink.display(); // } else if (event.target == picOfComboOne) { // comboOne.display(); // } else if (event.target == picOfComboTwo) { // comboTwo.display(); // } else if (event.target == picOfComboThree) { // comboThree.display(); // } else { // console.log("Cannot recognize.."); // } // }; //had to hardcode because the original snippet that ran through each one //was deleted and I can't rememeber it :( var showHamburger = function() { hamburger.display(); }; var showCheese = function() { cheeseBurger.display(); }; var showBacon = function() { baconCheese.display(); }; var showFries = function() { fries.display(); }; var showOnion = function() { onionRings.display(); }; var showDrink = function() { drink.display(); }; var showComboOne = function() { comboOne.display(); }; var showComboTwo = function() { comboTwo.display(); }; var showComboThree = function() { comboThree.display(); }; picOfHamburger.addEventListener('click', showHamburger()); picOfCheese.addEventListener('click', showCheese); picOfBacon.addEventListener('click', showBacon); picOfFries.addEventListener('click', showFries); picOfOnion.addEventListener('click', showOnion); picOfDrink.addEventListener('click', showDrink); picOfComboOne.addEventListener('click', showComboOne); picOfComboTwo.addEventListener('click', showComboTwo); picOfComboThree.addEventListener('click', showComboThree);
Go
UTF-8
1,687
3.421875
3
[]
no_license
package main import ( "crypto/sha256" "fmt" "strings" "time" ) // Article holds the cluster representation of an article type Article struct { Title string `json:"title"` Ticker string `json:"ticker"` Date time.Time `json:"date"` URLHash string `json:"urlHash"` Score Score `json:"score"` } type tempArticle struct { Title string `json:"title"` Ticker string `json:"ticker"` URLHash string `json:"urlHash"` Score Score `json:"score"` } // Score holds the subject and reference score of a cluster member type Score struct { SubjectScore float64 `json:"subjectScore"` ReferenceScore float64 `json:"referenceScore"` } // calcClusterHash Calculates the cluster hash based on title, ticker and date func calcClusterHash(title, ticker, date string) string { byteHash := sha256.Sum256([]byte(title + ticker + date)) return fmt.Sprintf("%x", byteHash) } // Format Formats the content of an article according to excpectations func (article *Article) Format() { article.Title = strings.ToLower(article.Title) article.Ticker = strings.ToUpper(article.Ticker) } // formatArticleDate Returns a string formated date in order to calculate cluster hash func formatArticleDate(date time.Time) string { return date.Format("2006-01-02") } // ToClusterMember Turns an article into a cluster member func (article *Article) ToClusterMember() ClusterMember { article.Format() dateStr := formatArticleDate(article.Date) return ClusterMember{ ClusterHash: calcClusterHash(article.Title, article.Ticker, dateStr), URLHash: article.URLHash, ReferenceScore: article.Score.ReferenceScore, SubjectScore: article.Score.SubjectScore, } }
Python
UTF-8
371
2.78125
3
[ "Apache-2.0" ]
permissive
''' @package: pyAudioLex @author: Jim Schwoebel @module: prp_freq #prp = pronoun, personal ''' from nltk.tokenize import word_tokenize from nltk.tag import pos_tag, map_tag from collections import Counter def prp_freq(importtext): text=word_tokenize(importtext) tokens=nltk.pos_tag(text) c=Counter(token for word, token in tokens) return c['PRP']/len(text)
C++
UTF-8
2,412
2.8125
3
[]
no_license
/* ************************************************************************** */ /* LE - / */ /* / */ /* MateriaSource.cpp .:: .:/ . .:: */ /* +:+:+ +: +: +:+:+ */ /* By: plamtenz <plamtenz@student.le-101.fr> +:+ +: +: +:+ */ /* #+# #+ #+ #+# */ /* Created: 2020/03/05 06:47:00 by plamtenz #+# ## ## #+# */ /* Updated: 2021/01/22 13:17:57 by plamtenz ### #+. /#+ ###.fr */ /* / */ /* / */ /* ************************************************************************** */ #include "MateriaSource.hpp" MateriaSource::MateriaSource() : idx(0) { for (size_t i = 0 ; i < sizeof(stock) / sizeof(*stock) ; i++) stock[i] = NULL; std::cout << "An empty MateriaSource has been created!" <<std::endl; } MateriaSource::MateriaSource(const MateriaSource& src) { for (size_t i = 0 ; i < sizeof(stock) / sizeof(*stock) ; i++) stock[i] = NULL; operator=(src); std::cout << "A new MateriaSource has been created!" <<std::endl; } MateriaSource::~MateriaSource() { for (size_t i = 0 ; i < sizeof(stock) / sizeof(*stock) ; i++) delete stock[i]; std::cout << "A MateriaSource has been destroyed!" <<std::endl; } MateriaSource& MateriaSource::operator=(const MateriaSource& src) { if (this != &src) { idx = src.idx; for (size_t i = 0 ; i < sizeof(stock) / sizeof(*stock) ; i++) delete stock[i]; for (size_t i = 0 ; i < sizeof(stock) / sizeof(*stock) && src.stock[i] ; i++) learnMateria(src.stock[i]->clone()); } return (*this); } void MateriaSource::learnMateria(AMateria* m) { if (idx >= 0 && static_cast<size_t>(idx) < sizeof(stock) / sizeof(*stock)) { size_t i = -1; while (++i < sizeof(stock) / sizeof(*stock) && stock[i]) ; stock[i] = m; idx++; } } AMateria* MateriaSource::createMateria(std::string const& type) { for (size_t i = 0 ; i < sizeof(stock) / sizeof(*stock) ; i++) if (stock[i]->getType() == type) return (stock[i]->clone()); return (NULL); }
PHP
UTF-8
947
2.515625
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers\Api; use App\Http\Controllers\Controller; use App\Models\Book; use App\Repositories\BookRepository; use http\Env\Response; use Illuminate\Http\Request; class BookController extends Controller { /** @var $bookRepo BookRepository */ protected $bookRepo; public function __construct(BookRepository $bookRepository) { $this->bookRepo = $bookRepository; } public function index(Request $request) { return response()->json($this->bookRepo->getBooks())->setStatusCode(200); } public function getAllBooks(Request $request): \Illuminate\Http\JsonResponse { $data = $this->bookRepo->getAllBooksFromShopify(); return api_response($data); } /** * @param $id * @return \Illuminate\Http\JsonResponse */ public function details($id) { return api_response($this->bookRepo->getBookFromShopify($id)); } }
C
UTF-8
3,523
3.328125
3
[]
no_license
// **** Include libraries here **** // Standard libraries #include <string.h> #include <math.h> #include <stdio.h> //CSE013E Support Library #include "UNIXBOARD.h" #include "Game.h" // User libraries // **** Set any macros or preprocessor directives here **** // **** Declare any data types here **** struct Room { char title[GAME_MAX_ROOM_TITLE_LENGTH + 1]; char desc[GAME_MAX_ROOM_DESC_LENGTH + 1]; uint8_t exit; char next; //store the user's next direction option } room; // **** Define any global or external variables here **** static uint8_t gameState = 1; // **** Declare any function prototypes here **** int main() { /******************************** Your custom code goes below here ********************************/ printf("Welcome to xzhan214's RPG game\n"); if (!GameInit()) { FATAL_ERROR(); } while (gameState) { if(!GameGetCurrentRoomTitle(room.title)){ FATAL_ERROR(); } if(!GameGetCurrentRoomDescription(room.desc)){ FATAL_ERROR(); } printf("\n\n%s\n%s\n\n", room.title, room.desc); room.exit = GameGetCurrentRoomExits(); printf("exit:"); if (room.exit & GAME_ROOM_EXIT_NORTH_EXISTS) { printf("N "); } if (room.exit & GAME_ROOM_EXIT_EAST_EXISTS) { printf("E "); } if (room.exit & GAME_ROOM_EXIT_SOUTH_EXISTS) { printf("S "); } if (room.exit & GAME_ROOM_EXIT_WEST_EXISTS) { printf("W "); } while (1) { printf("\nEnter direction(n,e,s,w) to go forward, or q to quit: "); room.next = getchar(); getchar(); //to clear the empty one if (room.next == 'n') { if(!(room.exit&GAME_ROOM_EXIT_NORTH_EXISTS)){ printf("\nInvalid direction!\n"); } else if (!GameGoNorth()) { FATAL_ERROR(); } else { break; } } else if (room.next == 'e') { if(!(room.exit&GAME_ROOM_EXIT_EAST_EXISTS)){ printf("\nInvalid direction!\n"); } else if (!GameGoEast()) { FATAL_ERROR(); } else { break; } } else if (room.next == 's') { if(!(room.exit&GAME_ROOM_EXIT_SOUTH_EXISTS)){ printf("\nInvalid direction!\n"); } else if (!GameGoSouth()) { FATAL_ERROR(); } else { break; } } else if (room.next == 'w') { if(!(room.exit&GAME_ROOM_EXIT_WEST_EXISTS)){ printf("\nInvalid direction!\n"); } else if (!GameGoWest()) { FATAL_ERROR(); } else { break; } } else if (room.next == 'q') { printf("\nThank you Goodbye\n"); gameState = 0; break; //just to make sure } else { printf("\nInvalid input: %c\n", room.next); } } } /**************************************************************************************************/ }
Markdown
UTF-8
885
2.671875
3
[]
no_license
## 60-minutpe IPA ### Ingredients Original: - 6kg pale ale malt - 170g Amber malt - 15g Warrior hops - 30g Simcoe hops - 60g Amarillo / Galaxy hops - 5g Irish moss - SafaleS-04 Multiply by 1.333: - 8kg pale ale malt - 225g Amber malt - 20g Warrior hops - 40g Simcoe hops [have 60g] - 80g Amarillo / Galaxy hops [have 40 +50 ] - 5g Irish moss [have this] - SafaleS-04 ## Irish Red Ale ### Ingredients - 1.5kg of caramalt extract plus 1kg dry malt, amber - 450 g crystal malt - 225 g toasted malted barley - 28 g Nothern Brewer hops (boiling) * HBU (225 MBU) - 28 g Santiam or Tettnagnger hops (aroma) - Safale 05 Have Fuggles 5% and Challenger 7.5 ## Dave's notes 3 L /kg for mash 4 L /kg for sparge We'll get some water getting into the grain (so less than 18L will make it through). Should have about 35L before the boil, but should lose a lot over the course of the boil.
Python
UTF-8
9,434
3.171875
3
[]
no_license
''' This program can help you create the examination How to use: 1.Enter the number of your question 2.Enter your question 3.Enter you answer choices 4.Enter the correct answer Author : Yaya & Tonpho @ITKMITL Last Modified Date : 22/12/2014 Time : 11:21 AM Language : Python 2.7.8 ''' import Tkinter as tk import tkMessageBox class App: def __init__(self, root): tk.Label(root, text='Welcome To The Examer', font = "Helvetica 32 bold italic", fg = "red").grid(padx=20, pady=10) howto = 'How to use:\n1.Enter the number of your question\n2.Enter your question\n3.Enter you answer choices\n4.Enter the correct answer\n5.Do the test' tk.Label(root, text=howto, font = "Helvetica 14").grid(padx=20, pady=10) tk.Button(root, text='Begin!', command=self.start).grid(pady=10) def start(self): self.first = tk.Toplevel() self.first.resizable(True, True) tk.Label(self.first, text='Please Enter The Number of Your Question :', font = "Helvetica 14").grid(padx=20, pady=5) self.num = tk.IntVar() entry = tk.Entry(self.first, textvariable=self.num) entry.grid(pady=5) tk.Button(self.first, text='Create', command=self.question).grid(pady=5) def restart(self): self.root6.destroy() self.start() def again(self): self.root6.destroy() self.main_do_exam() def submit(self): if self.num_choice.get() == self.ans_list[self.j-1]: self.score += 1 self.root4.destroy() self.root6 = tk.Toplevel() label1 = tk.Label(self.root6, text='Congratulation', font = "Helvetica 32 bold italic", fg = "red") score_label = tk.Label(self.root6, text='Your Score is : %d / %d' % (self.score, self.num.get()), font = "Helvetica 16 bold italic") label1.grid(padx = 100, pady = 20) score_label.grid(padx = 100, pady = 20) tk.Button(self.root6, text='Create New Test', command=self.restart).grid(row=3, pady=5) tk.Button(self.root6, text='Do the Exam Again', command=self.again).grid(row=4, pady=5) def sub_do_exam(self): if self.num_choice.get() == self.ans_list[self.j-1]: self.score += 1 num = self.num.get() value = self.values.get() self.j += 1 self.num_choice = tk.IntVar() next_button = tk.Button(self.root4, text='Next', command=self.sub_do_exam) submit_button = tk.Button(self.root4, text='Submit', command=self.submit) question_label = tk.Label(self.root4, text='%d.'%self.j+self.quest_list[self.j-1].get(), font='Helvetica 16 bold', width = 50, anchor='w') question_label.grid(sticky='W', row=0, column=0) for i in xrange(1, value+1): tk.Radiobutton(self.root4, text='(%d) : '% i+self.all_choice[self.j-1][i-1].get(), variable=self.num_choice, value=i, width = 50, anchor='w').grid(sticky='W', row=i, column=0, padx=10, pady=3) if self.j == len(self.quest_list): submit_button.grid(column=0, row=value+2) else: next_button.grid(column=0, row=value+2, pady=10) def main_do_exam(self): self.root5.destroy() self.root4 = tk.Toplevel() self.root4.resizable(True, True) num = self.num.get() value = self.values.get() self.score = 0 self.j = 1 self.num_choice = tk.IntVar() next_button = tk.Button(self.root4, text='Next', command=self.sub_do_exam) question_label = tk.Label(self.root4, text='%d.'%self.j+self.quest_list[self.j-1].get(), font='Helvetica 16 bold', width = 50, anchor='w') question_label.grid(sticky='W', row=0, column=0) for i in xrange(1, value+1): tk.Radiobutton(self.root4, text='(%d) : '% i+self.all_choice[self.j-1][i-1].get(), variable=self.num_choice, value=i, width = 50, anchor='w').grid(sticky='W', row=i, column=0, padx=10, pady=3) next_button.grid(column=0, row=value+2, pady=10) def finish_create(self): self.ans_list.append(self.correct_choice.get()) self.root3.destroy() self.root5 = tk.Toplevel() self.root5.resizable(True, True) label1 = tk.Label(self.root5, text='Your Examination are Ready to Use', font = "Helvetica 32 bold italic") label1.grid(pady = 100, padx = 300) do_exam_button = tk.Button(self.root5, text='Do the Exam Now !!!', font = "Helvetica 16 bold italic", fg = "red", command=self.main_do_exam) do_exam_button.grid(pady = 20, padx = 300) def sub_add_choice(self): self.ans_list.append(self.correct_choice.get()) self.i += 1 value = self.values.get() self.correct_choice = tk.IntVar(value='Select Answer') tk.Label(self.root3, width = 50, text=str(self.i)+'.'+self.quest_list[self.i-1].get()+' : ').grid(pady=3, row=0, columnspan=3) for i in xrange(value): self.choice_list.append('choice'+str(i)) for j in xrange(1, value+1): self.choice_list[j-1] = tk.StringVar() tk.Label(self.root3, text='('+str(j)+') :').grid(pady=3, row = j+1, column=1) tk.Entry(self.root3, width=50, textvariable=self.choice_list[j-1]).grid(pady=3, padx=10, row = j+1, column=2) self.all_choice.append(self.choice_list) self.choice_list = [] if value == 2: option = tk.OptionMenu(self.root3, self.correct_choice, 1, 2) elif value == 3: option = tk.OptionMenu(self.root3, self.correct_choice, 1, 2, 3) elif value == 4: option = tk.OptionMenu(self.root3, self.correct_choice, 1, 2, 3, 4) elif value == 5: option = tk.OptionMenu(self.root3, self.correct_choice, 1, 2, 3, 4, 5) option.grid(pady=3, column=2, row=value+2) button_next = tk.Button(self.root3, text='Next', command=self.sub_add_choice) button_submit = tk.Button(self.root3, text='Submit', command=self.finish_create) if self.i == len(self.quest_list): button_submit.grid(column=2, row=value+3) else: button_next.grid(column=2, row=value+3) def main_add_choice(self): self.root2.destroy() self.root3 = tk.Toplevel() self.root3.resizable(True,True) value = self.values.get() self.correct_choice = tk.IntVar(value='Select Answer') self.ans_list = [] self.choice_list = [] self.all_choice = [] self.i = 1 tk.Label(self.root3, width = 50, text=str(self.i)+'.'+self.quest_list[self.i-1].get()+' : ').grid(pady=3, row=0, columnspan=3) for i in xrange(value): self.choice_list.append('choice'+str(i)) for j in xrange(1, value+1): self.choice_list[j-1] = tk.StringVar() tk.Label(self.root3, text='('+str(j)+') :').grid(pady=3, row = j+1, column=1) tk.Entry(self.root3, width=50, textvariable=self.choice_list[j-1]).grid(pady=3, padx=10, row = j+1, column=2) self.all_choice.append(self.choice_list) self.choice_list = [] if value == 2: option = tk.OptionMenu(self.root3, self.correct_choice, 1, 2) elif value == 3: option = tk.OptionMenu(self.root3, self.correct_choice, 1, 2, 3) elif value == 4: option = tk.OptionMenu(self.root3, self.correct_choice, 1, 2, 3, 4) elif value == 5: option = tk.OptionMenu(self.root3, self.correct_choice, 1, 2, 3, 4, 5) option.grid(pady=3, column=2, row=value+2) tk.Button(self.root3, text='Next', command=self.sub_add_choice).grid(column=2) def choice(self): self.root1.destroy() self.root2 = tk.Toplevel() self.root2.resizable(True, True) tk.Label(self.root2, text='Please Enter The Number of Your Choices').grid(pady=5) self.values = tk.IntVar(value='Please Select') tk.OptionMenu(self.root2, self.values, 2, 3, 4, 5).grid(pady=2) tk.Button(self.root2, text='Submit', command=self.main_add_choice).grid(pady=5) def question(self): try: if self.num.get() == 1: raise ValueError self.first.destroy() self.root1 = tk.Toplevel() self.root1.resizable(True, True) self.quest_list = [] num = self.num.get() col = 0 row = 1 for j in xrange(1, num+1): self.quest_list.append('quest'+str(j)) for i in xrange(1, num+1): self.quest_list[i-1] = tk.StringVar() tk.Label(self.root1, text='Please Enter Your Question %d :' % i).grid(pady=5, row=(row-1)*2, column=col) entry = tk.Entry(self.root1, width=50, textvariable=self.quest_list[i-1]) entry.grid(row=(row*2)-1, column=col, padx=20) row += 1 if i%10 == 0: if num % 2 == 0: col += 2 else: col += 1 row = 1 tk.Button(self.root1, text='Submit', command=self.choice).grid(columnspan = col + 1, pady = 5) except: tkMessageBox.showerror(title='Error', message='Plase select more than one') root = tk.Tk() app = App(root) root.title('The Examer') root.resizable(True,True) root.mainloop()
Java
UTF-8
6,553
2.625
3
[]
no_license
package Controller; import Model.InHouse; import Model.Inventory; import Model.Outsourced; import Model.Part; import java.net.URL; import java.util.Optional; import java.util.ResourceBundle; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.Label; import javafx.scene.control.RadioButton; import javafx.scene.control.TextField; import javafx.scene.input.MouseEvent; import javafx.stage.Stage; public class AddPartController implements Initializable { Stage stage; Parent scene; @FXML private TextField addPartIdText; @FXML private TextField addPartNameText; @FXML private TextField addPartInvText; @FXML private TextField addPartPriceText; @FXML private TextField addPartMaxText; @FXML private TextField addPartMinText; @FXML private Label outsourcedOrInHouseLabel; @FXML private TextField outsourcedOrInHouseText; @FXML private RadioButton inHouseRb; @FXML private RadioButton outsourcedRb; /* *Asks user if they want to exit without saving. Redirects to Main Screen. */ @FXML void addPartCancelButtonClicked(MouseEvent event) throws Exception { Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setContentText("Are you sure you want to exit without saving?"); Optional<ButtonType> answer = alert.showAndWait(); if(answer.isPresent() && answer.get() == ButtonType.OK) { stage = (Stage)((Button)event.getSource()).getScene().getWindow(); scene = FXMLLoader.load(getClass().getResource("/View/MainScreenFXML.fxml")); stage.setScene(new Scene(scene)); stage.show(); } } /* * Saves the new Part into Inventory and redirects to main screen. * Generates an alert box if entered information doesn't match constraints. */ @FXML void addPartSaveButtonClicked(MouseEvent event) throws Exception { try { String name = addPartNameText.getText(); int inv = Integer.parseInt(addPartInvText.getText()); double price = Double.parseDouble(addPartPriceText.getText()); int max = Integer.parseInt(addPartMaxText.getText()); int min = Integer.parseInt(addPartMinText.getText()); if(min > max) { Alert alert = new Alert(Alert.AlertType.WARNING); alert.setTitle("WARNING: Invalid Values"); alert.setContentText("Min values cannot be greater than Max values."); alert.showAndWait(); } else if (name.equals("")) { Alert alert = new Alert(Alert.AlertType.WARNING); alert.setTitle("WARNING: Empty Fields"); alert.setContentText("All fields must be completed before saving."); alert.showAndWait(); } else if (inv > max || inv < min) { Alert invAlert = new Alert(Alert.AlertType.WARNING); invAlert.setTitle("WARNING: Invalid Values"); invAlert.setContentText("Inventory must be between Max and Min values."); invAlert.showAndWait(); } else { if (inHouseRb.isSelected()) { int machId = Integer.parseInt(outsourcedOrInHouseText.getText()); Part newPart = new InHouse(Part.partIdGenerator(), name, price, inv, min, max, machId); Inventory.addPart(newPart); stage = (Stage)((Button)event.getSource()).getScene().getWindow(); scene = FXMLLoader.load(getClass().getResource("/View/MainScreenFXML.fxml")); stage.setScene(new Scene(scene)); stage.show(); } if (outsourcedRb.isSelected()) { String companyName = outsourcedOrInHouseText.getText(); if (companyName.equals("")) { Alert alert = new Alert(Alert.AlertType.WARNING); alert.setTitle("WARNING: Empty Fields"); alert.setContentText("All fields must be completed before saving."); alert.showAndWait(); } else { Part newPart = new Outsourced(Part.partIdGenerator(), name, price, inv, min, max, companyName); Inventory.addPart(newPart); stage = (Stage)((Button)event.getSource()).getScene().getWindow(); scene = FXMLLoader.load(getClass().getResource("/View/MainScreenFXML.fxml")); stage.setScene(new Scene(scene)); stage.show(); } } } } catch (NumberFormatException e) { Alert alert = new Alert(Alert.AlertType.WARNING); alert.setTitle("WARNING: Empty Fields"); alert.setContentText("All fields must be completed before saving."); alert.showAndWait(); } } /* * Displays correct fields depending on RadioButton Selected (InHouse or Outsourced). */ @FXML void inHouseSelected(MouseEvent event) { outsourcedOrInHouseLabel.setText("Machine ID"); outsourcedOrInHouseText.setPromptText("Mach ID"); } @FXML void outsourcedSelected(MouseEvent event) { outsourcedOrInHouseLabel.setText("Company Name"); outsourcedOrInHouseText.setPromptText("Comp Name"); } @Override public void initialize(URL url, ResourceBundle rb) { addPartIdText.setDisable(true); inHouseRb.setSelected(true); outsourcedOrInHouseLabel.setText("Machine ID"); outsourcedOrInHouseText.setPromptText("Mach ID"); } }
C++
UTF-8
5,315
4.0625
4
[]
no_license
/* Item.h Created by Melinda Stannah Stanley Jothiraj on 02/25/2020. Student number- 1978413 Item class: The item class inherits from the Class Comparable and implements its pure virtual methods The item class also inherits from the Class HashValueType Data members include; inventory, name, year and grade whose access specifiers are protected so that derived class could inherit them The Item Class allows for comparison of 2 item objects based on the name It also has a create method to create dummy command objects a setData method to set the protected fields a toString method */ #include "Item.h" /** //-------------------------- Default constructor for class Item ------------------------------------// Create and new Item Object with deafault value where name = " ", year = 0; grade = 0 */ Item::Item(){ inventoryCount = 0; name = " "; year = " "; grade= " "; } /** //-------------------------- Destructor for class Item ------------------------------------// Destroys object and frees memory allocated by object. */ Item:: ~Item(){ } /** * Output a textual representation of this instance to the output stream. * @pre This instance must be initialized. * @post A textual representation of this instance is appended to a string and returned * @return A textual representation of this instance is appended to a string */ std::string Item::toString()const{ std::string in= std::to_string(inventoryCount); return in + ", " + year + ", " + grade + ", " + name; } /** * Output a textual representation of this instance as a string without the inventory * @pre This instance must be initialized. * @post A textual representation of this instance is appended to a string and returned * @return A textual representation of this instance is appended to a string without the inventory */ std::string Item::toStringWithoutCount()const{ return year + ", " + grade + ", " + name; } /** //-------------------------- Method to increase inventory ------------------------------------// Increments the inventory of an Item Object by 1 */ void Item::increaseInventory(){ inventoryCount++; } /** //-------------------------- Method to decrease inventory ------------------------------------// Decrements the inventory of an Item Object by 1 @returns a bool true if inventorycount was decreased or false if not */ bool Item::decreaseInventory(){ if(inventoryCount > 0){ inventoryCount--; return true; } return false; } /** //-------------------------- Method to set data ------------------------------------// Sets the data members of an Item Object with the parameters provided */ void Item::setData(std::string stringCount, std::string description){ } /** * Output a textual representation of this instance to the output stream. * @pre This instance must be initialized. * @post A textual representation of this instance is appended to a string and returned * @return A textual representation of this instance is appended to a output stream */ std::ostream& operator<<(std::ostream& out, const Item& obj1) { out << obj1.toString(); return out; } /** //-------------------------- Overloaded equal to operator == ------------------------------------// Determines if two Item are equal based on data members Preconditions: two item objects this and right Postconditions: boolean true if the left and right object are the same @return boolean true if same or false if not */ bool Item::operator==(const Comparable& right) const { const Item &c = static_cast<const Item &>(right); return(type == c.type); } /** //-------------------------- Overloaded not equal to operator != ------------------------------------// Determines if two Item are equal based on data members Preconditions: two item objects this and right Postconditions: boolean false if the left and right object are the same @return boolean true if different or false if not */ bool Item::operator!=(const Comparable& right)const { const Item &c = static_cast<const Item &>(right); return !(type == c.type); } /** //-------------------------- Overloaded lesser than operator <------------------------------------// Determines if the item object on the left hand side is smaller than the Item object on right hand side based on name of the item Preconditions: two item objects this and right Postconditions: boolean true if the left hand side data is smaller than the data on the right hand side @return boolean true is left is smaller than right */ bool Item::operator<(const Comparable& right)const { const Item &c = static_cast<const Item &>(right); return(type < c.type); } /** //-------------------------- Overloaded greater than operator > ------------------------------------// Determines if the item object on the left hand side is larger than the Item object on right hand side based on name of the item Preconditions: two item objects this and right Postconditions: boolean true if the left hand side data is larger than the data on the right hand side @return boolean true is left is larger than right */ bool Item::operator>(const Comparable& right)const { const Item &c = static_cast<const Item &>(right); return(type > c.type); } void Item::setType(std::string t){ type = t; }
Java
UTF-8
2,108
2.140625
2
[]
no_license
package com.ylean.cf_hospitalapp.my.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.facebook.drawee.view.SimpleDraweeView; import com.ylean.cf_hospitalapp.R; import com.ylean.cf_hospitalapp.my.bean.HelpEntry; import java.util.List; /** * 帮帮团adapter * Created by linaidao on 2019/1/15. */ public class HelpAdapter extends RecyclerView.Adapter<HelpAdapter.MyViewHolder> { private Context context; private List<HelpEntry.DataBean> helpList; public HelpAdapter(Context context, List<HelpEntry.DataBean> helpList) { this.context = context; this.helpList = helpList; } @Override public HelpAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new HelpAdapter.MyViewHolder( LayoutInflater.from(context).inflate(R.layout.item_help, parent, false)); } @Override public void onBindViewHolder(HelpAdapter.MyViewHolder holder, int position) { holder.tvName.setText(helpList.get(position).getOwner()); holder.tvHospitalName.setText(helpList.get(position).getRoomname()); holder.tvIntroduce.setText(helpList.get(position).getDescription()); holder.tvtime.setText(helpList.get(position).getCreatetime()); } @Override public int getItemCount() { return helpList == null ? 0 : helpList.size(); } class MyViewHolder extends RecyclerView.ViewHolder { SimpleDraweeView sdvImg; TextView tvName; TextView tvHospitalName; TextView tvIntroduce; TextView tvtime; MyViewHolder(View view) { super(view); sdvImg = view.findViewById(R.id.sdvImg); tvName = view.findViewById(R.id.tvName); tvHospitalName = view.findViewById(R.id.tvHospitalName); tvIntroduce = view.findViewById(R.id.tvIntroduce); tvtime = view.findViewById(R.id.tvtime); } } }
Markdown
UTF-8
6,532
2.859375
3
[ "MIT" ]
permissive
# Google-Cloud-Essential-Skills-Challenge-Lab-45-minutes GSP101 Google Cloud Self-Paced Labs Overview For this Challenge Lab you must complete a series of tasks within a limited time period. Instead of following step-by-step instructions, you'll be given a scenario and task - you figure out how to to complete it on your own! An automated scoring system (shown on this page) will provide feedback on whether you have completed your tasks correctly. To score 100% you must complete all tasks within the time period! When you take a Challenge Lab, you will not be taught Google Cloud concepts. You'll need to use your advanced Compute Engine skills to assess how to build the solution to the challenge presented. This lab is only recommended for students who have Compute Engine skills. Are you up for the challenge? Topics tested Create a Linux virtual machine instance Enable public access to VM instance Running basic Apache Web Server Test your server Setup Before you click the Start Lab button Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources will be made available to you. This Qwiklabs hands-on lab lets you do the lab activities yourself in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials that you use to sign in and access Google Cloud for the duration of the lab. What you need To complete this lab, you need: Access to a standard internet browser (Chrome browser recommended). Time to complete the lab. Note: If you already have your own personal Google Cloud account or project, do not use it for this lab. Note: If you are using a Pixelbook, open an Incognito window to run this lab. How to start your lab and sign in to the Google Cloud Console Click the Start Lab button. If you need to pay for the lab, a pop-up opens for you to select your payment method. On the left is a panel populated with the temporary credentials that you must use for this lab. Open Google Console Copy the username, and then click Open Google Console. The lab spins up resources, and then opens another tab that shows the Sign in page. Sign in Tip: Open the tabs in separate windows, side-by-side. If you see the Choose an account page, click Use Another Account. Choose an account In the Sign in page, paste the username that you copied from the Connection Details panel. Then copy and paste the password. Important: You must use the credentials from the Connection Details panel. Do not use your Qwiklabs credentials. If you have your own Google Cloud account, do not use it for this lab (avoids incurring charges). Click through the subsequent pages: Accept the terms and conditions. Do not add recovery options or two-factor authentication (because this is a temporary account). Do not sign up for free trials. After a few moments, the Cloud Console opens in this tab. Note: You can view the menu with a list of Google Cloud Products and Services by clicking the Navigation menu at the top-left. Cloud Console Menu Activate Cloud Shell Cloud Shell is a virtual machine that is loaded with development tools. It offers a persistent 5GB home directory and runs on the Google Cloud. Cloud Shell provides command-line access to your Google Cloud resources. In the Cloud Console, in the top right toolbar, click the Activate Cloud Shell button. Cloud Shell icon Click Continue. cloudshell_continue.png It takes a few moments to provision and connect to the environment. When you are connected, you are already authenticated, and the project is set to your PROJECT_ID. For example: Cloud Shell Terminal gcloud is the command-line tool for Google Cloud. It comes pre-installed on Cloud Shell and supports tab-completion. You can list the active account name with this command: gcloud auth list (Output) Credentialed accounts: - <myaccount>@<mydomain>.com (active) (Example output) Credentialed accounts: - google1623327_student@qwiklabs.net You can list the project ID with this command: gcloud config list project (Output) [core] project = <project_ID> (Example output) [core] project = qwiklabs-gcp-44776a13dea667a6 For full documentation of gcloud see the gcloud command-line tool overview. Challenge scenario Your company is ready to launch a brand new product! Because you are entering a totally new space, you have decided to deploy a new website as part of the product launch. The new site is complete, but the person who built the new site left the company before they could deploy it. Your challenge Your challenge is to deploy the site in the public cloud by completing the tasks below. You will use a simple Apache web server as a placeholder for the new site in this exercise. Good luck! Running a Basic Apache Web Server A virtual machine instance on Compute Engine can be controlled like any standard Linux server. Deploy a simple Apache web server (a placeholder for the new product site) to learn the basics of running a server on a virtual machine instance. Create a Linux VM Instance Create a Linux virtual machine, name it "Apache" and specify the zone as "us-central1-a". Enable Public Access to VM Instance While creating the Linux instance, make sure to apply the appropriate firewall rules so that potential customers can find your new product. Click Check my progress to verify the objective. Create a Compute Engine instance, add necessary firewall rules. Running a Basic Apache Web Server A virtual machine instance on Compute Engine can be controlled like any standard Linux server. Deploy a simple Apache web server (a placeholder for the new product site) to learn the basics of running a server on a virtual machine instance. Click Check my progress to verify the objective. Add Apache2 HTTP Server to your instance Test Your Server Test that your instance is serving traffic on its external IP. You should see the "Hello World!" page (a placeholder for the new product site). Click Check my progress to verify the objective. Test your server Troubleshooting Receiving a Connection Refused Error: Your VM instance is not publicly accessible because the VM instance does not have the proper tag that allows Compute Engine to apply the appropriate firewall rules, or your project does not have a firewall rule that allows traffic to your instance's external IP address. You are trying to access the VM using an https address. Check that your URL is http:// EXTERNAL_IP and not https:// EXTERNAL_IP Congratulations!
Python
UTF-8
1,420
3.34375
3
[]
no_license
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # below two dicts used to store the current node's max value # to avoid duplicated computing. node_dict1 = {} node_dict2 = {} def robb(self, current: TreeNode, parent_chk: bool) -> int: val = 0 if parent_chk: if current is not None: if current in self.node_dict1: return self.node_dict1[current] val = self.robb(current.left, False) + self.robb(current.right, False) self.node_dict1[current] = val else: val = 0 else: if current is not None: if current in self.node_dict2: return self.node_dict2[current] val = max(current.val + self.robb(current.left, True) + self.robb(current.right, True), self.robb(current.left, False) + self.robb(current.right, False)) self.node_dict2[current] = val else: val = 0 return val def rob(self, root: TreeNode) -> int: if root is not None: return max(root.val + self.robb(root.left, True) + self.robb(root.right, True), self.robb(root.left, False) + self.robb(root.right, False)) else: return 0
Python
UTF-8
1,978
3.140625
3
[]
no_license
#directory organizer import os import parser import ntree def check_string(string): try: str(string) return(True) except ValueError: return(False) class sorting_hat: def __init__(self): self.cache_file_name = '.cache.dat' self.data_tree = ntree.__init__() self.fp = None if os.stat(self.cache_file_name).st_size > 0: for line in self.fp.change_file(self.cache_file_name): temp = self.fp.read_line().split(' ') # self.file_map.update(temp[0], temp[1]) else: self.scan_directory() print('Initialized\n') def __del__(self): self.data_tree.__del__() def scan_directory(self): cur_dir = '' while True: cur_dir = input('Enter directory to start scan') if check_string(cur_dir) and os.path.isdir(cur_dir): break else: print('Invalid!\n') continue os.chdir(cur_dir) root = cur_dir #begin building directory tree while True: #list sub-directorys and files at current location temp_list = os.listdir(cur_dir) for item in temp_list: #somefunction that tells me waht the damn filetype is if os.path.isdir(cur_dir + item) is not True: #add data to current node self.data_tree.add_data(item, cur_dir) else: #add subdirectory to current node self.data_tree.add_node(item, cur_dir) temp_list.append(cur_dir + item) if len(temp_list) > 0: # update current dirrectory with subdirectory of current location cur_dir = temp_list.pop() else: # exit tree building when list is empty, representing no more subdirectories to scan break
JavaScript
UTF-8
1,308
3.609375
4
[]
no_license
/* * @lc app=leetcode.cn id=1 lang=javascript * * [1] 两数之和 */ // @lc code=start /** * @param {number[]} nums * @param {number} target * @return {number[]} */ // var twoSum = function(nums, target) { // // 0、声明一个map用于存储数据,如果map没有当前数据:key 为数组值,value为下标 存储 // // 1、遍历数组,map 中查找当前是否有 (target - nums[i]) 为Key存在 // // 2、如果(target - nums[i]) 在map中,返回数组的下标和当前map 对应key 的value // let diffMap = new Map(); // let len = nums.length; // for(let i=0; i<len; i++){ // if(diffMap.has(target-nums[i])){ // return [diffMap.get(target-nums[i]), i] // }else{ // diffMap.set(nums[i], i) // } // } // }; var twoSum = function (nums, target) { // 0、用while从后向前便利数组 // 1、每次遍历先pop最后一个值,再通过indexOf来查找是否有差值,pop的好处是防止有连个数相等 // 2、如果有对应的值,下标就是对应的indexOf和数组的长度 let i = nums.length; while (i > 1) { let last = nums.pop(); if (nums.indexOf(target - last) !== -1) { return [nums.indexOf(target - last), nums.length]; } i--; } }; // @lc code=end
Java
UTF-8
472
2.390625
2
[]
no_license
package pl.milgro.carrental.domain; import lombok.Getter; import lombok.NoArgsConstructor; import javax.persistence.*; @Getter @NoArgsConstructor @Entity(name = "pricelist") public class Cost { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(name = "cost_name") private String name; private Double price; public Cost(String name, Double price) { this.name = name; this.price = price; } }
Java
UTF-8
7,258
1.726563
2
[]
no_license
package com.myyg.ui.activity; import android.os.Bundle; import android.os.Handler; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Html; import android.widget.RelativeLayout; import com.alibaba.fastjson.JSON; import com.andview.refreshview.XRefreshView; import com.lidroid.xutils.HttpUtils; import com.lidroid.xutils.exception.HttpException; import com.lidroid.xutils.http.RequestParams; import com.lidroid.xutils.http.ResponseInfo; import com.lidroid.xutils.http.callback.RequestCallBack; import com.lidroid.xutils.http.client.HttpRequest; import com.myyg.R; import com.myyg.adapter.recycler.RecyclerAdapter; import com.myyg.adapter.recycler.RecyclerViewHolder; import com.myyg.base.BaseActivity; import com.myyg.base.BaseApplication; import com.myyg.constant.SysConstant; import com.myyg.constant.SysHtml; import com.myyg.constant.SysStatusCode; import com.myyg.constant.URLS; import com.myyg.model.MessageResult; import com.myyg.model.NoticeModel; import com.myyg.utils.DateHelper; import com.myyg.utils.MyLog; import com.myyg.utils.UIHelper; import com.myyg.widget.xrefreshview.MyygRefreshFooter; import com.myyg.widget.xrefreshview.MyygRefreshHeader; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2016/5/29. */ public class NoticeActivity extends BaseActivity { private List<NoticeModel> listNotice = new ArrayList<>(); private RecyclerAdapter<NoticeModel> adapter; private RecyclerView rv_notice; private XRefreshView xRefreshView; private int pageIndex = 1; @Override public void initView() { this.setContentView(R.layout.activity_notice); this.xRefreshView = (XRefreshView) this.findViewById(R.id.xRefreshView); this.rv_notice = (RecyclerView) this.findViewById(R.id.rv_notice); } @Override public void initData() { } @Override public void fillView() { this.setToolBar("通知"); this.bindRecycleView(); } /** * */ private void bindRecycleView() { this.xRefreshView.setPullLoadEnable(true); MyygRefreshHeader header = new MyygRefreshHeader(this.mContext); this.xRefreshView.setCustomHeaderView(header); this.xRefreshView.setMoveForHorizontal(true); this.xRefreshView.setAutoLoadMore(true); this.xRefreshView.setAutoRefresh(true); this.adapter = new RecyclerAdapter<NoticeModel>(this.mContext, this.listNotice, R.layout.item_notice) { @Override public void convert(RecyclerViewHolder helper, NoticeModel item, int position) { String title = item.getTitle(); if (item.getIs_read() == 0) { title = MessageFormat.format("<font color=\"#c62435\">[未读]</font><font color=\"#333333\">{0}</font>", title); } else { title = MessageFormat.format("<font color=\"#888888\">{0}</font>", title); } String time = MessageFormat.format("<font color=\"{0}\">{1}</font>", item.getIs_read() == 0 ? "#333333" : "#888888", DateHelper.getDefaultDate(item.getSend_time() * 1000)); helper.setText(R.id.tv_title, Html.fromHtml(title)); helper.setText(R.id.tv_time, Html.fromHtml(time)); RelativeLayout rl_content = helper.getView(R.id.rl_content); rl_content.setOnClickListener(v -> { item.setIs_read(1); adapter.notifyItemChanged(position); String linkUrl = MessageFormat.format("{0}/{1}", SysHtml.HTML_NOTICE_DETAILS, item.getId()); Bundle bundle = new Bundle(); bundle.putString(WebBrowseActivity.WEB_BROWSE_LINK_TAG, linkUrl); UIHelper.startActivity(mContext, WebBrowseActivity.class, bundle); readNotice(item.getId()); }); } }; this.rv_notice.setHasFixedSize(true); this.rv_notice.setLayoutManager(new LinearLayoutManager(this.mContext)); this.rv_notice.setAdapter(this.adapter); this.adapter.setCustomLoadMoreView(new MyygRefreshFooter(this.mContext)); } @Override public void bindListener() { this.xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() { @Override public void onRefresh() { xRefreshView.setPullLoadEnable(true); new Handler().postDelayed(() -> { pageIndex = 1; listNotice.clear(); loadData(); }, 1000); } @Override public void onLoadMore(boolean isSlience) { loadData(); } }); } /** * */ private void loadData() { String url = MessageFormat.format("{0}/{1}/{2}", URLS.USER_NOTICE_LIST, pageIndex, SysConstant.PAGE_SIZE); HttpUtils http = new HttpUtils(); http.configDefaultHttpCacheExpiry(0); RequestParams params = BaseApplication.getParams(); http.send(HttpRequest.HttpMethod.GET, url, params, new RequestCallBack<String>() { @Override public void onSuccess(ResponseInfo<String> responseInfo) { MessageResult message = MessageResult.parse(responseInfo.result); List<NoticeModel> list = new ArrayList<>(); if (message.getCode() == SysStatusCode.SUCCESS) { list = JSON.parseArray(message.getData(), NoticeModel.class); listNotice.addAll(list); adapter.notifyDataSetChanged(); } if (list.size() < SysConstant.PAGE_SIZE) { xRefreshView.setPullLoadEnable(false); } if (pageIndex == 1) { xRefreshView.stopRefresh(); } else { xRefreshView.stopLoadMore(); } if (list.size() == SysConstant.PAGE_SIZE) { pageIndex++; } } @Override public void onFailure(HttpException e, String s) { } }); } /** * @param noticeId */ private void readNotice(int noticeId) { HttpUtils http = new HttpUtils(); RequestParams params = BaseApplication.getParams(); params.addBodyParameter("id", noticeId + ""); http.send(HttpRequest.HttpMethod.POST, URLS.USER_READ_NOTICE, params, new RequestCallBack<String>() { @Override public void onSuccess(ResponseInfo<String> responseInfo) { MessageResult result = MessageResult.parse(responseInfo.result); if (result.getCode() != SysStatusCode.SUCCESS) { MyLog.i(TAG, result.getMsg()); return; } MyLog.i(TAG, "通知读取成功"); } @Override public void onFailure(HttpException e, String s) { MyLog.i(TAG, s); } }); } }
PHP
UTF-8
3,594
2.796875
3
[ "MIT", "LicenseRef-scancode-other-permissive" ]
permissive
<?php namespace Itgalaxy\Pillar\Feature; use Itgalaxy\Pillar\Base\FeatureAbstract; class YandexTableauWidgetFeature extends FeatureAbstract { protected $options = [ 'queryVar' => 'yandex-tableau-widget', 'filename' => 'yandex-tableau-widget.json', 'icons' => [ ['width' => 120, 'height' => 120] ], 'yandexManifestColor' => null ]; /** * Register our class method(s) with the appropriate WordPress hooks. * * @return void */ public function initialize() { add_filter('query_vars', [$this, 'queryVars']); add_filter('rewrite_rules_array', [$this, 'rewriteRulesArray']); add_action('parse_query', [$this, 'handle']); add_filter('site_icon_image_sizes', [$this, 'siteIconImageSizes']); add_filter('site_icon_meta_tags', [$this, 'siteIconMetaTags']); } public function activation() { flush_rewrite_rules(); } public function queryVars($queryVars) { $queryVars[] = $this->options['queryVar']; return $queryVars; } public function rewriteRulesArray($rules) { $newRewriteRules = []; $newRewriteRules['^' . preg_quote($this->options['filename']) . '$'] = 'index.php?' . $this->options['queryVar'] . '=' . pathinfo($this->options['filename'], PATHINFO_FILENAME); return $newRewriteRules + $rules; } public function handle($query) { if (array_key_exists($this->options['queryVar'], $query->query_vars)) { header('Content-Type: application/json; charset=' . get_option('blog_charset'), true); $manifest = new \stdClass(); $manifest->api_version = 4; $manifest->layout = new \stdClass(); $icon = current($this->options['icons']); $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower'; if (!empty($icon['width'])) { $siteIconURL = get_site_icon_url($icon['width']); if ($siteIconURL) { $ext = $strtolower(pathinfo($siteIconURL, PATHINFO_EXTENSION)); if ($ext == 'png') { $manifest->layout->logo = $siteIconURL; } } } if (!empty($this->options['yandexManifestColor'])) { $manifest->layout->color = $strtolower($this->options['yandexManifestColor']); } echo wp_json_encode($manifest); if (wp_doing_ajax()) { wp_die('', '', ['response' => null]); // escape ok } else { exit(); } } } public function siteIconImageSizes($sizes) { $newSizes = []; foreach ($this->options['icons'] as $size) { if (empty($size['width']) || !is_int($size['width'])) { continue; } $newSizes[] = $size['width']; } return array_unique(array_merge($sizes, $newSizes)); } public function siteIconMetaTags($metaTags) { $permalinkStructure = get_option('permalink_structure'); $url = $permalinkStructure ? get_home_url(null, $this->options['filename']) : 'index.php?' . $this->options['queryVar'] . '=' . $this->options['filename']; $metaTags[] = sprintf( '<link rel="yandex-tableau-widget" href="%s">', esc_url($url) ); return $metaTags; } }
Python
UTF-8
2,999
3.125
3
[ "MIT" ]
permissive
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import shutil import tkinter as tk def open_marc_folder(): '''Opens folder to location of MARC files.''' os.system(r'start .\marc_files') def join_marc_records(output_text): '''Joins MARC records located in MARC folder.''' # Change to MARC folder dir. os.chdir('./marc_files') marc_files = os.listdir() # Get number of MARC files, minus 1 from count if following file present. if 'combined_marc_files.mrc' in marc_files: num_marc_files = len(marc_files) - 1 else: num_marc_files = len(marc_files) # If 2 or more files are present, join the contents into single file. if num_marc_files >= 2: with open('combined_marc_files.mrc', 'wb') as wfd: for f in marc_files: if f == 'combined_marc_files.mrc': continue else: with open(f, 'rb') as fd: shutil.copyfileobj(fd, wfd) # Clear text box and provide status update. output_text.delete(1.0, tk.END) output_text.insert(tk.INSERT, f'{str(num_marc_files)} MARC files were' ' joined.\n') else: # Clear text box and provide status update. output_text.delete(1.0, tk.END) output_text.insert( tk.INSERT, 'At least two MARC records need to be present in the' ' the directory to join.\n') # Change dir back to root. os.chdir('..') def submission(url_entry, output_text, document_request, output_to_text, output_to_marc, doc_regex): ''' Requests document, searches document using regular expressions, outputs text to text box and writes data to a MARC file. ''' # Function is True if tuple is returned. if document_request(url_entry, output_text): num_pages, document_output = document_request(url_entry, output_text) # Unpack tuples from doc_regex output. (doc_num, doc_year, doc_title, non_filing, _, _, doc_iss_year, welcomes, this_res, field_710, date_field_008, time_field_590, time_field_856) = doc_regex(document_output) # Outputs bibliographic data in text format to text field. output_to_text(output_text, doc_year, doc_num, non_filing, doc_title, doc_iss_year, num_pages, welcomes, this_res, date_field_008, time_field_590, field_710, time_field_856, url_entry) # Outputs data in MARC format and writes to disk. output_to_marc(output_text, doc_year, doc_num, non_filing, doc_title, doc_iss_year, num_pages, welcomes, this_res, date_field_008, time_field_590, field_710, time_field_856, url_entry) # Outputs string to text field. output_text.insert( tk.INSERT, '\n\nWriting to MARC file...') else: return
C++
UTF-8
5,422
3.265625
3
[]
no_license
#include "CollisionProcessor.h" #include "../../utils/math/Coords.h" #include "../../components/map/Map.h" CollisionProcessor::CollisionProcessor(MapBounds *bounds, MapState *mapState, MapGraphics *mapGraphics) : m_bounds(bounds), m_mapState(mapState), m_mapGraphics(mapGraphics) {} void CollisionProcessor::processMovingTile(float cx, float cy, float radius, double angle, sf::Vector2f& collisionVector) { if (angle >= THREE_QUARTER_PI || angle <= -THREE_QUARTER_PI) { processLeft(cx, cy, radius, collisionVector); return; } if (angle >= QUARTER_PI) { processBottom(cx, cy, radius, collisionVector); return; } if (angle <= -QUARTER_PI) { processTop(cx, cy, radius, collisionVector); return; } processRight(cx, cy, radius, collisionVector); } void CollisionProcessor::processLeft(float cx, float cy, float radius, sf::Vector2f &collisionVector) { int topLeftValue = getTopLeftValue(cx, cy, radius); int bottomLeftValue = getBottomLeftValue(cx, cy, radius); if (topLeftValue > 0 && bottomLeftValue > 0) { collisionVector.x = 0; collisionVector.y = 0; return; } if (topLeftValue == 0 && bottomLeftValue > 0) { updateCollisionVector(UP_LEFT_ANGLE, collisionVector); return; } if (bottomLeftValue == 0 && topLeftValue > 0) { updateCollisionVector(DOWN_LEFT_ANGLE, collisionVector); } } void CollisionProcessor::processRight(float cx, float cy, float radius, sf::Vector2f &collisionVector) { int topRightValue = getTopRightValue(cx, cy, radius); int bottomRightValue = getBottomRightValue(cx, cy, radius); if (bottomRightValue > 0 && topRightValue > 0) { collisionVector.x = 0; collisionVector.y = 0; return; } if (topRightValue == 0 && bottomRightValue > 0) { updateCollisionVector(UP_RIGHT_ANGLE, collisionVector); return; } if (bottomRightValue == 0 && topRightValue > 0) { updateCollisionVector(DOWN_RIGHT_ANGLE, collisionVector); } } void CollisionProcessor::processTop(float cx, float cy, float radius, sf::Vector2f &collisionVector) { int topLeftValue = getTopLeftValue(cx, cy, radius); int topRightValue = getTopRightValue(cx, cy, radius); if (topLeftValue > 0 && topRightValue > 0) { collisionVector.x = 0; collisionVector.y = 0; return; } if (topLeftValue == 0 && topRightValue > 0) { updateCollisionVector(UP_LEFT_ANGLE, collisionVector); return; } if (topRightValue == 0 && topLeftValue > 0) { updateCollisionVector(UP_RIGHT_ANGLE, collisionVector); } } void CollisionProcessor::processBottom(float cx, float cy, float radius, sf::Vector2f &collisionVector) { int bottomLeftValue = getBottomLeftValue(cx, cy, radius); int bottomRightValue = getBottomRightValue(cx, cy, radius); if (bottomLeftValue > 0 && bottomRightValue > 0) { collisionVector.x = 0; collisionVector.y = 0; return; } if (bottomLeftValue == 0 && bottomRightValue > 0) { updateCollisionVector(DOWN_LEFT_ANGLE, collisionVector); return; } if (bottomRightValue == 0 && bottomLeftValue > 0) { updateCollisionVector(DOWN_RIGHT_ANGLE, collisionVector); } } void CollisionProcessor::updateCollisionVector(double angle, sf::Vector2f &collisionVector) { collisionVector.x = (float)cos(angle); collisionVector.y = (float)sin(angle); } int CollisionProcessor::getBottomRightValue(float cx, float cy, float radius) { sf::Vector2i coordsDRB((int)cx + BOUND_CHECK_HEAD_ROOM_OFFSET, (int)(cy + radius)); sf::Vector2i coordsDRT((int)(cx + radius * 2), (int)cy + BOUND_CHECK_HEAD_ROOM_OFFSET); return getTileValue(coordsDRB, coordsDRT); } int CollisionProcessor::getBottomLeftValue(float cx, float cy, float radius) { sf::Vector2i coordsDLB((int)cx - BOUND_CHECK_HEAD_ROOM_OFFSET, (int)(cy + radius)); sf::Vector2i coordsDLT((int)(cx - radius * 2), (int)cy + BOUND_CHECK_HEAD_ROOM_OFFSET); return getTileValue(coordsDLB, coordsDLT); } int CollisionProcessor::getTopLeftValue(float cx, float cy, float radius) { sf::Vector2i coordsTLT((int)cx - BOUND_CHECK_HEAD_ROOM_OFFSET, (int)(cy - radius)); sf::Vector2i coordsTLB((int)(cx - radius * 2), (int)cy - BOUND_CHECK_HEAD_ROOM_OFFSET); return getTileValue(coordsTLT, coordsTLB); } int CollisionProcessor::getTopRightValue(float cx, float cy, float radius) { sf::Vector2i coordsTRT((int)cx + BOUND_CHECK_HEAD_ROOM_OFFSET, (int)(cy - radius)); sf::Vector2i coordsTRB((int)(cx + radius * 2), (int)cy - BOUND_CHECK_HEAD_ROOM_OFFSET); return getTileValue(coordsTRT, coordsTRB); } int CollisionProcessor::getTileValue(sf::Vector2i &first, sf::Vector2i &second) { Coords::fromIsometric(first, m_mapState->x() - m_mapState->isometricOffsetX(), m_mapState->y()); first.x /= NODE_SIZE; first.y /= NODE_SIZE; Coords::fromIsometric(second, m_mapState->x() - m_mapState->isometricOffsetX(), m_mapState->y()); second.x /= NODE_SIZE; second.y /= NODE_SIZE; int value = m_bounds->get(first.x, first.y); if (m_bounds->get(second.x, second.y) > value) { return m_bounds->get(second.x, second.y); } return value; }
Java
UTF-8
24,740
2.015625
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Timetable.Management.System; import static Timetable.Management.System.AddRoom.DB_URL; import static Timetable.Management.System.DeleteBuilding.sList; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; /** * * @author swpas */ public class EditLecturer extends javax.swing.JFrame { /** * Creates new form EditLecturer */ public EditLecturer() throws SQLException { initComponents(); currentBuildings(); getLecidCombo(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel6 = new javax.swing.JLabel(); center = new javax.swing.JComboBox<>(); jLabel7 = new javax.swing.JLabel(); building = new javax.swing.JComboBox<>(); jLabel8 = new javax.swing.JLabel(); level = new javax.swing.JComboBox<>(); jLabel9 = new javax.swing.JLabel(); rank = new javax.swing.JTextField(); EditLecturer = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); name = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); dept = new javax.swing.JTextField(); BackLecturer = new javax.swing.JButton(); faculty = new javax.swing.JComboBox<>(); jLabel2 = new javax.swing.JLabel(); lecidcombo = new javax.swing.JComboBox<>(); submitID = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Time Table Management System"); setSize(new java.awt.Dimension(1400, 700)); jLabel6.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N jLabel6.setText("Center :"); center.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N center.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Malabe", "Metro", "Matara", "Kandy", "Kurunagala", "Jaffna" })); jLabel7.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N jLabel7.setText("Department :"); building.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N jLabel8.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N jLabel8.setText("Level :"); level.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N level.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "1-Professor", "2-Assistant Professor", "3-Senior Lecturer(HG)", "4-Senior Lecturer", "5-Lecturer", "6-Assistant Lecturer", "7-Instructors" })); jLabel9.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N jLabel9.setText("Rank :"); rank.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N EditLecturer.setBackground(new java.awt.Color(204, 204, 204)); EditLecturer.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N EditLecturer.setText("Edit"); EditLecturer.setMaximumSize(new java.awt.Dimension(63, 29)); EditLecturer.setMinimumSize(new java.awt.Dimension(63, 29)); EditLecturer.setPreferredSize(new java.awt.Dimension(63, 29)); EditLecturer.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EditLecturerActionPerformed(evt); } }); jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N jLabel1.setText("Lecturer Name : "); name.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N name.setHorizontalAlignment(javax.swing.JTextField.LEFT); name.setDropMode(javax.swing.DropMode.INSERT); name.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { nameActionPerformed(evt); } }); jLabel3.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N jLabel3.setForeground(new java.awt.Color(51, 51, 255)); jLabel3.setText("Select Lecturer ID :"); jLabel4.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N jLabel4.setText("Faculty : "); jLabel5.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N jLabel5.setText("Building :"); dept.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N dept.setHorizontalAlignment(javax.swing.JTextField.LEFT); dept.setDropMode(javax.swing.DropMode.INSERT); dept.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { deptActionPerformed(evt); } }); BackLecturer.setBackground(new java.awt.Color(204, 204, 204)); BackLecturer.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N BackLecturer.setText("Back"); BackLecturer.setMaximumSize(new java.awt.Dimension(63, 29)); BackLecturer.setMinimumSize(new java.awt.Dimension(63, 29)); BackLecturer.setPreferredSize(new java.awt.Dimension(63, 29)); BackLecturer.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BackLecturerActionPerformed(evt); } }); faculty.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N faculty.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Computing", "Engineering", "Business", "Humanities & Sciences" })); faculty.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/editLec.jpg"))); // NOI18N jLabel2.setText("jLabel2"); lecidcombo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { lecidcomboActionPerformed(evt); } }); submitID.setBackground(new java.awt.Color(204, 204, 204)); submitID.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N submitID.setText("submit"); submitID.setMaximumSize(new java.awt.Dimension(63, 29)); submitID.setMinimumSize(new java.awt.Dimension(63, 29)); submitID.setPreferredSize(new java.awt.Dimension(63, 29)); submitID.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { submitIDActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(287, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel6) .addComponent(jLabel7) .addComponent(jLabel9, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 176, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(dept) .addComponent(center, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(building, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(faculty, 0, 503, Short.MAX_VALUE) .addComponent(level, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(rank) .addComponent(name))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(EditLecturer, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(32, 32, 32) .addComponent(BackLecturer, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(171, 171, 171))) .addGap(323, 323, 323)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(lecidcombo, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(submitID, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(441, 441, 441)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(57, 57, 57) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lecidcombo, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(submitID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 64, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(faculty, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7) .addComponent(dept, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(center, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(building, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel8) .addComponent(level, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel9) .addComponent(rank, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(28, 28, 28) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(EditLecturer, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(BackLecturer, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(47, 47, 47)) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents Connection con; PreparedStatement show; private Connection DoConnect() throws SQLException{ Connection conn=null; try{ Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(DB_URL, "root", "1234"); }catch (ClassNotFoundException ex) { Logger.getLogger(AddRoom.class.getName()).log(Level.SEVERE, null, ex); } return conn; } private void currentBuildings() throws SQLException{ Connection conn = DoConnect(); try { ResultSet rs = conn.createStatement().executeQuery("SELECT * FROM buildings"); while(rs.next()){ sList.add(rs.getString(1)); building.addItem(String.format("%s | (%s)",rs.getString(2),rs.getString(3))); } } catch (SQLException ex) { Logger.getLogger(DeleteBuilding.class.getName()).log(Level.SEVERE, null, ex); } } //get id list to combo private void getLecidCombo(){ try { Class.forName("com.mysql.jdbc.Driver"); Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/timetablems","root","1234"); Statement statement = connection.createStatement(); String query = "SELECT lecid FROM lecturer"; ResultSet rs = statement.executeQuery(query); while (rs.next()) { String lid = rs.getString("lecid"); lecidcombo.addItem(rs.getString("lecid")); }//end while connection.close(); } catch (Exception e) { e.printStackTrace(); } } private void EditLecturerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EditLecturerActionPerformed // TODO add your handling code here: Connection con; PreparedStatement update; String selectedIDs = (String)lecidcombo.getSelectedItem(); String lname = name.getText(); String lfaculty = (String)faculty.getSelectedItem( ); String ldepartment = dept.getText(); String lcenter = (String)center.getSelectedItem(); String lbuilding = (String)building.getSelectedItem(); String llevel = (String)level.getSelectedItem(); String lrank = rank.getText(); try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost/timetablems","root","1234"); update = con.prepareStatement("update lecturer set name=?,faculty=?,department=?,center=?,building=?,level=?,rank=? where lecid=?"); update.setString(1, lname); update.setString(2, lfaculty); update.setString(3, ldepartment); update.setString(4, lcenter); update.setString(5, lbuilding); update.setString(6, llevel); update.setString(7, lrank); update.setString(8, selectedIDs); update.executeUpdate(); JOptionPane.showMessageDialog(this, "Lecturer "+ selectedIDs +" updated successfully!"); new Lecturerlist().setVisible(true); dispose(); } catch (ClassNotFoundException ex) { Logger.getLogger(AddLecturer.class.getName()).log(Level.SEVERE, null, ex); }catch (SQLException ex) { Logger.getLogger(AddLecturer.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_EditLecturerActionPerformed private void nameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nameActionPerformed // TODO add your handling code here: }//GEN-LAST:event_nameActionPerformed private void deptActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deptActionPerformed // TODO add your handling code here: }//GEN-LAST:event_deptActionPerformed private void BackLecturerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BackLecturerActionPerformed // TODO add your handling code here: new SystemLecturer().setVisible(true); dispose(); }//GEN-LAST:event_BackLecturerActionPerformed private void submitIDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submitIDActionPerformed // TODO add your handling code here: String selectedID = (String)lecidcombo.getSelectedItem(); try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost/timetablems","root","1234"); show = con.prepareStatement("select * from lecturer where lecid = '"+selectedID+"'"); ResultSet rs = show.executeQuery(); while (rs.next()) { name.setText(rs.getString("name")); faculty.setSelectedItem(rs.getString("faculty")); dept.setText(rs.getString("department")); center.setSelectedItem(rs.getString("center")); building.setSelectedItem(rs.getString("building")); level.setSelectedItem(rs.getString("level")); rank.setText(rs.getString("rank")); }//end while } catch (ClassNotFoundException ex) { Logger.getLogger(subjectlist.class.getName()).log(Level.SEVERE, null, ex); }catch (SQLException ex) { Logger.getLogger(subjectlist.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_submitIDActionPerformed private void lecidcomboActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_lecidcomboActionPerformed // TODO add your handling code here: }//GEN-LAST:event_lecidcomboActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(EditLecturer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(EditLecturer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(EditLecturer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(EditLecturer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { try { new EditLecturer().setVisible(true); } catch (SQLException ex) { Logger.getLogger(EditLecturer.class.getName()).log(Level.SEVERE, null, ex); } } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton BackLecturer; private javax.swing.JButton EditLecturer; private javax.swing.JComboBox<String> building; private javax.swing.JComboBox<String> center; private javax.swing.JTextField dept; private javax.swing.JComboBox<String> faculty; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JComboBox<String> lecidcombo; private javax.swing.JComboBox<String> level; private javax.swing.JTextField name; private javax.swing.JTextField rank; private javax.swing.JButton submitID; // End of variables declaration//GEN-END:variables }
C
UTF-8
2,386
3.765625
4
[]
no_license
#include<stdio.h> #include<stdlib.h> struct BSTNode{ struct BSTNode *left; struct BSTNode *right; int data; }; void preorder(struct BSTNode *root); // finding the element struct BSTNode* find(struct BSTNode *root,int data) { if(root==NULL) return NULL; if(data<root->data) return(find(root->left,data)); else if(data>root->data) return(find(root->right,data)); return(root); } // inserting the node in the list void insert( struct BSTNode *root,int data) { struct BSTNode *par; struct BSTNode *n=malloc(sizeof(struct BSTNode)); n->left=NULL; n->right=NULL; if(root==NULL) // if there is no noode n=root; else{ par=root; while(par!=NULL) { if(par->data>data) { // data of par> inserting data if(par->left==NULL) par->left=n; par=par->left; } else if(par->data<data) // data of par is < inserting data { if(par->right==NULL) par->right=n; par=par->right; } } } } // deletion in bst // if the element to be deleted is leaf node // struct BSTNode* Delete(struct BSTNode *root, int data) // { // structBSTNode *temp; // if(root==NULL) // pirntf("no such elelment exixts"); // else if(data<root->data) // } void preorder(struct BSTNode *root) { if(root) { printf("%d", root->data); preorder(root->left); preorder(root->right); } } int main() { int choice,data; struct BSTNode *root=NULL; while(1) { printf("/n1.for insert"); printf("/n2. for display"); printf("/n3. for exit"); printf("/nenter choice"); scanf("%d",&choice); switch(choice) { case 1: printf("/nenetr data"); scanf("%d",&data); insert(root,data); break; case 2: preorder(root); break; case 3: exit(0); default: printf("invalid choice"); } } }
C#
UTF-8
1,284
4.0625
4
[]
no_license
using System; class FindSumInArray { static void Main(string[] args) { // Write a program that finds in given array of integers a sequence of given sum S (if present). Console.WriteLine("Please enter values in the array: "); string[] input = Console.ReadLine().Split(' '); int s = int.Parse(Console.ReadLine()); int[] numbers = new int[input.Length]; for (int i = 0; i < input.Length; i++) { numbers[i] = int.Parse(input[i]); } int startIndex = 0; int currentSum = 0; int endIndex = 0; for (int i = 0; i < numbers.Length; i++) { currentSum += numbers[i]; if (currentSum > s) { currentSum = 0; i = startIndex; startIndex++; } if (currentSum == s) { endIndex = i; break; } } for (int i = startIndex; i <= endIndex; i++) { Console.Write("{0}, ", numbers[i]); } } }
PHP
UTF-8
387
2.734375
3
[]
no_license
<?php namespace aug\base; class Widget extends Base implements WidgetInterface{ public static function widget($options = []){ $className = get_called_class(); $widget = new $className; call_user_func_array([$widget, "init"], [$options]); return call_user_func_array([$widget, "run"], [$options]); } public function init($options = []){} public function run(){} }
Go
UTF-8
1,101
3
3
[ "MIT" ]
permissive
/** * Created: 2019/4/19 0019 * @author: Jason */ package network import ( "sync" "github.com/lightning-go/lightning/defs" ) type ConnectionMgr struct { mux sync.RWMutex conns map[string]defs.IConnection } func NewConnMgr() *ConnectionMgr { return &ConnectionMgr{ conns: make(map[string]defs.IConnection), } } func (cm *ConnectionMgr) ConnCount() int { cm.mux.RLock() count := len(cm.conns) cm.mux.RUnlock() return count } func (cm *ConnectionMgr) AddConn(conn defs.IConnection) { cm.mux.Lock() cm.conns[conn.GetId()] = conn cm.mux.Unlock() } func (cm *ConnectionMgr) DelConn(connId string) { cm.mux.Lock() _, ok := cm.conns[connId] if ok { delete(cm.conns, connId) } cm.mux.Unlock() } func (cm *ConnectionMgr) GetConn(connId string) defs.IConnection { cm.mux.RLock() conn, ok := cm.conns[connId] if !ok { cm.mux.RUnlock() return nil } cm.mux.RUnlock() return conn } func (cm *ConnectionMgr) Clean() { cm.mux.Lock() for _, conn := range cm.conns { if conn == nil { continue } conn.Close() delete(cm.conns, conn.GetId()) } cm.mux.Unlock() }
Python
UTF-8
4,622
2.890625
3
[ "MIT" ]
permissive
# -*-coding:utf-8-*- import sklearn from sklearn import datasets from sklearn.linear_model import LinearRegression from sklearn.linear_model import LogisticRegression from xgboost.sklearn import XGBClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import train_test_split, cross_val_score from sklearn import svm import numpy as np import warnings def feature_normalize(data): mu = np.mean(data, axis=0) sigma = np.std(data, axis=0, ddof=1) return np.nan_to_num((data - mu) / sigma) def get_features(selected_data): s = sum(selected_data) x = np.empty(shape=[0, s], dtype=np.float64) y = np.empty(shape=[0], dtype=np.float64) with open("../dataset/features.txt", encoding="utf-8") as f: for line in f: content = line.strip().split('\t') vec = np.array([[float(content[x]) for x in range(len(content)) if selected_data[x] == 1]], dtype=np.float64) x = np.append(x, vec, axis=0) y = np.append(y, float(content[-1])) f.close() return x, y def get_feature_matrix(): n_year = 52 x = np.empty(shape=[0, n_year * 5], dtype=np.float64) y = np.empty(shape=[0], dtype=np.float64) with open("../dataset/features_matrix.txt", encoding="utf-8") as f: cnt = 0 vec = np.zeros((1, n_year * 5), dtype=np.float64) for line in f: content = line.strip().split('\t') cnt += 1 if cnt == 1: pass elif cnt < 6: for i in range(n_year): vec[0][i + (cnt - 2) * n_year] = float(content[i]) elif cnt == 6: for i in range(n_year): vec[0][i + (cnt - 2) * n_year] = float(content[i]) x = np.append(x, vec, axis=0) vec = np.zeros((1, n_year * 5), dtype=np.float64) elif cnt == 7: y = np.append(y, float(content[-1])) cnt = 0 f.close() return x, y if __name__ == "__main__": warnings.filterwarnings("ignore") select_feature = [0, 0, 1, # 题目相似度 0, # 学术年龄之差 1, # n1文章数 1, # n2文章数 1, # 文章总数与n1文章数比值 1, # 文章总数与n2文章数比值 0, # 合作次数 0, # 合作时间 1, # 合作论文数与n1论文数比值 1, # 合作论文数与n2论文数比值 1, # 合作之前n1论文数 1, # 合作之前n2论文数 0, # kulc 0, # ir 0] #x, y = get_feature_matrix() #print(x.shape) x, y = get_features(select_feature) x = feature_normalize(x) x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.1) times = 1 # Logistic Regression model_LR = LogisticRegression() model_LR.fit(x_train, y_train) score_LR = 0 for time in range(times): score_LR += cross_val_score(model_LR, x_test, y_test, cv=10, scoring='accuracy').mean() print("The score of Logistic Regression is : ", score_LR / times) # SVM kernel = 'rbf' clf_rbf = svm.SVC(kernel='rbf') clf_rbf.fit(x_train, y_train) score_rbf = 0 for time in range(times): score_rbf += cross_val_score(clf_rbf, x_test, y_test, cv=10, scoring='accuracy').mean() print("The score of SVM rbf is : ", score_rbf / times) # SVM kernel = 'linear' clf_linear = svm.SVC(kernel='linear') clf_linear.fit(x_train, y_train) score_linear = 0 for time in range(times): score_linear += cross_val_score(clf_linear, x_test, y_test, cv=10, scoring='accuracy').mean() print("The score of SVM linear is : ", score_linear / times) # XGBoost model_xgboost = XGBClassifier() model_xgboost.fit(x_train, y_train) score_xgboost = 0 for time in range(times): score_xgboost += cross_val_score(model_xgboost, x_test, y_test, cv=10, scoring='accuracy').mean() print("The score of XGBoost is : ", score_xgboost / times) # Random Forest model_RF = RandomForestClassifier() model_RF.fit(x_train, y_train) score_RF = 0 for time in range(times): score_RF += cross_val_score(model_RF, x_test, y_test, cv=10, scoring='accuracy').mean() print("The score of Random Forest is : ", score_RF / times)
Ruby
UTF-8
629
3.953125
4
[]
no_license
def bucket_sort(array, range_low, range_high) bucket = {} (range_low..range_high).each do |value| bucket[value] = [] end array.each do |item| if item.value < range_low || item.value > range_high raise "out of bound value #{item.value}" end bucket[item.value] << item end result = [] (range_low..range_high).each do |value| result += bucket[value] end result end class Item attr_accessor :value def initialize(value) @value = value end end puts bucket_sort([ Item.new(0), Item.new(24), Item.new(255), Item.new(32), Item.new(44) ], 0, 255).map(&:value).join(" ")
Java
UTF-8
460
1.679688
2
[]
no_license
/** * * @author Ali Karimizandi * @since 2009 * */ package org.zcoreframework.base.method; import org.zcoreframework.base.core.Executor; import org.zcoreframework.base.log.LogMock.Type; @FunctionalInterface public interface MethodExecutor { Executor getExecutor() throws Exception; default Executor getLogger(String result, Type type) throws Exception { return null; } default Class<? extends Throwable>[] noRollbackFor() { return null; }; }
Python
UTF-8
197
3.4375
3
[]
no_license
a=float(input("pehla number: ")) b=float(input('d\'usra number:')) sum1=a+b print('sum: ' + str(sum1)) if sum1!=a+b: print("something's wrong") elif sum1==a+b: print("nothing to see here")
C#
UTF-8
1,849
3.5
4
[]
no_license
namespace PPP { using System; using System.Diagnostics; static class Utils { private static long ciclesPerSecond = 127659000; /// <summary> /// Simulates som CPU Intensive work ad displays a message on the screen /// </summary> /// <param name="work">What to say to the user</param> /// <param name="seconds">How many "fake" seconds it takes.</param> internal static void DoWork(string work, int seconds) { Console.WriteLine("Let's {0} for {1} seconds.", work, seconds); SpinningArround(seconds); Console.WriteLine("We are done with {0}.", work); } /// <summary> /// Sets the maximum nuber of processors to be used by this application. /// </summary> /// <param name="procs"></param> internal static void SetNumberOfProcessors(int procs) { int value = (int)Math.Pow(2, procs) - 1; Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(value); } /// <summary> /// Let's see how many cycles we get in on second /// </summary> internal static void Calibrate() { Stopwatch sw = Stopwatch.StartNew(); SpinningArround(1); sw.Stop(); ciclesPerSecond /= (int)sw.ElapsedMilliseconds; } /// <summary> /// Simulates CPU intensive work. /// </summary> /// <param name="seconds">The number of seconds</param> /// <returns></returns> private static int SpinningArround(int seconds) { int dummyVar = 0; for (long i = 0; i < ciclesPerSecond * seconds; i++) { dummyVar += (int)i % 5; } return dummyVar; } } }
Markdown
UTF-8
2,982
3.015625
3
[ "MIT" ]
permissive
# Words Finder Script for static code analysis. Search for different parts of speech in function names, class or variable names in .py files. In this version or script you can search for verbs (base form take) and nouns (singular). You can search in multiple local directories and git repositories (script downloads them into /repo folder). You can get reports to console, csv or json files. ## Getting Started To clone this script using pip: ```commandline $ pip install git+https://github.com/ravique/otus-homework1.git ``` If you have just downloaded script as [script-archive](https://github.com/ravique/otus-homework1/archive/master.zip), unzip it into any folder. Install requirements: ```commandline $ pip install -r requirements.txt ``` ### Installing After script installation, you need to install NLTK model: In Python console: ```python >> nltk.download('averaged_perceptron_tagger') ``` ## How to use ```commandline usage: words_finder.py [-h] [--dirs [FOLDERS [FOLDERS ...]]] [--git [REPOSITORIES [REPOSITORIES ...]]] [-T MAX_TOP] [-WT [WORD_TYPES [WORD_TYPES ...]]] [-RT REPORT_TYPE] [-O [OBJECTS [OBJECTS ...]]] Analyses usage of words in functions, classes or variables names optional arguments: -h, --help show this help message and exit --dirs [FOLDERS [FOLDERS ...]] Folders in quotes for analysis, split by space. Default: None. Example: --dirs "C:\Python36\Lib\email" "C:\Python36\Lib\logging" --git [REPOSITORIES [REPOSITORIES ...]] Git repo .git urls in quotes for analysis, split by space. Default: None. Example: --git "https://github.com/nickname/repo1" "https://github.com/nickname/repo2" -T MAX_TOP, --top MAX_TOP Count of top of words (by every type). Default: 10. Example: -T 20 -WT [WORD_TYPES [WORD_TYPES ...]], --word_types [WORD_TYPES [WORD_TYPES ...]] Word types for analysis, split by space. VB = verb, NN = noun. Default: NN. Example: -WT VB NN -RT REPORT_TYPE, --report_type REPORT_TYPE Type of the report: console, json, csv. Default=console. Example: -RT json -O [OBJECTS [OBJECTS ...]], --objects [OBJECTS [OBJECTS ...]] Оbjects for search, split by space: functions, classes, variables. Default: functions. Example: -O functions classes ``` ### Important Always wrap in quotes local paths (--dirs args) and git urls (--git args). ## Authors * **Andrei Etmanov** - *Student of OTUS :)* ## License This project is licensed under the MIT License – see the [LICENSE.md](LICENSE.md) file for details
C#
UTF-8
870
3.1875
3
[]
no_license
namespace EventsAndDelegates { class Program { static void Main(string[] args) { var video = new Video() {Title = "Video 1"}; var videoEncoder = new VideoEncoder(); // Publisher var mailService = new MailService(); //subscriber //Before we call the Encode method we needed to do subscription (21. satır) videoEncoder.VideoEncoded += mailService.OnVideoEncoded; // Starts with a publisher.Event and (+=) is for register publishermethod in MailService to Event in Publisher class var messageService = new MessageService(); // subscriber videoEncoder.VideoEncoded += messageService.OnVideoEncoded; // method çağırmıyorum, referans ekliyorum o yüzden "()" kullanılmıyor sadece isim yazılıyor videoEncoder.Encode(video); } } }
Java
UTF-8
501
1.78125
2
[]
no_license
package cn.hopever.platform.crm.repository; import cn.hopever.platform.crm.domain.ProductTable; import cn.hopever.platform.utils.web.GenericRepository; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.util.Map; /** * Created by Donghui Huo on 2016/8/30. */ public interface CustomProductTableRepository extends GenericRepository<ProductTable> { public Page<ProductTable> findByFilters(Map<String, Object> mapFilter, Pageable pageable); }
PHP
UTF-8
3,079
2.609375
3
[]
no_license
<?php error_reporting(1000); // project starter require_once('starter.php'); // defining post process function function postProcessFunction($row){ // add grid table to actions buttons // this column defined as "action" field in fields array $row['tweet_url'] = '<a href="../stats/'. $row['id'] .'">info</a> | <a href="'. $row['tweet_url'] .'">view</a>'; $row['id'] = '<a href="stats/'. $row['id'] .'" class="info" title="Campaign Info">'. $row['id'] .'</a>'; $row['timestamp'] = date("m/d/Y", strtotime($row['timestamp'])); $row['email'] = '<a href="mailto:'. $row['email'] .'">'. $row['email'] .'</a>'; $row['ref'] = '<a href="'. $row['ref'] .'">'. $row['ref'] .'</a>'; // return new row content return $row; } // building our grid $gridHTML = grid(array( 'table' => 'tpv_campaigns', 'fields' => array( /* field | name | width | sortable | searchable | database -----------+--------------------+--------+-----------+--------------+--------------- defaults: | 100px | true | false | true -----------+--------------------+--------+-----------+--------------+-------------*/ 'id' => array('#', 30, true, true), 'timestamp' => array('Date', 90, true, true), 'email' => array('Email', 130, true, true), 'tweet_text' => array('Tweet', 300, true, true), 'visits' => array('Visits', 30, true, true), 'views' => array('Views', 30, true, true), 'ref' => array('Refering Site', 180, true, true), 'tweet_url' => array('Actions', 70, false, false), ), 'order' => 'id', // default order (should be one of your field name) 'sort' => 'desc', // order direction (should be `asc` or `desc`) 'where' => 'id not like 0', // filter (this filter will be applied always) 'do' => 'postProcessFunction', // post processor for every row 'limit' => 20, 'searchable' => true )); ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>Grid Example</title> <link rel="stylesheet" type="text/css" media="screen" href="style.css"> <link rel="stylesheet" type="text/css" media="screen" href="grid.css"> <style type="text/css" media="screen"> body { padding: 20px; margin: 0; font: 12px "Lucida Grande", Lucida, Verdana, sans-serif; } /* grid content specific styles */ .cell.col_oturum, .cell.col_ip, .cell.col_zaman { font-size: 0.8em; } .col_zaman { text-align: center; } .cell.col_actions { font-size: 0.9em; } .cell.col_actions a.del { color: red; } </style> </head> <body> <div class="content"> <h1>Data Grid</h1> <?php print $gridHTML; ?> </div> </body> </html>
C++
UTF-8
4,152
3.484375
3
[]
no_license
#include "CFL.h" /** * Check whether two rectangles with the specified dimensions * intersect. * * @param x1 The horizontal location of the first rectangle. * @param y1 The vertical location of the first rectangle. * @param width1 The width of the first rectangle. * @param height1 The height of the first rectangle. * @param x2 The horizontal location of the second rectangle. * @param y2 The vertical location of the second rectangle. * @param width2 The width of the second rectangle. * @param height2 The height of the second rectangle. * @return Whether or not the two rectangles intersect. */ bool Intersects::rectanglesi(int x1, int y1, int width1, int height1, int x2, int y2, int width2, int height2) { if (width2 <= 0 || height2 <= 0 || width1 <= 0 || height1 <= 0) { return false; } width2 += x2; height2 += y2; width1 += x1; height1 += y1; return ((width2 < x2 || width2 > x1) && (height2 < y2 || height2 > y1) && (width1 < x1 || width1 > x2) && (height1 < y1 || height1 > y2)); } /** * Check whether two rectangles with the specified dimensions * intersect. * * @param x1 The horizontal location of the first rectangle. * @param y1 The vertical location of the first rectangle. * @param width1 The width of the first rectangle. * @param height1 The height of the first rectangle. * @param x2 The horizontal location of the second rectangle. * @param y2 The vertical location of the second rectangle. * @param width2 The width of the second rectangle. * @param height2 The height of the second rectangle. * @return Whether or not the two rectangles intersect. */ bool Intersects::rectanglesl(long x1, long y1, long width1, long height1, long x2, long y2, long width2, long height2) { if (width2 <= 0 || height2 <= 0 || width1 <= 0 || height1 <= 0) { return false; } width2 += x2; height2 += y2; width1 += x1; height1 += y1; return ((width2 < x2 || width2 > x1) && (height2 < y2 || height2 > y1) && (width1 < x1 || width1 > x2) && (height1 < y1 || height1 > y2)); } /** * Check whether two rectangles with the specified dimensions * intersect. * * @param x1 The horizontal location of the first rectangle. * @param y1 The vertical location of the first rectangle. * @param width1 The width of the first rectangle. * @param height1 The height of the first rectangle. * @param x2 The horizontal location of the second rectangle. * @param y2 The vertical location of the second rectangle. * @param width2 The width of the second rectangle. * @param height2 The height of the second rectangle. * @return Whether or not the two rectangles intersect. */ bool Intersects::rectanglesf(float x1, float y1, float width1, float height1, float x2, float y2, float width2, float height2) { if (width2 <= 0 || height2 <= 0 || width1 <= 0 || height1 <= 0) { return false; } width2 += x2; height2 += y2; width1 += x1; height1 += y1; return ((width2 < x2 || width2 > x1) && (height2 < y2 || height2 > y1) && (width1 < x1 || width1 > x2) && (height1 < y1 || height1 > y2)); } /** * Check whether two rectangles with the specified dimensions * intersect. * * @param x1 The horizontal location of the first rectangle. * @param y1 The vertical location of the first rectangle. * @param width1 The width of the first rectangle. * @param height1 The height of the first rectangle. * @param x2 The horizontal location of the second rectangle. * @param y2 The vertical location of the second rectangle. * @param width2 The width of the second rectangle. * @param height2 The height of the second rectangle. * @return Whether or not the two rectangles intersect. */ bool Intersects::rectanglesd(double x1, double y1, double width1, double height1, double x2, double y2, double width2, double height2) { if (width2 <= 0 || height2 <= 0 || width1 <= 0 || height1 <= 0) { return false; } width2 += x2; height2 += y2; width1 += x1; height1 += y1; return ((width2 < x2 || width2 > x1) && (height2 < y2 || height2 > y1) && (width1 < x1 || width1 > x2) && (height1 < y1 || height1 > y2)); }
Markdown
UTF-8
378
2.703125
3
[]
no_license
<h1>Class Scraper</h1> This is a tool to scrape the registrar pages of UCLA. With the information, students will be able to answer many questions, from "Is this professor a good enough lecturer to retain students?" to "Should I sign up for this class on my first of second pass?"<br> The information will be displayed on a webpage (not yet included).<br> Requires MySQL to run.
PHP
UTF-8
19,594
2.53125
3
[]
no_license
<?php if (!defined('BASE_PATH')) exit('Access Denied!'); /** * * Gou_Service_ScoreLog * @author terry * */ class Gou_Service_ScoreLog extends Common_Service_Base{ private static $score_summary = array( 'uid' => '', 'sum_score' => 0, 'sum_sign' => 0, 'sum_cut' => 0, 'sum_scut' => 0, 'sum_fcut' => 0, 'sum_runon' => 0, 'sign_date' => 0, 'look_task_date' => 0, ); /** * @description 积分列表 * @param int $page current page * @param int $limit page size * @param array $params conditions * @param array $orderBy order by index string * @return array */ public static function getList($page = 1, $limit = 10, $params = array(), $orderBy = array()) { $params = self::_cookData($params); if ($page < 1) $page = 1; $start = ($page - 1) * $limit; $ret = self::_getDao()->getList($start, $limit, $params, $orderBy); $total = self::_getDao()->count($params); return array($total, $ret); } /** * @function get * @description 根据id获取单条记录 * * @param integer $id input id * @return array */ public static function get($id) { if (!intval($id)) return false; return self::_getDao()->get(intval($id)); } /** * get user score info by uid * @param array $params * @param array $orderBy * @return boolean|mixed */ public static function getBy($params, $orderBy = array()) { if(!is_array($params)) return false; $data = self::_cookData($params); return self::_getDao()->getBy($data, $orderBy); } /** * get user score info list by uid * @param array $params * @param array $orderBy * @return boolean|mixed */ public static function getsBy($params, $orderBy = array()) { if(!is_array($params)) return false; $data = self::_cookData($params); return self::_getDao()->getsBy($data, $orderBy); } /** * @description 添加记录 * * @param array $data data will created * @return boolean */ public static function add($data){ if(!is_array($data)) return false; $data = self::_cookData($data); return self::_getDao()->insert($data); } /** * * @param $params * @return bool|string */ public static function count($params){ if(!is_array($params)) return false; $params = self::_cookData($params); return self::_getDao()->count($params); } /** * @description 添加每日积分任务 * @param $data * @return bool|int */ public static function addTask($data){ if (!is_array($data)) return false; $data = self::_cookDataTask($data); return self::_getDaoTask()->insert($data); } /** * @description 更新每日积分任务 * * @param array $params * @param array $step * @return bool|int */ public static function updateTask($params, $step){ if (!is_array($params)) return false; $params = self::_cookDataTask($params); return self::_getDaoTask()->increment('count', $params, $step); } /** * @description 获取每日某个积分任务 * @param $params * @return bool|array */ public static function getTask($params){ if (!is_array($params)) return false; $params = self::_cookDataTask($params); return self::_getDaoTask()->getBy($params); } /** * @description 获取每日所有积分任务 * @param $params * @return bool|array */ public static function getTasks($params){ if (!is_array($params)) return false; $params = self::_cookDataTask($params); return self::_getDaoTask()->getsBy($params); } /** * 会员积分处理适配器, 仅适配积分类型的一级类型 * @param int $id 积分类型ID * @param string $uid 会员UID * @param string $now_time 日期 * @return bool */ public static function score($id = '', $uid = '', $now_time = ''){ list($score_onoff, $score_date) = self::scoreAvailable(); $score_type = Common::resetKey(Common::getConfig('scoreConfig'), 'id'); if($score_onoff && $score_date && $uid && is_int($id) && array_key_exists($id, $score_type)){ $now_time = $now_time?strtotime($now_time):Common::getTime(); $adapter = 'adapter'.ucfirst($score_type[$id]['adapter']); if(method_exists(__CLASS__, $adapter)){ return self::$adapter($score_type[$id], $uid, $now_time); } } return false; } /** * 处理积分日志和积分任务 * @param $config * @param $uid * @param $now_time * @return bool 判断每日积分任务是否超过, 超过返回 false */ private static function scoreLogAndTask($config, $uid, $now_time){ //获取积分任务信息 $task = self::getTask(array( 'uid' => $uid, 'type_id' => $config['id'], 'date' => date('Y-m-d', $now_time))); if($task){ if($task['count'] < $config['limit']){ //添加积分日志 self::add(array( 'uid' => $uid, 'date' => date('Y-m-d', $now_time), 'create_time' => $now_time, 'score' => $config['score'], 'type_id' => $config['id'])); //更新每日任务 self::updateTask(array( 'uid' => $uid, 'date' => date('Y-m-d', $now_time), 'type_id' => $config['id']), 1); return true; } }else{ //添加积分日志 self::add(array( 'uid' => $uid, 'date' => date('Y-m-d', $now_time), 'create_time' => $now_time, 'score' => $config['score'], 'type_id' => $config['id'])); //添加每日任务 self::addTask(array( 'uid' => $uid, 'date' => date('Y-m-d', $now_time), 'type_id' => $config['id'], 'count' => 1)); return true; } return false; } /** * 处理积分累计日志, 并返回所获积分 * @param $config * @param $uid * @param $now_time * @param $count 累计次数 * @return int|bool 返回获取分数 */ private static function scoreUpto($config, $uid, $now_time, $count){ if(isset($config['upto'])){ foreach($config['upto'] as $item){ if($count !=0 && intval($count)%$item['total'] == 0){ //如果达到累计规则, 添加积分日志 self::add(array( 'uid' => $uid, 'date' => date('Y-m-d', $now_time), 'create_time' => $now_time, 'score' => $item['score'], 'type_id' => $item['id'])); //添加累计任务 self::addTask(array( 'uid' => $uid, 'date' => date('Y-m-d', $now_time), 'type_id' => $item['id'], 'count' => 1)); //返回增加的累计分 return $item['score']; } } } return false; } /** * 处理积分连续日志, 并返回所获积分 * @param $config * @param $uid * @param $now_time * @return int|bool 返回获取分数 */ private static function scoreRunon($config, $uid, $now_time, $runon){ if(isset($config['runon'])) { foreach ($config['runon'] as $item) { if ($item['total'] === $runon) { //如果达到累计规则, 添加积分日志 self::add(array( 'uid' => $uid, 'date' => date('Y-m-d', $now_time), 'create_time' => $now_time, 'score' => $item['score'], 'type_id' => $item['id'])); //添加累计任务 self::addTask(array( 'uid' => $uid, 'date' => date('Y-m-d', $now_time), 'type_id' => $item['id'], 'count' => 1)); //返回增加的累计分 return $item['score']; } } } return false; } /** * 每日签到 * @param array $config * @param string $uid * @param string $now_time * @return bool */ private static function adapterMrqd($config, $uid, $now_time){ try { parent::beginTransaction(); //处理积分日志和积分任务 if(self::scoreLogAndTask($config, $uid, $now_time)){ self::$score_summary['uid'] = $uid; $sum = Gou_Service_ScoreSummary::getBy(array('uid'=>$uid)); if(!$sum) $sum = array(); $sum = array_merge(self::$score_summary, $sum); $sum['sum_sign']++; $sum['sum_score'] += $config['score']; //处理积分累计日志 $score_upto = self::scoreUpto($config, $uid, $now_time, $sum['sum_sign']); $sum['sum_score'] += intval($score_upto); $yesterday = date('Y-m-d', $now_time-3600*24); if($sum['sign_date'] == 0 || ($sum['sign_date'] && $sum['sign_date'] == $yesterday)) $sum['sum_runon']++; //处理积分连续日志 $score_runon = self::scoreRunon($config, $uid, $now_time, $sum['sum_runon']); if($score_runon !== false){ $sum['sum_runon'] = 0; $sum['sum_score'] += intval($score_runon); } $sum['sign_date'] = date('Y-m-d', $now_time); //更新积分总计 Gou_Service_ScoreSummary::replace($sum); }else{ return false; } return parent::commit(); } catch (Exception $e) { parent::rollBack(); } } /** * 每日砍价 * @param array $config * @param string $uid * @param string $now_time * @return bool */ private static function adapterMrkj($config, $uid, $now_time){ try { parent::beginTransaction(); //处理积分日志和积分任务 if(self::scoreLogAndTask($config, $uid, $now_time)){ self::$score_summary['uid'] = $uid; $sum = Gou_Service_ScoreSummary::getBy(array('uid'=>$uid)); if(!$sum) $sum = array(); $sum = array_merge(self::$score_summary, $sum); $sum['sum_cut']++; $sum['sum_score'] += $config['score']; //处理积分累计日志 $score_upto = self::scoreUpto($config, $uid, $now_time, $sum['sum_cut']); $sum['sum_score'] += $score_upto; //更新积分总计 Gou_Service_ScoreSummary::replace($sum); }else{ return 0; } return parent::commit(); } catch (Exception $e) { parent::rollBack(); } } /** * 每日分享砍价 * @param array $config * @param string $uid * @param string $now_time * @return bool */ private static function adapterMrfxkj($config, $uid, $now_time){ try { parent::beginTransaction(); //处理积分日志和积分任务 if(self::scoreLogAndTask($config, $uid, $now_time)){ self::$score_summary['uid'] = $uid; $sum = Gou_Service_ScoreSummary::getBy(array('uid'=>$uid)); if(!$sum) $sum = array(); $sum = array_merge(self::$score_summary, $sum); $sum['sum_scut']++; $sum['sum_score'] += $config['score']; //处理积分累计日志 $score_upto = self::scoreUpto($config, $uid, $now_time, $sum['sum_scut']); $sum['sum_score'] += $score_upto; //更新积分总计 Gou_Service_ScoreSummary::replace($sum); }else{ return 0; } return parent::commit(); } catch (Exception $e) { parent::rollBack(); } } /** * 每日邀请好友帮忙砍价 * @param array $config * @param string $uid * @param string $now_time * @return bool */ private static function adapterMrhykj($config, $uid, $now_time){ try { parent::beginTransaction(); //处理积分日志和积分任务 if(self::scoreLogAndTask($config, $uid, $now_time)){ self::$score_summary['uid'] = $uid; $sum = Gou_Service_ScoreSummary::getBy(array('uid'=>$uid)); if(!$sum) $sum = array(); $sum = array_merge(self::$score_summary, $sum); $sum['sum_fcut']++; $sum['sum_score'] += $config['score']; //处理积分累计日志 $score_upto = self::scoreUpto($config, $uid, $now_time, $sum['sum_fcut']); $sum['sum_score'] += $score_upto; //更新积分总计 Gou_Service_ScoreSummary::replace($sum); }else{ return 0; } return parent::commit(); } catch (Exception $e) { parent::rollBack(); } } /** * 每日分享购物大厅 * @param array $config * @param string $uid * @param string $now_time * @return bool */ private static function adapterMrfxgwdt($config, $uid, $now_time){ try { parent::beginTransaction(); //处理积分日志和积分任务 if(self::scoreLogAndTask($config, $uid, $now_time)){ self::$score_summary['uid'] = $uid; $sum = Gou_Service_ScoreSummary::getBy(array('uid'=>$uid)); if(!$sum) $sum = array(); $sum = array_merge(self::$score_summary, $sum); $sum['sum_score'] += $config['score']; //更新积分总计 Gou_Service_ScoreSummary::replace($sum); }else{ return 0; } return parent::commit(); } catch (Exception $e) { parent::rollBack(); } } /** * 每日分享购物大厅链接 * @param array $config * @param string $uid * @param string $now_time * @return bool */ private static function adapterMrfxlj($config, $uid, $now_time){ try { parent::beginTransaction(); //处理积分日志和积分任务 if(self::scoreLogAndTask($config, $uid, $now_time)){ self::$score_summary['uid'] = $uid; $sum = Gou_Service_ScoreSummary::getBy(array('uid'=>$uid)); if(!$sum) $sum = array(); $sum = array_merge(self::$score_summary, $sum); $sum['sum_score'] += $config['score']; //更新积分总计 Gou_Service_ScoreSummary::replace($sum); }else{ return 0; } return parent::commit(); } catch (Exception $e) { parent::rollBack(); } } /** * 关注购物大厅微信 * @param array $config * @param string $uid * @param string $now_time * @return bool */ private static function adapterGzwx($config, $uid, $now_time){ try { parent::beginTransaction(); //处理积分日志和积分任务 if(self::scoreLogAndTask($config, $uid, $now_time)){ self::$score_summary['uid'] = $uid; $sum = Gou_Service_ScoreSummary::getBy(array('uid'=>$uid)); if(!$sum) $sum = array(); $sum = array_merge(self::$score_summary, $sum); $sum['sum_score'] += $config['score']; //更新积分总计 Gou_Service_ScoreSummary::replace($sum); }else{ return 0; } return parent::commit(); } catch (Exception $e) { parent::rollBack(); } } /** * 判断积分活动是否可用 * @return array * $score_onoff 积分系统开关 * $score_date 积分系统有效期 */ public static function scoreAvailable(){ //积分系统开关 $score_onoff = (bool)Gou_Service_Config::getValue('gou_score'); //积分开始和结束日期, 判断是否在有效期内 $score_sdate = strtotime(Gou_Service_Config::getValue('gou_score_sdate')); $score_edate = strtotime(Gou_Service_Config::getValue('gou_score_edate')); $today = Common::getTime(); $score_date = false; if($today >= $score_sdate && $today <= $score_edate) $score_date = true; return list($score_onoff, $score_date) = array($score_onoff, $score_date); } /** * 获取积分规则类型 * @return array */ public static function scoreType(){ $score_type = array(); foreach(Common::getConfig('scoreConfig') as $item){ $score_type[] = $item; if(isset($item['upto'])) $score_type[] = $item['upto'][0]; if(isset($item['runon'])) $score_type[] = $item['runon'][0]; } return Common::resetKey($score_type, 'id'); } /** * gou_score_log 参数过滤 * * @param array $data * @return array */ private static function _cookData($data) { $tmp = array(); if(isset($data['uid'])) $tmp['uid'] = $data['uid']; if(isset($data['date'])) $tmp['date'] = $data['date']; if(isset($data['create_time'])) $tmp['create_time'] = $data['create_time']; if(isset($data['score'])) $tmp['score'] = $data['score']; if(isset($data['type_id'])) $tmp['type_id'] = intval($data['type_id']); return $tmp; } /** * * @return Gou_Dao_ScoreLog */ private static function _getDao() { return Common::getDao("Gou_Dao_ScoreLog"); } /** * gou_score_task 参数过滤 * * @param array $data * @return array */ private static function _cookDataTask($data) { $tmp = array(); if(isset($data['uid'])) $tmp['uid'] = $data['uid']; if(isset($data['date'])) $tmp['date'] = $data['date']; if(isset($data['type_id'])) $tmp['type_id'] = intval($data['type_id']); if(isset($data['count'])) $tmp['count'] = intval($data['count']); return $tmp; } /** * @return Gou_Dao_ScoreTask */ private static function _getDaoTask(){ return Common::getDao("Gou_Dao_ScoreTask"); } }
Java
UTF-8
4,500
2.3125
2
[]
no_license
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * ******************************************************************/ package org.aspectj.bridge; import org.aspectj.util.LangUtil; import java.io.File; /** * Immutable source location. * This guarantees that the source file is not null * and that the numeric values are positive and line <= endLine. * @see org.aspectj.lang.reflect.SourceLocation * @see org.aspectj.compiler.base.parser.SourceInfo * @see org.aspectj.tools.ide.SourceLine * @see org.aspectj.testing.harness.ErrorLine */ public class SourceLocation implements ISourceLocation, java.io.Serializable { /** used when SourceLocation is not available */ public static final ISourceLocation UNKNOWN = new SourceLocation(ISourceLocation.NO_FILE, 0, 0, 0); /** @throws IllegalArgumentException if the input would not be a valid line */ public static final void validLine(int line) { if (line < 0) { throw new IllegalArgumentException("negative line: " + line); } else if (line > ISourceLocation.MAX_LINE) { throw new IllegalArgumentException("line too large: " + line); } } /** @throws IllegalArgumentException if the input would not be a valid column */ public static final void validColumn(int column) { if (column < 0) { throw new IllegalArgumentException("negative column: " + column); } else if (column > ISourceLocation.MAX_COLUMN) { throw new IllegalArgumentException("column too large: " + column); } } private final File sourceFile; private final int line; private final int column; private final int endLine; private boolean noColumn; /** * Same as SourceLocation(file, line, line, 0), * except that column is not rendered during toString() */ public SourceLocation(File file, int line) { this(file, line, line, NO_COLUMN); } /** same as SourceLocation(file, line, endLine, ISourceLocation.NO_COLUMN) */ public SourceLocation(File file, int line, int endLine) { this(file, line, endLine, ISourceLocation.NO_COLUMN); } /** * @param file File of the source; if null, use ISourceLocation.NO_FILE, not null * @param line int starting line of the location - positive number * @param endLine int ending line of the location - <= starting line * @param column int character position of starting location - positive number */ public SourceLocation(File file, int line, int endLine, int column) { if (column == NO_COLUMN) { column = 0; noColumn = true; } if (null == file) { file = ISourceLocation.NO_FILE; } validLine(line); validLine(endLine); LangUtil.throwIaxIfFalse(line <= endLine , line + " > " + endLine); LangUtil.throwIaxIfFalse(column >= 0, "negative column: " + column); this.sourceFile = file; this.line = line; this.column = column; this.endLine = endLine; } public File getSourceFile() { return sourceFile; } public int getLine() { return line; } /** * @return int actual column or 0 if not available per constructor treatment * of ISourceLocation.NO_COLUMN */ public int getColumn() { return column; } public int getEndLine() { return line; } /** @return String {file:}line{:column} */ public String toString() { StringBuffer sb = new StringBuffer(); if (sourceFile != ISourceLocation.NO_FILE) { sb.append(sourceFile.getPath()); sb.append(":"); } sb.append("" + line); if (!noColumn) { sb.append(":" + column); } return sb.toString(); } }
C++
UTF-8
1,420
2.765625
3
[ "MIT" ]
permissive
/* * MIT License * Copyright (c) 2021 Anton Sundqvist */ #ifndef GD_AUTOCAL_H #define GD_AUTOCAL_H #include <arduino.h> #define VECTOR_DIM 3 class MAGAC{ private: const float learningRate = 0.002; //Learning rate float m[VECTOR_DIM]; //Magnetic north vector float a[VECTOR_DIM]; //Bias distortion of the sensor float b[VECTOR_DIM]; //Offset of sensor reading from origo float xInvNorm = 1.0; //Normalization factor, measured on first iteration bool firstIteration = true; short learn(float* rawData); short predict(float* rawData); float calcNorm(float* vec); public: MAGAC(); short begin(); short autoCal(float* data); //High level function which updates and overwrites the input with the corrected data short update(float* rawData); //Calculate the correction and adjust the learned distortions. Input data is not overwritten short read(float* mOut); //Writes the current estimate of the m-vector to mOut. Requires that the update method has been called prior to calling. short setBias(float* aNew); //Used to initialize the bias factors short setOffset(float* bNew); //Used to initialize the offset terms short getBias(float* aOut); //Getter method for bias. short getOffset(float* bOut); //Getter method for offset. }; #endif
Python
UTF-8
2,646
3.125
3
[]
no_license
'''class shifu(object): def __init__(self): self.hui = '煎饼果子配方' def zuo(self): print(f'我会用{self.hui}做煎饼果子') class tudi(shifu): pass aa = tudi() aa.zuo() ''' '''class shifu(object): def __init__(self): self.gongfu = '麻辣' self.__qian = 200 def make(self): print(f'我会用{self.gongfu}做,我有{self.qian}') def get_money(self): return self.__qian def set_money(self): self.__qian = 500 class tudi(shifu): pass a = tudi() print(a.get_money()) a.set_money() print(a.get_money())''' '''class Master(object): def __init__(self): self.kongfu = '[五香]' def make_cake(self): print(f'用{self.kongfu}做煎饼果子') class School(object): def __init__(self): self.kongfu = '[香辣]' def make_cake(self): print(f'用{self.kongfu}做煎饼果子') class Prentice(Master, School, ): def __init__(self): self.kongfu = '自己创造的麻辣' def make_cake(self): self.__init__() print(f'我会用{self.kongfu}做煎饼果子') def make_old_cake(self): super().__init__() super().make_cake() aa = Prentice() aa.make_cake() aa.make_old_cake()''' # class dog(): # def word(self): # print('指哪打哪') # class jdog(): # def word(self): # print('追击绑匪') # class ddog(): # def word(self): # print('追击毒贩') # class persen(): # def witha(self,dog): # dog.word() # a = jdog() # b = ddog() # c = dog() # d = persen() # d.witha(a) # d.witha(b) # d.witha(c) '''class dog(): gao = 10 b = dog() c = dog() print(b.gao) print(c.gao) dog.gao = 20 print(b.gao) print(c.gao)''' #2-http协议的组成,状态码含义; '''常见的200 请求成功,但是不一定功能成功, 300 重定向 404 页面不存在 端的问题 500 服务挂了 后端问题 ''' #3-完成手机app抓包 # 已完成,通过同一wifi下,手机设置代理ip信息,下载fiddler或者Charles连接进行抓包 #4-get和post区别 '''get: 不安全,会把用户输入的信息带到url,比如账号密码等私密信息。一般获取列表之类的接口使用get请求 post:安全,不会带用户输入的信息 一般提交用户输入信息的接口使用post请求 ''' #-cookie和session区别 ''' COOKIE: cookie的数据会保存在客户端,而且可以通过f12在cookie存在的容器去篡改cookie的数据 SESSION:session的数据不会保存在客户端而是服务器,如果考虑安全用session,但是性能不如cookie '''
Java
UTF-8
626
1.929688
2
[]
no_license
package ika.test.runningapp.di; import android.content.Context; import dagger.Module; import dagger.Provides; import dagger.hilt.InstallIn; import dagger.hilt.android.qualifiers.ApplicationContext; import dagger.hilt.components.SingletonComponent; import ika.test.runningapp.data.RunDatabase; import ika.test.runningapp.data.Workout; import ika.test.runningapp.data.WorkoutDao; @Module @InstallIn({SingletonComponent.class}) public interface DatabaseModule { @Provides static WorkoutDao provideWorkoutDao(@ApplicationContext Context context){ return RunDatabase.getInstance(context).workoutDao(); } }
Shell
UTF-8
725
3.03125
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env bash echo "Provisioning trivy" apt-get install -y wget apt-transport-https gnupg lsb-release rpm wget -qO - https://aquasecurity.github.io/trivy-repo/deb/public.key | sudo apt-key add - echo deb https://aquasecurity.github.io/trivy-repo/deb $(lsb_release -sc) main | sudo tee -a /etc/apt/sources.list.d/trivy.list apt-get -y update apt-get install -y trivy echo "Provisioning Dockle" VERSION=$( curl --silent "https://api.github.com/repos/goodwithtech/dockle/releases/latest" | \ grep '"tag_name":' | \ sed -E 's/.*"v([^"]+)".*/\1/' \ ) && curl -L -o dockle.deb https://github.com/goodwithtech/dockle/releases/download/v${VERSION}/dockle_${VERSION}_Linux-64bit.deb sudo dpkg -i dockle.deb && rm dockle.deb
Markdown
UTF-8
12,224
3.078125
3
[ "Apache-2.0", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-free-unknown", "MIT", "LicenseRef-scancode-unknown-license-reference", "CC-BY-SA-4.0" ]
permissive
[#]: collector: (lujun9972) [#]: translator: ( ) [#]: reviewer: ( ) [#]: publisher: ( ) [#]: url: ( ) [#]: subject: (Formatting NFL data for doing data science with Python) [#]: via: (https://opensource.com/article/19/10/formatting-nfl-data-python) [#]: author: (Christa Hayes https://opensource.com/users/cdhayes2) Formatting NFL data for doing data science with Python ====== In part 1 of this series on machine learning with Python, learn how to prepare a National Football League dataset for training. ![A football field.][1] No matter what medium of content you consume these days (podcasts, articles, tweets, etc.), you'll probably come across some reference to data. Whether it's to back up a talking point or put a meta-view on how data is everywhere, data and its analysis are in high demand. As a programmer, I've found data science to be more comparable to wizardry than an exact science. I've coveted the ability to get ahold of raw data and glean something useful and concrete from it. What a useful talent! This got me thinking about the difference between data scientists and programmers. Aren't data scientists just statisticians who can code? Look around and you'll see any number of tools aimed at helping developers become data scientists. AWS has a full-on [machine learning course][2] geared specifically towards turning developers into experts. [Visual Studio][3] has built-in Python projects that—with the click of a button—will create an entire template for classification problems. And scores of programmers are writing tools designed to make data science easier for anyone to pick up. I thought I'd lean into the clear message of recruiting programmers to the data (or dark) side and give it a shot with a fun project: training a machine learning model to predict plays using a National Football League (NFL) dataset. ### Set up the environment Before I can dig into the data, I need to set up my [virtual environment][4]. This is important because, without an environment, I'll have nowhere to work. Fortunately, Opensource.com has [some great resources][5] for installing and configuring the setup. Any of the code you see here, I was able to look up through existing documentation. If there is one thing programmers are familiar with, it's navigating foreign (and sometimes very sparse) documentation. ### Get the data As with any modern problem, the first step is to make sure you have quality data. Luckily, I came across a set of [NFL tracking data][6] from 2017 that was used for the NFL Big Data Bowl. Even the NFL is trying its best to attract the brightest stars in the data realm. Everything I need to know about the schema is in the README. This exercise will train a machine learning model to predict run (in which the ball carrier keeps the football and runs downfield) and pass (in which the ball is passed to a receiving player) plays using the plays.csv [data file][7]. I won't use player tracking data in this exercise, but it could be fun to explore later. First things first, I need to get access to my data by importing it into a dataframe. The [Pandas][8] library is an open source Python library that provides algorithms for easy analysis of data structures. The structure in the sample NFL data happens to be a two-dimensional array (or in simpler terms, a table), which data scientists often refer to as a dataframe. The Pandas function dealing with dataframes is [pandas.DataFrame][9]. I'll also import several other libraries that I will use later. ``` import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt import xgboost as xgb from sklearn import metrics df = pd.read_csv('data/plays.csv') print(len(df)) print(df.head()) ``` ### Format the data The NFL data dump does not explicitly indicate which plays are runs (also called rushes) and which are passes. Therefore, I have to classify the offensive play types through some football savvy and reasoning. Right away, I can get rid of special teams plays in the **isSTPLAY** column. Special teams are neither offense nor defense, so they are irrelevant to my objective. ``` #drop st plays df = df[~df['isSTPlay']] print(len(df)) ``` Skimming the **playDescription** column, I see some plays where the quarterback kneels, which effectively ends a play. This is usually called a "victory formation" because the intent is to run out the clock. These are significantly different than normal running plays, so I can drop them as well. ``` #drop kneels df = df[~df['playDescription'].str.contains("kneels")] print (len(df)) ``` The data reports time in terms of the quarters in which a game is normally played (as well as the time on the game clock in each quarter). Is this the most intuitive in terms of trying to predict a sequence? One way to answer this is to consider how gameplay differs between time splits. When a team has the ball with a minute left in the first quarter, will it act the same as if it has the ball with a minute left in the second quarter? Probably not. Will it act the same with a minute to go at the end of both halves? All else remaining equal, the answer is likely yes in most scenarios. I'll convert the **quarter** and **GameClock** columns from quarters to halves, denoted in seconds rather than minutes. I'll also create a **half** column from the **quarter** values. There are some fifth quarter values, which I take to be overtime. Since overtime rules are different than normal gameplay, I can drop them. ``` #drop overtime df = df[~(df['quarter'] == 5)] print(len(df)) #convert time/quarters def translate_game_clock(row):     raw_game_clock = row['GameClock']     quarter = row['quarter']     minutes, seconds_raw = raw_game_clock.partition(':')[::2]     seconds = seconds_raw.partition(':')[0]     total_seconds_left_in_quarter = int(seconds) + (int(minutes) * 60)     if quarter == 3 or quarter == 1:         return total_seconds_left_in_quarter + 900     elif quarter == 4 or quarter == 2:         return total_seconds_left_in_quarter if 'GameClock' in list (df.columns):     df['secondsLeftInHalf'] = df.apply(translate_game_clock, axis=1) if 'quarter' in list(df.columns):     df['half'] = df['quarter'].map(lambda q: 2 if q &gt; 2 else 1) ``` The **yardlineNumber** column also needs to be transformed. The data currently lists the yard line as a value from one to 50. Again, this is unhelpful because a team would not act the same on its own 20-yard line vs. its opponent's 20-yard line. I will convert it to represent a value from one to 99, where the one-yard line is nearest the possession team's endzone, and the 99-yard line is nearest the opponent's end zone. ``` def yards_to_endzone(row):     if row['possessionTeam'] == row['yardlineSide']:         return 100 - row['yardlineNumber']     else :         return row['yardlineNumber'] df['yardsToEndzone'] = df.apply(yards_to_endzone, axis = 1) ``` The personnel data would be extremely useful if I could get it into a format for the machine learning algorithm to take in. Personnel identifies the different types of skill positions on the field at a given time. The string value currently shown in **personnel.offense** is not conducive to input, so I'll convert each personnel position to its own column to indicate the number present on the field during the play. Defense personnel might be interesting to include later to see if it has any outcome on prediction. For now, I'll just stick with offense. ``` def transform_off_personnel(row):    rb_count = 0    te_count = 0    wr_count = 0    ol_count = 0    dl_count = 0    db_count = 0    if not pd.isna(row['personnel.offense']):        personnel = row['personnel.offense'].split(', ')        for p in personnel:            if p[2:4] == 'RB':                rb_count = int(p[0])            elif p[2:4] == 'TE':                 te_count = int(p[0])            elif p[2:4] == 'WR':                 wr_count = int(p[0])            elif p[2:4] == 'OL':                 ol_count = int(p[0])            elif p[2:4] == 'DL':                 dl_count = int(p[0])            elif p[2:4] == 'DB':                db_count = int(p[0])    return pd.Series([rb_count,te_count,wr_count,ol_count,dl_count, db_count]) df[['rb_count','te_count','wr_count','ol_count','dl_count', 'db_count']] = df.apply(transform_off_personnel, axis=1) ``` Now the offense personnel values are represented by individual columns. ![Result of reformatting offense personnel][10] Formations describe how players are positioned on the field, and this is also something that would seemingly have value in predicting play outcomes. Once again, I'll convert the string values into integers. ``` df['offenseFormation'] = df['offenseFormation'].map(lambda f : 'EMPTY' if pd.isna(f) else f) def formation(row):     form = row['offenseFormation'].strip()     if form == 'SHOTGUN':         return 0     elif form == 'SINGLEBACK':         return 1     elif form == 'EMPTY':         return 2     elif form == 'I_FORM':         return 3     elif form == 'PISTOL':         return 4     elif form == 'JUMBO':         return 5     elif form == 'WILDCAT':         return 6     elif form=='ACE':         return 7     else:         return -1 df['numericFormation'] = df.apply(formation, axis=1) print(df.yardlineNumber.unique()) ``` Finally, it's time to classify the play types. The **PassResult** column has four distinct values: I, C, S, and null, which represent Incomplete passing plays, Complete passing plays, Sacks (classified as passing plays), and a null value. Since I've already eliminated all special teams plays, I can assume the null values are running plays. So I'll convert the play outcome into a single column called **play_type** represented by either a 0 for running or a 1 for passing. This will be the column (or _label_, as the data scientists say) I want my algorithm to predict. ``` def play_type(row):     if row['PassResult'] == 'I' or row['PassResult'] == 'C' or row['PassResult'] == 'S':         return 'Passing'     else:         return 'Rushing' df['play_type'] = df.apply(play_type, axis = 1) df['numericPlayType'] = df['play_type'].map(lambda p: 1 if p == 'Passing' else 0) ``` ### Take a break Is it time to start predicting things yet? Most of my work so far has been trying to understand the data and what format it needs to be in—before I even get started on predicting anything. Anyone else need a minute? In part two, I'll do some analysis and visualization of the data before feeding it into a machine learning algorithm, and then I'll score the model's results to see how accurate they are. Stay tuned! -------------------------------------------------------------------------------- via: https://opensource.com/article/19/10/formatting-nfl-data-python 作者:[Christa Hayes][a] 选题:[lujun9972][b] 译者:[译者ID](https://github.com/译者ID) 校对:[校对者ID](https://github.com/校对者ID) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出 [a]: https://opensource.com/users/cdhayes2 [b]: https://github.com/lujun9972 [1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/OSDC_LIFE_football__520x292.png?itok=5hPbxQF8 (A football field.) [2]: https://aws.amazon.com/training/learning-paths/machine-learning/developer/ [3]: https://docs.microsoft.com/en-us/visualstudio/python/overview-of-python-tools-for-visual-studio?view=vs-2019 [4]: https://opensource.com/article/19/9/get-started-data-science-python [5]: https://opensource.com/article/17/10/python-101 [6]: https://github.com/nfl-football-ops/Big-Data-Bowl [7]: https://github.com/nfl-football-ops/Big-Data-Bowl/tree/master/Data [8]: https://pandas.pydata.org/ [9]: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html [10]: https://opensource.com/sites/default/files/uploads/nfl-python-7_personneloffense.png (Result of reformatting offense personnel)
C
UTF-8
764
4
4
[]
no_license
/* ============================================================================ Name : bubble_sort.c Author : jerin jose Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <stdio.h> #include <stdlib.h> int main() { int array[100], n, i, j, swap; printf("Enter number of elements\n"); scanf("%d", &n); printf("Enter %d Numbers\n", n); for(i = 0; i < n; i++) scanf("%d", &array[i]); for(i = 0 ; i < n - 1; i++) { for(j = 0 ; j < n-i-1; j++) { if(array[j] > array[j+1]) { swap=array[j]; array[j]=array[j+1]; array[j+1]=swap; } } } printf("Sorted Array\n"); for(i = 0; i < n; i++) printf("%d\n", array[i]); return 0; }
Java
UTF-8
6,345
2.40625
2
[ "Apache-2.0" ]
permissive
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. Camunda licenses this file to you under the Apache License, * Version 2.0; 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 org.camunda.spin.impl.util; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.Arrays; import org.junit.After; import org.junit.Test; public class RewindableReaderTest { private static final String EXAMPLE_INPUT_STRING = "a long string with content"; private static final int DEFAULT_BUFFER_SIZE = 10; protected RewindableReader reader; @Test public void shouldRead() throws IOException { // read(char[]) reader = newReaderInstance(EXAMPLE_INPUT_STRING, DEFAULT_BUFFER_SIZE); assertThat(reader.getRewindBufferSize()).isEqualTo(DEFAULT_BUFFER_SIZE); assertThat(reader.getCurrentRewindableCapacity()).isEqualTo(DEFAULT_BUFFER_SIZE); char[] buffer = new char[5]; int charactersRead = reader.read(buffer); String bufferAsString = new String(buffer); assertThat(charactersRead).isEqualTo(5); assertThat(reader.getCurrentRewindableCapacity()).isEqualTo(DEFAULT_BUFFER_SIZE - 5); assertThat(bufferAsString).isEqualTo(EXAMPLE_INPUT_STRING.substring(0, 5)); reader.close(); // read(char[], off, len) reader = newReaderInstance(EXAMPLE_INPUT_STRING, DEFAULT_BUFFER_SIZE); buffer = new char[5]; charactersRead = reader.read(buffer, 2, 3); assertThat(charactersRead).isEqualTo(3); assertThat(buffer[0]).isEqualTo((char) 0); assertThat(buffer[1]).isEqualTo((char) 0); bufferAsString = new String(Arrays.copyOfRange(buffer, 2, 4)); assertThat(bufferAsString).isEqualTo(EXAMPLE_INPUT_STRING.substring(0, 2)); // read() reader = newReaderInstance(EXAMPLE_INPUT_STRING, DEFAULT_BUFFER_SIZE); char charRead = (char) reader.read(); assertThat(charRead).isEqualTo('a'); reader.close(); } @Test public void shouldRewind() throws IOException { reader = newReaderInstance(EXAMPLE_INPUT_STRING, DEFAULT_BUFFER_SIZE); char[] buffer = new char[5]; reader.read(buffer); reader.rewind(); assertThat(SpinIoUtil.getStringFromReader(reader)).isEqualTo(EXAMPLE_INPUT_STRING); } @Test public void shouldRewindAfterRepeatedRead() throws IOException { reader = newReaderInstance(EXAMPLE_INPUT_STRING, DEFAULT_BUFFER_SIZE); char[] buffer = new char[5]; reader.read(buffer); reader.read(buffer); reader.rewind(); assertThat(SpinIoUtil.getStringFromReader(reader)).isEqualTo(EXAMPLE_INPUT_STRING); } @Test public void shouldReadAndRewindWhenEndOfInputIsReached() throws IOException { String input = EXAMPLE_INPUT_STRING.substring(0, 5); reader = newReaderInstance(input, DEFAULT_BUFFER_SIZE); char[] buffer = new char[10]; int charactersRead = reader.read(buffer); String bufferAsString = new String(Arrays.copyOfRange(buffer, 0, charactersRead)); assertThat(charactersRead).isEqualTo(5); assertThat(bufferAsString).isEqualTo(input); charactersRead = reader.read(buffer); assertThat(charactersRead).isEqualTo(-1); reader.rewind(); charactersRead = reader.read(buffer); bufferAsString = new String(Arrays.copyOfRange(buffer, 0, charactersRead)); assertThat(charactersRead).isEqualTo(5); assertThat(bufferAsString).isEqualTo(input); } @Test public void shouldReadRemainder() throws IOException { reader = newReaderInstance(EXAMPLE_INPUT_STRING, DEFAULT_BUFFER_SIZE); char[] buffer = new char[5]; reader.read(buffer); assertThat(SpinIoUtil.getStringFromReader(reader)).isEqualTo(EXAMPLE_INPUT_STRING.substring(5)); } /** * When reading more characters than fits into the reader's buffer * @throws IOException */ @Test public void shouldFailWhenRewindLimitExceeded() throws IOException { // exceeding with read(char[]) reader = newReaderInstance(EXAMPLE_INPUT_STRING, DEFAULT_BUFFER_SIZE); char[] buffer = new char[DEFAULT_BUFFER_SIZE + 5]; reader.read(buffer); assertThat(SpinIoUtil.getStringFromReader(reader)) .isEqualTo(EXAMPLE_INPUT_STRING.substring(DEFAULT_BUFFER_SIZE + 5)); try { reader.rewind(); fail("IOException expected"); } catch (IOException e) { // happy path } // exceeding with read() reader = newReaderInstance(EXAMPLE_INPUT_STRING, DEFAULT_BUFFER_SIZE); buffer = new char[DEFAULT_BUFFER_SIZE]; reader.read(buffer); reader.read(); try { reader.rewind(); fail("IOException expected"); } catch (IOException e) { // happy path } // repeated read(char[]) reader = newReaderInstance(EXAMPLE_INPUT_STRING, DEFAULT_BUFFER_SIZE); buffer = new char[DEFAULT_BUFFER_SIZE]; reader.read(buffer); reader.read(buffer); try { reader.rewind(); fail("IOException expected"); } catch (IOException e) { // happy path } } @Test public void shouldRewindWhenNothingWasRead() throws IOException { reader = newReaderInstance("", DEFAULT_BUFFER_SIZE); int charRead = reader.read(); assertThat(charRead).isEqualTo(-1); reader.rewind(); charRead = reader.read(); assertThat(charRead).isEqualTo(-1); } @After public void closeReader() { if (reader != null) { SpinIoUtil.closeSilently(reader); } } protected RewindableReader newReaderInstance(String input, int bufferSize) { Reader reader = new StringReader(input); return new RewindableReader(reader, bufferSize); } }
Java
UTF-8
3,056
2.25
2
[]
no_license
package Client.com.nasri.restjersy.model; import java.io.Serializable; import javax.persistence.*; import java.util.Date; /** * The persistent class for the evenement database table. * */ @Entity @NamedQuery(name = "Evenement.findAll", query = "SELECT e FROM Evenement e") public class Evenement implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; @Temporal(TemporalType.DATE) private Date date; private String description; private String heure; private String latitude; private String lieux; private String longitude; private String nom; private String image; private int idClub; public Evenement() { } public Evenement(Date date, String description, String heure, String latitude, String lieux, String longitude, String nom, int idClub ) { super(); this.date = date; this.description = description; this.heure = heure; this.latitude = latitude; this.lieux = lieux; this.longitude = longitude; this.nom = nom; this.idClub = idClub; } public Evenement(String image , Date date, String description, String heure, String latitude, String lieux, String longitude, String nom, int idClub ) { super(); this.date = date; this.description = description; this.heure = heure; this.latitude = latitude; this.lieux = lieux; this.longitude = longitude; this.nom = nom; this.idClub = idClub; this.image = image; } public Evenement(int id, Date date, String description, String heure, String latitude, String lieux, String longitude, String nom, int idClub) { super(); this.id = id; this.date = date; this.description = description; this.heure = heure; this.latitude = latitude; this.lieux = lieux; this.longitude = longitude; this.nom = nom; this.idClub = idClub; } public int getId() { return this.id; } public void setId(int id) { this.id = id; } public Date getDate() { return this.date; } public void setDate(Date date) { this.date = date; } public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } public String getHeure() { return this.heure; } public void setHeure(String heure) { this.heure = heure; } public String getImage() { return this.image; } public void setImage(String image) { this.image = image; } public String getLatitude() { return this.latitude; } public void setLatitude(String latitude) { this.latitude = latitude; } public String getLieux() { return this.lieux; } public void setLieux(String lieux) { this.lieux = lieux; } public String getLongitude() { return this.longitude; } public void setLongitude(String longitude) { this.longitude = longitude; } public String getNom() { return this.nom; } public void setNom(String nom) { this.nom = nom; } public int getIdClub() { return idClub; } public void setIdClub(int idClub) { this.idClub = idClub; } }
C++
UTF-8
1,048
2.765625
3
[ "Unlicense" ]
permissive
#include "graph/edge.hpp" #include "graph/adjacency_list.hpp" #include "graph/dfs.hpp" #include "dp/tree_dp.hpp" class TreeGraph : public TreeDP<Tree<Edge>, pair<int, bool>> { private: vector<int> h; pair<int, bool> visit(int v, const vector<pair<int, bool>>& children) { auto f = [](pair<int, bool> p){return p.second;}; if (h[v] == 0 && none_of(children.begin(), children.end(), f)) return make_pair(0, false); auto s = [](int n, pair<int, bool> p){return n + p.first + (p.second ? 2 : 0);}; return make_pair(accumulate(children.begin(), children.end(), 0, s), true); } public: TreeGraph(const Tree<Edge>& tree, const vector<int>& h) : TreeDP(tree), h(h) {} }; int main() { int n, x; cin >> n >> x; --x; vector<int> h(n); for (int& i : h) cin >> i; AdjacencyList<Edge> graph(n); for (int i = 0; i < n - 1; ++i) { int a, b; cin >> a >> b; graph.addUndirectedEdge(a - 1, b - 1); } auto tree = dfsTree(graph, x); TreeGraph treeGraph(tree, h); cout << treeGraph.solve(x).first << endl; }
Python
UTF-8
2,827
3.125
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- import time import os import csv class fileDetails: def __init__(self, sample_rate, number, sensor): self.sample_rate = sample_rate self.number = number self.sensor = sensor def getFileName(self): if self.sensor == 'Acc': filename = "Accelerometer_data@" + time.strftime("%Y-%m-%d-%H-%M-%S") + ".csv" elif self.sensor == 'Gyr': filename = "Gyroscope_data@" + time.strftime("%Y-%m-%d-%H-%M-%S") + ".csv" elif self.sensor == 'Mag': filename = "Magnetometer_data@" + time.strftime("%Y-%m-%d-%H-%M-%S") + ".csv" else: filename = "Sensor_data@" + time.strftime("%Y-%m-%d-%H-%M-%S") + ".csv" return filename def getFileInfo(self): if self.sensor == 'Acc': file_info = ('#' + 'ACCELERATION' + "\n" + '#' + 'SAMPLE_RATE = ' + str(self.sample_rate) + ' Hz' + "\n" + '#' + 'Recorded at: ' + time.strftime("%Y-%m-%d-%H:%M:%S") + "\n" + '#' + 'Number of samples = ' + str(self.number) + "\n" + "\n") elif self.sensor == 'Gyr': file_info = ('#' + 'ANGULAR VELOCITY' + "\n" + '#' + 'SAMPLE_RATE = ' + str(self.sample_rate) + ' Hz' + "\n" + '#' + 'Recorded at: ' + time.strftime("%Y-%m-%d-%H:%M:%S") + "\n" + '#' + 'Number of samples = ' + str(self.number) + "\n" + "\n") elif self.sensor == 'Mag': file_info = ('#' + 'MAGNETIC FIELD' + "\n" + '#' + 'SAMPLE_RATE = ' + str(self.sample_rate) + ' Hz' + "\n" + '#' + 'Recorded at: ' + time.strftime("%Y-%m-%d-%H:%M:%S") + "\n" + '#' + 'Number of samples = ' + str(self.number) + "\n" + "\n") else: file_info = ('#' + 'Samples from Accelerometer, Gyroscope and Magnetometer' + "\n" + '#' + 'Recorded at: ' + time.strftime("%Y-%m-%d-%H:%M:%S") + "\n" + '#' + 'Number of samples = ' + str(self.number) + "\n" + "\n") return file_info def csvFile(file_path, sensor, sample_rate, data_i): number = len(data_i) if os.path.exists(file_path): print("Generating csv file.") file = fileDetails(sample_rate, number, sensor) filename = file.getFileName() f = open(os.path.join(file_path, filename), 'w+') file_info = file.getFileInfo() f.write(file_info) wr_acc = csv.writer(f, dialect='excel') for record in data_i: wr_acc.writerow(record) f.close() print("File generated with {} samples.".format(number)) print("Check your destination folder. Thank you.")
C
UTF-8
2,401
2.78125
3
[]
no_license
#include "functions.h" extern int memoryAlloc; char * commandPath(char * cmd) { char paths[200][200]; char allpaths[500]; int i = 0; char temp[100]; int path_found = 0; strcpy(allpaths,enVar("$PATH",NULL)); int offset = 0; while(i < 200 && sscanf(allpaths + offset,"%[^:]",paths[i]) == 1) { offset = offset + strlen(paths[i])+1; i++; } if(access(cmd,F_OK) == 0) return cmd; else if(cmd && memoryAlloc) { int j = 0; for(j = 0; j < i-1;j++ ) { strcat(paths[j],"/"); strcat(paths[j],cmd); if(access(paths[j],F_OK) == 0) { path_found = 1; break; } } if(path_found) { free(cmd); cmd = malloc(strlen(paths[j]) + 1); strcpy(cmd,paths[j]); } } return cmd; } char * expandCD(char * arg) { char targ[250]; int i, dots = 0, home = 0; char * rest; char path[250]; char p_pwd[250]; char * ptr = NULL; int noArg = 0; if(arg && arg[0] == '/') return arg; if(!arg) { strcpy(path,enVar("$HOME",NULL)); arg = (char *)calloc(strlen(path),1); strcpy(arg,path); return arg; } strcpy(targ,arg); for(i = 0; targ[i] && targ[i] != '/'; i++) { if(targ[i] == '.') dots++; if(targ[i] == '~') home = 1; } if(!dots && !home) rest = targ; else rest = targ + i + 1; if(!arg ) { home = 1; noArg = 1; } if(dots || home) { if(arg) free(arg); } if(home) { strcpy(path,enVar("$HOME",NULL)); if(path[strlen(path) -1 ] != '/') strcat(path,"/"); arg = (char * )calloc(strlen(path) + strlen(rest) + 1,1); strcpy(arg,path); if(*rest) strcat(arg,rest); } else if(dots == 1 || dots == 0) { strcpy(path,enVar("$PWD",NULL)); if(path[strlen(path) -1 ]!= '/') strcat(path,"/"); arg = (char *)calloc(strlen(path) + strlen(rest) + 1,1); strcpy(arg,path); if(*rest) strcat(arg,rest); } else if(dots == 2) { strcpy(path,enVar("$PWD",NULL)); if( path[strlen(path) -1 ] != '/') strcat(path,"/"); for(ptr = path + strlen(path) - 2; *ptr != '/';ptr--); *++ptr = '\0'; arg = (char *)calloc(strlen(path) + strlen(rest) + 1,1); strcpy(arg,path); if(*rest) strcat(arg,rest); } return arg; }
Python
UTF-8
160
3.265625
3
[]
no_license
text = input() data = [] for i in text: data.append(i) for d in range(0,len(text)): if data[d] == "?": data[d] = "D" ans = ''.join(data) print(ans)
Python
UTF-8
1,579
3.0625
3
[]
no_license
# -*- coding:utf-8 -*- # Code by Fan.Bai import numpy as np # w = [0, 2, 3, 4, 5] # v = [0, 3, 4, 5, 6] # s = 8 # n = 4 class Solution: def bag(self, n,s,w,v): res = [0] * (s + 1) res = [res] * (n + 1) res = np.array(res) for i in range(1, n + 1): for j in range(1, s + 1): if w[i] > j: res[i][j] = res[i - 1][j] else: res[i][j] = max([res[i - 1][j], res[i - 1][j - w[i]] + v[i]]) print(res) #选择最大的结果 amax=0 loci=locj=0 for i in range(1, n + 1): for j in range(1, s + 1): if res[i][j]>amax: amax=res[i][j] loci=i locj=j # 打印选择了哪些物品 while loci>0 and locj>0: if res[loci][locj]==res[loci-1][locj]: loci=loci-1 continue if res[loci][locj]==res[loci-1][locj-w[loci]]+v[loci]: print(w[loci],v[loci]) locj -= w[loci] loci-=1 class Solution1: def bag(self, n,s,w,v): res = [0] * (s + 1) res=np.array(res) for i in range(1, n + 1): for j in range(s,0,-1): if j>w[i]: res[j]=max(res[j],res[j-w[i]]+v[i]) print(res) n=int(input()) s=int(input()) w=[0] v=[0] for i in range(n): ss=str(input()) w.append(int(ss.split()[0])) v.append(int(ss.split()[1])) Solution().bag(n,s,w,v)
Java
UTF-8
2,086
2.234375
2
[]
no_license
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package powermobia.ve.utils; public class MThread { Thread hThread; private MThread() { hThread = null; } private native int nativeThreadProc(long l, long l1); public int create(final long threadProc, final long userData) { hThread = new Thread(new Runnable() { final MThread this$0; private final long val$threadProc; private final long val$userData; public void run() { nativeThreadProc(threadProc, userData); } { this$0 = MThread.this; threadProc = l; userData = l1; super(); } }); hThread.start(); return 0; } public int destroy() { return 0; } public int exit() { if (hThread.isAlive()) { try { hThread.join(); } catch (Exception exception) { } } return 0; } public int resume() { this; JVM INSTR monitorenter ; hThread.notify(); this; JVM INSTR monitorexit ; return 0; Exception exception; exception; throw exception; } public int sleep(int i) { long l = i; try { Thread.sleep(l); } catch (Exception exception) { } return 0; } public int suspend() { this; JVM INSTR monitorenter ; hThread.wait(); _L2: this; JVM INSTR monitorexit ; return 0; InterruptedException interruptedexception; interruptedexception; interruptedexception.printStackTrace(); if (true) goto _L2; else goto _L1 _L1: Exception exception; exception; throw exception; } }
SQL
UTF-8
1,358
4.28125
4
[]
no_license
--Are average scores for hospital quality or procedural variability correlated with patient survey responses? SELECT CORR(scores.score_std_dev, surveys.survey_score) AS proc_var_survey_corr , CORR(scores.average_score, surveys.survey_score) AS proc_var_survey_corr FROM ( SELECT sub.hospital_id , VARIANCE(sub.average_score) AS score_variation , STDDEV_POP(sub.average_score) AS score_std_dev , SUM(total_score) AS total_score , SUM(total_score)/SUM(total_sample) AS average_score , SUM(hospital_count) AS hospital_count FROM ( SELECT proc.hospital_id , proc.measure_name , SUM(proc.score) AS total_score , SUM(proc.sample) AS total_sample , SUM(proc.score)/SUM(proc.sample) AS average_score , COUNT(DISTINCT proc.hospital_id) AS hospital_count FROM procedures_transformed AS proc INNER JOIN hospitals_transformed AS hos ON proc.hospital_id = hos.hospital_id GROUP BY proc.hospital_id , proc.measure_name , hos.state HAVING hos.state NOT IN ('GU','VI','AS','MP','PR','VI') ) sub GROUP BY sub.hospital_id ) scores INNER JOIN ( SELECT hospital_id , SUM((hosp_comm_score + hos_rsp_score + hos_cln_score + hos_achv_score)/4) AS survey_score FROM surveys_transformed GROUP BY hospital_id ) surveys ON scores.hospital_id = surveys.hospital_id; GROUP BY scores.hospital_id ORDER BY survey_corr DESC LIMIT 100;
Java
UTF-8
3,460
2.1875
2
[ "MIT" ]
permissive
package org.firstinspires.ftc.teamcode.tester; import com.acmerobotics.dashboard.FtcDashboard; import com.acmerobotics.dashboard.config.Config; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorEx; import com.qualcomm.robotcore.hardware.PIDFCoefficients; import com.qualcomm.robotcore.hardware.Servo; import com.qualcomm.robotcore.util.ElapsedTime; import static org.firstinspires.ftc.teamcode.faraRR.PowersConfig2.IMPINS_BWD; import static org.firstinspires.ftc.teamcode.faraRR.PowersConfig2.IMPINS_FWD; @Config @Autonomous public class LansatTuning extends LinearOpMode { final static double MAX_RPM = 6000; final static double TICKS_PER_REV = 28; public static PIDFCoefficients pidCoefficients = new PIDFCoefficients(25, 0.0, 10, 13.45);//MAX_RPM * 60 / TICKS_PER_REV); public static double targetVelocity = 1350; public static double currentVelocity = 0; DcMotorEx lansat; Servo impins; boolean shooting = false; @Override public void runOpMode() throws InterruptedException { FtcDashboard dashboard = FtcDashboard.getInstance(); telemetry = dashboard.getTelemetry(); lansat = hardwareMap.get(DcMotorEx.class, "lansat"); lansat.setMode(DcMotor.RunMode.RUN_USING_ENCODER); impins = hardwareMap.get(Servo.class, "impins"); lansat.setPIDFCoefficients(DcMotor.RunMode.RUN_USING_ENCODER, pidCoefficients); waitForStart(); PIDFCoefficients prevCoeff = new PIDFCoefficients(pidCoefficients); while(opModeIsActive()) { currentVelocity = lansat.getVelocity(); if(prevCoeff.p != pidCoefficients.p || prevCoeff.i != pidCoefficients.i || prevCoeff.d != pidCoefficients.d || prevCoeff.f != pidCoefficients.f) lansat.setPIDFCoefficients(DcMotor.RunMode.RUN_USING_ENCODER, pidCoefficients); if(gamepad1.left_bumper && !shooting) { Thread shoot = new Thread(new OneButtonShoot()); shoot.start(); } if(gamepad1.x) impins.setPosition(IMPINS_FWD); else if(!shooting) impins.setPosition(IMPINS_BWD); if(gamepad1.dpad_left) lansat.setPower(0); if(gamepad1.dpad_right) lansat.setVelocity(targetVelocity); prevCoeff = new PIDFCoefficients(pidCoefficients); telemetry.addData("targetVelocity", targetVelocity); telemetry.addData("currVelocity", currentVelocity); telemetry.addData("PIDF", lansat.getPIDFCoefficients(DcMotor.RunMode.RUN_USING_ENCODER)); telemetry.update(); } } private class OneButtonShoot implements Runnable { @Override public void run() { ElapsedTime timer = new ElapsedTime(); shooting = true; for(int i = 0; i < 3; i++) { impins.setPosition(IMPINS_FWD); timer.reset(); while(timer.milliseconds() < 250) continue; impins.setPosition(IMPINS_BWD); timer.reset(); while(timer.milliseconds() < 250) continue; } shooting = false; } } }
C
UTF-8
1,637
3.390625
3
[]
no_license
#include "qsort.h" int _array_qsort_get_pivot(t_array array, t_array *array_without_pivot); t_array* _array_qsort_partition(t_array array, int pivot); t_array array_qsort(t_array array) { t_array sorted_array; int pivot; t_array pivot_array; t_array array_without_pivot; t_array *partitions; if (array->size <= 0) { sorted_array = array; } else { pivot = _array_qsort_get_pivot(array, &array_without_pivot); pivot_array = array_new(1); array_push(pivot_array, pivot); partitions = _array_qsort_partition(array_without_pivot, pivot); sorted_array = array_concat(3, array_qsort(partitions[0]), pivot_array, array_qsort(partitions[1])); array_free(pivot_array); array_free(array_without_pivot); array_free(partitions[0]); array_free(partitions[1]); free(partitions); } return sorted_array; } int _array_qsort_get_pivot(t_array array, t_array *array_without_pivot) { int pivot; assert(array->size > 0); *array_without_pivot = array_dup(array); pivot = (*array_without_pivot)->elements[(*array_without_pivot)->size - 1]; (*array_without_pivot)->size--; return pivot; } t_array* _array_qsort_partition(t_array array, int pivot) { t_array *partitions; int element; int partition_to_push; int i; partitions = (t_array*) malloc(sizeof(t_array) * 2); partitions[0] = array_new(array->size); partitions[1] = array_new(array->size); for (i = 0; i < array->size; i++) { element = array->elements[i]; partition_to_push = (element < pivot) ? 0 : 1; array_push(partitions[partition_to_push], element); } return partitions; }
Ruby
UTF-8
486
2.96875
3
[]
no_license
class Employee attr_accessor :id, :username, :password, :role def initialize(attributes = {}) @id = attributes[:id].to_i @username = attributes[:username].to_s @password = attributes[:password].to_s @role = attributes[:role].to_s end def manager? @role == "manager" end def delivery_guy? @role == "delivery_guy" end def headers ["id", "username", "password", "role"] end def build_row [@id, @username, @password, @role] end end
JavaScript
UTF-8
482
2.515625
3
[ "MIT" ]
permissive
(function($) { $(document).ready(function() { $('.hamburger').on('click', function() { var $this = $(this); var $menu = $('.nav'); if ($this.hasClass('is-active') ) { $this.removeClass('is-active'); $menu.removeClass('is-active'); } else { $this.addClass('is-active'); $menu.addClass('is-active'); } }); }); })(jQuery);
C
UTF-8
1,211
3.59375
4
[]
no_license
/* 数塔问题:将一些数字排成塔的形状,其第一层有一个数字,第二层有两个数字,,,,,。现在要从第一层走到第n层,每次只能走向下一层的两个数字中的一个 问:最后将路径上所有的数字相加后得到的和最大是多少?? */ /* #include<stdio.h> #define MAXSIZE 100 #define MAX(a, b) (a>b)?a:b int dp[MAXSIZE][MAXSIZE]; int tower[MAXSIZE][MAXSIZE]; // int max(int a, int b){ // return a>b ? a : b; // } int main(void){ int n; int i, j; //输入数塔的层数 printf("please, enter the n:"); scanf("%d", &n); //输入数塔的内容 for(i=1; i<=n; i++){ for(j=1; j<=i; j++) scanf("%d", &tower[i][j]); } //采用递推方式求解数塔的全局最优 for(i = n; i >= 1; i--){ if(i == n) for(j = 1; j <= i; j++){ dp[i][j] = tower[i][j]; } else for(j = 1; j <= i; j++) //转移方程 dp[i][j] = MAX(dp[i+1][j], dp[i+1][j+1]) + tower[i][j]; } printf("The result is %d", dp[1][1]); return 0; } */
C
UTF-8
443
3.578125
4
[]
no_license
#include "monty.h" /** * op_pop - removes the top element of the stack. * @stack: double pointer to head of the list * @index_line: line index * Return: void */ void op_pop(stack_t **stack, unsigned int index_line) { stack_t *head = *stack; if (head == NULL) { fprintf(stderr, "L%d: can't pop an empty stack\n", index_line); exit(EXIT_FAILURE); } *stack = head->next; if (head->next) head->next->prev = NULL; free(head); }
Java
ISO-8859-1
6,903
1.828125
2
[]
no_license
package Portal.Jasper; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpSession; import net.sf.jasperreports.engine.JRDataSource; import net.sf.jasperreports.engine.JREmptyDataSource; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JRExporterParameter; import net.sf.jasperreports.engine.JasperExportManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource; import net.sf.jasperreports.engine.export.JRHtmlExporter; import net.sf.jasperreports.engine.export.JRHtmlExporterParameter; import net.sf.jasperreports.j2ee.servlets.ImageServlet; import net.sf.jasperreports.view.JasperViewer; import uk.ltd.getahead.dwr.WebContextFactory; import Portal.Operacoes.OpRelSequenciaAjax; public class RelatorioAcessoJasperSequencia { public static final String ARQUIVO = "Volumetria.jasper"; public static final String ARQUIVO_CONSOLIDADO = "Registro_Acesso_C.jasper"; /** Linhas do relatrio, lista de objetos Log */ private ArrayList dados; /** Parmetros passados para o relatorio */ private HashMap parametros = new HashMap(); /** Relatorio conpilado */ private JasperPrint jasperPrint = null; //private final int BRASILTELECOM = 1; private static int quantPag = 0; private boolean consolidado; private OpRelSequenciaAjax sequenciaAjax; public void setDadosRelatorioAcesso(ArrayList dados, boolean consolidado, String path, OpRelSequenciaAjax opRelSequenciaAjax){ this.dados = dados; this.consolidado = consolidado; setSequenciaAjax(opRelSequenciaAjax); compile(path); } private void compile(String arquivo){ JRDataSource data = null; JRDataSource dataDownload = null; if(dados.size() > 0){ data = new JRBeanCollectionDataSource(dados); ArrayList temp = new ArrayList(); temp.addAll(dados); dataDownload = new JRBeanCollectionDataSource(temp); }else{ data = new JREmptyDataSource(1); dataDownload = new JREmptyDataSource(1); } // jasperPrint = new JasperPrint(); //setJp(new JasperPrint()); try { // jasperPrint = JasperFillManager.fillReport(arquivo, parametros, data); if(getSequenciaAjax().isDrill()){ getSequenciaAjax().setJasperPrintDrill(JasperFillManager.fillReport(arquivo, parametros, data)); String caminhoImagem =getSequenciaAjax().getSessao().getServletContext().getRealPath("/")+"imagens\\visent.png"; parametros.put("IMAGEM_TOPO", caminhoImagem); parametros.put( "IS_IGNORE_PAGINATION", true ); getSequenciaAjax().setJasperPrintDrillDownload(JasperFillManager.fillReport(getArquivoJasperDownload(arquivo), parametros, dataDownload)); quantPag = getSequenciaAjax().getJasperPrintDrill().getPages().size(); } else{ String caminhoImagem =getSequenciaAjax().getSessao().getServletContext().getRealPath("/")+"imagens\\reldetalha.png"; parametros.put("IMAGEM", caminhoImagem); getSequenciaAjax().setJasperPrint(JasperFillManager.fillReport(arquivo, parametros, data)); String caminhoImagemDownload =getSequenciaAjax().getSessao().getServletContext().getRealPath("/")+"imagens\\visent.png"; parametros.put("IMAGEM_TOPO", caminhoImagemDownload); parametros.put( "IS_IGNORE_PAGINATION", true ); getSequenciaAjax().setJasperPrintDownload(JasperFillManager.fillReport(getArquivoJasperDownload(arquivo), parametros, dataDownload)); quantPag = getSequenciaAjax().getJasperPrint().getPages().size(); //quantPag = jasperPrint.getPages().size(); } getSequenciaAjax().setQtdPages(quantPag); } catch (JRException e) { e.printStackTrace(); } } public void setDadosRelatorioAcessoPdf(JasperPrint jasper){ relatorioPdf(jasper); } public void relatorioPdf(JasperPrint jasper){ try { JasperExportManager.exportReportToPdfFile(jasper,"C:\\usr\\osx\\cdrview\\PortalOsx\\reports\\Relatorio.pdf"); // JasperExportManager.ex JasperViewer.viewReport(jasper); } catch (JRException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public int getNumeroPaginasRelAcesso() { return quantPag; } public String relatorioHTML(int pg, OpRelSequenciaAjax opRelSequenciaAjax){ JasperPrint jasper = null; if(opRelSequenciaAjax.isDrill()){ jasper = opRelSequenciaAjax.getJasperPrintDrill(); } else jasper = opRelSequenciaAjax.getJasperPrint(); HttpSession sess = WebContextFactory.get().getSession(); // HttpSession sess = (HttpSession) HibernateUtil.getSessionFactory().openSession(); //sess = sess.setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, jasper); JRHtmlExporter exporter = new JRHtmlExporter(); StringBuffer sbuffer = new StringBuffer(); Map imagesMap = new HashMap(); sess.setAttribute("IMAGES_MAP", imagesMap); exporter.setParameter(JRHtmlExporterParameter.IMAGES_MAP, imagesMap); exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, "/PortalOsx/servlets/image?rnd="+Math.random()+"&image="); exporter.setParameter(JRHtmlExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS,Boolean.FALSE); exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE); exporter.setParameter(JRExporterParameter.OUTPUT_STRING_BUFFER,sbuffer); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasper); if(pg == -1){ exporter.setParameter(JRExporterParameter.START_PAGE_INDEX, new Integer(0)); exporter.setParameter(JRExporterParameter.END_PAGE_INDEX, new Integer(jasper.getPages().size()-1)); exporter.setParameter(JRHtmlExporterParameter.BETWEEN_PAGES_HTML, "<br style=\"page-break-before:always;\">"); }else{ exporter.setParameter(JRExporterParameter.PAGE_INDEX, new Integer(pg)); exporter.setParameter(JRHtmlExporterParameter.BETWEEN_PAGES_HTML, ""); } exporter.setParameter(JRHtmlExporterParameter.HTML_HEADER, ""); exporter.setParameter(JRHtmlExporterParameter.HTML_FOOTER, ""); try { if(dados.size() > 0){ exporter.exportReport(); }else{ return null;//sem dados } } catch (JRException e) { System.out.println("Problema ao exportar relatorio "+e); //e.printStackTrace(); } return sbuffer.toString(); } private String getArquivoJasperDownload(String arquivo){ StringBuffer s = new StringBuffer(arquivo); s.insert(s.indexOf(".jasper"),"_download"); return s.toString(); } public JasperPrint getJasperPrint() { return jasperPrint; } public JasperPrint getJP(){ return jasperPrint; } public boolean isConsolidado(){ return this.consolidado; } public OpRelSequenciaAjax getSequenciaAjax() { return sequenciaAjax; } public void setSequenciaAjax(OpRelSequenciaAjax sequenciaAjax) { this.sequenciaAjax = sequenciaAjax; } }
Java
UTF-8
3,944
2.140625
2
[]
no_license
package com.baimicro.central.oauth.controller; import com.baimicro.central.common.model.Result; import com.baimicro.central.oauth.dto.ClientDto; import com.baimicro.central.oauth.mapper.ClientMapper; import com.baimicro.central.oauth.model.Client; import com.baimicro.central.common.model.DuplicateCheck; import com.baimicro.central.oauth.service.IClientService; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import io.swagger.annotations.ApiOperation; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.util.Arrays; import java.util.List; /** * @project: hospital-cloud-platform * @author: chen.baihoo * @date: 2020/2/16 * @Description: TODO 应用相关接口 * version 0.1 */ @RestController @RequestMapping("/clients") public class ClientController { @Autowired private IClientService clientService; @Autowired private ClientMapper clientMapper; @GetMapping(value = "/list") public Result<IPage<Client>> list(Client client, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) { Result<IPage<Client>> result = new Result<>(); Page<Client> page = new Page<>(pageNo, pageSize); String key = req.getParameter("clientName"); QueryWrapper<Client> wrapper = null; if (key != null) { wrapper = new QueryWrapper<>(); wrapper.like("client_name", "%" + key + "%"); } IPage<Client> pageList = clientService.page(page, wrapper); result.setSuccess(true); result.setResult(pageList); return result; } /** * 校验数据是否在系统中是否存在 * * @return */ @RequestMapping(value = "/check", method = RequestMethod.GET) public Result<Object> doDuplicateCheck(DuplicateCheck duplicateCheck, HttpServletRequest request) { Long num = null; if (StringUtils.isNotBlank(duplicateCheck.getDataId())) { // [2].编辑页面校验 num = clientMapper.duplicateCheckCountSql(duplicateCheck); } else { // [1].添加页面校验 num = clientMapper.duplicateCheckCountSqlNoDataId(duplicateCheck); } if (num == null || num == 0) { // 该值可用 return Result.succeed("该值可用!"); } else { // 该值不可用 return Result.failed("该值不可用,系统中已存在!"); } } @GetMapping("/{id}") public Result<Client> get(@PathVariable Long id) { return Result.succeed(clientService.getById(id)); } @GetMapping("/all") public Result<List<Client>> allClient() { return Result.succeed(clientService.list()); } /** * 通过id删除 * * @param id * @return */ @DeleteMapping(value = "/delete") public Result delete(@RequestParam(name = "id") String id) { return clientService.delClient(id); } /** * 批量删除 * * @param ids * @return */ @DeleteMapping(value = "/deleteBatch") public Result deleteBatch(@RequestParam(name = "ids") String ids) { return clientService.delClient(Arrays.asList(ids.split(","))); } @PostMapping("/saveOrUpdate") @ApiOperation(value = "保存或者修改应用") public Result saveOrUpdate(@RequestBody ClientDto clientDto) throws Exception { return clientService.saveClient(clientDto); } }
Python
UTF-8
745
2.546875
3
[]
no_license
#!/usr/bin/python import sys, math ifile = open( sys.argv[1], "r").readlines() chain = sys.argv[2] data = [] atomtypes = ["CA"] for line in ifile: if line[0:4] == "ATOM": if (line[21] == chain) or (chain=="all"): if str.split(line[12:16])[0] in atomtypes: x = float(line[30:38]) y = float(line[38:46]) z = float(line[46:54]) data.append([x,y,z]) ofile = open("structure.gro","w") ofile.write("generated from %s\n" % sys.argv[1]) ofile.write("%6i\n" % len(data)) for i in range(len(data)): line = data[i] x = 0.1*line[0] y = 0.1*line[1] z = 0.1*line[2] ofile.write(" %4iXXX CA %5i%8.3f%8.3f%8.3f\n" % (i+1, i+1,x,y,z)) ofile.write(" 10.00000 10.00000 10.00000\n") ofile.close()
Python
UTF-8
1,144
4.84375
5
[]
no_license
def add(num1, num2): print(f'The addition of this two number is : {num1 + num2}') def substract(num1, num2): print(f'The substraction of this two number is: {num1 - num2}') def multiplicate(num1, num2): print(f'The multiplication of this two number is : {num1 * num2}') def divide(num1, num2): print(f'The division of this two number is : {num1/num2} ') while True: print('***What you want to do right now?:: ') print(' 1. addition') print(' 2. substraction') print(' 3. multiplication') print(' 4. division') print('press 5 to Quit') try: a = input('Enter your choice:: ') num1 = int(input('Enter the first number:: ')) num2 = int(input('Enter the second number:: ')) if a == '1': add(num1, num2) elif a == '2': substract(num1, num2) elif a == '3': multiplicate(num1, num2) elif a == '4': divide(num1, num2) else: print('Thanks for using our calculator!') exit() except Exception as e: print(e)
Python
UTF-8
2,764
4.03125
4
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Dec 9 12:07:12 2018 @author: harriet """ #creates a class called Animal which is an object class Animal(object): pass #cCreates a class Dog which is a subclass of the class Animal, and has an init function with the params self and anem class Dog(Animal): def __init__ (self, name): #this line sets the self.name attribute of the class Dog to name self.name=name #this creates a class called Cat, which is a sub class of the class Animal and has an init function with the params self and name class Cat(Animal): def __init__ (self, name): #this sets the self.name attribute of the class Cat to name self.name=name #this creates a class called Person which is an object, and has an init function with the params self and name class Person(object): def __init__ (self, name): #this sets the self.name attribute of the class Person to name self.name=name #this creates a class Employee which is a subclass of the Person class and has an init function with the params self, name and salary class Employee(Person): def __init__ (self, name, salary): # this uses super to call the init method from the superclass super(Employee, self).__init__(name) #this sets the self.salary attribute of the class Employee to salary self.salary=salary #this creates a class called Fish class Fish(object): pass #this creates a class called Salmon which is a subclass of the Fish class class Salmon (Fish): pass #this creates a class called Halibut which is a subclass of the Fish class class Halibut(Fish): pass #instance variables below are "has-a" relationships #creates a variable called rover which is an instance of the Dog class, and sets the param of name to "Rover" rover=Dog("Rover") #creates a variable called satan which is an instance of the Cat class, and sets the param of name to "Satan" satan=Cat("Satan") #creates a variable called mary which is an instance of the person class, and sets the param of name to "Mary" mary=Person("Mary") #from mary gets the pet attribute and sets it to Satan mary.pet=satan #creates a variable called frank which is an instance of the Employee class and sets the params of name and salary frank=Employee("Frank", 1200000) #from frank gets the pet attribute and sets it to rover frank.pet=rover #creates a variable called flipper which is an instance of the Fish class flipper=Fish() #creates a variable called crouse which is an instance of the Salmon class crouse=Salmon() #creates a variable called harry which is an instance of the Halibut class harry = Halibut()
Python
UTF-8
3,291
2.625
3
[]
no_license
import vtk class LArSoftToVtkCoord(): # x_vtk is y larsoft # y_vtk is z larsoft # z_vtk is x larsoft #vtk units are in mm while larsoft (geant) are in cm #larsoft origin is at the center of the 1 m side of the TPC #vtk origin (inported from CAD) is at the center of the CRP def GetXVTK(self,x_larsoft,y_larsoft,z_larsoft): return y_larsoft*10 def GetYVTK(self,x_larsoft,y_larsoft,z_larsoft): return z_larsoft*10-1500 def GetZVTK(self,x_larsoft,y_larsoft,z_larsoft): return x_larsoft*10-500 def LArSoftOrigin(self): return [0.0, -1500.0, -500.0] def VTKOrigin(self): return [0.0, 0.0, 0.0] def VTKCenterTPC(self): return [0.0, 0.0, -500.0]#returns center of TPC volume in VTK coordinates def ReturnAxesActor(self): AxesTransform = vtk.vtkTransform() AxesTransform.Translate(self.LArSoftOrigin()) AxesTransform.Scale(1.5, 1.5, 1.5) axes = vtk.vtkAxesActor() axes.SetUserTransform(AxesTransform) axes.GetZAxisTipProperty().SetLineWidth(400) axes.SetXAxisLabelText("Y") axes.SetYAxisLabelText("Z") axes.SetZAxisLabelText("X") axes.SetTotalLength(500.0, 2500.0, 500.0) axes.SetNormalizedShaftLength(1.0, 1.0, 1.0) axes.SetNormalizedTipLength(0.05, 0.05*5/25, 0.05) xAxesLabel= axes.GetXAxisCaptionActor2D() xAxisLabel=axes.GetXAxisCaptionActor2D() xAxisLabel.GetTextActor().SetTextScaleModeToNone() xAxisLabel.GetCaptionTextProperty().SetFontSize(50) xAxisLabel.GetCaptionTextProperty().SetColor(1,0,0) xAxisLabel.GetCaptionTextProperty().ItalicOff yAxesLabel=axes.GetYAxisCaptionActor2D() yAxisLabel = axes.GetYAxisCaptionActor2D() yAxisLabel.GetTextActor().SetTextScaleModeToNone() yAxisLabel.GetCaptionTextProperty().SetFontSize(50) yAxisLabel.GetCaptionTextProperty().SetColor(0,1,0) yAxisLabel.GetCaptionTextProperty().ItalicOff zAxesLabel=axes.GetZAxisCaptionActor2D() zAxisLabel = axes.GetZAxisCaptionActor2D() zAxisLabel.GetTextActor().SetTextScaleModeToNone() zAxisLabel.GetCaptionTextProperty().SetFontSize(50) zAxisLabel.GetCaptionTextProperty().SetColor(0,0,1) zAxisLabel.GetCaptionTextProperty().ItalicOff return axes class PointsToGlyph(): def ReturnGlyphActorFromPoints(self, MyPoints , View, SphereRadius, color): inputDataGlyph= vtk.vtkPolyData() glyphMapper = vtk.vtkPolyDataMapper() glyphPoints = vtk.vtkGlyph3D() balls = vtk.vtkSphereSource() inputDataGlyph.SetPoints(MyPoints) balls.SetRadius(SphereRadius) balls.SetPhiResolution(10) balls.SetThetaResolution(10) glyphPoints.SetInputData(inputDataGlyph) glyphPoints.SetSourceConnection(balls.GetOutputPort()) glyphMapper.SetInputConnection(glyphPoints.GetOutputPort()) glyphActor = vtk.vtkActor() glyphActor.SetMapper(glyphMapper) glyphActor.GetProperty().SetDiffuseColor(color) glyphActor.GetProperty().SetSpecular(.3) glyphActor.GetProperty().SetSpecularPower(30) return glyphActor #class ComputeAxes():
PHP
UTF-8
1,536
2.71875
3
[ "Apache-2.0" ]
permissive
<?php namespace ContinuousPipe\CloudFlare; use ContinuousPipe\Model\Component\Endpoint\CloudFlareAuthentication; class TraceableCloudFlareClient implements CloudFlareClient { /** * @var ZoneRecord[] */ private $createdRecords = []; /** * @var string[] */ private $deletedRecords = []; /** * @var CloudFlareClient */ private $decoratedClient; /** * @param CloudFlareClient $decoratedClient */ public function __construct(CloudFlareClient $decoratedClient) { $this->decoratedClient = $decoratedClient; } /** * {@inheritdoc} */ public function createOrUpdateRecord(string $zone, CloudFlareAuthentication $authentication, ZoneRecord $record) : string { $identifier = $this->decoratedClient->createOrUpdateRecord($zone, $authentication, $record); $this->createdRecords[] = $record; return $identifier; } /** * {@inheritdoc} */ public function deleteRecord(string $zone, CloudFlareAuthentication $authentication, string $recordIdentifier) { $this->decoratedClient->deleteRecord($zone, $authentication, $recordIdentifier); $this->deletedRecords[] = $recordIdentifier; } /** * @return ZoneRecord[] */ public function getCreatedRecords(): array { return $this->createdRecords; } /** * @return string[] */ public function getDeletedRecords(): array { return $this->deletedRecords; } }
Java
UTF-8
2,252
2.453125
2
[]
no_license
package com.ictpoker.ixi.engine.commons; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; public class EvaluationTest { @Test public void testEvaluation() { final Hand hand1 = new Hand(Arrays.asList(new Card(Rank.TWO, Suit.CLUBS), new Card(Rank.THREE, Suit.CLUBS), new Card(Rank.JACK, Suit.DIAMONDS), new Card(Rank.SIX, Suit.DIAMONDS), new Card(Rank.JACK, Suit.HEARTS), new Card(Rank.KING, Suit.HEARTS), new Card(Rank.ACE, Suit.SPADES))); final Hand hand2 = new Hand(Arrays.asList(new Card(Rank.TWO, Suit.CLUBS), new Card(Rank.THREE, Suit.CLUBS), new Card(Rank.JACK, Suit.CLUBS), new Card(Rank.SIX, Suit.DIAMONDS), new Card(Rank.JACK, Suit.HEARTS), new Card(Rank.KING, Suit.HEARTS), new Card(Rank.ACE, Suit.SPADES))); final Evaluation evaluation1 = new Evaluation(hand1); final Evaluation evaluation2 = new Evaluation(hand2); Assert.assertEquals(evaluation1, evaluation2); Assert.assertEquals(evaluation1.hashCode(), evaluation2.hashCode()); } @Test(expected = IllegalStateException.class) public void testEvaluation2() { final Hand hand1 = new Hand(Arrays.asList(new Card(Rank.TWO, Suit.CLUBS), new Card(Rank.THREE, Suit.CLUBS), new Card(Rank.JACK, Suit.DIAMONDS), new Card(Rank.SIX, Suit.DIAMONDS), new Card(Rank.JACK, Suit.HEARTS), new Card(Rank.KING, Suit.HEARTS))); final Hand hand2 = new Hand(Arrays.asList(new Card(Rank.TWO, Suit.CLUBS), new Card(Rank.THREE, Suit.CLUBS), new Card(Rank.JACK, Suit.CLUBS), new Card(Rank.SIX, Suit.DIAMONDS), new Card(Rank.JACK, Suit.HEARTS), new Card(Rank.KING, Suit.HEARTS))); final Evaluation evaluation1 = new Evaluation(hand1); final Evaluation evaluation2 = new Evaluation(hand2); Assert.assertEquals(evaluation1, evaluation2); Assert.assertEquals(evaluation1.hashCode(), evaluation2.hashCode()); } }
Swift
UTF-8
1,936
3.0625
3
[]
no_license
// // AccordionRow.swift // SwiftUIAccordion // // Created by Nathan on 4/14/21. // import SwiftUI struct AccordionRow: View { var content: AccordionRowRepresentable var body: some View { HStack { VStack(alignment: .leading, spacing: 4) { Text(content.title) .kerning(0.11) .font(.body) .foregroundColor(content.isEnabled ? Color.blue : Color.gray) .disabled(!content.isEnabled) if let subtitle = content.subtitle { Text(subtitle) .kerning(0.11) .font(.caption) .foregroundColor(content.isEnabled ? Color.blue : Color.gray) .disabled(!content.isEnabled) } } .padding() if content.isExternalLink { Image(systemName: "share") .resizable() .aspectRatio(contentMode: .fit) .frame(width: 16, height: 16) .foregroundColor(content.isEnabled ? Color.blue : Color.gray) .disabled(!content.isEnabled) } Spacer() if let tag = content.accessoryText { Text(tag) .font(.caption) .foregroundColor(.white) .padding(EdgeInsets(top: 4, leading: 16, bottom: 4, trailing: 16)) .background(Capsule().foregroundColor(content.isEnabled ? .blue : Color.blue.opacity(0.5))) .disabled(!content.isEnabled) } } .padding() .overlay(SwiftUI.Divider(), alignment: .bottom) } init(content: AccordionRowRepresentable) { self.content = content } } struct AccordionRow_Previews: PreviewProvider { static var previews: some View { AccordionRow(content: RowContentPreview(title: "Asthma", subtitle: "Jan 10, 2020", accessoryText: "Pending")) } }
Java
UTF-8
2,396
2.546875
3
[]
no_license
package ru.semiot.semdesc.database; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Random; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; /** * * @author Daniil Garayzuev <garayzuev@gmail.com> */ @Stateless public class DataBase { @PersistenceContext(unitName = "DataSource") private EntityManager em; public long addNewUser(String token, int id, String login) { TypedQuery<Session> query = em.createNamedQuery("Session.findById", Session.class); query.setParameter("id", id); Session ses = null; try { Session s = query.getSingleResult(); remove(s.getSessionHash()); query.getSingleResult(); } catch (NoResultException ex) { ses = new Session(createHash(token, id), id, token, login); em.persist(ses); } return ses.getSessionHash(); } private long createHash(String token, int id) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { } md.reset(); md.update(token.getBytes()); byte[] digest = md.digest(generateSpicy(id)); return new BigInteger(digest).longValue(); } private byte[] generateSpicy(int id) { int length = id % 200; Random rnd = new Random(); final String alphabetic = "ASDFGHJKLQWERTYUIOPZXCVBNMpoilkjuythgfmnbrewqvcdsaxz"; char[] text = new char[length]; for (int i = 0; i < length; i++) { text[i] = alphabetic.charAt(rnd.nextInt(alphabetic.length())); } return new String(text).getBytes(); } public String getToken(long hash) { Session session = em.find(Session.class, hash); if (session != null) { return session.getToken(); } return null; } public String getLogin(long hash) { Session session = em.find(Session.class, hash); if (session != null) { return session.getLogin(); } return null; } public void remove(long hash) { em.remove(em.find(Session.class, hash)); } }
C++
UTF-8
1,493
2.75
3
[]
no_license
//layer.cpp #include "layer.h" layer::layer(tile_set* p_tile_set, int p_width, int p_height, int p_tile_width, int p_tile_height, std::vector<int>& p_map_ids, int p_id_offset, int p_offset_x, int p_offset_y) { m_x = p_offset_x; m_y = p_offset_y; int index = 0; for(int y = 0; y < p_height; y++) { for(int x = 0; x < p_width; x++) { int id = p_map_ids[index] - p_id_offset; tile* temp = new tile(*p_tile_set->get(id)); SDL_Rect rect = { x * p_tile_width + p_offset_x, y * p_tile_height + p_offset_y, p_tile_width, p_tile_height }; temp->set_tile_rect(rect); if(id == 20) // TODO: List of flags(?) temp->add_collider(rect); m_map.push_back(temp); index++; } } } layer::~layer() { for(auto&& tile : m_map) { if(tile != nullptr) delete tile; tile = nullptr; } } void layer::on_enable() { } void layer::update(int p_ms) { } void layer::render() { for(auto&& tile : m_map) { tile->render(); } } void layer::on_disable() { } void layer::on_collision(entity* p_other) { } tile* layer::get_tile(int p_id) { return m_map[p_id]; } int layer::size() { return m_map.size(); } void layer::reset() { }
PHP
UTF-8
2,528
2.828125
3
[]
no_license
<?php namespace MOLiBot\DataSources; use MOLiBot\Exceptions\DataSourceRetriveException; use Exception; use SoapBox\Formatter\Formatter; class CPCProductPrice extends Source { private $url; private $historyUrl; private $historyProdId = 1; /** * MoliKktix constructor. */ public function __construct() { parent::__construct(); $this->url = 'https://vipmember.tmtd.cpc.com.tw/OpenData/ListPriceWebService.asmx/getCPCMainProdListPrice'; $this->historyUrl = 'https://vipmember.tmtd.cpc.com.tw/OpenData/ListPriceWebService.asmx/getCPCMainProdListPrice_Historical'; } /** * @return array * @throws \GuzzleHttp\Exception\GuzzleException|DataSourceRetriveException */ public function getContent() : array { try { $response = $this->httpClient->request('GET', $this->url); return $this->handleResponse($response); } catch (Exception $e) { throw new DataSourceRetriveException($e->getMessage(), $e->getCode()); } } /** * @param $prodId * @return void */ public function setHistoryProdId($prodId) { if (!empty($prodId)) { $this->historyProdId = $prodId; } } /** * @return array * @throws \GuzzleHttp\Exception\GuzzleException|DataSourceRetriveException */ public function getHistoryContent() : array { /* $prodId = array( '1' => '92無鉛汽油', '2' => '95無鉛汽油', '3' => '98無鉛汽油', '4' => '超級/高級柴油', '5' => '低硫燃料油(0.5%)', '6' => '甲種低硫燃料油(0.5)' ); */ try { $response = $this->httpClient->request('GET', $this->historyUrl . '?prodid=' . $this->historyProdId); return $this->handleResponse($response); } catch (Exception $e) { throw new DataSourceRetriveException($e->getMessage(), $e->getCode()); } } /** * @param $response * @return array */ private function handleResponse($response) { $fileContents = $response->getBody()->getContents(); // SOAP response to regular XML $xml = preg_replace('/(<\/?)(\w+):([^>]*>)/', '$1$2$3', $fileContents); $formatter = Formatter::make($xml, Formatter::XML); $json = $formatter->toArray(); return $json['diffgrdiffgram']['NewDataSet']['tbTable']; } }
Python
UTF-8
699
3.15625
3
[]
no_license
from numpy import array, zeros, dot import time #Matrix Array (Wasnt sure how to make it an input) N = 5 A = array([[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]) B = array([[2, 3, 4, 5, 6], [2, 3, 4, 5, 6], [2, 3, 4, 5, 6], [2, 3, 4, 5, 6], [2, 3, 4, 5, 6]]) C = zeros([N,N],int) start = time.clock() #Matrix Multi for i in range(N): for j in range(N): for k in range(N): C[i,j] += A[i,k]*B[k,j] end = time.clock() #matrix multi print print("A =", A) print("B =", B) print("C =", C) #Time start2 = time.clock() d = dot(A,B) end2 = time.clock() #Time time = (end2 - start2) print(d) print("time =", time)
C#
UTF-8
235
3.390625
3
[]
no_license
class a { public void Info() { Console.WriteLine("I'm a"); } } class b : a { public new void Info() { Console.WriteLine("I'm b"); } }
Java
UTF-8
6,724
2.078125
2
[]
no_license
package core.ddf.base; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.Method; import java.util.Date; import java.util.Properties; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.io.FileHandler; import org.testng.Assert; import org.testng.ITestResult; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeSuite; import com.aventstack.extentreports.ExtentReports; import com.aventstack.extentreports.ExtentTest; import com.aventstack.extentreports.Status; import com.aventstack.extentreports.reporter.ExtentHtmlReporter; import core.ddf.dev.base.ExtentManager; import core.ddf.dev.base.Xls_Reader; public class BaseTest { public static WebDriver driver; public static Properties pro; public static ExtentReports extent=ExtentManager.getInstance(); public ExtentTest test; public static Xls_Reader xls; @BeforeClass public void Initialize() { if(pro==null) { pro=new Properties(); File file = new File(System.getProperty("user.dir")+"/src/main/resources/projectConfig.properties"); try { FileInputStream fileInputStream = new FileInputStream(file); pro.load(fileInputStream); if(xls==null) { xls=new Xls_Reader(System.getProperty("user.dir")+"/dataSheets/"+pro.getProperty("testDataSheetName")); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } @SuppressWarnings("resource") public void openBrowser(String browserType) { if(browserType.equalsIgnoreCase("chrome")) { System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"//drivers//chromedriver.exe"); driver=new ChromeDriver(); test.log(Status.INFO, "chrome browser is opening"); } else { System.setProperty("webdriver.gecko.driver", System.getProperty("user.dir")+"//drivers//geckodriver.exe"); driver=new FirefoxDriver(); test.log(Status.INFO, "firefox browser is opening"); } driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); driver.manage().window().maximize(); } public void navigate(String urlKey) { driver.get(pro.getProperty(urlKey)); test.log(Status.INFO, "navigating to "+pro.getProperty(urlKey)); } public void click(String elementKey) { getElement(elementKey).click(); test.log(Status.INFO, "clicking on "+pro.getProperty(elementKey)); } public void type(String elementXpath,String data) { getElement(elementXpath).sendKeys(data); test.log(Status.INFO, "typing in "+pro.getProperty(elementXpath)+" and entering "+data+" as input"); } public WebElement getElement(String elementXpath) { WebElement findElement=null; try { findElement= driver.findElement(By.xpath(pro.getProperty(elementXpath))); test.log(Status.INFO, "finding "+pro.getProperty(elementXpath)); } catch (Exception e) { test.log(Status.ERROR, "webelement name "+pro.getProperty(elementXpath)+" did not find"); //log exception Assert.fail(); } return findElement; } /***********************************validations****************************/ public boolean verifyTitle() { return false; } public boolean isElementPresent(String elementXpath) { int size = driver.findElements(By.xpath(pro.getProperty(elementXpath))).size(); test.log(Status.INFO, "checking "+pro.getProperty(elementXpath)); if(size>0) { test.log(Status.INFO,pro.getProperty(elementXpath)+" element found"); return true; } { test.log(Status.ERROR,pro.getProperty(elementXpath)+" element DID NOT FIND"); return false; } } /**********************************reporting****************************************/ public void pass() { //log pass } public void fail() { //log fail } public void takesScreenshot() { Date date=new Date(); String fileName=date.toString().replace(":", "-").replace(" ","-")+".png"; File sourceFile=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); try { FileHandler.copy(sourceFile, new File(ExtentManager.screenshotFolderPath+fileName)); test.log(Status.INFO, "screenshot->"+test.addScreenCaptureFromPath(ExtentManager.screenshotFolderPath+fileName)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /***************************finishing**********************************************/ @AfterMethod public void ending() { if(extent!=null) { extent.flush(); } if(driver!=null) { test.log(Status.INFO, "closing the browser"); driver.close(); } } public void waitForPageToLoad() { JavascriptExecutor js=(JavascriptExecutor)driver; String status = (String)js.executeScript("return document.readyState"); test.log(Status.INFO, "waiting the page to completely load"); while(!status.equalsIgnoreCase("complete")) { try { Thread.sleep(3000); status = (String)js.executeScript("return document.readyState"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void timeToWait(int timeInSeconds) { try { Thread.sleep(timeInSeconds*1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /***********************************App methods****************************/ public void zohoLogin(String userName,String password) { driver.get(pro.getProperty("zohoHomePage")); driver.findElement(By.xpath(pro.getProperty("zohoLogin"))).click(); test.log(Status.INFO, "login button clicked"); waitForPageToLoad(); type("zohoUserName",userName); driver.findElement(By.xpath(pro.getProperty("userNameNext"))).click(); type("password",password); driver.findElement(By.xpath(pro.getProperty("singInButton"))).click(); waitForPageToLoad(); driver.findElement(By.xpath(pro.getProperty("crm"))).click(); waitForPageToLoad(); } public void zohoLogout() { click("zohoSignOut1"); waitForPageToLoad(); click("zohoSignOut2"); } }