language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Python
UTF-8
3,174
3.609375
4
[]
no_license
import speech_recognition as sr #this module is for recognizing the voice of the user import pyttsx3 #text to speech version 3 module import pywhatkit #this module is to search on youtube import datetime #this module is to show date and time import wikipedia #this module is to search from wikipedia import pyjokes #this module is to show jokes listener = sr.Recognizer() #listener will listen to the voice and recognize the voice engine = pyttsx3.init() #engine variable will speak to user and initialize the engine voices = engine.getProperty('voices') #to get the voice of the female engine.setProperty('voice', voices[1].id) #to set the voice of the female def talk(text): #repeat the commands given by the user engine.say(text) engine.runAndWait() def take_command(): #take commands from alexa and user want to do some work using the alexa try : with sr.Microphone() as source : #source of our audio print("listening.......") voice = listener.listen(source) #voice variable listen to the source of the audio #command variable will listen to the voice to the google api and google will return you the text command = listener.recognize_google(voice) command = command.lower() if 'alexa' in command: command = command.replace("alexa"," ") #alexa will be removed from the string talk(command) except : #does nothing pass return command def run_alexa(): #take the command and run the alexa command = take_command() print(command) if 'play' in command: #play a song song = command.replace("play"," ") #play will be removed from the string talk("playing"+song) pywhatkit.playonyt(song) #playonyt means play on youtube elif 'time' in command : time = datetime.datetime.now().strftime('%I:%M %p') #shows the current time in AM or PM talk('Current time is :' + time) print(time) elif 'who is' in command: person = command.replace("who is"," ") #who is will removed from the string info = wikipedia.summary(person,1) #search from wikipedia print(info) talk(info) elif 'date' in command: talk('sorry,I have a headache') elif 'what is your name' in command: talk('My name is Alexa') elif 'are you single' in command: talk('I am in a relationship with WiFi') elif 'joke' in command: talk(pyjokes.get_joke()) elif 'who created you' in command: talk('i was created by Mahak Kushwah') elif 'how are you' in command: talk("I am fine,Thank you") talk('How are you') elif 'fine' in command: talk('Its is good to know that you are fine') elif 'exit' in command: #exit the alexa talk('Thank for giving me the time') exit() else : talk("Please say the command again....") while True: run_alexa()
Java
UTF-8
655
1.921875
2
[]
no_license
package com.uss.convertorapp.models; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.uss.convertorapp.enums.Bases; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import java.math.BigDecimal; /** * Entity uses for rate response. * * @author Iurii Geto */ @Getter @Setter @Builder @AllArgsConstructor @NoArgsConstructor public class ConversionResource { private Bases from; private Bases to; private BigDecimal amount; private BigDecimal converted; }
JavaScript
UTF-8
630
2.953125
3
[]
no_license
const axios = require("axios"); const cheerio = require("cheerio"); async function main() { let totalImg = 0; let imgAlt = 0; let response = await axios.get("https://en.wikipedia.org/wiki/Penguin"); let page = response.data; let $ = cheerio.load(page, { xml: { normalizeWhitespace: true, }, }); $("img").each(function () { totalImg++; let image = $(this); console.log($.html(image) + "\n"); if (image.attr("alt") || image.attr("alt") === "") { imgAlt++; } }); console.log( `${imgAlt} out of ${totalImg} total images have alternative descriptions` ); } main();
Java
UTF-8
2,508
3.734375
4
[]
no_license
package RoadTo1K; import java.util.HashMap; public class lt465minTransfers { class Solution { /* [[0,1,10], [2,0,5]] 0->1 $10 2->0 $5 [[0,1,10], [1,0,1], [1,2,5], [2,0,5]] 0->1 $10 1->0 $1 0->1 $10 - 1 = 9 1->2 $5 2->0 $5 好像可以通过input来建立一个人的所有外债的合,然后通过债务归并的思想来实现, 我们把当前债务归并给后面的任意一个人,但是要注意这个人一定是balance相反的,来看之后需要的债务的settle要多少次+1, 然后要注意当前没有债务的人要跳过,如果当前债务人已经到最后了,返回0,表示不要再额外的settle了 */ public int minTransfers(int[][] transactions) { HashMap<Integer, Integer> map = new HashMap<>(); for(int[] transaction : transactions){ int giver = transaction[0]; int taker = transaction[1]; int amount = transaction[2]; map.put(giver, map.getOrDefault(giver, 0) + amount); map.put(taker, map.getOrDefault(taker, 0) - amount); } int[] debts = new int[map.size()]; int idx = 0; for(int debt : map.values()){ debts[idx++] = debt; } return getMinTransfers(debts, 0); } /* 假设0~i-1 person的外债归并完了,对于i~n来说,getMinTransfer能求得最小的settle的次数使得balance平衡 */ private int getMinTransfers(int[] debts, int cur){ //cur没外债 // while(cur < debts.length && debts[cur] == 0){ // cur++; // } if(cur == debts.length){ return 0; } //cur 没外债 if(debts[cur] == 0){ return getMinTransfers(debts, cur + 1); } int min = Integer.MAX_VALUE; for(int i = cur + 1; i < debts.length; i++){ if(debts[i] * debts[cur] < 0){ //债务相反,试着归并 debts[i] += debts[cur]; //把当前的债务跟后面其中的一个人归并 min = Math.min(min, getMinTransfers(debts, cur + 1) + 1); //然后看剩下的债务要多少归并法 debts[i] -= debts[cur]; } } return min; } } }
Java
UTF-8
939
2.921875
3
[]
no_license
package database; public class PrimaryCell { private int fno; private int cid; private int lac; private String name; public PrimaryCell(){} public int getFno() { return fno; } public void setFno(int fno) { this.fno = fno; } public int getCid() { return cid; } public void setCid(int cid) { this.cid = cid; } public int getLac() { return lac; } public void setLac(int lac) { this.lac = lac; } public String getName() { return name; } public void setName(String name) { this.name = name; } public PrimaryCell(int fno ,int cid, int lac, String name) { super(); this.fno = fno; this.cid = cid; this.lac = lac; this.name = name; } //getters & setters @Override public String toString() { return "PrimaryCell [fno=" + fno + ", cid=" + cid + ", lac=" + lac +", name="+name + "]"; } }
C++
UTF-8
1,561
2.625
3
[]
no_license
#include "integrators/whitted.h" vec3 Whitted::Li(std::shared_ptr<Ray> ray, std::shared_ptr<Sampler> sampler, Scene &scene) { vec3 L(0); HitInfo p; // Find closest ray interaction or return background if (!scene.Intersect(ray, p)) { // Background color L = vec3(0, 0.2, 0.3); return L; } // TODO Add emitted light of object // Lighting params float ambient = 0.2; float diffuseStrength = 0.8; float specularStrength = 1; // Add contribution of each light source for (int i = 0; i < scene.lights.size(); i++) { vec3 wi; // Direction to light source vec3 Li = scene.lights[i]->SampleLi(p, wi); // Attenuated light float pdf = 1 / float(scene.lights.size()); // Light sample probability // TODO Implement BSDF // Apply diffuse lighting float diffuse = glm::dot(wi, p.normal) * diffuseStrength; // Apply specular reflection int shininess = 32; vec3 halfwayVector = glm::normalize(wi + -ray->direction()); float specularAngle = std::max(glm::dot(p.normal, halfwayVector), 0.0f); float specular = std::pow(specularAngle, shininess) * specularStrength; L += Li * (ambient + diffuse + specular) * pdf; } // If shadow ray hits nothing vec3 objectColor = vec3(0.9, 0.2, 0.2); L *= objectColor; L.r = std::min(L.r, 1.0f); L.g = std::min(L.g, 1.0f); L.b = std::min(L.b, 1.0f); // TODO Implement reflected rays return L; }
Python
UTF-8
1,053
3.375
3
[]
no_license
s = '''A computer is a machine that can be programmed to carry out sequences of arithmetic or logical operations automatically. Modern computers can perform generic sets of operations known as programs. These programs enable computers to perform a wide range of tasks. A computer system is a complete computer that includes the hardware operating system main software and peripheral equipment needed and used for full operation. This term may also refer to a group of computers that are linked and function together''' s2 = '''A broad range of industrial and consumer products use computers as control systems. Simple special-purpose devices like microwave ovens and remote controls are included, as are factory devices like industrial robots and computer-aided design, as well as general-purpose devices like personal computers and mobile devices like smartphones. Computers power the Internet, which links hundreds of millions of other computers and users.''' s_set = set(s.split()) s2_set = set(s2.split()) print(s2_set.intersection(s_set))
Java
UTF-8
8,262
2.109375
2
[]
no_license
package Testcase; import static org.junit.Assert.fail; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.junit.BeforeClass; import org.junit.Test; import org.openqa.selenium.By; import com.Core.BaseClass; import com.Core.CommFunc; import com.csvreader.CsvReader; import TestScript.ControlsStockTS; import java.nio.charset.Charset; /** * @author Lili.Sun * @date 2015年6月9日 上午10:53:53 * */ public class ControlsStockTest extends BaseClass{ private static final Logger log = LoggerFactory.getLogger(ControlsStockTest.class); @BeforeClass public static void testAddStock() throws Exception { ControlsStockTS.addStock(driver); } @Test public void testInputBox() throws Exception { log.info("***Run case of testInputBox.***"); PrintFlag = true; //输入框测试 try { String filePath = CommFunc.getTestDataFile(); CsvReader reader = new CsvReader(filePath,',',Charset.forName("UTF-8")); log.info(filePath); reader.readHeaders(); while (reader.readRecord()) { ControlsStockTS.controlsStock(driver, reader); } } catch (Exception e) { log.error("InputBox is error", e); e.printStackTrace(); fail("failure"); return; } PrintFlag = false; } @Test public void testDateControl() throws Exception { log.info("***Run case of testDateControl.***"); PrintFlag = true; //日期控件测试 try { CommFunc.highlightElement(driver,driver.findElement(By.xpath("//form[@id='modifyForm']/table/tbody/tr[2]/td[4]/span"))); driver.findElement(By.xpath("//form[@id='modifyForm']/table/tbody/tr[2]/td[4]/span")).click(); driver.findElement(By.xpath("//iframe[@border='0']")); driver.switchTo().frame(driver.findElement(By.xpath("//iframe[@border='0']"))); CommFunc.highlightElement(driver,driver.findElement(By.id("dpTodayInput"))); driver.findElement(By.id("dpTodayInput")).click(); driver.switchTo().defaultContent(); driver.switchTo().frame("ifrf"); } catch (Exception e) { log.error("DateControl is error", e); e.printStackTrace(); fail("failure"); return; } PrintFlag = false; } @Test public void testMultiSelect() throws Exception { log.info("***Run case of testMultiSelect.***"); PrintFlag = true; //多选下拉框测试 try { CommFunc.highlightElement(driver,driver.findElement(By.xpath("//form[@id='modifyForm']/table/tbody/tr[3]/td[4]/span/span/a"))); driver.findElement(By.xpath("//form[@id='modifyForm']/table/tbody/tr[3]/td[4]/span/span/a")).click(); CommFunc.highlightElement(driver,driver.findElement(By.xpath("//div[@id='_easyui_combobox_i5_2']"))); driver.findElement(By.xpath("//div[@id='_easyui_combobox_i5_2']")).click(); CommFunc.highlightElement(driver,driver.findElement(By.xpath("//div[@id='_easyui_combobox_i5_6']"))); driver.findElement(By.xpath("//div[@id='_easyui_combobox_i5_6']")).click(); CommFunc.highlightElement(driver,driver.findElement(By.xpath("//form[@id='modifyForm']/table/tbody/tr[4]/td[2]/span/input"))); driver.findElement(By.xpath("//form[@id='modifyForm']/table/tbody/tr[4]/td[2]/span/input")).clear(); driver.findElement(By.xpath("//form[@id='modifyForm']/table/tbody/tr[4]/td[2]/span/input")).sendKeys("15.9"); } catch (Exception e) { log.error("MultiSelect is error", e); e.printStackTrace(); fail("failure"); return; } PrintFlag = false; } @Test public void testSingleSelect() throws Exception { log.info("***Run case of testSingleSelect.***"); PrintFlag = true; //单选框下拉测试 try { CommFunc.highlightElement(driver,driver.findElement(By.xpath("//form[@id='modifyForm']/table/tbody/tr[4]/td[4]/span/span/a"))); driver.findElement(By.xpath("//form[@id='modifyForm']/table/tbody/tr[4]/td[4]/span/span/a")).click(); CommFunc.highlightElement(driver,driver.findElement(By.xpath("//div[@id='_easyui_combobox_i6_1']"))); driver.findElement(By.xpath("//div[@id='_easyui_combobox_i6_1']")).click(); } catch (Exception e) { log.error("SingleSelect is error", e); e.printStackTrace(); fail("failure"); return; } PrintFlag = false; } @Test public void testMultiSelectTree() throws Exception { log.info("***Run case of testMultiSelectTree.***"); PrintFlag = true; //多选树测试 try { CommFunc.highlightElement(driver,driver.findElement(By.xpath("//div[@id='modify_div_AREA']"))); driver.findElement(By.xpath("//div[@id='modify_div_AREA']")).click(); Thread.sleep(1000); CommFunc.highlightElement(driver,driver.findElement(By.xpath("//div[@id='_easyui_tree_2']/span[@class='tree-checkbox tree-checkbox0']"))); driver.findElement(By.xpath("//div[@id='_easyui_tree_2']/span[@class='tree-checkbox tree-checkbox0']")).click(); CommFunc.highlightElement(driver,driver.findElement(By.xpath("//div[@id='_easyui_tree_3']/span[@class='tree-checkbox tree-checkbox0']"))); driver.findElement(By.xpath("//div[@id='_easyui_tree_3']/span[@class='tree-checkbox tree-checkbox0']")).click(); CommFunc.highlightElement(driver,driver.findElement(By.xpath("//div[@class='panel window'][2]"))); //driver.findElement(By.xpath("//div[@class='panel window'][2]")).click(); CommFunc.highlightElement(driver,driver.findElement(By.xpath("//div[@id='dia_modify_t_AREA']/div/table/tbody/tr[2]/td[2]/input[@id='selectTo']"))); driver.findElement(By.xpath("//div[@id='dia_modify_t_AREA']/div/table/tbody/tr[2]/td[2]/input[@id='selectTo']")).click(); CommFunc.highlightElement(driver,driver.findElement(By.xpath("//div[@class='panel window'][2]/div[@class='dialog-button']/a/span/span"))); driver.findElement(By.xpath("//div[@class='panel window'][2]/div[@class='dialog-button']/a/span/span")).click(); } catch (Exception e) { log.error("MultiSelectTree is error", e); e.printStackTrace(); fail("failure"); return; } PrintFlag = false; } @Test public void testSingleSelectTree() throws Exception { log.info("***Run case of testSingleSelectTree.***"); PrintFlag = true; //单选树测试 try { CommFunc.highlightElement(driver,driver.findElement(By.xpath("//div[@id='modify_div_DEPARTMENT']"))); driver.findElement(By.xpath("//div[@id='modify_div_DEPARTMENT']")).click(); CommFunc.highlightElement(driver,driver.findElement(By.xpath("//div[@class='panel window'][2]"))); driver.findElement(By.xpath("//div[@class='panel window'][2]")).click(); CommFunc.highlightElement(driver,driver.findElement(By.xpath("//div[@id='dia_modify_t_DEPARTMENT']/div[@class='tablecontent']/table/tbody/tr[2]/td/ul/li/ul/li"))); driver.findElement(By.xpath("//div[@id='dia_modify_t_DEPARTMENT']/div[@class='tablecontent']/table/tbody/tr[2]/td/ul/li/ul/li")).click(); CommFunc.highlightElement(driver,driver.findElement(By.xpath("//div[@id='dia_modify_t_DEPARTMENT']/div[@class='tablecontent']/table/tbody/tr[2]/td/ul/li/ul/li/ul/li"))); driver.findElement(By.xpath("//div[@id='dia_modify_t_DEPARTMENT']/div[@class='tablecontent']/table/tbody/tr[2]/td/ul/li/ul/li/ul/li")).click(); CommFunc.highlightElement(driver,driver.findElement(By.xpath("//div[@id='dia_modify_t_DEPARTMENT']/div[@class='tablecontent']/table/tbody/tr[2]/td/ul/li/ul/li/ul/li/ul/li"))); driver.findElement(By.xpath("//div[@id='dia_modify_t_DEPARTMENT']/div[@class='tablecontent']/table/tbody/tr[2]/td/ul/li/ul/li/ul/li/ul/li")).click(); CommFunc.highlightElement(driver,driver.findElement(By.xpath("//div[@id='dia_modify_t_DEPARTMENT']/div/table/tbody/tr[2]/td[2]/input[@id='selectTo']"))); driver.findElement(By.xpath("//div[@id='dia_modify_t_DEPARTMENT']/div/table/tbody/tr[2]/td[2]/input[@id='selectTo']")).click(); CommFunc.highlightElement(driver,driver.findElement(By.xpath("//div[@class='panel window'][2]/div[@class='dialog-button']/a/span/span"))); driver.findElement(By.xpath("//div[@class='panel window'][2]/div[@class='dialog-button']/a/span/span")).click(); } catch (Exception e) { log.error("SingleSelectTree is error", e); e.printStackTrace(); fail("failure"); return; } PrintFlag = false; } }
C++
UTF-8
1,296
3.28125
3
[]
no_license
#include<functional> #include<vector> #include<cmath> #include"nonlinear_equation.h" double Halving(std::function<double(double)> f, double a, double b, double e1, double e2){ unsigned k = 0; double x = 0; while(true){ x = (a + b) / 2; double fx = f(x); if(std::abs(fx) < e1){ return x; } if(f(a) * f(x) < 0){ b = x; } else { a = x; } if(b - a <= e2){ return (a + b) / 2; } else { ++k; } } } double Relaxation(std::function<double(double)> f, std::function<double(double)> ff, double x, double e){ unsigned k = 0; double w = 0; double nx = 0; while(true){ w = 1 / (1 - ff(x)); nx = (1 - w) * x + w * f(x); if(std::abs(nx - x) < e){ return nx; } else { ++k; x = nx; } } } double Newton(std::function<double(double)> f, std::function<double(double)> ff, double x, double e){ unsigned k = 0; double nx = 0; while(true){ nx = x - f(x) / ff(x); if(std::abs(nx - x) < e){ return nx; } else { ++k; x = nx; } } }
C++
UTF-8
963
3.296875
3
[]
no_license
#include <iostream> #include <bits/unique_ptr.h> #include <vector> #include "circle.h" #include "cylinder.h" #include "rectangle.h" #include "parallelepiped.h" #include "rounded_rectangle.h" typedef std::vector<std::unique_ptr<shape>> shape_uptr; void get_data(const shape_uptr& shapes); int main() { char red[4] = "Red"; char blue[5] = "Blue"; shape_uptr shapes; shapes.push_back(std::make_unique<circle>(red, 2)); shapes.push_back(std::make_unique<cylinder>(blue, 3, 4)); shapes.push_back(std::make_unique<rectangle>(blue, 3, 3)); shapes.push_back(std::make_unique<parallelepiped>(blue, 13, 15, 22)); shapes.push_back(std::make_unique<rounded_rectangle>(red, 13, 15, 2)); get_data(shapes); return 0; } void get_data(const shape_uptr& shapes) { for (auto& s : shapes) { std::cout << "Colour\t" << s->get_colour() << "\t\tarea: " << s->get_area() << "\n"; } }
Python
UTF-8
263
2.96875
3
[]
no_license
A = [2] B = [1,3] class Solution: def fairCandySwap(self, A: List[int], B: List[int]) -> List[int]: s = (sum(A) - sum(B))//2 A = set(A) B = set(B) for i in B: if i + s in A: return [i+s,i]
Python
UTF-8
5,538
2.75
3
[ "MIT" ]
permissive
import unittest import numpy as np from taivasnet.layers import Softmax, Linear, ReLU, Dropout from taivasnet.losses import CrossEntropy from .gradientchecker import GradientChecker __author__ = 'Aki Rehn' __project__ = 'taivasnet' class TestLinear(unittest.TestCase): """ Test linear layer functionality """ def setUp(self): # initialize linear layer with 10 inputs and 3 outputs self.linear = Linear(10, 3) def test_forward(self): # test values from pytorch implementation self.linear.weights = np.array([ [-0.1679, 0.0930, -0.0913, -0.0347, -0.3040, -0.1508, 0.1716, -0.0769, 0.3150, 0.2535], [-0.0148, -0.2111, 0.1926, 0.0981, -0.2044, 0.2054, 0.1920, 0.2805, -0.1773, -0.0521], [-0.0061, 0.0462, -0.2400, -0.2244, 0.1720, -0.0742, 0.1545, 0.0180, 0.1038, 0.0695]]).T self.linear.bias = np.array([ 0.1150, 0.1568, -0.2929]) inputs = np.array([ [-1.5256, -0.7502, -0.6540, -1.6095, -0.1002, -0.6092, -0.9798, -1.6091, -0.7121, 0.3037], [-0.7773, -0.2515, -0.2223, 1.6871, -0.3206, -0.2993, 1.8793, -0.0721, 0.1578, -0.7735], [ 0.1991, 0.0457, -1.3924, 2.6891, -0.1110, 0.2927, -0.1578, -0.0288, 2.3571, -1.0373]]) correct = np.array([ [ 0.3474, -0.5798, -0.0053], [ 0.5082, 0.7010, -0.4063], [ 0.5640, -0.1794, -0.4543]]) result = self.linear.forward(inputs) self.assertTrue(np.allclose(result, correct, atol=1e-3), msg="Linear layer forward pass works") def test_backward(self): """ Test backpropagation using gradient checking """ # error tolerance epsilon = 1e-12 inputs = np.random.randn(10, 6) weights = np.random.randn(6, 5) bias = np.random.randn(5) grad_output = np.random.randn(10, 5) linear = Linear(60, 5) linear.weights, linear.bias = weights, bias grad_inputs_numerical = GradientChecker.eval_numerical_gradient_array( lambda x: linear.forward(inputs), inputs, grad_output) grad_weights_numerical = GradientChecker.eval_numerical_gradient_array( lambda x: linear.forward(inputs), weights, grad_output) grad_bias_numerical = GradientChecker.eval_numerical_gradient_array( lambda x: linear.forward(inputs), bias, grad_output) grad_inputs, grad_weights, grad_bias = linear.backward(grad_output) self.assertTrue(np.allclose(grad_inputs, grad_inputs_numerical, rtol=epsilon), msg="Linear grad_inputs works") self.assertTrue(np.allclose(grad_weights, grad_weights_numerical, rtol=epsilon), msg="Linear grad_weights works") self.assertTrue(np.allclose(grad_bias, grad_bias_numerical, rtol=epsilon), msg="Linear grad_bias works") class TestSoftmax(unittest.TestCase): """ Test Softmax functionality """ def setUp(self): self.softmax = Softmax() self.cross_entropy = CrossEntropy() def test_forward1(self): correct = np.array([[0.26894142, 0.73105858]]) data = np.array([[1., 2.]]) result = self.softmax.forward(data) self.assertTrue(np.allclose(result, correct), msg="Softmax forward1 works") def test_forward2(self): correct = np.array([[0.84203357, 0.04192238, 0.00208719, 0.11395685]]) data = np.array([[5., 2., -1, 3]]) result = self.softmax.forward(data) self.assertTrue(np.allclose(result, correct), msg="Softmax forward2 works") class TestReLU(unittest.TestCase): """ Test ReLU functionality """ def setUp(self): self.relu = ReLU() def test_forward1(self): data = np.random.randn(5, 5) # make sure at least one negative value exists data[0, 0] = -5 output = self.relu.forward(data) self.assertFalse(output[output < 0].any(), msg="ReLU forward1 works") def test_forward2(self): data = np.random.randn(10, 10) output = self.relu.forward(data) self.assertFalse(output[output < 0].any(), msg="ReLU forward2 works") def test_backward(self): """ Test backpropagation using gradient checking """ # error tolerance epsilon = 1e-12 x = np.random.randn(3, 2, 8, 8) grad_output = np.random.randn(3, 2, 8, 8) grad_numerical = GradientChecker.eval_numerical_gradient_array(lambda x: self.relu.forward(x), x, grad_output) output = self.relu.forward(x) grad = self.relu.backward(grad_output) self.assertTrue(np.allclose(grad, grad_numerical, rtol=epsilon), msg="ReLU backward works") class TestDropout(unittest.TestCase): """ Test Dropout layer functionality """ def test_forward1(self): # probability of dropping inputs p = 0.7 data = np.random.randn(10, 50) dropout = Dropout(p=p) output = dropout.forward(data) zeros = output[output == 0] pct = zeros.size / data.size self.assertTrue(np.isclose(pct, p, rtol=1e-1), msg="Dropout forward1 works") def test_forward2(self): # probability of dropping inputs p = 0.2 data = np.random.randn(40, 30) dropout = Dropout(p=0.2) output = dropout.forward(data) zeros = output[output == 0] pct = zeros.size / data.size self.assertTrue(np.isclose(pct, p, rtol=1e-1), msg="Dropout forward2 works")
Java
UTF-8
10,723
2.0625
2
[]
no_license
package com.eeduspace.report.service.impl; import com.eeduspace.report.dao.ReportDao; import com.eeduspace.report.model.GradeTotalModel; import com.eeduspace.report.po.ReportPo; import com.eeduspace.report.service.ReportService; import com.google.common.collect.Lists; import org.apache.commons.beanutils.BeanUtils; import org.hibernate.SQLQuery; import org.hibernate.transform.Transformers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Query; import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.Map; /** * <p>描述</p> * * @Author zhuchaowei * e-mail:zhuchaowei@e-eduspace.com * Date: 2017/3/17 9:31 **/ @Service public class ReportServiceImpl implements ReportService { @Autowired private ReportDao reportDao; @Autowired private EntityManagerFactory emf; @Override public ReportPo save(ReportPo reportPo) { return reportDao.save(reportPo); } @Override public ReportPo findByMakePaperRecordCode(String makePaperRecordCode) { return reportDao.findByMakePaperRecordCode(makePaperRecordCode); } /** * 按学生分组查询全学科总分 * * @param releaseExamCode 考试发布code * @return * @throws Exception */ @Override public List<GradeTotalModel> getTotalScoreByGrade(String releaseExamCode) throws Exception { { String sql = "SELECT\n" + "\tre.release_code,\n" + "\tre.release_name,\n" + "\te.grade_code,\n" + "\te.grade_name,\n" + "\te.user_code,\n" + "\te.user_name,\n" + " e.class_code,\n" + "e.class_name,\n" + "\tsum(r.score) AS totalscore, \n" + "re.total_score AS allscore \n" + "FROM\n" + "\tedu_release_exam re,\n" + "\tedu_exam e,\n" + "\tedu_report r\n" + "WHERE\n" + "\tre.`code` = e.release_exam_code\n" + "AND e.`code` = r.exam_code\n" + "AND re.`release_code` = ?1\n" + "GROUP BY\n" + "\te.user_code ORDER BY e.class_code asc "; EntityManager em = emf.createEntityManager(); try { Query query = em.createNativeQuery(sql); query.setParameter(1, releaseExamCode); SQLQuery nativeQuery = query.unwrap(SQLQuery.class); // 设置返回值类型 nativeQuery.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); List<GradeTotalModel> totalScores = Lists.newArrayList(); List<Map<String, Object>> mapResult = nativeQuery.list(); mapResult.forEach(map -> { GradeTotalModel model = new GradeTotalModel(); try { BeanUtils.populate(model, map); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } totalScores.add(model); }); return totalScores; } catch (Exception e) { e.printStackTrace(); throw new Exception("sql异常----》" + sql); } finally { em.close(); } } } /** * 按班级分组查询所有学生的平均分 * * @param releaseExamCode 考试发布code * @return * @throws Exception */ @Override public List<GradeTotalModel> getAvgScoreByClass(String releaseExamCode) throws Exception { String sql = "SELECT\n" + "\tre.release_code,\n" + "\tre.release_name,\n" + " e.class_code,\n" + " e.class_name,\n" + " e.subject_code,\n" + " e.subject_name,\n" + " SUM(r.score) as sumscore,\n" + " COUNT(e.user_code) usercount,\n" + "\tAVG(r.score) AS avgscore\n" + "FROM\n" + "\tedu_release_exam re,\n" + "\tedu_exam e,\n" + "\tedu_report r\n" + "WHERE\n" + "\tre.`code` = e.release_exam_code\n" + "AND e.`code` = r.exam_code\n" + "AND re.`release_code` = ?1\n" + "GROUP BY e.class_code,e.subject_code ORDER BY e.class_code asc "; // System.out.println(sql); EntityManager em = emf.createEntityManager(); try { Query query = em.createNativeQuery(sql); query.setParameter(1, releaseExamCode); SQLQuery nativeQuery = query.unwrap(SQLQuery.class); // 设置返回值类型 nativeQuery.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); List<GradeTotalModel> knowledgeModels = Lists.newArrayList(); List<Map<String, Object>> mapResult = nativeQuery.list(); mapResult.forEach(map -> { GradeTotalModel model = new GradeTotalModel(); try { BeanUtils.populate(model, map); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } knowledgeModels.add(model); }); return knowledgeModels; } catch (Exception e) { e.printStackTrace(); throw new Exception("sql异常----》" + sql); } finally { em.close(); } } /** * 全年级,各学科优秀,及格人数占比 * @param releaseExamCode 考试发布code * @return * @throws Exception */ @Override public List<GradeTotalModel> getPassingByGrade(String releaseExamCode) throws Exception { String sql = "SELECT count(\n" + "\t\tCASE\n" + "\t\tWHEN b.high_account >= 85 THEN\n" + "\t\t\tb.high_account\n" + "\t\tEND\n" + "\t) AS excellent_count,\n" + "\tcount(\n" + "\t\tCASE\n" + "\t\tWHEN b.high_account >= 60 THEN\n" + "\t\t\tb.high_account\n" + "\t\tEND\n" + "\t) AS passing_count,\n" + "\tb.subject_code\n" + "FROM\n" + "\t(\n" + "\t\tSELECT\n" + "\t\t\tROUND(\n" + "\t\t\t\ta.stu_score / a.total_score * 100,\n" + "\t\t\t\t2\n" + "\t\t\t) AS high_account,\n" + "\t\t\ta.subject_code\n" + "\t\tFROM\n" + "\t\t\t(\n" + "\t\t\t\tSELECT\n" + "\t\t\t\t\terp.paper_score AS total_score,\n" + "\t\t\t\t\tSUM(erp.score) AS stu_score,\n" + "\t\t\t\t\te.user_code,\n" + "\t\t\t\t\te.user_name,\n" + "\t\t\t\t\te.subject_code\n" + "\t\t\t\tFROM\n" + "\t\t\t\t\tedu_release_exam er,\n" + "\t\t\t\t\tedu_exam e,\n" + "\t\t\t\t\tedu_student_subject_score erp\n" + "\t\t\t\tWHERE\n" + "\t\t\t\t\ter.`code` = e.release_exam_code\n" + "\t\t\t\tAND e.`code` = erp.exam_code\n" + "\t\t\t\tAND er.release_code = ?1\n" + "\t\t\t\tGROUP BY\n" + "\t\t\t\t\te.user_code,\n" + "\t\t\t\t\te.subject_code\n" + "\t\t\t) a\n" + // "\t\tGROUP BY\n" + // "\t\t\ta.subject_code\n" + "\t) b\n" + "GROUP BY\n" + "\tb.subject_code "; // System.out.print(sql); EntityManager em = emf.createEntityManager(); try { Query query = em.createNativeQuery(sql); query.setParameter(1, releaseExamCode); SQLQuery nativeQuery = query.unwrap(SQLQuery.class); // 设置返回值类型 nativeQuery.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); List<GradeTotalModel> passinglist = Lists.newArrayList(); List<Map<String, Object>> mapResult = nativeQuery.list(); mapResult.forEach(map -> { GradeTotalModel model = new GradeTotalModel(); try { BeanUtils.populate(model, map); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } passinglist.add(model); }); return passinglist; } catch (Exception e) { e.printStackTrace(); throw new Exception("sql异常----》" + sql); } finally { em.close(); } } /** * 获取参加考试的学生数 * * @param releaseExamCode 考试发布code * @return * @throws Exception */ @Override public Integer getTotalPeople(String releaseExamCode) throws Exception { Integer count = 0; String sql = "select count( *)as count from(\n" + "SELECT\n" + "ee.user_code\n" + "FROM\n" + "\tedu_release_exam e,\n" + "\tedu_exam ee\n" + "WHERE\n" + "\te.`code` = ee.release_exam_code\n" + "AND e.release_code = ?1 \n" + "GROUP BY ee.user_code\n" + ") a"; EntityManager em = emf.createEntityManager(); try { Query query = em.createNativeQuery(sql); query.setParameter(1, releaseExamCode); Object ob = query.getSingleResult(); count = Integer.parseInt(ob.toString()); return count; } catch (Exception e) { e.printStackTrace(); throw new Exception("sql异常----》" + sql); }finally{ em.close(); } } }
Java
UTF-8
502
2.234375
2
[]
no_license
package ru.qaliti; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import java.util.List; public class Ul { private WebElement ulElement; private WebDriver driver; public Ul(WebElement ulElement, WebDriver driver){ this.ulElement = ulElement; this.driver = driver; } public List<WebElement> getLi(){ List<WebElement> li = ulElement.findElements(By.xpath(".//li")); return li; } }
JavaScript
UTF-8
372
2.953125
3
[]
no_license
class Person{ contructor(firstName, lastName, age){ this.firstName = firstName; this.lastName = lastName; this.age = age; } walk (distance); } class Student extends Person{ contructor(firstName, lastName, age, studID){ super((firstName, lastName, age); this.studID = studID; } enroll(){ } }
PHP
UTF-8
1,891
2.96875
3
[]
no_license
<html> <head> <style type="text/css"> h3 {color: yellow}; </style> </head> <body> <?php //This block insert the uploaded form information into Database called SudokuData. if (isset($_REQUEST["email"]) && isset($_REQUEST["name"]) && strcmp($_REQUEST["password1"], $_REQUEST["password2"])==0 ){ require_once("config/config.php"); if (!$sql){ //In the case that the SudokuData database has not been created, we create one and create the corresponding tables. mysql_query("CREATE DATABASE SudokuData", $con); mysql_select_db("SudokuData", $con); $new_table = "CREATE TABLE Records ( Series int NOT NULL AUTO_INCREMENT, PRIMARY KEY(Series), Name varchar(255), Email varchar(255), Password varchar(255), Score int, Quiz varchar(255), Ans varchar(255), Input varchar(255) )"; mysql_query($new_table, $con); } //Before we write the new information into our records, We must check that the email-address is unique: $result = mysql_query("SELECT * FROM Records"); while ($row = mysql_fetch_array($result)){ //Each time scan one row. if (strcmp($row['Email'], $_REQUEST["email"]) == 0){ die("<h3>Email address already exists.</h3>"); } } $encoded_password = sha1($_REQUEST["password1"]); //Before we put the password in, we must encode it. $new = "INSERT INTO Records (Name, Email, Password, Score) Values ('$_REQUEST[name]', '$_REQUEST[email]', '$encoded_password', 0)"; if (!mysql_query($new, $con)){ die('Error here: ' . mysql_error()); } echo " <h3> Congratulations! Your registration is successful!<br /> Welcome to the world of Sudoku, " . $_REQUEST["name"] . "! <br /> Click the log in button. Have fun :) </h3>"; mysql_close($con); } else { echo "<h3>Invalid form. Click Sign_up to try again.</h3>"; } ?> </body> </html>
Java
UTF-8
223
1.757813
2
[]
no_license
package cn.edu.ustc.springboot.repository; import cn.edu.ustc.springboot.domain.User; import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository<User,Integer> { }
Java
UTF-8
2,173
2.6875
3
[]
no_license
package iotwebsocketproxy.server; import javax.websocket.EndpointConfig; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import java.util.*; import java.util.concurrent.*; @ServerEndpoint(value = "/iotwebsocketproxy/{scope}/{deviceid}/{type}") public class IoTWebsocketProxy { private static Queue<Session> sessionQueue = new ConcurrentLinkedQueue<Session>(); @OnOpen public void onOpen(Session session, @PathParam("scope") String scope, @PathParam("deviceid") String deviceid, @PathParam("type") String type, EndpointConfig config) { sessionQueue.add(session); } @OnError public void error(Session session, Throwable t) { sessionQueue.remove(session); System.err.println("Error on session " + session.getId()); } @OnClose public void closedConnection(Session session) { sessionQueue.remove(session); System.out.println("session closed: " + session.getId()); } @OnMessage public void onMessage(Session session, String msg, @PathParam("scope") String scope, @PathParam("deviceid") String deviceid, @PathParam("type") String type) { sendAll(msg, deviceid, type, session.getId()); } private static void sendAll(String msg, String deviceid, String type, String sessionId) { String msgExtended = msg; try { ArrayList<Session> closedSessions = new ArrayList<>(); Session callingSession = null; for (Session session : sessionQueue) { if (!session.isOpen()) { System.err.println("Closed session: " + session.getId()); closedSessions.add(session); } else { if(session.getId().equals(sessionId)){ callingSession = session; }else{ session.getBasicRemote().sendText(msgExtended); } } } sessionQueue.removeAll(closedSessions); System.out.println("Sending " + msg + " to " + sessionQueue.size() + " clients"); if(callingSession != null){ callingSession.getBasicRemote().sendText("Data has been processed"); } } catch (Throwable e) { e.printStackTrace(); } } }
Python
UTF-8
11,814
2.875
3
[]
no_license
#!/usr/bin/python3 #Author: Matthew Yu #templateTest.py #history: #as of 6/6/18, template currently matches solid note heads of Accumula Town and #Floaroma Town with an acc around ~95%. #as of 6/8/18, template matches solid note heads, hollow note heads, sharps, flats, #and naturals, as well as full size clefs with good accuracy #naturals can tend to be found accidentally in unexpected places. #TODO: adjust threshold for best results, test with more sheet music #add rests, dots, classify staff separation #begin horizontal line checking to start assessing pitch #begin merging with readSheetMusV1/V2.py import cv2 import numpy as np import copy MAX_CENTERS = 100 font = cv2.FONT_HERSHEY_SIMPLEX def nothing(x): pass #init sheetname = "./sheet_music/SS_Anne"#"Floaroma_Town"#"Accumula_Town" # img_sheet_music = cv2.imread(sheetname + '.jpg') #if wrong size, resize shape = np.shape(img_sheet_music) if shape[0] != 1700 or shape[1] != 2200: img_sheet_music = cv2.resize(img_sheet_music, (1700, 2200)) #width, height #canvas program uses to determine objects img_gray = cv2.cvtColor(img_sheet_music, cv2.COLOR_BGR2GRAY) #function findObjects takes a template and attempts to find a list of locations of #objects that match the template in an image. #param: w - width of the template #param: h - height of the template #param: template - template object to find #param: threshold - change threshold value to affect how well object is found #param: first - boolean run through each pass to determine if lists are found #optional param: left - leftmost position to identify objects #optional param: top - topmost position to identify objects #optional param: src - image source to find objects #optional param: dst - image dst to display found objects #implied param, return: X - reference of list of X coordinates of found objects #implied param, return: Y - reference of list of Y coordinates of found objects #implied param, return: type - reference of list of types of found objects def findObjects(X, Y, type, w, h, objType, template, threshold, first, left = 0, top = 0, src = img_gray, dst = img_sheet_music): #get location of object res = cv2.matchTemplate(src, template, cv2.TM_CCOEFF_NORMED) loc = np.where( res >= threshold) if loc is not None: for pt in sorted(zip(*loc[::-1]), key = lambda x:x[0]): #for each pt determine center, compare to within range of other centers #get (X,Y) nX = pt[0] nY = pt[1] if nX > left and nY > top - 10: #if first entry if first is True: X.append(nX) Y.append(nY) type.append(objType) cv2.rectangle(dst, pt, (nX + w, nY + h), (255, 0, 0), 2) first = False #if not first entry else: #go through X and Y, and check dist key = True for coord in zip(X, Y): #if too close in X or Y dir, exclude; else add to arr and draw dX = abs(coord[0] - nX) dY = abs(coord[1] - nY) if dX < 10 and dY < 10: key = False break if key is True: X.append(nX) Y.append(nY) type.append(objType) #if in range, ignore, else draw cv2.rectangle(dst, pt, (nX + w, nY + h), (255, 0, 0), 1) return first #step 1: preprocessing/Staff Lines #identifying and removing staff bars in order to clarify image #removing staff bars is optional. TODO: find way to remove spaces without #compromising quality after removing bars lines = [] for i in range(2200): count = 0 for j in range(1700): if img_gray[i, j] < 200: count += 1 #print("row", i, ":", count) cv2.line(img_sheet_music, (0,i), (count, i), (255, 0, 0), 1) #if line is found, add to list if count > 1000: lines.append(i) #remove lines that are duplicate within row range slines = [] for idx in range(0, len(lines)): if abs(lines[idx]-lines[idx-1]) > 8: slines.append(lines[idx]) cv2.line(img_sheet_music, (0,lines[idx]), (100, lines[idx]), (0, 0, 255), 2) lines = slines cv2.putText(img_sheet_music, 'Staff Lines', (35, 20), font, .5, (0, 0, 255), 2) #print(lines) #step 2: object recognition #identify note head types, note tail types, accidentals, clefs, staff signatures, #dots which indicate dotted notes, etc, key signatures, time signatures. treble = cv2.imread('treble_clef.png', 0) tw, th = treble.shape[::-1] base = cv2.imread('base_clef.png', 0) bw, bh = base.shape[::-1] #note_head note_head = cv2.imread('note_head.png', 0) w1, h1 = note_head.shape[::-1] #empty_note_head h_note_head = cv2.imread('hollow_note_head.png', 0) w2, h2 = h_note_head.shape[::-1] #sharp sharp = cv2.imread('sharp.png', 0) w3, h3 = sharp.shape[::-1] #flat flat = cv2.imread('flat.png', 0) w4, h4 = flat.shape[::-1] #natural natural = cv2.imread('natural.png', 0) w5, h5 = natural.shape[::-1] #whole_rest whole_rest = cv2.imread('whole_rest.png', 0) w6, h6 = whole_rest.shape[::-1] #half_rest half_rest = cv2.imread('half_rest.png', 0) w7, h7 = half_rest.shape[::-1] #quarter_rest quarter_rest = cv2.imread('quarter_rest.png', 0) w8, h8 = quarter_rest.shape[::-1] #eighth_rest eighth_rest = cv2.imread('eighth_rest.png', 0) w9, h9 = eighth_rest.shape[::-1] #sixteenth_rest sixteenth_rest = cv2.imread('sixteenth_rest.png', 0) w10, h10 = sixteenth_rest.shape[::-1] #dot dot = cv2.imread('dot.png', 0) w11, h11 = dot.shape[::-1] #create window and trackbar img = np.zeros((10, 780, 3), np.uint8) cv2.namedWindow('image') cv2.namedWindow('out', cv2.WINDOW_NORMAL) # create trackbars for color change cv2.createTrackbar('note_head','image', 0, 100, nothing) cv2.createTrackbar('h_note_head','image', 0, 100, nothing) cv2.createTrackbar('sharp','image', 0, 100, nothing) cv2.createTrackbar('flat','image', 0, 100, nothing) cv2.createTrackbar('natural','image', 0, 100, nothing) cv2.createTrackbar('WR','image', 0, 100, nothing) cv2.createTrackbar('HR','image', 0, 100, nothing) cv2.createTrackbar('QR','image', 0, 100, nothing) cv2.createTrackbar('ER','image', 0, 100, nothing) cv2.createTrackbar('SR','image', 0, 100, nothing) cv2.createTrackbar('dot','image', 0, 100, nothing) iteration = 0 while(1): #print("running") cv2.imshow('image', img) k = cv2.waitKey(0) & 0xFF if k == 27: break; print("running") # get current positions of four trackbars tem_nh = cv2.getTrackbarPos('note_head','image')/100 tem_h_nh = cv2.getTrackbarPos('h_note_head','image')/100 tem_s = cv2.getTrackbarPos('sharp','image')/100 tem_f = cv2.getTrackbarPos('flat','image')/100 tem_n = cv2.getTrackbarPos('natural','image')/100 tem_WR = cv2.getTrackbarPos('WR','image')/100 tem_HR = cv2.getTrackbarPos('HR','image')/100 tem_QR = cv2.getTrackbarPos('QR','image')/100 tem_ER = cv2.getTrackbarPos('ER','image')/100 tem_SR = cv2.getTrackbarPos('SR','image')/100 tem_d = cv2.getTrackbarPos('dot','image')/100 iteration += 1 out = copy.copy(img_sheet_music) cv2.putText(out, str(iteration), (1600, 100), font, 2, (0, 0, 255), 2) #empty 2d array for (X,Y) coordinates of all objects X = [] Y = [] #1 - note_head, 2 - hollow_note_head, 3 - sharp, 4 - flat, 5 - natural, 6 - whole_rest #7 - half_rest, 8 - quarter_rest, 9 - eighth_rest, 10 - sixteenth_rest, 11 - dot #-1 - treble_clef, -2 - base_clef type = [] first = True key = True #get location of treble_clef first = findObjects(X, Y, type, tw, th, -1, treble, 0.60, first, dst = out) #get location of base_clef first = findObjects(X, Y, type, bw, bh, -2, base, 0.60, first, dst = out) #get top left most corner to sort left = X[0] + tw top = Y[0] for coord in zip(X, Y, type): if coord[2] is 5: if coord[0] + tw < left: left = coord[0] + tw elif coord[2] is 6: if coord[0] + bw < left: left = coord[0] + bw if coord[1] < top: top = coord[1] cv2.putText(out, 'Corner', (left, top), font, .5, (0, 0, 255), 2) #print("left:", left) #print("top:", top) #get location of note_heads first = findObjects(X, Y, type, w1, h1, 1, note_head, tem_nh, first, left, top, dst = out) #get location of hollow_note_heads first = findObjects(X, Y, type, w2, h2, 2, h_note_head, tem_h_nh, first, left, top, dst = out) #get location of whole_rest first = findObjects(X, Y, type, w6, h6, 6, whole_rest, tem_WR, first, left, top, dst = out) #get location of half_rest first = findObjects(X, Y, type, w7, h7, 7, half_rest, tem_HR, first, left, top, dst = out) #get location of quarter_rest first = findObjects(X, Y, type, w8, h8, 8, quarter_rest, tem_QR, first, left, top, dst = out) #get location of eighth_rest first = findObjects(X, Y, type, w9, h9, 9, eighth_rest, tem_ER, first, left, top, dst = out) #get location of sixteenth_rest first = findObjects(X, Y, type, w10, h10, 10, sixteenth_rest, tem_SR, first, left, top, dst = out) #get location of sharps first = findObjects(X, Y, type, w3, h3, 3, sharp, tem_s, first, left, top, dst = out) #get location of flats first = findObjects(X, Y, type, w4, h4, 4, flat, tem_f, first, left, top, dst = out) #get location of naturals first = findObjects(X, Y, type, w5, h5, 5, natural, tem_n, first, left, top, dst = out) #get location of dots first = findObjects(X, Y, type, w11, h11, 11, dot, tem_d, first, left, top, dst = out) #step 3: determine pitches #use staff lines to determine note pitches and subdivide notes into sections #based on division of staff bar groups #display output of processes occuring to the sheetmusic #write centerpoint dot for each note_head as well as type #0 - note_head, 1 - hollow_note_head, 2 - sharp, 3 - flat, 4 - natural, 5 - treble_clef, 6 - base_clef centers = [] for coord in zip(X, Y, type): if coord[2] is 1: cv2.putText(out, 'Q/E/S', (coord[0], coord[1]), font, .5, (0, 0, 255), 2) cv2.circle(out, (int(coord[0] + w1/2), int(coord[1] + h1/2)), 2, (255, 0, 0)) if coord[2] is 2: cv2.putText(out, 'W/H', (coord[0], coord[1]), font, .5, (0, 0, 255), 2) cv2.circle(out, (int(coord[0] + w2/2), int(coord[1] + h2/2)), 2, (255, 0, 0)) if coord[2] is 3: cv2.putText(out, 'Sharp', (coord[0], coord[1]), font, .5, (255, 0, 0), 2) if coord[2] is 4: cv2.putText(out, 'Flat', (coord[0], coord[1]), font, .5, (255, 0, 0), 2) if coord[2] is 5: cv2.putText(out, 'Natural', (coord[0], coord[1]), font, .5, (255, 0, 0), 2) if coord[2] is 6: cv2.putText(out, 'WR', (coord[0], coord[1]), font, .5, (0, 255, 0), 2) if coord[2] is 7: cv2.putText(out, 'HR', (coord[0], coord[1]), font, .5, (0, 255, 0), 2) if coord[2] is 8: cv2.putText(out, 'QR', (coord[0], coord[1]), font, .5, (0, 255, 0), 2) if coord[2] is 9: cv2.putText(out, 'ER', (coord[0], coord[1]), font, .5, (0, 255, 0), 2) if coord[2] is 10: cv2.putText(out, 'SR', (coord[0], coord[1]), font, .5, (0, 255, 0), 2) cv2.imshow('out', out) cv2.waitKey(100) cv2.destroyAllWindows() cv2.imwrite(sheetname + '2.png', out)
Markdown
UTF-8
1,315
3.21875
3
[ "MIT" ]
permissive
# `AbstractAutoEnum` Base Class This base class contains a default `all()` implementation that always returns the values of all public class constants. This makes writing usable enum classes very easy: extend this class, put some constants in it, done. [Exceptions]: Exceptions.md [Enum]: Class_Enum.md [AbstractEnum]: Class_AbstractEnum.md [AbstractAutoEnum]: Class_AbstractAutoEnum.md ## Class Details * Declaration: <code>class mle86\\Enum\\<b>AbstractAutoEnum</b> extends mle86\\Enum\\[AbstractEnum]</code>. * Class file: [src/AbstractAutoEnum.php](../src/AbstractAutoEnum.php) ## Method Reference * <code>static <b>all</b> (): array</code> Returns a list of all public constant values in this class (as an associative array with the constants' names as keys). ## Inherited Methods * **Constructor:** `__construct ($value)` * <code>static <b>isValid</b> ($value): bool</code> * <code>static <b>validate</b> ($value, string $forKey = null): void</code> * <code>static <b>validateOptional</b> ($value, string $forKey = null): void</code> * <code><b>value</b> (): mixed</code> * <code><b>jsonSerialize</b> (): mixed</code> * <code><b>__toString</b> (): string</code> * <code><b>equals</b> ($value): bool</code> All inherited methods are documented in the [AbstractEnum] class documentation.
Java
UTF-8
4,319
2.078125
2
[ "Apache-2.0" ]
permissive
/* * 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 com.jsquad.knowhunt; import DatabaseHelper.Qa; import DatabaseHelper.QaEJB; import com.google.gson.Gson; import static com.sun.org.apache.xalan.internal.xsltc.compiler.util.Util.println; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.ejb.EJB; import javax.persistence.EntityManagerFactory; import javax.persistence.PersistenceUnit; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import static javax.ws.rs.client.Entity.json; import jdk.nashorn.api.scripting.JSObject; import org.json.simple.JSONArray; import org.json.simple.JSONObject; /** * * @author elena */ @WebServlet(name = "KnowHuntServlet", urlPatterns = {"/KnowHuntServlet"}) public class KnowHuntServlet extends HttpServlet { @PersistenceUnit @EJB QaEJB qaEjb; private EntityManagerFactory emf; /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try (PrintWriter out = response.getWriter()) { response.setContentType("application/json"); JSONObject jsobObjFinal = new JSONObject(); JSONArray jSONArrayOfQaRaws = new JSONArray(); List<Qa> allQaValues = (List<Qa>)qaEjb.getList(); for(int i = 0; i < qaEjb.getList().size(); i++) { Qa qa = (Qa)qaEjb.getList().get(i); JSONObject oneRawJSonObject = new JSONObject(); oneRawJSonObject.put("secretCode", qa.getSecretCode()); oneRawJSonObject.put("question", qa.getQuestion()); oneRawJSonObject.put("rightAnswer", qa.getRightAnswer()); oneRawJSonObject.put("optionalAnswer1", qa.getOptionalAnswer1()); oneRawJSonObject.put("optionalAnswer2", qa.getOptionalAnswer2()); oneRawJSonObject.put("optionalAnswer3", qa.getOptionalAnswer3()); jSONArrayOfQaRaws.add(i, oneRawJSonObject); } jsobObjFinal.put("qaList", jSONArrayOfQaRaws); out.print(jsobObjFinal); out.flush(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
Java
UTF-8
527
1.835938
2
[]
no_license
package com.blockshine.authentication.service; import com.blockshine.authentication.dto.AuthorizationDTO; import com.blockshine.authentication.dto.LoginDTO; /** * Token generate and Token Refresh * * @author maxiaodong */ public interface TokenService { public AuthorizationDTO generateToken(AuthorizationDTO dto); public AuthorizationDTO refreshToken(AuthorizationDTO dto); public String getAppKey(String token); public LoginDTO generateLoginToken(LoginDTO dto); public boolean checkLogin(String token); }
Java
UTF-8
1,675
2.015625
2
[]
no_license
package com.spring.openstack.configure; import com.spring.openstack.configure.filters.OpenStackFilter; import com.spring.openstack.data.Constants; import com.spring.openstack.data.OpenStackAuth; import org.openstack4j.api.OSClient; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.context.annotation.RequestScope; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; @Configuration public class BeanInitializer { // 사용자 요청이 있을 때마다 토큰으로 생성하는 영역 @Bean @RequestScope public OSClient.OSClientV3 osClient() { HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest(); String scopedTokenId = (String)httpServletRequest.getSession().getAttribute("scopedTokenId"); OpenStackAuth openStackAuth = OpenStackAuth.projectScopedAuth(Constants.ADMIN_NAME, Constants.ADMIN_PASSWORD, "Default", Constants.ADMIN_PROJECT); if(openStackAuth.validateToken(scopedTokenId)) { openStackAuth.setToken(openStackAuth.getTokenDetails(scopedTokenId)); } return openStackAuth.getOsClient(); } // 어드민을 미리 만들어놓고 활용하는 부분 @Bean public OSClient.OSClientV3 adminOsClient() { return OpenStackAuth.projectScopedAuth(Constants.ADMIN_NAME, Constants.ADMIN_PASSWORD, "Default", Constants.ADMIN_PROJECT).getOsClient(); } }
JavaScript
UTF-8
758
2.71875
3
[]
no_license
(function () { document.body.addEventListener('click', (e) => { // get target element according to hash in url let url = (e.target.href || '').split('#'); let target = document.getElementById(url[1]); url = url[0]; // if target exisits on website and auto scrolling is supported if (target && target.scrollIntoView && location.href.split('#')[0] === url) { // prevent browser from jumping to hash e.preventDefault(); // smoothly scroll to target element target.scrollIntoView({behavior: 'smooth'}); // just clicked link should lose focus e.target.blur(); // add hash to history, so that "deep links" continue to work history.pushState(null, null, e.target.href); } }) }());
Markdown
UTF-8
1,560
2.78125
3
[]
no_license
## Nano Lua Dictionary Nano Lua Dictionary (or nano_luadict) is a simple C snippet that facilitates (with some compromises) the creation of Lua tables composed of K/V's (or dictionaries) as specified [here](http://lua-users.org/wiki/TablesTutorial). I made this nano-project to to aid in the creation of an event system for a rather simple Game Engine, and because integrating a huge Lua binding framework such as Luabind just to fulfill this propose seemed to be too much overhead for my personal needs. ### Usage example The project itself is self-explanatory, feel free to modify it to your needs, if you feel that a lot could be improved while maintaining simplicity and speed, just send a pull request :) , I'm not picky about them. #include "nanoluadict.h" luaDict(L /* L is Lua State */ , "sample_dictionary" /* Table name in global space */ , 8 /* Number of kvs that we are including in our dictionary */ , kvPairWithNumber("key1", 1) /* Keys are always strings, this is a numeric value */ , kvPairWithNumber("key2", 2) , kvPairWithString("key3", "string 3") /* This is a string value */ , kvPairWithNumber("key4", 4) , kvPairWithNumber("key5", 5) , kvPairWithNumber("key6", 6) , kvPairWithNumber("key7", 7) , kvPairWithCFunction("callback", &c_function)); /* This is for a function callback */
Java
UTF-8
3,424
1.960938
2
[]
no_license
// isComment package org.geometerplus.zlibrary.text.view.style; import java.io.*; import java.util.*; import org.geometerplus.zlibrary.core.filesystem.ZLFile; import org.geometerplus.zlibrary.core.util.MiscUtil; class isClassOrIsInterface { private enum State { EXPECT_SELECTOR, EXPECT_OPEN_BRACKET, EXPECT_NAME, EXPECT_VALUE, READ_COMMENT } private State isVariable; private State isVariable; private Map<Integer, ZLTextNGStyleDescription> isVariable; private Map<String, String> isVariable; private String isVariable; private String isVariable; Map<Integer, ZLTextNGStyleDescription> isMethod(ZLFile isParameter) { isNameExpr = new LinkedHashMap<Integer, ZLTextNGStyleDescription>(); isNameExpr = isNameExpr.isFieldAccessExpr; InputStream isVariable = null; try { isNameExpr = isNameExpr.isMethod(); final BufferedReader isVariable = new BufferedReader(new InputStreamReader(isNameExpr)); String isVariable; while ((isNameExpr = isNameExpr.isMethod()) != null) { for (String isVariable : isNameExpr.isMethod(isNameExpr)) { isMethod(isNameExpr); } } } catch (IOException isParameter) { } finally { if (isNameExpr != null) { try { isNameExpr.isMethod(); } catch (IOException isParameter) { } } } return isNameExpr; } private void isMethod(String isParameter) { if (isNameExpr != isNameExpr.isFieldAccessExpr && isNameExpr.isMethod("isStringConstant")) { isNameExpr = isNameExpr; isNameExpr = isNameExpr.isFieldAccessExpr; return; } switch(isNameExpr) { case isNameExpr: if (isNameExpr.isMethod("isStringConstant")) { isNameExpr = isNameExpr; } break; case isNameExpr: isNameExpr = isNameExpr; isNameExpr = isNameExpr.isFieldAccessExpr; break; case isNameExpr: if ("isStringConstant".isMethod(isNameExpr)) { isNameExpr = new HashMap<String, String>(); isNameExpr = isNameExpr.isFieldAccessExpr; } break; case isNameExpr: if ("isStringConstant".isMethod(isNameExpr)) { if (isNameExpr != null) { try { isNameExpr.isMethod(isNameExpr.isMethod(isNameExpr.isMethod("isStringConstant")), new ZLTextNGStyleDescription(isNameExpr, isNameExpr)); } catch (Exception isParameter) { // isComment } } isNameExpr = isNameExpr.isFieldAccessExpr; } else { isNameExpr = isNameExpr; isNameExpr = isNameExpr.isFieldAccessExpr; } break; case isNameExpr: if (isNameExpr != null && isNameExpr != null) { isNameExpr.isMethod(isNameExpr, isNameExpr); } isNameExpr = isNameExpr.isFieldAccessExpr; break; } } }
Java
UTF-8
1,614
2.125
2
[]
no_license
package com.dgg.hdforeman.mvp.model.been; import java.io.Serializable; /** * Created by kelvin on 2016/11/9. * 房产信息 */ public class HouseInfoData implements Serializable{ private String id;//项目id private String pm_cusname;//业主 private String measure;//工地测量(0,未测量,1,已测量) private String pm_cuscontactno;//业主电话 private String pm_housesname;//楼盘 private String pm_state;//项目状态(默认 0未签约 1待开工(已签约) 2施工中 3 停工(暂停) 4 完工 5未签约工长已接手6工长已报价待签约) private String pm_housetype; //户型 private String pm_acreage; //面积 private String pricestate;//业主报价(0未报价,1已报价 ) private String pm_roomno;//单元 private String pm_housesaddress;//地址 public String getId() { return id; } public String getPm_cusname() { return pm_cusname; } public String getMeasure() { return measure; } public String getPm_cuscontactno() { return pm_cuscontactno; } public String getPm_housesname() { return pm_housesname; } public String getPm_state() { return pm_state; } public String getPm_housetype() { return pm_housetype; } public String getPm_acreage() { return pm_acreage; } public String getPricestate() { return pricestate; } public String getPm_roomno() { return pm_roomno; } public String getPm_housesaddress() { return pm_housesaddress; } }
TypeScript
UTF-8
2,590
2.546875
3
[]
no_license
import { EmbedBuilder, ApplicationCommandOptionType } from "discord.js"; import R from "ramda"; import { CommandError } from "../../../../Configuration/definitions"; import F from "../../../../Helpers/funcs"; import { prisma } from "../../../../Helpers/prisma-init"; import { SlashCommand } from "../../../../Structures/EntrypointSlashCommand"; const command = new SlashCommand(<const>{ description: "Test command", options: [ { name: "user", description: "The user to check warns for", required: true, type: ApplicationCommandOptionType.User }, { name: "page", description: "Warning page number", required: false, type: ApplicationCommandOptionType.Integer } ] }); command.setHandler(async (ctx) => { await ctx.deferReply(); const member = await ctx.guild.members.fetch(ctx.opts.user); if (!member) throw new CommandError("Unable to find that user"); const page = ctx.opts.page ?? 1; const take = 10; const skip = (page - 1) * take; if (typeof page !== "number" || page < 1) throw new CommandError("Invalid page number."); const warnCount = await prisma.warning.count({ where: { warnedUserId: ctx.opts.user } }); const numPages = Math.ceil(warnCount / take); if (warnCount === 0) throw new CommandError("This user does not have any warnings."); const warns = await prisma.warning.findMany({ where: { warnedUserId: ctx.opts.user }, orderBy: { createdAt: "desc" }, skip, take }); if (warns.length === 0) throw new CommandError(`This page does not exist. There are ${numPages} pages available.`); const severityEmoji = (s: number) => { return ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"][s - 1] || "❓"; }; const averageSeverity = R.mean(warns.map((w) => w.severity || 5)); const embed = new EmbedBuilder() .setAuthor({ name: `${member.displayName}'s warnings`, iconURL: member.user.displayAvatarURL() }) .setColor(((255 * averageSeverity) / 10) << 16) .setFooter({ text: `Page ${page}/${numPages}` }); for (const warn of warns) { const emoji = severityEmoji(warn.severity); const timestamp = F.discordTimestamp(warn.createdAt, "relative"); embed.addFields([{ name: `${warn.reason}`, value: `${emoji} ${warn.type}\n${timestamp}` }]); } await ctx.editReply({ embeds: [embed] }); }); export default command;
Java
UTF-8
309
1.617188
2
[ "Apache-2.0" ]
permissive
package com.example.liem.sitorgetoffthepot.Interfaces; import android.location.Location; import com.google.android.gms.maps.model.LatLng; public interface AddLocationInterface { void newLocationCancelButtonPress(); void newLocationAddButtonPress(String _title, String _rating, String _detail); }
JavaScript
UTF-8
1,265
2.984375
3
[]
no_license
import React, { useReducer } from 'react'; import './App.css'; const ADD_USER = 'ADD_USER' const appReducer = (state, action) => { switch (action.type) { case ADD_USER: { return{ users: [...state.users, action.payload] }; } } }; function App() { const initialState = { users: [ { name: 'alan', age: 30 }, { name: 'messi', age: 31 }, ] }; const [state, dispatch] = useReducer( appReducer, initialState ); const addUsers = () => { const name = document.getElementById('form-name-input').value; const age = document.getElementById('form-age-input').value; const newUser = { name, age }; dispatch({ type: ADD_USER, payload: newUser }) } return ( <div className="App"> {state.users.map((user, index) => (<div key={index}>{`${user.name} ${user.age}`}</div>))} <div className="form"> <div className="form-name"> <label>name:</label> <input id="form-name-input" /> </div> <div className="form-age"> <label>age:</label> <input id="form-age-input" /> </div> <button onClick={() => addUsers()}>Add usser</button> </div> </div> ); } export default App;
Java
UTF-8
2,749
2.359375
2
[ "Apache-2.0" ]
permissive
package projector.api; import com.bence.projector.common.dto.BibleDTO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import projector.api.assembler.BibleAssembler; import projector.api.retrofit.ApiManager; import projector.api.retrofit.BibleApi; import projector.model.Bible; import retrofit2.Call; import java.net.ConnectException; import java.net.UnknownHostException; import java.util.List; public class BibleApiBean { private static final Logger LOG = LoggerFactory.getLogger(BibleApiBean.class); private final BibleApi bibleApi; private final BibleAssembler bibleAssembler; public BibleApiBean() { bibleApi = ApiManager.getClient().create(BibleApi.class); bibleAssembler = BibleAssembler.getInstance(); } public List<Bible> getBibles() { Call<List<BibleDTO>> call = bibleApi.getBibles(); return executeBiblesCall(call); } public List<Bible> getBibleTitles() { Call<List<BibleDTO>> call = bibleApi.getBibleTitles(); return executeBiblesCall(call); } public Bible getBible(String uuid) { Call<BibleDTO> call = bibleApi.getBible(uuid); return doCallBible(call); } public Bible updateBible(Bible bible) { Call<BibleDTO> call = bibleApi.getBible(bible.getUuid()); try { BibleDTO bibleDTO = call.execute().body(); if (bibleDTO != null) { return bibleAssembler.updateModel(bible, bibleDTO); } } catch (UnknownHostException e) { return null; } catch (Exception e) { LOG.error(e.getMessage(), e); } return null; } private List<Bible> executeBiblesCall(Call<List<BibleDTO>> call) { try { List<BibleDTO> bibleDTOs = call.execute().body(); if (bibleDTOs != null) { return bibleAssembler.createModelList(bibleDTOs); } } catch (UnknownHostException | ConnectException e) { return null; } catch (Exception e) { LOG.error(e.getMessage(), e); } return null; } private Bible doCallBible(Call<BibleDTO> call) { try { BibleDTO bibleDTO = call.execute().body(); if (bibleDTO != null) { return bibleAssembler.createModel(bibleDTO); } } catch (UnknownHostException e) { return null; } catch (Exception e) { LOG.error(e.getMessage(), e); } return null; } public Bible uploadBible(Bible bible) { final BibleDTO dto = bibleAssembler.createDto(bible); Call<BibleDTO> call = bibleApi.postBible(dto); return doCallBible(call); } }
C#
UTF-8
1,109
2.640625
3
[]
no_license
using System.Data.Common; using CollectionManager.DataBase.Tables; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; namespace CollectionManager.DataBase { public class CollectionManagerDbContext : DbContext { private readonly DbConnection _dbConnection; public DbSet<ItemSet> ItemSets { get; set; } public DbSet<ItemSetAuthor> ItemSetAuthors { get; set; } public CollectionManagerDbContext(DbConnection dbConnection) { this._dbConnection = dbConnection; } protected override void OnModelCreating(ModelBuilder modelBuilder) { // Primary Keys modelBuilder.Entity<ItemSet>().HasKey(x => x.ItemSetId); modelBuilder.Entity<ItemSetAuthor>().HasKey(x => new { x.ItemSetId, x.Name }); // Relation modelBuilder.Entity<ItemSetAuthor>() .HasOne(x => x.ItemSet) .WithMany(x => x.Authors) .OnDelete(DeleteBehavior.Cascade); } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { switch (this._dbConnection) { case SqliteConnection conn: optionsBuilder.UseSqlite(conn); break; } } } }
Java
UTF-8
8,511
1.757813
2
[]
no_license
package com.hxwl.wulinfeng.wulin; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnLongClickListener; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.Toast; import com.bumptech.glide.Glide; import com.bumptech.glide.request.animation.GlideAnimation; import com.bumptech.glide.request.target.SimpleTarget; import com.hxwl.common.utils.StringUtils; import com.hxwl.wulinfeng.R; import com.hxwl.wulinfeng.activity.HomeActivity; import com.hxwl.wulinfeng.base.BaseActivity; import com.hxwl.wulinfeng.net.AppClient; import com.hxwl.wulinfeng.photoView.PhotoView; import com.hxwl.wulinfeng.util.BitmapUtils; import com.hxwl.wulinfeng.util.Constants; import com.hxwl.wulinfeng.util.FileUtils; import com.hxwl.wulinfeng.util.ImageUtils; import com.hxwl.wulinfeng.util.NetUrlUtils; import com.hxwl.wulinfeng.util.SPUtils; import com.hxwl.wulinfeng.util.ToastUtils; import com.hxwl.wulinfeng.util.config.SystemDir; import com.jaeger.library.StatusBarUtil; import java.io.File; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; import static com.hxwl.wulinfeng.R.id.iv_downpic; /** * 查看单个照片页面(全屏) * @author Allen * */ public class SeeHighDefinitionPictureActivity extends BaseActivity { private PhotoView touchImageView; //真正的沉浸式状态栏 @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if(hasFocus && Build.VERSION.SDK_INT >= 19){ View decorView = getWindow().getDecorView(); decorView.setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); } } @Override protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.activity_highdefinition_picture); StatusBarUtil.setColor(SeeHighDefinitionPictureActivity.this,getResources().getColor(R.color.text_black),0); super.onCreate(savedInstanceState); touchImageView = (PhotoView)findViewById(R.id.mTouchImageView); Intent intent=getIntent(); final String url=intent.getStringExtra("highDefinitionUrl"); if(StringUtils.isEmpty(url)){ return ; } RelativeLayout rl_layout = (RelativeLayout) findViewById(R.id.rl_layout); rl_layout.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); } }); ImageView iv_downpic = (ImageView) findViewById(R.id.iv_downpic); iv_downpic.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String url_2 = url; String fileName2 = url_2.substring(url_2.lastIndexOf("/") + 1); final File file2 = new File(SystemDir.DIR_DOWN_IMAGE + "/" + fileName2 ); if (!file2.exists()) { List<String> picUrlList = new ArrayList<>(); picUrlList.add(url_2); File appDir = new File(SystemDir.DIR_DOWN_IMAGE); if (!appDir.exists()) { appDir.mkdirs(); } final File currentFile = new File(appDir, fileName2); if (currentFile.exists()) { return; } Glide.with(SeeHighDefinitionPictureActivity.this) .load(url_2) .asBitmap() .into(new SimpleTarget<Bitmap>() { @Override public void onResourceReady(Bitmap bitmap1, GlideAnimation<? super Bitmap> glideAnimation) { if (bitmap1 != null) { // 在这里执行图片保存方法 String filePath = currentFile.getPath(); BitmapUtils.saveBitToCanmer(bitmap1, filePath, 60); Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); Uri uri = Uri.fromFile(file2); intent.setData(uri); sendBroadcast(intent) ; ToastUtils.showToast(SeeHighDefinitionPictureActivity.this,"图片保存至"+filePath); } } }); } } }); touchImageView.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { String url_2 = url; String fileName2 = url_2.substring(url_2.lastIndexOf("/") + 1); final File file2 = new File(SystemDir.DIR_IMAGE); if (!file2.exists()) { List<String> picUrlList = new ArrayList<>(); picUrlList.add(url_2); File appDir = new File(SystemDir.DIR_IMAGE); if (!appDir.exists()) { appDir.mkdirs(); } final File currentFile = new File(appDir, fileName2); if (currentFile.exists()) { return false; } Glide.with(SeeHighDefinitionPictureActivity.this) .load(url_2) .asBitmap() .into(new SimpleTarget<Bitmap>() { @Override public void onResourceReady(Bitmap bitmap1, GlideAnimation<? super Bitmap> glideAnimation) { if (bitmap1 != null) { // 在这里执行图片保存方法 String filePath = currentFile.getPath(); BitmapUtils.saveBitToCanmer(bitmap1, filePath, 60); Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); Uri uri = Uri.fromFile(file2); intent.setData(uri); sendBroadcast(intent) ; ToastUtils.showToast(SeeHighDefinitionPictureActivity.this,"图片保存至"+filePath); } } }); } return false; } }); ImageUtils.getPic(url,touchImageView,SeeHighDefinitionPictureActivity.this); // final String fileName = FileUtils.getFileName(url); // String screenShotPath = getSdHighDefinitionImgPath(fileName); // final Bitmap bitmap = ImageUtils.getBitmapByPath(screenShotPath); // touchImageView.setOnLongClickListener(new OnLongClickListener() { // @Override // public boolean onLongClick(View arg0) { // String filePath=""; // String cameraPath = Environment.getExternalStorageDirectory() // + File.separator + "DCIM" + File.separator + "camera"; // File file = new File(cameraPath); // if (!file.exists()) { // file.mkdir(); // } // String filename = url.substring(url // .lastIndexOf("/")); // filePath = cameraPath +File.separator+filename; // if(bitmap!=null){ // ImageUtils.saveBitmapTOSd(filePath, bitmap); // ImageUtils.scanPhoto(SeeHighDefinitionPictureActivity.this,filePath); // }else{ // ImageUtils.downLoadImagToSd(SeeHighDefinitionPictureActivity.this, url, filePath); // } // return false; // } // }); touchImageView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); } }); // if(bitmap!=null){ // touchImageView.setImageBitmap(bitmap); // }else{ // AppClient.getImageForView(touchImageView ,url,SeeHighDefinitionPictureActivity.this); // // } } public Bitmap convertToBitmap(String path, int w, int h) { BitmapFactory.Options opts = new BitmapFactory.Options(); // 设置为ture只获取图片大小 opts.inJustDecodeBounds = true; opts.inPreferredConfig = Bitmap.Config.ARGB_8888; // 返回为空 BitmapFactory.decodeFile(path, opts); int width = opts.outWidth; int height = opts.outHeight; float scaleWidth = 0.f, scaleHeight = 0.f; if (width > w || height > h) { // 缩放 scaleWidth = ((float) width) / w; scaleHeight = ((float) height) / h; } opts.inJustDecodeBounds = false; float scale = Math.max(scaleWidth, scaleHeight); opts.inSampleSize = (int) scale; WeakReference<Bitmap> weak = new WeakReference<Bitmap>( BitmapFactory.decodeFile(path, opts)); return Bitmap.createScaledBitmap(weak.get(), w, h, true); } public static String getSdHighDefinitionImgPath(String fileName){ String imgPath = ""; Boolean sdCardExist = FileUtils.checkSaveLocationExists(); if (sdCardExist) { imgPath = Environment.getExternalStorageDirectory() + File.separator+ NetUrlUtils.project+File.separator; } else { imgPath = Environment.getRootDirectory() + File.separator+ NetUrlUtils.project + File.separator; } return imgPath; } @Override public void onBackPressed() { super.onBackPressed(); finish(); } @Override protected void onDestroy() { super.onDestroy(); System.gc(); } }
Go
UTF-8
690
3.171875
3
[]
no_license
package main import ( "Go-000/Week01/protoBuf/myproto" "fmt" "github.com/golang/protobuf/proto" ) func main() { test := &myproto.Test{ Name: "joke", Stature: 173, Weight: []int64{211, 189, 159}, Motto: "back !", } //将Struct test 转换成 protobuf data, err := proto.Marshal(test) if err != nil { fmt.Println("proto Marshal err.") } //得到一个新的Test结构体 newTest newtest := &myproto.Test{} //将data转换为Test结构体 err = proto.Unmarshal(data, newtest) if err != nil { fmt.Println("转码失败", err) } fmt.Println(newtest.String()) //得到具体字段信息 fmt.Println(newtest.GetName()) fmt.Println(newtest.GetWeight()) }
C#
UTF-8
1,749
2.703125
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; public enum ButtonAssignments { Left, Right, Shift, Down, Space, C, E, Q } public enum Condition { GreaterThan, LessThan } [System.Serializable] public class InputAxisState { public string axisName; public float offValue; public ButtonAssignments button; public Condition condition; public bool value { get { var val = Input.GetAxis(axisName); switch (condition) { case Condition.GreaterThan: return val > offValue; case Condition.LessThan: return val < offValue; } return false; } } } public class InputManager : MonoBehaviour { public InputAxisState[] inputs; public InputState inputState; public GameObject gameManager; public GameObject player; // function to make newly-instantiated Player (and its scripts) available to InputManager void GetPlayer() { // get reference to GameManager gameManager = GameObject.Find("GameManager"); // referenceinstantiated Player player = gameManager.GetComponent<FullGameManager>().player; // get inputState on instantiated Player inputState = player.GetComponent<InputState>(); } // Update is called once per frame void Update() { // if player doesn't exist then create (should only happen once) if (!player) { GetPlayer(); } foreach (var input in inputs) { inputState.SetButtonValue(input.button, input.value); } } }
Python
UTF-8
565
2.59375
3
[]
no_license
import time import sys import telnetlib #Other is same as VBS example. HOST = "192.168.1.78" #Emulator IP tn = telnetlib.Telnet(HOST) print tn.read_eager() tn.write("admin\r\n") #the user name is admin time.sleep(2) tn.write("\r\n") #there is no password - just return - now logged in print tn.read_eager() time.sleep(2) tn.write("\r\n") print tn.read_very_lazy() tn.write("\r\n") tn.write("GI\r\n") #hey camera tell me more about you print tn.read_very_lazy() #read output sess_op = tn.read_all() print sess_op tn.close()
Java
UTF-8
2,220
4.15625
4
[]
no_license
package pl.mazurmarcin.javastart.lecture10.homework.shapes; public class ShapeApp { private static ShapeCalculator shapeCalculator = new ShapeCalculator(); private static final String Rectangle = "Rectangle"; private static final String Line2D = "Line2D"; private static final String Circle = "Circle"; private static final String Ball = "Ball"; private static final String Cube = "Cube"; private static void printResult(String className, String values, double result) { switch (className) { case Rectangle: System.out.println("Prostokąt o bokach " + values + " ma pole " + result); break; case Line2D: System.out.println("Odcinek wyznaczony przez współrzędne " + values + " ma długość " + result); break; case Circle: System.out.println("Koło o promieniu wynoszącym " + values + " ma pole " + result); break; case Ball: System.out.println("Kula o promieniu wynoszącym " + values + " ma objętość: " + result); break; case Cube: System.out.println("Sześcian o długości krawędzi wynoszącej " + values + " ma pojemność " + result); break; default: System.out.println("Kształt nierozpoznany"); } } private static void calculateShape(Shape shape) { String className = shape.getClass().getSimpleName(); String values = shape.getValues(); if (shape instanceof GeometricShape) printResult(className, values, shapeCalculator.shapeArea((GeometricShape) shape)); else if (shape instanceof Line2D) printResult(className, values, shapeCalculator.lineLength((Line2D) shape)); else if (shape instanceof Shape3D) printResult(className, values, shapeCalculator.volume((Shape3D) shape)); else System.out.println("Kształt nierozpoznany"); } public static void main(String[] args) { Shape[] shapes = new Shape[5]; shapes[0] = new Line2D(new Point(2, 2), new Point(4, 2)); shapes[1] = new Circle(5); shapes[2] = new Rectangle(2, 5); shapes[3] = new Ball(5); shapes[4] = new Cube(5); for (Shape shape : shapes) System.out.println(shape); System.out.println("\n"); for (Shape shape : shapes) calculateShape(shape); } }
Python
UTF-8
351
3.75
4
[]
no_license
sum = 0 j=0 while j != 1: a,b = map(int,input().split( )) sum = 0 if a > b: c = a a = b b = c if a <= 0 or b <= 0: j = 1 if j != 1: for i in range(a,b+1): print('{}'.format(i)) sum +=i if i == b: print('Sum={}'.format(sum))
Java
UTF-8
737
2
2
[]
no_license
package com.Book.service; import java.util.List; import com.Book.entity.Book; import com.Book.exception.Invalidbookdetails; import com.Book.exception.InvaliedTitle; import com.Book.exception.NoRecordFound; import com.Book.exception.TitleAllreadyPresent; import com.Book.model.Request.BookRequest; import com.Book.model.Response.BookResponse; public interface BookService { public BookResponse addbook(BookRequest book) throws Invalidbookdetails, TitleAllreadyPresent; public BookResponse FindBytitle(String title) throws InvaliedTitle; public List<Book> FindByAuthorSorted(String author) throws NoRecordFound; public String deletebook(Integer id) throws NoRecordFound; public List<Book> sortbyprice() throws NoRecordFound; }
Markdown
UTF-8
1,007
2.875
3
[ "MIT" ]
permissive
<h1 dir="rtl">إلغاء مصطفى كمال أتاتورك السلطنة العثمانية .</h1> <h5 dir="rtl">العام الهجري: 1341 الشهر القمري: ربيع الأول العام الميلادي: 1922</h5> <p dir="rtl">قام مصطفى كمال أتاتورك -الذي كانت بيده مقاليدُ الأمور في تركيا- بإلغاء السَّلْطَنة العثمانية، ونفيِ السلطان عبد المجيد الثاني، وكان ذلك تمهيدًا لإلغاءِ الخلافة الإسلامية التي أصدر قرارًا بإلغائها سنة 1924م!! ونفى جميعَ أسرة آل عثمان التي حكمت العالم الإسلاميَّ خمسة قرون. وبذلك نجحت الجهودُ الغربية الاستعمارية في تدمير الرباطِ الرُّوحيِّ بين المسلمين بعد عشراتِ السنواتِ مِن التآمُرِ والمكائد لإسقاط الخلافة!!!</p></br>
Markdown
UTF-8
853
2.9375
3
[]
no_license
# Bug Identification For target1, the `strcpy` function in target1.c doesn't check the argument size. Thus, we can create a buffer with a size larger than `200` to overflow `the saved EIP`. Unlike target0, the buffer size is large enough, and thus shellcode can be put into the buffer so that we are able to get the user shell. # Details 1. First, make a buffer with a size of `200` to run target1, and use gdb to find the address of the buffer (`0xbffffce0`) and foo's saved EBP (`0xbffffda8`). 2. The buffer we create is a buffer with a size of `209` (200 buf + 4 stp + 4 ret addr + 1 null terminate). The structure of the buffer is `[(multiple)0x90][shellcode][stp][ret addr][null terminate]`. Here, `[stp]` doesn't matter so it is set as all `0x90`; `[ret addr]` is set as the address of the buffer (`0xbffffce0`); `[null terminate]` = `"\x00"`.
Python
UTF-8
1,140
2.625
3
[]
no_license
#!/usr/bin/env python3 import sys if len(sys.argv) < 4: print ("Correct usage: script.py structure1.pdb structure2.pdb output_structure.pdb") sys.exit() def rewrite(infile, chain, outfile, new): prev_orig = '' three2one = {'ALA':'A','ARG':'R','ASN':'N','ASP':'D', 'CYS':'C','GLN':'Q','GLU':'E','GLY':'G', 'HIS':'H','ILE':'I','LEU':'L','LYS':'K', 'MET':'M','PHE':'F','PRO':'P','SER':'S', 'THR':'T','TRP':'W','TYR':'Y','VAL':'V', 'MSE':'M'} with open(infile,'r') as f: for line in f: if line.startswith('ATOM'): if prev_orig != '' and line[22:27] != prev_orig: new+=1 renumb = ' '*(4-len(str(new)))+str(new)+' ' outline = line[:21]+chain+renumb+line[27:].rstrip() outfile.write(outline+'\n') prev_orig = line[22:27] outfile.write('TER\n') return new outfile = open(sys.argv[3],'w') new = 1 new = rewrite(sys.argv[1], 'A', outfile, new) new = rewrite(sys.argv[2], 'B', outfile, new+1) outfile.write('END') outfile.close()
C++
UTF-8
637
2.5625
3
[ "BSD-2-Clause" ]
permissive
// vi: tabstop=4:expandtab #include "exception/ExceptionBase.hh" #include <sstream> #include <stdio.h> #include <stdarg.h> #include <string.h> #include <stdlib.h> using namespace exception; ExceptionBase::ExceptionBase() throw() : message("Unknown") { } ExceptionBase::ExceptionBase(const std::string& msg) throw() : message(msg) { } ExceptionBase::ExceptionBase(const std::string& msg, const char *file, int line, const char *func) throw() : std::exception() { std::stringstream s; s << "At " << file << ":" << line << ": " << msg; message = s.str(); } ExceptionBase::~ExceptionBase() throw() { }
C#
UTF-8
1,356
3.625
4
[ "MIT" ]
permissive
using UnityEngine; /// <summary> /// The Cooldown class utility. /// </summary> public class Cooldown { /// <summary> /// Constructs a new Cooldown instance with a given cooldown. /// </summary> /// <param name="cooldown">The amount of time in seconds the cooldown should last.</param> public Cooldown(float cooldown) { this.cooldown = cooldown; } /// <summary> /// The amount of time in seconds the cooldown is applied for. /// </summary> public float cooldown; /// <summary> /// When this Cooldown is reset back to a full state. /// </summary> private float time = 0; /// <summary> /// Check whether or not this cooldown is limited. /// </summary> /// <param name="now">The current time in seconds, this usually is `Time.time`.</param> /// <returns>Whether or not this is still on cooldown.</returns> public bool CanUse() { if (Time.time < time) return false; ResetTime(Time.time); return true; } /// <summary> /// Sets the internal time to the current timestamp plus the cooldown. /// </summary> /// <param name="now">The current time in seconds.</param> private void ResetTime(float now) { time = now + cooldown; } }
Python
UTF-8
2,321
3.1875
3
[]
no_license
#!/usr/bin/env python import cv2 import math import numpy as np #print cv2.__version__ class LaneDetector: '''Grass Lane Detection''' def __init__(self, size): self.size = size self.image = np.zeros(size) self.houghPImg = np.zeros(size) self.houghImg = np.zeros(size) def updateImage(self, image): self.image = image def findLines(self): h,w = self.image.shape[0:2] if (h,w) != self.size: print "Received image of bad size. Required (h,w): (%d,%d). Got: (%d,%d)" % (h,w,self.size[0],self.size[1]) return #Kernel kernel10 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(10,10)) #Apply Morph Transforms image = cv2.GaussianBlur(self.image, (5, 5), 0) image = cv2.morphologyEx(image, cv2.MORPH_DILATE, kernel10) #Canny image self.contours = cv2.Canny(image,50,100) #PROBABALISTIC HOUGH TRANSFORM----------- self.houghPImg[...,...] = 0 houghP = cv2.HoughLinesP(self.contours,2, 5.*math.pi/180, 2 ) for i in range(0,len(houghP[0])): cv2.line(self.houghPImg,(houghP[0][i][0], houghP[0][i][1]),(houghP[0][i][2],houghP[0][i][3]),255,2) #HOUGH TRANSFORM----------- self.houghImg[...,...] = 0 hough = cv2.HoughLines(self.contours,2, 5.*math.pi/180, 60) nLines = 0 for i in range(0,len(hough[0])): rho= hough[0][i][0] theta= hough[0][i][1] if theta < math.pi/3.5 or theta > 3.*math.pi/3.5: if nLines > 10: break nLines += 1 #point of intersection of the line with first row pt1 = (int(rho/math.cos(theta)),0) #point of intersection of the line with last row pt2 = (int((rho-h*math.sin(theta))/math.cos(theta)),h) #Draw a white line cv2.line(self.houghImg, pt1, pt2, 255, 5) #Apply a logical 'and' to both images self.detectedLines = np.logical_and(self.houghPImg, self.houghImg) # if self.detectedLines: # self.detectedLines = cv2.morphologyEx(self.detectedLines, cv2.MORPH_OPEN, np.array(0),1) return self.detectedLines def showImage(self): #cv2.imshow("Contours", self.contours) #cv2.imshow("Hough", self.houghImg) #cv2.imshow("HoughP", self.houghPImg) cv2.imshow("Masked", self.detectedLines.astype(float)*255) #cv2.waitKey(0) def main(): image = cv2.imread("track.jpg") TEG = LaneDetector(image.shape[0:2]) TEG.updateImage(image) TEG.findLines() if __name__ == '__main__': main()
C++
UTF-8
2,571
2.59375
3
[]
no_license
#include <QCoreApplication> #include <qhash.h> #include <qdebug.h> #include "database.h" #include "table.h" #include "record.h" #include "btreeindex.h" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QHash<QString, QString> attribute_type_hash ; attribute_type_hash["rollno"]="int" ; attribute_type_hash["name"]="string" ; Table student("Students", attribute_type_hash) ; QHash<QString, QString> r1_hash ; r1_hash["rollno"]="144326"; r1_hash["name"]="Syed Ferhan Haider" ; Record r1(r1_hash) ; QHash<QString, QString> r2_hash ; r2_hash["rollno"]="144324"; r2_hash["name"]="Shayan Shokat" ; Record r2(r2_hash) ; QHash<QString, QString> r3_hash ; r3_hash["rollno"]="144333"; r3_hash["name"]="Asjad Zaheer" ; Record r3(r3_hash) ; Database mydb ; mydb.addTable(&student) ; Index* index=new BTreeIndex(3, "primary", "rollno", &student) ; mydb.add_index("Students", index) ; mydb.createRecord("Students", &r1) ; mydb.createRecord("Students", &r2) ; mydb.createRecord("Students", &r3) ; //qDebug()<<"Initiating deletion" ; //mydb.deleteRecord("Students", "rollno", "144333") ; //mydb.deleteRecord("Students", "rollno", "144326") ; //mydb.deleteRecord("Students", "rollno", "144324") ; QHash<QString, QString> r4_hash ; r4_hash["rollno"]="144075"; r4_hash["name"]="Farzam Azhar" ; Record r4(r4_hash) ; QHash<QString, QString> r5_hash ; r5_hash["rollno"]="144321"; r5_hash["name"]="Faisal Ali" ; Record r5(r5_hash) ; QHash<QString, QString> r6_hash ; r6_hash["rollno"]="144342"; r6_hash["name"]="Mr. XYZ" ; Record r6(r6_hash) ; mydb.createRecord("Students", &r4) ; mydb.createRecord("Students", &r5) ; mydb.createRecord("Students", &r6) ; QList<QString> attr_list; attr_list.append("rollno") ; attr_list.append("name") ; //mydb.updateRecord("Students", "name", "Bitch", "rollno", "144326") ; //mydb.deleteRecord("Students", "rollno", "144326") ; /*QHash<QString, QString> r7_hash ; r7_hash["rollno"]="144000"; r7_hash["name"]="Mr. ABC" ; Record r7(r7_hash) ; mydb.createRecord("Students", &r7) ; QHash<QString, QString> r8_hash ; r8_hash["rollno"]="144325"; r8_hash["name"]="Mr. KLM" ; Record r8(r8_hash) ; mydb.createRecord("Students", &r8) ;*/ mydb.deleteRecord("Students", "rollno", "144324") ; mydb.deleteRecord("Students", "rollno", "144326") ; mydb.print_table("Students") ; mydb.save_to_file("") ; return a.exec(); }
Python
UTF-8
1,437
3.421875
3
[]
no_license
from typing import Dict, List from game_period import GamePeriod from player import Player from player_stat_types import PlayerStatTypes class Team: """ A base class to represent a Team that played in a NBA game. Attributes ---------- name: str The name of the team scores: dict A dictionary of GamePeriods to ints to signify what the score of the team was during each period of the game. team_stats: dict A dictionary of PlayerStateTypes to float to represent stat attributes this team achieved throughout the match. players: list A list of Player objects that played on this team """ def __init__(self, name: str, scores: Dict[GamePeriod, int], team_stats: Dict[PlayerStatTypes, float], players: List[Player]): """ Parameters ---------- name: str The name of the team scores: dict A dictionary of GamePeriods to ints to signify what the score of the team was during each period of the game. team_stats: dict A dictionary of PlayerStateTypes to float to represent stat attributes this team achieved throughout the match. players: list A list of Player objects that played on this team """ self.name = name self.scores = scores self.team_stats = team_stats self.players = players
Shell
UTF-8
468
3.609375
4
[ "Apache-2.0" ]
permissive
#!/bin/sh # generates wordpress.conf by combining wordpress.conf-header # with the URLs in wordprss-urls outfile=wordpress.conf echo "## generated by $0 ##" > $outfile cat wordpress.conf-header >> $outfile for url in $(egrep -v '^#' wordpress-urls | sed 's/index\.php/(index.php)?/; s/\.php/\\.php/') do cat << EOF >> $outfile location ~ ${url}$ { include snippets/wordpress-nginx/admin-whitelist-ips.conf; include snippets/wordpress-nginx/php.conf; } EOF done
C#
UTF-8
3,674
2.59375
3
[]
no_license
using ProcuraServicosWebApi.Models; using ProcuraServicosWebApi.Repository; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace ProcuraServicosWebApi.Controllers { [RoutePrefix("api/Categoria")] public class CategoriaController : ApiController { CategoriaRepository _CR; public CategoriaRepository CR { get { if (_CR == null) _CR = new CategoriaRepository(); return _CR; } set { _CR = value; } } [HttpGet] [Route("SearchAll/{nomeCategoria}")] public HttpResponseMessage Get(string nomeCategoria) { try { var categorias = CR.GetAll(nomeCategoria); return Request.CreateResponse(HttpStatusCode.OK, categorias); } catch (Exception) { return Request.CreateResponse(HttpStatusCode.BadRequest); throw; } } [HttpGet] [Route("Search/{idCategoria}")] public HttpResponseMessage Get(int idCategoria) { try { var categoria = CR.GetOne(idCategoria); return Request.CreateResponse(HttpStatusCode.OK, categoria); } catch (Exception ex) { return Request.CreateResponse(HttpStatusCode.BadRequest + " Algo deu errado! " + ex.Message); throw; } } [HttpPost] [Route("Save")] public HttpResponseMessage Post(Categoria entity) { if (ModelState.IsValid) { try { CR.Save(entity); return Request.CreateResponse(HttpStatusCode.Created); } catch (Exception ex) { return Request.CreateResponse(HttpStatusCode.BadRequest + " Algo deu errado. " + ex.Message); throw; } } else return Request.CreateResponse(HttpStatusCode.BadRequest + " Fora dos padrões"); } [HttpPost] [Route("Change/{idCategoria}")] public HttpResponseMessage Put(int idCategoria, Categoria entity) { if (ModelState.IsValid) { try { var categoria = CR.GetOne(idCategoria); entity.id = categoria.id; CR.Save(entity); return Request.CreateResponse(HttpStatusCode.Accepted); } catch (Exception ex) { return Request.CreateResponse(HttpStatusCode.BadRequest + " Algo ocorreu: " + ex.Message); throw; } } else return Request.CreateResponse(HttpStatusCode.BadRequest + " Formato fora de padrão"); } [HttpDelete] [Route("Delete/{idCategoria}")] public HttpResponseMessage Delete(int idCategoria) { try { CR.Delete(idCategoria); return Request.CreateResponse(HttpStatusCode.MovedPermanently); } catch (Exception ex) { return Request.CreateResponse(HttpStatusCode.BadRequest + " Não excluido!, " + ex.Message); throw; } } } }
Java
UTF-8
710
2.515625
3
[]
no_license
package by.bsu.likhanova.hybridSorting.creator; import by.bsu.likhanova.hybridSorting.datareader.ReaderFromFile; import by.bsu.likhanova.hybridSorting.parameter.Parameters; import java.io.IOException; import java.util.ArrayList; public class FromFileArrayCreator { public static ArrayList<int[]> initArrays() throws IOException { ArrayList<int[]> arrayWithNumberArrays = new ArrayList<>(Parameters.FILE_AMOUNT); for (int i = 1; i <= Parameters.FILE_AMOUNT; i++) { String fileName = Parameters.FILE_NAME + i + Parameters.FILE_EXPANSION; arrayWithNumberArrays.add(ReaderFromFile.readArrayFromFile(fileName)); } return arrayWithNumberArrays; } }
JavaScript
UTF-8
988
3.09375
3
[ "MIT" ]
permissive
/** * @since 2017-03-20 08:53:17 * @author vivaxy * * @see https://leetcode.com/problems/simplify-path/ Given an absolute path for a file (Unix-style), simplify it. For example, path = "/home/", => "/home" path = "/a/./b/../../c/", => "/c" */ /** * @see https://leetcode.com/submissions/detail/97327909/ * * @param {string} path * @return {string} */ var simplifyPath = function(path) { var sections = path.split('/'); var current = []; sections.forEach(function(section) { switch (section) { case '': break; case '.': break; case '..': current.pop(); break; default: current.push(section); break; } }); return '/' + current.join('/'); }; var test = require('ava'); test('main', function(t) { t.is(simplifyPath('/home/'), '/home'); t.is(simplifyPath('/a/./b/../../c/'), '/c'); });
Java
UTF-8
328
1.820313
2
[]
no_license
package com.example.microadventure.domains.auth; import lombok.Data; import lombok.NoArgsConstructor; import lombok.Setter; @Data @Setter @NoArgsConstructor public class AuthTokenDTO { private String access_token; private String refresh_token; private Integer expires_in; private Integer refresh_expires_in; }
C++
UTF-8
1,210
3.125
3
[]
no_license
/* Authors: * Rajdeep Bandopadhyay * Sarah George * Yulia Martinez */ #include <iostream> #include "player.h" using namespace std; Player::Player(){ bet = 0; total = 500; } int Player::getBet(){ return bet; } int Player::getTotal(){ return total; } int Player::releaseBall(){ return wheel.spin(); } void Player::setWheel(int f, int e){ wheel.setStartVal(f); wheel.setEndVal(e); } void Player::showCurrentTotal(){ cout << "Your current total is $" << total; } void Player::setBet(int b){ bet = b; } void Player::incrementTotal(int a){ total = total + a; } void Player::decrementTotal(int c){ total = total - c; } PlayerH::PlayerH(){ bet = 0; total = 0; } int PlayerH::getBet(){ return bet; } int PlayerH::getTotal(){ return total; } int PlayerH::releaseBall(bool playerWon){ return wheel.spin(playerWon); } void PlayerH::setWheel(int f, int e){ wheel.setStartVal(f); wheel.setEndVal(e); } void PlayerH::showCurrentTotal(){ cout << "Your current total is $" << total; } void PlayerH::setBet(int b){ bet = b; } void PlayerH::incrementTotal(int a){ total = total + a; } void PlayerH::decrementTotal(int c){ total = total - c; }
Ruby
UTF-8
2,268
3.03125
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby require 'csv' MONTHS={ "January" => 1, "February" => 2, "March" => 3, "April" => 4, "May" => 5, "June" => 6, "July" => 7, "August" => 8, "September" => 9, "October" => 10, "November" => 11, "December" => 12 } months = MONTHS.keys.join("|") DESTINATIONS = { "Port Phillip" => ["Port Phillip", "New South Wales"], "Moreton Bay" => ["Moreton Bay", "Queensland"], "Maria Island" => ["Maria Island", "Tasmania"], "New South Wales" => ["", "New South Wales"], "Van Diemen" => ["", "Van Diemen's Land"], "Norfolk Island" => ["", "Norfolk Island"], "VDI" => ["", "Van Diemen's Land"], "V.D.I" => ["", "Van Diemen's Land"], "Gibraltar" => ["", "Gibraltrar"], "Western Australia" => ["", "Western Australia"], } INPUT_FILE="cleaned/cleaned.csv" CSV.foreach(INPUT_FILE, :encoding => "ISO-8859-1", :headers => :first_row) do |row| ### date simplification departure_date = row["Date of Departure"] year_matches = /(17|18)\d{2}/.match(departure_date) simple_date = "" year = "" unless year_matches.nil? year = year_matches[0] month_matches = /#{months}/.match(departure_date) unless month_matches.nil? month_number = MONTHS[month_matches[0]] simple_date = "%s-%02i" % [year, month_number] end end #puts simple_date ### vessel simplification vessel = row["Vessel"].to_s simple_vessel = vessel.to_s.gsub(".", "").gsub(/\[.*\]/, "").strip.sub(/[^a-zA-Z]*$/, "").sub("(Ship)", "").sub(/\(Ship$/, "").sub(/ Sentence details.*$/, "") # remove extra spaces in lists of ships simple_vessels = [] simple_vessel.split(";").each do |item| simple_vessels << item.strip end simple_vessel = simple_vessels.join("|") if simple_vessel.start_with? "Lord Lynedoch" simple_vessel = "Lord Lynedoch" end ### destination simplication destination = row["Place of Arrival"] simple_destinations = [] DESTINATIONS.each do |k,v| if destination.downcase.include? k.downcase simple_destinations << v end end simple_destination = simple_destinations[0] #.join(",").to_s #if simple_destination.length == 0 # puts destination #end puts [simple_date,simple_vessel, simple_destination[0], simple_destination[1]].to_csv end
Java
UTF-8
178
1.78125
2
[]
no_license
package _239_sliding_window_maximum; /** * https://leetcode.com/problems/sliding-window-maximum */ public class Solution { public void slidingWindowMaximum() { } }
PHP
UTF-8
2,802
2.78125
3
[]
no_license
<html> <head> <meta http-equiv="refresh" content="120" /> </head> <?php include("includes/configuration.php"); doDB(); function createURL($ticker){ $currentMonth = date("n"); $currentMonth = $currentMonth - 1; $currentDay = date("j"); $currentYear = date("Y"); return "http://ichart.finance.yahoo.com/table.csv?s=$ticker&d=$currentMonth&e=$currentDay&f=$currentYear&g=d&a=12&b=30&c=2009&ignore=.csv"; } function getCSVFile($url, $outputFile){ if (file_exists($outputFile)) { } else { $content = file_get_contents($url); $content = str_replace("Date,Open,High,Low,Close,Volume,Adj Close", "", $content); $content = trim($content); file_put_contents($outputFile, $content); } } function fileToDatabase($txtFile, $tableName){ Global $mysqli; $file = fopen($txtFile,"r"); $sql = "SELECT * FROM $tableName"; $result = mysqli_query($mysqli, $sql); if(!$result){ $sql2 = "CREATE TABLE $tableName (date DATE, PRIMARY KEY(date), open FLOAT, high FLOAT, low FLOAT, close FLOAT, volume INT, amount_change FLOAT, percent_change FLOAT)"; if(mysqli_query($mysqli, $sql2) === TRUE) { //printf("created table"); //$numrows = mysql_num_rows($result); while(!feof($file)){ $line = fgets($file); $pieces = explode(",", $line); $date = $pieces[0]; $open = $pieces[1]; $high = $pieces[2]; $low = $pieces[3]; $close = $pieces[4]; $volume = $pieces[5]; $amount_change = $close-$open; $percent_change = ($amount_change/$open)*100; $sql3 = "INSERT INTO $tableName (date, open, high, low, close, volume, amount_change, percent_change) VALUES ('$date','$open','$high','$low','$close','$volume','$amount_change','$percent_change')"; mysqli_query($mysqli, $sql3); } } } fclose($file); // mysqli_close($mysqli); } function main(){ // Start timer $time_start = microtime(true); $mainTickerFile = fopen("tickerMaster.txt","r"); while(!feof($mainTickerFile)){ $companyTicker = fgets($mainTickerFile); $companyTicker = trim($companyTicker); //$fileURL = createURL($companyTicker); $companyTxtFile = "txtFiles/".$companyTicker.".txt"; //getCSVFile($fileURL, $companyTxtFile); fileToDatabase($companyTxtFile, $companyTicker); $time_end = microtime(true); $time = $time_end - $time_start; if ($time > 100000000) { exit; } } printf("End of file reached"); } main(); ?> </html>
Java
UTF-8
7,696
1.875
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.mapper.integration; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.ConsistentReads; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.SaveBehavior; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DynamoDBEncryptor; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext; import com.amazonaws.services.dynamodbv2.mapper.encryption.StringAttributeTestClass; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestDynamoDBMapperFactory; import com.amazonaws.services.dynamodbv2.mapper.encryption.TestEncryptionMaterialsProvider; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.PutItemRequest; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** Tests simple string attributes */ public class SimpleStringAttributesITCase extends DynamoDBMapperCryptoIntegrationTestBase { private static final String ORIGINAL_NAME_ATTRIBUTE = "originalName"; private static final String STRING_ATTRIBUTE = "stringAttribute"; private static final List<Map<String, AttributeValue>> attrs = new LinkedList<Map<String, AttributeValue>>(); // Test data static { for (int i = 0; i < 5; i++) { Map<String, AttributeValue> attr = new HashMap<String, AttributeValue>(); attr.put(KEY_NAME, new AttributeValue().withS("" + startKey++)); attr.put(STRING_ATTRIBUTE, new AttributeValue().withS("" + startKey++)); attr.put(ORIGINAL_NAME_ATTRIBUTE, new AttributeValue().withS("" + startKey++)); attrs.add(attr); } } ; @BeforeClass public static void setUp() throws Exception { DynamoDBMapperCryptoIntegrationTestBase.setUp(); DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(new TestEncryptionMaterialsProvider()); EncryptionContext context = new EncryptionContext.Builder().withHashKeyName(KEY_NAME).withTableName(TABLE_NAME).build(); // Insert the data for (Map<String, AttributeValue> attr : attrs) { attr = encryptor.encryptAllFieldsExcept(attr, context, KEY_NAME); dynamo.putItem(new PutItemRequest(TABLE_NAME, attr)); } } @Test public void testLoad() throws Exception { DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (Map<String, AttributeValue> attr : attrs) { StringAttributeTestClass x = util.load(StringAttributeTestClass.class, attr.get(KEY_NAME).getS()); assertEquals(x.getKey(), attr.get(KEY_NAME).getS()); assertEquals(x.getStringAttribute(), attr.get(STRING_ATTRIBUTE).getS()); assertEquals(x.getRenamedAttribute(), attr.get(ORIGINAL_NAME_ATTRIBUTE).getS()); } } @Test public void testSave() { List<StringAttributeTestClass> objs = new ArrayList<StringAttributeTestClass>(); for (int i = 0; i < 5; i++) { StringAttributeTestClass obj = getUniqueObject(); objs.add(obj); } DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (StringAttributeTestClass obj : objs) { util.save(obj); } for (StringAttributeTestClass obj : objs) { StringAttributeTestClass loaded = util.load(StringAttributeTestClass.class, obj.getKey()); assertEquals(obj, loaded); } } /** Tests saving an incomplete object into DynamoDB */ @Test public void testIncompleteObject() { StringAttributeTestClass obj = getUniqueObject(); obj.setStringAttribute(null); DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); util.save(obj); assertEquals(obj, util.load(StringAttributeTestClass.class, obj.getKey())); // test removing an attribute assertNotNull(obj.getRenamedAttribute()); obj.setRenamedAttribute(null); util.save(obj); assertEquals(obj, util.load(StringAttributeTestClass.class, obj.getKey())); } @Test public void testUpdate() { List<StringAttributeTestClass> objs = new ArrayList<StringAttributeTestClass>(); for (int i = 0; i < 5; i++) { StringAttributeTestClass obj = getUniqueObject(); objs.add(obj); } DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); for (StringAttributeTestClass obj : objs) { util.save(obj); } for (StringAttributeTestClass obj : objs) { StringAttributeTestClass replacement = getUniqueObject(); replacement.setKey(obj.getKey()); util.save(replacement); assertEquals(replacement, util.load(StringAttributeTestClass.class, obj.getKey())); } } @Test public void testSaveOnlyKey() { KeyOnly obj = new KeyOnly(); obj.setKey("" + startKey++); DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); mapper.save(obj); KeyOnly loaded = mapper.load( KeyOnly.class, obj.getKey(), new DynamoDBMapperConfig(ConsistentReads.CONSISTENT)); assertEquals(obj, loaded); // saving again shouldn't be an error mapper.save(obj); } @Test public void testSaveOnlyKeyClobber() { KeyOnly obj = new KeyOnly(); obj.setKey("" + startKey++); DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo); mapper.save(obj, new DynamoDBMapperConfig(SaveBehavior.CLOBBER)); KeyOnly loaded = mapper.load( KeyOnly.class, obj.getKey(), new DynamoDBMapperConfig(ConsistentReads.CONSISTENT)); assertEquals(obj, loaded); // saving again shouldn't be an error mapper.save(obj, new DynamoDBMapperConfig(SaveBehavior.CLOBBER)); } @DynamoDBTable(tableName = "aws-java-sdk-util-crypto") public static final class KeyOnly { private String key; @DynamoDBHashKey public String getKey() { return key; } public void setKey(String key) { this.key = key; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; KeyOnly other = (KeyOnly) obj; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; return true; } } private StringAttributeTestClass getUniqueObject() { StringAttributeTestClass obj = new StringAttributeTestClass(); obj.setKey(String.valueOf(startKey++)); obj.setRenamedAttribute(String.valueOf(startKey++)); obj.setStringAttribute(String.valueOf(startKey++)); return obj; } }
Python
UTF-8
1,258
3.3125
3
[]
no_license
import requests, json from datetime import datetime # base URL #The Author name is Gayathri URL = "https://api.openweathermap.org/data/2.5/weather?" #City = "Warangal" mylocation = input("Enter the city name:") Api_Key = "cb93812ba032e7c818e82d66ce238df7" # upadting the URL URL = URL + "q=" + mylocation + "&appid=" + Api_Key # HTTP request response = requests.get(URL) api_data=response.json() # checking the status code of the request if response.status_code == 200: # getting data in the json format data = response.json() # getting the main dictionary block main = data['main'] # getting temperature temperature = main['temp'] # getting the humidity humidity = main['humidity'] # getting the windspeed wind_spd=api_data['wind']['speed'] #date_time datetime=datetime.now().strftime("%d %b %Y | %I %M %S %p") # weather report report = data['weather'] print(f"{mylocation:-^30}") print(f"Temperature: {temperature}") print(f"Humidity: {humidity}") print(f"Wind_Speed: {wind_spd}",'kmph') print(f"DateTime: {datetime}") print(f"Weather Report: {report[0]['description']}") else: # showing the error message print("Error in the HTTP request")
Python
UTF-8
340
3.296875
3
[]
no_license
# Import networkx and initialize the graph. import networkx as nx import matplotlib.pyplot as plt G = nx.Graph() G.add_edge('A', 'B') G.add_edge('A', 'C') G.add_edge('D', 'C') G.add_edge('D', 'B') pos = nx.spring_layout(G) nx.draw(G) nx.draw_networkx_labels(G, pos, font_size=20, font_family='sans-serif') # Show the plot. plt.show()
Java
UTF-8
269
1.8125
2
[]
no_license
package com.lovver.ssdbj.core; import com.lovver.ssdbj.exception.SSDBException; public interface Protocol { public String getProtocol(); public String getProtocolVersion(); public CommandExecutor getCommandExecutor(); public void auth() throws SSDBException ; }
Shell
UTF-8
2,122
2.953125
3
[]
no_license
#!/bin/bash # Location to save the MSCOCO data. MSCOCO_DIR="${HOME}/im2txt/data/mscoco" # Build the preprocessing script. cd research/im2txt bazel build //im2txt:download_and_preprocess_mscoco # Run the preprocessing script. bazel-bin/im2txt/download_and_preprocess_mscoco "${MSCOCO_DIR}" # Location to save the Inception v3 checkpoint. INCEPTION_DIR="${HOME}/im2txt/data" mkdir -p ${INCEPTION_DIR} wget "http://download.tensorflow.org/models/inception_v3_2016_08_28.tar.gz" tar -xvf "inception_v3_2016_08_28.tar.gz" -C ${INCEPTION_DIR} rm "inception_v3_2016_08_28.tar.gz" # Directory containing preprocessed MSCOCO data. MSCOCO_DIR="${HOME}/im2txt/data/mscoco" # Inception v3 checkpoint file. INCEPTION_CHECKPOINT="${HOME}/im2txt/data/inception_v3.ckpt" # Directory to save the model. MODEL_DIR="${HOME}/im2txt/model" # Build the model. cd research/im2txt bazel build -c opt //im2txt/... # Run the training script. bazel-bin/im2txt/train \ --input_file_pattern="${MSCOCO_DIR}/train-?????-of-00256" \ --inception_checkpoint_file="${INCEPTION_CHECKPOINT}" \ --train_dir="${MODEL_DIR}/train" \ --train_inception=false \ --number_of_steps=1000000 MSCOCO_DIR="${HOME}/im2txt/data/mscoco" MODEL_DIR="${HOME}/im2txt/model" # Ignore GPU devices (only necessary if your GPU is currently memory # constrained, for example, by running the training script). export CUDA_VISIBLE_DEVICES="" # Run the evaluation script. This will run in a loop, periodically loading the # latest model checkpoint file and computing evaluation metrics. bazel-bin/im2txt/evaluate \ --input_file_pattern="${MSCOCO_DIR}/val-?????-of-00004" \ --checkpoint_dir="${MODEL_DIR}/train" \ --eval_dir="${MODEL_DIR}/eval" MODEL_DIR="${HOME}/im2txt/model" # Run a TensorBoard server. tensorboard --logdir="${MODEL_DIR}" # Restart the training script with --train_inception=true. bazel-bin/im2txt/train \ --input_file_pattern="${MSCOCO_DIR}/train-?????-of-00256" \ --train_dir="${MODEL_DIR}/train" \ --train_inception=true \ --number_of_steps=3000000 # Additional 2M steps (assuming 1M in initial training).
C++
WINDOWS-1251
829
2.921875
3
[]
no_license
#include<iostream> #include "Songs.h" using namespace std; int main() { // // Songs songs; // songs.AddSong("Yesterday"); songs.AddSong("Problem"); songs.AddSong("Happy New Year"); // PopStyleOfMusic *pop = new PopStyleOfMusic(); RapStyleOfMusic *rap = new RapStyleOfMusic(); RockStyleOfMusic *rock = new RockStyleOfMusic(); // songs.SetConcreteStyle(pop); songs.SingSongs(); songs.SetConcreteStyle(rap); songs.SingSongs(); songs.SetConcreteStyle(rock); songs.SingSongs(); delete pop; delete rap; delete rock; return 0; }
Java
UTF-8
407
2.03125
2
[]
no_license
package org.jquant.instrument.rate; import org.joda.time.DateTime; import org.joda.time.Period; import org.jquant.model.Currency; import org.jquant.time.daycounter.DayCounter; public class Euribor extends IborIndex{ public Euribor(DateTime fixingDate, double rate, Currency currency, Period period, DayCounter dayCounter) { super(fixingDate, rate, currency, period, dayCounter,2); } }
Python
UTF-8
52
2.796875
3
[]
no_license
n, a = map(int, input().split()) print((n+a-1)//a)
JavaScript
UTF-8
1,045
2.578125
3
[]
no_license
let id = 0; export default function cart( state = { list: [], open: false }, { type, payload } ) { switch (type) { case "cart/open": return { ...state, open: true, }; case "cart/close": return { ...state, open: false, }; case "cart/add": return { ...state, list: [ ...state?.list, { id: id++, imgUrl: payload.imgUrl, name: payload.name, price: payload.price, quantity: payload.quantity, }, ], }; case "cart/remove": return { ...state, list: state.list.filter((item) => item.id !== payload), }; case "cart/changeQuantity": console.log(payload.change); return { ...state, list: state.list.map((item) => item.id === payload.id ? { ...item, quantity: item.quantity + payload.change } : item ), }; default: return state; } }
PHP
UTF-8
1,824
2.6875
3
[ "MIT" ]
permissive
<?php use App\News; use Illuminate\Http\Request; /** * Вывести список всех задач */ Route::get('/', function () { $news = News::orderBy('created_at', 'asc')->get(); return view('news', [ 'news' => $news ]); }); /** * Вывод административной части */ Route::get('/admin', function () { $news = News::orderBy('created_at', 'asc')->get(); return view('admin', [ 'news' => $news ]); }); /** * Вывод административной части */ Route::any('/concretnews/{id}', function ($id) { $news = News::where('id','=',$id)->get(); return view('concretnews', [ 'news' => $news ]); }); Route::any('/admin/edit/{id}', function($id){ $news = News::where('id','=',$id)->get(); return view ('edit',[ 'news'=>$news ]); }); Route::post('/admin/edit/{id}', function (Request $request) { $item = News::where('id','=',$request->id)->get(); $item->title = $request->title; $item->text = $request->text; $item->update(); return redirect('/admin/edit/{id}'); }); /** * Добавить новую задачу */ Route::post('/admin', function (Request $request) { $validator = Validator::make($request->all(), [ 'title' => 'required|max:255', 'text' => 'required|min:100' ]); if ($validator->fails()) { return redirect('/admin') ->withInput() ->withErrors($validator); } $item = new News; $item->title = $request->title; $item->text = $request->text; $item->save(); return redirect('/admin'); }); /** * Удалить существующую задачу */ Route::delete('/admin/{id}', function ($id) { News::findOrFail($id)->delete(); return redirect('/admin'); });
Python
UTF-8
918
4
4
[]
no_license
import random def generation_random_number(): """Ф-ция генерирует список случайных чисел""" random_list = [] for n in range(10): # кол-во чисел в списке 10 random_list.append(round(random.uniform(1, 100)/3*1.3,2)) return random_list received_list = generation_random_number() # полученный список случайных чисел print('Сгенерированный массив случайных чисел:\n', received_list) print('Минимум в списке (MIN):', min(received_list), '-', end = ' ') print('Номер по порядку в списке:', received_list.index(min(received_list))+1) print('Минимум в списке (MAX):', max(received_list), '-', end = ' ') print('Номер по порядку в списке:', received_list.index(max(received_list))+1) input()
C#
UTF-8
1,365
3.75
4
[]
no_license
using System; namespace Business { public class Coordinate { public readonly int X; public readonly int Y; protected bool Equals(Coordinate other) { return X == other.X && Y == other.Y; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((Coordinate) obj); } public override int GetHashCode() { unchecked { return (X * 397) ^ Y; } } public Coordinate(int x, int y) { this.X = x; this.Y = y; } public Coordinate GetNext(Direction roverCurrentDirection) { switch (roverCurrentDirection) { case Direction.North: return new Coordinate(X , Y+1); case Direction.West: return new Coordinate(X -1, Y); case Direction.South: return new Coordinate(X, Y - 1); case Direction.East: return new Coordinate(X +1, Y); } throw new Exception(); } } }
Python
UTF-8
10,325
2.59375
3
[]
no_license
# -*- coding: utf-8 -*- """ ota installer .. codeauthor:: Fedor Ortyanov <f.ortyanov@roscryptpro.ru> """ import getpass import codecs import os import sys from optparse import OptionParser __author__ = 'Fedor Ortyanov' __version__ = '0.1.0' try: from fabric.api import * # пытаемся импортировать необходимые модули из fabric from fabric.colors import * from fabric.contrib.files import * from fabric.contrib.console import confirm # необходимо для импользования проверок ввода (альтернатива существующему) except ImportError as e: # а если не получается, то скачиваем и устанавливаем fabric # Install dependencies os.system('sudo apt-get install python-pip -y') os.system('sudo pip install fabric --timeout=360') # и снова импортируем эти модули from fabric.api import * from fabric.colors import * from fabric.contrib.files import * from fabric.contrib.console import confirm # необходимо для импользования проверок ввода (альтернатива существующему) def parseOptions(argv): usageStr = """USAGE: python ota_install.py --path <path_to_install> --name <name_of_app> --host <host_string> --user <username>""" parser = OptionParser(usageStr) parser.add_option('--path', dest='path_to_install', help=u"Укажите путь установки, лучше всего /opt/", default='/opt/') parser.add_option('--host', dest='host_string', help=u"Укажите адрес сервера, на котором производить установку, например, 172.20.3.17", default='localhost') parser.add_option('--name', dest='name_of_app', help=u"Укажите имя для маршрутизации (не может содержать русские буквы, пробелы и знаки кроме \"-\")\n" + u"Наилучший вариант: ota-<имя_сервера>", default='ota-web') parser.add_option('--user', dest='username', help=u"Укажите имя пользователя, от имени которого вы планируете производить установку, \n" + u"он должен обладать правами sudo на сервере, который вы указали.", default=getpass.getuser()) options, otherjunk = parser.parse_args(argv) if len(otherjunk) != 0: print 'Use -h for help' raise Exception('Command line input not understood: ' + str(otherjunk)) args = {} args['path_to_install'] = options.path_to_install.rstrip('/') args['host_string'] = options.host_string args['name_of_app'] = options.name_of_app args['username'] = options.username return args class OTA(object): """ Собственно класс инсталлятора """ def __init__(self, path_to_install, name_of_app): self.path_to_install = path_to_install # данные которые будут использоваться для настройки чероки self.name = name_of_app # ######################################################## def get_config(self, filepath): """ Шаблонизация удаленного файла """ # with cd(CWD): content = codecs.open(filepath, 'rb', encoding="utf8").read() # запускаем команду терминала для просмотра содержимого файла и заносим строку с содержимым в content content %= self.__dict__ # подставляем в строку переменные по ключам-атрибутам return content # возвращает отформатированную строку def install_webserver(self): """ Установка веб-сервера """ env.sudo_user = 'root' print(cyan('Install Cherokee')) try: sudo('apt-get install cherokee -y') # скачиваем установочник веб-сервера Чероки except: sudo('add-apt-repository -y ppa:cherokee-webserver') sed('/etc/apt/sources.list.d/cherokee-webserver-ppa-trusty.list', 'trusty', 'saucy', use_sudo=True) sudo('apt-get update') sudo('apt-get install cherokee -y') cherokee_conf = self.get_config(os.path.join(CWD, 'ota_install_stuff/cherokee.conf')) # адрес файла настроек для Чероки append('/etc/cherokee/cherokee.conf', cherokee_conf, use_sudo=True) # заносим в файл отведенный для настроек наши настройки Чероки (дописывает в конец) sudo('/etc/init.d/cherokee start') # запускаем веб-сервер Чероки def make_venv(self): """ Создается хранилище для виртуального окружения в папке с проектом """ sudo('pip install virtualenv') with cd(os.path.join(self.path_to_install, 'ota_web')): sudo('mkdir venv') sudo('virtualenv venv --system-site-package') def env_run(self, command, use_sudo=False, env_name="venv", *args, **kwargs): """ Выполнение команды в виртуальном окружении """ env_var = 'source %s && ' % os.path.join(self.path_to_install, 'ota_web', '%s/bin/activate' % env_name) if use_sudo: if 'user' in kwargs: env.sudo_user = kwargs['user'] else: env.sudo_user = 'root' return sudo(env_var + command, *args, **kwargs) else: return run(env_var + command, *args, **kwargs) def install_requirements(self): """ Подтягиваем pip-ом сорцы из requirements.txt содержащемся в проекте ота_web """ with cd(os.path.join(self.path_to_install, 'ota_web')): self.env_run(command='pip install -r requirements.txt', use_sudo=True) def deploy_ota(self): """ Развертывание ота на сервере из архива (архив создавался из клонированной гитом версии) """ put(os.path.join(CWD, 'ota_web'), self.path_to_install, use_sudo=True) # заливаем на сервак папку с проектом ОТА sudo('rm -rf %s' % os.path.join(self.path_to_install, 'ota_web', '.git')) sudo('rm %s' % os.path.join(self.path_to_install, 'ota_web', 'otaBD.db')) # если есть файл БД то удаляем (сделаем свой с блекджеком и таблицами) self.install_requirements() self.env_run(command='python %s/ota_web/manage.py syncdb --noinput' % self.path_to_install, use_sudo=True) # инициируем создание БД и заливаем туда fixtures (noinput значит без создания суперюзера) sudo('chown %s %s' % (env.user, os.path.join(self.path_to_install, 'ota_web', 'otaBD.db'))) # даем права на доступ к файлу базы для пользователя от имени которого будет импользоваться приложение (от его же имени происходит установка) sudo('chown %s %s' % (env.user, os.path.join(self.path_to_install, 'ota_web'))) # оказывается недостаточно дать права файлу, необходимо дать их также и объемлющей его дирректории with cd(os.path.join(self.path_to_install, 'ota_web')): sudo("mkdir logs") # сюда чероки будет скидывать логи sudo("chmod 777 logs") def clean_server(self): """ Очистка сервера от приложения ОТА """ sed(filename='/etc/cherokee/cherokee.conf', before='# Gen for ota".*"interpreter', after='', use_sudo=True) # очищаем чероки от настроек ота TODO не работает, надо доделать sudo('rm -rf %s' % os.path.join(self.path_to_install, 'ota_web')) # удаляем сам проект с сервера if __name__ == "__main__": CWD = os.path.abspath(os.path.split(sys.argv[0])[0]) print('CWD: %s' % CWD) args = parseOptions(sys.argv[1:]) ota = OTA(path_to_install=args['path_to_install'], name_of_app=args['name_of_app']) env.host_string = '%s@%s' % (args['username'], args['host_string']) env.user = args['username'] env.password = prompt('password: ') env.sudo_user = 'root' with settings(host_string=env.host_string): append('/etc/hosts', '127.0.0.1 %s' % ota.name, use_sudo=True) ota.clean_server() ota.install_webserver() sudo('mkdir %s' % os.path.join(ota.path_to_install, 'ota_web')) ota.make_venv() ota.deploy_ota() sudo('/etc/init.d/cherokee restart') # перезапуск Чероки на всякий
Swift
UTF-8
1,050
3.46875
3
[]
no_license
// // ViewTwo.swift // ViewBuilderTape // // Created by Sraavan Chevireddy on 5/16/21. // import SwiftUI struct ViewTwo: View { var body: some View { NavigationView{ GenericContainer { Text("Hello") Text("World") Text("This is a Generic Container view") Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/, label: { Text("You can also add buttons to this..") }) } .navigationTitle("View Two") } } } struct ViewTwo_Previews: PreviewProvider { static var previews: some View { ViewTwo() } } struct GenericContainer<Content: View> : View{ let content : Content init(@ViewBuilder content: () -> Content) { self.content = content() } var body: some View{ VStack{ content.padding(5) } .padding(10) .background(RoundedRectangle(cornerRadius: 10).fill(Color.red)) .shadow(radius: 5) } }
Java
UTF-8
1,122
4.03125
4
[]
no_license
package com.kyondoku.first.level3; public class Car { String name; String color; int cc; // 1. 생성자이름이 클래스명과 같다. 2. 리턴타입이 없다. public Car() { /*생략가능, 내 직속부모의 주소값 . 내 부모의 기본 생성자를 호출하겠다는 의미*/ this("소나타", "흰색", 2500); } // 스트링값2개와 정수1개를 받는 생성자 public Car(String name, String color, int cc) { // super(); 위에는 아무것도 적을수 없음. super가 가장 먼저 실행되어야 하니까 super(); /* Object의 기본 생성자를 호출 */ this.name = name; this.color = color; this.cc = cc; // this.은 내가 가지고 있는 메소드를 호출 , super.는 부모가 가지고 있는 메소드를 호출 } public Car(String name) { this(name, "검정색", 3000); } public Car(String name, int cc) { this(name, "검정색", cc); } // 생성자는 여러개 만들수 있음. 구분만 할수 있으면. public void introduceMyCar() { System.out.printf("%s의 컬러는 %s이고 %dcc이다.\n" , name, color, cc); } }
Markdown
UTF-8
5,663
3.5
4
[]
no_license
# Vue的菜鳥開發學習歷程 # [Day10] ~~假~~ 認真一下 講講Vue的基本常用語法 續集之續集 --- ## 菜鳥認真講講Vue的基本常用語法 (續中續集) 好的 因為前天要加班一下 掰完“Mustache”语法 又掰太久,留剩下的到昨天 但昨天又手賤又加班了一下 只掰完"v-html"語法 好的 今天得努力下繼續生後面的兩個... --- 再補最後一次,一個component,基本上包含三個部分: - &lt;template&gt;: Html樣板 - &lt;script&gt;: JavaScript的部分,Vue的程式碼 - &lt;style&gt;: CSS樣式的部分 好的~ - Vue的基本語法1: **[Interpolations(插值)](https://vuejs.org/v2/guide/syntax.html#Interpolations)** ,作數據綁定 不同的插法不同的效果(笑): - 1. Text (文本) “Mustache”语法 (双大括号) ,「 **{{ }}** 」,最常見簡單的作法 ```html <span>Message: {{ msg }}</span> ``` Mustache標籤,也就是「{{ }}」會將包起來的區塊渲染成msg的值 - 2. Raw HTML (原始HTML) “v-html”语法 的使用,插入Raw Html ```html <p>Using v-html directive: <span v-html="rawHtml"></span></p> ``` ```javascript rawHtml = '<span style="color: #f00;">原始HTML</div>'; ``` 將將~ 簡單吧~(笑)![/images/emoticon/emoticon38.gif](/images/emoticon/emoticon38.gif) 好的~ 再繼續剩下兩個 - 3. Attributes (屬性綁定、單向綁定) 「 **v-bind** 」這方法跟 “Mustache”语法 一樣,是最常見常用的方式 因為 “Mustache”语法 不能作用在Html的attribute上,所以 將將~ 就靠它了 直接來個例子吧 ```html <p v-bind:id="myId"></p> ``` ```javascript myId = 'myParagraph'; ``` 融合~~~&darr; ```html <p id="myParagraph"></p> ``` 簡單吧~ 來附附個畫面 ![step 1](https://torotu.github.io/ITKeepSharing200806/img/day10/step_1.jpg) ![step 2](https://torotu.github.io/ITKeepSharing200806/img/day10/step_2.jpg) ![step 3](https://torotu.github.io/ITKeepSharing200806/img/day10/step_3.jpg) !! 哎唷 有沒有看到又紅又橘的框框 寫法不同 但效果一樣![/images/emoticon/emoticon64.gif](/images/emoticon/emoticon64.gif) 沒錯!!!! 「 **v-bind:id** 」跟「 **:id** 」都是一樣做屬性綁定(單向綁定)的, 所以「 **v-bind:&lt;attributes&gt;** 」的縮寫為「 **:&lt;attributes&gt;** 」 ***!!兄台留步!!*** 以為這樣就沒了!? 別急,魔鬼藏在細節裡 官方文件說了 > In the case of ***boolean attributes***, where their mere existence implies true, v-bind works a little differently. In this example: > ```html > <button v-bind:disabled="isButtonDisabled">Button</button> > ``` > If isButtonDisabled has the value of null, undefined, or false, the disabled attribute will not even be included in the rendered <button> element. > > ***[Attributes](https://vuejs.org/v2/guide/syntax.html#Attributes)*** 直接上個畫面吧 ![step 4](https://torotu.github.io/ITKeepSharing200806/img/day10/step_4.jpg) - 4. Using JavaScript Expressions (JavaScript表達式) 來吧~ 這最後的插法,簡單來說 Javascript的加減法,就是一種表達式 ...!?(蛤) ```javascript var sum = 1 + 2; ``` 老師:「來~同學,sum是多少~」 同學們心不甘情不願:「 3 」~~ 老師:「...」 老師:「好棒唷 答對了~」 對! 就是這樣 咦!? 但我這值想在畫面顯示而已,還用一個sum變數存起來?? 將將~ vue支援這樣的寫法,直~~接寫在「 **所有數據的綁定** 」都支持 來個官方例子 ```html {{ number + 1 }} {{ ok ? 'YES' : 'NO' }} {{ message.split('').reverse().join('') }} <div v-bind:id="'list-' + id"></div> ``` 厲害吧~ ![step 5](https://torotu.github.io/ITKeepSharing200806/img/day10/step_5.jpg) ![step 6](https://torotu.github.io/ITKeepSharing200806/img/day10/step_6.jpg) ***!!兄台再留步!!*** 魔鬼又藏在細節裡 官方文件又說了 > These expressions will be evaluated as JavaScript in the data scope of the owner Vue instance. One restriction is that each binding can only contain one single expression, so the following will ***NOT work***: > ```html > <!-- this is a statement, not an expression: --> > {{ var a = 1 }} > > <!-- flow control won't work either, use ternary expressions --> > {{ if (ok) { return message } }} > ``` > Template expressions are sandboxed and only have access to a whitelist of globals such as Math and Date. You should not attempt to access user defined globals in template expressions. > > ***[Using JavaScript Expressions](https://vuejs.org/v2/guide/syntax.html#Using-JavaScript-Expressions)*** 上...算了 各位自己試吧~哈 將將~快了時光總是過得特別快 明天再續吧~ 明天續續~![/images/emoticon/emoticon69.gif](/images/emoticon/emoticon69.gif)
PHP
UTF-8
2,324
2.84375
3
[]
no_license
<?php $servername = "localhost"; $username = "root"; $password = "root"; $dbname = "nbp"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } if ($_POST){ $eur = null; $usd = null; $gbp = null; $chf = null; $date = $_POST['date']; $newDate = date("Y-m-d", strtotime($date)); $file = @file_get_contents("http://api.nbp.pl/api/exchangerates/tables/a/" . $newDate . "?format=json"); $json = json_decode($file, TRUE); for ($i = 0; $i < sizeof($json[0]['rates']); $i++){ if ($json[0]['rates'][$i]['code'] == "EUR"){ $eur = $json[0]['rates'][$i]['mid']; }elseif ($json[0]['rates'][$i]['code'] == "USD"){ $usd = $json[0]['rates'][$i]['mid']; }elseif ($json[0]['rates'][$i]['code'] == "GBP"){ $gbp = $json[0]['rates'][$i]['mid']; }elseif ($json[0]['rates'][$i]['code'] == "CHF"){ $chf = $json[0]['rates'][$i]['mid']; } } $aTableName = $json[0]['no']; } $sql = "INSERT INTO kursy_walut (eur, usd, gbp, chf, nazwa, zapytanie) VALUES ('" . $eur . "', '" . $usd . "', '" . $gbp . "', '" . $chf . "', '" . $aTableName . "', '" . $newDate . "')"; $table1 = ""; if (mysqli_query($conn, $sql)) { $table1 = "<div class=\"table-nbp\"> <table> <tr> <th>Data</th> <td>$newDate</td> </tr> <tr> <th>Tabela</th> <td>$aTableName</td> </tr> <tr> <th>EUR</th> <td>$eur</td> </tr> <tr> <th>USD</th> <td>$usd</td> </tr> <tr> <th>GBP</th> <td>$gbp</td> </tr> <tr> <th>CHF</th> <td>$chf</td> </tr> </table> </div>"; } $sql_get_last_10 = "SELECT * FROM kursy_walut ORDER BY pid DESC LIMIT 10"; $result = mysqli_query($conn, $sql_get_last_10) ; $table2 = " <div class=\"table-nbp\"> <table> <tr> <th>Zapytanie</th> <th>Czas</th> </tr>"; if (mysqli_num_rows($result) > 0){ while($row = mysqli_fetch_assoc($result)){ $table2 .="<tr> <td>".$row["zapytanie"]."</td> <td>".$row["czas"]."</td> </tr>"; } }else{ $table2 = ""; } $table2 .= "</table></div>"; if ($file === FALSE){ $table1 = ""; $table2 = ""; $sql = "INSERT INTO kursy_walut (zapytanie) VALUES ('$newDate')"; mysqli_query($conn, $sql); } echo $table1; echo $table2; $conn->close(); ?>
Java
UTF-8
785
2.421875
2
[]
no_license
package pl.my.quickcash.data.converter; import pl.my.quickcash.controllers.modelfx.ClientAccountFx; import pl.my.quickcash.data.client.ClientAccount; public class ClientAccountConverter { public static ClientAccount convertToAccount(ClientAccountFx clientAccountFx) { ClientAccount clientAccount = new ClientAccount(clientAccountFx.getAccountBalance(), clientAccountFx.getAccountNumber()); return clientAccount; } public static ClientAccountFx convertToAccountFx(ClientAccount clientAccount) { ClientAccountFx clientAccountFx = new ClientAccountFx(); clientAccountFx.setAccountBalance(clientAccount.getAccountBalance()); clientAccountFx.setAccountNumber(clientAccount.getAccountNumber()); return clientAccountFx; } }
PHP
UTF-8
831
2.71875
3
[]
no_license
<?php $error = 'faltan_valores'; if (empty($_POST['nombre']) && empty($_POST['apellidos']) && empty($_POST['edad']) && empty($_POST['mail']) && empty($_POST['pass']) ) { $error = 'faltan_valores'; header("Location:index.php?error=$error"); }else { $error = 'ok'; $nombre = $_POST['nombre']; $apellidos = $_POST['apellidos']; $edad = $_POST['edad']; $mail = $_POST['mail']; $pass = $_POST['pass']; } ?> <!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <?php if ($error == 'ok'): ?> <p><?=$nombre?></p> <p><?=$apellidos?></p> <p><?=$edad?></p> <p><?=$mail?></p> <p><?=$pass?></p> <?php endif; ?> </body> </html>
PHP
UTF-8
1,911
2.65625
3
[]
no_license
<?php require_once 'header.php'; $path = "/opt/bitnami/apache2/htdocs/TimelyFlies/"; if ($loggedin) { if (isset($_SESSION['user'])) { $user = sanitizeString($_SESSION['user']); $path .= $user . "/"; echo "<div id='container'><div id='header' class='header'><h2>File Uploader</h2></div>"; echo "<h4>You can use this tool to upload files such as tickets or boarding passes. Permitted extensions are "; $allowedextensions = array("gif", "jpeg", "jpg", "png", "pdf"); $size = count($allowedextensions); for($i = 0; $i < $size-1; $i++) { echo "$allowedextensions[$i], "; } $lastelement = $size - 1; echo "and $allowedextensions[$lastelement]. "; echo "<div id='menu' class='menubar'>"; echo "<form action='uploader.php' method='post'"; echo "enctype='multipart/form-data'>"; echo "<label for='file'>Filename:</label>"; echo "<input type='file' name='file' id='file'/><br/>"; echo "<input type='submit' name='submit' value='Upload'/>"; echo "</form>"; echo "</div>"; echo "<div id='flights' class='main'>"; echo "<br><br/>"; echo "<h4>Your Files:</h4>"; //echo "List user's files here<br/><br/>"; if ($handle = opendir("$path")) { while (false !== ($entry = readdir($handle))) { if ($entry != "." && $entry != "..") { $filepath = "$user/$entry"; echo "<a href='viewfile.php?file=$entry'>$entry</a>"; echo "<br/><br/>"; } } closedir($handle); } echo "</div></div>"; } else { echo "Error with user account"; } echo "</body></html>"; } else { die("You are not logged in. Please <a href='login.php'>click here</a> to log in."); } ?>
Shell
UTF-8
191
3.109375
3
[]
no_license
#!/bin/bash for filename in *.pdf; do target=$(echo ${filename} | sed 's/^\(\([0-9]\{4\}\)\([0-9]\{2\}\).*\)$/\2\/\3\/\1/') mkdir -p $(dirname ${target}) mv ${filename} ${target} done
C++
UTF-8
1,303
2.84375
3
[]
no_license
#define pb push_back typedef pair<int, int> pii; #define f first #define s second #define mp make_pair bool unequal(int a, int b, int c, int d){ if(a == b) return false; if(a == c) return false; if(a == d) return false; if(b == c) return false; if(c == d) return false; if(b == d) return false; return true; } vector<int> Solution::equal(vector<int> &A) { int n = A.size(); map< int, vector<pii> > m; vector<int> output; vector<int> helper; for(int i = 0; i < n; i++){ for(int j = i+1; j < n; j++){ if(m.find(A[i]+A[j]) != m.end()){ for(int k = 0; k < m[A[i]+A[j]].size(); k++){ if(unequal(m[A[i]+A[j]][k].f, m[A[i]+A[j]][k].s, i, j)){ helper.clear(); helper.pb(m[A[i]+A[j]][k].f); helper.pb(m[A[i]+A[j]][k].s); helper.pb(i); helper.pb(j); if(output.size() == 0 || helper < output){ output = helper; } } } } if(m.find(A[i]+A[j]) == m.end()) m[A[i]+A[j]].pb(mp(i, j)); } } return output; }
PHP
UTF-8
4,506
2.90625
3
[]
no_license
<?php class Database { private static $dsn = 'mysql:host=localhost;dbname=contact_newsletter'; private static $username = 'root'; private static $password = ''; private static $db; private function __construct() {} public static function getDB () { if (!isset(self::$db)) { try { self::$db = new PDO(self::$dsn, self::$username, self::$password); } catch (PDOException $e) { $error_message = $e->getMessage(); echo $error_message; //include('../errors/database_error.php'); exit(); } } return self::$db; } } class Employee { private $id; public $firstName, $lastName; public function __construct($id, $firstName, $lastName) { $this->id = $id; $this->firstName = $firstName; $this->lastName = $lastName; } public function getID() { return $this->id; } public function setID($value) { $this->id = $value; } public function getFirstName() { return $this->firstName; } public function setFirstName($value) { $this->firstName = $value; } public function getLastName() { return $this->lastName; } public function setLastName($value) { $this->lastName = $value; } } class EmployeeDB { public static function getEmployees() { $db = Database::getDB(); $query = 'SELECT * FROM employee ORDER BY employeeID'; $statement = $db->prepare($query); $statement->execute(); $employees = array(); foreach ($statement as $row) { $employee = new Employee($row['employeeID'], $row['firstName'], $row['lastName'] ); $employees[] = $employee; } return $employees; } } $employees = EmployeeDB::getEmployees(); ?> <!DOCTYPE html> <!--Week 3 Project--> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="css/bootstrap.min.css" rel="stylesheet"> <link href="css/style.css" rel="stylesheet"> <title>Contact confirmation</title> </head> <body> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="index.html">Throat Honey - Boise Skate Punk</a> </div> <div class="collapse navbar-collapse" id="myNavbar"> <ul class="nav navbar-nav navbar-right"> <li class="active"><a href="index.html">Home</a></li> <li><a href="info.html">Calculate</a></li> <li><a href="newsletter.html">News</a></li> <li><a href="contact.html">Contact</a></li> <li><a href="faq.html">FAQ</a></li> </div> </div> </nav> <br> <br> <br> <div class="inner cover"> <br> <main> <!-- Display all employees --> <h1>Employee List:</h1> <br> <?php foreach ($employees as $employee) : ?> <li> <?php echo $employee->getID(); ?> <?php echo $employee->getFirstName(); ?> <?php echo $employee->getLastName(); ?> </li> <?php endforeach; ?> </main> </div> </body> </html>
Markdown
UTF-8
2,429
3.8125
4
[]
no_license
# Structured Query Language- SQL SQL, or Structured Query Language, is a language designed to allow both technical and non-technical users query, manipulate, and transform data from a relational database. And due to its simplicity, SQL databases provide safe and scalable storage for millions of websites and mobile applications. ## Relational databases A relational database represents a collection of related (two-dimensional) tables. Each of the tables are similar to an Excel spreadsheet, with a fixed number of named columns (the attributes or properties of the table) and any number of rows of data. SELECT queries * SELECT statements, which are often colloquially refered to as queries. * Query * Is a statement * declares what data is being searched * where to find data * how to transform it before it is returned Each rowe in a table has an instance - This means that the columns would then represent the common properties shared by all instances of that entity Select query for a specific columns `SELECT column, another_column, ...` `FROM mytable;`' Select query for all columns `SELECT *` `FROM mytable;` Queries with constraints `SELECT column, another_column, ...` `FROM mytable` `WHERE *CONDITION*` `AND/OR another_condition` `AND/OR ...;` More complex clauses can be constructed by joining numerous AND or OR logical keywords (ie. num_wheels >= 4 AND doors <= 2). And below are some useful operators that you can use for numerical data (ie. integer or floating point): Operator| Condition |SQL Example =, !=, < <=, >, >= |Standard numerical operators| col_name != 4 BETWEEN … AND … |Number is within range of two values (inclusive)| col_name BETWEEN 1.5 AND 10.5 NOT BETWEEN … AND … |Number is not within range of two values (inclusive)| col_name NOT BETWEEN 1 AND 10 IN (…) |Number exists in a list| col_name IN (2, 4, 6) NOT IN (…) |Number does not exist in a list| col_name NOT IN (1, 3, 5) exp. Find the movies not released in the years between 2000 and 2010 `SELECT title, year FROM movies` `WHERE year BETWEEN 2000 AND 2010;` ### Queries with constraints ### Filtering and Sorting Query results Select query with ordered results `SELECT column, another_column, …` `FROM mytable` `WHERE condition(s)` `ORDER BY column ASC/DESC;` ### Simple SELECT Queries [Read more](https://sqlbolt.com/lesson/select_queries_with_joins)
Python
UTF-8
710
2.9375
3
[ "MIT" ]
permissive
""" This module implements the simple rule that checks whether the loop terminates immediately because of the initial condition """ from diofant import sympify from .expression import get_initial_polarity_for_expression from .rule import Rule, Result from .utils import Answer class InitialStateRule(Rule): def is_applicable(self): return True def run(self, result: Result): loop_guard = sympify(self.program.loop_guard) maybePos, _ = get_initial_polarity_for_expression(loop_guard, self.program) if maybePos: return result result.PAST = Answer.TRUE result.AST = Answer.TRUE result.NONTERM = Answer.FALSE return result
Java
UTF-8
1,306
3.25
3
[]
no_license
package cn.colining.leetcode.string; import java.util.Scanner; /** * Created by colin on 2017/9/4. */ public class leetcode_14 { public static void main(String[] args) { // Scanner scanner = new Scanner(System.in); // while (scanner.hasNext()) { // int n = scanner.nextInt(); // String[] strs = new String[n]; // for (int i = 0; i < n; i++) { // strs[i] = scanner.next(); // } // System.out.println(longestCommonPrefix(strs)); // } String[] strings = new String[]{"", ""}; longestCommonPrefix(null); } public static String longestCommonPrefix(String[] strs) { StringBuilder stringBuilder = new StringBuilder(); if (strs==null || strs.length==0||strs[0] == null || strs[0].length() == 0) { return ""; } for (int i = 0; i < strs[0].length(); i++) { char a = strs[0].charAt(i); for (int j = 1; j < strs.length; j++) { if (strs[j] == null ||strs[j].length() == 0|| i>=strs[j].length()||strs[j].charAt(i) != a) { return String.valueOf(stringBuilder); } } stringBuilder.append(a); } return String.valueOf(stringBuilder); } }
Java
UTF-8
4,818
2.09375
2
[]
no_license
/* Obj-C to Java: * Class: NSColor. * Source File: NSColor.h. * Module: OpenStep : AppKit. * Time stamp: Mon Jun 23 22:55:01 1997. */ package openstep.appkit; import openstep.foundation.*; import openstep.appkit.*; class ColorComponents { float v1, v2, v3, v4; } public class OSColor extends OSObject implements OSCoding { // Class variables. static OSColor[] predefinitions; // Instance Variables. String colorspace_name; String catalog_name; String color_name; ColorComponents component; float white_component; int active_component; float alpha_component; boolean is_clear; // Methods. static OSColor colorWithCalibratedHue_saturation_brightness_alpha(float hue, float saturation, float brightness, float alpha) { return null; } static OSColor colorWithCalibratedRed_green_blue_alpha(float red, float green, float blue, float alpha) { return null; } static OSColor colorWithCalibratedWhite_alpha(float white, float alpha) { return null; } static OSColor colorWithCatalogName_colorName(String listName, String colorName) { return null; } static OSColor colorWithDeviceCyan_magenta_yellow_black_alpha(float cyan, float magenta, float yellow, float black, float alpha) { return null; } static OSColor colorWithDeviceHue_saturation_brightness_alpha(float hue, float saturation, float brightness, float alpha) { return null; } static OSColor colorWithDeviceRed_green_blue_alpha(float red, float green, float blue, float alpha) { return null; } static OSColor colorWithDeviceWhite_alpha(float white, float alpha) { return null; } static OSColor blackColor() { return null; } static OSColor blueColor() { return null; } static OSColor brownColor() { return null; } static OSColor clearColor() { return null; } static OSColor cyanColor() { return null; } static OSColor darkGrayColor() { return null; } static OSColor grayColor() { return null; } static OSColor greenColor() { return null; } static OSColor lightGrayColor() { return null; } static OSColor magentaColor() { return null; } static OSColor orangeColor() { return null; } static OSColor purpleColor() { return null; } static OSColor redColor() { return null; } static OSColor whiteColor() { return null; } static OSColor yellowColor() { return null; } static boolean ignoresAlpha() { return false; } static void setIgnoresAlpha(boolean flag) { } void getCyan_magenta_yellow_black_alpha(float cyan, float magenta, float yellow, float black, float alpha) { } void getHue_saturation_brightness_alpha(float hue, float saturation, float brightness, float alpha) { } void getRed_green_blue_alpha(float red, float green, float blue, float alpha) { } void getWhite_alpha(float white, float alpha) { } float alphaComponent() { return 0.0f; } float blackComponent() { return 0.0f; } float blueComponent() { return 0.0f; } float brightnessComponent() { return 0.0f; } String catalogNameComponent() { return null; } String colorNameComponent() { return null; } float cyanComponent() { return 0.0f; } float greenComponent() { return 0.0f; } float hueComponent() { return 0.0f; } String localizedCatalogNameComponent() { return null; } String localizedColorNameComponent() { return null; } float magentaComponent() { return 0.0f; } float redComponent() { return 0.0f; } float saturationComponent() { return 0.0f; } float whiteComponent() { return 0.0f; } float yellowComponent() { return 0.0f; } String colorSpaceName() { return null; } OSColor colorUsingColorSpaceName(String colorSpace) { return null; } OSColor colorUsingColorSpaceName_device(String colorSpace, OSDictionary deviceDescription) { return null; } OSColor blendedColorWithFraction_ofColor(float fraction, OSColor aColor) { return null; } OSColor colorWithAlphaComponent(float alpha) { return null; } static OSColor colorFromPasteboard(OSPasteboard pasteBoard) { return null; } void writeToPasteboard(OSPasteboard pasteBoard) { } void drawSwatchInRect(OSRect rect) { } void set() { } void encodeWithCoder(Object aCoder) { } Object initWithCoder(Object aDecoder) { return null; } }
PHP
UTF-8
2,420
2.640625
3
[]
no_license
<?php $query_result = $obj_app -> select_all_reservation_info(); //$query_result1=$obj_app->select_category_info_by_id(); ?> <head> <style> table tr { padding: 2px; } table tr th, td { padding: 20px; } </style> </head> <div class="container"> <h2>Here is your Bill</h2> <div class="row"> <table border="1"> <tr> <th>Room Category</th> <th>Number Of Rooms</th> <th>Number Of Days</th> <th>Price Per Room</th> <th>Total Bill</th> </tr> <?php $res_info = mysqli_fetch_assoc($query_result) ?> <tr> <td><?php echo $res_info['category_name'] ?></td> <td><?php echo $res_info['total_room'] ?></td> <td><?php $s_date = $res_info['arrival_date']; $d_date = $res_info['departure_date']; $date1 = date_create("$s_date"); $date2 = date_create("$d_date"); $diff = date_diff($date1, $date2); $d_diff=$diff -> format("%a days"); echo $d_diff; ?></td> <td><?php echo $res_info['room_price'] ?></td> <td><h4><?php $total= $res_info['total_room']* $d_diff*$res_info['room_price']; echo $total; ?></h4></td> </tr> </table> </div> </div> <?php if (isset($_POST['btn'])) { $obj_app->save_booking_info($_POST); } ?> <div class="container"> <div class="row"> <form action="" method="post"> <table> <tr> <td> <h4> Select how do u want to pay:</h4></td> </tr> <tr> <td>Cash On Delivery</td> <td><input type="radio" value="1" name="payment_type"></td> </tr> <hr/> <tr> <td>BKash</td> <td><input type="radio" value="2" name="payment_type"></td> </tr> <tr> <td> <input type="submit" name="btn" value="Confirm Payment" ></td> </tr> </table> </form> </div> </div>
Java
UTF-8
361
1.859375
2
[]
no_license
package net.sf.minuteProject.facade.face; import java.util.List; import net.sf.minuteProject.configuration.bean.Reference; import org.apache.ddlutils.model.Column; public interface EntityFacade { public Column getPrimaryKey(); public List<Column> getAttributes (); public List<Reference> getParents (); public List<Reference> getChildren (); }
JavaScript
UTF-8
37,754
2.765625
3
[]
no_license
//说明统一返回值中都含有一个code -= 10001 的时候 是正常返回,10002是异常,10003 没有查询到数据 asyncFlag同步为false,异步为true,默认同步 //任何可以后台执行的方法 function ajaxGetColums(tablename,asyncFlag){ if(!asyncFlag){ asyncFlag=false; } var resultdata=null; var data={}; data['tablename']=tablename; var dataUrl=basePath+'/zbjc/findColsList'; // 调用后台 $.ajax({ url :dataUrl,//后台处理程序 type:"post", //数据发送方式 async:asyncFlag, //同步为false,异步为true dataType:"text", //接受数据格式 data:data, success: function(result){//执行成功后 var da=eval('('+result+')'); resultdata=da; } }); return resultdata; } /** * * * @param configParam:对象相当于map * @param url:调用后台的url * @param asyncFlag :同步是false,异步true * @param returnmethod :回执方法名 * @returns */ function ajaxMethod(configParam,url,asyncFlag,returnmethod){ if(!asyncFlag){ asyncFlag=false; } var resultdata=null; var data={}; data['configParam']=JSON.stringify(configParam); var dataUrl=url; // 调用后台 $.ajax({ url :dataUrl,//后台处理程序 type:"post", //数据发送方式 async:asyncFlag, //同步为false,异步为true dataType:"text", //接受数据格式 data:data, success: function(result){//执行成功后 var da=eval('('+result+')'); resultdata=da; if(returnmethod){ //调用回执方法,可以有也可以自己手动处理 eval(returnmethod+'('+result+')'); } } }); return resultdata; } //单表操作-------- //1 增加 function ajaxAddSingleInfo(addInfo,typename,asyncFlag){ if(!asyncFlag){ asyncFlag=false; } var resultdata=null; var data={}; data['addInfo']=JSON.stringify(addInfo); data['typename']=typename; var dataUrl=basePath+'/share/addSingleInfo'; // 调用后台 $.ajax({ url :dataUrl,//后台处理程序 type:"post", //数据发送方式 async:asyncFlag, //同步为false,异步为true dataType:"text", //接受数据格式 data:data, success: function(result){//执行成功后 var da=eval('('+result+')'); resultdata=da; } }); return resultdata; } //2修改 /** * modifyInfo:修改内容{'bs':'1'} * typename:修改的类型名称,对应dataConfig.pro里面的表 * condition:是更该的条件{'id':'xxx'} */ function ajaxModifySingleInfo(modifyInfo,typename,condition,asyncFlag){ if(!asyncFlag){ asyncFlag=false; } var resultdata=null; var data={}; data['modifyInfo']=JSON.stringify(modifyInfo); data['condition']=JSON.stringify(condition); data['typename']=typename; var dataUrl=basePath+'/share/modifySingleInfo'; // 调用后台 $.ajax({ url :dataUrl,//后台处理程序 type:"post", //数据发送方式 async:asyncFlag, //同步为false,异步为true dataType:"text", //接受数据格式 data:data, success: function(result){//执行成功后 var da=eval('('+result+')'); resultdata=da; } }); return resultdata; } //3删除 /** * typename:修改的类型名称,对应dataConfig.pro里面的表 * condition:where条件 {id:xx,name:'zhangsan'} * resultdata:code 10001 就是成功的,否则失败的 */ function ajaxDelInfo(delInfo,typename,asyncFlag){ if(!asyncFlag){ asyncFlag=false; } var resultdata=null; var data={}; data['condition']=JSON.stringify(delInfo); data['typename']=typename; var dataUrl=basePath+'/share/delInfo'; // 调用后台 $.ajax({ url :dataUrl,//后台处理程序 type:"post", //数据发送方式 async:asyncFlag, //同步为false,异步为true dataType:"text", //接受数据格式 data:data, success: function(result){//执行成功后 var da=eval('('+result+')'); resultdata=da; } }); return resultdata; } //4查询list /** * typename:修改的类型名称,对应dataConfig.pro里面的表 * condition:where条件 * asyncFlag:可选,设置是异步还是同步,true是异步,false,是同步 * processResultMethod:处理结果的方法,可选可不选 */ function ajaxFindList(condition,typename,processResultMethod,asyncFlag){ if(!asyncFlag){ asyncFlag=false; } var resultdata=null; var data={}; data['condition']=JSON.stringify(condition); data['typename']=typename; var dataUrl=basePath+'/share/findList'; // 调用后台 $.ajax({ url :dataUrl,//后台处理程序 type:"post", //数据发送方式 async:asyncFlag, //同步为false,异步为true dataType:"text", //接受数据格式 data:data, success: function(result){//执行成功后 var da=eval('('+result+')'); resultdata=da; if(processResultMethod){ //调用方法,这样是为了异步处理数据设计的 eval(processResultMethod+'('+result+')'); } } }); return resultdata; } //5分页查询 /** * typename:修改的类型名称,对应dataConfig.pro里面的表 * condition:where条件 */ function ajaxFindListPage(condition,typename,asyncFlag){ if(!asyncFlag){ asyncFlag=false; } var resultdata=null; var data={}; data['condition']=JSON.stringify(condition); data['typename']=typename; var dataUrl=basePath+'/share/findListPage'; // 调用后台 $.ajax({ url :dataUrl,//后台处理程序 type:"post", //数据发送方式 async:asyncFlag, //同步为false,异步为true dataType:"text", //接受数据格式 data:data, success: function(result){//执行成功后 var da=eval('('+result+')'); resultdata=da; } }); return resultdata; } //6单个查询 /** * typename:修改的类型名称,对应dataConfig.pro里面的表 * condition:where条件 * asyncFlag:可选,设置是异步还是同步,true是异步,false,是同步 * processResultMethod:处理结果的方法,可选可不选 */ function ajaxFindSingInfo(condition,typename,processResultMethod,asyncFlag){ if(!asyncFlag){ asyncFlag=false; } var resultdata=null; var data={}; data['condition']=JSON.stringify(condition); data['typename']=typename; var dataUrl=basePath+'/share/findSingInfo'; // 调用后台 $.ajax({ url :dataUrl,//后台处理程序 type:"post", //数据发送方式 async:asyncFlag, //同步为false,异步为true dataType:"text", //接受数据格式 data:data, success: function(result){//执行成功后 var da=eval('('+result+')'); resultdata=da; if(processResultMethod){ //调用方法,这样是为了异步处理数据设计的 eval(processResultMethod+'('+result+')'); } } }); return resultdata; } //多表操作--------- //1查询list /** * methodName:查询方法 * condition:where条件 如果没有传值 为 '' * paramconfig:是参数,不是用于where,而是用于mybatis 如果没有传值 为 '' */ function ajaxFindListSql(condition,methodName,paramconfig,asyncFlag){ if(!asyncFlag){ asyncFlag=false; } var resultdata=null; var data={}; data['condition']=JSON.stringify(condition); data['paramconfig']=JSON.stringify(paramconfig); data['methodName']=methodName; var dataUrl=basePath+'/share/findListSql'; // 调用后台 $.ajax({ url :dataUrl,//后台处理程序 type:"post", //数据发送方式 async:asyncFlag, //同步为false,异步为true dataType:"text", //接受数据格式 data:data, success: function(result){//执行成功后 var da=eval('('+result+')'); resultdata=da; } }); return resultdata; } //1.2查询list /** * sql:sql内容 */ function ajaxFindListSqlParam(sql,asyncFlag){ if(!asyncFlag){ asyncFlag=false; } var resultdata=null; var data={}; data['sql']=sql; var dataUrl=basePath+'/share/findListSqlParam'; // 调用后台 $.ajax({ url :dataUrl,//后台处理程序 type:"post", //数据发送方式 async:asyncFlag, //同步为false,异步为true dataType:"text", //接受数据格式 data:data, success: function(result){//执行成功后 var da=eval('('+result+')'); resultdata=da; } }); return resultdata; } function ajaxDelInfoSql(condition,methodName,asyncFlag){ if(!asyncFlag){ asyncFlag=false; } var resultdata=null; var data={}; data['condition']=JSON.stringify(condition); data['methodName']=methodName; var dataUrl=basePath+'/share/findListSql'; // 调用后台 $.ajax({ url :dataUrl,//后台处理程序 type:"post", //数据发送方式 async:asyncFlag, //同步为false,异步为true dataType:"text", //接受数据格式 data:data, success: function(result){//执行成功后 var da=eval('('+result+')'); resultdata=da; } }); return resultdata; } //2分页查询 /** * methodName:查询方法 * condition:where条件 如果没有传值 为 '' * paramconfig:是参数,不是用于where,而是用于mybatis 如果没有传值 为 '' */ function ajaxFindListPageSql(condition,methodName,paramconfig,asyncFlag){ if(!asyncFlag){ asyncFlag=false; } var resultdata=null; var data={}; data['condition']=JSON.stringify(condition); data['paramconfig']=JSON.stringify(paramconfig); data['methodName']=methodName; var dataUrl=basePath+'/share/findListPageSql'; // 调用后台 $.ajax({ url :dataUrl,//后台处理程序 type:"post", //数据发送方式 async:asyncFlag, //同步为false,异步为true dataType:"text", //接受数据格式 data:data, success: function(result){//执行成功后 var da=eval('('+result+')'); resultdata=da; } }); return resultdata; } /** * methodName:查询方法 * condition:where条件 如果没有传值 为 '' * paramconfig:是参数,不是用于where,而是用于mybatis 如果没有传值 为 '' */ function ajaxFindListPageSqlOutWhere(condition,methodName,paramconfig,asyncFlag){ if(!asyncFlag){ asyncFlag=false; } var resultdata=null; var data={}; data['condition']=JSON.stringify(condition); data['paramconfig']=JSON.stringify(paramconfig); data['methodName']=methodName; var dataUrl=basePath+'/share/findListPageSqlOutWhere'; // 调用后台 $.ajax({ url :dataUrl,//后台处理程序 type:"post", //数据发送方式 async:asyncFlag, //同步为false,异步为true dataType:"text", //接受数据格式 data:data, success: function(result){//执行成功后 var da=eval('('+result+')'); resultdata=da; } }); return resultdata; } //3单个查询 /** * methodName:查询方法 * condition:where条件 如果没有传值 为 '' * paramconfig:是参数,不是用于where,而是用于mybatis 如果没有传值 为 '' */ function ajaxFindSingleInfoSql(condition,methodName,paramconfig,processResultMethod,asyncFlag){ if(!asyncFlag){ asyncFlag=false; } var resultdata=null; var data={}; data['condition']=JSON.stringify(condition); data['paramconfig']=JSON.stringify(paramconfig); data['methodName']=methodName; var dataUrl=basePath+'/share/findSingleInfoSql'; // 调用后台 $.ajax({ url :dataUrl,//后台处理程序 type:"post", //数据发送方式 async:asyncFlag, //同步为false,异步为true dataType:"text", //接受数据格式 data:data, success: function(result){//执行成功后 var da=eval('('+result+')'); resultdata=da; if(processResultMethod){ //调用方法,这样是为了异步处理数据设计的 eval(processResultMethod+'('+result+')'); } } }); return resultdata; } //获取表单数据 function getFormData(formid){ var data={}; var array =$('#'+formid).serializeArray(); array.forEach(function(sitem,index){ data[sitem.name]=sitem.value; }); return data; } /** * 显示详情页面 * @param formid:form 表单的id * @param resultData 填充的数据 */ function displayFormData(formid,data){ if(!isEmpty(data)){ $.each(Object.keys(data),function(index,key){ $('#'+formid).find('[name='+key+']').val(data[key]); }); } } //提交表单 function onsubmits(formid){ var bv=$('#'+formid).data('bootstrapValidator'); //bv.isValid() 为true的时候是通过,false的时候不通过 //手动验证,此验证之后,如果不通过界面会有红字出现 bv.validate(); if(!bv.isValid()){ //验证不通过 return true; }else{ return false; } } function validateForm(formid,tablelist){ if($('#'+formid).data('bootstrapValidator')!=undefined ){ $('#'+formid).data('bootstrapValidator',null); } //头部信息 var title=""+ " $('#"+formid+"').bootstrapValidator({ \n " + " message:'this value is not valid', \n "+ " feedbackIcons:{ \n "+ " valid:'glyphicon glyphicon-ok', \n "+ " invalid:'glyphicon glyphicon-remove', \n "+ " invalid:'glyphicon glyphicon-refresh' \n "+ " }, \n "+ " fields:{ \n "; //尾部信息 var end=" } \n"; end+="}).on('sucess.form.bv',function(e){e.preventDefault();});"; //中间信息,中间的是字段 var middle=''; $.each(tablelist,function(index,typename){ var gm=ajaxClomns(typename,formid); if(gm){ if(middle!=''){ middle+=","; } middle+= gm; } }); if($('#'+formid).data('bootstrapValidator')!=undefined ){ $('#'+formid).data('bootstrapValidator',null); } var allhtml=title+middle+end; eval(allhtml); return allhtml; } //获取 function ajaxClomns(typename,formid){ var colList=''; var data={}; data["typename"]=typename; //后台查询获取fields var dataUrl=basePath+'/share/findValidators'; // 调用后台 $.ajax({ url :dataUrl,//后台处理程序 type:"post", //数据发送方式 async:false, //同步为false,异步为true dataType:"text", //接受数据格式 data:data, success: function(da){//执行成功后 var result=eval('('+da+')'); if(result.code=='10001'){ var columns=result['result']; colList=getHtml(columns,formid); }else{ console.log("查询失败请联系管理员!"); } } }); return colList } //界面验证 function validateInfo(typename,formid){ if($('#'+formid).data('bootstrapValidator')!=undefined ){ //$('#mrqksb_add_formID').data('bootstrapValidator').destroy(); //$('#'+formid).data('bootstrapValidator').restForm(); $('#'+formid).data('bootstrapValidator',null); } /*$('#'+formid).bootstrapValidator().on('sucess.form.bv',function(e){ //阻止默认提交 e.preventDefault(); });*/ var html=""+ " $('#"+formid+"').bootstrapValidator({ \n " + " message:'this value is not valid', \n "+ " feedbackIcons:{ \n "+ " valid:'glyphicon glyphicon-ok', \n "+ " invalid:'glyphicon glyphicon-remove', \n "+ " invalid:'glyphicon glyphicon-refresh' \n "+ " }, \n "+ " fields:{ \n "; var data={}; data["typename"]=typename; //后台查询获取fields var dataUrl=basePath+'/share/findValidators'; // 调用后台 $.ajax({ url :dataUrl,//后台处理程序 type:"post", //数据发送方式 async:false, //同步为false,异步为true dataType:"text", //接受数据格式 data:data, success: function(da){//执行成功后 var result=eval('('+da+')'); if(result.code=='10001'){ var childhtml=''; var mrqk=result['result']; if(childhtml!=''){ childhtml+=","; } childhtml=getHtml(mrqk,formid,childhtml); html+=childhtml; }else{ console.log("查询失败请联系管理员!"); } } }); html+=" } \n"+ "});"; eval(html); return html; } //界面验证 function validateInfoAdd(typename,formid){ /*if($('#'+formid).data('bootstrapValidator')!=undefined ){ //$('#mrqksb_add_formID').data('bootstrapValidator').destroy(); $('#'+formid).data('bootstrapValidator',null); }*/ var data={}; data["typename"]=typename; //后台查询获取fields var dataUrl=basePath+'/share/findValidators'; // 调用后台 $.ajax({ url :dataUrl,//后台处理程序 type:"post", //数据发送方式 async:false, //同步为false,异步为true dataType:"text", //接受数据格式 data:data, success: function(da){//执行成功后 var result=eval('('+da+')'); if(result.code=='10001'){ var mrqk=result['result']; getHtmlAdd(mrqk,formid); }else{ console.log("查询失败请联系管理员!"); } } }); } //获取字段配置信息,根据配置信息增加校验 function getHtmlAdd(infos,formid){ var html=''; $.each(infos,function(index,item){ var validateStr=''; var valsHtml=''; //字段名称 var name=item['COLUMNENAME']; //dataType var dataType=item['DATATYPE']; ////枚举内容menuType var menuType=item['MENUTYPE']; //是否为空 var isNull=item['ISNULL']; //自定义匹配内容 正则表达式 var matchInfo=item['MATCHINFO']; //正则提示信息 var alertInfo=item['ALERTINFO']; //最大最小 var stringLength=item['STRINGLENGTH']; //首先判断字段是否存在文本框,如果存在才加校验 if($('#'+formid+' [name='+name+']').length>0 && $('#'+formid+' [name='+name+']').prop('type')!='hidden'){ //校验头部 validateStr+=" { \n "; validateStr+=" validators:{ \n "; //是否为空 if(isNull=='0'){ if(valsHtml!=''){ valsHtml+=", \n "; } valsHtml+=" notEmpty:{ \n"; valsHtml+=" message:'不能为空!' \n"; valsHtml+=" }"; } //最长最短 if(stringLength!='' && stringLength !=undefined && stringLength != 'undefined'){ var ss=stringLength.split(","); if(ss.length==2){ if(valsHtml!=''){ valsHtml+=", \n "; } valsHtml+=" stringLength:{ \n"; valsHtml+=" min: "+ss[0]+", \n"; valsHtml+=" max: "+ss[1]+", \n"; valsHtml+=" message:'长度在"+ss[0]+"到"+ss[1]+"位之间!' \n"; valsHtml+=" }"; } } //正则表达式 if(matchInfo!=null && alertInfo!=null && matchInfo!='' && alertInfo !=''){ if(valsHtml!=''){ valsHtml+=", \n "; } valsHtml+=" regexp:{ \n "; valsHtml+=" regexp:"+matchInfo+", \n "; valsHtml+=" message:'"+alertInfo+"' \n "; valsHtml+=" } "; }else { //其他数据类型 //增加对身份证的验证 if(dataType=="SF"){ if(valsHtml!=''){ valsHtml+=", \n "; } valsHtml+=" creditCard:{\n "; valsHtml+=" message:'身份证格式不正确!'\n "; valsHtml+=" } "; } else if((dataType=="L"||dataType=="I")){ if(valsHtml!=''){ valsHtml+=", \n "; } valsHtml+=" regexp:{ \n "; valsHtml+=" regexp:/^[0-9]\\d*$/,\n "; valsHtml+=" message:'必须是正整数' \n "; valsHtml+=" } "; }else if(dataType=="D"){ if(valsHtml!=''){ valsHtml+=", \n "; } valsHtml+=" numeric:{\n "; valsHtml+=" message:'请输入正确的数字'\n "; valsHtml+=" } "; }else if(dataType=="C"){ if(valsHtml!=''){ valsHtml+=", \n "; } valsHtml+=" regexp:{\n "; valsHtml+=" regexp:/^\\d+(\\.\\d+)?$/,\n "; valsHtml+=" message:'请输入正确的金额!'\n "; valsHtml+=" } "; }else if(dataType=="TD"){ if(valsHtml!=''){ valsHtml+=", \n "; } valsHtml+=" date:{\n "; valsHtml+=" format:'YYYY-MM-DD',\n "; valsHtml+=" message:'请输入正确的日期'\n "; valsHtml+=" } "; }else if(dataType=="T"){ if(valsHtml!=''){ valsHtml+=", \n "; } valsHtml+=" date:{\n "; valsHtml+=" format:'YYYY-MM-DD HH:mm:ss',\n "; valsHtml+=" message:'请输入正确的日期'\n "; valsHtml+=" }\n "; } } //中间加上内容 validateStr+=valsHtml; if(valsHtml!=''){ valsHtml+=" \n "; } //最后的数据 validateStr+=" }\n "; validateStr+=" }\n "; /*console.log(validateStr); console.log("----------------------");*/ var v=eval('('+validateStr+')'); //console.log(v); if(Object.keys(v).length>0){ $('#'+formid).bootstrapValidator('addField',name,v); } } }); return html; } //获取字段配置信息,根据配置信息增加校验 function getHtml(infos,formid,childhtml){ var html=''; $.each(infos,function(index,item){ var validateStr=''; var valsHtml=''; //字段名称 var name=item['COLUMNENAME']; //dataType var dataType=item['DATATYPE']; ////枚举内容menuType var menuType=item['MENUTYPE']; //是否为空 var isNull=item['ISNULL']; //自定义匹配内容 正则表达式 var matchInfo=item['MATCHINFO']; //正则提示信息 var alertInfo=item['ALERTINFO']; //最大最小 var stringLength=item['STRINGLENGTH']; //如果已经存在name,跳过去 if(childhtml&&childhtml.indexOf(" "+name+":{")>=0){ return false; } //首先判断字段是否存在文本框,如果存在才加校验 if($('#'+formid+' [name='+name+']').length>0 && $('#'+formid+' [name='+name+']').prop('type')!='hidden'){ //校验头部 validateStr+=" "+name+":{ \n "; validateStr+=" validators:{ \n "; //是否为空 if(isNull=='0'){ if(valsHtml!=''){ valsHtml+=", \n "; } valsHtml+=" notEmpty:{ \n"; valsHtml+=" message:'不能为空!' \n"; valsHtml+=" }"; } //最长最短 if(stringLength!='' && stringLength !=undefined && stringLength != 'undefined'){ var ss=stringLength.split(","); if(ss.length==2){ if(valsHtml!=''){ valsHtml+=", \n "; } valsHtml+=" stringLength:{ \n"; valsHtml+=" min: "+ss[0]+", \n"; valsHtml+=" max: "+ss[1]+", \n"; valsHtml+=" message:'长度在"+ss[0]+"到"+ss[1]+"位之间!' \n"; valsHtml+=" }"; } } //正则表达式 if(matchInfo!=null && alertInfo!=null && matchInfo!='' && alertInfo !=''){ if(valsHtml!=''){ valsHtml+=", \n "; } valsHtml+=" regexp:{ \n "; valsHtml+=" regexp:"+matchInfo+", \n "; valsHtml+=" message:'"+alertInfo+"' \n "; valsHtml+=" } "; }else { } //其他数据类型 //增加对身份证的验证 if(dataType=="SF"){ if(valsHtml!=''){ valsHtml+=", \n "; } valsHtml+=" creditCard:{\n "; valsHtml+=" message:'身份证格式不正确!'\n "; valsHtml+=" } "; } else if((dataType=="L"||dataType=="I")){ /*if(valsHtml!=''){ valsHtml+=", \n "; } valsHtml+=" regexp:{ \n "; valsHtml+=" regexp:/^[0-9]\\d*$/,\n "; valsHtml+=" message:'必须是整数' \n "; valsHtml+=" } ";*/ if(valsHtml!=''){ valsHtml+=", \n "; } valsHtml+="callback:{ \n "; valsHtml+=" message:'必须是正整数', \n "; valsHtml+=" callback:function(value,validator){ \n "; valsHtml+=" var regexp=/^[0-9]*[0-9]*$/;\n "; valsHtml+=" if(!value){return true;} \n "; valsHtml+=" return regexp.test(value);\n "; valsHtml+=" } "; valsHtml+=" } "; }else if(dataType=="D"){ if(valsHtml!=''){ valsHtml+=", \n "; } valsHtml+=" numeric:{\n "; valsHtml+=" message:'请输入正确的数字'\n "; valsHtml+=" } "; }else if(dataType=="C"){ if(valsHtml!=''){ valsHtml+=", \n "; } /*valsHtml+=" regexp:{\n "; valsHtml+=" regexp:/^\\d+(\\.\\d+)?$/,\n "; valsHtml+=" message:'请输入正确的金额!'\n "; valsHtml+=" } ";*/ valsHtml+="callback:{ \n "; valsHtml+=" message:'请输入正确的金额!', \n "; valsHtml+=" callback:function(value,validator){ \n "; valsHtml+=" var regexp=/^\\d+(\\.\\d+)?$/;\n "; valsHtml+=" if(!value){return true;} return regexp.test(value);\n "; valsHtml+=" } "; valsHtml+=" } "; }else if(dataType=="TD"){ if(valsHtml!=''){ valsHtml+=", \n "; } valsHtml+=" date:{\n "; valsHtml+=" format:'YYYY-MM-DD',\n "; valsHtml+=" message:'请输入正确的日期'\n "; valsHtml+=" } "; }else if(dataType=="T"){ if(valsHtml!=''){ valsHtml+=", \n "; } valsHtml+=" date:{\n "; valsHtml+=" format:'YYYY-MM-DD HH:mm:ss',\n "; valsHtml+=" message:'请输入正确的日期'\n "; valsHtml+=" }\n "; } /*if((dataType=="L"||dataType=="I")){ if(valsHtml!=''){ valsHtml+=", \n "; } valsHtml+="callback:{ \n "; valsHtml+=" message:'必须是整数', \n "; valsHtml+=" callback:function(value,validator){ \n "; valsHtml+=" var regexp=/^[0-9]\\d*$/;\n "; valsHtml+=" return regexp.test(value);\n "; valsHtml+=" } "; valsHtml+=" } "; }*/ //中间加上内容 validateStr+=valsHtml; if(valsHtml!=''){ valsHtml+=" \n "; } //最后的数据 validateStr+=" }\n "; validateStr+=" }\n "; if(html!=''){ html+=','+validateStr; }else{ html+=validateStr; } } }); return html; } //获取随机数,目前是最长获取30位 function getRandomChars(){ var radomChars=Math.random().toString(36).substr(2,10)+Math.random().toString(36).substr(2,10)+Math.random().toString(36).substr(2,10); return radomChars; } //获取当前时间 function getCurrentDate(){ var date=new Date(); var currentDate=date.getFullYear()+"-"+(date.getMonth()+1>=10?date.getMonth()+1:"0"+(date.getMonth()+1))+"-"+(date.getDate()>=10?date.getDate():"0"+date.getDate()); return currentDate; } function getCurrentTime(){ var date=new Date(); return format(date,'yyyy-MM-dd hh:mm:ss'); } /** * 时间格式装换 format 方法 * * @param date 时间 * @param dateformat 格式化(yyyy-MM-dd hh:mi:ss) * * @example 调用 new Date().format("yyyy-MM-dd hh:mi:ss") */ function format(date, dateformat) { //为空返回空串 if (isNaN(date)){ return ""; } var format = dateformat; var o = { "M+": date.getMonth() + 1, "d+": date.getDate(), "h+": date.getHours(), "m+": date.getMinutes(), "s+": date.getSeconds(), "q+": Math.floor((date.getMonth() + 3) / 3), "S": date.getMilliseconds() }; if (/(y+)/.test(format)) { format = format.replace(RegExp.$1, (date.getFullYear() + "") .substr(4 - RegExp.$1.length)); } for (var k in o) { if (new RegExp("(" + k + ")").test(format)) { format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)); } } return format; } //如果有了html,但是没有name和id,则在此处赋值 function setName(){ var data={}; data['ZAIWJGS']='在位军官'; data['ZAIWSGS']='在位士官'; data['ZAIWYWBS']='在位义务兵'; var keys=Object.keys(data); //console.log(keys); //var spans=$('#jbxx .form-group label span'); var spans=$('.base_info_zhjg .form-group>label>span'); $.each(spans,function(index,item){ var name=$(item).html().trim().substr(0,$(item).html().trim().indexOf(':')); $.each(keys,function(num,key){ //如果标签中含有状态 if(name==data[key]){ //查询标签中含有运行状态的字段 var select =$(item).parent().next().find('select,input,textarea'); $(select).attr('name',key); console.log($(select).prop('name')); } }); }); } //初始化form表单 //初始化信息parentElement 可能是form表单,也可能是其他元素 function updateChildFormInfo(parentElement,condition,typename){ //展示数据 var data=ajaxFindSingInfo(condition,typename); if(data.result!=undefined&&Object.keys(data.result).length>0){ $.each(Object.keys(data.result),function(index,item){ var value=data.result[item]; //设置不可少 $(parentElement).find('[name='+item+']').val(value); }); } return data; } //根据数据更新表单 function updateChildFormInfoByData(parentElement,data){ //展示数据 if(data!=undefined&&Object.keys(data).length>0){ $.each(Object.keys(data),function(index,item){ var value=data[item]; //设置不可少 $(parentElement).find('[name='+item+']').val(value); }); } return data; } //日期弹出框 function displayDateInfo(obj){ var times=$(obj).closest('.col-md-12').find('.inptime'); var time_copy = { elem:"#testid", format:'YYYY-MM-DD hh:mm:ss', //min:laydate.now(), //max:"2199-06-16 23:59:59", istime:true, istoday:true, choose:function(datas){ $("#mrqksb_add_formID .inptime").attr('id','') }, change:function(value,date,endDate){ $("#mrqksb_add_formID .inptime").attr('id','') } }; if(times.eq(0).attr('id')==$(obj).attr('id')&&times.eq(1).val()!=''){ time_copy['max']=times.eq(1).val(); } if(times.eq(1).attr('id')==$(obj).attr('id')&&times.eq(0).val()!=''){ time_copy['min']=times.eq(0).val(); } laydate(time_copy); } /** * 根据type获取时间或者日期,如果是time则返回待时分秒 * 否则就获取 * @param type */ function getDateOrTime(type){ var resultdata=null; var data={'type':type}; var dataUrl=basePath+'/share/getServerDateOrTime'; // 调用后台 $.ajax({ url :dataUrl,//后台处理程序 type:"post", //数据发送方式 async:false, //同步为false,异步为true dataType:"text", //接受数据格式 data:data, success: function(result){//执行成功后 var da=eval('('+result+')'); resultdata=da; } }); if(resultdata.result){ return resultdata.result; }else{ return null; } } /** * 判断对象是否为空 * @param obj * @returns {Boolean} */ function isEmpty(obj){ if(typeof obj == "undefined" || obj== null || obj=='' || obj == "undefined"){ return true; }else { return false; } } /****************************************************************升级start*/ function updateButton(){ //updateOldToNewConfig('101','060000011','综合计划席2'); updateOldToNewConfig('101','01050101','通信网络组'); return ; var dataresult=ajaxFindListSql('','updaeFindDwnmAndXwm',''); if(dataresult.code=='10001'&&dataresult.result.length>0){ //return ; var array=dataresult.result; $.each(array,function(i,item){ updateOldToNewConfig('101',item['DWNM'],item['XWM']); }); } } //升级系统,更新模板 function updateOldToNewConfig(mblx,dwnm,xwm){ //toConfigInfoUpdate(mblx); //先获取界面html var parentDom=$('#mrqkrb_config_form_add .modal-body'); //查询模板的配置信息,选择复选框 toConfigInfoUpdate(parentDom,mblx,dwnm,xwm); //processModalUpdate(parentDom,mblx,dwnm,xwm); $('#mrqkrb_config_form_add .modal-body').find('.child_con,.label_con,.row_con').css('background-color',''); look(); //直接升级 saveModalConfigUpdate(mblx,dwnm,xwm); //保存模板 进行测试 //保存的时候,先执行了预览,然后进行保存 //$('#modalTable_mrqkrb_config').modal('show'); /*$('#mrqkrb_config_btn').click(function(){ //对模板101进行一个单独的逻辑处理,信息管理情况中,军兵种信息管理情况和战区信息管理情况 只能存在一个,否则给出提示 look(); //移除背景色 $('#mrqkrb_config_form_add .modal-body').find('.child_con,.label_con,.row_con').css('background-color',''); saveModalConfigUpdate(mblx,dwnm,xwm); });*/ } //点击配置界面 function toConfigInfoUpdate(parentDom,mblx,dwnm,xwm){ $('#mrqkrb_config_form_add').html(''); $('#mrqkrb_config_form_add').html('<div class="modal-body" style="max-height:640px;overflow:auto"></div>'); $('#mrqkrb_config_form_add').bootstrapValidator('resetForm',true); $('#mrqkrb_config_form_add')[0].reset(); var parentDom=$('#mrqkrb_config_form_add .modal-body'); //加载内容 initMrqkConfig(false,parentDom,mblx); //复选框控制 checkbox_control(); //展开 zhankai(); //增加校验 //各种后续的处理1 收起,展开 //显示弹出框 var parentDom=$('#mrqkrb_config_form_add .modal-body'); processModalUpdate(parentDom,mblx,dwnm,xwm); } //根据配置信息设置显示的内容 function processModalUpdate(parentDom,mblx,dwnm,xwm){ //查询已有配置,如果存在数据则直接展示,否则展示全面的 var paramConfig={}; paramConfig['GNBS']=mblx;//功能标识GNBS paramConfig['DWNM']=dwnm;//单位内码DWNM paramConfig['XWM']=xwm;//席位名XWM var dataresult=ajaxFindListSql('','findConfigListInfo',paramConfig); if(dataresult.code=='10001'&&dataresult.result.length>0){ var html=''; $.each(dataresult.result,function(index,item){ html+=item.DISCONTENT; }); var rows=$(html); $.each(rows,function(num,row){ //找到右侧的信息,并找到右侧对应目前的row var name=$(row).find('.left_con [type=checkbox]').eq(0).prop('name'); var currRow=$(parentDom).find('.left_con [name='+name+']').closest('.row_con'); //设置右侧 var childCheckboxs=$(row).find('.right_con [type=checkbox]'); if(childCheckboxs.length>0){ $.each(childCheckboxs,function(index,item){ var cn=$(item).prop('name'); $(currRow).find('.right_con [name='+cn+']').prop('checked',true); }); //如果所有的子选项都被选中,则父选项也选中 if(childCheckboxs.length==$(currRow).find('.right_con [type=checkbox]').length){ $(currRow).find('.left_con [name='+name+']').prop('checked',true); } }else{ //如果没有子选项,直接选中 $(currRow).find('.left_con [name='+name+']').prop('checked',true); } }); } } //保存配置信息 function saveModalConfigUpdate(mblx,dwnm,xwm){ //获取所有的check信息he radio var content=$('#mrqkrb_config_form_add .modal-body').html(); var data={}; var paramConfig={}; paramConfig['GNBS']=mblx;//功能标识GNBS paramConfig['DWNM']=dwnm;//单位内码DWNM paramConfig['XWM']=xwm;//席位名XWM data['mainConfig']=JSON.stringify(paramConfig); data['checkbox']=content; data["URL"]="/supplement/zbjc/saveModalConfig"; var dataUrl='sys/supplement/tosupplement'; // 调用后台 $.ajax({ url :dataUrl,//后台处理程序 type:"post", //数据发送方式 async:false, //同步为false,异步为true dataType:"text", //接受数据格式 data:data, success: function(result){//执行成功后 var da=eval('('+result+')'); if(da.code=='10001'){ //layer.open({content:'保存成功!'}); //$('#modalTable_mrqkrb_config .CloseBtn').click(); console.log('设置成功,对应单位:【'+dwnm+'】'); }else{ console.log('设置失败,对应单位:【'+dwnm+'】'); //layer.open({content:'保存失败,请联系管理员!'}); } } }); } /****************************************************************升级end*/ /* 隐藏和显示 20180928 start */ /** * element是一个jquery对象 */ function noshow(element){ $(element).addClass('noshow'); $(element).removeClass('isshow'); } function isshow(element){ $(element).addClass('isshow'); $(element).removeClass('noshow'); } /* 隐藏和显示 20180928 end */ /** * 重置form表单 */ function resetFormAndValidate(formid,validatorFlag){ //初始化form $('#'+formid)[0].reset(); if($('#'+formid).data('bootstrapValidator')!=undefined ){ $('#'+formid).data('bootstrapValidator',null); //$('#'+formid).bootstrapValidator('resetForm',true); //$('#'+formid).find('small').css('display','none'); ///$('#'+formid).find('small').remove(); $('#'+formid).find('.has-success').removeClass('has-success'); $('#'+formid).find('.has-error').removeClass('has-error'); } if(validatorFlag){ var html= eval(formid+'ValidatorHTML'); if(!isEmpty(html)){ //约定好,用forid+ValidatorHTML 执行进行重新进行校验 eval(html); } } } /** * 获取序号 bootstrap table * @param value * @param row * @param index * @returns */ function getXhByRow(value, row, index){ return index+1; }
TypeScript
UTF-8
1,381
2.546875
3
[]
no_license
import { Socket } from 'net'; import GameServer from './gameserver'; import { createGameServer } from './matchmakingmanager'; let matchServerKey = 'secret'; export const setMatchServerKey = (key: string) => { matchServerKey = key; }; const onServerData = (server: GameServer, data: string) => { try { const d = JSON.parse(data); if (d.type && d.data) { const da = JSON.parse(d.data); if (d.type === 'connection') { if (da.key === matchServerKey) { server.authenticated = true; GameServer.gameServers.push(server); } } else { if (server.authenticated) { server.emit(d.type, da); } } } } catch (err) { console.error('An error occured while handling match server request !'); console.error(data); console.error(err); } }; const onServerEnd = (server: GameServer) => { console.log('Game server disconnection !'); const index = GameServer.gameServers.indexOf(server); GameServer.gameServers.splice(index, 1); server.emit('disconnection', {}); }; export const onServerConnect = (socket: Socket) => { const server: GameServer = createGameServer(socket); server.emit('connection', {}); socket.on('data', (data: string) => onServerData(server, data)); socket.on('end', () => onServerEnd(server)); socket.on('error', (err) => console.error(err)); };
Python
UTF-8
563
3.609375
4
[]
no_license
from math import factorial n = int(input()) k = 12 def binomialCoeff(n, k): C = [[0 for i in range(k + 1)] for i in range(n + 1)] # Calculate value of Binomial Coefficient in bottom up manner for i in range(0, n + 1, 1): for j in range(0, min(i, k) + 1, 1): # Base Cases if (j == 0 or j == i): C[i][j] = 1 # Calculate value using previously stored values else: C[i][j] = C[i - 1][j - 1] + C[i - 1][j] return C[n][k] print(binomialCoeff(n - 1, k - 1))
Shell
UTF-8
89
2.59375
3
[]
no_license
#!/bin/bash set -Eeuo pipefail setup_vars() { } main() { setup_vars } main "$@"
C#
UTF-8
1,342
2.734375
3
[]
no_license
using RestSharp; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RestTestsLibrary.Base { public class RestTestBase { public static RestClient restClient; public static RestRequest request; public static IRestResponse response; /// <summary> /// Does a Register request /// </summary> /// <param name="a"></param> /// <returns></returns> public static IRestResponse SendRegisterRequest(Dictionary<string, string> a) { restClient = new RestClient("https://reqres.in/api/register"); request = new RestRequest(Method.POST); foreach (KeyValuePair<string, string> entry in a) { request.AddParameter(entry.Key, entry.Value); } return restClient.Execute(request); } /// <summary> /// Requests a list of users /// </summary> /// <param name="a"></param> /// <returns></returns> public static IRestResponse SendGetUserListRequest() { restClient = new RestClient("https://reqres.in/api/users"); request = new RestRequest(Method.GET); return restClient.Execute(request); } } }
Java
UTF-8
2,394
2.703125
3
[]
no_license
package org; import java.awt.Button; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; public class ClientHandler implements ActionListener { Socket client=null; InputStream is=null; DataInputStream dis=null; DataOutputStream dos=null; OutputStream os=null; @Override public void actionPerformed(ActionEvent e) { ClientFrame frm=(ClientFrame)((Button)e.getSource()).getParent(); String actionCommand=e.getActionCommand(); if(actionCommand.equals("Connect")) { try { System.out.println("client connecting.."); client=new Socket(frm.txtFields[0].getText(),Integer.parseInt(frm.txtFields[1].getText())); System.out.println("connected..."); is=client.getInputStream(); dis=new DataInputStream(is); int limit=dis.readInt(); for(int index=0;index<limit;index++) { frm.lstFiles.add(dis.readUTF()); } } catch (UnknownHostException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else if(actionCommand.equals("Disconnect")) { try { if(dis!=null) dis.close(); if(is!=null) is.close(); if(client!=null) client.close(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else { try { os=client.getOutputStream(); dos=new DataOutputStream(os); String downloadFile=frm.lstFiles.getSelectedItem(); dos.writeUTF(downloadFile); int limit=dis.readInt(); byte []data=new byte[limit]; dis.read(data); File download=new File("D:\\"+frm.lstFiles.getSelectedItem()); if(!download.exists()) download.createNewFile(); FileOutputStream fos=new FileOutputStream(download); fos.write(data); Thread.sleep(100); System.out.println("Downloaded on client"); } catch (IOException | InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } }
Python
UTF-8
408
3.265625
3
[]
no_license
def unique_chars_str(string): unique = list(set(list(string))) all_chars = list(string) if len(unique) == len(all_chars): print "OK: '{}' has all unique characters.".format(string) else: print "NO: {} does not have all unique characters.".format(string) unique_chars_str("Pooja") unique_chars_str("abcd") unique_chars_str("qwertyu") unique_chars_str("formation data systems")
Java
UTF-8
254
1.945313
2
[]
no_license
package jo.secondstep.solid.dependencyinversion.correct; import java.util.HashMap; public class sheinShopping implements ShoppingProvider { @Override public shopping provideClothes(HashMap clothesOrder) { return new shine(clothesOrder); } }
Java
UTF-8
1,578
2.28125
2
[]
no_license
package com.spring.starter.model; import com.fasterxml.jackson.annotation.JsonIgnore; import javax.persistence.*; @Entity @Table(name = "fund_transfer_SLIPS_files") public class FundTransferSLIPSFiles { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int fundTransferSLIPSFilesId; private String fileType; private String fileUrl; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "fundTransferSLIPSId") @JsonIgnore private FundTransferSLIPS fundTransferSLIPS; public FundTransferSLIPSFiles() { } public FundTransferSLIPSFiles(String fileType, String fileUrl, FundTransferSLIPS fundTransferSLIPS) { this.fileType = fileType; this.fileUrl = fileUrl; this.fundTransferSLIPS = fundTransferSLIPS; } public int getFundTransferSLIPSFilesId() { return fundTransferSLIPSFilesId; } public void setFundTransferSLIPSFilesId(int fundTransferSLIPSFilesId) { this.fundTransferSLIPSFilesId = fundTransferSLIPSFilesId; } public String getFileType() { return fileType; } public void setFileType(String fileType) { this.fileType = fileType; } public String getFileUrl() { return fileUrl; } public void setFileUrl(String fileUrl) { this.fileUrl = fileUrl; } public FundTransferSLIPS getFundTransferSLIPS() { return fundTransferSLIPS; } public void setFundTransferSLIPS(FundTransferSLIPS fundTransferSLIPS) { this.fundTransferSLIPS = fundTransferSLIPS; } }
Java
UTF-8
15,133
1.515625
2
[ "Apache-2.0" ]
permissive
/* * © Copyright 2016-2023 Micro Focus or one of its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hpe.adm.nga.sdk.network.google; import com.google.api.client.http.HttpRequest; import com.hpe.adm.nga.sdk.Octane; import com.hpe.adm.nga.sdk.authentication.Authentication; import com.hpe.adm.nga.sdk.authentication.SimpleUserAuthentication; import com.hpe.adm.nga.sdk.exception.OctaneException; import com.hpe.adm.nga.sdk.model.ErrorModel; import com.hpe.adm.nga.sdk.model.LongFieldModel; import com.hpe.adm.nga.sdk.model.StringFieldModel; import com.hpe.adm.nga.sdk.network.OctaneHttpRequest; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Matchers; import org.mockito.Mockito; import org.mockserver.integration.ClientAndServer; import org.mockserver.matchers.TimeToLive; import org.mockserver.matchers.Times; import org.mockserver.mock.action.ExpectationResponseCallback; import org.mockserver.model.Cookie; import org.mockserver.model.Delay; import org.mockserver.model.HttpResponse; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.SocketTimeoutException; import java.time.Duration; import java.time.LocalDateTime; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.concurrent.TimeUnit; import java.util.stream.IntStream; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.times; import static org.mockserver.integration.ClientAndServer.startClientAndServer; import static org.mockserver.model.HttpClassCallback.callback; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.response; import static org.powermock.api.mockito.PowerMockito.doReturn; import static org.powermock.api.mockito.PowerMockito.doThrow; import static org.powermock.api.mockito.PowerMockito.spy; import static org.powermock.api.mockito.PowerMockito.verifyPrivate; @PowerMockIgnore("javax.management.*") @RunWith(PowerMockRunner.class) @PrepareForTest(GoogleHttpClient.class) public class TestGoogleHttpClient { public static final String OAUTH_AUTH_URL = "/authentication/sign_in"; public static final String LWSSO_COOKIE_KEY = "LWSSO_COOKIE_KEY"; private static final Logger logger = LoggerFactory.getLogger(TestGoogleHttpClient.class); @Test public void testRequestRetry() throws Exception { Authentication authentication = new SimpleUserAuthentication("", ""); GoogleHttpClient googleHttpClientSpy = spy(new GoogleHttpClient("http://url.com", authentication)); doReturn(null).when(googleHttpClientSpy, "convertOctaneRequestToGoogleHttpRequest", any(OctaneHttpRequest.class)); doReturn(true).when(googleHttpClientSpy, "authenticate"); Whitebox.setInternalState(googleHttpClientSpy, "lastUsedAuthentication", PowerMockito.mock(Authentication.class)); long currentTimeMs = System.currentTimeMillis(); Whitebox.setInternalState(googleHttpClientSpy, "lastSuccessfulAuthTimestamp", currentTimeMs); Whitebox.setInternalState(googleHttpClientSpy, "requestStartTime", ThreadLocal.withInitial(() -> currentTimeMs + 1)); //Create timeout exception, the same way octane does ErrorModel errorModel = new ErrorModel(new HashSet<>()); errorModel.setValue(new StringFieldModel("errorCode", "VALIDATION_TOKEN_EXPIRED_IDLE_TIME_OUT")); errorModel.setValue(new LongFieldModel(ErrorModel.HTTP_STATUS_CODE_PROPERTY_NAME, 401L)); OctaneException octaneException = new OctaneException(errorModel); doThrow(octaneException) .when(googleHttpClientSpy, "executeRequest", Matchers.any(HttpRequest.class)); OctaneHttpRequest request = new OctaneHttpRequest.GetOctaneHttpRequest("http://url.com"); try { googleHttpClientSpy.execute(request); } catch (Exception ex) { //this is supposed to fail, eventually } /* Check if the method retried the right amount of times */ verifyPrivate( googleHttpClientSpy, times(GoogleHttpClient.getHttpRequestRetryCount() + 1)) .invoke("execute", any(), anyInt()); } @Test public void testCustomSettings() { int connTimeout = 2345; Octane.OctaneCustomSettings settings = new Octane.OctaneCustomSettings() {{ set(Setting.READ_TIMEOUT, 55000); set(Setting.CONNECTION_TIMEOUT, 2345); }}; GoogleHttpClient client = new GoogleHttpClient("http://google.com:8090", null, settings); OctaneHttpRequest request = new OctaneHttpRequest.GetOctaneHttpRequest("http://google.com:9090"); long start = System.currentTimeMillis(); try { client.execute(request); } catch (Exception e) { long end = System.currentTimeMillis(); Assert.assertTrue(e.getCause() instanceof SocketTimeoutException); long duration = end - start; Assert.assertTrue(duration < 3000 && duration > 2000); } } @Test @Ignore public void testParallelRequestRetry() { ClientAndServer clientAndServer = startClientAndServer(); Octane octane; long totalExecutionTime = 500; long cookieExpirationTime = 250; initServerResponse(clientAndServer, cookieExpirationTime); Authentication authentication = new SimpleUserAuthentication("", ""); String url = "http://localhost:" + clientAndServer.getLocalPort(); GoogleHttpClient spyGoogleHttpClient = spy(new GoogleHttpClient(url, authentication)); octane = new Octane.Builder(authentication, spyGoogleHttpClient).Server(url).workSpace(1002).sharedSpace(1001).build(); int nrCores = Math.max(Runtime.getRuntime().availableProcessors(),2); IntStream.rangeClosed(1, nrCores).parallel().forEach((nr) -> runGetRequests(octane, totalExecutionTime)); clientAndServer.stop(); //Exactly 2 authentications are done: one for 1st log in and 2nd for cookie refresh Mockito.verify(spyGoogleHttpClient, times(2)).authenticate(); //There are more execution invocations than there are threads Mockito.verify(spyGoogleHttpClient, atLeast(nrCores + 1)).execute(any()); } public void runGetRequests(Octane octane, long totalExecutionTime) { LocalDateTime pastTime = LocalDateTime.now(); LocalDateTime currentTime = LocalDateTime.now(); while (Duration.between(pastTime, currentTime).toMillis() < totalExecutionTime) { octane.entityList("").get().execute(); currentTime = LocalDateTime.now(); } } public void initServerResponse(ClientAndServer clientAndServer, long cookieExpirationTime) { Cookie firstCookie = new Cookie("LWSSO_COOKIE_KEY", "one"); Cookie secondCookie = new Cookie("LWSSO_COOKIE_KEY", "two"); Delay serverDelay = Delay.milliseconds(10); //First cookie given only once to the main octane object clientAndServer .when( request().withPath("/authentication/sign_in"), Times.once()) .respond( response().withStatusCode(200).withCookie(firstCookie).withDelay(serverDelay)); //Second cookie given every time a new authentication request is made clientAndServer .when( request().withPath("/authentication/sign_in")) .respond( response().withStatusCode(200).withCookie(secondCookie).withDelay(serverDelay)); //Accept request with second cookie clientAndServer .when( request().withCookie(secondCookie)) .respond( response().withStatusCode(200).withDelay(serverDelay)); //Requests with the first cookie are accepted cookieExpirationTime milliseconds clientAndServer .when( request().withMethod("GET").withCookie(firstCookie), Times.unlimited(), TimeToLive.exactly(TimeUnit.MILLISECONDS, cookieExpirationTime)) .respond( response().withStatusCode(200).withDelay(serverDelay)); //Requests with first cookies (after cookieExpirationTime milliseconds) get IDLE TIME OUT clientAndServer .when( request().withMethod("GET").withCookie(firstCookie), Times.unlimited()) .respond( response().withStatusCode(401).withDelay(serverDelay) .withBody("{\"errorCode\":\"VALIDATION_TOKEN_EXPIRED_IDLE_TIME_OUT\"," + "\"accumulatedMessage\":\"Previous validation errors " + "(non mandatory validators): \"}")); } @Test public void testCookieCollision() { try (ClientAndServer clientAndServer = startClientAndServer()) { int nrCores = Math.max(Runtime.getRuntime().availableProcessors(), 4); TestOctaneResponseCallback.cores = nrCores; clientAndServer .when(request()) .respond( callback().withCallbackClass( TestOctaneResponseCallback.class ) ); Authentication authentication = new SimpleUserAuthentication("", ""); String url = "http://localhost:" + clientAndServer.getLocalPort(); GoogleHttpClient googleHttpClient = new GoogleHttpClient(url, authentication); googleHttpClient.authenticate(); Octane octane = new Octane.Builder(authentication, googleHttpClient) .Server(url).workSpace(1002).sharedSpace(1001).build(); IntStream.rangeClosed(1, nrCores).parallel().forEach((nr) -> runGetRequests(octane, 5000)); } catch (Exception e) { fail("Error: " + e.getMessage()); } } public static class TestOctaneResponseCallback implements ExpectationResponseCallback { public static int cores = 4; private static int regularRequestsCount = 0; private static int authRequestsCount = 0; private static Cookie usingCookie = null; private static Long cookieExpiredAt = null; private static Long cookieShouldBeUpdatedAt = null; private final static Random random = new Random(); public synchronized void setNewUsingCookie(String name) { usingCookie = new Cookie(LWSSO_COOKIE_KEY, name); cookieExpiredAt = System.currentTimeMillis() + 1000; cookieShouldBeUpdatedAt = System.currentTimeMillis() + 500; logger.debug("Using new cookie: {}={}", usingCookie.getName(), usingCookie.getValue()); } public boolean isCookieShouldBeUpdated() { return cookieShouldBeUpdatedAt != null && cookieShouldBeUpdatedAt <= System.currentTimeMillis(); } public static Delay getServerDelay() { int max = 50; int min = 10; return Delay.milliseconds(random.nextInt(max - min + 1) + min); } @Override public HttpResponse handle(org.mockserver.model.HttpRequest httpRequest) throws Exception { String howToHandle = "empty"; boolean isAuthRequest = httpRequest.getPath().getValue().endsWith(OAUTH_AUTH_URL); synchronized (TestOctaneResponseCallback.class) { if (isAuthRequest) { howToHandle = "auth"; authRequestsCount++; } else { if (cookieExpiredAt != null) { Long currentTime = System.currentTimeMillis(); if (cookieExpiredAt <= currentTime) { logger.debug("NULL the cookie"); usingCookie = null; } } if (usingCookie != null && httpRequest.getCookies() != null) { List<Cookie> cookies = httpRequest.getCookies().getEntries(); for (Cookie cookie : cookies) { if (cookie.equals(usingCookie)) { howToHandle = "regular"; break; } } } regularRequestsCount++; } } switch (howToHandle) { case "auth": synchronized (TestOctaneResponseCallback.class) { setNewUsingCookie("auth-lwsso-" + authRequestsCount); return response() .withStatusCode(200) .withCookie(usingCookie.getName(), usingCookie.getValue()); } case "regular": synchronized (TestOctaneResponseCallback.class) { if (isCookieShouldBeUpdated()) { setNewUsingCookie("regular-lwsso-" + regularRequestsCount); return response().withStatusCode(200) .withCookie(usingCookie.getName(), usingCookie.getValue()); } } return response().withStatusCode(200).withDelay(getServerDelay()); default: return response().withStatusCode(401).withDelay(getServerDelay()) .withBody("{\"errorCode\":\"VALIDATION_TOKEN_EXPIRED_IDLE_TIME_OUT\"," + "\"accumulatedMessage\":\"Previous validation errors " + "(non mandatory validators): \"}"); } } } }
C++
UTF-8
1,472
2.78125
3
[]
no_license
#include <iostream> #include <string> using namespace std; int n, d, l, r; string s, ss; string Izvajdane (string s1, string s2) { int d1=0, d2, i, p=0, q=0, vz=0, r=0; string otg = ""; bool fl=false; d1 = s1.size(); d2 = s2.size(); if (d2 < d1) { while (d2 < d1) { s2 = "0" + s2; d2 ++; } } for (i = d1-1; i >= 0; i --) { p = s1[i] - '0'; q = s2[i] - '0'; if (p < q || (p == q && vz == 1)) { p += 10; fl = true; } r = p-q-vz; if (fl) { vz = 1; fl = false; } else vz = 0; otg = char(r+'0') + otg; } while (otg[0] == '0' && otg.size() > 1) otg.erase(0,1); return otg; } string Sabirane (string s1, string s2) { int d1, d2, i, p, q, naum=0, sb; string otg; d1 = s1.size(); d2 = s2.size(); while (d1 < d2) { s1 = "0" + s1; d1 ++; } while (d2 < d1) { s2 = "0" + s2; d2 ++; } for (i = d1-1; i >= 0; i --) { p = s1[i] - '0'; q = s2[i] - '0'; sb = (p+q+naum)%10; if ((p+q+naum) >= 10) { naum = 1; } else naum = 0; otg = char (sb+'0') + otg; } if (naum == 1) otg = "1" + otg; return otg; } int main () { int i=1, d; cin >> n >> s; ss = s; d = s.size(); while (d < n) { s = s + "0"; d ++; } while (d == n) { s = Izvajdane (s,ss); d = s.size(); } cout << Sabirane(s,ss) << endl; return 0; } /* 12345670000000 1234567 2 3 - 12 4 10 - 1000 5 120 - 10080 15 1234567 - 100000001074020 */
Markdown
UTF-8
807
2.796875
3
[]
no_license
--- layout: home title: NHumphrey.com --- NHumphrey.com ============= To make this site I'm using: - [Jekyll](https://jekyllrb.com/), a simple static website generator that lets you use templates and write content in Markdown without having to spin up a server to host your content management system. Github Pages rebuilds the site on a commit to the master branch. - [Bootstrap](http://getbootstrap.com/), making the site mobile friendly and responsive, but with a few custom tweaks so that it's styled a bit more to my liking. - Thanks to Start Bootstrap for their [Simple Sidebar](http://startbootstrap.com/template-overviews/simple-sidebar/) template, also customized. - Plain ol' HTML and CSS. Check it out [on Github](https://github.com/NealHumphrey/NealHumphrey.github.io) if you're curious.
Java
UTF-8
5,098
2.296875
2
[ "Apache-2.0" ]
permissive
package org.aieonf.template.controller; import java.util.ArrayList; import java.util.Collection; import org.aieonf.concept.IDescribable; import org.aieonf.concept.IDescriptor; import org.aieonf.concept.context.IContextAieon; import org.aieonf.model.builder.IModelBuilderListener; import org.aieonf.model.builder.ModelBuilderEvent; import org.aieonf.model.core.IModelLeaf; import org.aieonf.model.core.IModelNode; import org.aieonf.template.builder.ITemplateBuilder; import org.aieonf.template.context.ITemplateContextFactory; import org.aieonf.template.def.ITemplateLeaf; public abstract class AbstractModelController<D extends IDescriptor, M extends IDescribable> implements IModelController<M> { private boolean initialised; private M model; private ITemplateLeaf<IContextAieon> template; private boolean open; private ITemplateContextFactory<M> factory; private Collection<IModelBuilderListener<M>> listeners; protected AbstractModelController( ITemplateContextFactory<M> factory ) { super(); this.open = false; this.factory = factory; this.initialised = false; listeners = new ArrayList<IModelBuilderListener<M>>(); } @Override public void open(){ this.open = (this.factory != null ); } @Override public boolean isOpen() { return open; } @Override public void addBuilderListener( IModelBuilderListener<M> listener ){ this.listeners.add( listener ); } @Override public void removeBuilderListener( IModelBuilderListener<M> listener ){ this.listeners.remove( listener ); } /** * Notfiy the listeners of changes * @param event */ protected void notifyModelChanged(ModelBuilderEvent<M> event) { for( IModelBuilderListener<M> listener: getListeners() ) listener.notifyChange(event); } protected Collection<IModelBuilderListener<M>> getListeners() { return listeners; } protected ITemplateContextFactory<M> getFactory() { return factory; } public ITemplateLeaf<IContextAieon> getTemplate() { return factory.getTemplate(); } @Override public void initialise() { this.initialised = ( this.factory != null ); template = factory.createTemplate(); this.initialised = ( template != null ); } @Override public void close() { this.model = null; this.template = null; this.initialised = false; } @Override public boolean isInitialised() { return initialised; } /** * add the required model builder to build the model * @return */ protected abstract ITemplateBuilder<M> getModelBuilder(); /** * Verify the model with the given string for categories * @param categories * @return */ public abstract boolean verifyModel(); @Override public M createModel(){ ITemplateBuilder<M> builder = this.getModelBuilder(); IModelBuilderListener<M> listener = new IModelBuilderListener<M>(){ @Override public void notifyChange(ModelBuilderEvent<M> event) { for( IModelBuilderListener<M> listener: listeners) listener.notifyChange(event); } }; builder.addListener(listener); model = builder.createModel(template); builder.removeListener(listener); return null; } @Override public M getModel() { return model; } /** * It is possible that a certain model is created externally. In that case it can be included here * @param factory * @param root */ @Override public void setModel( M root ) { this.model = root; } @SuppressWarnings("unchecked") @Override public IModelLeaf<IDescriptor> getSubModel(IDescriptor descriptor) { return this.getSubModel( (IModelLeaf<? extends IDescriptor>) model, descriptor); } @SuppressWarnings("unchecked") protected final IModelLeaf<IDescriptor> getSubModel( IModelLeaf<? extends IDescriptor> model, IDescriptor descriptor ){ if( model.getDescriptor().equals( descriptor )) return (IModelLeaf<IDescriptor>) model; if( model.isLeaf() ) return null; IModelNode<IDescriptor> node = (IModelNode<IDescriptor>) model; for( IModelLeaf<? extends IDescriptor>child: node.getChildren().keySet() ){ IModelLeaf<IDescriptor>result = this.getSubModel(child, descriptor ); if( result != null ) return result; } return null; } /** * Get the concept * @param concept * @return */ public ITemplateLeaf<IDescriptor> getTemplate( String identifier ){ return (ITemplateLeaf<IDescriptor>) getModel( this.template, identifier ); } @SuppressWarnings("unchecked") public static IModelLeaf<IDescriptor> getModel( IModelLeaf<? extends IDescriptor> leaf, String identifier ){ if( identifier.equals( leaf.getIdentifier() )) return (IModelLeaf<IDescriptor>) leaf; if( leaf.isLeaf()) return null; IModelNode<IDescriptor> node = (IModelNode<IDescriptor>) leaf; for( IModelLeaf<? extends IDescriptor> child: node.getChildren().keySet()){ IModelLeaf<IDescriptor> result = getModel( child, identifier ); if( result != null ) return result; } return null; } }
Java
UTF-8
180
2.734375
3
[]
no_license
package com.module1coma1.people; public class Male extends Person { public Male(String name) { super(name); } public void voice(){ System.out.println("Hey there! "); } }
Python
UTF-8
1,341
3.453125
3
[]
no_license
""" Get请求:Get请求会通过URL网址传递消息,可以直接在URL中写上要传递的信息, 也可以由表单进行传递。如果使用表单进行传递,这表单中的信息会自动转为URL 地址中的数据,通过URL地址传递 """ import urllib.request def search_without_chinese(): # 构建对应的URL地址,该URL地址包含GET请求的字段名和字段内容等信息,并且 # URL地址满足GET请求的格式,即“http://网址?字段名1=字段内容1&字段名2=字段内容2” keywd = "hello" url = "http://www.baidu.com/s?wd=" + keywd # 以对应的URL为参数,构建Request对象 req = urllib.request.Request(url) # 通过urlopen()打开构建的Request对象 data = urllib.request.urlopen(req).read() fhandle = open("./doc/4.html", "wb") fhandle.write(data) fhandle.close() def search_with_chinese(): url = "http://www.baidu.com/s?wd=" # 中文 keywd = "你好" # 对中文进行编码 key_code = urllib.request.quote(keywd) url_all = url + key_code req = urllib.request.Request(url_all) data = urllib.request.urlopen(req).read() fh = open("./doc/5.html", "wb") fh.write(data) fh.close() pass if __name__ == '__main__': # search_without_chinese() search_with_chinese() pass