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
C#
UTF-8
632
3.953125
4
[]
no_license
using System; namespace MathLibrary { public class Circle { public static void Main(string[] args) { Console.Write("Please enter the radius of the circle: "); String input = Console.ReadLine(); double radius = double.Parse(input); double area_Circle = Math.PI * Math.Pow(radius, radius); double perimeter_Circle = 2 * (Math.PI) * radius; Console.WriteLine("A circle radius {0:F2} has area {1:F2} and a Permimeter of {2:F2}" , radius, area_Circle, perimeter_Circle); Console.ReadLine(); } } }
JavaScript
UTF-8
808
2.953125
3
[]
no_license
const numberReg =/(^-?\\d+$)|(^(-?\\d+)(\\.\\d+)?$)|(^[01]+$)|(^[0-7]+$)|((^0x[a-f0-9]{1,2}$)|(^0X[A-F0-9]{1,2}$)|(^[A-F0-9]{1,2}$)|(^[a-f0-9]{1,2}$))/; const strReg = /(^(?=.*[a-zA-Z])(?=.*\d)(?=.*[\u0021-\u002F\u003A-\u0040\u005B-\u0060\u007B-\u007E])[\u0021-\u007E]{6,16}$)|(^(?=.*[a-zA-Z])(?=.*\d)(?=.*[\x21-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E])[\x21-\x7E]{6,16}$)|((?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*)/; function encodeUTF(text) { const code = encodeURIComponent(text); const bytes = []; for (let i = 0; i < code.length; i++) { const c = code.charAt(i); if (c === '%') { const hex = code.charAt(i + 1) + code.charAt(i + 2); const hexVal = parseInt(hex, 16); bytes.push(hexVal); i += 2; } else bytes.push(c.charCodeAt(0)); } return bytes; }
Python
UTF-8
2,529
4.21875
4
[ "MIT" ]
permissive
def isPalindromePermutation(string=''): ''' Solution 1 - Hash table Complexity Analysis O(n) time | O(n) space Check if it is a permutation of a palindrome string: string - ASCII (128 characters) return: boolean ''' # Gracefully handle type and Falsy values if (not isinstance(string, str) or string == ''): print('Argument should be a valid non-empty string') return string charsMap = dict() for char in string.lower(): if (char == ' '): continue if (char in charsMap): charsMap[char] += 1 else: charsMap[char] = 1 oddCount = 0 for char in charsMap: if (charsMap[char] % 2 == 1): oddCount += 1 return oddCount <= 1 # Test cases (black box - unit testing) testCases = [ { 'assert': isPalindromePermutation('Wow'), 'expected': True }, { 'assert': isPalindromePermutation('Anna'), 'expected': True }, { 'assert': isPalindromePermutation('Kayak'), 'expected': True }, { 'assert': isPalindromePermutation('1abcba1'), 'expected': True }, { 'assert': isPalindromePermutation('AbCdcBa'), 'expected': True }, { 'assert': isPalindromePermutation('Repaper'), 'expected': True }, { 'assert': isPalindromePermutation('abcdefg'), 'expected': False }, { 'assert': isPalindromePermutation('Tact Coa'), 'expected': True }, { 'assert': isPalindromePermutation('Ab Cd cBa'), 'expected': True }, { 'assert': isPalindromePermutation('ab c d efg'), 'expected': False }, { 'assert': isPalindromePermutation('Hello World'), 'expected': False }, # Boundary conditions (empty lists, singleton list, large numbers, small numbers) { 'assert': isPalindromePermutation(), 'expected': '' }, { 'assert': isPalindromePermutation(0), 'expected': 0 }, { 'assert': isPalindromePermutation(''), 'expected': '' }, { 'assert': isPalindromePermutation([]), 'expected': [] }, { 'assert': isPalindromePermutation(()), 'expected': () }, { 'assert': isPalindromePermutation({}), 'expected': {} }, { 'assert': isPalindromePermutation(None), 'expected': None }, { 'assert': isPalindromePermutation(False), 'expected': False }, # Extremes ] # Run tests for (index, test) in enumerate(testCases): print(f'# Test {index + 1}') print(f'Actual: {test["assert"]}') print(f'Expected: {test["expected"]}') print('🤘 Test PASSED 🤘' if test["assert"] == test["expected"] else '👎 Test FAILED 👎', '\n')
Java
UTF-8
1,573
3.6875
4
[]
no_license
package SumOfCoins; import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String[] elements = in.nextLine().substring(7).split(", "); int[] coins = new int[elements.length]; for (int i = 0; i < coins.length; i++) { coins[i] = Integer.parseInt(elements[i]); } int targetSum = Integer.parseInt(in.nextLine().substring(5)); int[] ints = Arrays.stream(coins).sorted().toArray(); Map<Integer, Integer> usedCoins = chooseCoins(ints, targetSum); for (Map.Entry<Integer, Integer> usedCoin : usedCoins.entrySet()) { System.out.println(usedCoin.getKey() + " -> " + usedCoin.getValue()); } } private static Map<Integer, Integer> chooseCoins(int[] coins, int targetSum) { Map<Integer, Integer> map = new LinkedHashMap<>(); int index = coins.length - 1; int result; int currentSum = targetSum; int count=0; while (index >= 0) { result = currentSum / coins[index]; if (result != 0) { map.put(coins[index], result); count+=result; currentSum -= (coins[index] * result); } index--; } if (currentSum > 0){ System.out.println("Error"); return new HashMap<>(); } System.out.println("Number of coins to take: "+count); return map; } }
Markdown
UTF-8
6,843
3.34375
3
[]
no_license
# Base 1. `equals` 和 `==` 1. `==`是一个比较运算符,基本数据类d型比较的是值,引用数据类型比较的是地址值。 2. `equals()` 是一个方法,只能比较引用数据类型。重写前比较的是地址值,重写后比一般是比较对象的属性。 1. 自反性:对于任何非空引用x,x.equals(x)应该返回true。 2. 对称性:对于任何引用x和y,如果x.equals(y)返回true,那么y.equals(x)也应该返回true。 3. 传递性:对于任何引用x、y和z,如果x.equals(y)返回true,y.equals(z)返回true,那么x.equals(z)也应该返回true。 4. 一致性:如果x和y引用的对象没有发生变化,那么反复调用x.equals(y)应该返回同样的结果。 5. 非空性:对于任意非空引用x,x.equals(null)应该返回false。 2. Java 中的引用 1. 强引用是使用最普遍的引用。如果一个对象具有强引用,那么垃圾回收器绝不会回收它。 1. JVM即使抛出OOM异常,也不会回收强引用所指向的对象。 2. 软引用是除了强引用外,最强的引用类型。可以通过 `java.lang.ref.SoftReference` 使用软引用。 一个持有软引用的对象,不会被JVM很快回收,JVM会根据当前堆的使用情况来判断何时回收。当堆使用率临近阈值时,才会去回收软引用的对象。 软引用可以用于实现对内存敏感的高速缓存。 3. 弱引用是一种比软引用较弱的引用类型。在系统GC时,只要发现弱引用,不管系统堆空间是否足够,都会将对象进行回收。 由于垃圾回收器是一个优先级很低的线程,因此不一定会很快发现那些只具有弱引用的对象。 弱引用主要用于监控对象是否已经被垃圾回收器标记为即将回收的垃圾,可以通过弱引用的isEnQueued方法返回对象是否被垃圾回收器标记。 4. 虚引用是所有类型中最弱的一个。一个持有虚引用的对象和没有引用几乎是一样的,随时可能被垃圾回收器回收。 当试图通过虚引用的get()方法取得强引用时,总是会失败。 虚引用必须和引用队列一起使用,它的作用在于检测对象是否已经从内存中删除,跟踪垃圾回收过程。 3. `Comparable` 是内部比较器,而 `Comparator` 是外部比较器。 1. 一个类本身实现了 `Comparable` 比较器,就意味着它本身支持排序; 2. 若它本身没实现 `Comparable`,也可以通过外部比较器 `Comparator` 进行排序。 4. 异常: 1. 关键字: * `try` -- 用于监听。将要被监听的代码(可能抛出异常的代码)放在try语句块之内,当try语句块内发生异常时,异常就被抛出。 * `catch` -- 用于捕获异常。catch用来捕获try语句块中发生的异常。 * `finally` -- finally语句块总是会被执行。它主要用于回收在try块里打开的物力资源(如数据库连接、网络连接和磁盘文件)。只有finally块,执行完成之后,才会回来执行try或者catch块中的return或者throw语句,如果finally中使用了return或者throw等终止方法的语句,则就不会跳回执行,直接停止。 * `throw` -- 用于抛出异常。 * `throws` -- 用在方法签名中,用于声明该方法可能抛出的异常。 2. 异常分类 * `Throwable` 是 Java 语言中所有错误或异常的超类。 * `Exception` 及其子类是 `Throwable` 的一种形式,它指出了合理的应用程序想要捕获的条件。 * `RuntimeException`(`Exception` 的字类) 是那些可能在 Java 虚拟机正常运行期间抛出的异常的超类。 编译器不会检查 `RuntimeException` 异常。 如果代码会产生 `RuntimeException` 异常,则需要通过修改代码进行避免。例如,若会发生除数为零的情况,则需要通过代码避免该情况的发生! * `Error` 和 `Exception` 一样,`Error` 也是 `Throwable` 的子类。它用于指示合理的应用程序不应该试图捕获的严重问题,大多数这样的错误都是异常条件。 和 `RuntimeException` 一样,编译器也不会检查 `Error`。 3. 使用 1. Java将可抛出(`Throwable`)的结构分为三种类型:被检查的异常(`Checked Exception`),运行时异常(`RuntimeException`)和错误(`Error`)。 2. 运行时异常 定义: `RuntimeException`及其子类都被称为运行时异常。 特点: Java编译器不会检查它。也就是说,当程序中可能出现这类异常时,倘若既"没有通过`throws`声明抛出它",也"没有用`try-catch`语句捕获它",还是会编译通过。例如,除数为零时产生的`ArithmeticException`异常,数组越界时产生的IndexOutOfBoundsException异常,fail-fail机制产生的ConcurrentModificationException异常等,都属于运行时异常。   虽然Java编译器不会检查运行时异常,但是我们也可以通过`throws`进行声明抛出,也可以通过`try-catch`对它进行捕获处理。   如果产生运行时异常,则需要通过修改代码来进行避免。例如,若会发生除数为零的情况,则需要通过代码避免该情况的发生! 3. 被检查的异常 定义: `Exception` 类本身,以及 `Exception` 的子类中除了"运行时异常"之外的其它子类都属于被检查异常。 特点: Java编译器会检查它。此类异常,要么通过throws进行声明抛出,要么通过 `try-catch` 进行捕获处理,否则不能通过编译。例如,`CloneNotSupportedException` 就属于被检查异常。当通过`clone()`接口去克隆一个对象,而该对象对应的类没有实现Cloneable接口,就会抛出CloneNotSupportedException异常。   被检查异常通常都是可以恢复的。 4. 错误 定义: `Error` 类及其子类。 特点: 和运行时异常一样,编译器也不会对错误进行检查。   当资源不足、约束失败、或是其它程序无法继续运行的条件发生时,就产生错误。程序本身无法修复这些错误的。例如,`VirtualMachineError`就属于错误。   按照Java惯例,我们是不应该是实现任何新的`Error`子类的! 5. 对于上面的3种结构,我们在抛出异常或错误时,到底该哪一种?《Effective Java》中给出的建议是:对于可以恢复的条件使用被检查异常,对于程序错误使用运行时异常。 ## 参考 * [Java异常简介及其架构](https://www.cnblogs.com/skywang12345/p/3544168.html) * **《Effective Java》** *
Markdown
UTF-8
998
2.5625
3
[ "Apache-2.0" ]
permissive
# Bike Sharing Demand # Table of Contents * [Description](#Description) * [Prerequisites](#Prerequisites) * [Contributing](#Contributing) * [Author](#Author) * [Contact](#Contact) *** # Description * This repository containts my solution and analysis on [**bike sharing demand**](https://www.kaggle.com/c/bike-sharing-demand) dataset. * The models I tried were: **DecisionTreeRegressor**, **RandomForestRegressor**, **KNeighborsRegressor**, **BaggingRegressor**. * I have achived RMSLE score of **0.50390** on test set. *** # Prerequisites Ensure you have met the following requirements: * You have installed Python 3. * You have installed Sklearn * You have installed Pandas * You have installed Numpy * You have installed Matplotlib # Contributing * All ideas and helps are welcome. Please contact with me. # Author * Serkan Kaan Bahşi # Contact * [@SerkanKaanBahsi](https://github.com/SerkanKaanBahsi/) on **GitHub** * [@serkan-kaan-bahsi](https://www.linkedin.com/in/serkan-kaan-bahsi/) on **LinkedIn**
C++
UTF-8
3,356
2.828125
3
[ "Apache-2.0" ]
permissive
#include "lux/kit.hpp" #include "lux/define.cpp" #include <string.h> #include <vector> #include <set> #include <stdio.h> using namespace std; using namespace lux; int main() { kit::Agent gameState = kit::Agent(); // initialize gameState.initialize(); while (true) { /** Do not edit! **/ // wait for updates gameState.update(); vector<string> actions = vector<string>(); /** AI Code Goes Below! **/ Player &player = gameState.players[gameState.id]; Player &opponent = gameState.players[(gameState.id + 1) % 2]; GameMap &gameMap = gameState.map; vector<Cell *> resourceTiles = vector<Cell *>(); for (int y = 0; y < gameMap.height; y++) { for (int x = 0; x < gameMap.width; x++) { Cell *cell = gameMap.getCell(x, y); if (cell->hasResource()) { resourceTiles.push_back(cell); } } } // we iterate over all our units and do something with them for (int i = 0; i < player.units.size(); i++) { Unit unit = player.units[i]; if (unit.isWorker() && unit.canAct()) { if (unit.getCargoSpaceLeft() > 0) { // if the unit is a worker and we have space in cargo, lets find the nearest resource tile and try to mine it Cell *closestResourceTile; float closestDist = 9999999; for (auto it = resourceTiles.begin(); it != resourceTiles.end(); it++) { auto cell = *it; if (cell->resource.type == ResourceType::coal && !player.researchedCoal()) continue; if (cell->resource.type == ResourceType::uranium && !player.researchedUranium()) continue; float dist = cell->pos.distanceTo(unit.pos); if (dist < closestDist) { closestDist = dist; closestResourceTile = cell; } } if (closestResourceTile != nullptr) { auto dir = unit.pos.directionTo(closestResourceTile->pos); actions.push_back(unit.move(dir)); } } else { // if unit is a worker and there is no cargo space left, and we have cities, lets return to them if (player.cities.size() > 0) { auto city_iter = player.cities.begin(); auto &city = city_iter->second; float closestDist = 999999; CityTile *closestCityTile; for (auto &citytile : city.citytiles) { float dist = citytile.pos.distanceTo(unit.pos); if (dist < closestDist) { closestCityTile = &citytile; closestDist = dist; } } if (closestCityTile != nullptr) { auto dir = unit.pos.directionTo(closestCityTile->pos); actions.push_back(unit.move(dir)); } } } } } // you can add debug annotations using the methods of the Annotate class. // actions.push_back(Annotate::circle(0, 0)); /** AI Code Goes Above! **/ /** Do not edit! **/ for (int i = 0; i < actions.size(); i++) { if (i != 0) cout << ","; cout << actions[i]; } cout << endl; // end turn gameState.end_turn(); } return 0; }
C++
UTF-8
614
2.90625
3
[]
no_license
#include<iostream> #include<vector> using namespace std; int main() { string n[10]={"zero","one","two","three","four","five","six","seven","eight","nine"}; string num; // cin>>num; int sum=0; for(int i=0;i<num.size();i++) { sum+=num[i]-'0'; } vector<int> res; if(sum==0) res.push_back(0); while(sum>0) { int temp=sum%10; res.push_back(temp); sum=(sum-temp)/10; } for(int i=res.size()-1;i>0;i--) { printf("%s ",n[res[i]].c_str()); } printf("%s",n[res[0]].c_str()); return 0; }
Markdown
UTF-8
1,993
3.296875
3
[]
no_license
# MiBay Application MiBay is an application for delivery. Which is built up by Java using Eclipse. This program allows users to add customers, add products, prepare orders, remove products and display all deliveries. ## Menu<br> ![1](https://github.com/KandyChung/MIBay/assets/80769024/c757f201-248c-4b3d-af7d-592a7234fe44) ## Add Customer When users input “AC”, then input their information, such as first name, last name, street number, street name, suburb and postcode(Figure 1.0). Postcode must be a fixed 4 digit number and has to be numberice. Otherwise the program will display an error message(Figure 1.1).<br> ![2](https://github.com/KandyChung/MIBay/assets/80769024/1138361b-2b60-4935-a501-e2d7f126ddae) Figure 1.0 ![3](https://github.com/KandyChung/MIBay/assets/80769024/65e9643b-f9bf-4392-b326-20a76d1ebbe6) Figure 1.1 ## Add Product When users input “AP”, then input the product details to add a product(Figure 1.3).<br> ![4](https://github.com/KandyChung/MIBay/assets/80769024/1c2fabac-3b96-4139-94eb-ac32d7fd03ef) Figure 1.3 ## Prepare Order When users input “PP” which is preparing an order, choose the customer just add in previously then pick 1 or more products in the product list just add in previously. Next is to set the delivery date(Figure 1.4). Then the package for kandy chung was successfully prepared.<br> ![5](https://github.com/KandyChung/MIBay/assets/80769024/782c2c0b-d317-481f-a46e-4904e14f7bb7) Figure 1.4 ## Remove Product When input “RP '' which is remove product, choose the customer then select which product user wants to remove(Figure 1.5).<br> ![6](https://github.com/KandyChung/MIBay/assets/80769024/92f26c9e-aa98-433d-8498-34704850db82) Figure 1.5 ## Display All Deliveries When user input “DA” which displays all the deliveries, the user can choose to display ascending order or descending order(Figure 1.6).<br> ![7](https://github.com/KandyChung/MIBay/assets/80769024/87cfaeea-18e5-4e8f-b7c8-39fbcf7848ac) Figure 1.6
Java
UTF-8
9,641
2.578125
3
[]
no_license
package lab5; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.util.GenericOptionsParser; public class JoinTable { public static class TokenizerMapper extends Mapper<Object, Text, Text, Text>{ private Text word1=new Text(); private Text word2=new Text(); public void map(Object key, Text value, Context context ) throws IOException, InterruptedException { InputSplit inputSplit=(InputSplit)context.getInputSplit(); String filename=((FileSplit)inputSplit).getPath().getName(); System.out.println(filename); if(filename.equalsIgnoreCase("join1.txt")){ String line1=value.toString(); word1=new Text(line1); context.write(new Text("1"), word1); System.out.println(word1.toString()); }else if(filename.equalsIgnoreCase("join2.txt")){ String line2=value.toString(); word2=new Text(line2); context.write(new Text("1"), word2); System.out.println(word2.toString()); } } } public static class IntSumReducer extends Reducer<Text,Text,Text,Text> { Text word=new Text(); public void reduce(Text key, Iterable<Text> values, Context context ) throws IOException, InterruptedException { String[]arr=new String[100]; int count=0; System.out.println("reduce"); for (Text val : values) { arr[count]=val.toString(); count++; } System.out.println(arr[0]); System.out.println(arr[1]); String s1=arr[0]+" "+arr[1]; System.out.println(s1); String s2=arr[3]+" "+arr[4]; String[]arr1=s2.split(" "); String[]arr2=s1.split(" "); for (int i = 1; i < arr1.length; i=i+3) { for (int j = 0; j < arr2.length; j=j+2) { if(arr1[i].equals(arr2[j])){ System.out.println(arr1[i-1]+" "+arr1[i+1]+" "+arr2[j+1]); context.write(new Text(arr1[i-1]+" "+arr1[i]+ " "+arr1[i+1]+" "+arr2[j+1]), new Text(" ")); }else{ } } } } } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); // 判断output文件夹是否存在,如果存在则删除 Path path = new Path(args[1]);// 取第1个表示输出目录参数(第0个参数是输入目录) FileSystem fileSystem = path.getFileSystem(conf);// 根据path找到这个文件 if (fileSystem.exists(path)) { fileSystem.delete(path, true);// true的意思是,就算output有东西,也一带删除 } String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs(); if (otherArgs.length < 2) { System.err.println("Usage: wordcount <in> [<in>...] <out>"); System.exit(2); } Job job = new Job(conf, "word count"); job.setJarByClass(JoinTable.class); job.setMapperClass(TokenizerMapper.class); job.setReducerClass(IntSumReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); for (int i = 0; i < otherArgs.length - 1; ++i) { FileInputFormat.addInputPath(job, new Path(otherArgs[i])); } FileOutputFormat.setOutputPath(job, new Path(otherArgs[otherArgs.length - 1])); System.exit(job.waitForCompletion(true) ? 0 : 1); } } /*public class JoinTable { public static class MapClass extends Mapper { private static Hashtable joinData=new Hashtable(); public void configure(JobConf conf){ try { Path[] cachefiles=DistributedCache.getLocalCacheFiles(conf); if (cachefiles!=null&&cachefiles.length>0) { String line; String[]tokens; BufferedReader joinreader=new BufferedReader(new FileReader(cachefiles[0].toString())); try { while((line=joinreader.readLine())!=null){ tokens=line.split("\\t",2); joinData.put(tokens[0], tokens[1]); } } finally { joinreader.close(); } } } catch (Exception e) { System.err.println(""+e); } } public void map(Object key, Object value, OutputCollector output,Reporter reporter ) throws IOException, InterruptedException { Text text=(Text)value; String[] fields=text.toString().split("\\t"); String address=(String) joinData.get(fields[2]); if(address!=null){ output.collect(new Text(fields[2]),new Text(fields[0]+"\t"+fields[1]+"\t"+address)); } } } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); // 判断output文件夹是否存在,如果存在则删除 Path path = new Path(args[1]);// 取第1个表示输出目录参数(第0个参数是输入目录) FileSystem fileSystem = path.getFileSystem(conf);// 根据path找到这个文件 if (fileSystem.exists(path)) { fileSystem.delete(path, true);// true的意思是,就算output有东西,也一带删除 } String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs(); if (otherArgs.length < 2) { System.err.println("Usage: wordcount <in> [<in>...] <out>"); System.exit(2); } Job job = new Job(conf, "word count"); job.setJarByClass(JoinTable.class); job.setMapperClass(MapClass.class); DistributedCache.addCacheFile(new Path("/join2.txt").toUri(), conf); job.setOutputKeyClass(Text.class); job.setOutputValueClass(TextOutputFormat.class); FileInputFormat.addInputPath(job, new Path(otherArgs[0])); FileOutputFormat.setOutputPath(job, new Path(otherArgs[1])); System.exit(job.waitForCompletion(true) ? 0 : 1); } }*/ /*public class JoinTable { public static int time=0; public static class TokenizerMapper extends Mapper<Object, Text, Text, Text>{ public void map(Object key, Text value, Context context ) throws IOException, InterruptedException { String line=value.toString(); int i=0; if(line.contains("tellname")==true||line.contains("addressname")==true) //找出数据中的分割点 while(line.charAt(i) >= '9'|| line.charAt(i)<='0'){ i++; } if(line.charAt(i) >= '9'|| line.charAt(i)<='0'){ int j=i-1; while(line.charAt(j)!=' ') j--; String[]values={line.substring(0, j) , line.substring(i)}; context.write(new Text(values[1]), new Text("1+"+values[0])); } else{ int j=i+1; while(line.charAt(j)!=' ') j++; String[]values={line.substring(0, i+1) , line.substring(j)}; context.write(new Text(values[0]), new Text("2+"+values[1])); } } } public static class IntSumReducer extends Reducer<Text,Text,Text,Text> { public void reduce(Text key, Iterable<Text> values, Context context ) throws IOException, InterruptedException { int tell=0; String[]telllist=new String[10]; int address=0; String[]addresslist=new String[10]; Iterator iterator=values.iterator(); while(iterator.hasNext()){ String record=iterator.next().toString(); int len=record.length(); int i=2; char type=record.charAt(0); String tellname=new String(); String addressname=new String(); if(type=='1'){ telllist[tell]=record.substring(2); tell++; }else{ addresslist[address]=record.substring(2); address++; } } if(tell!=0&&address!=0){ for (int i = 0; i < tell; i++) { for (int j = 0; j < address; j++) { context.write(new Text(telllist[i]),new Text(addresslist[j])); } } } } } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); // 判断output文件夹是否存在,如果存在则删除 Path path = new Path(args[1]);// 取第1个表示输出目录参数(第0个参数是输入目录) FileSystem fileSystem = path.getFileSystem(conf);// 根据path找到这个文件 if (fileSystem.exists(path)) { fileSystem.delete(path, true);// true的意思是,就算output有东西,也一带删除 } String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs(); if (otherArgs.length < 2) { System.err.println("Usage: wordcount <in> [<in>...] <out>"); System.exit(2); } Job job = new Job(conf, "word count"); job.setJarByClass(JoinTable.class); job.setMapperClass(TokenizerMapper.class); job.setCombinerClass(IntSumReducer.class); job.setReducerClass(IntSumReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); for (int i = 0; i < otherArgs.length - 1; ++i) { FileInputFormat.addInputPath(job, new Path(otherArgs[i])); } FileOutputFormat.setOutputPath(job, new Path(otherArgs[otherArgs.length - 1])); System.exit(job.waitForCompletion(true) ? 0 : 1); } } */
Ruby
UTF-8
1,336
3.09375
3
[]
no_license
# Class: DinnerClub # # Models a dinner club that includes a number of diners. # # Attributes: # @name - String: contains club name. # @id - Number: id number associated with primary key in dinnerclubs table. # @table - String: "dinnerclubs" # # Public Methods: # #where_name class DinnerClub extend DatabaseClassMethods include DatabaseInstanceMethods attr_reader :id, :table attr_accessor :name # Public: .where_name # Get a list of dinner clubs with the given name. # # Parameters: # x - String: The name to search for. # # Returns: Array that contains objects for matching dinner club records. def self.where_name(x) results = DATABASE.execute("SELECT * FROM dinnerclubs WHERE name = '#{x}'") results_as_objects = [] results.each do |r| results_as_objects << self.new(r) end results_as_objects end # Public: #initialize # Creates DinnerClub object. # # Parameters: # @name - Array: contains member names. # @id - Number: derived from dinnerclubs table primary key. # @table - String: "dinnerclubs" - name of associated table # # Returns: # DinnerClub object. # # State Changes: # New object created. def initialize(options) @name = options["name"] @id = options["id"] @table = "dinnerclubs" end end
Python
UTF-8
3,984
3.78125
4
[]
no_license
# -*- coding: utf-8 -*- # TODO: прописать ходы для всех фигур: как они могут ходить через условия # TODO: прописать кнструкторы для всех фигур. Можно начать с короля. Наверно лучше создать одну фигуру полноценно, # потом уже по подобию описать и другие фигуры тоже # Сначала задаём константы. Нарисуем массив, который представляет собой шахматную доску: BOARD = [[False] * 8 for _ in range(8)] for y in range(8, 0, -1): for x in range(1, 9): BOARD[8 - y][x - 1] = {(x, y, 'white'): False} if (x + y) % 2 else {(x, y, 'black'): False} # массив вида 8 х 8 представляет собой список словарей. Кажый список - это горизонтальная строка шахматной доски, # столбец - вертикальная. Каждый словарь - это статус каждой клетки доски. # обозначение клеток доски: # {(x, y, color)}: is_empty - координаты клетки (x, y), color - цвет клетки, is_empty - свободна ли сейчас клетка, # или на ней находится фигура (если пуста, то False, если нет - то какая фигура на ней стоит) class Chessboard: """basic class Chessboard config""" def __init__(self): self = BOARD def __repr__(self): res = '' for _y in range(8): res += ''.join(map(str, BOARD[_y])) + "\n" # Все точки будут скллены в одну строку и перенесены. # # Так как два join объединяет только строки, а не объекты, приводим каждый элемент списка к строке. # # Проще всего это сделать при помощи операции map, которая берет каждый элемент списка и применяет # # к нему какую-либо функцию. В данном случае каждый объект передается функцией привидения к строке - str return res class King(Chessboard): """child class the King Chess piece""" def __init__(self): pass def move(self): pass def attack(self): pass def under_check(self): pass def checkmate(self): pass class Queen(Chessboard): """child class the Queen Chess piece""" def __init__(self): pass def move(self): pass def attack(self): pass class Rook(Chessboard): """child class the Rook Chess piece""" def __init__(self): pass def move(self): pass def attack(self): pass class Bishop(Chessboard): """child class the Bishop Chess piece""" def __init__(self): pass def move(self): pass def attack(self): pass class Knight(Chessboard): """child class the Knight Chess piece""" def __init__(self): pass def move(self): pass def attack(self): pass class Pawn(Chessboard): """child class the Pawn Chess piece""" def __init__(self): pass def move(self): pass def attack(self): pass def reward_choice(self): self.choice = input("Make your choice: Queen, Rook, Bishop or Knight: ").capitalize() if self.choice == "Queen": self = Queen() elif self.choice == "Rook": self = Rook() elif self.choice == "Bishop": self = Bishop() elif self.choice == "Knight": self = Knight()
Java
UTF-8
17,217
1.523438
2
[ "Apache-2.0" ]
permissive
/******************************************************************************* * Copyright 2012 Internet2 * * 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 edu.internet2.middleware.grouper.ws.coresoap; import java.util.Arrays; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.exception.ExceptionUtils; import edu.internet2.middleware.grouper.hibernate.GrouperTransactionType; import edu.internet2.middleware.grouper.misc.GrouperVersion; import edu.internet2.middleware.grouper.util.GrouperUtil; import edu.internet2.middleware.grouper.ws.GrouperServiceJ2ee; import edu.internet2.middleware.grouper.ws.GrouperWsConfig; import edu.internet2.middleware.grouper.ws.ResultMetadataHolder; import edu.internet2.middleware.grouper.ws.WsResultCode; import edu.internet2.middleware.grouper.ws.coresoap.WsAssignAttributeBatchResult.WsAssignAttributeBatchResultCode; import edu.internet2.middleware.grouper.ws.exceptions.GrouperWsException; import edu.internet2.middleware.grouper.ws.rest.WsResponseBean; import edu.internet2.middleware.grouper.ws.util.GrouperServiceUtils; import edu.internet2.middleware.grouper.ws.util.GrouperWsLog; /** * <pre> * results for assigning attributes call. * * result code: * code of the result for this attribute assignment overall * SUCCESS: means everything ok * INSUFFICIENT_PRIVILEGES: problem with some input where privileges are not sufficient * INVALID_QUERY: bad inputs * EXCEPTION: something bad happened * </pre> * @author mchyzer */ public class WsAssignAttributesBatchResults implements WsResponseBean, ResultMetadataHolder { /** * make sure if there is an error, to record that as an error * @param grouperTransactionType for request * @param theSummary * @return true if success, false if not */ public boolean tallyResults(GrouperTransactionType grouperTransactionType, String theSummary) { //maybe already a failure boolean successOverall = GrouperUtil.booleanValue(this.getResultMetadata() .getSuccess(), true); if (this.getWsAssignAttributeBatchResultArray() != null) { // check all entries int successes = 0; int failures = 0; int arrayLength = GrouperUtil.length(this.getWsAssignAttributeBatchResultArray()); for (int i=0;i<arrayLength;i++) { WsAssignAttributeBatchResult wsAssignAttributeBatchResult = this.getWsAssignAttributeBatchResultArray()[i]; if(wsAssignAttributeBatchResult == null) { wsAssignAttributeBatchResult = new WsAssignAttributeBatchResult(); this.getWsAssignAttributeBatchResultArray()[i] = wsAssignAttributeBatchResult; } if (wsAssignAttributeBatchResult.getResultMetadata() == null) { wsAssignAttributeBatchResult.setResultMetadata(new WsResultMeta()); wsAssignAttributeBatchResult.getResultMetadata().setSuccess("F"); } boolean theSuccess = "T".equalsIgnoreCase(wsAssignAttributeBatchResult.getResultMetadata() .getSuccess()); if (theSuccess) { successes++; } else { failures++; } } final Map<String, Object> debugMap = GrouperServiceJ2ee.retrieveDebugMap(); GrouperWsLog.addToLogIfNotBlank(debugMap, "successes", successes); GrouperWsLog.addToLogIfNotBlank(debugMap, "failures", failures); //if transaction rolled back all line items, if ((!successOverall || failures > 0) && grouperTransactionType.isTransactional() && !grouperTransactionType.isReadonly()) { for (int i=0;i<arrayLength;i++) { WsAssignAttributeBatchResult wsAssignAttributeBatchResult = this.getWsAssignAttributeBatchResultArray()[i]; if (GrouperUtil.booleanValue( wsAssignAttributeBatchResult.getResultMetadata().getSuccess(), true)) { wsAssignAttributeBatchResult .assignResultCode(WsAssignAttributeBatchResultCode.TRANSACTION_ROLLED_BACK); failures++; } } } if (failures > 0) { this.getResultMetadata().appendResultMessage( "There were " + successes + " successes and " + failures + " failures of assigning attributes. "); this.assignResultCode(WsAssignAttributesBatchResultsCode.PROBLEM_WITH_ASSIGNMENT); //this might not be a problem GrouperWsException.logWarn(this.getResultMetadata().getResultMessage()); } else { this.assignResultCode(WsAssignAttributesBatchResultsCode.SUCCESS); } } else { //none is not ok, must pass one in this.assignResultCode(WsAssignAttributesBatchResultsCode.SUCCESS); this.getResultMetadata().appendResultMessage( "No attribute assignments were passed in, "); } //make response descriptive if (GrouperUtil.booleanValue(this.getResultMetadata().getSuccess(), false)) { this.getResultMetadata().appendResultMessage("Success for: " + theSummary); return true; } //false if need rollback return !grouperTransactionType.isTransactional(); } /** * process an exception, log, etc * @param wsAssignAttributesBatchResultsCode * @param theError * @param e */ public void assignResultCodeException( WsAssignAttributesBatchResultsCode wsAssignAttributesBatchResultsCode, String theError, Exception e) { wsAssignAttributesBatchResultsCode = GrouperUtil.defaultIfNull( wsAssignAttributesBatchResultsCode, WsAssignAttributesBatchResultsCode.PROBLEM_WITH_ASSIGNMENT); //a helpful exception will probably be in the getMessage() this.assignResultCode(wsAssignAttributesBatchResultsCode); this.getResultMetadata().appendResultMessageError(theError); this.getResultMetadata().appendResultMessageError(e); GrouperWsException.logError(theError, e); } /** * attribute def references in the assignments or inputs (and able to be read) */ private WsAttributeDef[] wsAttributeDefs; /** * attribute def references in the assignments or inputs (and able to be read) * @return attribute defs */ public WsAttributeDef[] getWsAttributeDefs() { return this.wsAttributeDefs; } /** * attribute def references in the assignments or inputs (and able to be read) * @param wsAttributeDefs1 */ public void setWsAttributeDefs(WsAttributeDef[] wsAttributeDefs1) { this.wsAttributeDefs = wsAttributeDefs1; } /** * attribute def names referenced in the assignments or inputs (and able to read) */ private WsAttributeDefName[] wsAttributeDefNames; /** * attribute def names referenced in the assignments or inputs (and able to read) * @return attribute def names */ public WsAttributeDefName[] getWsAttributeDefNames() { return this.wsAttributeDefNames; } /** * attribute def names referenced in the assignments or inputs (and able to read) * @param wsAttributeDefNames1 */ public void setWsAttributeDefNames(WsAttributeDefName[] wsAttributeDefNames1) { this.wsAttributeDefNames = wsAttributeDefNames1; } /** * the assignment results being queried */ private WsAssignAttributeBatchResult[] wsAssignAttributeBatchResultArray; /** * the assignment results being queried * @return the assignments being queried */ public WsAssignAttributeBatchResult[] getWsAssignAttributeBatchResultArray() { return this.wsAssignAttributeBatchResultArray; } /** * the assignment results being queried * @param wsAttributeAssignResults1 */ public void setWsAssignAttributeBatchResultArray(WsAssignAttributeBatchResult[] wsAttributeAssignResults1) { this.wsAssignAttributeBatchResultArray = wsAttributeAssignResults1; } /** * attributes of subjects returned, in same order as the data */ private String[] subjectAttributeNames; /** * result code of a request. The possible result codes * of WsGetMembersResultCode (with http status codes) are: * SUCCESS(200), EXCEPTION(500), INVALID_QUERY(400) */ public static enum WsAssignAttributesBatchResultsCode implements WsResultCode { /** found the attributeAssignments (lite status code 200) (success: T) */ SUCCESS(200), /** if one or more entries had problems, but some others succeeded. (success: F) */ PROBLEM_WITH_ASSIGNMENT(500); /** get the name label for a certain version of client * @param clientVersion * @return name */ public String nameForVersion(GrouperVersion clientVersion) { return this.name(); } /** * construct with http code * @param theHttpStatusCode the code */ private WsAssignAttributesBatchResultsCode(int theHttpStatusCode) { this.httpStatusCode = theHttpStatusCode; } /** http status code for result code */ private int httpStatusCode; /** * if this is a successful result * @return true if success */ public boolean isSuccess() { return this == SUCCESS; } /** get the http result code for this status code * @return the status code */ public int getHttpStatusCode() { return this.httpStatusCode; } } /** * assign the code from the enum * @param getAttributeAssignmentsResultCode */ public void assignResultCode(WsAssignAttributesBatchResultsCode getAttributeAssignmentsResultCode) { this.getResultMetadata().assignResultCode(getAttributeAssignmentsResultCode); } /** * attributes of subjects returned, in same order as the data * @return the attributeNames */ public String[] getSubjectAttributeNames() { return this.subjectAttributeNames; } /** * attributes of subjects returned, in same order as the data * @param attributeNamesa the attributeNames to set */ public void setSubjectAttributeNames(String[] attributeNamesa) { this.subjectAttributeNames = attributeNamesa; } /** * metadata about the result */ private WsResultMeta resultMetadata = new WsResultMeta(); /** * @return the resultMetadata */ public WsResultMeta getResultMetadata() { return this.resultMetadata; } /** * metadata about the result */ private WsResponseMeta responseMetadata = new WsResponseMeta(); /** * groups that are in the results */ private WsGroup[] wsGroups; /** * stems that are in the results */ private WsStem[] wsStems; /** * stems that are in the results * @return stems */ public WsStem[] getWsStems() { return this.wsStems; } /** * stems that are in the results * @param wsStems1 */ public void setWsStems(WsStem[] wsStems1) { this.wsStems = wsStems1; } /** * results for each assignment sent in */ private WsMembership[] wsMemberships; /** * subjects that are in the results */ private WsSubject[] wsSubjects; /** * @see edu.internet2.middleware.grouper.ws.rest.WsResponseBean#getResponseMetadata() * @return the response metadata */ public WsResponseMeta getResponseMetadata() { return this.responseMetadata; } /** * @param resultMetadata1 the resultMetadata to set */ public void setResultMetadata(WsResultMeta resultMetadata1) { this.resultMetadata = resultMetadata1; } /** * @param responseMetadata1 the responseMetadata to set */ public void setResponseMetadata(WsResponseMeta responseMetadata1) { this.responseMetadata = responseMetadata1; } /** * @return the wsGroups */ public WsGroup[] getWsGroups() { return this.wsGroups; } /** * results for each assignment sent in * @return the results */ public WsMembership[] getWsMemberships() { return this.wsMemberships; } /** * subjects that are in the results * @return the subjects */ public WsSubject[] getWsSubjects() { return this.wsSubjects; } /** * @param wsGroup1 the wsGroups to set */ public void setWsGroups(WsGroup[] wsGroup1) { this.wsGroups = wsGroup1; } /** * results for each assignment sent in * @param results1 the results to set */ public void setWsMemberships(WsMembership[] results1) { this.wsMemberships = results1; } /** * subjects that are in the results * @param wsSubjects1 */ public void setWsSubjects(WsSubject[] wsSubjects1) { this.wsSubjects = wsSubjects1; } /** * assign results * @param attributeAssignBatchResults * @param theSubjectAttributeNames */ public void assignResult(List<WsAssignAttributeBatchResult> attributeAssignBatchResults, String[] theSubjectAttributeNames) { this.subjectAttributeNames = theSubjectAttributeNames; this.setWsAssignAttributeBatchResultArray(GrouperUtil.toArray(attributeAssignBatchResults, WsAssignAttributeBatchResult.class)); } /** * sort the results by assignment */ public void sortResults() { //dont do this, they should be in order //if (this.wsAssignAttributeBatchResultArray != null) { // Arrays.sort(this.wsAssignAttributeBatchResultArray); //} if (this.wsAttributeDefNames != null) { Arrays.sort(this.wsAttributeDefNames); } if (this.wsAttributeDefs != null) { Arrays.sort(this.wsAttributeDefs); } if (this.wsGroups != null) { Arrays.sort(this.wsGroups); } if (this.wsMemberships != null) { Arrays.sort(this.wsMemberships); } if (this.wsStems != null) { Arrays.sort(this.wsStems); } if (this.wsSubjects != null) { Arrays.sort(this.wsSubjects); } } /** * add a result to the list of results, and keep track of all the related objects * @param wsAssignAttributesResults * @param theError * @param e * @param index */ public void addResult(WsAssignAttributesResults wsAssignAttributesResults, String theError, Exception e, int index) { //lets collate the results, note, we can make this more efficient later as far as resolving objects WsAssignAttributeBatchResult wsAssignAttributeBatchResult = null; //there should only be one result... if (wsAssignAttributesResults != null && GrouperUtil.length(wsAssignAttributesResults.getWsAttributeAssignResults()) > 0) { if (GrouperUtil.length(wsAssignAttributesResults.getWsAttributeAssignResults()) > 1) { throw new RuntimeException("Why are there more one result???? " + GrouperUtil.length(wsAssignAttributesResults.getWsAttributeAssignResults())); } wsAssignAttributeBatchResult = new WsAssignAttributeBatchResult(wsAssignAttributesResults, wsAssignAttributesResults.getWsAttributeAssignResults()[0]); //do the related objects this.wsAttributeDefNames = GrouperServiceUtils.mergeArrays(this.wsAttributeDefNames, wsAssignAttributesResults.getWsAttributeDefNames(), "name", WsAttributeDefName.class); this.wsAttributeDefs = GrouperServiceUtils.mergeArrays(this.wsAttributeDefs, wsAssignAttributesResults.getWsAttributeDefs(), "name", WsAttributeDef.class); this.wsGroups = GrouperServiceUtils.mergeArrays(this.wsGroups, wsAssignAttributesResults.getWsGroups(), "name", WsGroup.class); this.wsMemberships = GrouperServiceUtils.mergeArrays(this.wsMemberships, wsAssignAttributesResults.getWsMemberships(), "membershipId", WsMembership.class); this.wsStems = GrouperServiceUtils.mergeArrays(this.wsStems, wsAssignAttributesResults.getWsStems(), "name", WsStem.class); this.wsSubjects = GrouperServiceUtils.mergeArrays(this.wsSubjects, wsAssignAttributesResults.getWsSubjects(), new String[]{"sourceId", "id"}, WsSubject.class); } else { wsAssignAttributeBatchResult = new WsAssignAttributeBatchResult(wsAssignAttributesResults, theError, e); //add a blank one? } this.wsAssignAttributeBatchResultArray[index] = wsAssignAttributeBatchResult; //add it to the array of results //there should be one result from the assignment //tempResults.get } }
Markdown
UTF-8
1,119
3.09375
3
[ "MIT" ]
permissive
--- title: 强制类型转换 date: 2018-4-8 --- * content {:toc} ## msdn的解释 [强制转换运算符](https://msdn.microsoft.com/zh-cn/library/5f6c9f8h.aspx) `dynamic_cast` 用于多态类型的转换。 `static_cast` 用于非多态类型的转换。 `const_cast` 用于删除 `const、volatile` 和 `__unaligned` 特性。 `reinterpret_cast` 用于位的简单重新解释。 ### [dynamic_cast 运算符](https://msdn.microsoft.com/zh-cn/library/cby9kycs.aspx) 语法: `dynamic_cast < type-id > ( expression )` dynamic_cast 只适用于指针或引用,而且运行时类型检查也是一项开销. 即 `type-id` 必须是指针或引用,或是`void*` ### [static_cast 运算符](https://msdn.microsoft.com/zh-cn/library/c36yw7x9.aspx) 运算符可用于将指向基类的指针转换为指向派生类的指针等操作。 此类转换并非始终安全。 ### [const_cast 运算符](https://msdn.microsoft.com/zh-cn/library/bz6at95h.aspx) 从类中移除 `const、volatile` 和 `__unaligned` 特性. ### [reinterpret_cast 运算符](https://msdn.microsoft.com/zh-cn/library/e0w9f63b.aspx)
Shell
UTF-8
706
2.765625
3
[ "Apache-2.0" ]
permissive
TERMUX_PKG_HOMEPAGE="https://github.com/danielgtaylor/restish" TERMUX_PKG_DESCRIPTION="A CLI for interacting with REST-ish HTTP APIs" TERMUX_PKG_LICENSE="MIT" TERMUX_PKG_LICENSE_FILE="LICENSE.md" TERMUX_PKG_MAINTAINER="@termux" TERMUX_PKG_VERSION="0.14.0" TERMUX_PKG_SRCURL="https://github.com/danielgtaylor/restish/archive/v$TERMUX_PKG_VERSION.tar.gz" TERMUX_PKG_SHA256="2688340ff307aa522325afab40b9eaf6847d0b4b6a7a9c05f041056408b3fc50" TERMUX_PKG_AUTO_UPDATE=true termux_step_make() { termux_setup_golang cd "$TERMUX_PKG_SRCDIR" export GOPATH="${TERMUX_PKG_BUILDDIR}" go build } termux_step_make_install() { install -Dm755 -t "${TERMUX_PREFIX}/bin" "${TERMUX_PKG_SRCDIR}/restish" }
Java
UTF-8
1,656
2.359375
2
[]
no_license
package com.petsmile.servlets; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; import com.petsmile.dto.MascotaDTO; import com.petsmile.service.MascotaServiceImpl; /** * Servlet implementation class MascotaServlet */ public class MascotaServlet extends HttpServlet { private static final long serialVersionUID = 1L; private Gson gson = new Gson(); /** * @see HttpServlet#HttpServlet() */ public MascotaServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String rut = request.getParameter("rut"); MascotaServiceImpl mascotaService = new MascotaServiceImpl(); List<MascotaDTO> mascotas = mascotaService.buscarMascotasPorDueno(rut); String data = this.gson.toJson(mascotas); PrintWriter out = response.getWriter(); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); out.print(data); out.flush(); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
Markdown
UTF-8
1,585
3.5625
4
[]
no_license
/*题目描述 多项式 多项式的系数[b(2)b(1)b(0)]=[1 2 5] 二者相乘所得的多项式的系数[c(3)c(2)c(1)c(0)]=[1 3 7 5] 利用上面的计算方法,我们很容易得到: c(0)=a(0)b(0) c(1)=a(0)b(1)+a(1)b(0) c(2)=a(0)b(2)+a(1)b(1)+a(2)b(0) c(3)=a(0)b(3)+a(1)b(2)+a(2)b(1)+a(3)b(0) 其中:a(3)=a(2)=b(3)=0 在上面的基础上推广一下: 假定两个多项式的系数分别为a(n),n=0-n1和b(n),n=0-n2,这 两个多项式相乘所得的多项式系数为c(n),则: c(0)=a(0)b(0) c(1)=a(0)b(1)+a(1)b(0) c(2)=a(0)b(2)+a(1)b(1)+a(2)b(0) c(3)=a(0)b(3)+a(1)b(2)+a(2)b(1)+a(3)b(0) c(4)=a(0)b(4)+a(1)b(3)+a(2)b(2)+a(3)b(1)+a(4)b(0) 以此类推可以得到卷积算法: ![卷积算法公式](./a.png) 上面这个式子就是a(n)和b(n)的卷积表达式 通常我们把a(n)和b(n)的卷积记为:a(n)*b(n),其中的*表示卷积运算符 输入描述: 两个最高阶数为4的复数多项式系数序列。高阶系数先输入,每个系数为复数,复数先输入实数部分, 再输入虚数部分,实部或者虚部为0,则输入0; 每个实部和虚部的系数最大值不超过1000 输出描述 求卷积多项式系数输出;先输出高阶系数,多项式算法: ![卷积算法公式](./a.png) 示例 输入 1 1 1 1 1 1 1 1 1 ... 输出 0 2 0 4 0 6 0 8 0 10 0 8 0 6 ... */ public class Test2 { }
TypeScript
UTF-8
1,055
3.046875
3
[ "Apache-2.0" ]
permissive
import { BigNumber } from "bignumber.js"; import Web3 = require("web3"); export class Bitstream { private data: string; constructor() { this.data = ""; } public getData() { if (this.data.length === 0) { return "0x0"; } else { return "0x" + this.data; } } public addBigNumber(x: BigNumber, numBytes = 32) { this.data += this.padString(web3.toHex(x).slice(2), numBytes * 2); } public addNumber(x: number, numBytes = 4) { this.addBigNumber(new BigNumber(x), numBytes); } public addAddress(x: string, numBytes = 20) { this.data += this.padString(x.slice(2), numBytes * 2); } public addHex(x: string) { if (x.startsWith("0x")) { this.data += x.slice(2); } else { this.data += x; } } private padString(x: string, targetLength: number) { if (x.length > targetLength) { throw Error("0x" + x + " is too big to fit in the requested length (" + targetLength + ")"); } while (x.length < targetLength) { x = "0" + x; } return x; } }
Shell
UTF-8
553
2.765625
3
[ "Apache-2.0" ]
permissive
#!/bin/bash # ??? Magic ??? # Delete uneccessary static libraries, which we don't need for some reason. find /usr/local/cuda-*/lib*/ -type f -name 'lib*_static.a' -not -name 'libcudart_static.a' -delete rm /usr/lib/x86_64-linux-gnu/libcudnn_static_v*.a # Link the libcuda stub to the location where tensorflow is searching for it and reconfigure # dynamic linker run-time bindings ln -s /usr/local/cuda/lib64/stubs/libcuda.so /usr/local/cuda/lib64/stubs/libcuda.so.1 echo "/usr/local/cuda/lib64/stubs" > /etc/ld.so.conf.d/z-cuda-stubs.conf ldconfig
JavaScript
UTF-8
2,121
3.234375
3
[]
no_license
import data from './data/rickandmorty/rickandmorty.js'; import {sortData} from './data.js'; console.log(sortData, data); // Averiguar porqué no es una función pura const sortBy = "name"; // Función para aparecer y desaparecer páginas const firstPage = document.getElementById("firstPage"); const secondPage = document.getElementById("secondPage"); // Botón INGRESAR document.getElementById("buttonEnter").addEventListener("click", () => { firstPage.style.display = "none"; secondPage.style.display = "block"; }); // Botón VOLVER document.getElementById("buttonBack").addEventListener("click", () => { secondPage.style.display = "none"; firstPage.style.display = "block"; }); // Evento onclick para redireccionar a páginas /* document.getElementById('buttonTrailer').onclick = () => { location.href = "https://www.youtube.com/watch?v=E8cXKMR9a1Q&ab_channel=JoyasDeLaAnimaci%C3%B3n" } document.getElementById('buttonSynopsis').onclick = () => { location.href = "https://www.sensacine.com/series/serie-11561/" } */ // Llamar personajes // <li>Episodio: ${rickandmorty.episode}</li> const rickandmorty = data.results; const printCharacters = document.getElementById("root"); const drawCard = (rickandmorty) => { return ` <section class="card"> <img src="${rickandmorty.image}" alt="imagen del personaje" class="cardImage"> <ul> <p class="cardText">${rickandmorty.name}</p> <p class="cardText">Especie: ${rickandmorty.species}</p> <p class="cardText">Estatus: ${rickandmorty.status}</p> </ul> </section>`; }; /* for (let i=0; i < rickandmorty.length; i++) { */ for (let i=0; i < 20; i++) { printCharacters.innerHTML += drawCard(rickandmorty[i]); }; // SortBy const orderOption = document.querySelector(".orderedBox"); orderOption.addEventListener("change", (event) => { const chosenOrder = sortData(data, sortBy, event.target.value); const print = (results) => { printCharacters.innerHTML = ""; for (let i=0; i < 20; i++) { printCharacters.innerHTML += drawCard(rickandmorty[i]); }; } print(chosenOrder); });
Rust
UTF-8
2,387
2.875
3
[]
no_license
extern crate atelier_core; extern crate serde_json; extern crate bincode; #[test] fn serialize_asset_uuid_string() { let uuid = atelier_core::AssetUuid([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, ]); let result = serde_json::to_string(&uuid).unwrap(); assert_eq!("\"01020304-0506-0708-090a-0b0c0d0e0f10\"".to_string(), result); } #[test] fn serialize_asset_uuid_binary() { let data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; let uuid = atelier_core::AssetUuid(data); let result: Vec<u8> = bincode::serialize(&uuid).unwrap(); assert_eq!(data.to_vec(), result); } #[test] fn deserialize_asset_uuid_string() { let string = "\"01020304-0506-0708-090a-0b0c0d0e0f10\""; let result: atelier_core::AssetUuid = serde_json::from_str(string).unwrap(); let expected = atelier_core::AssetUuid([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, ]); assert_eq!(expected, result); } #[test] fn deserialize_asset_uuid_binary() { let data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; let result: atelier_core::AssetUuid = bincode::deserialize(&data).unwrap(); assert_eq!(atelier_core::AssetUuid(data), result); } #[test] fn serialize_type_uuid_string() { let uuid = atelier_core::AssetTypeId([ 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, ]); let result = serde_json::to_string(&uuid).unwrap(); assert_eq!("\"03010401-0509-0206-0503-050809070903\"".to_string(), result); } #[test] fn serialize_type_uuid_binary() { let data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; let uuid = atelier_core::AssetTypeId(data); let result: Vec<u8> = bincode::serialize(&uuid).unwrap(); assert_eq!(data.to_vec(), result); } #[test] fn deserialize_type_uuid_string() { let string = "\"03010401-0509-0206-0503-050809070903\""; let result: atelier_core::AssetTypeId = serde_json::from_str(string).unwrap(); let expected = atelier_core::AssetTypeId([ 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, ]); assert_eq!(expected, result); } #[test] fn deserialize_type_uuid_binary() { let data = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3]; let result: atelier_core::AssetTypeId = bincode::deserialize(&data).unwrap(); assert_eq!(atelier_core::AssetTypeId(data), result); }
Markdown
UTF-8
1,053
2.71875
3
[ "BSD-3-Clause" ]
permissive
# 2. Use torando_openapi3 instead of JSON Schema validation Date: 2021-01-21 ## Status Accepted ## Context Previously, the API would use parts of the OpenAPI spec to validate request payloads using a JSON Schema validator. With the creation of [tornado_openapi3](https://pypi.org/project/tornado-openapi3/), we can simplify the overall API architecture, validating all requests in the `Tornado.web.RequestHandler.prepare()` method. Such validation provides a holistic approach to request validation, validating the headers, query args, request body, etc. ## Decision `tornado_openapi3` has been swapped out for the previous JSON schema behavior validation approach. ## Consequences While the validation is more holistic, errors in the API spec will prevent otherwise successful requests from succeeding. This approach requires a high level of accuracy in the OpenAPI spec, which given the scope of the API, can be difficult to achieve. In addition, a non-trivial amount of work was done to refactor the codebase to switch to this approach.
Java
UTF-8
5,513
2.375
2
[ "MIT" ]
permissive
package uk.gov.hmcts.reform.iacaseapi.domain.handlers.postsubmit; import static java.util.Objects.requireNonNull; import static uk.gov.hmcts.reform.iacaseapi.domain.entities.AsylumCaseFieldDefinition.*; import static uk.gov.hmcts.reform.iacaseapi.domain.entities.ccd.field.PaymentStatus.FAILED; import static uk.gov.hmcts.reform.iacaseapi.domain.entities.ccd.field.PaymentStatus.PAID; import java.util.Optional; import org.springframework.stereotype.Component; import uk.gov.hmcts.reform.iacaseapi.domain.RequiredFieldMissingException; import uk.gov.hmcts.reform.iacaseapi.domain.entities.AsylumCase; import uk.gov.hmcts.reform.iacaseapi.domain.entities.ccd.Event; import uk.gov.hmcts.reform.iacaseapi.domain.entities.ccd.State; import uk.gov.hmcts.reform.iacaseapi.domain.entities.ccd.callback.Callback; import uk.gov.hmcts.reform.iacaseapi.domain.entities.ccd.callback.PostSubmitCallbackResponse; import uk.gov.hmcts.reform.iacaseapi.domain.handlers.PostSubmitCallbackHandler; @Component public class AppealPaymentConfirmation implements PostSubmitCallbackHandler<AsylumCase> { private final AppealPaymentConfirmationProvider appealPaymentConfirmationProvider; public AppealPaymentConfirmation(AppealPaymentConfirmationProvider appealPaymentConfirmationProvider) { this.appealPaymentConfirmationProvider = appealPaymentConfirmationProvider; } public boolean canHandle( Callback<AsylumCase> callback ) { requireNonNull(callback, "callback must not be null"); return callback.getEvent() == Event.PAYMENT_APPEAL; } public PostSubmitCallbackResponse handle( Callback<AsylumCase> callback ) { if (!canHandle(callback)) { throw new IllegalStateException("Cannot handle callback"); } PostSubmitCallbackResponse postSubmitResponse = new PostSubmitCallbackResponse(); final AsylumCase asylumCase = callback.getCaseDetails().getCaseData(); final String feeLabel = "\n\n#### Fee\n"; final String paymentReferenceNumberLabel = "\n\n#### Payment reference number\n"; if (appealPaymentConfirmationProvider.getPaymentStatus(asylumCase).equals(Optional.of(FAILED))) { String paymentErrorMessage = requireNonNull(callback.getCaseDetails().getCaseData().read(PAYMENT_ERROR_MESSAGE, String.class) .<RequiredFieldMissingException>orElseThrow(() -> new RequiredFieldMissingException("payment error message missing"))); postSubmitResponse.setConfirmationHeader(""); postSubmitResponse.setConfirmationBody( "![Payment failed confirmation](https://raw.githubusercontent.com/hmcts/ia-appeal-frontend/master/app/assets/images/paymentFailed.png)\n" + "#### Do this next\n\n" + "Call 01633 652 125 (option 3) or email MiddleOffice.DDServices@liberata.com to try to resolve the payment issue.\n\n" + "\n\n\n#### Payment failed" + paymentReferenceNumberLabel + appealPaymentConfirmationProvider.getPaymentReferenceNumber(asylumCase) + "\n\n#### Payment by account number\n" + appealPaymentConfirmationProvider.getPaymentAccountNumber(asylumCase) + feeLabel + "£" + appealPaymentConfirmationProvider.getFee(asylumCase) + "\n\n#### Reason for failed payment\n" + paymentErrorMessage ); } if (appealPaymentConfirmationProvider.getPaymentStatus(asylumCase).equals(Optional.of(PAID))) { final State currentState = callback .getCaseDetails() .getState(); if (currentState.equals(State.APPEAL_STARTED)) { postSubmitResponse.setConfirmationHeader("# You have paid for the appeal \n# You still need to submit it"); postSubmitResponse.setConfirmationBody( "#### Do this next\n\n" + "You still need to [submit your appeal](/case/IA/Asylum/" + callback.getCaseDetails().getId() + "/trigger/submitAppeal)" + "\n\n\n#### Payment successful" + paymentReferenceNumberLabel + appealPaymentConfirmationProvider.getPaymentReferenceNumber(asylumCase) + "\n\n#### Payment by account number\n" + appealPaymentConfirmationProvider.getPaymentAccountNumber(asylumCase) + feeLabel + "£" + appealPaymentConfirmationProvider.getFee(asylumCase) ); } else { postSubmitResponse.setConfirmationHeader("# You have paid for the appeal"); postSubmitResponse.setConfirmationBody( "#### What happens next\n\n" + "You will receive a notification to confirm the payment has been made." + "\n\n\n#### Payment successful" + paymentReferenceNumberLabel + appealPaymentConfirmationProvider.getPaymentReferenceNumber(asylumCase) + "\n\n#### Payment by Account number\n" + appealPaymentConfirmationProvider.getPaymentAccountNumber(asylumCase) + feeLabel + "£" + appealPaymentConfirmationProvider.getFee(asylumCase) ); } } return postSubmitResponse; } }
Markdown
UTF-8
709
2.984375
3
[ "MIT" ]
permissive
# SubmitButton Button for submitting form. *`SubmitButton` should be wrapped into `Form`* ## Public interface ### Props `SubmitButton` contains html `<button />` element. All props for `<button />` are valid for `SubmitButton`. Own props: - `loadingClassname` - class that applies while submit. By default - `is-loading`. - `loadingComponent` - component that will render while submit. `Optional` ## Example ```jsx <Form onSubmit={async (values) => await someRequest(values)} validator={new SchemaValidator(ExampleSchema)} errorParser={(error) => myCustomParser(error)} > <SubmitButton loadingComponent={<span>wait...</span>}> <span> submit </span> </SubmitButton> </Form> ```
JavaScript
UTF-8
1,735
2.9375
3
[]
no_license
/** * Function: addMarker * Add a new marker to the markers layer given the following lonlat, * popupClass, and popup contents HTML. Also allow specifying * whether or not to give the popup a close box. * * Parameters: * ll - {<OpenLayers.LonLat>} Where to place the marker * layer - {<OpenLayers.Layer>} Which layers to place the marker * popupClass - {<OpenLayers.Class>} Which class of popup to bring up * when the marker is clicked. * popupContentHTML - {String} What to put in the popup * closeBox - {Boolean} Should popup have a close box? * overflow - {Boolean} Let the popup overflow scrollbars? * * (Taken from somewhere in the Internets and then modified) */ function addMarker(ll, markerObj, layer, popupClass, popupContentHTML, closeBox, overflow, icon) { var feature = new OpenLayers.Feature(layer, ll); feature.closeBox = closeBox; feature.popupClass = popupClass; feature.data.popupContentHTML = popupContentHTML; feature.data.overflow = (overflow) ? "auto" : "hidden"; if(icon != ""){ feature.data.icon = new OpenLayers.Icon(OpenLayers.Util.getImageLocation(icon) , { w:21, h:25 },{ x:-10.5, y:-25 }); } var marker = feature.createMarker(); marker.events.register("mousedown", feature, function(evt) { if (this.popup == null) { this.popup = this.createPopup(this.closeBox); map.addPopup(this.popup); this.popup.show(); } else { this.popup.toggle(); } currentPopup = this.popup; OpenLayers.Event.stop(evt); }); layer.addMarker(marker); markers[markerObj] = marker; }
Java
UTF-8
1,625
3.59375
4
[]
no_license
/** The purpose of this code is to print Logback records to the console in the following order: debug, info, and error. * The error message is also exported to a log file. Unlike First Log, Third Log is more Logback-dependent. */ package LoggerJam; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import org.slf4j.LoggerFactory; public class ThirdLog { /* Format: Year-Month-Day Hour:Minute:Second:Milliseconds LEVEL [thread] class:line number - message */ static final Logger xylem = (Logger) LoggerFactory.getLogger(ThirdLog.class); /** fwoosh adjusts the root logger level * @param L is the new logger level */ public void fwoosh(Level L){ Logger swap = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); // instantiate logger swap.setLevel(L); // change the logger level } /* Main Method */ public static void main(String[] args){ ThirdLog phloem = new ThirdLog(); // instantiate constructor phloem.fwoosh(Level.ERROR); // set root logger level to ERROR // check if root logger level is below INFO if (!xylem.isInfoEnabled()){ phloem.fwoosh(Level.INFO); // set root logger level to INFO } // The default root logger level should be DEBUG. if (!xylem.isDebugEnabled()){ phloem.fwoosh(Level.DEBUG); // set level to DEBUG } xylem.debug("Snap!"); // print DEBUG message to console xylem.info("Crackle!"); // print INFO message to console xylem.error("Pop!"); // print ERROR message to console and log file } }
Python
UTF-8
926
3.703125
4
[]
no_license
# -*- coding: utf-8 -*- """ 1365. How Many Numbers Are Smaller Than the Current Number @link https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/ """ from typing import List class Solution: def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: nums_copy = nums.copy() nums_copy.sort() nums_sort_dict = {} count = 0 for i in range(0, len(nums_copy)): if nums_sort_dict.get(nums_copy[i]) is None: nums_sort_dict[nums_copy[i]] = count count += 1 result = [] for num in nums: result.append(nums_sort_dict.get(num)) return result if __name__ == '__main__': print(Solution().smallerNumbersThanCurrent(nums=[8, 1, 2, 2, 3])) print(Solution().smallerNumbersThanCurrent(nums=[6, 5, 4, 8])) print(Solution().smallerNumbersThanCurrent(nums=[7, 7, 7, 7]))
Java
UTF-8
332
1.601563
2
[]
no_license
package com.sweb.bestlunch.restaurantservice.restaurant; import com.sweb.bestlunch.restaurantservice.restaurant.Restaurant; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface RestaurantRepository extends JpaRepository<Restaurant, Long> { }
JavaScript
UTF-8
249
2.8125
3
[]
no_license
asyncFunc(cb, cb, cb); function asyncFunc (running, done,hi) { for (var i = 0;i<10;i++) { running('i = ' + i); } done('done'); for (var j = 0;j<4;j++) { hi('j = ' + j); } } function cb (str) { console.log(str); }
Shell
UTF-8
812
3.15625
3
[]
no_license
#!/bin/bash #Mini challenge for lab 4 #Question 1 input: Cats eat 5 billion birds a year #Output: 5 billion? 5 billion! echo "Cats eat 5 billion birds a year" | sed 's/\(Cats eat\) \(5 billion\) \(birds a year\)/\2? \2!/' #Question 2 input: 12345abcde678910fghij #output:abcdefghij12345678910 echo "12345abcde678910fghij" | sed 's/\(12345\)\([a-e]*\)\(678910\)\([f-j]*\)/\2\4\1\3/' #Q3 Input 12345abcde678910fghij #Output ab cd ef gh ij 12 34 56 78 91 0 echo "12345abcde678910fghij" | sed 's/\([0-9]*\)\([a-e]*\)\([0-9]*\)\([f-j]*\)/\2\4\1\3/' | sed 's/\(..\)/\1\t/g' #the /g ensures that all pairs of characters will be included as oppsed to just the first occurence #Q4 input:12345abcde678910fghij #output: ab cd ef gh ij echo "12345abcde678910fghij" | sed 's/\([0-9]*\)//g' | sed 's/\(..\)/\1\t/g'
C++
UTF-8
8,206
2.796875
3
[ "MIT", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
/****************************************************************************** * * Author: Milos Stojanovic Stojke (milsto) * Adapted by Kevin Huynh from DifferentialEvolution.h from milsto's Github repo, * https://github.com/milsto/differential-evolution, permission granted by * milsto/differential-evolution's MIT license. * * SPDX-License-Identifier: (MIT) * *****************************************************************************/ // Description: Implementation for the differential evolution algorithm. // The implemented differential evolution algorithm is derived from // Storn, R., Price, K. Differential Evolution – A Simple and // Efficient Heuristic for global Optimization over Continuous // Spaces. Journal of Global Optimization 11, 341–359 (1997). // https://doi.org/10.1023/A:1008202821328 #ifndef included_DifferentialEvolution_h #define included_DifferentialEvolution_h #include <vector> #include <functional> #include <random> #include <utility> #include <memory> #include <limits> namespace CAROM { /** * Class IOptimizable is a simple interface for defining the constrained optimization problem. */ class IOptimizable { public: /** * @brief Constraints to be fulfilled by the variable candidates. */ struct Constraints { /** * @brief Constructor. * * @param[in] lower Lower bound for constraint * @param[in] upper Upper bound for constraint * @param[in] isConstrained Whether to check the constraints */ Constraints(double lower = 0.0, double upper = 1.0, bool isConstrained = false) : lower(lower), upper(upper), isConstrained(isConstrained) { } /** * @brief Check whether the current variable candidate fulfills the constraints. */ bool Check(double candidate) { if (isConstrained) { if (candidate <= upper && candidate >= lower) { return true; } else { return false; } } else { return true; } } /** * @brief Lower bound for constraint */ double lower; /** * @brief Upper bound for constraint */ double upper; /** * @brief Whether to check the constraints */ bool isConstrained; }; /** * @brief Evaluate the cost function with the current set of inputs. */ virtual double EvaluateCost(std::vector<double> inputs) const = 0; /** * @brief Return the number of parameters. */ virtual unsigned int NumberOfParameters() const = 0; /** * @brief Return the list of constraints. */ virtual std::vector<Constraints> GetConstraints() const = 0; /** * @brief Destructor. */ virtual ~IOptimizable() {} }; /** * Class DifferentialEvolution is a general purpose black box optimizer for the class IOptimizable. */ class DifferentialEvolution { public: /** * @brief Constructor. * * @param[in] costFunction Cost function to minimize * @param[in] populationSize Number of agents in each optimization step * @param[in] F The differential weight. * @param[in] CR The crossover probability. * @param[in] randomSeed Set random seed to a fix value to have * repeatable (non stochastic) experiments * @param[in] shouldCheckConstraints Should constraints be checked on for each new candidate. * This check may be turned off to * increase performance if the cost function is defined * and has no local minimum outside of the constraints. * @param[in] callback Optional callback to be called after each optimization * iteration has finished. * @param[in] terminationCondition Optional termination condition callback to be called * after each optimization iteration has finished. */ DifferentialEvolution(const IOptimizable& costFunction, unsigned int populationSize, double F = 0.8, double CR = 0.9, int randomSeed = 1, bool shouldCheckConstraints = true, std::function<void(const DifferentialEvolution&)> callback = nullptr, std::function<bool(const DifferentialEvolution&)> terminationCondition = nullptr); /** * @brief Constructor. * * @param[in] min_iterations The minimum number of iterations to run. * Cost tolerance is not checked until then. * @param[in] max_iterations The maximum number of iterations to run. * @param[in] cost_tolerance The cost tolerance to determine convergence. * @param[in] verbose Verbosity. */ std::vector<double> Optimize(int min_iterations, int max_iterations, double cost_tolerance, bool verbose = true); private: /** * @brief Check that the agent meets the constraints. */ bool CheckConstraints(std::vector<double> agent); /** * @brief Initialize the population at the first iteration. */ void InitPopulation(); /** * @brief Select and cross agents during each iteration. */ void SelectionAndCrossing(); /** * @brief Get current best agent. */ std::vector<double> GetBestAgent() const; /** * @brief Get current best cost. */ double GetBestCost() const; /** * @brief Get population and its associated cost. */ std::vector<std::pair<std::vector<double>, double>> GetPopulationWithCosts() const; /** * @brief Print population information. */ void PrintPopulation() const; /** * @brief Cost function */ const IOptimizable& m_cost; /** * @brief Population size */ unsigned int m_populationSize; /** * @brief Differential weight */ double m_F; /** * @brief Crossover probability */ double m_CR; /** * @brief Number of parameters */ unsigned int m_numberOfParameters; /** * @brief Whether to check constraints. */ bool m_shouldCheckConstraints; /** * @brief Optional callback function. */ std::function<void(const DifferentialEvolution&)> m_callback; /** * @brief Optional termination condition callback function. */ std::function<bool(const DifferentialEvolution&)> m_terminationCondition; /** * @brief Random number generator */ std::default_random_engine m_generator; /** * @brief Container holding populations */ std::vector<std::vector<double>> m_population; /** * @brief Container holding minimum cost per agent */ std::vector<double> m_minCostPerAgent; /** * @brief Container holding constraints */ std::vector<IOptimizable::Constraints> m_constraints; /** * @brief Index of the current best agent */ int m_bestAgentIndex; /** * @brief Current minimum cost */ double m_minCost; /** * @brief Lower and upper constraint limits */ static constexpr double g_defaultLowerConstraint = -std::numeric_limits<double>::infinity(); static constexpr double g_defaultUpperConstraint = std::numeric_limits<double>::infinity(); /** * @brief The rank of the process this object belongs to. */ int d_rank; }; } #endif
Java
UTF-8
154
1.6875
2
[]
no_license
package letters.content; /** * Class representing a content of a letter. * * @author CHARNEUX Dimitri & MOEVI Alexandre * */ public interface Content { }
Python
UTF-8
2,164
2.6875
3
[]
no_license
# -*- coding: utf-8 -*- import threading import functools import traceback from . import lock EMPTY = [] class Promise(object): @lock.init_synchronize def __init__(self, f): self.func = f self.__next = None self.__onerror = None self.__thread = None self.__value = EMPTY self.__error = EMPTY @lock.synchronizemethod def __set_value(self, value): if self.__value is EMPTY: self.__value = value self.__run_next() @lock.synchronizemethod def __set_error(self, err): if self.__error is EMPTY: self.__error = err self.__run_onerror() @lock.synchronizemethod def __run_next(self): if self.__value is not EMPTY and self.__next is not None: self.__next.run(self.__value) @lock.synchronizemethod def __run_onerror(self): if self.__error is not EMPTY: if self.__onerror is not None: self.__onerror.run(self.__error) else: traceback.print_exc() def __run(self, *argl, **argd): try: ret = self.func(*argl, **argd) self.__set_value(ret) except KeyboardInterrupt: pass except StopIteration: pass except Exception, e: self.__set_error(e) @lock.synchronizemethod def run(self, *argl, **argd): if self.__thread is None: self.__thread = threading.Thread(target=self.__run, args=argl, kwargs=argd) self.__thread.start() @lock.synchronizemethod def then(self, handle, error=None): if self.__next is None: self.__next = Promise(handle) if self.__onerror is None and error is not None: self.__onerror = Promise(error) self.__run_next() self.__run_onerror() return self.__next def promise(func, *argl, **argd): p = Promise(func) p.run(*argl, **argd) return p def promisize(f): @functools.wraps(f) def promisized(*args, **argd): return promise(f, *args, **argd) return promisized
PHP
UTF-8
167
2.609375
3
[]
no_license
<?php require 'connect.php'; $query = 'INSERT INTO individual VALUES(10, "George", "Kelman", "1972-04-12")'; $result = $db->query($query); print("\nRow inserted!");
Python
UTF-8
521
3.328125
3
[]
no_license
f = open("jolts.txt") joltageRat = [] for line in f: line = int(line) joltageRat.append(line) joltageRat.sort() diffCounts = {1:0,2:0,3:1} lng = len(joltageRat) prevNum = 0 i = 0 while i < lng: diff = joltageRat[i]-prevNum #print(diff) diffCounts[diff] = diffCounts.get(diff)+1 prevNum = joltageRat[i] i+=1 print(diffCounts) answer = diffCounts[1] * diffCounts[3] print("The product of the number of 1 differences and the number of 3 differences is",answer)
Python
UTF-8
574
3.625
4
[]
no_license
def disp(matrix): for i in matrix: print(i) print("----------") image =[[1 , 1, 0] , [0 , 1, 0] , [1 , 1 , 1]] disp(image) def floodfill(grid , r , c , newCol , oldCol): if r>=len(grid) or r<0 or c>=len(grid[0]) or c<0: return if grid[r][c] in [0 , newCol]: return if grid[r][c] == oldCol: grid[r][c] = newCol x_path = [1 , -1 , 0 , 0] y_path = [0 , 0 , 1 , -1] for i in range(len(x_path)): floodfill(grid , r+x_path[i] , c+y_path[i] , newCol , oldCol) floodfill(image , 0 , 0 , 2 , 1) disp(image)
Java
UTF-8
1,298
2.125
2
[]
no_license
package dev.sanero.services; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import dev.sanero.dao.CustomerDAO; import dev.sanero.entities.Customer; import dev.sanero.utils.User; @Service public class CustomerService { @Autowired CustomerDAO customerDAO; public boolean checkUsernameExist(String username) { return customerDAO.checkUsernameExist(username); } public boolean checkLogin(User user) { return customerDAO.checkLogin(user); } public User getUserInfoByUsername(String username) { return customerDAO.getUserInfoByUsername(username); } public int getIdByUsername(String username) { return customerDAO.getIdByUsername(username); } public long getCustomerCount() { return customerDAO.getCustomerCount(); } public List<Customer> getListCustomerByPage(int page, int pageSize) { return customerDAO.getListCustomerByPage(page, pageSize); } public boolean delete(int id) { return customerDAO.delete(id); } public boolean insert(Customer customer) { return customerDAO.insert(customer); } public Customer getCustomerById(int id) { return customerDAO.getCustomerById(id); } public boolean update(Customer customer) { return customerDAO.update(customer); } }
Markdown
UTF-8
933
2.71875
3
[ "MIT" ]
permissive
--- layout: post title: "Palabras encadenadas" tags: [linguistica] categories: [ninos, actividad] author: monse image: /assets/posts/2020-07-21-palabras.jpeg hidden: true --- ![Actividad de palabras](/assets/posts/2020-07-21-palabras.jpeg)<br/> Desarrollar la habilidad lingüística en todo momento es importante, sobre todo si es con juegos divertidos en familia. ## Materiales - No se requiere de ningún material. ## Instrucciones 1. Se colocarán en círculo. 2. El primer participante dirá una palabra, el que sigue tendrá que decir otra palabra que empiece con la última letra que dijo la persona anterior, ejemplo, carro, el siguiente dirá oso, el siguiente Omar, y así sucesivamente. 3. Pueden ser palabras de algún tema en general o no. ## Beneficios Esta dinámica los ayudará a ampliar su vocabulario y a pensar en palabras para seguir con el juego, además de desarrollar su habilidad lingüística.
Java
UTF-8
1,255
3.40625
3
[]
no_license
package StackPriorityQueue.NO347TopKFrequentElements; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.PriorityQueue; /** * @author zzj * @version 1.0 * @date 2020/12/23 13:37 * @description --------------堆只维护前K个元素 注意堆操作 从堆顶弹出元素是O(1) 插入元素是O(lgn) */ public class SolutionII { public int[] topKFrequent(int[] nums, int k) { Map<Integer, Integer> nToC = new HashMap<>(); for (int n : nums) { nToC.put(n, nToC.getOrDefault(n, 0) + 1); } PriorityQueue<Integer> q = new PriorityQueue<>(Comparator.comparingInt(nToC::get)); for (int n : nToC.keySet()) { if (q.size() < k) { q.add(n); } else { if (nToC.get(n) > nToC.get(q.peek())) { //O(logk)复杂度 因为是将尾部元素放在堆顶重新调整堆 保证堆数组不会出现空缺位 q.poll(); //O(logk)的复杂度 q.add(n); } } } int[] res = new int[k]; for (int i = 0; i < k; i++) { res[i] = q.poll(); } return res; } }
C#
UTF-8
493
2.75
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MusicPlayer { public class Album { public byte[] Thumbnail; public string Name; public int Year; public Album() { this.Name = "NoName"; this.Year = DateTime.Now.Year; } public override string ToString() { return this.Name; } } }
Java
UTF-8
2,965
2.65625
3
[]
no_license
package util.api.token; import java.util.Calendar; import java.util.Date; import org.joda.time.DateTime; import io.jsonwebtoken.ExpiredJwtException; import io.jsonwebtoken.JwtBuilder; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import models.general.Usuario; import play.Play; /** * Created by thiagoaos on 24/05/2016. */ public class ApiToken { private ApiToken() { throw new IllegalAccessError("Utility class"); } /** * Gera um token, no formato JWT, com base nas informações passadas. * Este vai ser utilizado para identificar um usuário. * * @param user objeto usuário contendo as informações utilizadas para gerar o token * @return Token no formato como string utilizando o padrão JWT */ public static String generate(Usuario user) { return generate(user, null); } /** * Assinatura detalhada para gerar um token. * Aceita um horário de criação do token * * @param tokenTime dia e horário que o token vai ser gerado */ public static String generate(Usuario user, DateTime tokenTime) { if (tokenTime == null) { tokenTime = new DateTime(); } JwtBuilder builder = Jwts.builder().setIssuedAt(tokenTime.toDate()) .setSubject(user.getId().toString()).claim("name", user.getNome()) .setIssuer(Play.configuration.getProperty("application.prettyName")) .signWith(SignatureAlgorithm.HS512, Play.configuration.getProperty("application.apisecret")); int timeToExpiration = Integer.parseInt(Play.configuration.getProperty("application.timeToExpiration")); builder.setExpiration(tokenTime.plusMinutes(timeToExpiration).toDate()); return builder.compact(); } public static void validateToken(String token)throws ExpiredJwtException{ Jwts.parser().setSigningKey(Play.configuration.getProperty("application.apisecret")).parseClaimsJws(token); } public static String updateToken(String token, Integer duracaoApiTokenDia)throws Exception{ Long id = Long.parseLong(Jwts.parser().setSigningKey(Play.configuration.getProperty("application.apisecret")).parseClaimsJws(token).getBody().getSubject()); DateTime tokenTime = new DateTime(); Usuario usuario = Usuario.find(" id = ? ", id).first(); if (usuario != null){ JwtBuilder builder = Jwts.builder().setIssuedAt(tokenTime.toDate()) .setSubject(usuario.id.toString()).claim("name", usuario.getNome()) .setIssuer(Play.configuration.getProperty("application.prettyName")) .signWith(SignatureAlgorithm.HS512, Play.configuration.getProperty("application.apisecret")); Calendar c = Calendar.getInstance(); c.add(Calendar.DAY_OF_YEAR, duracaoApiTokenDia); Date dataExpiracao = new Date(c.getTimeInMillis()); builder.setExpiration(dataExpiracao); return builder.compact(); } throw new Exception("Acesso negado."); } }
C
UTF-8
342
3.125
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> struct TreeNode{ int val; struct TreeNode *left; struct TreeNode *right; }; void firstTree(struct TreeNode *T){ if (T == NULL){ return; } printf("%d", T->val); firstTree(T->left); firstTree(T->right); } void NodeTest(){ struct TreeNode* T; firstTree(*T); }
C
UTF-8
253
2.96875
3
[]
no_license
#include <stdio.h> #include "activate_bit.h" int main(void) { int num = 17; int *ptr = &num; int pos = 12; int altered = activate_bit(ptr, pos); printf("\naltered = %d\n", altered); printf("\nresult = %d:0x%x\n", *ptr, *ptr); return 0; }
Markdown
UTF-8
6,710
2.75
3
[]
no_license
<p></p> ## Introducing: The ELK stack It will take some time to fetch and build the containers (containers are briefly explained below) needed to get the ELK stack up and running. Therefore, the next commands will clone the stack and invoke `docker-compose` (also explained below) to let it set up while you read the information about ELK as the stack is initializing. First, go back to the first terminal tab, and stop the base application (<kbd>Ctrl</kbd>+<kbd>C</kbd>) if it is still running. This will speed up the process of building the containers. Then, go back to `Terminal 2` (we will use `Terminal` when we want to run the base application, and `Terminal 2` to run the ELK stack), and make sure you are in the `/root`-folder. This is done because the tutorial assumes both `gs-serving-web-content` and `docker-elk` are in the `/root` folder. `cd /root`{{execute T2}} Next, clone the repo, enter the new folder, and invoke `docker-compose` to build the containers. `git clone https://github.com/deviantony/docker-elk.git`{{execute T2}} `cd docker-elk`{{execute T2}} `docker-compose up --no-start`{{execute T2}} <details> <summary>Containers and docker-compose</summary> <div style="display: block; margin-left: 10px; margin-right: 10px; background-color: aliceblue; padding: 1em;"> A <i>container</i> consists of an application and everything that application needs to run, in terms of dependencies, needed system configurations, and so on. Containerization is a useful way of shipping software to make sure it can be run anywhere, assuming software capable of running the containers is available.</br> </br> In this tutorial, we are using <code>docker-compose</code> (pre-installed in our Katacoda environment) to start three containers: one containing Elasticsearch, one containing Logstash, and one containing Kibana. The <code>--no-start</code>-flag passed to <code>docker-compose</code> is used to make it build the containers without starting them (we will want to make some configurations before we start).</br> </br> You can read more about <code>docker-compose</code> <a href="https://docs.docker.com/compose/reference/">here</a> (and specifically about <code>docker-compose up</code> <a href="https://docs.docker.com/compose/reference/up/">here</a>). </div> </details> There are various ways to run the ELK stack. You can: * [install](https://www.elastic.co/downloads/) the tools separately and configure them yourself * use the [hosted ELK service](https://www.elastic.co/cloud/elasticsearch-service/signup?baymax=rtp&storm=whatis-all&elektra=whatis-elkstack) * run a containerized version where everything is "connected" already For simplicity's sake, we have chosen the third option by using a Github repository (the `docker-elk` repo you cloned above) that already contains the needed software and configurations. This will allow us to set up the stack quickly and actually focus on using its features. ## Why log management? At this point, it might be good to motivate why we even need log management tools like the ELK stack. The answer is that these tools are highly useful whenever searching and aggregating log data from applications is of interest. This can provide useful insights for managing an application by e.g. showing where crashes are most likely to occur, or showing how users are interacting with your application. Without log management tools like the ELK stack, the process of writing custom scripts to scan extensive log outputs of large applications can be daunting. This task is further complicated in the setting of distributed applications (i.e. applications running on several computers, connected via a network) where logs end up in different places. This is especially the case for applications that are implemented using the *microservices architecture*, given their distributed nature (and tendency to have services implemented in many different languages and frameworks). ## A closer look at the ELK stack <!-- As mentioned, the ELK stack consists of Elasticsearch, Logstash, and Kibana. In the coming steps, we will: * use Logstash to: * pull log messages from our `spring.log` file * parse the messages to tag different parts of them (timestamps, log-levels, pid, actual message, etc.) * send the data to Elasticsearch * use Elasticsearch as a data repository containing the data it received from Logstash * use Kibana ... testar en annan approach här nere: --> As mentioned, the ELK stack consists of Elasticsearch, Logstash, and Kibana. In the coming steps, we will use Logstash to pull log messages from our `spring.log` file. Then, we'll configure Logstash to parse the messages and tag different parts of them (timestamps, log-levels, pid, actual message, etc.). Finally, Logstash will send the data to Elasticsearch. We will not have to change any configurations having to do with Elasticsearch; it will simply store the data Logstash sends to it. Finally, we will use Kibana to access the Logstash-data contained in Elasticsearch. <!-- * sen fokus på ELK stack: * beskriva hur logstash tar in från olika ställen, utför transformationer, skickar till olika ställen, och koppla detta till logstash.conf-filen vi kommer ändra på senare, nämn ordet 'plugins' * beskriva hur elasticsearch index funkar? jag vet inte detta själv * beskriv hur Kibana låter en "browse elasticsearch data" och "use it to craft data visualizations" eller liknande * borde antagligen nämna "Elastic stack" och att Beats finns. dels tycker jag det är schysst mot användaren, som kanske vill forska om egna saker, dels visar det att vi har förståelse för att det vi använder inte är "den allra senaste iterationen" (så att säga) av stacken, och dels behöver vi inte vifta bort det faktum att det finns en 'beats-plugin' i logstash-konfigurationen från docker-elk repot ^^^ Oklart hur mycket av det här som vi vill nämna redan här. Kanske sparar vi tid på att bara skriva om det när det faktiskt dyker upp i kommande steg. --> <!-- ## Difference between ELK stack and Elastic stack Skriv kort om historiken, hänvisa till denna länk: https://www.elastic.co/what-is/elk-stack --> ## Moving on with the tutorial By now, the command you executed at the top should hopefully have completed. When it has, you will see the following in the terminal: ``` Creating docker-elk_elasticsearch_1 ... done Creating docker-elk_kibana_1 ... done Creating docker-elk_logstash_1 ... done ``` Since it takes some time to start the containers (remember, we've only *built* them so far), we will take care of the configuration first. In the next step, we will start by configuring Logstash.
C++
UTF-8
1,824
3.421875
3
[]
no_license
#include <iostream> #include "GameEngine.h" #include "ConsoleHelpers.h" using namespace std; using namespace GameEngine; using namespace ConsoleHelpers; void showMainMenu(); void playGame(); void showRules(); int main() { showMainMenu(); return 0; } void showMainMenu() { int userChoice = 0; do { clearScreen(); cout << "Welcome in Blackjack game!" << endl << endl; cout << "[1] Play game" << endl; cout << "[2] Rules" << endl; cout << "[3] Exit" << endl; cout << endl << endl; userChoice = askUserForInt("Choose option"); switch (userChoice) { case 1: playGame(); break; case 2: showRules(); break; case 3: break; default: break; } } while (userChoice != 3); } void playGame() { auto playerName = askUserForStringInput("Enter your name"); auto player = Player(playerName); auto* playerPtr = &player; int decksNo = 0; do { decksNo = askUserForInt("How many deck you want to play with? [max 6 decks]"); } while (decksNo < 1 && decksNo > 6); clearScreen(); startGame(playerPtr, decksNo); } void showRules() { clearScreen(); cout << "Rules: " << endl << endl; cout << "1) The goal of blackjack is to beat the dealer's hand without going over 21." << endl; cout << "2) Face cards are worth 10. Aces are worth 1 or 11, whichever makes a better hand." << endl; cout << "3) Each player starts with two cards." << endl; cout << "4) To 'Hit' is to ask for another card." << endl; cout << "5) If you go over 21 you bust, and the dealer wins regardless of the dealer's hand." << endl; cout << "6) If you are dealt 21 from the start (Ace & 10), you got a blackjack." << endl; cout << "7) Blackjack means you win 1.5 the amount of your bet." << endl; cout << "8) Dealer will hit until his/her cards total 17 or higher." << endl; system("pause"); }
Markdown
UTF-8
1,720
3.265625
3
[ "MIT" ]
permissive
### Useful links! These are all awesome resources I've used for you to poke around for more TypeScript resources / something more useful than this cookbook. *** | Title | Description | Link | | ------------- | -------------| ----- | | Ray Toal's TypeScript Notes | My mentor for this TypeScript foray and all-around awesome university professor at LMU! As a plus he *loves* programming languages so you can tell these notes are going to be great.| [http://cs.lmu.edu/~ray/notes/introtypescript/](http://cs.lmu.edu/~ray/notes/introtypescript/) | | Official TypeScript Documentation| Sometimes all you want is information straight from the creators themselves. | [https://www.typescriptlang.org/docs/home.html](https://www.typescriptlang.org/docs/home.html)| | Marius Schluz's Blog on New TypeScript Features | Concise posts about new and useful features in TypeScript. Gives a lot of practical examples as well.| [https://blog.mariusschulz.com/](https://blog.mariusschulz.com/) | | Hejlsberg's What's New in TypeScript 2018 Talk | Fantastic talk on TypeScript from one of the heads of the TypeScript team himself. Gives a quick introduction, examples of using TypeScript features in production, and how they address some interesting theoretical problems.| [https://youtu.be/hDACN-BGvI8](https://youtu.be/hDACN-BGvI8) | | Eli Bendersky's Post on Type Inference | Not strictly related to TypeScript persay, but nonetheless a particularly interesting discussion of type inference systems. | [https://eli.thegreenplace.net/2018/type-inference/](https://eli.thegreenplace.net/2018/type-inference/) | | Basarat Syed's TypeScript Deep Dive | Another resource to delve deep with TypeScript! |http://basarat.gitbooks.io/typescript/ |
Python
UTF-8
39,613
2.6875
3
[ "MIT" ]
permissive
#!/usr/bin/python # -*- coding: utf-8 -*- u""" TileMap loader for python for Tiled, a generic tile map editor from http://mapeditor.org/ . It loads the \*.tmx files produced by Tiled. """ __version__ = u'$Id: tiledtmxloader.py 382 2010-07-14 18:39:21Z dr0iddr0id@gmail.com $' __author__ = u'DR0ID_ @ 2009' if __debug__: import sys sys.stdout.write(u'%s loading ... \n' % (__name__)) import time _start_time = time.time() #------------------------------------------------------------------------------- import sys from xml.dom import minidom, Node import base64 import gzip import StringIO import os.path #import codecs # TODO: ideas: save indexed_tiles as {type:data} so no image loader is needed # user would have to write its own image loading # different types would be : {gid : ('img_parts', (margin, spacing, path, tile_w, tile_h, colorkey))} # {gid : ('img_path', ('C:/...', colorkey)} # {gid : ('file_like', (file_like_obj, colorkey))} # # maybe use cStringIO instead of StringIO #------------------------------------------------------------------------------- class IImageLoader(object): u""" Interface for image loading. Depending on the framework used the images have to be loaded differently. """ def load_image(self, filename, colorkey=None): # -> image u""" Load a single image. :Parameters: filename : string Path to the file to be loaded. colorkey : tuple The (r, g, b) color that should be used as colorkey (or magic color). Default: None :rtype: image """ raise NotImplementedError(u'This should be implemented in a inherited class') def load_image_file_like(self, file_like_obj, colorkey=None): # -> image u""" Load a image from a file like object. :Parameters: file_like_obj : file This is the file like object to load the image from. colorkey : tuple The (r, g, b) color that should be used as colorkey (or magic color). Default: None :rtype: image """ raise NotImplementedError(u'This should be implemented in a inherited class') def load_image_parts(self, filename, margin, spacing, tile_width, tile_height, colorkey=None): #-> [images] u""" Load different tile images from one source image. :Parameters: filename : string Path to image to be loaded. margin : int The margin around the image. spacing : int The space between the tile images. tile_width : int The width of a single tile. tile_height : int The height of a single tile. colorkey : tuple The (r, g, b) color that should be used as colorkey (or magic color). Default: None Luckily that iteration is so easy in python:: ... w, h = image_size for y in xrange(margin, h, tile_height + spacing): for x in xrange(margin, w, tile_width + spacing): ... :rtype: a list of images """ raise NotImplementedError(u'This should be implemented in a inherited class') #------------------------------------------------------------------------------- class ImageLoaderPygame(IImageLoader): u""" Pygame image loader. It uses an internal image cache. The methods return Surface. :Undocumented: pygame """ def __init__(self): self.pygame = __import__('pygame') self._img_cache = {} # {name: surf} def load_image(self, filename, colorkey=None): img = self._img_cache.get(filename, None) if img is None: img = self.pygame.image.load(filename) self._img_cache[filename] = img if colorkey: img.set_colorkey(colorkey) return img def load_image_part(self, filename, x, y, w, h, colorkey=None): source_rect = self.pygame.Rect(x, y, w, h) img = self._img_cache.get(filename, None) if img is None: img = self.pygame.image.load(filename) self._img_cache[filename] = img img_part = self.pygame.Surface((w, h), 0, img) img_part.blit(img, (0, 0), source_rect) if colorkey: img_part.set_colorkey(colorkey) return img_part def load_image_parts(self, filename, margin, spacing, tile_width, tile_height, colorkey=None): #-> [images] source_img = self._img_cache.get(filename, None) if source_img is None: source_img = self.pygame.image.load(filename) self._img_cache[filename] = source_img w, h = source_img.get_size() images = [] for y in xrange(margin, h, tile_height + spacing): for x in xrange(margin, w, tile_width + spacing): img_part = self.pygame.Surface((tile_width, tile_height), 0, source_img) img_part.blit(source_img, (0, 0), self.pygame.Rect(x, y, tile_width, tile_height)) if colorkey: img_part.set_colorkey(colorkey) images.append(img_part) return images def load_image_file_like(self, file_like_obj, colorkey=None): # -> image # pygame.image.load can load from a path and from a file-like object # that is why here it is redirected to the other method return self.load_image(file_like_obj, colorkey) #------------------------------------------------------------------------------- class ImageLoaderPyglet(IImageLoader): u""" Pyglet image loader. It uses an internal image cache. The methods return some form of AbstractImage. The resource module is not used for loading the images. Thanks to HydroKirby from #pyglet to contribute the ImageLoaderPyglet and the pyglet demo! :Undocumented: pyglet """ def __init__(self): self.pyglet = __import__('pyglet') self._img_cache = {} # {name: image} def load_image(self, filename, colorkey=None, fileobj=None): img = self._img_cache.get(filename, None) if img is None: if fileobj: img = self.pyglet.image.load(filename, fileobj, self.pyglet.image.codecs.get_decoders("*.png")[0]) else: img = self.pyglet.image.load(filename) self._img_cache[filename] = img return img def load_image_part(self, filename, x, y, w, h, colorkey=None): img = self._img_cache.get(filename, None) if img is None: img = self.pyglet.image.load(filename) self._img_cache[filename] = img img_part = image.get_region(x, y, w, h) return img_part def load_image_parts(self, filename, margin, spacing, tile_width, tile_height, colorkey=None): #-> [images] source_img = self._img_cache.get(filename, None) if source_img is None: source_img = self.pyglet.image.load(filename) self._img_cache[filename] = source_img images = [] # Reverse the map column reading to compensate for pyglet's y-origin. for y in xrange(source_img.height - tile_height, margin - tile_height, -tile_height - spacing): for x in xrange(margin, source_img.width, tile_width + spacing): #img_part = source_img.get_region(x, y, tile_width, tile_height) img_part = source_img.get_region(x, y - spacing, tile_width, tile_height) images.append(img_part) return images def load_image_file_like(self, file_like_obj, colorkey=None): # -> image # pyglet.image.load can load from a path and from a file-like object # that is why here it is redirected to the other method return self.load_image(file_like_obj, colorkey, file_like_obj) #------------------------------------------------------------------------------- class TileMap(object): u""" The TileMap holds all the map data. :Ivariables: orientation : string orthogonal or isometric or hexagonal or shifted tilewidth : int width of the tiles (for all layers) tileheight : int height of the tiles (for all layers) width : int width of the map (number of tiles) height : int height of the map (number of tiles) version : string version of the map format tile_sets : list list of TileSet properties : dict the propertis set in the editor, name-value pairs, strings pixel_width : int width of the map in pixels pixel_height : int height of the map in pixels layers : list list of TileLayer map_file_name : dict file name of the map object_groups : list list of :class:MapObjectGroup indexed_tiles : dict dict containing {gid : (offsetx, offsety, surface} if load() was called when drawing just add the offset values to the draw point named_layers : dict of string:TledLayer dict containing {name : TileLayer} named_tile_sets : dict dict containing {name : TileSet} """ def __init__(self): # This is the top container for all data. The gid is the global id (for a image). # Before calling convert most of the values are strings. Some additional # values are also calculated, see convert() for details. After calling # convert, most values are integers or floats where appropriat. u""" The TileMap holds all the map data. """ # set through parser self.orientation = None self.tileheight = 0 self.tilewidth = 0 self.width = 0 self.height = 0 self.version = 0 self.tile_sets = [] # TileSet self.layers = [] # WorldTileLayer <- what order? back to front (guessed) self.indexed_tiles = {} # {gid: (offsetx, offsety, image} self.object_groups = [] self.properties = {} # {name: value} # additional info self.pixel_width = 0 self.pixel_height = 0 self.named_layers = {} # {name: layer} self.named_tile_sets = {} # {name: tile_set} self.map_file_name = "" self._image_loader = None def convert(self): u""" Converts numerical values from strings to numerical values. It also calculates or set additional data: pixel_width pixel_height named_layers named_tile_sets """ self.tilewidth = int(self.tilewidth) self.tileheight = int(self.tileheight) self.width = int(self.width) self.height = int(self.height) self.pixel_width = self.width * self.tilewidth self.pixel_height = self.height * self.tileheight for layer in self.layers: self.named_layers[layer.name] = layer layer.opacity = float(layer.opacity) layer.x = int(layer.x) layer.y = int(layer.y) layer.width = int(layer.width) layer.height = int(layer.height) layer.pixel_width = layer.width * self.tilewidth layer.pixel_height = layer.height * self.tileheight layer.visible = bool(int(layer.visible)) for tile_set in self.tile_sets: self.named_tile_sets[tile_set.name] = tile_set tile_set.spacing = int(tile_set.spacing) tile_set.margin = int(tile_set.margin) for img in tile_set.images: if img.trans: img.trans = (int(img.trans[:2], 16), int(img.trans[2:4], 16), int(img.trans[4:], 16)) for obj_group in self.object_groups: obj_group.x = int(obj_group.x) obj_group.y = int(obj_group.y) obj_group.width = int(obj_group.width) obj_group.height = int(obj_group.height) for map_obj in obj_group.objects: map_obj.x = int(map_obj.x) map_obj.y = int(map_obj.y) map_obj.width = int(map_obj.width) map_obj.height = int(map_obj.height) def load(self, image_loader): u""" loads all images using a IImageLoadermage implementation and fills up the indexed_tiles dictionary. The image may have per pixel alpha or a colorkey set. """ self._image_loader = image_loader for tile_set in self.tile_sets: # do images first, because tiles could reference it for img in tile_set.images: if img.source: self._load_image_from_source(tile_set, img) else: tile_set.indexed_images[img.id] = self._load_image(img) # tiles for tile in tile_set.tiles: for img in tile.images: if not img.content and not img.source: # only image id set indexed_img = tile_set.indexed_images[img.id] self.indexed_tiles[int(tile_set.firstgid) + int(tile.id)] = (0, 0, indexed_img) else: if img.source: self._load_image_from_source(tile_set, img) else: indexed_img = self._load_image(img) self.indexed_tiles[int(tile_set.firstgid) + int(tile.id)] = (0, 0, indexed_img) def _load_image_from_source(self, tile_set, a_tile_image): # relative path to file img_path = os.path.join(os.path.dirname(self.map_file_name), a_tile_image.source) tile_width = int(self.tilewidth) tile_height = int(self.tileheight) if tile_set.tileheight: tile_width = int(tile_set.tilewidth) if tile_set.tilewidth: tile_height = int(tile_set.tileheight) offsetx = 0 offsety = 0 # if tile_width > self.tilewidth: # offsetx = tile_width if tile_height > self.tileheight: offsety = tile_height - self.tileheight idx = 0 for image in self._image_loader.load_image_parts(img_path, \ tile_set.margin, tile_set.spacing, tile_width, tile_height, a_tile_image.trans): self.indexed_tiles[int(tile_set.firstgid) + idx] = (offsetx, -offsety, image) idx += 1 def _load_image(self, a_tile_image): img_str = a_tile_image.content if a_tile_image.encoding: if a_tile_image.encoding == u'base64': img_str = decode_base64(a_tile_image.content) else: raise Exception(u'unknown image encoding %s' % a_tile_image.encoding) sio = StringIO.StringIO(img_str) new_image = self._image_loader.load_image_file_like(sio, a_tile_image.trans) return new_image def decode(self): u""" Decodes the TileLayer encoded_content and saves it in decoded_content. """ for layer in self.layers: layer.decode() #------------------------------------------------------------------------------- class TileSet(object): u""" A tileset holds the tiles and its images. :Ivariables: firstgid : int the first gid of this tileset name : string the name of this TileSet images : list list of TileImages tiles : list list of Tiles indexed_images : dict after calling load() it is dict containing id: image indexed_tiles : dict after calling load() it is a dict containing gid: (offsetx, offsety, image) , the image corresponding to the gid spacing : int the spacing between tiles marging : int the marging of the tiles properties : dict the propertis set in the editor, name-value pairs tilewidth : int the actual width of the tile, can be different from the tilewidth of the map tilehight : int the actual hight of th etile, can be different from the tilehight of the map """ def __init__(self): self.firstgid = 0 self.name = None self.images = [] # TileImage self.tiles = [] # Tile self.indexed_images = {} # {id:image} self.indexed_tiles = {} # {gid: (offsetx, offsety, image} <- actually in map data self.spacing = 0 self.margin = 0 self.properties = {} self.tileheight = 0 self.tilewidth = 0 #------------------------------------------------------------------------------- class TileImage(object): u""" An image of a tile or just an image. :Ivariables: id : int id of this image (has nothing to do with gid) format : string the format as string, only 'png' at the moment source : string filename of the image. either this is set or the content encoding : string encoding of the content trans : tuple of (r,g,b) the colorkey color, raw as hex, after calling convert just a (r,g,b) tuple properties : dict the propertis set in the editor, name-value pairs image : TileImage after calling load the pygame surface """ def __init__(self): self.id = 0 self.format = None self.source = None self.encoding = None # from <data>...</data> self.content = None # from <data>...</data> self.image = None self.trans = None self.properties = {} # {name: value} #------------------------------------------------------------------------------- class Tile(object): u""" A single tile. :Ivariables: id : int id of the tile gid = TileSet.firstgid + Tile.id images : list of :class:TileImage list of TileImage, either its 'id' or 'image data' will be set properties : dict of name:value the propertis set in the editor, name-value pairs """ def __init__(self): self.id = 0 self.images = [] # uses TileImage but either only id will be set or image data self.properties = {} # {name: value} #------------------------------------------------------------------------------- class TileLayer(object): u""" A layer of the world. :Ivariables: x : int position of layer in the world in number of tiles (not pixels) y : int position of layer in the world in number of tiles (not pixels) width : int number of tiles in x direction height : int number of tiles in y direction pixel_width : int width of layer in pixels pixel_height : int height of layer in pixels name : string name of this layer opacity : float float from 0 (full transparent) to 1.0 (opaque) decoded_content : list list of graphics id going through the map:: e.g [1, 1, 1, ] where decoded_content[0] is (0,0) decoded_content[1] is (1,0) ... decoded_content[1] is (width,0) decoded_content[1] is (0,1) ... decoded_content[1] is (width,height) usage: graphics id = decoded_content[tile_x + tile_y * width] content2D : list list of list, usage: graphics id = content2D[x][y] """ def __init__(self): self.width = 0 self.height = 0 self.x = 0 self.y = 0 self.pixel_width = 0 self.pixel_height = 0 self.name = None self.opacity = -1 self.encoding = None self.compression = None self.encoded_content = None self.decoded_content = [] self.visible = True self.properties = {} # {name: value} self.content2D = None def decode(self): u""" Converts the contents in a list of integers which are the gid of the used tiles. If necessairy it decodes and uncompresses the contents. """ s = self.encoded_content if self.encoded_content: if self.encoding: if self.encoding == u'base64': s = decode_base64(s) else: raise Exception(u'unknown data encoding %s' % (self.encoding)) if self.compression: if self.compression == u'gzip': s = decompress_gzip(s) else: raise Exception(u'unknown data compression %s' %(self.compression)) else: raise Exception(u'no encoded content to decode') self.decoded_content = [] for idx in xrange(0, len(s), 4): val = ord(str(s[idx])) | (ord(str(s[idx + 1])) << 8) | \ (ord(str(s[idx + 2])) << 16) | (ord(str(s[idx + 3])) << 24) self.decoded_content.append(val) # generate the 2D version self._gen_2D() def _gen_2D(self): self.content2D = [] # generate the needed lists for xpos in xrange(self.width): self.content2D.append([]) # fill them for xpos in xrange(self.width): for ypos in xrange(self.height): self.content2D[xpos].append(self.decoded_content[xpos + ypos * self.width]) def pretty_print(self): num = 0 for y in range(int(self.height)): s = u"" for x in range(int(self.width)): s += str(self.decoded_content[num]) num += 1 print s #------------------------------------------------------------------------------- class MapObjectGroup(object): u""" Group of objects on the map. :Ivariables: x : int the x position y : int the y position width : int width of the bounding box (usually 0, so no use) height : int height of the bounding box (usually 0, so no use) name : string name of the group objects : list list of the map objects """ def __init__(self): self.width = 0 self.height = 0 self.name = None self.objects = [] self.x = 0 self.y = 0 self.properties = {} # {name: value} #------------------------------------------------------------------------------- class MapObject(object): u""" A single object on the map. :Ivariables: x : int x position relative to group x position y : int y position relative to group y position width : int width of this object height : int height of this object type : string the type of this object image_source : string source path of the image for this object image : :class:TileImage after loading this is the pygame surface containing the image """ def __init__(self): self.name = None self.x = 0 self.y = 0 self.width = 0 self.height = 0 self.type = None self.image_source = None self.image = None self.properties = {} # {name: value} #------------------------------------------------------------------------------- def decode_base64(in_str): u""" Decodes a base64 string and returns it. :Parameters: in_str : string base64 encoded string :returns: decoded string """ return base64.decodestring(in_str) #------------------------------------------------------------------------------- def decompress_gzip(in_str): u""" Uncompresses a gzip string and returns it. :Parameters: in_str : string gzip compressed string :returns: uncompressed string """ # gzip can only handle file object therefore using StringIO copmressed_stream = StringIO.StringIO(in_str) gzipper = gzip.GzipFile(fileobj=copmressed_stream) s = gzipper.read() gzipper.close() return s #------------------------------------------------------------------------------- def printer(obj, ident=''): u""" Helper function, prints a hirarchy of objects. """ import inspect print ident + obj.__class__.__name__.upper() ident += ' ' lists = [] for name in dir(obj): elem = getattr(obj, name) if isinstance(elem, list) and name != u'decoded_content': lists.append(elem) elif not inspect.ismethod(elem): if not name.startswith('__'): if name == u'data' and elem: print ident + u'data = ' printer(elem, ident + ' ') else: print ident + u'%s\t= %s' % (name, getattr(obj, name)) for l in lists: for i in l: printer(i, ident + ' ') #------------------------------------------------------------------------------- class TileMapParser(object): u""" Allows to parse and decode map files for 'Tiled', a open source map editor written in java. It can be found here: http://mapeditor.org/ """ def _build_tile_set(self, tile_set_node, world_map): tile_set = TileSet() self._set_attributes(tile_set_node, tile_set) for node in self._get_nodes(tile_set_node.childNodes, u'image'): self._build_tile_set_image(node, tile_set) for node in self._get_nodes(tile_set_node.childNodes, u'tile'): self._build_tile_set_tile(node, tile_set) self._set_attributes(tile_set_node, tile_set) world_map.tile_sets.append(tile_set) def _build_tile_set_image(self, image_node, tile_set): image = TileImage() self._set_attributes(image_node, image) # id of TileImage has to be set!! -> Tile.TileImage will only have id set for node in self._get_nodes(image_node.childNodes, u'data'): self._set_attributes(node, image) image.content = node.childNodes[0].nodeValue tile_set.images.append(image) def _build_tile_set_tile(self, tile_set_node, tile_set): tile = Tile() self._set_attributes(tile_set_node, tile) for node in self._get_nodes(tile_set_node.childNodes, u'image'): self._build_tile_set_tile_image(node, tile) tile_set.tiles.append(tile) def _build_tile_set_tile_image(self, tile_node, tile): tile_image = TileImage() self._set_attributes(tile_node, tile_image) for node in self._get_nodes(tile_node.childNodes, u'data'): self._set_attributes(node, tile_image) tile_image.content = node.childNodes[0].nodeValue tile.images.append(tile_image) def _build_layer(self, layer_node, world_map): layer = TileLayer() self._set_attributes(layer_node, layer) for node in self._get_nodes(layer_node.childNodes, u'data'): self._set_attributes(node, layer) layer.encoded_content = node.lastChild.nodeValue world_map.layers.append(layer) def _build_world_map(self, world_node): world_map = TileMap() self._set_attributes(world_node, world_map) if world_map.version != u"1.0": raise Exception(u'this parser was made for maps of version 1.0, found version %s' % world_map.version) for node in self._get_nodes(world_node.childNodes, u'tileset'): self._build_tile_set(node, world_map) for node in self._get_nodes(world_node.childNodes, u'layer'): self._build_layer(node, world_map) for node in self._get_nodes(world_node.childNodes, u'objectgroup'): self._build_object_groups(node, world_map) return world_map def _build_object_groups(self, object_group_node, world_map): object_group = MapObjectGroup() self._set_attributes(object_group_node, object_group) for node in self._get_nodes(object_group_node.childNodes, u'object'): tiled_object = MapObject() self._set_attributes(node, tiled_object) for img_node in self._get_nodes(node.childNodes, u'image'): tiled_object.image_source = img_node.attributes[u'source'].nodeValue object_group.objects.append(tiled_object) world_map.object_groups.append(object_group) #-- helpers --# def _get_nodes(self, nodes, name): for node in nodes: if node.nodeType == Node.ELEMENT_NODE and node.nodeName == name: yield node def _set_attributes(self, node, obj): attrs = node.attributes for attr_name in attrs.keys(): setattr(obj, attr_name, attrs.get(attr_name).nodeValue) self._get_properties(node, obj) def _get_properties(self, node, obj): props = {} for properties_node in self._get_nodes(node.childNodes, u'properties'): for property_node in self._get_nodes(properties_node.childNodes, u'property'): try: props[property_node.attributes[u'name'].nodeValue] = property_node.attributes[u'value'].nodeValue except KeyError: props[property_node.attributes[u'name'].nodeValue] = property_node.lastChild.nodeValue obj.properties.update(props) #-- parsers --# def parse(self, file_name): u""" Parses the given map. Does no decoding nor loading the data. :return: instance of TileMap """ #dom = minidom.parseString(codecs.open(file_name, "r", "utf-8").read()) dom = minidom.parseString(open(file_name, "rb").read()) for node in self._get_nodes(dom.childNodes, 'map'): world_map = self._build_world_map(node) break world_map.map_file_name = os.path.abspath(file_name) world_map.convert() return world_map def parse_decode(self, file_name): u""" Parses the map but additionally decodes the data. :return: instance of TileMap """ world_map = TileMapParser().parse(file_name) world_map.decode() return world_map def parse_decode_load(self, file_name, image_loader): u""" Parses the data, decodes them and loads the images using the image_loader. :return: instance of TileMap """ world_map = self.parse_decode(file_name) world_map.load(image_loader) return world_map #------------------------------------------------------------------------------- def demo_pygame(file_name): pygame = __import__('pygame') # parser the map world_map = TileMapParser().parse_decode(file_name) # init pygame and set up a screen pygame.init() pygame.display.set_caption("tiledtmxloader - " + file_name) screen_width = min(1024, world_map.pixel_width) screen_height = min(768, world_map.pixel_height) screen = pygame.display.set_mode((screen_width, screen_height)) # load the images using pygame world_map.load(ImageLoaderPygame()) #printer(world_map) # an example on how to access the map data and draw an orthoganl map # draw the map assert world_map.orientation == "orthogonal" running = True dirty = True # cam_offset is for scrolling cam_offset_x = 0 cam_offset_y = 0 # mainloop while running: # eventhandling events = [pygame.event.wait()] events.extend(pygame.event.get()) for event in events: dirty = True if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: running = False elif event.key == pygame.K_DOWN: cam_offset_y -= world_map.tileheight elif event.key == pygame.K_UP: cam_offset_y += world_map.tileheight elif event.key == pygame.K_LEFT: cam_offset_x += world_map.tilewidth elif event.key == pygame.K_RIGHT: cam_offset_x -= world_map.tilewidth # draw the map if dirty: dirty = False for layer in world_map.layers[:]: if layer.visible: idx = 0 # loop over all tiles for ypos in xrange(0, layer.height): for xpos in xrange(0, layer.width): # add offset in number of tiles x = (xpos + layer.x) * world_map.tilewidth y = (ypos + layer.y) * world_map.tileheight # get the gid at this position img_idx = layer.content2D[xpos][ypos] idx += 1 if img_idx: # get the actual image and its offset offx, offy, screen_img = world_map.indexed_tiles[img_idx] # only draw the tiles that are relly visible (speed up) if x >= cam_offset_x - 3 * world_map.tilewidth and x + cam_offset_x <= screen_width + world_map.tilewidth\ and y >= cam_offset_y - 3 * world_map.tileheight and y + cam_offset_y <= screen_height + 3 * world_map.tileheight: if screen_img.get_alpha(): screen_img = screen_img.convert_alpha() else: screen_img = screen_img.convert() if layer.opacity > -1: #print 'per surf alpha', layer.opacity screen_img.set_alpha(None) alpha_value = int(255. * float(layer.opacity)) screen_img.set_alpha(alpha_value) screen_img = screen_img.convert_alpha() # draw image at right position using its offset screen.blit(screen_img, (x + cam_offset_x + offx, y + cam_offset_y + offy)) # map objects for obj_group in world_map.object_groups: goffx = obj_group.x goffy = obj_group.y if goffx >= cam_offset_x - 3 * world_map.tilewidth and goffx + cam_offset_x <= screen_width + world_map.tilewidth \ and goffy >= cam_offset_y - 3 * world_map.tileheight and goffy + cam_offset_y <= screen_height + 3 * world_map.tileheight: for map_obj in obj_group.objects: size = (map_obj.width, map_obj.height) if map_obj.image_source: surf = pygame.image.load(map_obj.image_source) surf = pygame.transform.scale(surf, size) screen.blit(surf, (goffx + map_obj.x + cam_offset_x, goffy + map_obj.y + cam_offset_y)) else: r = pygame.Rect((goffx + map_obj.x + cam_offset_x, goffy + map_obj.y + cam_offset_y), size) pygame.draw.rect(screen, (255, 255, 0), r, 1) # simple pygame pygame.display.flip() #------------------------------------------------------------------------------- def demo_pyglet(file_name): """Loads and views a map using pyglet. Holding the arrow keys will scroll along the map. Holding the left shift key will make you scroll faster. Pressing the escape key ends the application. """ import pyglet from pyglet.gl import glTranslatef, glLoadIdentity world_map = TileMapParser().parse_decode(file_name) # delta is the x/y position of the map view. # delta is a list because the scoping is different for immutable types. # This list can be used within the update method. delta = [0.0, 0.0] window = pyglet.window.Window() @window.event def on_draw(): window.clear() # Reset the "eye" back to the default location. glLoadIdentity() # Move the "eye" to the current location on the map. glTranslatef(delta[0], delta[1], 0.0) batch.draw() keys = pyglet.window.key.KeyStateHandler() window.push_handlers(keys) world_map.load(ImageLoaderPyglet()) def update(dt): speed = 3.0 + keys[pyglet.window.key.LSHIFT] * 6.0 if keys[pyglet.window.key.LEFT]: delta[0] += speed if keys[pyglet.window.key.RIGHT]: delta[0] -= speed if keys[pyglet.window.key.UP]: delta[1] -= speed if keys[pyglet.window.key.DOWN]: delta[1] += speed # Generate the graphics for every visible tile. batch = pyglet.graphics.Batch() groups = [] sprites = [] for group_num, layer in enumerate(world_map.layers[:]): if layer.visible is False: continue groups.append(pyglet.graphics.OrderedGroup(group_num)) for xtile in range(layer.width): for ytile in range(layer.height): image_id = layer.content2D[xtile][ytile] if image_id: # o_x and o_y are offsets. They are not helpful here. o_x, o_y, image_file = world_map.indexed_tiles[image_id] # To compensate for pyglet's upside-down y-axis, the # Sprites are placed in rows that are backwards compared # to what was loaded into the map. The "max - current" # formula does this reversal. sprites.append(pyglet.sprite.Sprite(image_file, xtile * world_map.tilewidth, layer.pixel_height - (ytile+1) * world_map.tileheight, batch=batch, group=groups[group_num])) pyglet.clock.schedule_interval(update, 1.0 / 60.0) pyglet.app.run() #------------------------------------------------------------------------------- def main(): args = sys.argv[1:] if len(args) != 2: #print 'usage: python test.py mapfile.tmx [pygame|pyglet]' print('usage: python %s your_map.tmx [pygame|pyglet]' % \ os.path.basename(__file__)) return if args[1] == 'pygame': demo_pygame(args[0]) elif args[1] == 'pyglet': demo_pyglet(args[0]) else: print 'missing framework, usage: python test.py mapfile.tmx [pygame|pyglet]' sys.exit(-1) #------------------------------------------------------------------------------- if __name__ == '__main__': main() if __debug__: _dt = time.time() - _start_time sys.stdout.write(u'%s loaded: %fs \n' % (__name__, _dt))
Markdown
UTF-8
789
3
3
[]
no_license
### 无数据展示组件 <div style='width:475px;height: 375px;position: relative; border: 1px solid #eee;border-radius: 8px;'> <div id="blankComm"></div> </div> <script type="text/javascript" defer> window.BlankComm.$mount('#blankComm') </script> ### 案例 ```html <div style=''> <div id="blankComm"></div> </div> ``` ```javascript const Blank = Vue.extend({ components: { blank }, render(h) { return <blank text="目前本班级没有在读学员哦~"></blank>; }, }); ``` ### 使用场景 ### 属性 <div class="markdown-grid"> | 名称 | 类型 | 描述 |默认值 | :-------- | :-------- | :-- |:-- | text | String | 文字展示 | 无
Java
UTF-8
434
2.515625
3
[ "MIT" ]
permissive
package mediator; /** * */ public abstract class AbstractCourt { /** * * @param startTime 球场开始使用的时间 */ public abstract void changeStartTime(String startTime); /** * * @param court 需要借用设备的球场 */ public abstract void borrow(String court); /** * 出借设备的球场 * @param court */ public abstract void lend(String court); }
Java
UTF-8
724
2.15625
2
[]
no_license
package com.qiheng.service.impl; import java.util.List; import com.qiheng.DAO.UserDAO; import com.qiheng.bean.User; import com.qiheng.service.UserService; public class UserServiceImpl implements UserService { private UserDAO dao; public UserDAO getDao() { return dao; } public void setDao(UserDAO dao) { this.dao = dao; } public void saveUser(User user) { dao.saveUser(user); } public List<User> findAllUsers() { return dao.findAllUsers(); } public void deleteUser(int id) { dao.deleteUser(id); } public void updateUser(User user) { dao.updateUser(user); } public User findUserById(int id) { return dao.findUserById(id); } }
Shell
UTF-8
773
3.5625
4
[ "MIT" ]
permissive
#!/bin/bash echo "[WINDOWS-DC] Looking for Windows DC on the local network" while [[ $(./get-win-ip.sh | wc -w) < 1 ]] ; do echo "[WINDOWS-DC] Cannot locate Windows DC" sleep 10 done echo "[OSQUERY] Checking if Kolide container is running" while [[ $(docker ps -q -f name=fleet -f status=running | wc -l) < 1 ]] ; do echo "[OSQUERY] Kolide container is not running" sleep 10 done echo "[OSQUERY] Checking fleetctl status" while [[ $(sudo docker exec -i fleet /bin/sh -c 'fleetctl login --email guerillaBT@bsides.lab --password bsid3s! 2> /dev/null' | grep -c "Fleet login successful") < 1 ]] ; do echo "[OSQUERY] Fleetctl is not up yet" sleep 5 done echo "[OSQUERY] Fleet is up and working, configuring osquery on Windows DC.." ansible-playbook ./config-osquery.yml
Java
WINDOWS-1252
2,522
2.8125
3
[]
no_license
package me.virusbrandon.fileio; import java.io.File; import me.virusbrandon.bottomlesschests.Chest; import org.bukkit.configuration.file.YamlConfiguration; public class Writer{ private Chest chest; private boolean method; private YamlConfiguration Config; /** * FileIO.Writer Constructor * * @param chest * @param method * * */ public Writer(Chest chest,boolean method){ this.chest = chest; this.method = method; } /** * save Method, Begins Writting Contents * To The Server Hard Disk * * */ public void save(boolean isAutosave){ String cL = "C."; try{ File config = null; if(!method){ try{ config = new File("plugins/BottomLessChests/Chests/Name", chest.getName()+".yml"); } catch(Exception e1){ File file = new File("plugins/BottomLessChests/Chests/Name"); file.mkdirs(); config.createNewFile(); save(isAutosave); } } else { try{ config = new File("plugins/BottomLessChests/Chests/UUID", chest.UUID()+".yml"); } catch(Exception e1){ File file = new File("plugins/BottomLessChests/Chests/UUID"); file.mkdirs(); config.createNewFile(); save(isAutosave); } } Config = YamlConfiguration.loadConfiguration(config); Config.set(cL+"S", chest.getChest().size()); Config.set(cL+"N", chest.getName()); for(int x = 0;x<chest.getChest().size();x++){ try{ if(chest.getChest().get(x).getItemId()!=0){ try{ Config.set(cP(cL+x+".STK"),chest.getChest().get(x).getItemStack()); }catch(Exception e1){} try{ Config.set(cP(cL+x+".OW"),chest.getChest().get(x).getOrgWorld()); }catch(Exception e1){} } else { cP(cL+x); } }catch(Exception e1){} } Config.set(cP(cL+"F.T"), chest.getFriends().size()); try{ for(int y = 0;y<chest.getFriends().size();y++){ Config.set(cP(cL+"F."+y+".N"), chest.getFriends().get(y).getName()); Config.set(cP(cL+"F."+y+".U"), chest.getFriends().get(y).getUUID()); } }catch(Exception e1){} Config.set(cP(cL+"TimeStamp"), System.currentTimeMillis()); Config.save(config); if(!isAutosave){ chest.shutdown(); } }catch(Exception e1){} } /** * cP - Stands For Clear Path * * Clear Contents In This Section Of The Chest * Configuration File * * */ private String cP(String path){ Config.set(path, null); return path; } /* * 2016 Brandon Mueller * DO NOT DE-COMPILE THIS SOFTWARE OR ATTEMPT ANY FORM OF REVERSE ENGINEERING! */ }
Java
UTF-8
8,501
2.234375
2
[]
no_license
import java.io.IOException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.Map; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.chain.ChainMapper; import org.apache.hadoop.mapreduce.lib.chain.ChainReducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; /* * 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. */ /** * * @author Zhuang Zhuo <zhuo.z@husky.neu.edu> */ public class MapReduce3 { /** * @param args the command line arguments */ static class TempMapper extends Mapper<LongWritable, Text, CompositeKey_wd, IntWritable> { CompositeKey_wd wd = new CompositeKey_wd(); @Override public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { // 打印样本: Before Mapper: 0, 2000010115 //System.out.println("Before Mapper: " + key + "." + value); String line = value.toString(); try { String[] lineSplit = line.split(","); // String requestUrl = line.substring(0, 10); wd.setDayOfWeek(lineSplit[1]); wd.setDest(lineSplit[22]); String requestUrl = lineSplit[21]; if(requestUrl.equals("1")){ context.write(wd, new IntWritable(1)); } // System.out.println("" + "After Mapper:" + new Text(requestUrl) + "," + new IntWritable(1)); } // context.write(out,one); catch (java.lang.ArrayIndexOutOfBoundsException e) { // context.getCounter(Counter.LINESKIP).increment(1); } } } static class TempReducer extends Reducer<CompositeKey_wd, IntWritable, CompositeKey_wd, IntWritable> { @Override public void reduce(CompositeKey_wd key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { // System.out.println("Before Reduce:" + key + ","); int count = 0; for (IntWritable v : values) { count = count + v.get(); } try { context.write(key, new IntWritable(count)); // System.out.println( ""+ "After Reduce:" + key + "," + count); } catch (InterruptedException e) { e.printStackTrace(); } } } static class TempMapper2 extends Mapper<LongWritable, Text, IntWritable, CompositeKey_wd> { CompositeKey_wd wd = new CompositeKey_wd(); @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); try { String[] lineSplit = line.split("\t"); // String requestUrl = line.substring(0, 10); String requestUrl = lineSplit[0]; String[] lineSplit2 = requestUrl.split(","); wd.setDayOfWeek(lineSplit2[0]); wd.setDest(lineSplit2[1]); int val = Integer.parseInt(lineSplit[1]); context.write(new IntWritable(val),wd); } // context.write(out,one); catch (java.lang.ArrayIndexOutOfBoundsException e) { // context.getCounter(Counter.LINESKIP).increment(1); } } } static class TempReduce2 extends Reducer<IntWritable, CompositeKey_wd,Text, IntWritable> { ArrayList<LinkedHashMap<String,Integer>> tm = new ArrayList<LinkedHashMap<String,Integer>>(); int count=0; @Override protected void reduce(IntWritable key,Iterable<CompositeKey_wd> values, Context context) throws IOException, InterruptedException { for(CompositeKey_wd v :values){ int a = Integer.parseInt(v.getDayOfWeek())-1; if(tm.size()<7){ for(int i=0;i<12; i++){ LinkedHashMap<String,Integer> f = new LinkedHashMap<>(); tm.add(f); } } LinkedHashMap<String,Integer> fin = tm.get(a); fin.put(v.toString(), key.get()); System.out.println("" + "reduce2:" + a + " || " +v.toString() + "| "+ fin.size()+" |"+key.get()); // context.write(result, key); } } @Override protected void cleanup(Context context) throws IOException, InterruptedException { for(LinkedHashMap<String,Integer> f: tm){ int i=0; for (Map.Entry<String,Integer> entry : f.entrySet()) { i++; if(i==f.size()){ Text fi = new Text(entry.getKey()); context.write(fi,new IntWritable(entry.getValue())); } } } } } public static void main(String[] args) throws Exception { //输入路径 String dst = "hdfs://localhost:9000/data/2006a.csv"; //输出路径,必须是不存在的,空文件加也不行。 // String dstOut = "hdfs://localhost:9000/mapreduce/result3/1"; String dstOut = "/Users/wendyzhuo/NetBeansProjects/final_Hadoop/src/output3/1"; String outFiles = "/Users/wendyzhuo/NetBeansProjects/final_Hadoop/src/output3/2"; Configuration hadoopConfig = new Configuration(); hadoopConfig.set("fs.hdfs.impl", org.apache.hadoop.hdfs.DistributedFileSystem.class.getName() ); hadoopConfig.set("fs.file.impl", org.apache.hadoop.fs.LocalFileSystem.class.getName() ); Job job = new Job(hadoopConfig); Job job2 = new Job(hadoopConfig); FileInputFormat.addInputPath(job, new Path(dst)); FileOutputFormat.setOutputPath(job, new Path(dstOut)); FileInputFormat.addInputPath(job2, new Path(dstOut)); FileOutputFormat.setOutputPath(job2, new Path(outFiles)); JobConf map1Conf = new JobConf(false); ChainMapper.addMapper(job,TempMapper.class,LongWritable.class,Text.class,CompositeKey_wd.class,IntWritable.class,map1Conf); JobConf reduceConf = new JobConf(false); ChainReducer.setReducer(job,TempReducer.class,CompositeKey_wd.class,IntWritable.class,CompositeKey_wd.class,IntWritable.class,reduceConf); JobConf map2Conf = new JobConf(false); ChainMapper.addMapper(job2,TempMapper2.class,LongWritable.class,Text.class,IntWritable.class,CompositeKey_wd.class,map2Conf); JobConf map3Conf = new JobConf(false); ChainReducer.setReducer(job2,TempReduce2.class,IntWritable.class,CompositeKey_wd.class,Text.class,IntWritable.class,map3Conf); // // JobClient.runJob(job); //指定自定义的Mapper和Reducer作为两个阶段的任务处理类 // job.setMapperClass(TempMapper.class); // // job.setReducerClass(TempReducer.class); //设置最后输出结果的Key和Value的类型 job.setOutputKeyClass(CompositeKey_wd.class); job.setOutputValueClass(IntWritable.class); job2.setMapOutputKeyClass(IntWritable.class); job2.setMapOutputValueClass(CompositeKey_wd.class); // job2.setSortComparatorClass(LongWritable.DecreasingComparator.class); //执行job,直到完成 job.waitForCompletion(true); System.out.println("Finished1"); job2.waitForCompletion(true); System.out.println("Finished2"); } }
Java
UTF-8
1,204
3.46875
3
[]
no_license
import java.util.Scanner; public class IfElseExercise { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in); System.out.println("Please input what type of licence you are applying for 1 for g1 - 2 for g2 - 3 for g"); int type= sc.nextInt(); System.out.println("Please Input your age"); double age= sc.nextDouble(); System.out.println("Please input your Citizen status. 1 for Citizen - 2 for PR - 3 for immigrant"); String cStatus= sc.next(); if(cStatus.equals(3)) { System.out.println("Do you have a driving license Y/N"); char otherCountry = sc.nextLine().charAt(0); } System.out.println("Please enter your driving experience"); double experience= sc.nextDouble(); if(type==1 && age>=16 && age <=90 && (cStatus.equals("1") || cStatus.equals("2"))) { //for pr and citizens System.out.println("You are eligible for g1 licence"); } else if(type==2 && age>=17 && age<=90 && (cStatus.equals("1") || cStatus.equals("2") && experience >=1)) { System.out.println("You are eligible for g2 licence"); } } }
C++
UTF-8
1,744
3.796875
4
[]
no_license
#include "buffer.h" #include <iostream> #include <memory> class A { public: virtual void print() const { std::cout << "A\n"; } }; class B : public A { public: B() {} B(int m, float d) : m(m), d(d) {} virtual void print() const { std::cout << "B " << m << " / " << d << "\n"; } public: int m = 100; float d = 69.0f; }; class C : public A { public: C() {} C(int m, float d) : m(m), d(d) {} virtual void print() const { std::cout << "C " << d << " / " << m << "\n"; } public: int m = 100; float d = 69.0f; }; void print(A& a) { a.print(); } // call of base class using namespace std; int main() { assert(sizeof(B) == sizeof(C)); Buffer<A> buffer(sizeof(B)); // populate derived class buffer.push_back<B>(B{1,2}); buffer.push_back<B>(B{3,4}); // populate another derived class of the same size for (int i = 0; i < 10; ++i) buffer.push_back<C>(C{5,6}); cout << "Buffer stride:" << buffer.stride() << "\n"; cout << "Buffer size:" << buffer.size() << "\n"; cout << "\nIterate as base class(operator[]):\n"; for (int i = 0; i < buffer.size(); ++i) { cout << "iter..." << i << "\n"; buffer.at(i).print(); print(buffer.at(i)); } cout << "\nIterate as base class(iterator):\n"; for (Buffer<A>::iterator iter = buffer.begin(); iter != buffer.end(); ++iter) { cout << "iter..." << distance<A>(buffer.begin(), iter) << "\n"; iter->print(); print(*iter); } cout << "\nIterate as base class(foreach):\n"; int cnt{}; for (A& a : buffer) { cout << "iter..." << cnt++ << "\n"; a.print(); print(a); } return 0; }
PHP
UTF-8
7,475
2.5625
3
[ "BSD-3-Clause", "MIT", "Apache-2.0", "JSON", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * Basic methods for converting Atom and XML */ class InputBasicXmlConverter { public static function loadString($requestParam, $namespace = null) { $entityLoaderConfig = libxml_disable_entity_loader(true); $result = simplexml_load_string($requestParam, 'SimpleXMLElement', LIBXML_NOCDATA, $namespace); libxml_disable_entity_loader($entityLoaderConfig); return $result; } public static function convertActivities($xml, $activityXml) { $activity = array(); if (! isset($xml->title)) { throw new Exception("Mallformed activity xml"); } // remember to either type cast to (string) or trim() the string so we don't get // SimpleXMLString types in the internal data representation. I often prefer // using trim() since it cleans up the data too $activity['id'] = isset($xml->id) ? trim($xml->id) : ''; $activity['title'] = trim($xml->title); $activity['body'] = isset($xml->summary) ? trim($xml->summary) : ''; $activity['streamTitle'] = isset($activityXml->streamTitle) ? trim($activityXml->streamTitle) : ''; $activity['streamId'] = isset($activityXml->streamId) ? trim($activityXml->streamId) : ''; $activity['updated'] = isset($xml->updated) ? trim($xml->updated) : ''; if (isset($activityXml->mediaItems)) { $activity['mediaItems'] = array(); foreach ($activityXml->mediaItems->MediaItem as $mediaItem) { $item = array(); if (! isset($mediaItem->type) || ! isset($mediaItem->mimeType) || ! isset($mediaItem->url)) { throw new Exception("Invalid media item in activity xml"); } $item['type'] = trim($mediaItem->type); $item['mimeType'] = trim($mediaItem->mimeType); $item['url'] = trim($mediaItem->url); $activity['mediaItems'][] = $item; } } return $activity; } public static function convertAlbums($xml, $albumXml) { $fields = array('id', 'description', 'mediaItemCount', 'thumbnailUrl', 'ownerId', 'mediaMimeType'); $album = self::copyFields($albumXml, $fields); if (isset($xml->title) && !empty($xml->title)) { $album['title'] = trim($xml->title); } else if (isset($albumXml->caption)) { $album['title'] = trim($albumXml->caption); } if (isset($albumXml->mediaType) && in_array(strtoupper(trim($albumXml->mediaType)), MediaItem::$TYPES)) { $album['mediaType'] = strtoupper(trim($albumXml->mediaType)); } if (isset($albumXml->location)) { $address = self::convertAddresses($albumXml->location); if ($address) { $album['location'] = $address; } } return $album; } public static function convertMediaItems($xml, $mediaItemXml) { $fields = array('albumId', 'created', 'description', 'duration', 'fileSize', 'id', 'language', 'lastUpdated', 'mimeType', 'numComments', 'numViews', 'numVotes', 'rating', 'startTime', 'taggedPeople', 'tags', 'thumbnailUrl', 'url'); $mediaItem = self::copyFields($mediaItemXml, $fields); if (isset($xml->title) && !empty($xml->title)) { $mediaItem['title'] = trim($xml->title); } else if (isset($mediaItemXml->caption)) { $mediaItem['title'] = trim($mediaItemXml->caption); } if (isset($mediaItemXml->type) && in_array(strtoupper(trim($mediaItemXml->type)), MediaItem::$TYPES)) { $mediaItem['type'] = strtoupper(trim($mediaItemXml->type)); } if (isset($mediaItemXml->location)) { $address = self::convertAddresses($mediaItemXml->location); if ($address) { $mediaItem['location'] = $address; } } return $mediaItem; } public static function convertAddresses($xml) { $fields = array('country', 'extendedAddress', 'latitude', 'locality', 'longitude', 'poBox', 'postalCode', 'region', 'streetAddress', 'type', 'unstructuredAddress', 'formatted'); return self::copyFields($xml, $fields); } public static function copyFields($xml, $fields) { $object = array(); if (!is_array($fields)) { $fields = array($fields); } foreach ($fields as $field) { if ($xml && isset($xml->$field)) { $object[$field] = trim($xml->$field); } } return $object; } public static function convertMessages($requestParam, $xml, $content) { // As only message handler has the context to know whether it's a message or a message // collection request. All the fields for both the Message and the MessageCollection // classes are converted here. Message handler has the responsibility to validate the // params. $message = array(); if (isset($xml->id)) { $message['id'] = trim($xml->id); } if (isset($xml->title)) { $message['title'] = trim($xml->title); } if (!empty($content)) { $message['body'] = trim($content); } if (isset($xml->bodyId)) { $meesage['bodyId'] = trim($xml->bodyId); } if (isset($xml->titleId)) { $message['titleId'] = trim($xml->titleId); } if (isset($xml->appUrl)) { $message['appUrl'] = trim($xml->appUrl); } if (isset($xml->status)) { $message['status'] = trim($xml->status); } if (isset($xml->timeSent)) { $message['timeSent'] = trim($xml->timeSent); } if (isset($xml->type)) { $message['type'] = trim($xml->type); } if (isset($xml->updated)) { $message['updated'] = trim($xml->updated); } if (isset($xml->senderId)) { $message['senderId'] = trim($xml->senderId); } if (isset($xml->appUrl)) { $message['appUrl'] = trim($xml->appUrl); } if (isset($xml->collectionIds)) { $message['collectionIds'] = array(); foreach ($xml->collectionIds as $collectionId) { $message['collectionIds'][] = trim($collectionId); } } // Tries to retrieve recipients by looking at the osapi name space first then // the default namespace. $recipientXml = self::loadString($requestParam, "http://opensocial.org/2008/opensocialapi"); if (empty($recipientXml) || !isset($recipientXml->recipient)) { $recipientXml = $xml; } if (isset($recipientXml->recipient)) { $message['recipients'] = array(); foreach ($recipientXml->recipient as $recipient) { $message['recipients'][] = trim($recipient); } } // TODO: Parses the inReplyTo, replies and urls fields. // MessageCollection specified fiedls. if (isset($xml->total)) { $message['total'] = trim($xml->total); } if (isset($xml->unread)) { $message['unread'] = trim($xml->unread); } return $message; } }
C++
UTF-8
6,368
3.703125
4
[ "MIT" ]
permissive
#if !defined _DYNAMICARRAY_H_ #define _DYNAMICARRAY_H_ #include <iostream> using namespace std; // interfaces of Dynamic Array class DArray template<class T> class DArray { private: T *m_pData; // the pointer to the array memory int m_nSize; // the size of the array int m_nMax; private: void Init(); // initilize the array void Free(); // free the array inline int InvalidateIndex(int nIndex); // judge the validate of an index public: DArray(); // default constructor DArray(int nSize, T dValue = 0); // set an array with default values DArray(const DArray& arr); // copy constructor ~DArray(); // deconstructor void Print(); // print the elements of the array int GetSize(); // get the size of the array bool SetSize(int nSize); // set the size of the array T GetAt(int nIndex); // get an element at an index bool SetAt(int nIndex, T dValue); // set the value of an element T operator[](int nIndex) const; // overload operator '[]' bool PushBack(T dValue); // add a new element at the end of the array bool DeleteAt(int nIndex); // delete an element at some index bool InsertAt(int nIndex, T dValue); // insert a new element at some index DArray& operator = (const DArray& arr); //overload operator '=' }; // default constructor template<class T> DArray<T>::DArray() { Init(); } // set an array with default values template<class T> DArray<T>::DArray(int nSize, T dValue) { m_pData = new T [nSize]; for(int i=0; i<nSize; i++) { m_pData[i] = dValue; } m_nSize = nSize; m_nMax = nSize; } template<class T> DArray<T>::DArray(const DArray& arr) { m_nSize = arr.m_nSize; m_nMax = arr.m_nSize; m_pData = new T [m_nSize]; for (int i=0; i<m_nSize; i++) { m_pData[i] = arr[i]; } } // deconstructor template<class T> DArray<T>::~DArray() { Free(); } // display the elements of the array template<class T> void DArray<T>::Print() { cout<<"size= "<<m_nSize<<":"; for(int i=0; i<m_nSize; i++) { cout<<" "<<GetAt(i); } cout<<endl; } // initilize the array template<class T> void DArray<T>::Init() { m_nSize = 0; m_nMax = 0; m_pData = nullptr; } // free the array template<class T> void DArray<T>::Free() { delete[] m_pData; m_pData = nullptr; m_nSize = 0; m_nMax = 0; } // judge the validate of an index template<class T> inline int DArray<T>::InvalidateIndex(int nIndex) { if(nIndex < 0 || nIndex > m_nSize) { return true; } else { return false; } } // get the size of the array template<class T> int DArray<T>::GetSize() { return m_nSize; } // set the size of the array template<class T> bool DArray<T>::SetSize(int nSize) { if( m_pData == nullptr ) { m_pData = new T [nSize]; if( m_pData == nullptr ) { cout<< "Can not alloc memory in SetSize()!" << endl; return false; } for(int i=0; i<nSize; i++) { m_pData[i] = (T)0; } m_nSize = nSize; m_nMax = nSize; } else if( m_nSize==nSize ) { return true; } else { T *pTemp=nullptr; pTemp = new T [nSize]; if( pTemp == nullptr ) { cout<< "Can not alloc memory in SetSize()!" << endl; return false; } for(int i=0; i<nSize; i++) { pTemp[i] = 0; } int nBound = 0; if( m_nSize<nSize ) { nBound = m_nSize; } else { nBound = nSize; } for( int i=0; i<nBound; i++ ) { pTemp[i] = m_pData[i]; } delete[] m_pData; m_pData = pTemp; m_nSize = nSize; m_nMax = nSize; } return true; } // get an element at an index template<class T> T DArray<T>::GetAt(int nIndex) { if( InvalidateIndex(nIndex) ) { cout<<"Index is invalide in GetAt()!"<<endl; return false; } else { return m_pData[nIndex]; } } // set the value of an element template<class T> bool DArray<T>::SetAt(int nIndex, T dValue) { if( InvalidateIndex(nIndex) ) { cout<<"Index is invalide in SetAt()!"<<endl; return false; } else { m_pData[nIndex]=dValue; return true; } } // overload operator '[]' template<class T> T DArray<T>::operator[](int nIndex) const { return m_pData[nIndex]; } // add a new element at the end of the array template<class T> bool DArray<T>::PushBack(T dValue) { if( m_nSize < m_nMax ) { m_pData[m_nSize] = dValue; m_nSize++; } else { if( m_nMax == 0 ) { m_nMax = 1; } else { m_nMax *= 2; } T *pTemp=nullptr; pTemp = new T [m_nMax]; if( pTemp == nullptr ) { cout<< "Can not alloc memory in PushBack()!" << endl; return false; } for( int i=0; i<m_nSize; i++ ) { pTemp[i] = m_pData[i]; } pTemp[m_nSize] = dValue; delete[] m_pData; m_pData = pTemp; m_nSize++; } return true; } // delete an element at some index template<class T> bool DArray<T>::DeleteAt(int nIndex) { if( InvalidateIndex(nIndex) ) { cout<<"Index is invalide in DeleteAt()!"<<endl; return false; } else { T *pTemp=nullptr; pTemp = new T [m_nSize-1]; if( pTemp == nullptr ) { cout<< "Can not alloc memory in DeleteAt()!" << endl; return false; } for( int i=0; i<nIndex; i++ ) { pTemp[i] = m_pData[i]; } for( int i=nIndex; i<m_nSize-1; i++ ) { pTemp[i] = m_pData[i+1]; } delete[] m_pData; m_pData = pTemp; m_nSize--; m_nMax = m_nSize; return true; } } // insert a new element at some index template<class T> bool DArray<T>::InsertAt(int nIndex, T dValue) { if( InvalidateIndex(nIndex) ) { cout<<"Index is invalide in InsertAt()!"<<endl; return false; } else { if(m_nSize < m_nMax) { for( int i=m_nSize; i>nIndex; i-- ) { m_pData[i] = m_pData[i-1]; } m_pData[nIndex]=dValue; m_nSize++; } else { T *pTemp=nullptr; if(m_nMax == 0 ) { m_nMax = 1; } else { m_nMax *= 2; } pTemp = new T [m_nMax]; if( pTemp == nullptr ) { cout<< "Can not alloc memory in InsertAt()!" << endl; return false; } for( int i=0; i<nIndex; i++ ) { pTemp[i] = m_pData[i]; } pTemp[nIndex]=dValue; for( int i=nIndex+1; i<m_nSize+1; i++ ) { pTemp[i] = m_pData[i-1]; } delete[] m_pData; m_pData = pTemp; m_nSize++; } return true; } } // overload operator '=' template<class T> DArray<T>& DArray<T>::operator = (const DArray& arr) { delete m_pData; m_nSize = arr.m_nSize; m_nMax = arr.m_nSize; m_pData = new T [m_nSize]; for (int i=0; i<m_nSize; i++) { m_pData[i] = arr[i]; } return *this; } #endif // _DYNAMICARRAY_H_
Python
UTF-8
1,327
2.578125
3
[]
no_license
#!/usr/bin/python """ sends URL request (POST) to consult patient episodes checks authorization """ import json import urllib2 import time import unittest from time import sleep import logging import ast #................................................................ cedula = 703927262 email = "autenticated_user@gmail.com" #email = "foobar@doctor.com" #................................................................ url = 'http://localhost:4567/api/doc/get' #url = 'http://157.253.211.97:4567/api/doc/get' logging.basicConfig(filename='logs/sendConsultTestMongo.log',level=logging.DEBUG) logging.info('sendConsultTestMongo.py') def getJson(url,data): req = urllib2.Request(url) req.add_header('Content-Type', 'application/json') try: start = time.time() response = urllib2.urlopen(req, data) end = time.time() response_json = json.load( response ) jdata = ast.literal_eval(response_json) logging.info( 'HTTPCode = ' + str(response.getcode() ) ) return response.getcode(), len(jdata) except urllib2.URLError, e: logging.error('URLError = ' + str(e.reason) ) return e.code, 0 data = '{ cedula : ' + str(cedula) + ', email : ' + '"' + email + '"' + ' }' logging.info(data) value = getJson(url,data) print"return http code and len(registers): ", value
SQL
UTF-8
228
2.65625
3
[]
no_license
CREATE TABLE IF NOT EXISTS one.users ( id INTEGER PRIMARY KEY, name VARCHAR(30), email VARCHAR(50) ); CREATE TABLE IF NOT EXISTS one.home ( id INTEGER PRIMARY KEY, home_name VARCHAR(30), home_address VARCHAR(50) );
Python
UTF-8
703
3.125
3
[]
no_license
import re class Solution: def myAtoi(self, s: str) -> int: if not s: return 0 s_process = s.strip() if not s_process: return 0 if re.match(r"^(\-|\+)?\d+", s_process): for i in range(1, len(s_process)): if not re.match(r"\d", s_process[i]): s_process = s_process[:i] break num = int(s_process) if num < pow(-2, 31): return pow(-2, 31) if num >= pow(2, 31): return pow(2, 31) - 1 return num return 0 if __name__ == '__main__': s = Solution() print(s.myAtoi("4193 with words"))
C#
UTF-8
2,585
2.53125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using Excel = Microsoft.Office.Interop.Excel; using System.Runtime.InteropServices; using WORD = System.UInt16; using DWORD = System.UInt32; namespace SimpleMMDImporter.MMDMotion { class CameraMotionData { public DWORD FrameNo { get; set; } public float Length { get; set; } public float[] Location { get; private set; } public float[] Rotation { get; private set; } public byte[][] Interpolation { get; private set; } public WORD viewingAngle { get; private set; } public byte[] Unknown { get; protected set; } public CameraMotionData(BinaryReader reader, float CoordZ, float scale) { Read(reader, CoordZ, scale); } public void Read(BinaryReader reader, float CoordZ, float scale) { FrameNo = BitConverter.ToUInt32(reader.ReadBytes(4), 0); Length = BitConverter.ToSingle(reader.ReadBytes(4), 0); Location = new float[3]; for (int i = 0; i < Location.Length; i++) { Location[i] = BitConverter.ToSingle(reader.ReadBytes(4), 0) * scale; } Rotation = new float[3]; for (int i = 0; i < Rotation.Length; i++) { Rotation[i] = BitConverter.ToSingle(reader.ReadBytes(4), 0); } Interpolation = new byte[6][]; for (int i = 0; i < Interpolation.Length; i++) { Interpolation[i] = new byte[4]; for (int j = 0; j < Interpolation[i].Length; j++) { Interpolation[i][j] = reader.ReadByte(); } } Unknown = new byte[3]; for (int i = 0; i < Unknown.Length; i++) { Unknown[i] = reader.ReadByte(); } Location[2] *= CoordZ; Rotation[2] *= CoordZ; } public void Write(StreamWriter writer) { writer.Write(FrameNo + ","); writer.Write(Length + ","); foreach (var v in Location) writer.Write(v + ","); foreach (var v in Rotation) writer.Write(v + ","); //foreach (var v1 in Interpolation) // foreach (var v in v1) // writer.Write(v + ","); writer.Write(viewingAngle + ","); foreach (var v in Unknown) writer.Write(v + ","); writer.WriteLine(); } } }
Java
UTF-8
14,597
2.484375
2
[]
no_license
package com.c45y.CutePVP; import org.bukkit.ChatColor; import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.player.PlayerChatEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerRespawnEvent; import com.c45y.CutePVP.buff.TeamBuff; // ---------------------------------------------------------------------------- /** * Event listener implementation. * * The synchronous PlayerChatEvent is deprecated but it's just so much easier to * handle that way. */ @SuppressWarnings("deprecation") public class CutePVPListener implements Listener { // ------------------------------------------------------------------------ /** * Constructor. * * @param plugin the plugin. */ public CutePVPListener(CutePVP plugin) { _plugin = plugin; } // ------------------------------------------------------------------------ /** * Cancel attempts to take off the woolen helmet. */ @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onInventoryClick(InventoryClickEvent event) { Player player = (Player) event.getWhoClicked(); if (!_plugin.getTeamManager().isExempted(player) && event.getSlot() == 39) { event.setCancelled(true); } } // ------------------------------------------------------------------------ /** * Respawn players in their team spawn. */ @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onPlayerRespawn(PlayerRespawnEvent event) { TeamPlayer teamPlayer = _plugin.getTeamManager().getTeamPlayer(event.getPlayer()); if (teamPlayer != null) { _plugin.getLogger().info(event.getPlayer().getName() + " respawned on " + teamPlayer.getTeam().getName() + "."); teamPlayer.setHelmet(); event.setRespawnLocation(teamPlayer.getTeam().getSpawn()); } } // ------------------------------------------------------------------------ /** * On join, allocate players to a team if not exempted. */ @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onPlayerJoin(PlayerJoinEvent event) { TeamManager tm = _plugin.getTeamManager(); Player player = event.getPlayer(); if (player.hasPermission(Permissions.MOD)) { tm.onStaffJoin(player); _plugin.getLogger().info(player.getName() + " has staff permissions."); } if (tm.isExempted(player)) { _plugin.getLogger().info(player.getName() + " is exempted from team assignment."); return; } TeamPlayer teamPlayer = tm.getTeamPlayer(player); if (teamPlayer == null) { // We don't care whether they have played before or not. If not // exempted, allocate to a team now. tm.onFirstJoin(player); teamPlayer = tm.getTeamPlayer(player); } else { Team team = teamPlayer.getTeam(); player.sendMessage("You're on " + team.encodeTeamColor(team.getName()) + "."); _plugin.getLogger().info(player.getName() + " rejoined " + team.getName() + "."); } // The old OfflinePlayer instance can't be used to reference the player. // This new one can, so store that. teamPlayer.setOfflinePlayer(event.getPlayer()); player.setDisplayName(teamPlayer.getTeam().encodeTeamColor(player.getName())); teamPlayer.setHelmet(); event.setJoinMessage(player.getDisplayName() + " joined the game."); } // ------------------------------------------------------------------------ /** * When leaving, show the (colorful) display name in the leave message. * * Drop the flag if the player is carrying it. */ @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onPlayerQuit(PlayerQuitEvent event) { Player player = event.getPlayer(); event.setQuitMessage(player.getDisplayName() + " left the game."); TeamManager tm = _plugin.getTeamManager(); TeamPlayer teamPlayer = tm.getTeamPlayer(player); if (teamPlayer != null && teamPlayer.isCarryingFlag()) { teamPlayer.getCarriedFlag().drop(); } tm.onPlayerQuit(player); } // ------------------------------------------------------------------------ /** * When the player steps on a block with special properties, apply the * corresponding buff. */ @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onPlayerMove(PlayerMoveEvent event) { Player player = event.getPlayer(); TeamPlayer teamPlayer = _plugin.getTeamManager().getTeamPlayer(player); if (teamPlayer != null) { _plugin.updateTeamPlayerEffects(teamPlayer); } } // ------------------------------------------------------------------------ /** * Bar held and projectile weapon PvP damage in player's own team's base. * * Also block damage from own team members, and between participants and * non-participants (both cases). */ @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { if (!(event.getEntity() instanceof Player)) { return; } if (event.getDamager() instanceof Player) { TeamPlayer attacker = _plugin.getTeamManager().getTeamPlayer((Player) event.getDamager()); TeamPlayer victim = _plugin.getTeamManager().getTeamPlayer((Player) event.getEntity()); handlePvPDamage(event, attacker, victim); } else if (event.getDamager() instanceof Projectile) { Projectile projectile = (Projectile) event.getDamager(); if (projectile.getShooter() instanceof Player) { TeamPlayer attacker = _plugin.getTeamManager().getTeamPlayer((Player) projectile.getShooter()); TeamPlayer victim = _plugin.getTeamManager().getTeamPlayer((Player) event.getEntity()); handlePvPDamage(event, attacker, victim); } } } // ------------------------------------------------------------------------ /** * Handle EntityDamageByEntityEvent by checking for PvP and disallowing PvP * damage when: * * <ul> * <li>Between participants and non-participants, or</li> * <li>Between participants on the same team, or</li> * <li>When the victim is in his team's base.</li> * </ul> */ protected void handlePvPDamage(EntityDamageByEntityEvent event, TeamPlayer attacker, TeamPlayer victim) { if (attacker == null || victim == null) { // One or other player is not a participant. No damage dealt. event.setCancelled(true); } else if (attacker.getTeam() == victim.getTeam()) { // Both players on the same team. No damage dealt. event.setCancelled(true); } else if (victim.getTeam().inTeamBase(victim.getPlayer().getLocation())) { attacker.getPlayer().sendMessage(ChatColor.DARK_RED + "You cannot attack within another team's base."); event.setCancelled(true); } } // ------------------------------------------------------------------------ /** * Handle flag steals, captures (scoring) and returns, which all require * that a player right clicks on a flag. * * <ul> * <li>To steal a flag, a player must right click on the opposing team's * flag (whether dropped or at home).</li> * <li>To capture a flag, a player must be carrying an opposing team's flag * when he clicks on his own flag at home.</li> * <li>To return a flag, a player must click on his own flag when it is * dropped (not at home).</li> * </ul> * * @param event the event. */ @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onPlayerInteract(PlayerInteractEvent event) { Player player = event.getPlayer(); TeamManager tm = _plugin.getTeamManager(); TeamPlayer teamPlayer = tm.getTeamPlayer(player); if (teamPlayer == null || event.getAction() != Action.RIGHT_CLICK_BLOCK) { return; } // Is the clicked block a team buff? Block clickedBlock = event.getClickedBlock(); TeamBuff teamBuff = _plugin.getBuffManager().getTeamBuffFromBlock(clickedBlock); if (teamBuff != null) { teamBuff.claimBy(teamPlayer); return; } // Is it a team block and therefore possibly a flag? Team clickedBlockTeam = tm.getTeamFromBlock(clickedBlock); if (clickedBlockTeam != null) { // Block is of the same material as a team block. Is it a flag? Flag flag = clickedBlockTeam.getFlagFromBlock(clickedBlock); if (flag != null) { // Player's own team flag? if (clickedBlockTeam == teamPlayer.getTeam()) { // Returning a dropped flag? if (flag.isDropped()) { flag.doReturn(); teamPlayer.getScore().returns.increment(); teamPlayer.getTeam().getScore().returns.increment(); Messages.broadcast(player.getDisplayName() + Messages.BROADCAST_COLOR + " returned " + teamPlayer.getTeam().getName() + "'s flag."); } else if (flag.isHome() && teamPlayer.isCarryingFlag()) { // Capturing an opposition team's flag. teamPlayer.getScore().captures.increment(); teamPlayer.getTeam().getScore().captures.increment(); Flag carriedFlag = teamPlayer.getCarriedFlag(); carriedFlag.doReturn(); Messages.broadcast(player.getDisplayName() + Messages.BROADCAST_COLOR + " captured " + carriedFlag.getTeam().getName() + "'s " + carriedFlag.getName() + " flag."); } } else { // An opposition team flag. if (teamPlayer.isCarryingFlag()) { player.sendMessage(ChatColor.DARK_RED + "You can only carry one flag at a time."); } else { flag.stealBy(teamPlayer); teamPlayer.getScore().steals.increment(); teamPlayer.getTeam().getScore().steals.increment(); Messages.broadcast(player.getDisplayName() + Messages.BROADCAST_COLOR + " has stolen " + clickedBlockTeam.getName() + "'s flag."); } } } } } // onPlayerInteract // ------------------------------------------------------------------------ /** * When a player dies: * * <ul> * <li>Drop the flag if he's carrying it.</li> * <li>Increment his and his team's kill scores if they are not on the same * team. Players can't hurt their team mates, so the check is redundant, but * cheap and future-proof.</li> * </ul> */ @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onPlayerDeath(PlayerDeathEvent event) { Player player = event.getEntity(); TeamPlayer teamPlayer = _plugin.getTeamManager().getTeamPlayer(player); if (teamPlayer != null) { if (teamPlayer.isCarryingFlag()) { teamPlayer.getCarriedFlag().drop(); } Player killer = player.getKiller(); TeamPlayer teamKiller = _plugin.getTeamManager().getTeamPlayer(killer); if (teamKiller != null && teamPlayer.getTeam() != teamKiller.getTeam()) { teamKiller.getTeam().getScore().kills.increment(); teamKiller.getScore().kills.increment(); } } } // ------------------------------------------------------------------------ /** * Handle chat by cancelling the normal event and directly messaging players * with team colors inserted. */ @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onPlayerChat(PlayerChatEvent event) { event.setCancelled(true); Player player = event.getPlayer(); _plugin.getLogger().info(player.getName() + ": " + ChatColor.stripColor(event.getMessage())); TeamPlayer teamPlayer = _plugin.getTeamManager().getTeamPlayer(player); String message = "<" + player.getDisplayName() + "> " + ChatColor.stripColor(event.getMessage()); if (teamPlayer != null) { // A match participant. Team team = teamPlayer.getTeam(); team.message(message); } // Copy the message to staff (all non-participants). for (Player staff : _plugin.getTeamManager().getOnlineStaff()) { staff.sendMessage(message); } } // ------------------------------------------------------------------------ /** * Allow block placement per * {@link CutePVPListener#allowBlockEdit(Player, Location)}. */ @EventHandler(ignoreCancelled = true) public void onBlockPlace(BlockPlaceEvent event) { if (!allowBlockEdit(event.getPlayer(), event.getBlock().getLocation())) { event.setCancelled(true); } } // ------------------------------------------------------------------------ /** * Allow block breaks per * {@link CutePVPListener#allowBlockEdit(Player, Location)}. */ @EventHandler(ignoreCancelled = true) public void onBlockBreak(BlockBreakEvent event) { if (!allowBlockEdit(event.getPlayer(), event.getBlock().getLocation())) { event.setCancelled(true); } } // ------------------------------------------------------------------------ /** * Return true if attempted edits should be allowed. * * <ul> * <li>Staff can edit blocks anywhere.</li> * <li>Players in their own base regions can edit, except for the flag * blocks.</li> * <li>Players in the base regions of other teams cannot edit any blocks.</li> * </ul> * * @param player the player doing the edit. * @param location the location of the edited block. * @return true if attempted edits should be allowed. */ protected boolean allowBlockEdit(Player player, Location location) { TeamPlayer teamPlayer = _plugin.getTeamManager().getTeamPlayer(player); if (teamPlayer == null) { // Staff member. return true; } if (teamPlayer.getTeam().inTeamBase(location)) { return !teamPlayer.getTeam().isFlagHomeLocation(location); } else if (_plugin.getTeamManager().inEnemyTeamBase(player)) { player.sendMessage(ChatColor.DARK_RED + "You cannot build in an enemy base"); return false; } else { return true; } } // ------------------------------------------------------------------------ /** * Owning plugin. */ private final CutePVP _plugin; } // CutePVPListener
Java
UTF-8
1,919
3.25
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package labtest1; import java.io.File; import java.io.PrintWriter; import java.util.Scanner; import java.lang.*; /** * * @author iiita */ public class Separatewordnumbers { public static void main(String[] args) { try { File file = new File("input.txt"); Scanner sc = new Scanner(file); // PrintWriter pw = new PrintWriter("output.txt"); PrintWriter pw1 = new PrintWriter("words.txt"); PrintWriter pw2 = new PrintWriter("numbers.txt"); PrintWriter pw3 = new PrintWriter("punctuations.txt"); String mod,mod1; while(sc.hasNext()){ mod1=""; mod = sc.next(); // System.out.println(mod); int len = mod.length(); char c = mod.charAt(0); // System.out.println(c); char check = mod.charAt(len-1); if(check == '.'|| check==','||check=='*'){ mod1 = mod.substring(0,len-1); pw3.println(mod.charAt(len-1)); // System.out.println(check); } else mod1=mod; if(c>='0' && c<='9'){ pw2.println(mod1); } else { pw1.println(mod1); } } sc.close(); // pw.close(); pw1.close(); pw2.close(); pw3.close(); } catch(Exception e){ System.out.println("Heyy error!!"); } } }
JavaScript
UTF-8
1,461
2.90625
3
[]
no_license
export const getUrlParam = (key) => { const reg = new RegExp(`\\?.*${key}=?(.*?)(?=&|$|(?=#))`, 'g') const url = window.location.href.toString() const match = reg.exec(url) if(match){ return match[1] ? match[1] : true } return undefined } // 添加Url参数 export const addUrlParam = (params) => { let href = window.location.href.toString() const keys = Object.keys(params) keys.forEach(key => { const value = typeof params[key] === 'undefined' ? '' : `=${params[key]}` if(getUrlParam(key)){ const reg = new RegExp(`${key}=?.*?(?=&|$|(?=#))`, 'g') href = href.replace(reg, (match) => { return `${key}${value}` }) }else{ const paramStr = `${href.includes('?') ? '&' : '?'}${key}${value}` href += paramStr } }) window.history.replaceState('', '', href); } // 获取URL中的hash值 export const getUrlHash = () => { const href = window.location.href.toString() const reg = /#(.*?)$/g const match = reg.exec(href) if(match){ return match[1] } return false } // 设置URL中的hash值 export const setUrlHash = (hash) => { let href = window.location.href.toString() if(href.includes('#')){ const reg = /#(.*?)$/g href = href.replace(reg, `#${hash}`) }else { href += `#${hash}` } window.history.replaceState('', '', href); }
Java
UTF-8
378
1.75
2
[]
no_license
package com.care.root.mybatis.mileage; import java.util.ArrayList; import com.care.root.mileage.dto.MileageDTO; import com.care.root.order.dto.OrderDTO; public interface MileageMapper { public ArrayList<MileageDTO> getUserMileages(String memberIdx); public int getUserTotalMileage(String memberIdx); public ArrayList<String> getUserMileageStateList(String memberIdx); }
JavaScript
UTF-8
4,109
2.546875
3
[]
no_license
import React, { useState } from "react"; import { makeStyles } from "@material-ui/core/styles"; import PopupMessage from "../PopupMessage"; // import Card from "@material-ui/core/Card"; // import { CardActionArea, CardActions, CardContent, CardMedia, Typography, Button, Grid } from "@material-ui/core"; import API from "../../utils/API"; import "./style.css"; const useStyles = makeStyles((theme) => ({ root: { minWidth: 350, width: "70%", margin: "20px auto" }, header: { height: 50 }, image: { width: 100 } })); export default function BookCard(props) { const classes = useStyles(); const [disabledButton, setDisabledButton] = useState(false); const [popupOpen, setPopupOpen] = useState(false); const [popupType, setPopupType] = useState("success"); const handleSaveButtonClick = () => { const book = { id: props.id, title: props.title, authors: props.authors, description: props.description, link: props.link, image: props.img }; API.saveBook(book) .then(res => console.log(`'${props.title}' has been saved!`)) .then(() => { setPopupType("success"); setPopupOpen(true); }) .catch(err => { console.log(err); setPopupType("error"); setPopupOpen(true); }); setDisabledButton(true); }; // Format author array const renderAuthors = (authors) => { if (authors.length < 1) { return "Unknown author(s)"; } else if (authors.length === 1) { return `By ${authors[0]}`; } else if (authors.length === 2) { return `By ${authors[0]} & ${authors[1]}`; } else { let authorStr = "By "; for (let i = 0; i < authors.length; i++) { if (i < authors.length - 2) { authorStr += `${authors[i]}, `; } else if (i === authors.length - 2) { authorStr += `${authors[i]} `; } else { authorStr += `& ${authors[i]}`; } } return authorStr; } }; // Handle close for popup message const handleClose = (event, reason) => { if (reason === 'clickaway') { return; } setPopupOpen(false); }; return ( <div className="book-card"> <div className="book-thumbnail"> <div className="book-shadow"> <img src={props.img} alt={props.imgAlt}></img> </div> <button className="view-book-btn"><a href={props.link} target="_blank" rel="noreferrer noopener">View on Google</a></button> </div> <div className="book-content"> <div className="book-content-heading"> <div className="heading-col1"> <h4>{props.title}</h4> </div> <div className="heading-col2"> <div className="book-actions"> {window.location.href === "https://jkaho-google-books.herokuapp.com/saved" ? <div><button className="remove-book-btn" onClick={() => props.onClick(props.id)}>Remove</button></div> : <div> <button className="save-book-btn" onClick={handleSaveButtonClick} disabled={props.saved ? true : disabledButton ? true : false } > {props.saved ? "Saved" : disabledButton ? "Saved" : "Save"} </button> </div> } </div> </div> </div> <div className="book-content-authors"> {renderAuthors(props.authors)} </div> <div className="book-content-description"> {props.description} </div> </div> <PopupMessage message={ popupType === "success" ? `"${props.title}" successfully saved!` : "An error occurred, please try again later" } severity={ popupType === "success" ? "success" : "error" } open={popupOpen} handleClose={handleClose} /> </div> ) }
Java
UTF-8
3,411
2.53125
3
[]
no_license
package vic.rpg.client.net; import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import vic.rpg.Game; import vic.rpg.client.packet.PacketHandlerSP; import vic.rpg.gui.Gui; import vic.rpg.gui.GuiError; import vic.rpg.gui.GuiMain; import vic.rpg.registry.GameRegistry; import vic.rpg.server.GameState; import vic.rpg.server.Server; import vic.rpg.server.packet.Packet; import vic.rpg.server.packet.Packet0StateUpdate; public class NetHandler extends Thread { public Socket socket; public DataInputStream in; public DataOutputStream out; public boolean connected; public boolean IS_SINGLEPLAYER = false; public String lastError = ""; public int STATE = GameState.RUNNING; public NetHandler() { this.setName("Network Thread"); } public boolean connect(String adress, int port, String username) { Game.USERNAME = username; try { connected = true; socket = new Socket(adress, port); in = new DataInputStream(socket.getInputStream()); out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream())); out.writeUTF(Game.USERNAME); out.writeUTF(GameRegistry.VERSION); out.flush(); this.start(); Game.packetHandler = new PacketHandlerSP(); System.out.println("Succsessfully connected to: " + adress + ":" + port + " as player " + username); return true; } catch (Exception e) { e.printStackTrace(); lastError = e.toString(); this.close(); } return false; } double unprocessedSeconds = 0; long previousTime = System.nanoTime(); double secondsPerTick = 3; public void run() { while(connected) { try { long currentTime = System.nanoTime(); long passedTime = currentTime - previousTime; previousTime = currentTime; unprocessedSeconds += passedTime / 1000000000.0; while(unprocessedSeconds > secondsPerTick) { Game.packetHandler.addPacketToSendingQueue(new Packet0StateUpdate(STATE)); unprocessedSeconds -= secondsPerTick; } if(socket.isConnected() && in.available() > 1) { int id = in.readByte(); Packet packet = Packet.getPacket(id); packet.readData(in); Game.packetHandler.addPacketToQueue(packet); } Thread.sleep(1); } catch (Exception e) { e.printStackTrace(); lastError = e.toString(); this.close(); } } } public void close() { try { System.out.println("Destroying Network Thread..."); this.connected = false; while(this.isAlive()) { Thread.sleep(100); } if(this.socket != null) { if(this.socket.isConnected()) { STATE = GameState.QUIT; Game.packetHandler.sendPacket(new Packet0StateUpdate(STATE)); } this.socket.close(); } System.out.println("done!"); if(IS_SINGLEPLAYER) { Server.server.inputHandler.handleCommand("stop", null, Server.server); } Game.playerUUID = null; Game.level = null; if(lastError.length() > 0) { Gui.setGui(new GuiError()); } else Gui.setGui(new GuiMain()); } catch (Exception e) { e.printStackTrace(); } } public boolean available() { try { return in.available() > 0; } catch (IOException e) { e.printStackTrace(); } return false; } }
Python
UTF-8
508
2.828125
3
[]
no_license
""" Url: https://www.codechef.com/problems/DRAGNXOR """ __author__ = "Ronald Kaiser" __email__ = "raios dot catodicos at gmail dot com" for _ in range(int(input())): N, A, B = list(map(int, input().split())) bA = format(A, 'b') A = '0'*(N-len(bA)) + bA A1 = A.count('1') A0 = A.count('0') bB = format(B, 'b') B = '0'*(N-len(bB)) + bB B1 = B.count('1') B0 = B.count('0') ones = min(A1, B0) + min(A0, B1) s = '1'*ones + '0'*(N-(ones)) print(int(s, 2))
PHP
UTF-8
874
2.546875
3
[]
no_license
<?php namespace Cubex\Quantum\Base\FileStore\Interfaces; use Cubex\Quantum\Base\FileStore\FileStoreException; use Packaged\Config\ConfigurableInterface; interface FileStoreInterface extends ConfigurableInterface { /** * @param $relativePath * * @return FileStoreObjectInterface[] * @throws FileStoreException */ public function list(string $relativePath): array; public function store(string $relativePath, $data, array $metadata): bool; public function mkdir(string $relativePath): bool; public function delete(string $relativePath): bool; public function retrieve(string $relativePath): string; public function rename(string $fromRelativePath, string $toRelativePath): bool; public function copy(string $fromRelativePath, string $toRelativePath): bool; public function getObject(string $relativePath): FileStoreObjectInterface; }
Markdown
UTF-8
4,649
2.78125
3
[]
no_license
--- description: "recipes for Pepperoni pizza | how to make good Pepperoni pizza" title: "recipes for Pepperoni pizza | how to make good Pepperoni pizza" slug: 445-recipes-for-pepperoni-pizza-how-to-make-good-pepperoni-pizza date: 2020-09-17T10:50:30.615Z image: https://img-global.cpcdn.com/recipes/c0f41605fe1111cf/751x532cq70/pepperoni-pizza-recipe-main-photo.jpg thumbnail: https://img-global.cpcdn.com/recipes/c0f41605fe1111cf/751x532cq70/pepperoni-pizza-recipe-main-photo.jpg cover: https://img-global.cpcdn.com/recipes/c0f41605fe1111cf/751x532cq70/pepperoni-pizza-recipe-main-photo.jpg author: Seth Pittman ratingvalue: 4.3 reviewcount: 9 recipeingredient: - "1 pack Beef peperoni" - "1 can pineapple slices" - "1 pack mozarella cheese" - "1 can pizza sauce" - " For the dough i just brought some ready made from the supermarket it cost 15aed for 6pcsmedium size dough and for this peperoni pizza and its ingredients you can make it up to 2pizzasenjoy" recipeinstructions: - "First you have to prepare all the ingredients,the dough is ready made so it might be frozen so you need to keep it warm like 3mins in the oven before you put on the rest of the ingredients.." - "Add on some pizza sauce according to your desire" - "Add on the beff peperoni" - "The pineapple" - "And finally the mozarella cheese" - "After adding all the ingredients put it inside the oven around 10mins and your DONE!☺️😁🙂" categories: - Recipe tags: - pepperoni - pizza katakunci: pepperoni pizza nutrition: 286 calories recipecuisine: American preptime: "PT31M" cooktime: "PT50M" recipeyield: "3" recipecategory: Dinner --- ![Pepperoni pizza](https://img-global.cpcdn.com/recipes/c0f41605fe1111cf/751x532cq70/pepperoni-pizza-recipe-main-photo.jpg) Hey everyone, it is me, Dave, welcome to my recipe site. Today, we're going to make a distinctive dish, pepperoni pizza. One of my favorites. This time, I will make it a little bit tasty. This will be really delicious. Pepperoni pizza is one of the most favored of recent trending foods on earth. It's simple, it's quick, it tastes yummy. It's appreciated by millions every day. Pepperoni pizza is something that I've loved my entire life. They're nice and they look fantastic. Who makes the best pepperoni pizza? My kids love pizza, so pepperoni pizza is usually a surefire dinner win. But if I&#39;m being honest, I How to Make Pepperoni Pizza. To begin with this particular recipe, we must prepare a few components. You can cook pepperoni pizza using 5 ingredients and 6 steps. Here is how you cook it. <!--inarticleads1--> ##### The ingredients needed to make Pepperoni pizza: 1. Get 1 pack Beef peperoni 1. Take 1 can pineapple slices 1. Make ready 1 pack mozarella cheese 1. Get 1 can pizza sauce 1. Take For the dough i just brought some ready made from the supermarket it cost 15aed for 6pcs.medium size dough and for this peperoni pizza and its ingredients you can make it up to 2pizzas..😋enjoy! Find pepperoni pizza stock images in HD and millions of other royalty-free stock photos, illustrations and vectors in the Shutterstock collection. Pizza Pepperoni is the authentic Italian taste. Cook this classic Pepperoni pizza in Ooni pizza ovens. The spicy pepperoni paired with creamy mozzarella is an instant crowd-pleaser. <!--inarticleads2--> ##### Steps to make Pepperoni pizza: 1. First you have to prepare all the ingredients,the dough is ready made so it might be frozen so you need to keep it warm like 3mins in the oven before you put on the rest of the ingredients.. 1. Add on some pizza sauce according to your desire 1. Add on the beff peperoni 1. The pineapple 1. And finally the mozarella cheese 1. After adding all the ingredients put it inside the oven around 10mins and your DONE!☺️😁🙂 Peperoni Pizzeria is an Italian restaurant serving rustic Italian cuisine such as wood fired thin crust pizzas and pastas. Each outlet has an in-house bar, serving a stellar collection of wines. For the pizza dough, place the flour, yeast and salt into a large mixing bowl and stir to combine. I love super crispy pizza and those pizza pans with holes really work! I was reading the Pepperoni Pizza recipe it didn&#39;t say anything about putting oil on the dough or in the bowl is it necessary? So that's going to wrap this up for this Good food pepperoni pizza recipe. Thank you very much for your time. I am confident that you can make this at home. There is gonna be more interesting food at home recipes coming up. Don't forget to bookmark this page in your browser, and share it to your family, friends and colleague. Thank you for reading. Go on get cooking!
PHP
UTF-8
1,735
2.65625
3
[]
no_license
<?php use Illuminate\Database\Seeder; class RecipeSeed extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $recipes = [ [ 'name' => 'Lemon Chicken', 'cooking_time' => 30, 'image' => '/images/recipes/lemon_chicken.png', 'ingredients' => [ [4, 'Chicken Breasts'], ['1 tsp', 'Thyme'], [1, 'Lemon'] ] ], [ 'name' => 'Beef Stroganoff', 'cooking_time' => 30, 'image' => '/images/recipes/beef_stroganoff.png', 'ingredients' => [ [1, 'Beef'], [1, 'Mustard'], [1, 'Mushroom'] ] ], [ 'name' => 'Chicken Caesar Salad', 'cooking_time' => 25, 'image' => '/images/recipes/caesar_salad.png', 'ingredients' => [ [1, 'Lettuce'], [2, 'Chicken'], [1, 'Parmesan'] ] ] ]; foreach ($recipes as $recipe) { $model = App\Recipe::create([ 'name' => $recipe['name'], 'cooking_time' => $recipe['cooking_time'], 'image' => $recipe['image'] ]); foreach ($recipe['ingredients'] as $ingredient) { $model->ingredients()->create([ 'quantity' => $ingredient[0], 'name' => $ingredient[1] ]); } } } }
C++
UTF-8
481
3
3
[]
no_license
#include<iostream> using namespace std; int main(){ int i,n; cout<<"The time taken by worker in hours(enter bet 2h to 5h more):\n"; cin>>n; if(3>n && n>=2 ) cout<<"the worker is highly efficient. \n"; else if(4>n && n>=3 ) cout<<"the worker is improve speed. \n"; else if(5>n && n>=4 ) cout<<"the worker is given training to improve his speed. \n"; else cout<<"the worker has to leave the company. \n"; }
Java
UTF-8
12,684
2.125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package regis_klinik; /** * * @author User */ public class GUI_RegisKlinik extends javax.swing.JFrame { /** * Creates new form GUI_RegisKlinik */ public GUI_RegisKlinik() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { kolomNama = new javax.swing.JTextField(); kolomUltah1 = new javax.swing.JComboBox<>(); kolomUltah2 = new javax.swing.JComboBox<>(); kolomUltah3 = new javax.swing.JComboBox<>(); kolomUmur = new javax.swing.JTextField(); kolomID = new javax.swing.JTextField(); kolomDokter = new javax.swing.JComboBox<>(); rLakilaki = new javax.swing.JRadioButton(); rPerempuan = new javax.swing.JRadioButton(); kolomDaftar = new javax.swing.JButton(); kolomReset = new javax.swing.JButton(); kolomHarga = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); kolomReport = new javax.swing.JTextArea(); jLabel3 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); kolomNama.setBackground(new java.awt.Color(204, 204, 255)); getContentPane().add(kolomNama, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 180, 180, 30)); kolomUltah1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Tgl", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31" })); getContentPane().add(kolomUltah1, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 240, 50, 30)); kolomUltah2.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Bln", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" })); getContentPane().add(kolomUltah2, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 240, 60, 30)); kolomUltah3.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Thn", "1980", "1982", "1983", "1985", "1986", "1988", "1989", "1991", "1992", "1994", "1995", "1997", "1998", "2000", "2001", "2003", "2004", "2006", "2007", "2009", "2010", "2012", "2013", "2015", "2016", "2018", "2019" })); getContentPane().add(kolomUltah3, new org.netbeans.lib.awtextra.AbsoluteConstraints(260, 240, 70, 30)); kolomUmur.setBackground(new java.awt.Color(204, 204, 255)); getContentPane().add(kolomUmur, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 300, 180, 30)); kolomID.setBackground(new java.awt.Color(204, 204, 255)); getContentPane().add(kolomID, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 370, 180, 30)); kolomDokter.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Pilih", "Dokter Rafi (BPJS)", "Dokter Intan (Umum)", "Dokter Roland (Spesialis)", "Dokter Ana (Gigi)" })); getContentPane().add(kolomDokter, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 440, 180, 30)); rLakilaki.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { rLakilakiActionPerformed(evt); } }); getContentPane().add(rLakilaki, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 500, -1, -1)); rPerempuan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { rPerempuanActionPerformed(evt); } }); getContentPane().add(rPerempuan, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 540, -1, -1)); kolomDaftar.setFont(new java.awt.Font("Berlin Sans FB", 0, 24)); // NOI18N kolomDaftar.setForeground(new java.awt.Color(0, 0, 153)); kolomDaftar.setText("DAFTAR"); kolomDaftar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { kolomDaftarActionPerformed(evt); } }); getContentPane().add(kolomDaftar, new org.netbeans.lib.awtextra.AbsoluteConstraints(260, 510, 130, 50)); kolomReset.setFont(new java.awt.Font("Berlin Sans FB", 0, 24)); // NOI18N kolomReset.setForeground(new java.awt.Color(0, 0, 153)); kolomReset.setText("RESET"); kolomReset.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { kolomResetActionPerformed(evt); } }); getContentPane().add(kolomReset, new org.netbeans.lib.awtextra.AbsoluteConstraints(420, 510, 140, 50)); kolomHarga.setFont(new java.awt.Font("Berlin Sans FB Demi", 1, 18)); // NOI18N kolomHarga.setBorder(new javax.swing.border.MatteBorder(null)); kolomHarga.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { kolomHargaActionPerformed(evt); } }); getContentPane().add(kolomHarga, new org.netbeans.lib.awtextra.AbsoluteConstraints(390, 220, 170, 50)); jLabel2.setBackground(new java.awt.Color(204, 204, 255)); jLabel2.setFont(new java.awt.Font("Berlin Sans FB", 0, 24)); // NOI18N jLabel2.setForeground(new java.awt.Color(255, 153, 0)); jLabel2.setText("ADMINISTRASI"); getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 180, 150, 50)); kolomReport.setColumns(20); kolomReport.setRows(5); kolomReport.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jScrollPane1.setViewportView(kolomReport); getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 310, 220, 150)); jLabel3.setFont(new java.awt.Font("Berlin Sans FB", 0, 24)); // NOI18N jLabel3.setForeground(new java.awt.Color(255, 153, 0)); jLabel3.setText("REPORT"); getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(430, 280, -1, -1)); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/regis_klinik/TA.jpg"))); // NOI18N getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1)); pack(); }// </editor-fold>//GEN-END:initComponents private void rLakilakiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rLakilakiActionPerformed // TODO add your handling code here: }//GEN-LAST:event_rLakilakiActionPerformed private void rPerempuanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rPerempuanActionPerformed // TODO add your handling code here: }//GEN-LAST:event_rPerempuanActionPerformed private void kolomResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_kolomResetActionPerformed // TODO add your handling code here: kolomNama.setText(""); kolomUltah1.setSelectedItem("Tgl"); kolomUltah2.setSelectedItem("Bln"); kolomUltah3.setSelectedItem("Thn"); kolomUmur.setText(""); kolomID.setText(""); kolomDokter.setSelectedItem("Pilih"); rPerempuan.setText(""); rLakilaki.setText(""); kolomReport.setText(""); kolomHarga.setText(""); }//GEN-LAST:event_kolomResetActionPerformed private void kolomDaftarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_kolomDaftarActionPerformed // TODO add your handling code here: String nama = kolomNama.getText(); int tanggal = kolomUltah1.getSelectedIndex(); int bulan = kolomUltah2.getSelectedIndex(); int tahun = kolomUltah3.getSelectedIndex(); String usia = kolomUmur.getText(); String ID = kolomID.getText(); int dokter = kolomDokter.getSelectedIndex(); String data = kolomHarga.getText(); String JK; if (rPerempuan.isSelected()){ JK = "Perempuan"; }else { JK = "Laki-Laki"; } int harga = 0; int total = 0; switch(dokter){ case (0): harga = 0; break; case (1): harga = 0; break; case (2): harga = 75000; break; case (3): harga = 200000; break; case (4): harga = 335000; } total = harga; kolomHarga.setText(" Rp. "+total); kolomReport.setText("Nama Pasien : "+nama+" \nTanggal Lahir: "+kolomUltah1.getItemAt(tanggal)+" "+kolomUltah2.getItemAt(bulan)+" "+kolomUltah3.getItemAt(tahun)+" \nUsia : "+usia+" \nJenis Kelamin : "+JK+" \nNo ID : "+ID+" \nTrimakasih "+nama+" Sudah Mendaftar \nMohon Tunggu Panggilan dari "+kolomDokter.getItemAt(dokter)); }//GEN-LAST:event_kolomDaftarActionPerformed private void kolomHargaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_kolomHargaActionPerformed // TODO add your handling code here: }//GEN-LAST:event_kolomHargaActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(GUI_RegisKlinik.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(GUI_RegisKlinik.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(GUI_RegisKlinik.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(GUI_RegisKlinik.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new GUI_RegisKlinik().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JButton kolomDaftar; private javax.swing.JComboBox<String> kolomDokter; private javax.swing.JTextField kolomHarga; private javax.swing.JTextField kolomID; private javax.swing.JTextField kolomNama; private javax.swing.JTextArea kolomReport; private javax.swing.JButton kolomReset; private javax.swing.JComboBox<String> kolomUltah1; private javax.swing.JComboBox<String> kolomUltah2; private javax.swing.JComboBox<String> kolomUltah3; private javax.swing.JTextField kolomUmur; private javax.swing.JRadioButton rLakilaki; private javax.swing.JRadioButton rPerempuan; // End of variables declaration//GEN-END:variables }
Python
UTF-8
1,240
2.578125
3
[]
no_license
#! /usr/bin/env python #coding=utf-8 import os import sys import datetime def traverse(path): if os.path.isfile(path): analysis(path) else: for temp in os.listdir(path): traverse(path + os.sep + temp) def analysis(path): file_name = os.path.split(path)[1] if is_legal_log(file_name): file = open(path, 'r') try: for line in file: print line finally: file.close() def is_legal_log(file_name): ''' (1) file_name must start with 'host.access.log' (2) file must be today's or yesterday's log file ''' today = datetime.date.today() oneday = datetime.timedelta(days=1) yesterday = today - oneday if file_name.startswith('host.access.log'): tail = os.path.splitext(file_name)[1][1:9] if tail == today.strftime('%Y%m%d') \ or tail == yesterday.strftime('%Y%m%d'): return True def get_data(line): '''return useful data from line''' return '' def record(data): '''record data''' pass def generate_result_file(): pass def send_result(result_file): pass if __name__ == '__main__': traverse('d:/opt/log1/nginx_log/') is_legal_log('')
Shell
UTF-8
1,411
3.34375
3
[]
no_license
#!/bin/bash export BENCHMARK_NAME=ls export BENCHMARK_DIR=$CHISEL_BENCHMARK_HOME/benchmark/bsysi_$BENCHMARK_NAME export SRC=$BENCHMARK_DIR/$BENCHMARK_NAME.c export ORIGIN_BIN=$BENCHMARK_DIR/$BENCHMARK_NAME.origin export REDUCED_BIN=$BENCHMARK_DIR/$BENCHMARK_NAME.reduced export TIMEOUT="-k 1 1" export LOG=$BENCHMARK_DIR/log.txt export TESTENV=$BENCHMARK_DIR/testenv source $CHISEL_BENCHMARK_HOME/benchmark/test-base-make.sh function clean() { rm -rf $TESTENV return 0 } function test(){ FILE=$1 ARGS=$2 diff -q \ <(timeout $TIMEOUT $ORIGIN_BIN $ARGS "$FILE") \ <(timeout $TIMEOUT $REDUCED_BIN $ARGS "$FILE") \ >&/dev/null || return 1 return 0 } # -l Long listing format # -S Sort by size # -R List subdirectories recursively # -h with -l and -s, print sizes like 1K 234M 2G etc. # -a list hidden files as well function create_test_env(){ mkdir -p $TESTENV/{1..4}/{1..4} touch $TESTENV/{1,2}/{a,b} $TESTENV/{3,4}/{3,4}/{c,d} echo "dummytext dummytext dummytext dummytext dummytext" >> $TESTENV/4/4/d } function desired() { create_test_env test "." || return 1 test "$TESTENV" "-l" || return 1 test "$TESTENV" "-S" || return 1 test "$TESTENV" "-R" || return 1 test "$TESTENV" "-h" || return 1 test "$TESTENV" "-a" || return 1 return 0 } function undesired() { # TODO return 0 } function desired_disaster() { # TODO return 0 } # main desired
Java
UTF-8
367
2.140625
2
[ "Apache-2.0" ]
permissive
package com.kit181.yakov777; import java.util.ArrayList; public interface Gamer { String getName(); void setName(String name); String getSide(); void setSide(String side); int getWins(); void addWins(); void clearWins(); void clearHits(); ArrayList<Integer> getHits(); void setHits(int position); int getColor(); }
Java
UTF-8
953
2.609375
3
[ "Apache-2.0" ]
permissive
package com.vaadin.tests.components.datefield; import java.util.Calendar; import java.util.Locale; import com.vaadin.tests.components.TestBase; import com.vaadin.ui.DateField; public class CustomDateFormat extends TestBase { @Override protected void setup() { Locale locale = new Locale("fi", "FI"); Calendar cal = Calendar.getInstance(); cal.set(2010, 0, 1); DateField df = new DateField(); df.setResolution(DateField.RESOLUTION_DAY); df.setLocale(locale); df.setWidth("300px"); String pattern = "d. MMMM'ta 'yyyy 'klo 'H.mm.ss"; df.setDateFormat(pattern); df.setValue(cal.getTime()); addComponent(df); } @Override protected String getDescription() { return "Month name should be visible in text box if format pattern includes it"; } @Override protected Integer getTicketNumber() { return 3490; } }
Swift
UTF-8
1,241
2.828125
3
[ "MIT" ]
permissive
// // SWXMLSelectMapping.swift // SWXMLMapping // // Created by Samuel Williams on 12/02/16. // // import Foundation @objc(SWXMLSelection) public protocol SWXMLSelection { init(attributes: [String : String]!, mapping: SWXMLMapping) func mapObject(_ object: Any!, withKeyPath keyPath: String!) -> AnyObject! } /* This mapping allows you to make a selection by instantiating a class which manages the query against a object/keyPath relationship. The result is essentially a collection of items. <select keyPath="property"> */ @objc(SWXMLSelectMapping) open class SWXMLSelectMapping: SWXMLMemberMapping { let mappingClass: SWXMLSelection.Type override init!(tag: String!, keyPath: String!, attributes: [String : String]!) { mappingClass = NSClassFromString(attributes["class"]!) as! SWXMLSelection.Type super.init(tag: tag, keyPath: keyPath, attributes: attributes) } override open func serializedObjectMember(_ object: Any!, with mapping: SWXMLMapping!) -> String! { let mappingObject = mappingClass.init(attributes: self.attributes, mapping: mapping) let mappedObject = mappingObject.mapObject(object, withKeyPath: self.keyPath) return SWXMLTags.tagNamed(self.tag, forValue: mapping.serializeObject(mappedObject)) } }
Markdown
UTF-8
10,457
3.71875
4
[]
no_license
# Whiteboard Challenge Workflow This file contains details on what is expected when completing a whiteboard challenge. Please refer to the visual as a guideline to what content is required for each whiteboarding challenge. ![Example Whiteboard Image](./DataStructuresWhiteboard.PNG) ## Overall Guidance on Whiteboard Workflow The steps in this document are meant to show you one solid workflow. It's a structure that works for most people to help them solve whiteboarding problems effectively. As you get started doing whiteboards, we suggest that you stick to the steps we recommend, in the order that we recommend. Once you gain more confidence in the process of whiteboard interviewing, you are welcome to deviate from this process *at your own risk*. If you find that pieces of the process do not work well for you, or make more sense in a different order, that's allowed! And during an interview, you should always be prepared for an interviewer to ask you to complete steps in a different order than you're used to, or to ask you to clarify your thinking even when your normal process would move on. Listening to and working with your interviewer is always the best option, and you should expect that not every whiteboard interview will go the same way. For an example of an instructor solving a whiteboard (quickly) with a modified version of this process, see [this YouTube video](https://youtu.be/9KAy1AampQc?t=1386){:target="_blank"}. ### 1. Problem Domain Re-iterate the problem domain that you have been asked. This can be done either verbatim from the initial question, or a summary in your own words, whatever makes more sense to you. ### 2. Visual Draw out what the problem domain is and visually solve the problem. Label all of the appropriate properties, define your input and output, and show how you will approach the problem towards a solution. (It's common for people to switch up the ordering on visuals/problem domain depending on the problem; sometimes, drawing a picture helps you understand the problem better, at which point you can write out the problem domain.) ### 3. Algorithm The algorithm is a breakdown of what you need to achieve. This should be a bulleted list or a general overview of what you plan to implement later in the interview. The most practical way of creating an algorithm is often to focus on the example input/output in your visual. You should consider the steps that your algorithm will take to use the input in moving towards the output. This process of working through the problem yourself, and noticing the steps you take along the way, should naturally help you flesh out the steps that will be part of your algorithm. ### 4. Big O Analyze the space AND time efficiency of the algorithm that you just proposed. You should revisit this analysis throughout the interview as you make updates to your algorithm during pseudocode/code/stepthrough. ### 5. Pseudocode Write out pseudocode that defines your algorithm! Use the [pseudocode cheat sheet](./Pseudocode){:target="_blank"} as a guideline to what symbols are acceptable. ### 6. Code Write out syntactically correct code in the language of your course to solve the problem presented. Your real code should be based off of your pseudocode. ### 7. Test There are two main parts to testing. First, walk through both the problem domain and your solution to make sure that it both works and is efficient. This should be a careful, line-by-line stepthrough of your code, where you track variables in a written table along the way. It's very normal to start the stepthrough, realize that you have a bug in your code, and go back to your code to try and fix the bug; in this case, make sure to go back to careful stepthrough for any modified parts of your code. Secondly, you should talk about how you would test this code if you were writing unit tests. This means listing out a variety of test cases; your goal is to show the interviewer that you know what kinds of tests are useful to ensure that a function is working. At a minimum, you want to list out: - a standard input and output - a standard input that has a different output than your first listed i/o - some edge cases in how the data is structured; you'll probably list several of these (the array is already sorted! the tree is very unbalanced! the string is just the character 'a' twelve times! etc.) - the input is null/negative/zero (the "normal" edge cases) ## Examples of What That Looks Like In the best possible interview, you might have all of the ideas that you need and be able to move in this perfect linear order. In most interviews, though, you won't have that perfect flow from step 1 linearly through to step 7. While no two interviews will look the same, here is one example of a normal interview process: - Step 1: You write down the problem domain as the interviewer reads the problem to you. - Step 2: You draw a picture of what that input will look like and write down what you think the output will be. - Step 1 Again: The interviewer corrects you: your proposed output is incorrect. You revisit the problem domain. - Step 2 Again: Now that you understand the problem better, you come up with a more representative visual. - Steps 2 And 3: You develop your algorithm. You show with arrows in your visual how you'll transform the input into the output, and write down a bulleted list of steps as you go. - Step 4: You analyze the runtime and space complexity of the algorithm you just proposed, using big O notation. - Step 4.5: The interviewer asks you why you've chosen to use a particular data structure instead of some other choice, and how that impacts your runtime and space complexity. You reason through the use of that data structure vs. alternatives verbally with the interviewer, and decide your choice of data structure was good, and you'll continue using it. - Step 5: You decide your algorithm has some ambiguity, so you start writing pseudocode that matches your algorithm. - Step "Oh No": You realize which part of your algorithm was imprecise; there's more going on in this problem than you realized. You go back to your visual and algorithm and try to work through how this new realization fits in. - Steps 2 And 3 And 4 Again: You figure out how you'll work through this issue, and add that into your arrows and your bullet points. Since you've changed your approach, you also change your estimate of the runtime/space complexity. - Step 5 Again: You keep working through your pseudocode. - Step 6: You write out syntactically correct code that matches your pseudocode. - Step 7: You start stepping through your example input from Step 2, walking through your syntactically correct code line by line. - Step "Oh No" Again: You realize as you step through that your code doesn't actually generate the output that you expected. - Step 6 Again: You debug your code and get it working on your example input. - Step 4 Again: Since you changed your code while debugging, you re-analyze runtime/space complexity. - Step 6 Again: You finish your stepthrough on the example input, and it's now generating the correct output. - Step 7, Continued: You list out test cases that you would want to test this program on. - Step 8: Whatever your interviewer says! ## Advanced Whiteboard Interviewing: Making this process your own After practicing whiteboard interviews, many people find that they want to modify this process. Here are some common things students want to do, and our analysis of those options. ### Skipping or Shortening the Problem Domain It's possible to have a successful whiteboard without writing the problem domain on the whiteboard first. It's often okay to just write a few notes of the important pieces of the problem and use a visual with example input/output to verify with your interviewer that you understand the problem. Be aware that some interviewers will not correct you if you are working on the wrong problem, so it is *extremely* important that you verify the problem domain verbally, even if you don't write it on the whiteboard. ### Shortening Algorithm, Pseudocode, and Actual Code We include all 3 of algorithm/pseudocode/actual code because, for many people, each of those steps helps to refine their algorithm. The first iteration of the algorithm helps get ideas of thoughts down on the whiteboard; the second iteration helps ensure that those ideas will translate well into code; and the third iteration allows you to focus on your language's syntax. If you are a person who writes an extremely exact code-like algorithm, or if you are very comfortable with your language's syntax, you may find that the pseudocode step slows you down without providing any benefits. In that case, it's fine to skip the pseudocode step. ### "Skipping Around" between Algorithm and Actual Code **It is almost always a bad idea** to figure out half of your algorithm, write code for that half of your algorithm, and then figure out the rest of your algorithm. If you have half a strategy, but have no idea how to do the second half, you'll often need to change the first half of your strategy once you figure out a complete algorithm. You run the risk of coming up with the start of your strategy, taking the time to write out code for that part of your strategy, coming back to thinking about your strategy, and realizing you need a different strategy and no longer need the code that you wrote. It's best to have some idea of how you'll solve the entire problem before you start writing code. There's one exception: sometimes you have the majority of your algorithm, and you're confident it will work, but you're not sure about some small piece (whether the loop should run n or n-1 times, or whether to use a HashTable or a HashSet, or something else insignificant compared to the "interesting" part of the algorithm). In that case, writing out your code and then coming back to the tiny-question afterwards is usually a good strategy; a good stepthrough will help you know the right solution. ## Writing Headings on the Whiteboard Some people love writing the headings "Problem Domain", "Visual", etc. on the whiteboard to help them remember the steps they want to take. Other people find that feels robotic, and that they naturally flow among different parts of the whiteboard during problem solving. Either strategy is reasonable, as long as you're consistent (either lots of headings, or no headings).
Python
UTF-8
1,032
3.359375
3
[]
no_license
from sets import Set from sets engineers = Set(['Saketh', 'Jana', 'Vachan', 'Aura']) print (engineers) programmers = Set(['Vachan', 'Sama', 'Dheer', 'Aura']) print (programmers) managers = Set(['Jana', 'Vachan', 'Dheer', 'Achyu']) print (managers) employees = engineers | programmers | managers # union print (employees) engineering_management = engineers & managers # intersection print (engineering_management) fulltime_management = managers - engineers - programmers # difference print (fulltime_management) engineers.add('Dilip') # add element print (engineers) print ("employees issuperset of engineers", employees.issuperset(engineers)) print (employees) employees.update(engineers) # update from another set print (employees) print ("employees issuperset of engineers", employees.issuperset(engineers)) for group in [engineers, programmers, managers, employees]: group.discard('Achyu') # unconditionally remove element print (group)
Java
UTF-8
757
2.09375
2
[]
no_license
package com.kwws.view.actionbar; import android.view.View; /** * MyActionBar事件监听器 * * @author Kw */ public interface OnMyActionBarClickListener { /** * 后退按钮事件 * * @param view * @return 返回true时关闭当前Activity */ boolean onBackButtonClick(View view); /** * 搜索按钮事件 * * @param view */ void onQueryButtonClick(View view); /** * 新建按钮事件 * * @param view */ void onNewButtonClick(View view); /** * 更多按钮事件 * * @param view */ void onMoreButtonClick(View view); /** * 文本按钮事件 * * @param view */ void onTextButtonClick(View view); }
C++
UTF-8
3,392
3.125
3
[]
no_license
#include "Shader.h" #include <fstream> #include <string> #include <vector> Shader::Shader(const char* vertFilePath, const char* fragFilePath) { m_ProgramID = glCreateProgram(); std::string vertexSource = ReadInFile(vertFilePath); std::string fragmentSource = ReadInFile(fragFilePath); AddToProgram(GL_VERTEX_SHADER, vertexSource.c_str()); AddToProgram(GL_FRAGMENT_SHADER, fragmentSource.c_str()); glLinkProgram(m_ProgramID); glValidateProgram(m_ProgramID); } Shader::~Shader() { glDeleteProgram(m_ProgramID); } void Shader::Use() const { glUseProgram(m_ProgramID); } void Shader::Unuse() const { glUseProgram(0); } std::string Shader::ReadInFile(const char* filePath) { std::string fileContent; std::ifstream fileStream(filePath, std::ios::in); assert(fileStream.is_open() && "Could not read file: {0}", filePath); std::string line = ""; while (!fileStream.eof()) { std::getline(fileStream, line); fileContent.append(line + "\n"); } fileStream.close(); return fileContent; } void Shader::AddToProgram(GLenum shaderType, const char* shaderSource) { GLuint shaderID = CompileProgram(shaderType, shaderSource); glAttachShader(m_ProgramID, shaderID); glDeleteShader(shaderID); } GLuint Shader::CompileProgram(GLenum type, const char* source) { // Necessary because OpenGL needs a raw string const char* shaderSource = source; GLuint shaderID = glCreateShader(type); glShaderSource(shaderID, 1, &shaderSource, NULL); glCompileShader(shaderID); /* ERROR HANDLING */ GLint compiled; // Returns the compile status from the shader and stores it into compiled glGetShaderiv(shaderID, GL_COMPILE_STATUS, &compiled); // OpenGL checks if the shader compile status is false if (compiled == GL_FALSE) { // Queries the error message length of the shader GLint length; glGetShaderiv(shaderID, GL_INFO_LOG_LENGTH, &length); // Gets and prints the actual log std::vector<GLchar> errorMsg(length); glGetShaderInfoLog(shaderID, length, NULL, &errorMsg[0]); assert(false, errorMsg.data()); } return shaderID; } void Shader::SetBool(const char* uniform, const bool b) { GLuint location = glGetUniformLocation(m_ProgramID, uniform); glUniform1i(location, b); } void Shader::SetInt(const char* uniform, int i) { GLuint location = glGetUniformLocation(m_ProgramID, uniform); glUniform1i(location, i); } void Shader::SetUint(const char* uniform, const unsigned int i) { GLuint location = glGetUniformLocation(m_ProgramID, uniform); glUniform1ui(location, i); } void Shader::SetFloat(const char* uniform, const float f) { GLuint location = glGetUniformLocation(m_ProgramID, uniform); glUniform1f(location, f); } void Shader::SetVec3(const char* uniform, const glm::vec3& vec) { GLuint location = glGetUniformLocation(m_ProgramID, uniform); glUniform3fv(location, 1, &vec[0]); } void Shader::SetVec4(const char* uniform, const glm::vec4& vec) { GLuint location = glGetUniformLocation(m_ProgramID, uniform); glUniform4fv(location, 1, &vec[0]); } void Shader::SetMat3(const char* uniform, const glm::mat3& mat) { GLuint location = glGetUniformLocation(m_ProgramID, uniform); glUniformMatrix3fv(location, 1, GL_FALSE, &mat[0][0]); } void Shader::SetMat4(const char* uniform, const glm::mat4& mat) { GLuint location = glGetUniformLocation(m_ProgramID, uniform); glUniformMatrix4fv(location, 1, GL_FALSE, &mat[0][0]); }
C#
UTF-8
1,331
3.265625
3
[]
no_license
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; /** * @Author: Churong Zhang * @Email: churong.zhang@utdallas.edu * @Date: 4/10/2020 * This is the comparer for the list view */ namespace Multithreaded_Text_Search { class ListViewItemCompare : IComparer { private SortOrder order; public ListViewItemCompare() { // default sorting to be ascending order = SortOrder.Ascending; } public ListViewItemCompare(bool decending) { // set the sorting order if (decending) order = SortOrder.Descending; else order = SortOrder.Ascending; } public int Compare(object x, object y) { int ret = -1; ListViewItem x1 = (ListViewItem)x; ListViewItem x2 = (ListViewItem)y; // get the int value and compare them int v1 = int.Parse(x1.SubItems[0].Text); int v2 = int.Parse(x2.SubItems[0].Text); ret = v1 - v2; // negate it if is descending if (order == SortOrder.Descending) ret = -ret; return ret; } } }
Python
UTF-8
423
4.03125
4
[]
no_license
# Program takes in input of persons height and weight # and then outputs the calculated Body Mass Index # Author: Oisin Casey height = int(input("Please enter your height in cm: ")) weight = int(input("Please enter your weight in kg: ")) bmi = weight / height #next line formats the variable bmi into a string with two numbers after the decimal point formattedBmi = "{:.2f}".format(bmi) print ("BMI is: " + formattedBmi + ".")
C#
UTF-8
484
2.765625
3
[]
no_license
/*using System.Linq; using static System.Linq.Enumerable; using static System.String; public static class Kata { public static string GenerateShape(int n) { return Join('\n', Range(0, n).Select(_ => Concat(Repeat('+', n)))); } }*/ using static System.Linq.Enumerable; using static System.String; public static class Kata { public static string GenerateShape(int n) { return Join('\n', Repeat(new string('+', n), n)); } }
C#
UTF-8
1,834
3.65625
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Item44bExercises { class Program { static void grade() { Console.WriteLine("Enter students quiz score as a number out of 100 with no % :"); int quiz = int.Parse(Console.ReadLine()); Console.WriteLine("Enter students midterm score as a number out of 100 with no % :"); int midterm = int.Parse(Console.ReadLine()); Console.WriteLine("Enter students final score as a number out of 100 with no % :"); int final = int.Parse(Console.ReadLine()); int finalgrade = (quiz + midterm + final) / (3); if (finalgrade >= 90) { Console.WriteLine("The student's final grade of {0}% gets them an A in the class.", finalgrade); } else if (finalgrade >= 80 && finalgrade < 90) { Console.WriteLine("The student's final grade of {0}% gets them a B in the class.", finalgrade); } else if (finalgrade >= 70 && finalgrade < 80) { Console.WriteLine("The student's final grade of {0}% gets them a C in the class.", finalgrade); } else if (finalgrade >= 60 && finalgrade < 70) { Console.WriteLine("The student's final grade of {0}% gets them a D in the class.", finalgrade); } else if (finalgrade < 60) { Console.WriteLine("Ouch, the student's final grade of {0}% gets them an F in the class.", finalgrade); } } static void Main(string[] args) { Program.grade(); } } }
Python
UTF-8
680
3.53125
4
[]
no_license
# basic class Master(object): def __init__(self) -> None: # super().__init__() self.kongfu = "Master cook method" def make_cook(self): print(f'use {self.kongfu} make') class School(object): def __init__(self) -> None: self.kongfu = "School cook method" def make_cook(self): print(f'use {self.kongfu} make') # derived class Prentice(Master, School): pass p = Prentice() # visit instance property print(p.kongfu) # visit instance method p.make_cook() """ Master cook method use Master cook method make 注意:当⼀个类有多个⽗类的时候,默认使用第⼀个⽗类的同名属性和⽅法 """
C++
UTF-8
1,999
3.015625
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> #include <unordered_map> using namespace std; int minCutUtilDP( int startIdx, int endIdx, string A, vector<vector<bool>>& palindromeOrNotMap, vector<vector<int>>& DPStringByIndexesMap ){ if( DPStringByIndexesMap[startIdx][endIdx] != A.size() ) return DPStringByIndexesMap[startIdx][endIdx]; if( palindromeOrNotMap[startIdx][endIdx] == true ){ DPStringByIndexesMap[startIdx][endIdx] = 0; return 0; } int min = numeric_limits<int>::max(); for( int i=startIdx; i<endIdx; i++ ){ int currMinCutDP = 1; currMinCutDP += minCutUtilDP( startIdx, i, A, palindromeOrNotMap, DPStringByIndexesMap ); currMinCutDP += minCutUtilDP( i+1, endIdx, A, palindromeOrNotMap, DPStringByIndexesMap ); if( currMinCutDP < min ) min = currMinCutDP; } DPStringByIndexesMap[startIdx][endIdx] = min; return min; } int minCut(string A) { unsigned long int n = A.size(); vector<vector<bool>> palindromeOrNotMap( n, vector<bool>( n, false ) ); for( int i=0; i<n; i++ ) palindromeOrNotMap[i][i] = true; for( int size=2; size <= n; size++ ){ for( int startIdx=0; startIdx < n-size+1; startIdx++ ){ int endIdx = startIdx + size -1; if( size == 2 ) palindromeOrNotMap[startIdx][endIdx] = ( A[startIdx] == A[endIdx] ); else palindromeOrNotMap[startIdx][endIdx] = ( A[startIdx] == A[endIdx] ) && palindromeOrNotMap[startIdx+1][endIdx-1]; } } vector<vector<int>> DPStringByIndexesMap( n, vector<int>(n, (const int &) n) ); return minCutUtilDP(0, (int) (n - 1), A, palindromeOrNotMap, DPStringByIndexesMap ); } int main() { string A = "ababbbabbababa"; // => a | babbbab | b | ababa ---> total = 3 cout<<"Ans: "<<minCut( A )<<endl; string B = "dVGAaVO25EmT6W3zSTEA0k12i64Kkmmli09Kb4fArlF4Gc2PknrlkevhROxUg"; // 59 -> TLE Case cout<<"Ans: "<<minCut( B )<<endl; return 0; }
TypeScript
UTF-8
538
2.71875
3
[]
no_license
import { Request } from 'express'; import { IParamBinder } from './param-binder.interface'; import { IValueParser } from './types'; export class CookieParamBinder implements IParamBinder { private readonly name: string; private readonly valueParser: IValueParser; public constructor(name: string, valueParser: IValueParser) { this.name = name; this.valueParser = valueParser; } public extractValue(req: Request): { [key: string]: unknown } { return { [this.name]: this.valueParser(req.cookies[this.name]) }; } }
Java
UTF-8
737
2.171875
2
[]
no_license
package action; import mybean.UserLogin; import javax.servlet.http.*; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; public class ExitAction extends Action { @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(true); UserLogin login = (UserLogin)session.getAttribute("login"); if(login==null) return mapping.findForward("success"); else { session.invalidate(); return mapping.findForward("success"); } } }
JavaScript
UTF-8
402
2.765625
3
[]
no_license
$(document).ready(function() { signUpButtonListener(); }); var signUpButtonListener = function () { $(".register").on("click", function(event) { event.preventDefault() var target = $(this) var url = target.attr('href') var request = $.ajax({ url: url }) request.done(function (response) { // console.log(response) $(".register-container").html(response) }) }) }
Python
UTF-8
427
3.328125
3
[]
no_license
def accum(s): lis = [] count = 0 for letter in s: letter = letter.lower() count += 1 lis.append(letter*count) ats = [x.capitalize() for x in lis] return "-".join(ats) print( accum("Abcd")) #https://www.codewars.com/kata/5667e8f4e3f572a8f2000039/solutions/python def accum(s): output = "" for i in range(len(s)): output+=(s[i]*(i+1))+"-" return output.title()[:-1]
Java
UTF-8
5,567
2.4375
2
[]
no_license
package FX; import dao.QueryUtil; import javafx.beans.property.ReadOnlyObjectWrapper; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.util.Callback; import main.Main; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * Created by lapko on 29.11.2017. */ public class FunctionWindowController { QueryUtil queryUtil; @FXML Label label1; @FXML Label label2; @FXML Label label3; @FXML Label label4; @FXML TextField textField; @FXML TextField textField2; @FXML TextField textField3; @FXML TextField textField4; @FXML TableView<String> table; @FXML Button button; List<TableColumn<String,String>> columns; private ObservableList<String> list = FXCollections.observableArrayList(); private String sql; @FXML private void initialize(){ queryUtil = new QueryUtil(Main.getOurSessionFactory()); columns = new ArrayList<>(); } @FXML private void queryButtonHandler(){ ResultSetMetaData meta; ResultSet resultSet; list.clear(); columns.clear(); table.getColumns().clear(); try { if(textField.getText().isEmpty()) resultSet = queryUtil.createQuery(sql); else { if(!textField.getText().isEmpty()) { queryUtil.addParam(textField.getText()); } if(!textField2.getText().isEmpty()) queryUtil.addParam(textField2.getText()); resultSet = queryUtil.createQueryWithParam(sql); } meta = resultSet.getMetaData(); for(int i=1;i<=meta.getColumnCount();i++) { columns.add(new TableColumn(meta.getColumnName(i))); } while (resultSet.next()){ String result = ""; for(int i=1;i<=meta.getColumnCount();i++){ result+= resultSet.getString(i)+";"; } list.add(result); } for(int i=1;i<=meta.getColumnCount();i++){ final int finalI = i; columns.get(i-1).setCellValueFactory(new Callback<TableColumn.CellDataFeatures<String, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(TableColumn.CellDataFeatures<String, String> param) { return new ReadOnlyObjectWrapper<String>(param.getValue().split(";")[ finalI -1]); } }); } table.getColumns().addAll(columns); table.setItems(list); } catch (Exception e) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error"); alert.setHeaderText("Error when execute query"); alert.setContentText("Try again"); alert.showAndWait(); } queryUtil.clearParams(); } public void setSql(String SQL){ this.sql = SQL; int pos; setParamInvisible(); if(!sql.contains("?")){ queryButtonHandler(); setParamInvisible(); }else if((pos = sql.indexOf('?'))!=-1){ setVisibleFirstParam(); if((pos = sql.indexOf('?',pos+1))!=-1){ setVisibleSecondParam(); if((pos = sql.indexOf('?',pos+1))!=-1){ setVisibleThirdParam(); if((pos = sql.indexOf('?',pos+1))!=-1){ setVisibleFouthParam(); } } } } } public void setParamesNames(String[] str){ if(str.length >=1){ label1.setText(str[0]); if(str.length>=2){ label2.setText(str[1]); if(str.length>=3){ label3.setText(str[2]); if(str.length>=4){ label4.setText(str[3]); } } } } } private void setParamInvisible(){ button.setVisible(false); button.disableProperty().setValue(true); textField.setVisible(false); textField.disableProperty().setValue(true); textField2.setVisible(false); textField2.disableProperty().setValue(true); textField3.setVisible(false); textField3.disableProperty().setValue(true); textField4.setVisible(false); textField4.disableProperty().setValue(true); label1.setText(""); label2.setText(""); label4.setText(""); label4.setText(""); } private void setVisibleFirstParam(){ button.setVisible(true); button.disableProperty().setValue(false); textField.setVisible(true); textField.disableProperty().setValue(false); } private void setVisibleSecondParam(){ textField2.setVisible(true); textField2.disableProperty().setValue(false); } private void setVisibleThirdParam(){ textField3.setVisible(true); textField3.disableProperty().setValue(false); } private void setVisibleFouthParam(){ textField4.setVisible(true); textField4.disableProperty().setValue(false); } }
Java
UTF-8
5,874
2.921875
3
[ "MIT" ]
permissive
package com.joinesty.domains.staticVault.managers.dateOfBirth; import com.joinesty.domains.staticVault.StaticVault; import com.joinesty.services.crypto.AESDTO; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.Unirest; import java.net.URLEncoder; import java.util.List; /** * DateOfBirthManager Class */ public class DateOfBirthManager { private StaticVault vault; private DateOfBirthManager() { } /** * Creates an instance of DateOfBirthManager. * * @param vault Vault */ public DateOfBirthManager(StaticVault vault) { this.vault = vault; } /** * Create a new DateOfBirth string to be aliased for a specific static vault * * @param dateOfBirth Date of Birth * @return DateOfBirthResponse * @throws Exception Exception */ public DateOfBirthResponse create(String dateOfBirth) throws Exception { return this.create(dateOfBirth, null, null, null); } /** * Create a new DateOfBirth string to be aliased for a specific static vault * * @param dateOfBirth Date of Birth * @param tags Tags * @return DateOfBirthResponse * @throws Exception Exception */ public DateOfBirthResponse create(String dateOfBirth, List<String> tags) throws Exception { return this.create(dateOfBirth, null, null, tags); } /** * Create a new DateOfBirth string to be aliased for a specific static vault * * @param dateOfBirth Date of Birth * @param year Year * @param month Month * @return DateOfBirthResponse * @throws Exception Exception */ public DateOfBirthResponse create(String dateOfBirth, Integer year, Integer month) throws Exception { return this.create(dateOfBirth, year, month, null); } /** * Create a new DateOfBirth string to be aliased for a specific static vault * * @param dateOfBirth Date of Birth * @param year Year * @param month Month * @param tags Tags * @return DateOfBirthResponse * @throws Exception Exception */ public DateOfBirthResponse create(String dateOfBirth, Integer year, Integer month, List<String> tags) throws Exception { AESDTO cipher = this.vault.encrypt(dateOfBirth); String url = "/vault/static/" + this.vault.getId() + "/dateofbirth?"; if (year != null) url += "year=" + year + "&"; if (month != null) url += "month=" + month; DateOfBirthRequest request = new DateOfBirthRequest(); request.setDateofbirth(cipher.getEncryptedData()); request.setDateofbirthHash(this.vault.hash(dateOfBirth)); request.setAuthTag(cipher.getAuthenticationTag()); request.setIv(cipher.getInitializationVector()); request.setTags(tags); HttpResponse<DateOfBirthResponse> response = Unirest .post(this.vault.getClient().getApi().setUrl(url)) .body(request) .asObject(DateOfBirthResponse.class); DateOfBirthResponse responseBody = response.getBody(); return responseBody; } /** * Retrieve the DateOfBirth string alias from a static vault * * @param id ID * @return DateOfBirthResponse * @throws Exception Exception */ public DateOfBirthResponse retrieve(String id) throws Exception { HttpResponse<DateOfBirthResponse> response = Unirest .get(this.vault.getClient().getApi().setUrl("/vault/static/" + this.vault.getId() + "/dateofbirth/" + id)) .asObject(DateOfBirthResponse.class); DateOfBirthResponse responseBody = response.getBody(); String decrypted = this.vault.decrypt(responseBody.getIv(), responseBody.getAuthTag(), responseBody.getDateofbirth()); responseBody.setDateofbirth(decrypted); return responseBody; } /** * Retrieve the DateOfBirth alias from real dateOfBirth * Real value must be an exact match and will also be case sensitive. * Returns an array of matching values.Array will be sorted by date created. * * @param dateOfBirth Date of Birth * @return List of DateOfBirthResponse * @throws Exception Exception */ public DateOfBirthResponse[] retrieveFromRealData(String dateOfBirth) throws Exception { return this.retrieveFromRealData(dateOfBirth, null); } /** * Retrieve the DateOfBirth alias from real dateOfBirth * Real value must be an exact match and will also be case sensitive. * Returns an array of matching values.Array will be sorted by date created. * * @param dateOfBirth Date of Birth * @param tags Tags * @return DateOfBirthResponse[] * @throws Exception Exception */ public DateOfBirthResponse[] retrieveFromRealData(String dateOfBirth, List<String> tags) throws Exception { String hash = this.vault.hash(dateOfBirth); String url = "/vault/static/" + this.vault.getId() + "/dateofbirth?hash=" + URLEncoder.encode(hash, "UTF-8"); if (tags != null) { for (int i = 0; i < tags.size(); i++) { url += ("&tag=" + URLEncoder.encode(tags.get(i), "UTF-8")); } } HttpResponse<DateOfBirthResponse[]> response = Unirest .get(this.vault.getClient().getApi().setUrl(url)) .asObject(DateOfBirthResponse[].class); DateOfBirthResponse[] responseBody = response.getBody(); for (int i = 0; i < responseBody.length; i++) { String decrypted = this.vault.decrypt( responseBody[i].getIv(), responseBody[i].getAuthTag(), responseBody[i].getDateofbirth() ); responseBody[i].setDateofbirth(decrypted); } return responseBody; } /** * Delete the DateOfBirth alias from static vault * * @param id ID * @return boolean * @throws Exception Exception */ public boolean delete(String id) throws Exception { HttpResponse<String> response = Unirest .delete(this.vault.getClient().getApi().setUrl("/vault/static/" + this.vault.getId() + "/dateofbirth/" + id)) .asString(); return response.getBody().contains("{\"ok\":true}"); } }
SQL
UTF-8
10,375
3.609375
4
[]
no_license
CREATE TABLE tbl_ator( cod_ator INT NOT NULL PRIMARY KEY AUTO_INCREMENT, nome_ator VARCHAR(100) NOT NULL, data_nascimento DATE NULL, biografia TEXT ); CREATE TABLE tbl_filme( cod_filme INT NOT NULL PRIMARY KEY AUTO_INCREMENT, titulo_filme VARCHAR(100) NOT NULL, duracao_filme TIME NOT NULL, ano_lancamento YEAR NOT NULL, sinopse TEXT NULL, cod_idioma INT NOT NULL, FOREIGN KEY (cod_idioma) REFERENCES tbl_idioma (cod_idioma) ); CREATE TABLE tbl_filme_ator( cod_filme INT(11) NOT NULL, cod_ator INT(11) NOT NULL, FOREIGN KEY (cod_filme) REFERENCES tbl_filme (cod_filme), FOREIGN KEY (cod_ator) REFERENCES tbl_ator (cod_ator), personagem VARCHAR(100) NULL ); INSERT INTO tbl_filme ( titulo_filme, duracao_filme, ano_lancamento, sinopse, cod_idioma ) VALUES ('STAR WAR', '2:30:00', 1977, 'Eu não sei!', 1); INSERT INTO tbl_idioma (nome_idioma) VALUES ('English'); INSERT INTO tbl_idioma (nome_idioma) VALUES ('Francês'); INSERT INTO tbl_filme ( titulo_filme, duracao_filme, ano_lancamento, sinopse, cod_idioma ) VALUES ('Miranha De Volta Ao Lar', '2:21:00', 2017, 'Aaaah, Cê Sabe', 1); INSERT INTO tbl_filme ( titulo_filme, duracao_filme, ano_lancamento, sinopse, cod_idioma ) VALUES ('Tropa de Elite', '2:02:00', 2017, 'SEU ANIMAL!', 2); SELECT titulo_filme, ano_lancamento, nome_idioma FROM tbl_filme, tbl_idioma WHERE tbl_filme.cod_idioma = tbl_idioma.cod_idioma; SELECT f.titulo_filme AS Título, f.ano_lancamento AS Lançamento, i.nome_idioma AS Idioma FROM tbl_filme AS f, tbl_idioma AS i WHERE f.cod_idioma = i.cod_idioma; INSERT INTO tbl_ator(nome_ator, data_nascimento, biografia) VALUES('Robert Denyro', '1955-6-10', 'Obi-Wan Kenobi'); INSERT INTO tbl_filme_ator(cod_filme, cod_ator, personagem) VALUES(2, 4, 'Obi-Wan Kenobi'); SELECT tbl_filme.titulo_filme, tbl_ator.nome_ator, tbl_filme_ator.personagem FROM tbl_filme, tbl_filme_ator, tbl_ator WHERE tbl_filme.cod_filme = tbl_filme_ator.cod_filme AND tbl_filme_ator.cod_ator = tbl_ator.cod_ator AND tbl_filme.titulo_filme = 'STAR WARS'; SELECT f.titulo_filme, a.nome_ator, fa.personagem FROM tbl_filme AS f, tbl_filme_ator AS fa, tbl_ator AS a WHERE f.cod_filme = fa.cod_filme AND fa.cod_ator = a.cod_ator AND a.nome_ator = 'Wagner Moura'; ALTER TABLE tbl_ator ADD COLUMN telefone VARCHAR(100) NOT NULL ALTER TABLE tbl_ator DROP COLUMN telefone; ALTER TABLE tbl_ator ADD COLUMN xpto VARCHAR(100) NULL FIRST; ALTER TABLE tbl_ator ADD COLUMN cpf VARCHAR(100) NULL AFTER nome_ator; CREATE TABLE tbl_classificacao( cod_classificacao INT NOT NULL PRIMARY KEY AUTO_INCREMENT, classificacao VARCHAR(100) NOT NULL ); ALTER TABLE tbl_filme ADD COLUMN cod_classificacao INT NOT NULL ALTER TABLE tbl_filme ADD CONSTRAINT fk_classificacao_filme FOREIGN KEY (cod_classificacao) REFERENCES tbl_classificacao (cod_classificacao); CONSTRAINT => restrição, limitação, regra; /*No INSERT, quando a quantidade de VALUES for igual a quantidade de campos, NÃO é necessário especificar os campos, DESDE QUE OS VALUES sejam colocados na ORDEM que esta no banco*/ INSERT INTO tbl_classificacao (cod_classificacao, classificacao) VALUES(0, 'temp'); ↓ INSERT INTO tbl_classificacao VALUES(0, 'temp'); ←↓ CREATE TABLE tbl_diretor( cod_diretor INT NOT NULL PRIMARY KEY AUTO_INCREMENT, nome_diretor VARCHAR(100) NOT NULL, data_nascimento DATE NULL, biografia TEXT NULL, nacionalidade VARCHAR(100) NULL ); CREATE TABLE tbl_filme_diretor( cod_filme INT NOT NULL, cod_diretor INT NOT NULL, CONSTRAINT fk_filme_diretor_cod_filme FOREIGN KEY (cod_filme) REFERENCES tbl_filme (cod_filme), CONSTRAINT fk_filme_diretor_cod_diretor FOREIGN KEY (cod_diretor) REFERENCES tbl_diretor (cod_diretor) ); CREATE TABLE tbl_genero( cod_genero INT NOT NULL PRIMARY KEY AUTO_INCREMENT, genero VARCHAR(100) NOT NULL ); CREATE TABLE tbl_filme_genero( cod_filme INT NOT NULL, cod_genero INT NOT NULL, CONSTRAINT fk_filme_genero_cod_filme FOREIGN KEY (cod_filme) REFERENCES tbl_filme (cod_filme), CONSTRAINT fk_filme_diretor_cod_genero FOREIGN KEY (cod_genero) REFERENCES tbl_genero (cod_genero) ); CREATE TABLE tbl_sessao( cod_sessao INT NOT NULL PRIMARY KEY AUTO_INCREMENT, sessao TIME NOT NULL ); CREATE TABLE tbl_sala( cod_sala INT NOT NULL PRIMARY KEY AUTO_INCREMENT, sala VARCHAR(100) NOT NULL ); CREATE TABLE tbl_dia_semana( cod_dia_semana INT NOT NULL PRIMARY KEY AUTO_INCREMENT, dia VARCHAR(100) NOT NULL ); CREATE TABLE tbl_agenda( cod_agenda INT NOT NULL PRIMARY KEY AUTO_INCREMENT, cod_filme INT NOT NULL, cod_sessao INT NOT NULL, cod_sala INT NOT NULL, cod_dia_semana INT NOT NULL, CONSTRAINT fk_agenda_filme FOREIGN KEY (cod_filme) REFERENCES tbl_filme (cod_filme), CONSTRAINT fk_agenda_sessao FOREIGN KEY (cod_sessao) REFERENCES tbl_sessao (cod_sessao), CONSTRAINT fk_agenda_sala FOREIGN KEY (cod_sala) REFERENCES tbl_sala (cod_sala), CONSTRAINT fk_agenda_dia_semana FOREIGN KEY (cod_dia_semana) REFERENCES tbl_dia_semana (cod_dia_semana) ); /* ---**---BACKUP DE BANCO DE DADOS NO MYSQL---**--- Na pasta bin do MySQL Server executar o mysqldump mysqldump.exe -u root -p cinema > \Users\18175301\cinema.bkp ← nome do arquivo de backup ↑ usuario ↑ ↑lugar onde o bakcup será guardado ↑nome do banco ---**---IMPORTAR BACKUP DE BANCO DE DADOS NO MYSQL---**--- source C:\Users\18175301\cinema.bkp ← nome do arquivo de backup ↑lugar onde o bakcup será guardado */ /* CRIAR USUARIO DO BANCO CREATE USER 'cinema'@'localhost' IDENTIFIED BY '123' ↑ ↑origem do usuario ↑senha do usuario ↑nome do usuario DAR PERMISSÕES AO USUÁRIO GRANT ALL PRIVILEGES ON db_cinema.* TO 'cinema'@'localhost' ← usuario ↑tipo de permissao ↑ ↑tabelas permitidas ↑banco permitido GRANT SELECT PRIVILEGES ON db_cinema.* TO 'cinema'@'localhost' ← usuario GRANT INSERT PRIVILEGES ON db_cinema.* TO 'cinema'@'localhost' ← usuario SHOW PROCCESS LIST */ -- ******NÃO UTILIZAR COM 'WHERE'****** SELECT f.cod_filme AS Código, f.titulo_filme AS Título, i.nome_idioma AS Idioma, c.classificacao AS Classificação FROM tbl_filme AS f, tbl_idioma AS i, tbl_classificacao AS c WHERE f.cod_idioma = i.cod_idioma AND f.cod_classificacao = c.cod_classificacao; -- ******MESMO SELECT, MAS COM JOIN****** SELECT f.cod_filme, f.titulo_filme, i.nome_idioma FROM tbl_filme AS f JOIN tbl_idioma AS i JOIN tbl_classificacao AS c WHERE f.cod_idioma = i.cod_idioma AND f.cod_classificacao = c.cod_classificacao; ------- SELECT f.cod_filme AS Código, f.titulo_filme AS Título, i.nome_idioma AS Idioma, c.classificacao AS Classificação FROM tbl_filme AS f, tbl_idioma AS i, tbl_classificacao AS c WHERE f.cod_idioma = i.cod_idioma AND f.cod_classificacao = c.cod_classificacao; SELECT f.cod_filme, f.titulo_filme, i.nome_idioma, c.classificacao FROM tbl_filme AS f -- INNER JOIN(JOIN) - SERVER PARA JUNTAR 2 TABELAS COM CAMPOS CONINCIDENTES(ON) INNER JOIN tbl_idioma AS i ON f.cod_idioma = i.cod_idioma INNER JOIN tbl_classificacao AS c ON f.cod_classificacao = c.cod_classificacao; SELECT f.cod_filme, f.titulo_filme, i.nome_idioma, c.classificacao FROM tbl_filme AS f, tbl_idioma AS i, tbl_classificacao AS c WHERE f.cod_idioma = i.cod_idioma AND f.cod_classificacao = c.cod_classificacao; SELECT f.title, c.name FROM filme AS f JOIN category AS C ON f.category_id = c.category_id; ------CONTA QUANTAS VEZES O CAMPO REQUISITADO APARECE NO RESULTADO DA CONSULTA------- SELECT COUNT(film_id) FROM film; SELECT f.title AS Título, c.name AS Categoria, fc.category_id AS 'Código da Categoria' FROM film AS f JOIN film_category AS fc ON f.film_id = fc.film_id JOIN category AS c ON fc.category_id = c.category_id ORDER BY f.title LIMIT 10; SELECT f.title AS Título, c.name AS Categoria, fc.category_id AS 'Código da Categoria' FROM film AS f JOIN film_category AS fc ON f.film_id = fc.film_id JOIN category AS c ON fc.category_id = c.category_id ORDER BY f.title LIMIT 10; /* CONSULTA DE ATORES POR FILME*/ SELECT f.title AS Título, f.description AS Descrição, a.first_name AS 'Primeiro Nome', a.last_name AS 'Último Nome' FROM film AS f JOIN film_actor AS fa ON f.film_id = fa.film_id JOIN actor AS a ON fa.actor_id = a.actor_id WHERE f.film_id = 1000; /*CONSULTA FILMES POR ATOR*/ SELECT f.title AS Título, f.description AS Descrição, -- ↓junta 2 ou mais campos no mesmo resultado concat_ws(" ", a.first_name, a.last_name) AS Nome -- ↑caracter separador FROM film AS f JOIN film_actor AS fa ON f.film_id = fa.film_id JOIN actor AS a ON fa.actor_id = a.actor_id WHERE a.actor_id = 1; SELECT c.store_id AS Store, concat_ws(" ", c.first_name, c.last_name) AS Name, ct.city AS City, co.country AS Country FROM customer AS c JOIN address AS a ON c.address_id = a.address_id JOIN city AS ct ON ct.city_id = a.city_id JOIN country AS co ON ct.country_id = co.country_id WHERE co.country LIKE '_R%'; /*_ = Uma caracter */ /*% = QUALQUER QUANTIDADE DE CARACTERES*/ /*PARA COMPARAÇÕES COMSTRINGS É CERTO USAR O LIKE*/ /*WHERE co.country LIKE 'Brazil' OR co.country LIKE 'Argentina' OR co.country LIKE 'Chile' OR co.country LIKE 'Colombia';*/ /*WHERE co.country = 'Brazil' OR co.country = 'Argentina' OR co.country = 'Chile' OR co.country = 'Colombia';*/ /*WHERE co.country IN ('Brazil', 'Argentina', 'Chile', 'Colombia');*/
JavaScript
UTF-8
738
2.734375
3
[]
no_license
import React, { useState } from "react"; function Node(props) { let hasChild = props.data.nodes.length !== 0; const [expand, setExpand] = useState(props.data.isOpen); // console.log(`${props.data.text} : has child : ${hasChild}`); function renderChilds() { return ( <> {props.data.nodes.map((item) => { return <Node data={item} />; })} </> ); } function expandChildren() { if (hasChild) { setExpand((prev) => { return !prev; }); } } return ( <> <div onClick={expandChildren}> {hasChild ? <span>*</span> : <span>-</span>} {props.data.text} </div> <div className="child"> {expand ? renderChilds() : <></>} </div> </> ); } export default Node;
Java
UTF-8
1,427
2.453125
2
[ "Apache-2.0" ]
permissive
package net.openhft.chronicle.wire.marshallable; import net.openhft.chronicle.core.io.IORuntimeException; import net.openhft.chronicle.wire.AbstractMarshallable; import net.openhft.chronicle.wire.Marshallable; import net.openhft.chronicle.wire.WireIn; import net.openhft.chronicle.wire.Wires; import org.jetbrains.annotations.NotNull; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; public class MarshallableWithOverwriteFalseTest { @Test public void test() { MyDto2 myDto2 = new MyDto2(); MyDto myDto1 = new MyDto(); myDto2.myDto.put("", myDto1); myDto1.strings.add("hello"); myDto1.strings.add("world"); String cs = myDto2.toString(); System.out.println(cs); MyDto2 o = (MyDto2) Marshallable.fromString(cs); assert o.myDto.get("").strings.size() == 2; } static class MyDto extends AbstractMarshallable { List<String> strings = new ArrayList<>(); public void readMarshallable(@NotNull WireIn wire) throws IORuntimeException { // WORKS // Wires.readMarshallable(this, wire, true); // WORKS // FAILS Wires.readMarshallable(this, wire, false); } } static class MyDto2 extends AbstractMarshallable { Map<String, MyDto> myDto = new TreeMap<String, MyDto>(); } }
C++
UTF-8
5,667
2.953125
3
[]
no_license
// // Created by smedina on 12/2/18. // #ifndef ADULTS_CPP_DECISION_TREE_H #define ADULTS_CPP_DECISION_TREE_H #include <vector> #include <cmath> #include <limits> #include "csv_reader.h" class decision_tree { private: int x_decision_index = -1; std::vector<std::tuple<int, decision_tree>> children; int y_index = -1; int value = -1; public: void print(csv_reader &csv, std::string parents="", std::ostream &output=std::cout) { if (value >= 0) { auto value_string = csv.get_value_string(y_index, value); auto column_name = csv.get_column_name(y_index); output << parents << " => " << column_name << " = " << value_string << std::endl; } else { if (not parents.empty()) { parents = parents + " & "; } for (auto &[value_index, sub_tree] : children) { auto value_string = csv.get_value_string(x_decision_index, value_index); auto column_name = csv.get_column_name(x_decision_index); auto parent_string = parents + column_name + " = " + value_string; sub_tree.print(csv, parent_string); } } } int max_index(std::vector<int> &counters) { int max_index = 0; int max_value = counters[0]; for (int value_index = 1; value_index < counters.size(); value_index += 1) { if (counters[value_index] > max_value) max_index = value_index; } return max_index; } decision_tree(int value, int y_index, bool guess_from_parent=true) : value(value), y_index(y_index){ } /** * Builds decision tree * @param csv Input CSV object * @param y_index Label index * @param guess_from_parent Guesses the leaves' class of unseen examples from the parent's labels */ decision_tree(csv_reader &csv, int y_index, bool guess_from_parent=true) : value(-1), y_index(y_index) { csv.disable_column(y_index); // Check if all elements have the same class auto [counters, total] = csv.count_values(y_index); auto max_index = this->max_index(counters); if (counters[max_index] == total) { // All instances have the same class value = max_index; } else if (csv.all_equal()) { // All instances have the same values value = max_index; } else { auto [min_column, entropy] = min_conditional_entropy(csv); x_decision_index = min_column; auto [counters_x, total_x] = csv.count_values(x_decision_index); for (int value_index = 0; value_index < counters_x.size(); value_index += 1) { if (counters_x[value_index] > 0) { auto filtered_csv = csv.filter(x_decision_index, value_index); /* std::cout << "compute decision_tree " << csv.get_column_name(x_decision_index) << "/" << csv.get_value_string(x_decision_index, value_index) << " -> " << std::to_string(filtered_csv.enabled_rows_count()) << std::endl; */ // TODO: Call this in a pool of threads, there are no locks between calls decision_tree child_decision_tree(filtered_csv, y_index, guess_from_parent); children.emplace_back(std::tuple<int, decision_tree>(value_index, child_decision_tree)); } else if (guess_from_parent) { // We have to guess from the parent's majority decision_tree child_decision_tree(max_index, y_index, guess_from_parent); children.emplace_back(std::tuple<int, decision_tree>(value_index, child_decision_tree)); } } } } double entropy(csv_reader& csv, int column_index) { auto [counters, total] = csv.count_values(column_index); return this->entropy(counters, total); } double entropy(std::vector<int> const& counters, int total) { double entropy = 0; for (int count: counters) { if (count > 0) { double probability = double(count) / double(total); entropy -= probability * std::log2(probability); } } return entropy; } double conditional_entropy(csv_reader& csv, int column_index) { double conditional_entropy = 0; auto [counters, total] = csv.count_values(column_index); for (int value_index = 0; value_index < counters.size(); value_index += 1) { auto [value_counters, value_total] = csv.count_values(y_index, column_index, value_index); auto entropy = this->entropy(value_counters, value_total); auto count_value_index = counters[value_index]; if (count_value_index > 0) { double probability = double(count_value_index) / double(total); conditional_entropy += probability * entropy; } } return conditional_entropy; } std::tuple<int, double> min_conditional_entropy(csv_reader &csv) { auto enabled_columns = csv.get_enabled_columns(); int min_index = 0; double min_entropy = std::numeric_limits<double>::max(); for (auto column_index : enabled_columns) { auto entropy = conditional_entropy(csv, column_index); if (entropy < min_entropy) { min_index = column_index; min_entropy = entropy; } } return {min_index, min_entropy}; } }; #endif //ADULTS_CPP_DECISION_TREE_H
Java
UTF-8
289
2.09375
2
[]
no_license
package com.xuya.charge.phone.constant; public enum OrderStatusEnum { SUCCESS(0), FAILED(1), PROCESSING(2), UNKNOWN(3); private Integer status; private OrderStatusEnum(Integer status) { this.status = status; } public Integer getStatus() { return status; } }
Java
UTF-8
2,918
2.5625
3
[]
no_license
import static org.junit.Assert.*; import java.util.ArrayList; import java.util.Arrays; import main.Item; import main.ItemBag; import main.State; import org.junit.Before; import org.junit.Test; import constraints.BinaryEqual; import constraints.BinaryMutualExclusive; import constraints.BinaryNotEqual; import constraints.UnaryExclusive; import constraints.UnaryInclusive; /** * */ /** * @author Zach * */ public class TestConstraints { ArrayList<Item> items = new ArrayList<Item>(); ArrayList<ItemBag> bags = new ArrayList<ItemBag>(); UnaryInclusive ui; UnaryExclusive ue; BinaryMutualExclusive bme; /** * @throws java.lang.Exception */ @Before public void setUp() throws Exception { //bme = new BinaryMutualExclusive(bags,items); } @Test public void testUnaryInclusiveConstraintValidity() { Item C14 = new Item("C",14); items.add(C14); Item D14 = new Item("D",14); items.add(D14); ItemBag q15 = new ItemBag("q",15); ItemBag p15 = new ItemBag("p",15); bags.add(p15); bags.add(q15); p15.addItem(C14); ArrayList<ItemBag> p15Array = new ArrayList<ItemBag>(); p15Array.add(p15); ui = new UnaryInclusive(p15Array,C14); ue = new UnaryExclusive(p15Array,C14); State s = new State(bags,items); assertTrue(ui.isValid(s,p15,C14)); assertFalse(ue.isValid(s,p15,C14)); } @Test public void testBinaryInExclusiveConstraintValidity() { Item C14 = new Item("C",14); items.add(C14); Item D14 = new Item("D",14); items.add(D14); ItemBag q15 = new ItemBag("q",15); ItemBag p15 = new ItemBag("p",15); bags.add(p15); bags.add(q15); p15.addItem(C14); p15.addItem(D14); ArrayList<ItemBag> p15Array = new ArrayList<ItemBag>(Arrays.asList(p15)); BinaryEqual be = new BinaryEqual(D14,C14); BinaryNotEqual bne = new BinaryNotEqual(D14,C14); State s = new State(bags,items); assertTrue(be.isValid(s,p15,C14)); assertFalse(bne.isValid(s,p15,C14)); } @Test public void testMutualExclusiveConstraintValidity() { Item C14 = new Item("C",14); items.add(C14); Item D14 = new Item("D",14); items.add(D14); ItemBag q15 = new ItemBag("q",15); ItemBag p15 = new ItemBag("p",15); bags.add(p15); bags.add(q15); p15.addItem(C14); p15.addItem(D14); BinaryMutualExclusive bme = new BinaryMutualExclusive(p15,q15,C14,D14); State s = new State(bags,items); assertTrue(bme.isValid(s,p15,C14)); } @Test public void testMutualExclusiveConstraintValidity2() { Item C14 = new Item("C",14); items.add(C14); Item D14 = new Item("D",14); items.add(D14); ItemBag q15 = new ItemBag("q",15); ItemBag p15 = new ItemBag("p",15); bags.add(p15); bags.add(q15); p15.addItem(C14); q15.addItem(D14); BinaryMutualExclusive bme = new BinaryMutualExclusive(p15,q15,C14,D14); State s = new State(bags,items); assertFalse(bme.isValid(s,p15,C14)); } }