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
Java
UHC
857
3.375
3
[]
no_license
import java.util.Scanner; public class BJ1316 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); sc.nextLine(); int cnt = 0; for(int i=0; i<n; i++){ boolean arr[] = new boolean[26]; String str = sc.nextLine(); StringBuilder newStr = new StringBuilder(); //1. ؼ ڴ ϳ //2. ó 迭 insert char[] ch = str.toCharArray(); for(int j=0; j<ch.length; j++){ if(j != 0 && ch[j-1] == ch[j]){ continue; } newStr.append(ch[j]); } int rst = 0; for(int j=0; j<newStr.length(); j++){ int idx = newStr.charAt(j)-97; if(arr[idx] == false){ arr[idx] = true; }else{ rst = -1; break; } } if(rst != -1){ cnt++; } } System.out.println(cnt+""); } }
C++
UTF-8
1,027
3.1875
3
[ "MIT" ]
permissive
#include "time_conversion.h" #include <iostream> #include <iomanip> #include <string> #include <regex> using namespace hackerrank::bmgandre::algorithms::warmup; /// Practice>Algorithms>Warmup>Time Conversion /// /// https://www.hackerrank.com/challenges/time-conversion void time_conversion::solve() { std::string pattern = R"regex((\d{2}):(\d{2}):(\d{2})(AM|PM))regex"; std::regex regex(pattern, std::regex::ECMAScript); std::smatch matches; std::string input_time; std::cin >> input_time; if (std::regex_search(input_time, matches, regex)) { auto hour = std::stoi(matches[1].str()); auto min = std::stoi(matches[2].str()); auto sec = std::stoi(matches[3].str()); auto ampm = matches[4].str(); if (ampm == "PM" && hour < 12) { hour = (hour + 12) % 24; } else if (ampm == "AM" && hour == 12) { hour = 0; } std::cout << std::setfill('0') << std::setw(2) << hour << ":" << std::setfill('0') << std::setw(2) << min << ":" << std::setfill('0') << std::setw(2) << sec; } }
Markdown
UTF-8
6,330
3.1875
3
[]
no_license
## Roadmapping #### In a nutshell Roadmapping is the process of establishing one or more concrete, achievable goals and laying out each of the tasks which must be completed in order to accomplish each goal. To have a useful roadmap, it is important that these goals and the tasks which need to be done to accomplish them are explicitly documented, and easily accessed by all members of the team. It is important that the tasks which compose a goal in a roadmap be tracked; It should be known at all times whether or not a task is completed, if it's actively being worked on, and who is working on it if it is. Examples of good roadmap goals: - Implement an MVP - Implement all API endpoints - Complete 5 user tests Roadmap goals to avoid: - Complete the project - Find users for user testing #### Why Bother Like any other activity which demands time and effort from the team members of a project, it is important to understand the value prospect of roadmapping. This section describes some of the important and tangible benefits of roadmapping a project. ###### Make work distributable When a goal is broken down into a step-by-step process which is accessible to the entire team, then each team member can take on a step, allowing multiple steps to be worked on by different people at the same time. ###### Make onboarding simpler When the current project goal and the tasks is consists of are documented, it becomes simpler to take on new contributors. New contributors can simply be pointed to the location in which all of this information is documented, and select a task to begin working on. This simplicity lowers the barrier of entry for people to get involved with a new project. ###### Make project progress trackable/measurable Documenting the tasks which need to be accomplished to fulfill the current project goal is the first step toward having a process for documenting the in-progress and completion status of each such task as well. This allows for a concrete measurement of progress toward a goal; how many tasks are done vs how many are not can help quantify how close the team is to accomplishing the overall goal. ###### Make collaboration easier When individual tasks are being tracked as part of a roadmap, this makes it easier for teammates to collaborate. Teammates can avoid duplicating effort by knowing who is working on what, and have a shared understanding of what needs to be worked on next. ## Onboarding #### In a nutshell Onboarding is the process of taking a potential new contributor from the point of knowing nothing about your project up to the point of making impactful contributions. As an open source project to which people donate their time, it is important to set reasonable expectations around contributors; many will come and go over the lifetime of a project. Because of this reality, it is important to keep the barrier of entry to new contributors as low as possible. #### Doing it successfully ###### Simple introspection into current project status and tasks It is important that a new contributor can easily view the current project status, and determine from the current status of the project which tasks need to be done but are not currently being worked on. This provides a direct path for a new contributor to know how to become immediately helpful to a project. This is a need which can be met by establishing and maintaining a project roadmap, with tracked tasks. ###### Clear, concise, up-to-date instructions on getting started with development (on all platforms!) All projects should provide instructions on how developers can setup their local machines to start working on the project. It is important that instructions exist **for every major platform** (Windows, OS X, Linux); every individual has their own preferences, and excluding platforms which your current team does not prefer alienates potential contributors. This should be done on a best effort basis; if no one on the team has access to a Windows license or to a MacBook in order to provide instructions, then it simply cannot be done. What's perhaps most important about this point is that projects should avoid incorportating platform specific workflows into the development process (e.g., requiring batch scripts or AppleScript as part of the development process). ###### Documented code base The code base should have comments on all methods and functions, and before any sequences of difficult to read or unusual code. This is a general coding best practice, but is highlighted in this context because of its impact on the ability of a new contributor to quickly become familiar with the current code base (and therefore more quickly make meaningful contributions) ###### Human contact! Always be available to potential new contributors to ask questions, or even proactively reach out to them to try to help them find tasks to work on! The best documentation in the world is still no substitute for old fashioned human contact and communication. Contributors usually join projects to feel like they're working with a group of people to accomplish something. ## Keeping up momentum #### In a nutshell Keeping a project moving forward is important; having a sense of progress keeps team members invested and gives the project the best chance of actually launching. This section covers some tips on helping to continuously foster a sense of progress in a project. #### Regular check-ins Have team members regularly report the current status of tasks they are working on. Not only does this help each team member motivate themselves to have progress to show, but it also gives the team insight into when a team member may need help with a task, or no longer has time to continue working on a task. This transparency also helps ensure that task and project statuses remain up to date, and reflect the actual state of the project. In addition to helping foster a sense of ongoing progress, this helps with things like new contributor onboarding and roadmap tracking as well. #### Goals and Deadlines When establishing roadmaps, set target dates for each step in the roadmap. Constraining goals to be accomplished by a certain deadline helps set a pace for progress on the project, and can provide that sense that the project is continuing to move steadily forward.
Go
UTF-8
277
3.046875
3
[ "MIT" ]
permissive
package main // https://space.bilibili.com/206214 func minImpossibleOR(nums []int) int { mask := 0 for _, x := range nums { if x&(x-1) == 0 { // x 是 2 的幂次 mask |= x } } // 取反后,用 lowbit 找第一个 0 比特位 mask = ^mask return mask & -mask }
Python
UTF-8
1,970
3.5
4
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/7/20 10:48 # @Author : Lyrichu # @Email : 919987476@qq.com # @File : improve_random_walk.py ''' @Description:改进的随机游走算法 这里求解:f = sin(r)/r + 1,r = sqrt((x-50)^2+(y-50)^2)+e,0<=x,y<=100 的最大值 求解f的最大值,可以转化为求-f的最小值问题 ''' from __future__ import print_function import math import random N = 100 # 迭代次数 step = 10.0 # 初始步长 epsilon = 0.00001 variables = 2 # 变量数目 x = [-100,-10] # 初始点坐标 walk_num = 1 # 初始化随机游走次数 n = 10 # 每次随机生成向量u的数目 print("迭代次数:",N) print("初始步长:",step) print("每次产生随机向量数目:",n) print("epsilon:",epsilon) print("变量数目:",variables) print("初始点坐标:",x) # 定义目标函数 def function(x): r = math.sqrt((x[0]-50)**2 + (x[1]-50)**2) + math.e f = math.sin(r)/r + 1 return -f # 开始随机游走 while(step > epsilon): k = 1 # 初始化计数器 while(k < N): # 产生n个向量u x1_list = [] # 存放x1的列表 for i in range(n): u = [random.uniform(-1,1) for i1 in range(variables)] # 随机向量 # u1 为标准化之后的随机向量 u1 = [u[i3]/math.sqrt(sum([u[i2]**2 for i2 in range(variables)])) for i3 in range(variables)] x1 = [x[i4] + step*u1[i4] for i4 in range(variables)] x1_list.append(x1) f1_list = [function(x1) for x1 in x1_list] f1_min = min(f1_list) f1_index = f1_list.index(f1_min) x11 = x1_list[f1_index] # 最小f1对应的x1 if(f1_min < function(x)): # 如果找到了更优点 k = 1 x = x11 else: k += 1 step = step/2 print("第%d次随机游走完成。" % walk_num) walk_num += 1 print("随机游走次数:",walk_num-1) print("最终最优点:",x) print("最终最优值:",function(x))
Python
UTF-8
58,406
3.171875
3
[]
no_license
""" GSU main functions. """ import random import math import utils # ================================================================================================== def rounded_point(p, digits=10): """ Get rounded point for constructing bags of points. :param p: point :param digits: accuracy :return: rounded point """ return round(p[0], digits), round(p[1], digits), round(p[2], digits) # -------------------------------------------------------------------------------------------------- def mean_nodes_point(ns): """ Get mean point of nodes. :param ns: nodes :return: mean point """ xs = [n.P[0] for n in ns] ys = [n.P[1] for n in ns] zs = [n.P[2] for n in ns] return sum(xs) / len(xs), sum(ys) / len(ys), sum(zs) / len(zs) # -------------------------------------------------------------------------------------------------- def fun_face_cx(): """ Function that returns X coordinate of the face center. :return: function """ return lambda f: mean_nodes_point(f.Nodes)[0] # -------------------------------------------------------------------------------------------------- def fun_face_cy(): """ Function that returns Y coordinate of the face center. :return: function """ return lambda f: mean_nodes_point(f.Nodes)[1] # -------------------------------------------------------------------------------------------------- def fun_face_cz(): """ Function that returns Z coordinate of the face center. :return: function """ return lambda f: mean_nodes_point(f.Nodes)[2] # ================================================================================================== class Node: """ Node of the grid. """ # ---------------------------------------------------------------------------------------------- def __init__(self, p): """ Constructor node. :param p: node point (tuple of coordinates) """ # Global identifier (in grid numeration). self.GloId = -1 self.P = p # Rounded coordinates for registration in set. self.RoundedCoords = rounded_point(p) # Links with edges and faces. self.Edges = [] self.Faces = [] # ---------------------------------------------------------------------------------------------- def is_near(self, n): """ Check if one node is near to another. :param n: another node :return: True - if nodes are near to each other, False - otherwise """ return self.RoundedCoords == n.RoundedCoords # ================================================================================================== class Edge: """ Edge of the grid. """ # ---------------------------------------------------------------------------------------------- def __init__(self): """ Constructor. """ # Global identifier (in grid numeration). self.GloId = -1 # Links to nodes and faces. self.Nodes = [] self.Faces = [] # ---------------------------------------------------------------------------------------------- def is_border(self): """ Check if edge is border edge. :return: True - if edge is border edge, False - otherwise """ # Border edge has only one neighbour face. return len(self.Faces) == 1 # ---------------------------------------------------------------------------------------------- def is_cross(self): """ Check if edge is cross-zones. :return: True - if edge is cross-zones, False - otherwise """ # Cross-zone edge has two neighbour faces from different zones. faces_count = len(self.Faces) if faces_count == 1: return False elif faces_count == 2: return self.Faces[0].Zone != self.Faces[1].Zone else: raise Exception('Edge cannot has {0} neighbours faces.'.format(faces_count)) # ---------------------------------------------------------------------------------------------- def is_inner(self): """ Check if edge is inner. :return: True - if edge is inner, False - otherwise """ # Inner edge has two faces from one zone. faces_count = len(self.Faces) if faces_count == 1: return False elif faces_count == 2: return self.Faces[0].Zone == self.Faces[1].Zone else: raise Exception('Edge cannot has {0} neighbours faces.'.format(faces_count)) # ---------------------------------------------------------------------------------------------- def is_connect_zones(self, z0, z1): """ Check if edge connect two given zones. :param z0: first zone :param z1: second zone :return: True - if edge connects two given zones, False - otherwise """ if len(self.Faces) != 2: return False fz0, fz1 = self.Faces[0].Zone, self.Faces[1].Zone return ((z0 == fz0) and (z1 == fz1)) or ((z0 == fz1) and (z1 == fz0)) # ================================================================================================== class Face: """ Face of the grid. """ # ---------------------------------------------------------------------------------------------- def __init__(self, data): """ Constructor face. :param data: face data (tuple) """ # Global identifier (in grid numeration). self.GloId = -1 self.Data = data # Links with nodes and edges. self.Nodes = [] self.Edges = [] # Link to zone (each face belongs only to one single zone). self.Zone = None # ---------------------------------------------------------------------------------------------- def get_t(self): """ Get temperature value. :return: temperature value """ return self.Data[0] # ---------------------------------------------------------------------------------------------- def set_t(self, t): """ Set temperature value to face data. :param t: temperature """ self.Data[0] = t # ---------------------------------------------------------------------------------------------- def get_hw(self): """ Get water height value. :return: water height """ return self.Data[1] # ---------------------------------------------------------------------------------------------- def set_hw(self, hw): """ Set water height value to face data. :param hw: water height """ self.Data[1] = hw # ---------------------------------------------------------------------------------------------- def get_hi(self): """ Get ice height value. :return: ice height """ return self.Data[2] # ---------------------------------------------------------------------------------------------- def set_hi(self, hi): """ Set ice height value to face data. :param hi: ice height """ self.Data[2] = hi # ---------------------------------------------------------------------------------------------- def get_glo_id_t_hw_hi_str(self): """ Get string with global identifier, temperature, and water and ice heights. :return: string """ # Random data for t, hw, hi. a = [self.get_t() + random.random(), self.get_hw() + random.random(), self.get_hi() + random.random()] i_list = [str(self.GloId)] + ['{0:.18e}'.format(ai) for ai in a] i_str = ' '.join(i_list) return i_str # ---------------------------------------------------------------------------------------------- def get_neighbour(self, edge): """ Get neighbour through edge. :param edge: edge :return: neighbour """ incident_faces = len(edge.Faces) if incident_faces == 1: if edge.Faces[0] != self: raise Exception('Error while getting face neighbour.') return None elif incident_faces == 2: if edge.Faces[0] == self: return edge.Faces[1] elif edge.Faces[1] == self: return edge.Faces[0] else: raise Exception('Error while getting face neighbour.') else: raise Exception('Wrong edge incident faces ({0}).'.format(incident_faces)) # ---------------------------------------------------------------------------------------------- def unlink_from_zone(self): """ Unlink face from zone. """ if self.Zone is None: return # Face is linked. # Unlink it. self.Zone.Faces.remove(self) self.Zone = None # ---------------------------------------------------------------------------------------------- def get_center(self): """ Get center point. :return: center point """ a, b, c, = self.Nodes[0].P, self.Nodes[1].P, self.Nodes[2].P return ((a[0] + b[0] + c[0]) / 3.0, (a[1] + b[1] + c[1]) / 3.0, (a[2] + b[2] + c[2]) / 3.0) # ---------------------------------------------------------------------------------------------- def get_ab_vector(self): """ Get vector from A point to B point. :return: vector from A point to B point """ a, b = self.Nodes[0].P, self.Nodes[1].P return (b[0] - a[0], b[1] - a[1], b[2] - a[2]) # ---------------------------------------------------------------------------------------------- def get_bc_vector(self): """ Get vector from B point to C point. :return: vector from B point to C point """ b, c = self.Nodes[1].P, self.Nodes[2].P return (c[0] - b[0], c[1] - b[1], c[2] - b[2]) # ---------------------------------------------------------------------------------------------- def get_normal1(self): """ Get outer normal, normalized to 1.0. :return: normalized normal """ ab, bc = self.get_ab_vector(), self.get_bc_vector() n = utils.cross_product(ab, bc) return utils.normalized(n) # ---------------------------------------------------------------------------------------------- def get_point_above(self, d): """ Get point above face (on distance d). :param d: distance :return: point """ c = self.get_center() n1 = self.get_normal1() return utils.a_kb(c, d, n1) # ================================================================================================== class Zone: """ Zone of the grid. """ # ---------------------------------------------------------------------------------------------- def __init__(self, name): """ Constructor. :param name: name of zone """ self.Id = -1 self.Name = name # No nodes or faces in the zone yet. self.Nodes = [] self.Edges = [] self.Faces = [] # Fixed zone flag. self.IsFixed = False # ---------------------------------------------------------------------------------------------- def nodes_count(self): """ Get count of nodes. :return: nodes count """ return len(self.Nodes) # ---------------------------------------------------------------------------------------------- def edges_count(self): """ Get count of edges. :return: edges count """ return len(self.Edges) # ---------------------------------------------------------------------------------------------- def faces_count(self): """ Get count of faces. :return: faces count. """ return len(self.Faces) # ---------------------------------------------------------------------------------------------- def get_nodes_coord_slice_str(self, i): """ Get string composed from i-th coord of all nodes. :param i: index of nodes coord :return: composed string """ i_list = ['{0:.18e}'.format(node.P[i]) for node in self.Nodes] i_str = ' '.join(i_list) return i_str # ---------------------------------------------------------------------------------------------- def get_faces_data_slice_str(self, i): """ Get string composed from i-th elements of data of all faces. :param i: index of nodes data :return: composed string """ i_list = ['{0:.18e}'.format(face.Data[i]) for face in self.Faces] i_str = ' '.join(i_list) return i_str # ---------------------------------------------------------------------------------------------- def get_faces_global_ids_slice_str(self): """ Get string composed from global identifiers of all faces. :return: composed string """ i_list = [str(face.GloId) for face in self.Faces] i_str = ' '.join(i_list) return i_str # ---------------------------------------------------------------------------------------------- def add_node(self, n): """ Add node to zone. :param n: node :return: added node """ # Just add node. self.Nodes.append(n) return n # ---------------------------------------------------------------------------------------------- def add_edge(self, e): """ Add edge to zone. :param e: edge :return: added edge """ # Just add egde. self.Edges.append(e) return e # ---------------------------------------------------------------------------------------------- def add_face(self, f): """ Add face to zone (with link). :param f: face :return: added face """ # If face is already link to some zome, # we have to unlink it first. if f.Zone is not None: f.unlink_from_zone() # Just add and set link to the zone. f.Zone = self self.Faces.append(f) return f # ---------------------------------------------------------------------------------------------- def capture_nearest_face(self): """ Capture face nearest to zone (breadth-first search). """ for f in self.Faces: for e in f.Edges: if not e.is_border(): f2 = f.get_neighbour(e) if f2.Zone is None: self.add_face(f2) return # ================================================================================================== class ZonesAdjacencyMatrix: """ Matrix of zones adjacency. For example if there is 3 zones matrix should be the following: | i00 c01 c02 br0 | | c01 i11 c12 br1 | | c02 c12 i22 br2 | | br0 br1 br2 0 | where cxy - count of cross edges between x-th and y-th zones, ixx - count of inner edges for x-th zone, brx - count of border edges for x-th zone. """ # ---------------------------------------------------------------------------------------------- def __init__(self, es, zs): """ Constructor. :param es: edges list :param zs: zones list """ # Init size and zero matrix. zc = len(zs) self.ZonesCount = zc self.M = [] # Do not copy arrays because we have to create arrays, not references. for i in range(zc + 1): self.M.append([0] * (zc + 1)) # Calculate for each edge. for e in es: fc = len(e.Faces) if fc == 1: f0 = e.Faces[0] z0 = zs.index(f0.Zone) self.inc_border(z0) elif fc == 2: f0, f1 = e.Faces[0], e.Faces[1] z0, z1 = zs.index(f0.Zone), zs.index(f1.Zone) self.inc(z0, z1) else: raise Exception('Wrong edge faces count ({0}).'.format(fc)) # ---------------------------------------------------------------------------------------------- def inc(self, i, j): """ Increment matrix element value. :param i: first zone index :param j: second zone index """ self.M[i][j] += 1 if i != j: self.M[j][i] += 1 # ---------------------------------------------------------------------------------------------- def inc_border(self, i): """ Increment value of border edges count. :param i: zone number """ self.inc(i, self.ZonesCount) # ---------------------------------------------------------------------------------------------- def edges_statistics(self): """ Get edges statistics. Statistics is a tuple with following elements: ec - full edges count bec - border edges count iec - inner edges count cec - cross edges count becp - border edges count percent iecp - inner edges count percent cecp - cross edges count percent :return: tuple """ ec = 0 bec = 0 iec = 0 cec = 0 # Count all lines without the last one. for i in range(self.ZonesCount): line = self.M[i] # Border edges count for this zone is in the last row. # Inner edges count for this zone is on the main diagonal of the matrix. # All values between these two cells are cross edges. bec += line[self.ZonesCount] iec += line[i] cec += sum(line[(i + 1):self.ZonesCount]) # Total count and percents. ec = bec + iec + cec becp, iecp, cecp = 100.0 * bec / ec, 100.0 * iec / ec, 100.0 * cec / ec return ec, bec, iec, cec, becp, iecp, cecp # ---------------------------------------------------------------------------------------------- def edges_statistics_string(self): """ String of edges statistics: :return: string """ ec, bec, iec, cec, becp, iecp, cecp = self.edges_statistics() return 'edges stats: ' \ '{0} border ({1:.2f}%), ' \ '{2} inner ({3:.2f}%), ' \ '{4} cross ({5:.2f}%)'.format(bec, becp, iec, iecp, cec, cecp) # ---------------------------------------------------------------------------------------------- def zone_cross_edges_array(self, zi): """ Array with count of cross edges. :param zi: zone index :return: array with cross edges count. """ line = self.M[zi] line2 = line[:] line2[zi] = 0 line2[self.ZonesCount] = 0 return line2 # ---------------------------------------------------------------------------------------------- def zone_max_cross_border_len(self, zi): """ Maximum border length for given zone. :param zi: zone index :return: max zone border length """ return max(self.zone_cross_edges_array(zi)) # ---------------------------------------------------------------------------------------------- def max_cross_border_len(self): """ Max value of cross zones border lengths. :return: max border length """ return max([self.zone_max_cross_border_len(zi) for zi in range(self.ZonesCount)]) # ---------------------------------------------------------------------------------------------- def zone_cross_edges_count(self, zi): """ Get zone cross-edges count. :param zi: zone index :return: count of cross-edges for this zone """ return sum(self.zone_cross_edges_array(zi)) # ---------------------------------------------------------------------------------------------- def zone_cross_borders_count(self, zi): """ Get borders count for given zone. :param zi: zone index :return: borders count """ return len([x for x in self.zone_cross_edges_array(zi) if x > 0]) # ================================================================================================== class Grid: """ Grid (Surface Unstructured). """ # ---------------------------------------------------------------------------------------------- def __init__(self): """ Constructor. """ # Empty name. self.Name = '' # Mode. self.Mode = '' # Variables. self.VariablesStr = '' self.Variables = [] self.FaceVariablesCount = 0 # Set empty sets of nodes, faces, zones. self.Nodes = [] self.Edges = [] self.Faces = [] self.Zones = [] # Rounded coordinates self.RoundedCoordsBag = set() # ---------------------------------------------------------------------------------------------- def clear(self): """ Clear grid. """ self.Nodes.clear() self.Edges.clear() self.Faces.clear() self.Zones.clear() self.RoundedCoordsBag.clear() # ---------------------------------------------------------------------------------------------- def nodes_count(self): """ Get count of nodes. :return: nodes count """ return len(self.Nodes) # ---------------------------------------------------------------------------------------------- def edges_count(self): """ Get count of edges. :return: edges count """ return len(self.Edges) # ---------------------------------------------------------------------------------------------- def faces_count(self): """ Get count of faces. :return: faces count. """ return len(self.Faces) # ---------------------------------------------------------------------------------------------- def faces_count_in_zones(self): """ Count of faces that are placed in zones. :return: total faces count in zones """ return sum([z.faces_count() for z in self.Zones]) # ---------------------------------------------------------------------------------------------- def faces_count_in_fixed_zones(self): """ Count of faces in fixed zones. :return: faces count in fixed zones """ return sum([z.faces_count() for z in self.Zones if z.IsFixed]) # ---------------------------------------------------------------------------------------------- def random_face(self): """ Get random face. :return: random face """ fc = self.faces_count() ind = random.randint(0, fc - 1) return self.Faces[ind] # ---------------------------------------------------------------------------------------------- def print_info(self, is_print_edges_statistics=False, is_print_faces_distribution=False, is_print_zones_adjacency_matrix=False): """ Print information about grid. :param is_print_edges_statistics: flag for print edges statistics :param is_print_faces_distribution: flag for print faces distribution between zones :param is_print_zones_adjacency_matrix: flag for print zones adjacency matrix """ ec = self.edges_count() fc = self.faces_count() zc = len(self.Zones) print('GSU: {0}'.format(self.Name)) print(' {0} nodes, {1} edges, ' '{2} faces, {3} zones'.format(len(self.Nodes), ec, fc, zc)) # Zones adjacency matrix. zam = ZonesAdjacencyMatrix(self.Edges, self.Zones) # Edges statistics. if is_print_edges_statistics: print(' ' + zam.edges_statistics_string()) # Distribution faces between zones. if is_print_faces_distribution: print(' distribution faces between zones:') for zone in self.Zones: print(' {0} : {1} faces'.format(zone.Name, len(zone.Faces))) zones_faces_count = [len(zone.Faces) for zone in self.Zones] ideal_mean = len(self.Faces) / len(self.Zones) max_zone_faces_count = max(zones_faces_count) faces_distr_dev = 100.0 * (max_zone_faces_count - ideal_mean) / ideal_mean print(' ~ max zone faces {0}, ' 'faces distribution deviation : {1:.2f}%'.format(max_zone_faces_count, faces_distr_dev)) # Distribution edges between pairs of neighbours. if is_print_zones_adjacency_matrix: for i in range(zc + 1): print(' '.join(['{0:5}'.format(e) for e in zam.M[i]])) print(' ~ max cross-zones border length : {0}'.format(zam.max_cross_border_len())) # ---------------------------------------------------------------------------------------------- def find_near_node(self, n): """ Find in grid nodes collection node that is near to a given node. :param n: node to check :return: near node from grid nodes collection """ # First try to find in bag. if n.RoundedCoords in self.RoundedCoordsBag: for node in self.Nodes: if node.is_near(n): return node raise Exception('We expect to find node ' \ 'with coordinates {0} in the grid'.format(n.RoundedCoords)) return None # ---------------------------------------------------------------------------------------------- def add_node(self, n, is_merge_same_nodes): """ Add node. :param n: node :param is_merge_same_nodes: flag merge same nodes :return: node registered in self.Nodes """ found_node = self.find_near_node(n) if (found_node is None) or (not is_merge_same_nodes): # There is no such node in the grid. # We have to add it. n.GloId = len(self.Nodes) self.Nodes.append(n) self.RoundedCoordsBag.add(n.RoundedCoords) return n else: # There is already such a node in the grid. # Just return it. return found_node # ---------------------------------------------------------------------------------------------- def add_edge(self, e): """ Add edge to grid. :param e: edge :return: added edge """ # Just add edge with global id correction. e.GloId = len(self.Edges) self.Edges.append(e) return e # ---------------------------------------------------------------------------------------------- def add_face(self, f): """ Add face. :param f: face :return: added face """ # Just correct global id and add. f.GloId = len(self.Faces) self.Faces.append(f) return f # ---------------------------------------------------------------------------------------------- def set_zones_ids(self): """ Set zones identifiers. """ for (i, z) in enumerate(self.Zones): z.Id = i # ---------------------------------------------------------------------------------------------- def reset_zones_ids(self): """ Reset zones identifiers. """ for z in self.Zones: z.Id = -1 # ---------------------------------------------------------------------------------------------- def link_node_edge(node, edge): """ Link node with edge. :param node: node :param edge: edge """ node.Edges.append(edge) edge.Nodes.append(node) # ---------------------------------------------------------------------------------------------- def link_node_face(node, face): """ Link face with node. :param node: node :param face: face """ node.Faces.append(face) face.Nodes.append(node) # ---------------------------------------------------------------------------------------------- def link_edge_face(edge, face): """ Link edge with face. :param edge: edge :param face: face """ # Check if it is enable to link the face with the edge. if len(edge.Faces) == 2: raise Exception('Too many faces linking with this edge ({0} - {1},' 'GloId = {2})'.format(edge.Nodes[0].P, edge.Nodes[1].P, edge.GloId)) edge.Faces.append(face) face.Edges.append(edge) # ---------------------------------------------------------------------------------------------- def find_edge(node_a, node_b): """ Find edge with given nodes. :param node_a: the first node :param node_b: the second node :return: edge - if it is found, None - otherwise """ for edge in node_a.Edges: if node_b in edge.Nodes: return edge return None # ---------------------------------------------------------------------------------------------- def complex_link_face_node_node_edge(self, face, node_a, node_b): """ Complex link nodes with edge, and edge with face. :param face: face :param node_a: the first node :param node_b: th second node """ # First we need to find edge. edge = Grid.find_edge(node_a, node_b) if edge is None: # New edge and link it. edge = Edge() self.add_edge(edge) Grid.link_node_edge(node_a, edge) Grid.link_node_edge(node_b, edge) Grid.link_edge_face(edge, face) else: # Edge is already linked with nodes. # Link only with the face. Grid.link_edge_face(edge, face) # ---------------------------------------------------------------------------------------------- def bfs_path_connectivity_component(self, start, pred): """ Connectivity component of BFS path from given face. :param start: start face :param pred: predicate for faces :return: path for one connectivity component (list of faces) """ # This function uses bfs_mark field for faces. if start.bfs_mark or not pred(start): # Start face does not satisfy conditions. return [] # Initiate path. start.bfs_mark = True p = [start] i = 0 # Walk. while i < len(p): f = p[i] for e in f.Edges: if not e.is_border(): f2 = f.get_neighbour(e) if not f2.bfs_mark and pred(f2): f2.bfs_mark = True p.append(f2) i = i + 1 return p # ---------------------------------------------------------------------------------------------- def get_no_bfs_mark_face(self, pred): """ Get first no bfs mark face. :param pred: predicate for face :return: first face with false bfs mark """ for f in self.Faces: if not f.bfs_mark and pred(f): return f return None # ---------------------------------------------------------------------------------------------- def bfs_path(self, start, pred): """ Get BFS path. :param start: start face :param pred: predicate for faces :return: path for whole grid (list of faces) """ # This function uses bfs_mark field for faces. # Reset all faces bfs marks. for f in self.Faces: f.bfs_mark = False p = [] # Walk while we can. while True: p = p + self.bfs_path_connectivity_component(start, pred) start = self.get_no_bfs_mark_face(pred) if start is None: return p # ---------------------------------------------------------------------------------------------- def load(self, filename, is_merge_same_nodes=True): """ Load grid from file. :param filename: file name :param is_merge_same_nodes: merge same nodes """ # Clear all objects of the grid. self.clear() # Open file and try to load it line by line. with open(filename, 'r') as f: line = f.readline() while line: if '# EXPORT_MODE=' in line: # Head of grid. mode_line = line title_line = f.readline() variables_line = f.readline() # Parse all and check. self.Mode = mode_line.split('=')[-1][:-1] if 'TITLE=' not in title_line: raise Exception('Wrong title line ({0}).'.format(title_line)) self.Name = title_line.split('=')[1][1:-2] if 'VARIABLES=' not in variables_line: raise Exception('Wrong variables line ({0}).'.format(variables_line)) self.VariablesStr = variables_line.split('=')[-1][:-1] self.Variables = self.VariablesStr.replace('"', '').replace(',', '').split() self.FaceVariablesCount = len(self.Variables) - 3 elif 'ZONE T=' in line: # Create new zone. zone_name = line.split('=')[-1][1:-2] zone = Zone(zone_name) self.Zones.append(zone) # Read count of nodes and faces to read. nodes_line = f.readline() faces_line = f.readline() packing_line = f.readline() zonetype_line = f.readline() varlocation_line = f.readline() if 'NODES=' not in nodes_line: raise Exception('Wrong nodes line ({0}).'.format(nodes_line)) if 'ELEMENTS=' not in faces_line: raise Exception('Wrong faces line ({0}).'.format(faces_line)) if 'DATAPACKING=BLOCK' != packing_line[:-1]: raise Exception('Wrong packing line ({0}).'.format(packing_line)) if 'ZONETYPE=FETRIANGLE' != zonetype_line[:-1]: raise Exception('Wrong zonetype line ({0}).'.format(zonetype_line)) right_varlocation_line = 'VARLOCATION=' \ '([4-{0}]=CELLCENTERED)'.format(len(self.Variables)) if right_varlocation_line != varlocation_line[:-1]: raise Exception('Wrong varlocation line ({0}). ' 'Right value is {1}'.format(varlocation_line, right_varlocation_line)) nodes_to_read = int(nodes_line.split('=')[-1][:-1]) # print('LOAD: zone {0}, nodes_to_read = {1}'.format(zone_name, nodes_to_read)) faces_to_read = int(faces_line.split('=')[-1][:-1]) # Read data for nodes. c = [] for i in range(3): line = f.readline() c.append([float(xi) for xi in line.split()]) for i in range(nodes_to_read): p = [c[0][i], c[1][i], c[2][i]] node = Node(p) node = self.add_node(node, is_merge_same_nodes) zone.add_node(node) # Read data for faces. d = [] for i in range(self.FaceVariablesCount): line = f.readline() d.append([float(xi) for xi in line.split()]) for i in range(faces_to_read): face = Face([d[j][i] for j in range(self.FaceVariablesCount)]) self.add_face(face) zone.add_face(face) # Read connectivity lists. for i in range(faces_to_read): line = f.readline() face = zone.Faces[i] nodes = [zone.Nodes[int(ss) - 1] for ss in line.split()] if len(nodes) != 3: raise Exception('Wrong count of ' \ 'face linked nodes ({0}).'.format(len(nodes))) Grid.link_node_face(nodes[0], face) Grid.link_node_face(nodes[1], face) Grid.link_node_face(nodes[2], face) else: raise Exception('Unexpected line : {0}.'.format(line)) line = f.readline() f.close() # Now we need to fix rest objects links. for face in self.Faces: node_a = face.Nodes[0] node_b = face.Nodes[1] node_c = face.Nodes[2] self.complex_link_face_node_node_edge(face, node_a, node_b) self.complex_link_face_node_node_edge(face, node_a, node_c) self.complex_link_face_node_node_edge(face, node_b, node_c) # Relink. self.link_nodes_and_edges_to_zones() # ---------------------------------------------------------------------------------------------- def store(self, filename): """ Store grid to file. :param filename: file name """ with open(filename, 'w', newline='\n') as f: # Store head. f.write('# EXPORT_MODE={0}\n'.format(self.Mode)) f.write('TITLE="{0}"\n'.format(self.Name)) f.write('VARIABLES={0}\n'.format(self.VariablesStr)) # Additional structure for calculating local identifiers # of the nodes for connectivity lists storing. loc_ids = [-1] * len(self.Nodes) # Store zones. for zone in self.Zones: # Store zone head. f.write('ZONE T="{0}"\n'.format(zone.Name)) f.write('NODES={0}\n'.format(len(zone.Nodes))) f.write('ELEMENTS={0}\n'.format(len(zone.Faces))) f.write('DATAPACKING=BLOCK\n') f.write('ZONETYPE=FETRIANGLE\n') f.write('VARLOCATION=([4-{0}]=CELLCENTERED)\n'.format(len(self.Variables))) # Write first 3 data items (X, Y, Z coordinates). for i in range(3): f.write(zone.get_nodes_coord_slice_str(i) + ' \n') # Write rest faces data items. for i in range(self.FaceVariablesCount): f.write(zone.get_faces_data_slice_str(i) + ' \n') # Write connectivity lists. for i, node in enumerate(zone.Nodes): loc_ids[node.GloId] = i for face in zone.Faces: f.write(' '.join([str(loc_ids[n.GloId] + 1) for n in face.Nodes]) + '\n') f.close() # ---------------------------------------------------------------------------------------------- def store_mpi(self, filename_base, ts, sf='.cry'): """ Store grid for mpi program. As many processes count as zones count. :param filename_base: base of filename "param ts: timestamp string :param sf: suffixes of files """ zam = ZonesAdjacencyMatrix(self.Edges, self.Zones) # Local identifiers. loc_nodes_ids = [-1] * len(self.Nodes) loc_edges_ids = [-1] * len(self.Edges) for (zi, z) in enumerate(self.Zones): with open('{0}_{1:05d}_{2}{3}'.format(filename_base, zi, ts, sf), 'w', newline='\n') as file: nc = len(z.Nodes) ec = len(z.Edges) fc = len(z.Faces) # Write head information. file.write('TITLE="{0}"\n'.format(z.Name)) variables = self.Variables[:3] + ['GloId'] + self.Variables[3:] variables = ['"{0}"'.format(x) for x in variables] variables_str = ', '.join(variables) file.write('VARIABLES={0}\n'.format(variables_str)) file.write('MPI={0}\n'.format(zi)) file.write('NODES={0}\n'.format(nc)) file.write('EDGES={0}\n'.format(ec)) file.write('CROSS-EDGES={0}\n'.format(zam.zone_cross_edges_count(zi))) file.write('FACES={0}\n'.format(fc)) # Write nodes and faces data. file.write('NODES COORDINATES:\n') for i in range(3): file.write(z.get_nodes_coord_slice_str(i) + ' \n') file.write('FACES DATA:\n') file.write(z.get_faces_global_ids_slice_str() + '\n') for i in range(self.FaceVariablesCount): file.write(z.get_faces_data_slice_str(i) + ' \n') # Write connectivity lists. for i, node in enumerate(z.Nodes): loc_nodes_ids[node.GloId] = i for i, edge in enumerate(z.Edges): loc_edges_ids[edge.GloId] = i file.write('FACE-NODE CONNECTIVITY LIST:\n') for f in z.Faces: file.write(' '.join([str(loc_nodes_ids[n.GloId]) for n in f.Nodes]) + '\n') file.write('FACE-EDGE CONNECTIVITY LIST:\n') for f in z.Faces: file.write(' '.join([str(loc_edges_ids[e.GloId]) for e in f.Edges]) + '\n') file.write('EDGE-NODE CONNECTIVITY LIST:\n') for e in z.Edges: file.write(' '.join([str(loc_nodes_ids[n.GloId]) for n in e.Nodes]) + '\n') # Write MPI-borders. file.write('MPI-BORDERS={0}\n'.format(zam.zone_cross_borders_count(zi))) line = zam.zone_cross_edges_array(zi) for (li, le) in enumerate(line): if le > 0: # Border between zones with indices zi and li. lz = self.Zones[li] # Border between zones z and lz. file.write('[{0}] '.format(li)) for e in z.Edges: if e.is_connect_zones(z, lz): file.write('{0} '.format(loc_edges_ids[e.GloId])) file.write('\n') file.close() # ---------------------------------------------------------------------------------------------- def link_nodes_and_edges_to_zones(self): """ Link nodes and edges to zones. """ # Clear old information. for z in self.Zones: z.Nodes.clear() z.Edges.clear() self.set_zones_ids() # Add nodes. for n in self.Nodes: zids = list(set([f.Zone.Id for f in n.Faces])) for zid in zids: self.Zones[zid].add_node(n) # Add edges. for e in self.Edges: zids = list(set([f.Zone.Id for f in e.Faces])) for zid in zids: self.Zones[zid].add_edge(e) self.reset_zones_ids() # ---------------------------------------------------------------------------------------------- def unlink_faces_from_zones(self): """ Unlink faces from zones. """ for face in self.Faces: if not face.Zone.IsFixed: face.Zone = None # ---------------------------------------------------------------------------------------------- def check_faces_are_linked_to_zones(self): """ Check if all faces are linked to zones. """ for face in self.Faces: if face.Zone is None: raise Exception('Unlinked face detected.') # ---------------------------------------------------------------------------------------------- def decompose_mono(self, new_name=None): """ Create mono distribution (with 1 zone). :param new_name: grid new name """ if new_name is not None: self.Name = new_name # Delete all zones and create one zone with name 'mono'. self.Zones.clear() self.unlink_faces_from_zones() zone = Zone('mono') self.Zones.append(zone) for face in self.Faces: zone.add_face(face) # Link nodes. self.link_nodes_and_edges_to_zones() self.check_faces_are_linked_to_zones() # ---------------------------------------------------------------------------------------------- def decompose_random(self, count=32, new_name=None): """ Create random distribution. :param count: zones count :param new_name: grid new name """ if new_name is not None: self.Name = new_name # Delete all zones. # Create 'count' zones and random distribute faces between them. self.Zones.clear() self.unlink_faces_from_zones() for i in range(count): zone = Zone('random ' + str(i)) self.Zones.append(zone) for face in self.Faces: self.Zones[random.randint(0, count - 1)].add_face(face) # Link nodes. self.link_nodes_and_edges_to_zones() self.check_faces_are_linked_to_zones() # ---------------------------------------------------------------------------------------------- def decompose_linear(self, count=32, new_name=None): """ Linear distribution. :param count: zones count :param new_name: grid new name """ if new_name is not None: self.Name = new_name fc = len(self.Faces) fcpz = fc // count fcrm = fc % count # Delete all zones. # Create 'count' zones and random distribute faces between them. self.Zones.clear() self.unlink_faces_from_zones() for i in range(count): zone = Zone('linear ' + str(i)) self.Zones.append(zone) # Distribute faces accurately. cur_face_i = 0 for (i, zone) in enumerate(self.Zones): faces_to_add = fcpz if i < fcrm: faces_to_add += 1 for j in range(cur_face_i, cur_face_i + faces_to_add): zone.add_face(self.Faces[j]) cur_face_i += faces_to_add if cur_face_i != fc: raise Exception('Wrong linera distribution mathematics.') # Link nodes. self.link_nodes_and_edges_to_zones() self.check_faces_are_linked_to_zones() # ---------------------------------------------------------------------------------------------- def split_zone_metric(self, zone, zl, zr, fun): """ Split zone, calculate metric and roll-back. :param zone: zone :param zl: left child zone :param zr: right child zone :param fun: function for sign extraction :return: metric """ # Now all faces are in zone. signs = [fun(f) for f in zone.Faces] signs.sort() blade = signs[len(signs) // 2] # Distribute. zlc = 0 zrc = 0 for f in zone.Faces: if fun(f) < blade: f.Zone = zl zlc += 1 else: f.Zone = zr zrc += 1 # Prevent empty zone. if (zlc == 0) or (zrc == 0): return math.inf # Metric. r = 0 for f in zone.Faces: for e in f.Edges: if len(e.Faces) == 2: ff = e.Faces[0] sf = e.Faces[1] if (ff.Zone == zl and sf.Zone == zr) or (ff.Zone == zr and sf.Zone == zl): r += 1 # Roll back. for f in zone.Faces: f.Zone = zone return r # ---------------------------------------------------------------------------------------------- def split_zone(self, zone, extract_signs_funs): """ Split zone. :param zone: zone :param extract_signs_funs: list of functions for extraction. """ # Do not split zone if it is fixed. if zone.IsFixed: self.Zones.remove(zone) self.Zones.append(zone) return # Do not split zone if it is impossible. if len(zone.Faces) < 2: print('Warning : not enough faces to split zone {0} ' \ '({1} faces).'.format(zone.Name, len(zone.Faces))) # Replace to the end. self.Zones.remove(zone) self.Zones.append(zone) return # Technical actions. zl = Zone(zone.Name + 'l') zr = Zone(zone.Name + 'r') self.Zones.remove(zone) self.Zones.append(zl) self.Zones.append(zr) # Explore metrics. metrics = [self.split_zone_metric(zone, zl, zr, extract_signs_funs[i]) for i in range(len(extract_signs_funs))] min_metric = min(metrics) if min_metric is math.inf: print('Warning : bad metrics to split zone {0}'.format(zone.Name)) # Replace to the end. self.Zones.remove(zone) self.Zones.append(zone) return spl_index = metrics.index(min_metric) # Split. signs = [extract_signs_funs[spl_index](f) for f in zone.Faces] signs.sort() blade = signs[len(signs) // 2] for face in zone.Faces: if extract_signs_funs[spl_index](face) < blade: zl.add_face(face) else: zr.add_face(face) # ---------------------------------------------------------------------------------------------- def decompose_hierarchical(self, extract_signs_funs, levels=6, new_name=None, fixed_zones=[]): """ Hierarchical distribution with given numbers of levels. :param extract_signs_funs: list of functions for signs extraction :param levels: levels count :param new_name: grid new name :param fixed_zones: list of fixed zones """ # Mark fixed zones. for z in self.Zones: z.IsFixed = z.Name in fixed_zones if new_name is not None: self.Name = new_name # Delete all zones (not fixed) and links. self.Zones = [z for z in self.Zones if z.IsFixed] self.unlink_faces_from_zones() # Check levels. if levels < 1: raise Exception('It must be at least 1 level.') zone = Zone('h') self.Zones.append(zone) for face in self.Faces: if face.Zone is None: zone.add_face(face) for li in range(levels - 1): c = len(self.Zones) for zi in range(c): # nm = self.Zones[0].Name # print('split zone {0} -> {1}, {2}.'.format(nm, nm + 'l', nm + 'r')) self.split_zone(self.Zones[0], extract_signs_funs) # Links nodes. self.link_nodes_and_edges_to_zones() self.check_faces_are_linked_to_zones() # ---------------------------------------------------------------------------------------------- def each_zone_capture_nearest_face(self): """ Each zone capture nearest face. """ for z in self.Zones: z.capture_nearest_face() # ---------------------------------------------------------------------------------------------- def decompose_pressure(self, count=32, new_name=None, fz_names=[]): """ Create distribution based on pressure algorithm. :param count: zones count :param new_name: grid new name :param fz_names: list of fixed zones names """ # Mark fixed zones. for z in self.Zones: z.IsFixed = z.Name in fz_names if new_name is not None: self.Name = new_name # Keep fixed zones and create additional. self.Zones = [z for z in self.Zones if z.IsFixed] fz_count = len(self.Zones) self.unlink_faces_from_zones() for i in range(count): zone = Zone('pressure ' + str(i)) self.Zones.append(zone) # # Distribute faces between zones. # fc = self.faces_count() - self.faces_count_in_fixed_zones() zone_sizes = [fc // count + (fc % count > i) for i in range(count)] # Put right number of faces into each zone. start = self.Faces[0] for i in range(count): z = self.Zones[i + fz_count] zone_size = zone_sizes[i] path = self.bfs_path(start, lambda f: (f.Zone is None)) for fi in range(zone_size): z.add_face(path[fi]) if len(path) > zone_size: start = path[zone_size] # Link nodes. self.link_nodes_and_edges_to_zones() self.check_faces_are_linked_to_zones() # ---------------------------------------------------------------------------------------------- def box(self): """ Get box around grid (tuple with 6 values - XYZ of the left down back point and XYZ of the right up front point). :return: tuple """ xs = [n.P[0] for n in self.Nodes] ys = [n.P[1] for n in self.Nodes] zs = [n.P[2] for n in self.Nodes] return min(xs), min(ys), min(zs), max(xs), max(ys), max(zs) # ---------------------------------------------------------------------------------------------- def move_from_mean_point(self, k=0.1): """ Move zones from mean point. :param k: factor while zones moving """ gx, gy, gz = mean_nodes_point(self.Nodes) for z in self.Zones: zx, zy, zz = mean_nodes_point(z.Nodes) vx, vy, vz = k * (zx - gz), k * (zy - gy), k * (zz - gz) for n in z.Nodes: p = n.P n.P = (p[0] + vx, p[1] + vy, p[2] + vz) # ---------------------------------------------------------------------------------------------- def store_faces_calc_data(self, filename): """ Store calc values to file. :param filename: name of file """ with open(filename, 'w', newline='\n') as f: f.write('VARIABLES="GloId", "T", "Hw", "Hi"\n') for face in self.Faces: p = mean_nodes_point(face.Nodes) f.write(face.get_glo_id_t_hw_hi_str() + '\n') f.close() # ---------------------------------------------------------------------------------------------- def load_faces_calc_data(self, filename): """ Load calc data from file and write it to grid. Warning! This function rewrite VARIABLES list of grid. :param filename: name of file """ with open(filename, 'r') as f: line = f.readline() while line: if 'VARIABLES=' in line: # Set new variables. variables_xyz = '"X", "Y", "Z"' variables_oth = line.split('=')[-1][9:-1] # We know only basic modes. if variables_oth == '"T", "Hw", "Hi"': self.Mode = 'BASIC' elif variables_oth == '"T", "Hw", "Hi", "HTC", "Beta", "TauX", "TauY", "TauZ"': self.Mode = 'CHECK_POINT' elif variables_oth == '"MassImpinged", "WaterFilmHeight", "CurrentIceGrowth", ' \ '"TotalIceGrowth", "CurrentMassEvaporation", ' \ '"SurfaceTemperature", ' \ '"FilmVx", "FilmVy", "FilmVz", "FilmV", ' \ '"IcesolConvectiveFlux", ' \ '"EvapHeatFlux", "IceThickness", "HTC"': self.Mode = 'CIAM' else: raise Exception('unknown export mode') self.VariablesStr = variables_xyz + ', ' + variables_oth self.Variables = self.VariablesStr.replace('"', '').replace(',', '').split() self.FaceVariablesCount = len(self.Variables) - 3 else: ss = line.split() glo_id = int(ss[0]) ss = ss[1:] face = self.Faces[glo_id] face.Data = [float(x) for x in ss] line = f.readline() f.close() # ==================================================================================================
Java
UTF-8
1,396
1.78125
2
[ "Apache-2.0" ]
permissive
// Copyright (C) 2015 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.server.account; import com.google.gerrit.server.git.ValidationError; import com.google.gerrit.server.git.meta.TabFile; import java.io.IOException; import java.util.List; import java.util.Map; public class QueryList extends TabFile { public static final String FILE_NAME = "queries"; protected final Map<String, String> queriesByName; private QueryList(List<Row> queriesByName) { this.queriesByName = toMap(queriesByName); } static QueryList parse(String text, ValidationError.Sink errors) throws IOException { return new QueryList(parse(text, FILE_NAME, TRIM, TRIM, errors)); } public String getQuery(String name) { return queriesByName.get(name); } String asText() { return asText("Name", "Query", queriesByName); } }
Java
UTF-8
3,024
2.203125
2
[]
no_license
/* SpagoBI, the Open Source Business Intelligence suite * Copyright (C) 2012 Engineering Ingegneria Informatica S.p.A. - SpagoBI Competency Center * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0, without the "Incompatible With Secondary Licenses" notice. * If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package it.eng.spagobi.utilities.filters; import it.eng.spagobi.container.ContextManager; import it.eng.spagobi.container.SpagoBIHttpSessionContainer; import it.eng.spagobi.container.strategy.ExecutionContextRetrieverStrategy; import it.eng.spagobi.container.strategy.IContextRetrieverStrategy; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; /** * @author Andrea Gioia (andrea.gioia@eng.it) * */ public class FilterIOManager { ServletRequest request; ServletResponse response; ContextManager contextManager; private static final String EXECUTION_ID = "SBI_EXECUTION_ID"; //---------------------------------------------------------------------------------------------------- // Constructor //---------------------------------------------------------------------------------------------------- public FilterIOManager(ServletRequest request, ServletResponse response) { setRequest( request ); setResponse( response ); } //---------------------------------------------------------------------------------------------------- // Accessor methods //---------------------------------------------------------------------------------------------------- public ServletRequest getRequest() { return request; } public void setRequest(ServletRequest request) { this.request = request; } public ServletResponse getResponse() { return response; } public void setResponse(ServletResponse response) { this.response = response; } /** * @deprecated */ public HttpSession getSession() { return ((HttpServletRequest)getRequest()).getSession(); } /** * @deprecated */ public Object getFromSession(String key) { return getSession().getAttribute(key); } /** * @deprecated */ public void setInSession(String key, Object value) { getSession().setAttribute(key, value); } public void initConetxtManager() { SpagoBIHttpSessionContainer sessionContainer; IContextRetrieverStrategy contextRetriveStrategy; String executionId; sessionContainer = new SpagoBIHttpSessionContainer( getSession() ); executionId = (String)getRequest().getParameter(EXECUTION_ID); contextRetriveStrategy = new ExecutionContextRetrieverStrategy( executionId ); setContextManager( new ContextManager(sessionContainer, contextRetriveStrategy) ); } public ContextManager getContextManager() { return contextManager; } public void setContextManager(ContextManager contextManager) { this.contextManager = contextManager; } }
Python
UTF-8
529
4.4375
4
[]
no_license
#Additional Program #Aug. 30, 2020 #Create a variable and assign a number to it in a range from 80 to 100 #For the given number, calculate the letter grade #-------------------------------------------------------------------------- import random x = random.randint(80, 100) print("Numerical Grade:\t\t", x) if (x >= 95 or x == 100): print("Letter Grade:\t\tA+") elif (x >= 90 and x < 95): print("Letter Grade:\t\tA") elif (x >= 85 and x < 90): print("Letter Grade:\t\tA-") else: print("Letter Grade:\t\tB+")
Java
UTF-8
4,410
2.46875
2
[]
no_license
package com.testmanage.oldtest.view; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View; import com.testmanage.R; /** * Created by Administrator on 2016/3/30. */ public class CustomProgreeView extends View { //第一个颜色 private int mFirstColor; //第二个颜色 private int mSecondColor; //速度 private int mSpeed; //圆环宽度 private int mCircleWidth; private Paint mPaint; //当前进度 private int mProgress; //是否进行下一个 private boolean isNext = false; public CustomProgreeView(Context context) { this(context, null); // init(); } public CustomProgreeView(Context context, AttributeSet attrs) { this(context, attrs, 0); // init(); } /** * 获取自定义属性 * * @param context * @param attrs * @param defStyleAttr */ public CustomProgreeView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); TypedArray array = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomProgreeView, defStyleAttr, 0); int n = array.getIndexCount(); for (int i = 0; i < n; i++) { int attr = array.getIndex(i); switch (attr) { case R.styleable.CustomProgreeView_firstColor: mFirstColor = array.getColor(attr, Color.BLACK); break; case R.styleable.CustomProgreeView_secondColor: mSecondColor = array.getColor(attr, Color.BLACK); break; case R.styleable.CustomProgreeView_circleWidth: mCircleWidth = array.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 20, getResources().getDisplayMetrics())); // mCircleWidth = array.getInt(attr,0); break; case R.styleable.CustomProgreeView_speed: mSpeed = array.getInt(attr, 20); break; } } array.recycle(); mPaint = new Paint(); //绘图线程 new Thread(new Runnable() { @Override public void run() { while (true) { mProgress++; if (mProgress == 360) { //满一个圆圈就重绘 mProgress = 0; if (!isNext) { isNext = true; } else { isNext = false; } } postInvalidate(); try { Thread.sleep(mSpeed); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int center = getWidth() / 2; //获取中心点 int radius = center - mCircleWidth / 2; //计算半径 mPaint.setStrokeWidth(mCircleWidth); //设置圆环宽度 mPaint.setAntiAlias(true); mPaint.setStyle(Paint.Style.STROKE); //设置空心 //用于定义圆弧的形状和大小 RectF rectF = new RectF(center - radius, center - radius, center + radius, center + radius); mPaint.setStrokeCap(Paint.Cap.ROUND); // 定义线段形状为圆头 if (!isNext) { //第一圈颜色完整,跑第二圈 mPaint.setColor(mFirstColor); //设置圆环颜色 canvas.drawCircle(center, center, radius, mPaint); //画出圆环 mPaint.setColor(mSecondColor); // 设置圆环颜色 canvas.drawArc(rectF, -90, mProgress, false, mPaint); //根据进度画圆弧 } else { mPaint.setColor(mSecondColor); canvas.drawCircle(center, center, radius, mPaint); mPaint.setColor(mFirstColor); canvas.drawArc(rectF, -90, mProgress, false, mPaint); } } }
Python
UTF-8
1,268
2.5625
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os from epa.utils import get_class_with_name, ClassNotFoundError class Handler(object): handler_id = None def close(self): raise NotImplementedError def read(self): """ Read one Parameters ---------- None Returns ------- generator with object JSON decoded object """ raise NotImplementedError def write(self, value): """ Write multi Parameters ---------- value : object a JSON encodable object Returns ------- None """ raise NotImplementedError def _get_py_module(dirname): for f in os.listdir(dirname): name, ext = os.path.splitext(f) if os.path.isfile(os.path.join(dirname, f)) and \ ext == ".py" and \ not name.startswith("__"): yield name def get_handler_cls(handler_cls_name): for name in _get_py_module(os.path.dirname(__file__)): try: cls = get_class_with_name(f"handler.{name}", handler_cls_name) return cls except ClassNotFoundError: continue raise ClassNotFoundError
Java
UTF-8
1,066
2.828125
3
[]
no_license
package com.hmdu.bigdata.rpc; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.ipc.RPC; import java.io.IOException; import java.net.InetSocketAddress; /** * @ Author :liuhao * @ Date :Created in 14:13 2018/6/26 * @ rpc客户端: * 首先使用RPC的getPRroxy方法获取RPC客户端的代理类,也就是客户端类实现的接口,用来向服务器发送消息 */ public class RPCClient implements Hello { @Override public String say(String words) { return "success"; } public static void main(String[] args) { try { while (true) { Hello hello = RPC.getProxy(Hello.class, 1L, new InetSocketAddress("127.0.0.1", 6666), new Configuration()); String ret = hello.say("I am datanode01, I am live..."); System.out.println(ret); Thread.sleep(3000); } } catch (IOException | InterruptedException e) { e.printStackTrace(); } } }
Python
UTF-8
413
3.65625
4
[]
no_license
# message = 'A: Valar Morgulis! B: Valar Dahaeris..' # print(message) # print(len(message)) # print(message[0:].lower()) # print(message.count('A')) # #string.find -> shows from where the searched str starts # x = message.replace('A:', 'S:') # print(x) greeting = 'Cyka' name = 'Michael' beleidigung = 'Gandon, eb tvou mat`' bb = 'bb...' message = f'{greeting}, {name}, {beleidigung}. Welcome {bb}' print(help(str.lower))
C++
UTF-8
2,692
2.9375
3
[]
no_license
/* * Copyright (c) 2003 Duke University All rights reserved. * See COPYING for license statement. */ #include <boost/config.hpp> #include <iostream> #include <vector> #include <map> #include <utility> #include <algorithm> #include <string> #include <boost/graph/adjacency_list.hpp> using namespace boost; using namespace std; #include "mngraph.h" //This functor prints a (key,value) pair as key="value" template <class T> struct PrintPair{ string _prefix; ostream& _out; PrintPair(ostream& out=cout, string prefix=""):_prefix(prefix), _out(out){} void operator()(const string& key, const T& value) const { _out << " " << _prefix << key << "=\"" << value << "\""; } }; // Print all the attributes in an AttributeMap to out, with type prefixes void printAttributes(ostream& out, AttributeMap& attr) { attr.forEachString(PrintPair<string>(out,"")); attr.forEachInt(PrintPair<int>(out,"int_")); attr.forEachDouble(PrintPair<double>(out,"dbl_")); } /***************************************** * GraphXMLPrinter works for iteration over vertices and edges, and prints * each element as XML. *****************************************/ struct GraphXMLPrinter { int _indent; ostream& _out; GraphXMLPrinter(ostream& out=cout, int indent=0):_indent(indent),_out(out){} // For iteration over vertices void operator()(MNGraph& g, const MNGraph::Vertex& v) const { _out << string(_indent,' ') << "<vertex"; printAttributes(_out, g[v]); _out << "/> " << endl; } //For iteration over edges void operator()(MNGraph& g, const MNGraph::Edge& e) const { _out << string(_indent,' ') << "<edge"; printAttributes(_out, g[e]); _out << "/> " << endl; } }; // Print g to out as XML void write_to_xml(MNGraph& g, ostream& out) { out << "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" << endl; out << "<topology"; printAttributes(out, g); out << ">" << endl; GraphXMLPrinter printer(out,8); out << " <vertices>" << endl; g.for_each_vertex(printer); out << " </vertices>" << endl; out << " <edges>" << endl; g.for_each_edge(printer); out << " </edges>" << endl; out << "</topology>" << endl; } #if 0 int main(int, char*[]) { std::size_t N = 10; MNGraph g(N); unsigned int i; // Create random edges for (i=0; i<N*N/8; ++i) { std::size_t a = rand()%N, b = rand()%N; while ( a == b ) b = rand()%N; // Get the descriptor for a new edge. MNGraph::Edge e = add_edge(a, b, g).first; // Set an attribute of the edge g[e].d("bw") = rand()*3.14; } // Set graph attributes g.s("name") = "test graph"; g.i("num_vertices") = num_vertices(g); g.i("num_edges") = num_edges(g); // Output write_to_xml(g); return 0; } #endif
JavaScript
UTF-8
934
2.5625
3
[]
no_license
/** 数据初始化 */ import { observe } from './observe/index' export function initState (vm) { const options = vm.$options // vue 的数据来源 属性 方法 数据 计算属性 watch if (options.props) { initProps(vm) } if (options.methods) { initMethod(vm) } if (options.data) { initData(vm) } if (options.computed) { initComputed(vm) } if (options.watch) { initWatch(vm) } } function initProps (vm) { } function initMethod (vm) { } function initData (vm) { // 数据的初始化工作 // 用户传递的 data let data = vm.$options.data data = vm._data = typeof data === 'function' ? data.call(vm) : data // 对象劫持, 用户改变数据, 获得通知 // MVVM 模式, 数据变化驱动视图变化 // Object.defineProperty() 给属性增加 get 方法和 set 方法 observe(data) // 响应式原理 } function initComputed (vm) { } function initWatch (vm) { }
C
UTF-8
23,065
2.515625
3
[ "Apache-2.0", "LicenseRef-scancode-gary-s-brown", "Unlicense", "BSD-2-Clause" ]
permissive
/** * * @file: fb_smo_jerry_test1.c * * @copyright * Copyright 2016-2020 Fitbit, Inc * SPDX-License-Identifier: Apache-2.0 * * @author Gilles Boccon-Gibod * * @date 2016-11-05 * * @details * * Simple Multipurpose Objects - JerryScript Tests 1 * */ /*---------------------------------------------------------------------- | includes +---------------------------------------------------------------------*/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "jerryscript.h" #include "jerryscript-port-default.h" #include "fb_smo_jerryscript.h" /*---------------------------------------------------------------------- | macros +---------------------------------------------------------------------*/ /* use this so we can put a breakpoint */ static void print_error(unsigned int line) { fprintf(stderr, "ERROR line %d\n", line); } #define CHECK(x) do { \ if (!(x)) { \ print_error(__LINE__); \ return 1; \ } \ } while(0) #define CHECK_E(x) do { \ if (!(x)) { \ print_error(__LINE__); \ exit(1); \ } \ } while(0) /*---------------------------------------------------------------------- | InjectCbor +---------------------------------------------------------------------*/ static int InjectCbor(const uint8_t* cbor, unsigned int cbor_size) { int result; jerry_value_t obj; result = Fb_Smo_Deserialize_CBOR_ToJerry(NULL, cbor, cbor_size, &obj); if (result != FB_SMO_SUCCESS) { return result; } { jerry_value_t global = jerry_get_global_object(); jerry_value_t obj_name = jerry_create_string((const jerry_char_t*)"cbor"); jerry_set_property(global, obj_name, obj); jerry_release_value(obj); jerry_release_value(obj_name); jerry_release_value(global); } return 0; } /*---------------------------------------------------------------------- | MakeRandomCbor +---------------------------------------------------------------------*/ uint8_t cbor_test1[] = { 12 }; static int MakeRandomCbor(uint8_t** cbor, unsigned int* cbor_size) { *cbor = cbor_test1; *cbor_size = 1; return 0; } /*---------------------------------------------------------------------- | BasicTypesTest +---------------------------------------------------------------------*/ static int BasicTypesTest(void) { /* init JerryScript */ jerry_init(JERRY_INIT_EMPTY); jerry_value_t obj; const uint8_t cbor_zero[5] = { 0x00 }; // 0 int result = Fb_Smo_Deserialize_CBOR_ToJerry(NULL, cbor_zero, sizeof(cbor_zero), &obj); CHECK(result == FB_SMO_SUCCESS); CHECK(jerry_value_is_number(obj)); CHECK((uint32_t)jerry_get_number_value(obj) == 0); jerry_release_value(obj); const uint8_t cbor_tiny_positive_int[5] = { 0x01 }; // 1 result = Fb_Smo_Deserialize_CBOR_ToJerry(NULL, cbor_tiny_positive_int, sizeof(cbor_tiny_positive_int), &obj); CHECK(result == FB_SMO_SUCCESS); CHECK(jerry_value_is_number(obj)); CHECK((uint32_t)jerry_get_number_value(obj) == 1); jerry_release_value(obj); const uint8_t cbor_tiny_negative_int[5] = { 0x20 }; // -1 result = Fb_Smo_Deserialize_CBOR_ToJerry(NULL, cbor_tiny_negative_int, sizeof(cbor_tiny_negative_int), &obj); CHECK(result == FB_SMO_SUCCESS); CHECK(jerry_value_is_number(obj)); CHECK((int32_t)jerry_get_number_value(obj) == -1); jerry_release_value(obj); const uint8_t cbor_small_positive_int[5] = { 0x18, 0x55 }; // 85 result = Fb_Smo_Deserialize_CBOR_ToJerry(NULL, cbor_small_positive_int, sizeof(cbor_small_positive_int), &obj); CHECK(result == FB_SMO_SUCCESS); CHECK(jerry_value_is_number(obj)); CHECK((uint32_t)jerry_get_number_value(obj) == 85); jerry_release_value(obj); const uint8_t cbor_small_negative_int[5] = { 0x38, 0x54 }; // -85 result = Fb_Smo_Deserialize_CBOR_ToJerry(NULL, cbor_small_negative_int, sizeof(cbor_small_negative_int), &obj); CHECK(result == FB_SMO_SUCCESS); CHECK(jerry_value_is_number(obj)); CHECK((int32_t)jerry_get_number_value(obj) == -85); jerry_release_value(obj); const uint8_t cbor_medium_positive_int[5] = { 0x19, 0x55, 0x66 }; // 21862 result = Fb_Smo_Deserialize_CBOR_ToJerry(NULL, cbor_medium_positive_int, sizeof(cbor_medium_positive_int), &obj); CHECK(result == FB_SMO_SUCCESS); CHECK(jerry_value_is_number(obj)); CHECK((uint32_t)jerry_get_number_value(obj) == 21862); jerry_release_value(obj); const uint8_t cbor_medium_negative_int[5] = { 0x39, 0x55, 0x65 }; // -21862 result = Fb_Smo_Deserialize_CBOR_ToJerry(NULL, cbor_medium_negative_int, sizeof(cbor_medium_negative_int), &obj); CHECK(result == FB_SMO_SUCCESS); CHECK(jerry_value_is_number(obj)); CHECK((int32_t)jerry_get_number_value(obj) == -21862); jerry_release_value(obj); const uint8_t cbor_positive_int[5] = { 0x1a, 0x00, 0x12, 0xd6, 0x87 }; // 1234567 result = Fb_Smo_Deserialize_CBOR_ToJerry(NULL, cbor_positive_int, sizeof(cbor_positive_int), &obj); CHECK(result == FB_SMO_SUCCESS); CHECK(jerry_value_is_number(obj)); CHECK((uint32_t)jerry_get_number_value(obj) == 1234567); jerry_release_value(obj); const uint8_t cbor_negative_int[5] = { 0x3a, 0x00, 0x12, 0xd6, 0x86 }; // -1234567 result = Fb_Smo_Deserialize_CBOR_ToJerry(NULL, cbor_negative_int, sizeof(cbor_negative_int), &obj); CHECK(result == FB_SMO_SUCCESS); CHECK(jerry_value_is_number(obj)); CHECK((int32_t)jerry_get_number_value(obj) == -1234567); jerry_release_value(obj); const uint8_t cbor_float[9] = { 0xfb, 0x3f, 0xf3, 0xc0, 0xc9, 0x53, 0x9b, 0x88, 0x87 }; // 1.234567 result = Fb_Smo_Deserialize_CBOR_ToJerry(NULL, cbor_float, sizeof(cbor_float), &obj); CHECK(result == FB_SMO_SUCCESS); CHECK(jerry_value_is_number(obj)); CHECK(jerry_get_number_value(obj) == 1.234567); jerry_release_value(obj); const uint8_t cbor_false[1] = { 0xf4 }; // false result = Fb_Smo_Deserialize_CBOR_ToJerry(NULL, cbor_false, sizeof(cbor_false), &obj); CHECK(result == FB_SMO_SUCCESS); CHECK(jerry_value_is_boolean(obj)); CHECK(jerry_get_boolean_value(obj) == false); jerry_release_value(obj); const uint8_t cbor_true[1] = { 0xf5 }; // true result = Fb_Smo_Deserialize_CBOR_ToJerry(NULL, cbor_true, sizeof(cbor_true), &obj); CHECK(result == FB_SMO_SUCCESS); CHECK(jerry_value_is_boolean(obj)); CHECK(jerry_get_boolean_value(obj) == true); jerry_release_value(obj); const uint8_t cbor_null[1] = { 0xf6 }; // null result = Fb_Smo_Deserialize_CBOR_ToJerry(NULL, cbor_null, sizeof(cbor_null), &obj); CHECK(result == FB_SMO_SUCCESS); CHECK(jerry_value_is_null(obj)); jerry_release_value(obj); const uint8_t cbor_undefined[1] = { 0xf7 }; // 'undefined' result = Fb_Smo_Deserialize_CBOR_ToJerry(NULL, cbor_undefined, sizeof(cbor_undefined), &obj); CHECK(result == FB_SMO_SUCCESS); CHECK(jerry_value_is_undefined(obj)); jerry_release_value(obj); const uint8_t cbor_string[10] = { 0x69, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0xcf, 0x80 }; // "Hello, π" result = Fb_Smo_Deserialize_CBOR_ToJerry(NULL, cbor_string, sizeof(cbor_string), &obj); CHECK(result == FB_SMO_SUCCESS); CHECK(jerry_value_is_string(obj)); uint8_t str_buffer[10] = {}; jerry_string_to_utf8_char_buffer(obj, str_buffer, sizeof(str_buffer)); CHECK(!strcmp((const char*)str_buffer, "Hello, π")); jerry_release_value(obj); const uint8_t cbor_bytes[4] = { 0x43, 0x01, 0x02, 0x03 }; // 3 bytes 0x00 0x01 0x02 uint8_t cbor_bytes_check[4]; unsigned int cbor_bytes_check_size = sizeof(cbor_bytes_check); result = Fb_Smo_Deserialize_CBOR_ToJerry(NULL, cbor_bytes, sizeof(cbor_bytes), &obj); CHECK(result == FB_SMO_SUCCESS); CHECK(jerry_value_is_object(obj)); result = Fb_Smo_Serialize_CBOR_FromJerry(obj, cbor_bytes_check, &cbor_bytes_check_size, 1, NULL, NULL); CHECK(result == FB_SMO_SUCCESS); CHECK(cbor_bytes_check_size == 0); CHECK(memcmp(cbor_bytes_check, cbor_bytes, sizeof(cbor_bytes)) == 0); jerry_release_value(obj); const uint8_t cbor_array[4] = { 0x83, 0x01, 0x02, 0x03 }; // [1,2,3] result = Fb_Smo_Deserialize_CBOR_ToJerry(NULL, cbor_array, sizeof(cbor_array), &obj); CHECK(result == FB_SMO_SUCCESS); CHECK(jerry_value_is_array(obj)); CHECK(jerry_get_array_length(obj) == 3); jerry_value_t key0 = jerry_create_string((const jerry_char_t*)"0"); jerry_value_t j0 = jerry_get_property(obj, key0); jerry_release_value(key0); CHECK(jerry_value_is_number(j0)); CHECK(jerry_get_number_value(j0) == 1); jerry_release_value(j0); jerry_value_t key1 = jerry_create_string((const jerry_char_t*)"1"); jerry_value_t j1 = jerry_get_property(obj, key1); jerry_release_value(key1); CHECK(jerry_value_is_number(j1)); CHECK(jerry_get_number_value(j1) == 2); jerry_release_value(j1); jerry_value_t key2 = jerry_create_string((const jerry_char_t*)"2"); jerry_value_t j2 = jerry_get_property(obj, key2); jerry_release_value(key2); CHECK(jerry_value_is_number(j2)); CHECK(jerry_get_number_value(j2) == 3); jerry_release_value(j2); jerry_release_value(obj); const uint8_t cbor_obj[7] = { 0xa2, 0x61, 0x61, 0x01, 0x61, 0x62, 0x02 }; // {a:1, b:2} result = Fb_Smo_Deserialize_CBOR_ToJerry(NULL, cbor_obj, sizeof(cbor_obj), &obj); CHECK(result == FB_SMO_SUCCESS); CHECK(jerry_value_is_object(obj)); jerry_value_t keys = jerry_get_object_keys(obj); CHECK(jerry_get_array_length(keys) == 2); key0 = jerry_get_property_by_index(keys, 0); jerry_value_t val0 = jerry_get_property(obj, key0); jerry_release_value(key0); CHECK(jerry_get_number_value(val0) == 1); jerry_release_value(val0); key1 = jerry_get_property_by_index(keys, 1); jerry_value_t val1 = jerry_get_property(obj, key1); jerry_release_value(key1); CHECK(jerry_get_number_value(val1) == 2); jerry_release_value(val1); jerry_release_value(keys); jerry_release_value(obj); const uint8_t cbor_obj2[7] = { 0xa1, 0x62, 0xcf, 0x80, 0x62, 0xcf, 0x80 }; // {π, "π"} result = Fb_Smo_Deserialize_CBOR_ToJerry(NULL, cbor_obj2, sizeof(cbor_obj2), &obj); CHECK(result == FB_SMO_SUCCESS); CHECK(jerry_value_is_object(obj)); keys = jerry_get_object_keys(obj); CHECK(jerry_get_array_length(keys) == 1); key0 = jerry_get_property_by_index(keys, 0); val0 = jerry_get_property(obj, key0); jerry_release_value(key0); CHECK(jerry_value_is_string(val0)); jerry_release_value(val0); jerry_release_value(keys); jerry_release_value(obj); jerry_cleanup(); return 0; } /*---------------------------------------------------------------------- | FailuresTest +---------------------------------------------------------------------*/ static int FailuresTest() { jerry_init(JERRY_INIT_EMPTY); const uint8_t cbor_obj[7] = { 0xa2, 0x01, 0x01, 0x02, 0x02 }; // invalid object with integer keys {1:1, 1:2} jerry_value_t obj; int result = Fb_Smo_Deserialize_CBOR_ToJerry(NULL, cbor_obj, sizeof(cbor_obj), &obj); CHECK(result == FB_SMO_ERROR_INVALID_FORMAT); #if 0 // JerryScript seems to exit on out of memory conditions! uint8_t longstring_cbor[] = { 0x78, 0x33, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a }; unsigned int i; for (i=0; i<10000; i++) { result = Fb_Smo_Deserialize_CBOR_ToJerry(NULL, longstring_cbor, sizeof(longstring_cbor), &obj); } #endif jerry_cleanup(); return 0; } /*---------------------------------------------------------------------- | SimpleParseTest +---------------------------------------------------------------------*/ static int SimpleParseTest(void) { /* init JerryScript */ jerry_init(JERRY_INIT_EMPTY); jerry_value_t ret_value = jerry_create_undefined (); const char* source = "JSON.stringify(cbor);"; ret_value = jerry_parse((const jerry_char_t*)source, strlen(source), false); uint8_t* cbor = NULL; unsigned int cbor_size = 0; int result = MakeRandomCbor(&cbor, &cbor_size); CHECK(result == FB_SMO_SUCCESS); CHECK(!jerry_value_is_error(ret_value)); InjectCbor(cbor, cbor_size); jerry_value_t func_val = ret_value; ret_value = jerry_run(func_val); jerry_release_value(func_val); CHECK(!jerry_value_is_error(ret_value)); jerry_release_value (ret_value); jerry_cleanup(); return 0; } /*---------------------------------------------------------------------- | SimpleSerializeTest +---------------------------------------------------------------------*/ static int SimpleSerializeTest(void) { /* init JerryScript */ jerry_init(JERRY_INIT_EMPTY); jerry_value_t ret_value = jerry_create_undefined (); const char* source = "({object1: {a:1, b:2}, array1: [1, 2, 'hello', 1.2345], float1: 1.2345, string1: 'someString', number1: 12345, bool1: false, bool2: true, nullv: null, undef: undefined, ninf: -Infinity, pinf: Infinity, nan: NaN});"; ret_value = jerry_parse((const jerry_char_t*)source, strlen(source), false); CHECK(!jerry_value_is_error(ret_value)); jerry_value_t func_val = ret_value; ret_value = jerry_run(func_val); jerry_release_value(func_val); CHECK(!jerry_value_is_error(ret_value)); uint8_t* cbor = NULL; unsigned int cbor_size = 0; unsigned int cbor_size_copy = 0; int result = Fb_Smo_Serialize_CBOR_FromJerry(ret_value, NULL, &cbor_size, 16, NULL, NULL); CHECK(result == FB_SMO_SUCCESS); CHECK(cbor_size != 0); cbor = (uint8_t*)malloc(cbor_size); cbor_size_copy = cbor_size; result = Fb_Smo_Serialize_CBOR_FromJerry(ret_value, cbor, &cbor_size, 16, NULL, NULL); CHECK(result == FB_SMO_SUCCESS); CHECK(cbor_size == 0); cbor_size = cbor_size_copy; jerry_value_t obj_out; result = Fb_Smo_Deserialize_CBOR_ToJerry(NULL, cbor, cbor_size, &obj_out, NULL, NULL); CHECK(result == FB_SMO_SUCCESS); CHECK(!jerry_value_is_undefined(obj_out)); jerry_value_t keys = jerry_get_object_keys(obj_out); uint32_t key_count = jerry_get_array_length(keys); jerry_release_value(keys); CHECK(key_count == 12); jerry_value_t string1_prop = jerry_create_string((const jerry_char_t*)"string1"); CHECK(!jerry_value_is_error(string1_prop)); jerry_value_t string1 = jerry_get_property(obj_out, string1_prop); jerry_release_value(string1_prop); CHECK(jerry_value_is_string(string1)); jerry_char_t buf[50] = {}; jerry_string_to_utf8_char_buffer(string1, buf, sizeof(buf)); // Use strncmp because `jerry_string_to_utf8_char_buffer` doesn't NULL terminate CHECK(!strncmp("someString", (const char*)buf, strlen("someString"))); jerry_release_value(string1); jerry_release_value(obj_out); free(cbor); jerry_release_value(ret_value); jerry_cleanup(); return 0; } /*---------------------------------------------------------------------- | ArrayBufferTest +---------------------------------------------------------------------*/ static int ArrayBufferTest(void) { /* init JerryScript */ jerry_init(JERRY_INIT_EMPTY); jerry_value_t ret_value = jerry_create_undefined (); const char* source = "var a = new ArrayBuffer(3); var b = new Uint8Array(a); b[0] = 1; b[1] = 2; b[2] = 3; a"; ret_value = jerry_parse((const jerry_char_t*)source, strlen(source), false); CHECK(!jerry_value_is_error(ret_value)); jerry_value_t func_val = ret_value; ret_value = jerry_run(func_val); jerry_release_value(func_val); CHECK(!jerry_value_is_error(ret_value)); uint8_t cbor[4] = {0}; unsigned int cbor_size = 0; int result = Fb_Smo_Serialize_CBOR_FromJerry(ret_value, NULL, &cbor_size, 16, NULL, NULL); CHECK(result == FB_SMO_SUCCESS); CHECK(cbor_size == 4); result = Fb_Smo_Serialize_CBOR_FromJerry(ret_value, cbor, &cbor_size, 16, NULL, NULL); CHECK(result == FB_SMO_SUCCESS); CHECK(cbor_size == 0); CHECK(cbor[0] == 0x43); CHECK(cbor[1] == 0x01); CHECK(cbor[2] == 0x02); CHECK(cbor[3] == 0x03); jerry_release_value(ret_value); jerry_cleanup(); return 0; } /*---------------------------------------------------------------------- | TypedArrayTest +---------------------------------------------------------------------*/ static int TypedArrayTest(void) { /* init JerryScript */ jerry_init(JERRY_INIT_EMPTY); jerry_value_t ret_value = jerry_create_undefined (); const char* source = "var a = new ArrayBuffer(4); var b = new Uint8Array(a); b[0] = 99; b[1] = 1; b[2] = 2; b[3] = 3; new Uint8Array(a, 1, 3)"; ret_value = jerry_parse((const jerry_char_t*)source, strlen(source), false); CHECK(!jerry_value_is_error(ret_value)); jerry_value_t func_val = ret_value; ret_value = jerry_run(func_val); jerry_release_value(func_val); CHECK(!jerry_value_is_error(ret_value)); uint8_t cbor[4] = {0}; unsigned int cbor_size = 0; int result = Fb_Smo_Serialize_CBOR_FromJerry(ret_value, NULL, &cbor_size, 16, NULL, NULL); CHECK(result == FB_SMO_SUCCESS); CHECK(cbor_size == 4); result = Fb_Smo_Serialize_CBOR_FromJerry(ret_value, cbor, &cbor_size, 16, NULL, NULL); CHECK(result == FB_SMO_SUCCESS); CHECK(cbor_size == 0); CHECK(cbor[0] == 0x43); CHECK(cbor[1] == 0x01); CHECK(cbor[2] == 0x02); CHECK(cbor[3] == 0x03); jerry_release_value(ret_value); jerry_cleanup(); /* init JerryScript */ jerry_init(JERRY_INIT_EMPTY); ret_value = jerry_create_undefined (); const char* source2 = "var a = new Uint16Array(1); a[0] = 0x1234; a"; ret_value = jerry_parse((const jerry_char_t*)source2, strlen(source2), false); CHECK(!jerry_value_is_error(ret_value)); func_val = ret_value; ret_value = jerry_run(func_val); jerry_release_value(func_val); CHECK(!jerry_value_is_error(ret_value)); uint8_t cbor2[3] = {0}; cbor_size = 0; result = Fb_Smo_Serialize_CBOR_FromJerry(ret_value, NULL, &cbor_size, 16); CHECK(result == FB_SMO_SUCCESS); CHECK(cbor_size == 3); result = Fb_Smo_Serialize_CBOR_FromJerry(ret_value, cbor2, &cbor_size, 16); CHECK(result == FB_SMO_SUCCESS); CHECK(cbor_size == 0); CHECK(cbor2[0] == 0x42); if (cbor2[1] == 0x12) { // big endian CHECK(cbor2[1] == 0x12); CHECK(cbor2[2] == 0x34); } else { // little endian CHECK(cbor2[1] == 0x34); CHECK(cbor2[2] == 0x12); } jerry_release_value(ret_value); jerry_cleanup(); /* init JerryScript */ jerry_init(JERRY_INIT_EMPTY); ret_value = jerry_create_undefined (); const char* source3 = "var a = new Uint32Array(1); a[0] = 0x12345678; a"; ret_value = jerry_parse((const jerry_char_t*)source3, strlen(source3), false); CHECK(!jerry_value_is_error(ret_value)); func_val = ret_value; ret_value = jerry_run(func_val); jerry_release_value(func_val); CHECK(!jerry_value_is_error(ret_value)); uint8_t cbor3[5] = {0}; cbor_size = 0; result = Fb_Smo_Serialize_CBOR_FromJerry(ret_value, NULL, &cbor_size, 16, NULL, NULL); CHECK(result == FB_SMO_SUCCESS); CHECK(cbor_size == 5); result = Fb_Smo_Serialize_CBOR_FromJerry(ret_value, cbor3, &cbor_size, 16, NULL, NULL); CHECK(result == FB_SMO_SUCCESS); CHECK(cbor_size == 0); CHECK(cbor3[0] == 0x44); if (cbor3[1] == 0x12) { // big endian CHECK(cbor3[1] == 0x12); CHECK(cbor3[2] == 0x34); CHECK(cbor3[3] == 0x56); CHECK(cbor3[4] == 0x78); } else { // little endian CHECK(cbor3[1] == 0x78); CHECK(cbor3[2] == 0x56); CHECK(cbor3[3] == 0x34); CHECK(cbor3[4] == 0x12); } jerry_release_value(ret_value); jerry_cleanup(); return 0; } /*---------------------------------------------------------------------- | ParseDepthTest +---------------------------------------------------------------------*/ static int ParseDepthTest(void) { /* init JerryScript */ jerry_init(JERRY_INIT_EMPTY); jerry_value_t ret_value = jerry_create_undefined (); const char* source = "({a:{a:{a:{a:{a:{a:{a:{a:{}}}}}}}}});"; ret_value = jerry_parse((const jerry_char_t*)source, strlen(source), false); CHECK(!jerry_value_is_error(ret_value)); jerry_value_t func_val = ret_value; ret_value = jerry_run(func_val); jerry_release_value(func_val); CHECK(!jerry_value_is_error(ret_value)); unsigned int cbor_size = 0; int result = Fb_Smo_Serialize_CBOR_FromJerry(ret_value, NULL, &cbor_size, 0, NULL, NULL); CHECK(result == FB_SMO_ERROR_OVERFLOW); cbor_size = 0; result = Fb_Smo_Serialize_CBOR_FromJerry(ret_value, NULL, &cbor_size, 1, NULL, NULL); CHECK(result == FB_SMO_ERROR_OVERFLOW); cbor_size = 0; result = Fb_Smo_Serialize_CBOR_FromJerry(ret_value, NULL, &cbor_size, 9, NULL, NULL); CHECK(result == FB_SMO_SUCCESS); jerry_release_value(ret_value); jerry_cleanup(); return 0; } /*---------------------------------------------------------------------- | EncoderTest +---------------------------------------------------------------------*/ static bool CounterEncoder(void* context, jerry_value_t obj, uint8_t** serialized, unsigned int* available, int* result) { int* counter = (int*)context; (&counter)++; return false; } static int EncoderTest(void) { jerry_init(JERRY_INIT_EMPTY); jerry_value_t jerry_number = jerry_create_number(3); unsigned int cbor_size = 0; int counter = 0; int result = Fb_Smo_Serialize_CBOR_FromJerry(jerry_number, NULL, &cbor_size, 16, CounterEncoder, &counter) CHECK(counter == 1); jerry_release_value(jerry_number); jerry_cleanup(); return 0; } /*---------------------------------------------------------------------- | main +---------------------------------------------------------------------*/ int main(int argc, char** argv) { int result; /* fixed seed */ srand(0); /* basic tests */ result = SimpleParseTest(); if (result) return 1; result = ArrayBufferTest(); if (result) return 1; result = TypedArrayTest(); if (result) return 1; result = BasicTypesTest(); if (result) return 1; result = SimpleSerializeTest(); if (result) return 1; result = ParseDepthTest(); if (result) return 1; result = FailuresTest(); if (result) return 1; result = EncoderTest(); if (result) return 1; return 0; }
Go
UTF-8
1,214
3.375
3
[]
no_license
//给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 的那 两个 整数,并返回它们的数组下标。 // // 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。 // // 你可以按任意顺序返回答案。 // // // // 示例 1: // // //输入:nums = [2,7,11,15], target = 9 //输出:[0,1] //解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。 // // // 示例 2: // // //输入:nums = [3,2,4], target = 6 //输出:[1,2] // // // 示例 3: // // //输入:nums = [3,3], target = 6 //输出:[0,1] // // // // // 提示: // // // 2 <= nums.length <= 103 // -109 <= nums[i] <= 109 // -109 <= target <= 109 // 只会存在一个有效答案 // // Related Topics 数组 哈希表 // 👍 11084 👎 0 package cn //leetcode submit region begin(Prohibit modification and deletion) func twoSum(nums []int, target int) []int { for i, _ := range nums { for j := i + 1; j < len(nums); j++ { if nums[i]+nums[j] == target { return []int{i, j} } } } return nil } //leetcode submit region end(Prohibit modification and deletion)
C++
ISO-8859-1
10,074
2.796875
3
[]
no_license
#include "NoArvoreEsparsa.h" NoArvoreEsparsa::NoArvoreEsparsa() { this->esq = nullptr; this->dir = nullptr; this->info = nullptr; } NoArvoreEsparsa::~NoArvoreEsparsa() { if (this->info != nullptr) delete info; if (this->esq != nullptr) delete esq; if (this->dir != nullptr) delete dir; } NoArvoreEsparsa::NoArvoreEsparsa(const NoArvoreEsparsa& noBase) throw(char*) { this->esq = nullptr; this->dir = nullptr; this->info = nullptr; this->equilibrio = 0; this->equilibrio = noBase.getEquilibrio(); if (noBase.info != nullptr) { this->info = noBase.info; } if (noBase.getPtrNoFilho(0) != nullptr) {//esq no nulo this->esq = new NoArvoreEsparsa(*(noBase.getPtrNoFilho(0))); } if (noBase.getPtrNoFilho(1) != nullptr) {//dir no nulo this->dir = new NoArvoreEsparsa(*(noBase.getPtrNoFilho(1))); } //balancear(); } NoArvoreEsparsa* NoArvoreEsparsa::getPtrNoFilho(unsigned char indicePtr) const throw(char*) { switch (indicePtr) { case 0: return (this->esq); break; case 1: return (this->dir); break; default: throw("ndice maior que 1 em rvore binria !!"); break; } } void NoArvoreEsparsa::setPtrNoFilho(NoArvoreEsparsa* novoNo, unsigned char indFilho) throw(char*) { if (novoNo == nullptr) throw("Novo n nulo!"); switch (indFilho) { case 0: if (this->esq == nullptr) this->esq = new NoArvoreEsparsa(*novoNo); else *(this->esq) = *novoNo; //balancear(); break; case 1: if (this->dir == nullptr) this->dir = new NoArvoreEsparsa(*novoNo); else *(this->dir) = *novoNo; //balancear(); break; default: throw("ndice maior que 1 em rvore binria !!"); break; } } InfoArvoreEsparsa* NoArvoreEsparsa::getPtrInfo() const throw() { return this->info; } char NoArvoreEsparsa::inserirVetorOrdem(InfoArvoreEsparsa* info)throw() { if (info == nullptr) return -1; //supondo rvore est ordenada if ((this->info) != nullptr) { if (*info < *(this->info)) { if (this->esq == nullptr) { this->esq = new NoArvoreEsparsa(); this->esq->info = info; balancear(); return 1; } else this->esq->inserirVetorOrdem(info); } if (*info > *(this->info)) { if (this->dir == nullptr) { this->dir = new NoArvoreEsparsa(); this->dir->info = info; balancear(); return 1; } else this->dir->inserirVetorOrdem(info); } if (*(this->info) == *info) { return 0; } } else { this->info = /*new InfoArvoreEnaria(**/info/*)*/; balancear(); return 1; } } char NoArvoreEsparsa::removerVetorOrdem(InfoArvoreEsparsa* info, NoArvoreEsparsa* ant)throw() { if (info == nullptr) return -1; if (this->isFolha()) { if (*info == *(this->info)) { this->info = nullptr; /*NoArvoreEsparsa* no = this; no = nullptr;*/ if (ant != nullptr) { if (*info > *(ant->info)) { ant->dir = nullptr; } if (*info < *(ant->info)) { ant->esq = nullptr; } } else { //rvore est vazia this->info = nullptr; } //balancear(); return 1; } else { balancear(); return 0; } } //se o fluxo de execuo chegou aqui, ento no folha if (*info == *(this->info)) { //tem que achar info pra por no lugar *(this->info) = *(acharInfoPorLugar()); return 2; } if (*info < *(this->info)) { if (this->esq == nullptr) { balancear(); return -2; } else this->esq->removerVetorOrdem(info, this); } if (*info > *(this->info)) { if (this->dir == nullptr) { balancear(); return -3; } else this->dir->removerVetorOrdem(info, this); } } char NoArvoreEsparsa::isCheio() const throw() { return this->info != nullptr; } char NoArvoreEsparsa::isVazio() const throw() { return (this->info) == nullptr; } char NoArvoreEsparsa::isFolha() const throw() { return (this->esq == nullptr && this->dir == nullptr); } char NoArvoreEsparsa::haInfo(const InfoArvoreEsparsa& info) const throw() { NoArvoreEsparsa* noRel = (NoArvoreEsparsa*)(this); loop:while (1) { if (noRel == nullptr) return 0; if ((noRel->info) != nullptr) { if (*(noRel->info) == info) { return true; } if (*(noRel->info) > info) { //ir pro ponteiro de n i-1 noRel = (noRel->esq); goto loop; } if (*(noRel->info) < info) { noRel = (noRel->dir); goto loop; } } else { return 0; } } } /* InfoArvoreEsparsa * info; NoArvoreEsparsa* esq; NoArvoreEsparsa* dir;*/ InfoArvoreEsparsa* NoArvoreEsparsa::acharInfoPorLugar() throw(char*) { InfoArvoreEsparsa* infoTrocarFilho = nullptr; if (this->esq == nullptr) { infoTrocarFilho = menorDosMaiores(); } else { infoTrocarFilho = maiorDosMenores(); } return infoTrocarFilho; } InfoArvoreEsparsa* NoArvoreEsparsa::menorDosMaiores() throw(char*) { NoArvoreEsparsa* noAnt = (NoArvoreEsparsa*)this; NoArvoreEsparsa* noRel = (NoArvoreEsparsa*)this->dir; NoArvoreEsparsa* noAchado; char passou = 0; while (noRel->esq != nullptr) { passou = 1; noAnt = noRel; noRel = noRel->esq; } if (noRel->dir == nullptr) { noAchado = new NoArvoreEsparsa(*noRel); noRel->info = nullptr; if (passou) noAnt->esq = noRel = nullptr; else noAnt->dir = noRel = nullptr; return noAchado->info; } else { noAchado = new NoArvoreEsparsa(*noRel); noAnt->dir = noRel->dir; noRel->info = nullptr; noRel = nullptr; return noAchado->info; } } InfoArvoreEsparsa* NoArvoreEsparsa::maiorDosMenores() throw(char*) { NoArvoreEsparsa* noAnt = (NoArvoreEsparsa*)this; NoArvoreEsparsa* noRel = (NoArvoreEsparsa*)this->esq; NoArvoreEsparsa* noAchado; char passou = 0; while (noRel->dir != nullptr) { passou = 1; noAnt = noRel; noRel = noRel->dir; } if (noRel->esq == nullptr) { noAchado = new NoArvoreEsparsa(*noRel); noRel->info = nullptr; if (passou) noAnt->dir = noRel = nullptr; else noAnt->esq = noRel = nullptr; return noAchado->info; } else { noAchado = new NoArvoreEsparsa(*noRel); noAnt->esq = noRel->esq; noRel->info = nullptr; noRel = nullptr; return noAchado->info; } } ostream& operator<< (ostream& os, const NoArvoreEsparsa& no) throw() { int indicePtr = 0; int indiceInfo = 0; if (no.getPtrInfo() != nullptr) { InfoArvoreEsparsa* info = (no.getPtrInfo()); os << " " << (*(info)) << " "; } else { os << " ** "; } os << '['; if (no.getPtrNoFilho(0) != nullptr) { os << '(' << *(no.getPtrNoFilho(0)) << ')'; } else { os << ""; } os << " , "; if (no.getPtrNoFilho(1) != nullptr) { os << '(' << *(no.getPtrNoFilho(1)) << ')'; } else { os << ""; } os << ']'; return os; } char NoArvoreEsparsa::calcularEquilibrio() throw() { char niveisEsq(0), niveisDir(0); if (this->isFolha()) { this->equilibrio = 0; } if (this->esq == nullptr) { this->equilibrio = this->getNiveis(); } if (this->dir == nullptr) { this->equilibrio = -(this->getNiveis()); } if (this->esq != nullptr && this->dir != nullptr) { equilibrio = this->dir->getNiveis() - this->esq->getNiveis(); } return this->equilibrio; } char NoArvoreEsparsa::getNiveis()const throw() { if (this->isFolha()) return 0; if (this->esq == nullptr && this->dir != nullptr) return this->dir->getNiveis() + 1; if (this->dir == nullptr && this->esq != nullptr) return this->esq->getNiveis() + 1; char niveisEsq(0), niveisDir(0); if (this->esq != nullptr && this->esq != (NoArvoreEsparsa*)0xdddddddddddddddd) niveisEsq = this->esq->getNiveis(); if (this->dir != nullptr && this->dir != (NoArvoreEsparsa*)0xdddddddddddddddd) niveisDir = this->dir->getNiveis(); return niveisEsq > niveisDir ? niveisEsq + 1 : niveisDir + 1; } char NoArvoreEsparsa::getEquilibrio() const throw() { return this->equilibrio; } void NoArvoreEsparsa::balancear() throw() { this->calcularEquilibrio(); if (this->equilibrio <= 1 && this->equilibrio >= -1) { if (this->esq != nullptr) this->esq->balancear(); if (this->dir != nullptr) this->dir->balancear(); } if (this->equilibrio > 1) { if (this->dir->getEquilibrio() < 0) rotacaoDuplaEsquerda(); else rotacaoEsquerda(); if (this->esq != nullptr) this->esq->balancear(); if (this->dir != nullptr) this->dir->balancear(); } if (this->equilibrio < -1) { if (this->esq->getEquilibrio() > 0) rotacaoDuplaDireita(); else rotacaoDireita(); if (this->esq != nullptr) this->esq->balancear(); if (this->dir != nullptr) this->dir->balancear(); } if (this->esq != nullptr) this->esq->balancear(); if (this->dir != nullptr) this->dir->balancear(); this->calcularEquilibrio(); } void NoArvoreEsparsa::rotacaoEsquerda() throw() { NoArvoreEsparsa* novaRaiz = new NoArvoreEsparsa(*(this->dir)); novaRaiz->setPtrNoFilho(new NoArvoreEsparsa(*this), 0); novaRaiz->esq->dir = this->dir->esq; this->dir->esq = nullptr; this->dir = novaRaiz->dir; this->esq = novaRaiz->esq; this->info = novaRaiz->info; //delete novaRaiz; this->calcularEquilibrio(); } void NoArvoreEsparsa::rotacaoDireita() throw() { NoArvoreEsparsa* novaRaiz = new NoArvoreEsparsa(*(this->esq)); novaRaiz->setPtrNoFilho(new NoArvoreEsparsa(*this), 1); novaRaiz->dir->esq = this->esq->dir; this->esq->dir = nullptr; this->dir = novaRaiz->dir; this->esq = novaRaiz->esq; this->info = novaRaiz->info; //delete novaRaiz; this->calcularEquilibrio(); } void NoArvoreEsparsa::setInfo(const InfoArvoreEsparsa& novaInfo) throw() { *this->info = novaInfo; } InfoArvoreEsparsa* NoArvoreEsparsa::getInfo() throw() { return this->info; } void NoArvoreEsparsa::rotacaoDuplaEsquerda() throw() { this->dir->rotacaoDireita(); this->rotacaoEsquerda(); } void NoArvoreEsparsa::rotacaoDuplaDireita() throw() { this->esq->rotacaoEsquerda(); this->rotacaoDireita(); }
Java
UTF-8
602
2.53125
3
[]
no_license
package java.nio.file.spi; import java.io.IOException; import java.nio.file.Path; public abstract class FileTypeDetector { private static Void checkPermission() { SecurityManager localSecurityManager = System.getSecurityManager(); if (localSecurityManager != null) { localSecurityManager.checkPermission(new RuntimePermission("fileTypeDetector")); } return null; } private FileTypeDetector(Void paramVoid) {} protected FileTypeDetector() { this(checkPermission()); } public abstract String probeContentType(Path paramPath) throws IOException; }
PHP
UTF-8
3,241
2.65625
3
[]
no_license
<?php namespace Controllers; use \Library\View, \Library\Composer, \Library\Sanitize; use Models\EmailModel; class ReviewController { const AD_INCOMPLETE = 0; const AD_PENDING = 1; const AD_APPROVED = 2; const AD_REJECTED = 3; const AD_AUTO_APPROVED = 4; /** * Print the needed form to interact with the broadcaster * @param string $formName The name of the form * @param integer [$broadcasterID = 0] The broadcaster ID */ public function form($formName, $adID, $action = 0) { \Library\User::restricted("APPROVE_CREATIVES"); switch($formName) { case "review": //Get the view $form = new \Library\View("reviews/review"); //Retrieve needed infos $adID = \Library\Sanitize::int($adID); $action = \Library\Sanitize::string($action); //Attach the infos $form->adID = $adID; $form->action = $action; break; } echo $form->render(); } /** * Insert a new review, if possible, for the given ad * @param integer $adID The ad to ork with */ public function createReview($adID) { //First let's see if the ad is complete $ad = \Objects\Ad::getInstance($adID); $nbrScreens = $ad->getNbrScreens(); $nbrCreatives = $ad->getNbrCreatives(); if($nbrCreatives != $nbrScreens) return; //Ads are missing, no review for now //The Ad is complete //Define the review status $reviewStatus = ReviewController::AD_PENDING; $reviewerID = NULL; $reviewedDate = 0; if(\Library\User::isAdmin()) { $reviewStatus = ReviewController::AD_APPROVED; $reviewerID = \Library\User::id(); $reviewedDate = time(); } else if(\Library\User::restricted("TRUSTED_CLIENT", true)) { $reviewStatus = ReviewController::AD_AUTO_APPROVED; $reviewerID = \Library\User::id(); $reviewedDate = time(); } $reviewModel = new \Models\ReviewModel(); $reviewModel->create($adID, $reviewStatus, $reviewerID, $reviewedDate); if($reviewerID == NULL) { $emailController = new EmailController(); $emailController->create(EmailController::EMAIL_REVIEW_AD, $adID); } } public function validate() { \Library\User::restricted("APPROVE_CREATIVES"); //Exclude any possible errors if(empty($_POST['adID']) ||empty($_POST['action'])) { http_response_code(400); echo "fatalError"; return; } $adID = Sanitize::int($_POST['adID']); $action = Sanitize::string($_POST['action']); $comment = Sanitize::string($_POST['comment']); if($action == "approve") $newStatus = self::AD_APPROVED; else if($action == "reject") $newStatus = self::AD_REJECTED; else { http_response_code(400); echo "fatalError"; return; } $reviewModel = new \Models\ReviewModel(); $reviewModel->validate($adID, $newStatus, $comment); $ad = \Objects\Ad::getInstance($adID); if($ad == false) { $homeController = new HomeController(); $homeController->clients(); } $campaignID = $ad->getCampaignID(); $emailController = new EmailController(); $emailController->create(EmailController::EMAIL_REVIEWED_AD, $adID); $campaignController = new CampaignController(); $campaignController->display($campaignID); } }
JavaScript
UTF-8
1,842
2.65625
3
[]
no_license
const pool = require("../database") async function getPharmacies() { const results = await pool.query(`SELECT * from pharmacies`) try { return results.map(result => { const { longitude, latitude, ...res } = result res.coords = { longitude, latitude } return res }) } catch (error) { throw new Error(error) } } async function getPharmaciesByDrug(idDrug) { var query = `SELECT id_pharma, pharmacies.label AS label_pharma, id_drug, drugs.label AS label_drugs, quantity, address, cp, longitude, latitude ` query += `FROM pharmacies_drugs ` query += `INNER JOIN pharmacies ON pharmacies_drugs.id_pharma = pharmacies.id ` query += `INNER JOIN drugs ON pharmacies_drugs.id_drug = drugs.id where pharmacies_drugs.id_drug=${idDrug}` const results = await pool.query(query) try { return results.map(result => { const { longitude, latitude, ...res } = result res.coords = { longitude, latitude } return res }) } catch (error) { throw new Error(error) } } async function getPharmaciesCountryStat(){ var query = `SELECT pays, COUNT(pays) as countPays FROM pharmacies GROUP BY pays ORDER BY countPays DESC limit 20;` const results = await pool.query(query) try { return results } catch (error) { throw new Error(error) } } async function getPharmaciesCityStat(){ var query = `SELECT city, COUNT(city) as countCity FROM pharmacies GROUP BY city ORDER BY countCity DESC limit 20;` const results = await pool.query(query) try { return results } catch (error) { throw new Error(error) } } module.exports = { getPharmacies, getPharmaciesByDrug, getPharmaciesCountryStat, getPharmaciesCityStat, };
TypeScript
UTF-8
2,552
2.875
3
[ "bzip2-1.0.6", "BSD-3-Clause", "LicenseRef-scancode-openssl", "APSL-1.0", "LicenseRef-scancode-unknown-license-reference", "APSL-1.2", "MPL-1.1", "JSON", "LicenseRef-scancode-free-unknown", "LGPL-2.0-or-later", "ICU", "BSD-4-Clause-UC", "LicenseRef-scancode-warranty-disclaimer", "NTP", "GPL-2.0-or-later", "Apache-1.1", "MITNFA", "LicenseRef-scancode-google-patent-license-webrtc", "dtoa", "Zlib", "GPL-1.0-or-later", "MIT", "CPL-1.0", "MPL-2.0", "LicenseRef-scancode-mit-veillard-variant", "ISC", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
import { app, BrowserWindow } from "electron"; interface Logger { log: (...msgs: Array<string>) => void; info: (...msgs: Array<string>) => void; warn: (...msgs: Array<string>) => void; error: (...msgs: Array<string>) => void; } export function isDev(): boolean { return /(\/|\\)electron(.exe)?$/i.test(app.getPath("exe")); } let mainWindow: BrowserWindow | null; export function setLoggerWindow(win: BrowserWindow): void { win.webContents.once("did-frame-finish-load", (event: any) => { mainWindow = win; }); } export function unsetLoggerWindow(win: BrowserWindow): void { if (mainWindow === win) { mainWindow = null; } } const _console: any = {}; function callMainWindowConsole(method: string, ...args: Array<string>): void { if (mainWindow) { try { mainWindow.webContents.send("console-msg", method, ...args); } catch (e) { // Do nothing. } return; } _console[method].call(console, ...args); } // this is run only for shell, we hijack console.xxx methods so they can be passed onto main window if (app) { const c: any = console; Object.keys(c).forEach((key: string) => { if (typeof c[key] !== "function") { return; } _console[key] = c[key]; c[key] = (...args: Array<any>): void => callMainWindowConsole(key, ...args); }); } export function getLogger(name: string): Logger { return { log: (...msgs: Array<string>) => console.log(`[${name}]`, ...msgs), // tslint:disable-line info: (...msgs: Array<string>) => console.info(`[${name}]`, ...msgs), // tslint:disable-line warn: (...msgs: Array<string>) => console.warn(`[${name}]`, ...msgs), error: (...msgs: Array<string>) => console.error(`[${name}]`, ...msgs) }; } export function errToString(err: Error): string { if (err.stack) { return err.stack; } if (err.name && err.message) { return err.name + ": " + err.message; } return err.toString(); } export function errToMessage(err: Error): string { let message = err.message; if (message && err.name) { message = err.name + ": " + message; } return message ? message : err.toString(); } export function convertWindowsPathToUnixPath(path: string): string { return process.platform === "win32" ? path.replace(/\\/g, "/") : path; } export function convertBracketsPathToWindowsPath(path: string): string { return process.platform === "win32" ? path.replace(/\//g, "\\") : path; }
SQL
UTF-8
748
3.4375
3
[]
no_license
create database Messenger_Data use Messenger_Data create table Account ( Id int primary key identity(1,1), Login varchar(max) not null, Password nvarchar(max) not null, Name nvarchar(max) not null, Email varchar(max) not null, Image image not null ) select * from Account create table Message ( Id int primary key identity(1,1), DeliverId int foreign key references Account(Id), Content nvarchar(max) not null, Data datetime not null ) create table Contacts ( Id int primary key identity(1,1), OwnerId int foreign key references Account(Id), ContactId int foreign key references Account(Id) ) create table Chat ( Id int primary key identity(1,1), Participants nvarchar(max), MessageId int foreign key references Message(Id), )
Python
UTF-8
8,938
3.171875
3
[]
no_license
import numpy as np import chainer import chainer.functions as F import chainer.links as L import chainerrl import math """ NOTE: this is navigation agent for chaser -> target. ACTION: up,down,left,right = 0,1,2,3 STATE: [cy,cx,ry,rx,direc] = chaser y, chaser x, runner y, runner x, direction looking from chaser to runner RESULT: Agent reliably taking optimal route to target/runner pos after around 1~3k episodes of training. (haven't tested when, but it does work :)) + = open space X = wall S = start G = Goal """ #walls = [[0,3],[1,1],[2,1],[3,3],[2,3],[2,2]] walls = [] class Nav(chainer.Chain): #class for the DQN def __init__(self,obs_size,n_actions,n_hidden_channels): super(Nav,self).__init__() with self.init_scope(): #defining the layers self.l1=L.Linear(obs_size,n_hidden_channels) self.l2=L.Linear(n_hidden_channels,n_hidden_channels) self.l3=L.Linear(n_hidden_channels,n_hidden_channels) self.l4=L.Linear(n_hidden_channels,n_actions) def __call__(self,x,test=False): #activation function = sigmoid h1=F.sigmoid(self.l1(x)) h2=F.sigmoid(self.l2(h1)) h3=F.sigmoid(self.l3(h2)) y=chainerrl.action_value.DiscreteActionValue(self.l4(h3)) #agent chooses distinct action from finite action set return y def get_dist(s): #returns euclidiean distance between (s[0],s[1]) and (s[2],s[3]) return math.sqrt((s[0]-s[2])**2+(s[1]-s[3])**2) def get_direc(s): #get state representation of direction from (s[0],s[1]) to (s[2],s[3]) [ay,ax]=s[:2] #[y,x] form [by,bx]=s[2:4] #coords r in pygame style, top left = [0,0] going down adds positively on the y value i.e. [+1,0] #representing cardinal directions in clockwise order, starting with N s=0 if ax==bx: if ay>by:s=1 #N else:s=5 #S elif ay==by: if ax<bx:s=3 #E else:s=7 #W elif ax>bx: if ay>by:s=8 #NW else:s=6 #SW elif ax<bx: if ay>by:s=2 #NE else:s=4 #SE return s def find_index(arr,t): #arr.index(t), but with numpy arrays. Returns False if t not in arr for i,n in enumerate(arr): if np.array_equal(t,n): return i return False def disp_wall(s): #ASCII representation of the current grid. See top of code for terminology of letters grid=[["+" for a in range(5)] for _ in range(5)] for y,x in walls: grid[y][x]="X" grid[s[0]][s[0]]="S" grid[s[1]][s[0]]="G" for n in grid: print("".join(n)) def random_action(): #returns random action, used by "explorer" return np.random.choice([0,1,2,3]) #this is where optimizers, explorers, replay buffers, network structure, and agent type is defined def setup(gamma,obs_size,n_actions,n_hidden_channels,start_epsilon=1,end_epsilon=0.1,num_episodes=1): #the skeletal structure of my agent. func=Nav(obs_size,n_actions,n_hidden_channels) #model's structure defined here optimizer=chainer.optimizers.Adam(eps=1e-8) #optimizer chosen optimizer.setup(func) #explorer setup explorer=chainerrl.explorers.LinearDecayEpsilonGreedy(start_epsilon=start_epsilon,end_epsilon=end_epsilon,decay_steps=num_episodes,random_action_func=random_action) replay_buffer=chainerrl.replay_buffer.PrioritizedReplayBuffer(capacity=10**6) #experience replay buffer setup phi=lambda x: x.astype(np.float32,copy=False) #must be float32 for chainer #defining network type and setting up agent. Required parameter differs for most networks (e.g. DDPG, AC3, DQN) agent=chainerrl.agents.DQN(func,optimizer,replay_buffer,gamma,explorer,replay_start_size=300,update_interval=1,target_update_interval=50,phi=phi) return agent #given current state s, and action a from network, returns next state and reward for that action a def step(s,a): r=0 #record chaser position py,px=s[0],s[1] if a==0 and s[0]!=0:#up s[0]-=1 elif a==1 and s[0]!=4:#down s[0]+=1 elif a==2 and s[1]!=0:#left s[1]-=1 elif a==3 and s[1]!=4:#right s[1]+=1 else: #if no movement observed, penalize r=-100 #if collided into wall, penalize if [s[0],s[1]] in walls: s[0],s[1]=py,px; r=-100 return s,r #return new state, and reward def r_both_pos(state): #generate random pos for both entities, which is not overlapping with themselves nor the walls state[0]=np.random.choice([0,1,2,3,4]) state[1]=np.random.choice([0,1,2,3,4]) state[2]=np.random.choice([0,1,2,3,4]) state[3]=np.random.choice([0,1,2,3,4]) while [state[0],state[1]]==[state[2],state[3]] or [n for n in state[:2]] in walls or [n for n in state[2:4]] in walls: state[0]=np.random.choice([0,1,2,3,4]) state[1]=np.random.choice([0,1,2,3,4]) state[2]=np.random.choice([0,1,2,3,4]) state[3]=np.random.choice([0,1,2,3,4]) return state def train(num_episodes,name,save=True,load=True,interv_save=True,disp_interval=1,save_interval=100): #actual train algo #agent setup below agent=setup(0.3,5,4,50,1,0.1,num_episodes) #gamma,state_dim,action_num,hidden_num,start_epsilon=1,end_epsilon=0.01,num_episodes=1 #loading prexisting agent if load: agent.load("nav_agent"+name) longest_dist=get_dist(np.array([0,4,4,0])) #longest possible dist max_step=30 #time/step limit timeout_states=[] #for recording starting states which resulted in a failed catch (timeout) mem=10 #number of past steps to store for episode in range(num_episodes): #episode loop state=np.array([4,0,0,4,0]) #cx,cy,rx,ry,direc #Choose a state which resulted in failed catch, or random pos if len(timeout_states)>0: if np.random.uniform(0,1)>0.5: state=r_both_pos(state) else: state=np.copy(timeout_states.pop(0)) else: state=r_both_pos(state) state[4]=get_direc(state[:4]) #set initial direction prev_states=[] #used with "mem", for recording previous steps start_state=[n for n in state] #record starting state #set vars r=0 #cur reward total_r=0 #total reward of that episode step_taken=0 #step/time counter #distance vars dist=get_dist(state) #current distance og_dist=get_dist(state) #distance at initial state #caught or not caught=True while [state[0],state[1]]!=[state[2],state[3]] and caught: #step loop action=agent.act_and_train(state,r) #get action from agent, and update network (train) #recording "mem" number of past states from [newest,...,oldest] if len(prev_states)<=mem: prev_states.insert(0,state[:4]) else: prev_states.pop() prev_states.insert(0,state[:4]) state,r=step(state,action) #update state from given action #distance rewarding/penalizing and update d=get_dist(state) if d<dist: r+=longest_dist #if current distance is less than previous, reward elif d>dist: r-=longest_dist #otherwise penalize dist=d #penalizing for repeated pos in previous "mem" steps i=find_index(prev_states,state[:4]) if i: r-=longest_dist*((mem-i+1)*(5/mem)) #The more recent the repeated position, the more you are penalized for total_r+=r #update current episode's total reward step_taken+=1 #increment step counter #update direc state[4]=get_direc(state[:4]) #time limit, detect failed catch if step_taken>max_step: r-=100 #penalize print("***********************************************") timeout_states.append(np.copy(start_state)) #record starting state of this episode as a "failed catch" caught=False if caught: r+=10**5 #larger reward for successful catch total_r+=r agent.stop_episode_and_train(state,r,caught) #final train of episode #displaying data if episode%disp_interval==0: print(f"episode: {episode}, chaser reward: {total_r}") print(f"steps taken: {step_taken}, start state: {start_state}, length of timeouts: {len(timeout_states)}") print() #saving agent models in intervals if episode%save_interval==0 and interv_save: agent.save("nav_agent"+name) #saving agent models after all episode ran if save: agent.save("nav_agent"+name) #display basic values of network print(agent.get_statistics()) train(5000,"Test",False,False,False)
C++
UTF-8
842
2.9375
3
[]
no_license
// // main.cpp // Distinct Subsequences // // Created by Renchu Song on 10/7/14. // Copyright (c) 2014 Renchu Song. All rights reserved. // #include <iostream> using namespace std; class Solution { public: int numDistinct(string S, string T) { int n = (int)S.length(), m = (int)T.length(); if (n < m || m == 0) return 0; int dp[n + 1][m + 1]; for (int i = 0; i <= n; ++i) for (int j = 0; j <= m; ++j) dp[i][j] = 0; for (int i = 0; i <= n; ++i) dp[i][0] = 1; for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) { dp[i][j] = dp[i - 1][j]; if (S[i - 1] == T[j - 1]) dp[i][j] += dp[i - 1][j - 1]; } return dp[n][m]; } }; int main(int argc, const char * argv[]) { cout << (new Solution())->numDistinct("ccc", "c") << endl; // insert code here... std::cout << "Hello, World!\n"; return 0; }
Java
UTF-8
2,286
2.125
2
[]
no_license
package id.ac.ui.cs.mobileprogramming.muhammadauliaadil.jasapedia.fragments; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProviders; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.List; import id.ac.ui.cs.mobileprogramming.muhammadauliaadil.jasapedia.R; import id.ac.ui.cs.mobileprogramming.muhammadauliaadil.jasapedia.adapters.BookingAdapter; import id.ac.ui.cs.mobileprogramming.muhammadauliaadil.jasapedia.models.Booking; import id.ac.ui.cs.mobileprogramming.muhammadauliaadil.jasapedia.viewmodels.BookingViewModel; public class BookingsFragment extends Fragment { private BookingViewModel bookingViewModel; private RecyclerView recyclerView; private BookingAdapter adapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_bookings, container, false); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); recyclerView = getView().findViewById(R.id.recycler_view); recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); recyclerView.setHasFixedSize(true); adapter = new BookingAdapter(getContext()); recyclerView.setAdapter(adapter); bookingViewModel = ViewModelProviders.of(this).get(BookingViewModel.class); bookingViewModel.getAllBookings().observe(this, new Observer<List<Booking>>() { @Override public void onChanged(List<Booking> bookings) { adapter.setBookings(bookings); adapter.notifyDataSetChanged(); } }); } }
Shell
UTF-8
198
2.921875
3
[]
no_license
#!/bin/bash set -e . "$(dirname -- "$0")"/functions.sh # Mac only is_mac || exit 1 # install for app in tmux reattach-to-user-namespace; do type -p "$app" >/dev/null || brew install "$app" done
JavaScript
UTF-8
2,914
2.765625
3
[]
no_license
import asyncHandler from 'express-async-handler'; import Property from '../models/propertyModel.js'; import Reservation from '../models/reservationModel.js'; import { isEqual } from 'lodash-es'; // @desc Fetch all propertyies // @route GET /api/properties?offset=&limit=&search_term=&sortby=&sortdirection= // @access Public export const getProperties = asyncHandler(async (req, res) => { let offset = parseInt(req.query.offset) - 1 || 0; let limit = parseInt(req.query.limit) || 5; let search = req.query.search_term || ''; let sortby = req.query.sortby || ''; let sortdirection = req.query.sortdirection === 'ASC' ? 1 : -1; let properties = []; properties = await Property.find({ name: { $regex: new RegExp('^' + search.toLowerCase(), 'i') } }, {}) .skip(offset * limit) .limit(limit) .sort(req.query.sortdirection ? { [sortby]: sortdirection } : { $natural: -1 }); const propertyCount = await Property.find( { name: { $regex: new RegExp('^' + search.toLowerCase(), 'i') } }, {} ).countDocuments(); res.json({ results: properties, totalCount: propertyCount }); }); // @desc Fetch single property // @route GET /api/properties/:id // @access Public export const getPropertyById = asyncHandler(async (req, res) => { const property = await Property.findById(req.params.id); if (property) { res.send(property); } else { res.status(404); throw new Error('Property not found'); } }); // @desc Fetch available rooms by property id and selected date // @route GET /api/properties/:id/availability?from_date=&to_date // @access Public export const getPropertyAvailability = asyncHandler(async (req, res) => { let fromDate = new Date(req.query.from_date) || new Date(); let toDate = new Date(req.query.to_date) || new Date(); const property = await Property.findById(req.params.id); let reservations = []; if (isEqual(fromDate, toDate)) { reservations = await Reservation.find( { $or: [ { from_date: { $eq: fromDate } }, { to_date: { $eq: toDate } }, { $and: [{ from_date: { $lt: fromDate } }, { to_date: { $gt: fromDate } }] } ], property: req.params.id }, {} ); } else { reservations = await Reservation.find( { $or: [{ from_date: { $gte: fromDate, $lte: toDate } }, { to_date: { $gte: fromDate, $lte: toDate } }], property: req.params.id }, {} ); } const bookedRooms = reservations.reduce(function (sum, reservation) { return sum + reservation.number_of_rooms; }, 0); // const toDate = new Date(); // const fromDate = new Date(new Date().setDate(new Date().getDate() - 30)); if (reservations && reservations.length !== 0) { res.json({ availableRooms: property.number_of_rooms - bookedRooms }); } else { res.json({ availableRooms: property.number_of_rooms }); } });
PHP
UTF-8
1,603
2.546875
3
[ "MIT" ]
permissive
<?php namespace App\Services; use App\Repositories\Abstracts\Repository; use App\Repositories\OptionRepository; use Illuminate\Contracts\Pagination\LengthAwarePaginator; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Collection; class OptionService { /** * @var OptionRepository */ private $optionRepository; public function __construct(OptionRepository $optionRepository) { $this->optionRepository = $optionRepository; } public function update(int $optionId, string $name): int { return $this->optionRepository->update([ 'option_name' => $name ], $optionId); } public function paginate(): LengthAwarePaginator { return $this->optionRepository->makeQuery()->with('values')->orderByDesc('created_at')->paginate(Repository::DEFAULT_PER_PAGE); } public function createNewOption(string $name): Model { return $this->optionRepository->create([ 'option_name' => $name ]); } public function findOptionById(int $id): ?Model { return $this->optionRepository->find($id); } public function delete(int $id) { return $this->optionRepository->delete($id); } public function pluck(): Collection { $options = $this->optionRepository->makeQuery()->pluck('option_name', 'id'); return $options; } public function with(): Collection { $options = $this->optionRepository->with(['values'])->get(); return $options; } }
Java
UTF-8
10,295
1.898438
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2022 by Hitachi Vantara : http://www.pentaho.com * ******************************************************************************* * * 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 org.pentaho.di.trans.steps.fileinput.text; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; import org.pentaho.di.core.logging.LogChannelInterface; import org.pentaho.di.core.variables.VariableSpace; import org.pentaho.di.trans.steps.file.BaseFileField; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; public class TextFileInputUtilsTest { @Test public void guessStringsFromLine() throws Exception { TextFileInputMeta inputMeta = Mockito.mock( TextFileInputMeta.class ); inputMeta.content = new TextFileInputMeta.Content(); inputMeta.content.fileType = "CSV"; String line = "\"\\\\valueA\"|\"valueB\\\\\"|\"val\\\\ueC\""; // "\\valueA"|"valueB\\"|"val\\ueC" String[] strings = TextFileInputUtils .guessStringsFromLine( Mockito.mock( VariableSpace.class ), Mockito.mock( LogChannelInterface.class ), line, inputMeta, "|", "\"", "\\" ); Assert.assertNotNull( strings ); Assert.assertEquals( "\\valueA", strings[ 0 ] ); Assert.assertEquals( "valueB\\", strings[ 1 ] ); Assert.assertEquals( "val\\ueC", strings[ 2 ] ); } @Test public void convertLineToStrings() throws Exception { TextFileInputMeta inputMeta = Mockito.mock( TextFileInputMeta.class ); inputMeta.content = new TextFileInputMeta.Content(); inputMeta.content.fileType = "CSV"; inputMeta.inputFields = new BaseFileField[ 3 ]; inputMeta.content.escapeCharacter = "\\"; String line = "\"\\\\fie\\\\l\\dA\"|\"fieldB\\\\\"|\"fie\\\\ldC\""; // ""\\fie\\l\dA"|"fieldB\\"|"Fie\\ldC"" String[] strings = TextFileInputUtils .convertLineToStrings( Mockito.mock( LogChannelInterface.class ), line, inputMeta, "|", "\"", "\\" ); Assert.assertNotNull( strings ); Assert.assertEquals( "\\fie\\l\\dA", strings[ 0 ] ); Assert.assertEquals( "fieldB\\", strings[ 1 ] ); Assert.assertEquals( "fie\\ldC", strings[ 2 ] ); } @Test public void convertCSVLinesToStrings() throws Exception { TextFileInputMeta inputMeta = Mockito.mock( TextFileInputMeta.class ); inputMeta.content = new TextFileInputMeta.Content(); inputMeta.content.fileType = "CSV"; inputMeta.inputFields = new BaseFileField[ 2 ]; inputMeta.content.escapeCharacter = "\\"; String line = "A\\\\,B"; // A\\,B String[] strings = TextFileInputUtils .convertLineToStrings( Mockito.mock( LogChannelInterface.class ), line, inputMeta, ",", "", "\\" ); Assert.assertNotNull( strings ); Assert.assertEquals( "A\\", strings[ 0 ] ); Assert.assertEquals( "B", strings[ 1 ] ); line = "\\,AB"; // \,AB strings = TextFileInputUtils .convertLineToStrings( Mockito.mock( LogChannelInterface.class ), line, inputMeta, ",", "", "\\" ); Assert.assertNotNull( strings ); Assert.assertEquals( ",AB", strings[ 0 ] ); Assert.assertEquals( null, strings[ 1 ] ); line = "\\\\\\,AB"; // \\\,AB strings = TextFileInputUtils .convertLineToStrings( Mockito.mock( LogChannelInterface.class ), line, inputMeta, ",", "", "\\" ); Assert.assertNotNull( strings ); Assert.assertEquals( "\\,AB", strings[ 0 ] ); Assert.assertEquals( null, strings[ 1 ] ); line = "AB,\\"; // AB,\ strings = TextFileInputUtils .convertLineToStrings( Mockito.mock( LogChannelInterface.class ), line, inputMeta, ",", "", "\\" ); Assert.assertNotNull( strings ); Assert.assertEquals( "AB", strings[ 0 ] ); Assert.assertEquals( "\\", strings[ 1 ] ); line = "AB,\\\\\\"; // AB,\\\ strings = TextFileInputUtils .convertLineToStrings( Mockito.mock( LogChannelInterface.class ), line, inputMeta, ",", "", "\\" ); Assert.assertNotNull( strings ); Assert.assertEquals( "AB", strings[ 0 ] ); Assert.assertEquals( "\\\\", strings[ 1 ] ); line = "A\\B,C"; // A\B,C strings = TextFileInputUtils .convertLineToStrings( Mockito.mock( LogChannelInterface.class ), line, inputMeta, ",", "", "\\" ); Assert.assertNotNull( strings ); Assert.assertEquals( "A\\B", strings[ 0 ] ); Assert.assertEquals( "C", strings[ 1 ] ); } @Test public void convertCSVLinesToStringsWithEnclosure() throws Exception { TextFileInputMeta inputMeta = Mockito.mock( TextFileInputMeta.class ); inputMeta.content = new TextFileInputMeta.Content(); inputMeta.content.fileType = "CSV"; inputMeta.inputFields = new BaseFileField[ 2 ]; inputMeta.content.escapeCharacter = "\\"; inputMeta.content.enclosure = "\""; String line = "\"A\\\\\",\"B\""; // "A\\","B" String[] strings = TextFileInputUtils .convertLineToStrings( Mockito.mock( LogChannelInterface.class ), line, inputMeta, ",", "\"", "\\" ); Assert.assertNotNull( strings ); Assert.assertEquals( "A\\", strings[ 0 ] ); Assert.assertEquals( "B", strings[ 1 ] ); line = "\"\\\\\",\"AB\""; // "\\","AB" strings = TextFileInputUtils .convertLineToStrings( Mockito.mock( LogChannelInterface.class ), line, inputMeta, ",", "\"", "\\" ); Assert.assertNotNull( strings ); Assert.assertEquals( "\\", strings[ 0 ] ); Assert.assertEquals( "AB", strings[ 1 ] ); line = "\"A\\B\",\"C\""; // "A\B","C" strings = TextFileInputUtils .convertLineToStrings( Mockito.mock( LogChannelInterface.class ), line, inputMeta, ",", "\"", "\\" ); Assert.assertNotNull( strings ); Assert.assertEquals( "A\\B", strings[ 0 ] ); Assert.assertEquals( "C", strings[ 1 ] ); } @Test public void getLineWithEnclosureTest() throws Exception { String text = "\"firstLine\"\n\"secondLine\""; StringBuilder linebuilder = new StringBuilder( "" ); InputStream is = new ByteArrayInputStream( text.getBytes() ); BufferedInputStreamReader isr = new BufferedInputStreamReader( new InputStreamReader( is ) ); TextFileLine line = TextFileInputUtils.getLine( Mockito.mock( LogChannelInterface.class ), isr, EncodingType.SINGLE, 1, linebuilder, "\"", "", 0 ); Assert.assertEquals( "\"firstLine\"", line.getLine() ); } @Test public void getLineBrokenByEnclosureTest() throws Exception { String text = "\"firstLine\n\"\"secondLine\""; StringBuilder linebuilder = new StringBuilder( "" ); InputStream is = new ByteArrayInputStream( text.getBytes() ); BufferedInputStreamReader isr = new BufferedInputStreamReader( new InputStreamReader( is ) ); TextFileLine line = TextFileInputUtils.getLine( Mockito.mock( LogChannelInterface.class ), isr, EncodingType.SINGLE, 1, linebuilder, "\"", "", 0 ); Assert.assertEquals( text, line.getLine() ); } @Test public void getLineBrokenByEnclosureLenientTest() throws Exception { System.setProperty( "KETTLE_COMPATIBILITY_TEXT_FILE_INPUT_USE_LENIENT_ENCLOSURE_HANDLING", "Y" ); String text = "\"firstLine\n\"\"secondLine\""; StringBuilder linebuilder = new StringBuilder( "" ); InputStream is = new ByteArrayInputStream( text.getBytes() ); BufferedInputStreamReader isr = new BufferedInputStreamReader( new InputStreamReader( is ) ); TextFileLine line = TextFileInputUtils.getLine( Mockito.mock( LogChannelInterface.class ), isr, EncodingType.SINGLE, 1, linebuilder, "\"", "", 0 ); Assert.assertEquals( "\"firstLine", line.getLine() ); System.clearProperty( "KETTLE_COMPATIBILITY_TEXT_FILE_INPUT_USE_LENIENT_ENCLOSURE_HANDLING" ); } @Test public void testCheckPattern() { // Check more information in: // https://docs.oracle.com/javase/tutorial/essential/regex/literals.html String metacharacters = "<([{\\^-=$!|]})?*+.>"; for( int i = 0; i < metacharacters.length(); i++ ) { int matches = TextFileInputUtils.checkPattern( metacharacters, String.valueOf( metacharacters.charAt( i ) ), null ); Assert.assertEquals( 1, matches ); } } @Test public void testCheckPatternWithEscapeCharacter() { List<String> texts = new ArrayList<>(); texts.add( "\"valueA\"|\"valueB\\\\\"|\"valueC\"" ); texts.add( "\"valueA\"|\"va\\\"lueB\"|\"valueC\"" ); for ( String text : texts ) { int matches = TextFileInputUtils.checkPattern( text, "\"", "\\" ); Assert.assertEquals( 6, matches ); } } @Test public void convertCSVLinesToStringsWithSameEnclosureAndEscape() throws Exception { TextFileInputMeta inputMeta = Mockito.mock(TextFileInputMeta.class); inputMeta.content = new TextFileInputMeta.Content(); inputMeta.content.fileType = "CSV"; inputMeta.inputFields = new BaseFileField[2]; inputMeta.content.escapeCharacter = "\""; inputMeta.content.enclosure = "\""; //the escape character is same as enclosure String line = "\"\"\"\"\"\""; // """""" String[] strings = TextFileInputUtils .convertLineToStrings(Mockito.mock(LogChannelInterface.class), line, inputMeta, ",", "\"", "\""); Assert.assertNotNull(strings); Assert.assertEquals("\"\"", strings[0]);//"""" line = "\"{\"\"Example1\"\":\"\"\"\",\"\"Example\"\":\"\"Test\"\"}\""; // """""" strings = TextFileInputUtils .convertLineToStrings(Mockito.mock(LogChannelInterface.class), line, inputMeta, ",", "\"", "\""); Assert.assertNotNull(strings); Assert.assertEquals("{\"Example1\":\"\",\"Example\":\"Test\"}", strings[0]);//"""" } }
Python
UTF-8
2,408
3.3125
3
[]
no_license
""" idea: """ import time import itertools def main(): max_consecutive = 0 max_config = tuple() a = 1 b = 2 c = 3 d = 4 while True: if a == b: a = 1 b += 1 if b == c: b = 2 c += 1 if c == d: c = 3 d += 1 target_nums = get_possible_target_nums(a, b, c, d) consecutive = count_consecutive(target_nums) if max_consecutive < consecutive: max_consecutive = consecutive max_config = a, b, c, d print('consecutive: {} (max {}), a,b,c,d: {} {} {} {} (max {})'.format(consecutive, max_consecutive, a, b, c, d, max_config)) a += 1 def count_consecutive(target_nums): count = 0 curr = 1 while True: if curr in target_nums: count += 1 curr += 1 else: return count def get_possible_target_nums(a, b, c, d): # contains all numbers that can be generated found_targets = set() for perm in list(itertools.permutations([a, b, c, d])): n1, n2, n3, n4 = perm operations = ['*', '/', '+', '-'] for x1 in operations: for x2 in operations: for x3 in operations: expressions = ['n1{}n2{}n3{}n4'.format(x1, x2, x3), '(n1{}n2){}n3{}n4'.format(x1, x2, x3), '(n1{}n2{}n3){}n4'.format(x1, x2, x3), 'n1{}(n2{}n3){}n4'.format(x1, x2, x3), 'n1{}(n2{}n3{}n4)'.format(x1, x2, x3), 'n1{}n2{}(n3{}n4)'.format(x1, x2, x3), '(n1{}n2){}(n3{}n4)'.format(x1, x2, x3)] for expression in expressions: #print(expression.replace('n1', str(n1)).replace('n2', str(n2)).replace('n3', str(n3)).replace('n4', str(n4)), eval(expression)) try: res = eval(expression) if res % 1 == 0 and res > 0: found_targets.add(res) except ZeroDivisionError: continue return found_targets if __name__ == '__main__': start_time = time.time() main() print("time:", time.time() - start_time)
C#
UTF-8
422
3.25
3
[]
no_license
namespace System.IO { using System.Text; using System.Threading.Tasks; internal static class StreamExtensions { public async static Task<string> ReadStringAsync(this Stream @this) { @this.Position = 0; using (var reader = new StreamReader(@this, Encoding.UTF8)) { return await reader.ReadToEndAsync(); } } } }
PHP
UTF-8
3,669
3.078125
3
[]
no_license
<?php require_once 'Conexion.php'; // class Empleado{ private $nif; public $nombre; public $telefono; public $email; public $departamento; public $categoria; public $salario; const tabla = 'empleados'; public function __construct($nif='', $nombre='', $telefono='', $email='', $departamento='', $categoria='', $salario=''){ $this->nif=$nif; $this->nombre=$nombre; $this->telefono=$telefono; $this->email=$email; $this->departamento=$departamento; $this->categoria=$categoria; $this->salario=$salario; } public function getNif(){ return $this->nif; } public function getNombre(){ return $this->nombre; } public function getTelefono(){ return $this->telefono; } public function getEmail(){ return $this->email; } public function getDepartamento(){ return $this->departamento; } public function getCategoria(){ return $this->categoria; } public function getSalario(){ return $this->salario; } public function setSalario(){ $this->salario = $salario; } public function setCategoria(){ $this->categoria = $categoria; } public function setDepartamento(){ $this->departamento = $departamento; } public function setEmail(){ $this->email = $email; } public function setTelefono(){ $this->telefono = $telefono; } public function setNombre(){ $this->nombre = $nombre; } public function setNif($nif){ $this->nif = $nif; } public function inserta($nif, $nombre, $telefono, $email, $departamento, $categoria, $salario){ $conexion = new Conexion(); try { $sql = 'INSERT INTO '.self::tabla.' VALUES (?, ?, ?, ?, ?, ?, ?)'; $sql = $conexion->prepare($sql); $sql->execute( array($nif, $nombre, $telefono, $email, $departamento, $categoria, $salario) ); } catch (Exception $e) { die($e->getMessage()); } $conexion = null; } public function elimina($nif){ try { $conexion = new Conexion(); $stm = $conexion->prepare('DELETE FROM '.self::tabla.' WHERE nif = ?'); $stm->execute(array($nif)); $conexion=null; }catch (Exception $e) { die($e->getMessage()); } } // public function listarAll(){ $conexion= new Conexion(); $sql = 'SELECT * FROM '.self::tabla; $res = $conexion->query($sql); $filas = $res->rowCount(); foreach ($res as $fila){ echo "<br/> nif: ".$fila[0]; echo "<br/> nombre: ".$fila[1]; echo " telefono: ".$fila[2]; echo " email: ".$fila[3]; echo " departamento: ".$fila[4]; echo " categoria: ".$fila[5]; echo "<br/> salario: ".$fila[6]; } echo "<br/> Total de empleados: $filas."; $res=null; $conexion=null; } public function listarMin(){ $conexion= new Conexion(); $sql= 'SELECT * FROM '.self::tabla.' WHERE salario = (SELECT MIN(salario) FROM '.self::tabla.')'; $res = $conexion->query($sql); $filas = $res->rowCount(); foreach ($res as $fila){ echo "<br/> nif: ".$fila[0]; echo "<br/> nombre: ".$fila[1]; echo " telefono: ".$fila[2]; echo " email: ".$fila[3]; echo " departamento: ".$fila[4]; echo " categoria: ".$fila[5]; echo "<br/> salario: ".$fila[6]; } echo "<br/> Total de empleados: $filas.<br/>"; $res=null; $conexion=null; } } class Departamento{ private $codigo; private $nombre; const tabla = 'departamentos'; public function __construct($codigo='', $nombre=''){ $this->codigo=$codigo; $this->nombre=$nombre; } public function getCodigo(){ return $this->codigo; } public function getNombre(){ return $this->nombre; } public function setNombre($nombre){ $this->nombre = $nombre; } public function setCodigo($codigo){ $this->nif = $codigo; } } ?>
JavaScript
UTF-8
362
2.90625
3
[ "Unlicense" ]
permissive
'use strict'; const inputRef = document.querySelector('#validation-input'); inputRef.addEventListener('focus', e => { inputRef.classList.remove('invalid', 'valid'); }); inputRef.addEventListener('blur', e => { e.target.value.length >= e.target.getAttribute('data-length') ? inputRef.classList.add('valid') : inputRef.classList.add('invalid'); });
Markdown
UTF-8
1,038
2.859375
3
[ "MIT" ]
permissive
linter-crystal ========================= This linter plugin for [Linter](https://github.com/AtomLinter/Linter) provides an interface to Crystal's builtin syntax analysis. It will be used with files that have the `Crystal` syntax. As well, you must have the Crystal compiler installed on this system for this to work, to learn how to install this please visit the [Crystal Language Documentation](http://crystal-lang.org/docs/installation/index.html). This package will ensure all dependencies are installed at activation. ## Contributing If you would like to contribute enhancements or fixes, please do the following: 1. Fork the plugin repository. 1. Hack on a separate topic branch created from the latest `master`. 1. Commit and push the topic branch. 1. Make a pull request. 1. welcome to the club Please note that modifications should follow these coding guidelines: - Indent is 2 spaces. - Code should pass coffeelint linter. - Vertical whitespace helps readability, don’t be afraid to use it. Thank you for helping out!
Python
UTF-8
833
3.6875
4
[]
no_license
# Definition for a binary tree node class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # @param root, a tree node # @return a tree node def recoverTree(self, root): self.node1 = None self.node2 = None self.pre = None self.inorderRec(root) tmp = node1.val self.node1.val = node2.val self.node2.val = tmp return root def inorderRec (self, root): if root == None: return self.inorderRec(root.left) if pre == None: self.pre = root if self.node1 == None and self.pre.val > self.root.val: self.node1 = self.pre self.node2 = root elif pre.val > root.val: self.node2 = root self.pre = root self.inorderRec(root.right)
C#
UTF-8
1,187
3.140625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace la01_2_oroklodes_konstruktor { class Ember { public int Eletkor { get; set; } public string Nev { get; set; } public void Bemutatkozas() { Console.WriteLine("Szia, én {0} vagyok.", Nev); } public Ember(string nev, int eletkor) { this.Nev = nev; this.Eletkor = eletkor; } } class Hallgato : Ember { public string NeptunKod { get; set; } public Hallgato(string nev, int eletkor) : base(nev, eletkor) { } public Hallgato(string nev, int eletkor, string neptunkod) : base(nev, eletkor) { this.NeptunKod = neptunkod; } } class Program { static void Main(string[] args) { Hallgato h = new Hallgato("Lajoska", 12); h.NeptunKod = "WER123"; Console.WriteLine(h.NeptunKod); Console.WriteLine(h.Nev); } } }
Python
UTF-8
1,149
2.8125
3
[]
no_license
from pathlib import Path import os import getpass import PyPDF2 DIR_PATH = Path.home()/"---"/"~~~" def main(): for folder_name, sub_folders, file_names in os.walk(DIR_PATH): for file_name in file_names: if not file_name.endswith(".pdf"): continue full_file_name = os.path.join(folder_name, file_name) pdf_reader = PyPDF2.PdfFileReader(open(full_file_name, "rb")) if not pdf_reader.isEncrypted: continue print("Open a file "+full_file_name) password = str(getpass.getpass("Please Enter Password:")) if pdf_reader.decrypt(password): pdf_writer = PyPDF2.PdfFileWriter() for page_num in range(pdf_reader.numPages): pdf_writer.addPage(pdf_reader.getPage(page_num)) with open(full_file_name.replace("_encrypted", ""), 'wb') as decrypted_pdf: pdf_writer.write(decrypted_pdf) print("Decrypted the file!") else: print("Wrong password! Can't open the file.") if __name__ == '__main__': main()
Java
UTF-8
7,920
2.390625
2
[]
no_license
package com.liuhuan.widget; import android.content.Context; import android.os.SystemClock; import android.support.annotation.Nullable; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.TextUtils; import android.text.style.ForegroundColorSpan; import android.util.AttributeSet; public class CountDownView extends android.support.v7.widget.AppCompatTextView { private boolean mStopTicking; private boolean mShouldRunTicker; private long endTime; //和时间结合一起的描述语,必须是这种格式:测试格式%s private String description=""; /** * 时分秒是否需要颜色 */ private int timeColor=-1; private CountDownLinstener countDownLinstener; public void setCountDownLinstener(CountDownLinstener linstener) { this.countDownLinstener = linstener; } public void setDescription(String des) { this.description = des; } public void setTimeColor(int timeColor) { this.timeColor = timeColor; } public void setEndTime(long endTime) { this.endTime = endTime; //onTimeChanged(); } public CountDownView(Context context) { super(context); } public CountDownView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public CountDownView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); start(); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); cancel(); } @Override public void onVisibilityAggregated(boolean isVisible) { super.onVisibilityAggregated(isVisible); if (!mShouldRunTicker && isVisible) { mShouldRunTicker = true; mTicker.run(); } else if (mShouldRunTicker && !isVisible) { mShouldRunTicker = false; getHandler().removeCallbacks(mTicker); } } private void onTimeChanged() { if (mShouldRunTicker) { long currentTime = System.currentTimeMillis(); long distanceTime = endTime -currentTime; if(distanceTime/1000 > 0){ setText(dealTime(distanceTime)); }else{ //setText("倒计时完成1"); if(countDownLinstener!=null && !mStopTicking){ mStopTicking = true; countDownLinstener.complete(CountDownView.this); } } } } public void start(){ if(!isAttachedToWindow()){ return; } mStopTicking = false; mShouldRunTicker = true; long distanceTime = endTime - System.currentTimeMillis(); if(endTime == -1){ return; } if(endTime > 0 && distanceTime/1000 > 0){ mTicker.run(); }else{ onTimeChanged(); } } public void cancel(){ if(mShouldRunTicker && isAttachedToWindow()){ //LogUtils.e("倒计时取消了"); mShouldRunTicker = false; mStopTicking = true; getHandler().removeCallbacks(mTicker); } } private final Runnable mTicker = new Runnable() { public void run() { if (mStopTicking) { return; // Test disabled the clock ticks } onTimeChanged(); long now = SystemClock.uptimeMillis(); long next = now + (1000 - now % 1000);//凑足1秒 long distanceTime = endTime - System.currentTimeMillis(); if(distanceTime/1000 > 0){ getHandler().postAtTime(mTicker, next); }else{ if(countDownLinstener!=null && !mStopTicking){ mStopTicking = true; countDownLinstener.complete(CountDownView.this); //setText("倒计时完成2"); } } } }; public CharSequence dealTime(long time) { StringBuffer returnString = new StringBuffer(); time = time/1000; long day = time / (24 * 60 * 60); long hours = (time % (24 * 60 * 60)) / (60 * 60); long minutes = ((time % (24 * 60 * 60)) % (60 * 60)) / 60; long second = ((time % (24 * 60 * 60)) % (60 * 60)) % 60; String format = "%02d";//补O使用 String dayStr =String.format(format,day); String hoursStr = String.format(format,hours); String minutesStr = String.format(format,minutes); String secondStr = String.format(format,second); /* returnString.append(hoursStr).append("小时").append(minutesStr) .append("分钟").append(secondStr).append("秒");*/ if(day > 0){ returnString.append(dayStr).append("天"); returnString.append(hoursStr).append("小时"); returnString.append(minutesStr).append("分钟"); returnString.append(secondStr).append("秒"); }else if(hours > 0){ returnString.append(hoursStr).append("小时"); returnString.append(minutesStr).append("分钟"); returnString.append(secondStr).append("秒"); }else if(minutes > 0){ returnString.append(minutesStr).append("分钟"); returnString.append(secondStr).append("秒"); }else if(second >= 0){ returnString.append(secondStr).append("秒"); } String content = returnString.toString(); if(!TextUtils.isEmpty(description)){ content = String.format(description,content); } if(timeColor!=-1){ //注意 description不能出现,天,小时,分钟,秒,字样,不然这里的颜色设置位置会出错 ForegroundColorSpan colorSpan0= new ForegroundColorSpan(timeColor); ForegroundColorSpan colorSpan1= new ForegroundColorSpan(timeColor); ForegroundColorSpan colorSpan2 = new ForegroundColorSpan(timeColor); ForegroundColorSpan colorSpan3 = new ForegroundColorSpan(timeColor); int dayIndex = content.indexOf("天")-dayStr.length(); int hoursIndex = content.indexOf("小时")-2; int minutesIndex = content.indexOf("分钟")-2; int secondIndex = content.indexOf("秒")-2; SpannableStringBuilder txt = new SpannableStringBuilder(content); if(day > 0) { txt.setSpan(colorSpan0, dayIndex, dayIndex+dayStr.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE); txt.setSpan(colorSpan1,hoursIndex,hoursIndex+2, Spanned.SPAN_EXCLUSIVE_INCLUSIVE); txt.setSpan(colorSpan2,minutesIndex,minutesIndex+2, Spanned.SPAN_EXCLUSIVE_INCLUSIVE); txt.setSpan(colorSpan3,secondIndex,secondIndex+2, Spanned.SPAN_EXCLUSIVE_INCLUSIVE); }else if(hours > 0){ txt.setSpan(colorSpan1,hoursIndex,hoursIndex+2, Spanned.SPAN_EXCLUSIVE_INCLUSIVE); txt.setSpan(colorSpan2,minutesIndex,minutesIndex+2, Spanned.SPAN_EXCLUSIVE_INCLUSIVE); txt.setSpan(colorSpan3,secondIndex,secondIndex+2, Spanned.SPAN_EXCLUSIVE_INCLUSIVE); }else if(minutes > 0){ txt.setSpan(colorSpan2,minutesIndex,minutesIndex+2, Spanned.SPAN_EXCLUSIVE_INCLUSIVE); txt.setSpan(colorSpan3,secondIndex,secondIndex+2, Spanned.SPAN_EXCLUSIVE_INCLUSIVE); } else if(second >= 0){ txt.setSpan(colorSpan3,secondIndex,secondIndex+2, Spanned.SPAN_EXCLUSIVE_INCLUSIVE); } return txt; } return content; } public interface CountDownLinstener{ void complete(CountDownView countDownView); } }
Markdown
UTF-8
1,115
2.609375
3
[]
no_license
# 一键锁屏.js ``` importClass(android.app.admin.DevicePolicyManager); importClass(android.content.ComponentName); var mDPM = context.getSystemService(context.DEVICE_POLICY_SERVICE); // 获取设备策略服务 var mDeviceAdminSample = new ComponentName(context, "org.autojs.autojs.ui.edit.EditActivity_"); activeAdmin(); lockScreen(); /** 激活设备管理器 */ function activeAdmin() { var intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN); intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mDeviceAdminSample); intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "我们有了超级设备管理器,好NB"); app.startActivity(intent); } /** 一键锁屏 */ function lockScreen() { if (mDPM.isAdminActive(mDeviceAdminSample)) { //判断设备管理器是否已经激活 mDPM.lockNow(); //立即锁屏 //mDPM.resetPassword("123456", 0); //设置密码 } else { toastLog("必须先激活设备管理器!"); } } //var vibrator = context.getSystemService(context.VIBRATOR_SERVICE); //vibrator.vibrate(10000);```
Markdown
UTF-8
1,436
2.75
3
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# Administration and security of Code Insights ## Code Insights enforce user permissions Users can only create code insights that include repositories they have access to. Moreover, when creating code insights, the repository field will *not* validate nor show users repositories they would not have access to otherwise. ## Security of native Sourcegraph Code Insights (Search-based and Language Insights) Sourcegraph search-based and language insights run natively on a Sourcegraph instance using the instance's Sourcegraph search API. This means they don't send any information about your code to third-party servers. ## Security of Sourcegraph extension-provided Code Insights Sourcegraph extension-provided insights adhere to the same security standards as any other Sourcegraph extension. Refer to [Security and privacy of Sourcegraph extensions](../../extensions/security.md). If you are concerned about the security of extension-provided insights, then you can: ## Disable Sourcegraph extension-provided Code Insights If you want to disable Sourcegraph-extension-provided code insights, you can do so the same way you would disable any other extension. Refer to [Disabling remote extensions](../../admin/extensions.md#use-extensions-from-sourcegraph-com-or-disable-remote-extensions) and [Allow only specific extensions](../../admin/extensions.md#use-extensions-from-sourcegraph-com-or-disable-remote-extensions).
C#
UTF-8
2,845
2.75
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace server_test_KLIENT { public class OdseparowaneIP { public byte ip3, ip2, ip1, ip0; public byte m3, m2, m1, m0; private byte mask; public Int32 numberOfComputers { get; private set; } public OdseparowaneIP() { mask = 32; GenerateNumberOfComputers(); } public override string ToString() { return "IP: " + IPToString() + "\nMask: " + MaskToString() + "\n Number of computers: " + numberOfComputers.ToString(); } public void ResetToNetworkAddress() { ip3 = (byte)(ip3 & m3); ip2 = (byte)(ip2 & m2); ip1 = (byte)(ip1 & m1); ip0 = (byte)(ip0 & m0); } public String MaskToString() { return ValuesToString(m3, m2, m1, m0); } public String IPToString() { return ValuesToString(ip3, ip2, ip1, ip0); } private String ValuesToString(byte v3, byte v2, byte v1, byte v0) { return v3.ToString() + "." + v2.ToString() + "." + v1.ToString() + "." + v0.ToString(); } private void SetIp(byte ip3, byte ip2, byte ip1, byte ip0) { this.ip3 = ip3; this.ip2 = ip2; this.ip1 = ip1; this.ip0 = ip0; } private void SetMask(Byte mask) { this.m3 = 0; this.m2 = 0; this.m1 = 0; this.m0 = 0; this.mask = mask; for (int i = 0; i < 8; i++) { if (i < mask) this.m3 += (byte)(1 << Math.Max(7 - i, 0)); } for (int i = 8; i < 16; i++) { if (i < mask) this.m2 += (byte)(1 << Math.Max(15 - i, 0)); } for (int i = 16; i < 24; i++) { if (i < mask) this.m1 += (byte)(1 << Math.Max(23 - i, 0)); } for (int i = 24; i < 32; i++) { if (i < mask) this.m0 += (byte)(1 << Math.Max(31 - i, 0)); } //MessageBox.Show(this.ToString()); } public void SetIPMask(byte ip3, byte ip2, byte ip1, byte ip0, Byte mask) { this.ip3 = ip3; this.ip2 = ip2; this.ip1 = ip1; this.ip0 = ip0; SetMask(mask); this.GenerateNumberOfComputers(); } private void GenerateNumberOfComputers() { numberOfComputers = (Int32)Math.Max(Math.Pow(2, 32 - mask) - 2, 1); //MessageBox.Show(this.ToString()); } } }
Java
UTF-8
1,447
2.03125
2
[]
no_license
package ru.webotix.app; import com.google.inject.Binder; import com.google.inject.Inject; import com.google.inject.Module; import com.google.inject.servlet.ServletModule; import io.dropwizard.Configuration; import io.dropwizard.assets.AssetsBundle; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; import io.dropwizard.websockets.WebsocketBundle; import ru.webotix.common.JerseyBaseApplication; import ru.webotix.websocket.WebSocketBundleInit; public abstract class WebApplication<T extends Configuration> extends JerseyBaseApplication<T> implements Module { @Inject private WebSocketBundleInit webSocketBundleInit; private WebsocketBundle websocketBundle; @Override public void initialize(final Bootstrap<T> bootstrap) { bootstrap.addBundle( new AssetsBundle("/assets/", "/", "index.html")); super.initialize(bootstrap); websocketBundle = new WebsocketBundle(new Class[]{}); bootstrap.addBundle(websocketBundle); } @Override protected abstract Module createApplicationModule(); @Override public void run(T webotixConfiguration, Environment environment) { super.run(webotixConfiguration, environment); webSocketBundleInit.init(websocketBundle); } @Override public void configure(Binder binder) { super.configure(binder); binder.install(new ServletModule()); } }
PHP
UTF-8
6,229
2.671875
3
[ "Apache-2.0" ]
permissive
<?php namespace Kolay; use Http\Client\Common\Plugin\ErrorPlugin; use Http\Discovery\HttpClientDiscovery; use Http\Client\Common\PluginClient; use Http\Client\Common\Exception\ClientErrorException; use Http\Client\HttpClient; use Http\Discovery\MessageFactoryDiscovery; use Http\Discovery\UriFactoryDiscovery; use Http\Message\Authentication; use Http\Message\RequestFactory; use Http\Message\UriFactory; use Psr\Http\Client\ClientExceptionInterface; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\UriInterface; class KolayClient { /** * @var string $baseUrl */ private $baseUrl = 'https://kolayik.com/api/v'; /** * @var string $apiVersion */ private $apiVersion = '1'; /** * @var HttpClient $httpClient */ private $httpClient; /** * @var RequestFactory $requestFactory */ private $requestFactory; /** * @var UriFactory $uriFactory */ private $uriFactory; /** * @var object Authentication method */ private $authenticator; /** * KolayClient constructor. * * @param array $options Connection options to be used through out the request. */ public function __construct($options = []) { if (isset($options['userCredentials'])) { $this->authenticator = new KolayAuthMethodUserCredentials($options['userCredentials']); } elseif (isset($options['public'])) { $this->authenticator = null; } else { throw new Exception('Invalid authentication method.'); } $this->baseUrl = $this->baseUrl . $this->apiVersion . '/'; $this->httpClient = $this->getDefaultHttpClient(); $this->requestFactory = MessageFactoryDiscovery::find(); $this->uriFactory = UriFactoryDiscovery::find(); } /** * Sets the HTTP client. * * @param HttpClient $httpClient */ public function setHttpClient(HttpClient $httpClient) { $this->httpClient = $httpClient; } /** * Sets the request factory. * * @param RequestFactory $requestFactory */ public function setRequestFactory(RequestFactory $requestFactory) { $this->requestFactory = $requestFactory; } /** * Sets the URI factory. * * @param UriFactory $uriFactory */ public function setUriFactory(UriFactory $uriFactory) { $this->uriFactory = $uriFactory; } /** * Sends POST request to Kolay API. * * @param string $endpoint * @param array $params * @return stdClass */ public function post($endpoint, $params) { $response = $this->sendRequest('POST', $this->baseUrl . $endpoint, $params); return $this->handleResponse($response); } /** * Sends PUT request to Kolay API. * * @param string $endpoint * @param array $params * @return stdClass */ public function put($endpoint, $params) { $response = $this->sendRequest('PUT', $this->baseUrl . $endpoint, $params); return $this->handleResponse($response); } /** * Sends DELETE request to Kolay API. * * @param string $endpoint * @param array $params * @return stdClass */ public function delete($endpoint, $params) { $response = $this->sendRequest('DELETE', $this->baseUrl . $endpoint, $params); return $this->handleResponse($response); } /** * Sends GET request to Kolay API. * * @param string $endpoint * @param array $queryParams * @return stdClass */ public function get($endpoint, $queryParams = []) { $uri = $this->uriFactory->createUri($this->baseUrl . $endpoint); if (!empty($queryParams)) { $uri = $uri->withQuery(http_build_query($queryParams)); } $response = $this->sendRequest('GET', $uri); return $this->handleResponse($response); } /** * @return HttpClient */ private function getDefaultHttpClient() { return new PluginClient( HttpClientDiscovery::find(), [new ErrorPlugin()] ); } /** * @return array */ private function getRequestHeaders() { return [ 'Accept' => 'application/json', 'Content-Type' => 'application/json' ]; } /** * Returns authenticator * * @return Authentication */ private function getAuthenticator() { if (!empty($this->authenticator)) { return $this->authenticator; } return null; } /** * Authenticates a request object * @param RequestInterface $request * * @return RequestInterface */ private function signRequest(RequestInterface $request) { $authenticator = $this->getAuthenticator(); return $authenticator ? $authenticator->sign($request)->authenticate($request) : $request; } /** * @param string $method * @param string|UriInterface $uri * @param array|string|null $body * * @return ResponseInterface * @throws ClientExceptionInterface */ private function sendRequest($method, $uri, $body = null) { $headers = $this->getRequestHeaders(); $body = is_array($body) ? json_encode($body) : $body; try { $request = $this->signRequest( $this->requestFactory->createRequest($method, $uri, $headers, $body) ); return $this->httpClient->sendRequest($request); } catch (ClientErrorException $e) { return $e->getResponse(); } } /** * @param ResponseInterface $response * * @return stdClass */ private function handleResponse(ResponseInterface $response) { $stream = $response->getBody()->getContents(); $response = json_decode($stream); if ($response->error) { return new KolayErrorResponse($response->code, $response->message, $response->details); } return $response->data ?? $response; } }
Java
UTF-8
917
2.515625
3
[]
no_license
package com.maksimovamaris.chess.game.pieces; import org.junit.Before; public class TestBishopBehavour extends TestHelper { private Bishop testBishop; private DiagonalCells diagonalCells; @Before public void prepareBoardDirector() { initialPrepare(); testBishop = new Bishop(Colors.WHITE, initialPosition); diagonalCells = new DiagonalCells(); correctPositions = diagonalCells.getPositions(); } @Override public void figureCantMove() { correctPositions.clear(); diagonalCells.block(anyFigure, director); testPosition(testBishop, correctPositions); } @Override public void figureCanEat() { diagonalCells.setEat(anyFigure, director); testPosition(testBishop, correctPositions); } @Override public void figureOnEmptyBoard() { testPosition(testBishop, correctPositions); } }
Rust
UTF-8
19,450
2.765625
3
[]
no_license
use rand::{random}; use std::mem; use fake_wesnoth; use rust_lua_shared::*; #[derive (Clone, Serialize, Deserialize, Debug)] pub struct Player { pub unit_moves: Vec<Option <Vec<(Move, f64)>>>, } use fake_wesnoth::{State, Unit, Move}; impl fake_wesnoth::Player for Player { fn move_completed (&mut self, state: & State, previous: & Unit, current: & Unit) { self.invalidate_moves (state, [previous.x, previous.y], 0); self.invalidate_moves (state, [current.x, current.y], 0) } fn attack_completed (&mut self, state: & State, attacker: & Unit, defender: & Unit, _: Option <& Unit>, _: Option <& Unit>) { self.invalidate_moves (state, [attacker.x, attacker.y], 0); self.invalidate_moves (state, [defender.x, defender.y], 0); } fn recruit_completed (&mut self, state: & State, unit: & Unit) { self.invalidate_moves (state, [unit.x, unit.y], 0); } fn turn_started (&mut self, _: & State) { for location in self.unit_moves.iter_mut() { *location = None; } } fn choose_move (&mut self, state: & State)->Move { let mut moves = self.collect_moves (state); moves.sort_by (|a, b| a.1.partial_cmp(&b.1).unwrap()); //printlnerr!("Moves: {:?}", moves); moves.iter().rev().next().unwrap().0.clone() } } impl Player { pub fn new(map: & fake_wesnoth::Map)->Player {Player {unit_moves: vec![None; (map.width*map.height) as usize]}} pub fn calculate_moves (&mut self, state: &fake_wesnoth::State) { for (index, location) in state.locations.iter().enumerate() { if let Some (unit) = location.unit.as_ref() { if self.unit_moves [index].is_none() && unit.side == state.current_side { self.unit_moves [index] = Some (possible_unit_moves (state, unit).into_iter().map (| action | { let evaluation = evaluate_move (state, &action, Default::default()); (action, evaluation) }).collect()); } } } } pub fn invalidate_moves (&mut self, state: &fake_wesnoth::State, origin: [i32; 2], extra_turns: i32) { for (index, location) in state.locations.iter().enumerate() { if location.unit.as_ref().map_or (true, | unit | fake_wesnoth::distance_between ([unit.x, unit.y], origin) <= unit.moves + 1 + extra_turns*unit.unit_type.max_moves) { self.unit_moves [index] = None; } } } pub fn collect_moves (&mut self, state: &fake_wesnoth::State)->Vec<(fake_wesnoth::Move, f64)> { self.calculate_moves (state); let mut results = vec![(fake_wesnoth::Move::EndTurn, 0.0)]; for location in self.unit_moves.iter() { if let Some (moves) = location.as_ref() { results.extend (moves.into_iter().cloned()); } } results } } fn stats_badness (unit: & Unit, stats: & fake_wesnoth::CombatantStats)->f64 { (unit.hitpoints as f64 - stats.average_hitpoints)*(if unit.canrecruit {2.0} else {1.0}) + stats.death_chance*(if unit.canrecruit {1000.0} else {50.0}) } pub fn evaluate_unit_position (state: & State, unit: &Unit, x: i32, y: i32)->f64 { let mut result = 0.0; let location = state.get(x, y); let terrain_info = state.map.config.terrain_info.get (location.terrain).unwrap(); let defense = *unit.unit_type.defense.get (location.terrain).unwrap() as f64; result -= defense / 10.0; if terrain_info.healing > 0 { let healing = ::std::cmp::min(terrain_info.healing, unit.unit_type.max_hitpoints - unit.hitpoints); result += healing as f64 - 0.8; } if unit.canrecruit { //result -= defense / 2.0; if !terrain_info.keep {result -= 6.0;} } result } #[derive (Copy, Clone)] pub struct EvaluateMoveParameters { pub accurate_combat: bool, pub aggression: f64, } impl Default for EvaluateMoveParameters { fn default()->Self {EvaluateMoveParameters { accurate_combat: true, aggression: 1.0, }} } pub fn evaluate_move (state: & State, input: & fake_wesnoth::Move, parameters: EvaluateMoveParameters)->f64 { match input { &fake_wesnoth::Move::Move {src_x, src_y, dst_x, dst_y, moves_left} => { let unit = state.get (src_x, src_y).unit.as_ref().unwrap(); let mut result = evaluate_unit_position (state, unit, dst_x, dst_y) - evaluate_unit_position (state, unit, src_x, src_y) + (random::<f64>() - moves_left as f64) / 100.0; let destination = state.get(dst_x, dst_y); let terrain_info = state.map.config.terrain_info.get (destination.terrain).unwrap(); if terrain_info.village { if let Some(owner) = destination.village_owner.as_ref() { if state.is_enemy (unit.side, *owner) { result += 14.0; } else if *owner != unit.side { result -= 0.5; } } else { result += 10.0; } } result }, &fake_wesnoth::Move::Attack {src_x, src_y, dst_x, dst_y, attack_x, attack_y, weapon} => { let mut attacker = state.get (src_x, src_y).unit.clone().unwrap(); attacker.x = dst_x; attacker.y = dst_y; let defender = state.get (attack_x, attack_y).unit.as_ref().unwrap(); let stats = if parameters.accurate_combat { fake_wesnoth::simulate_combat (state, &attacker, defender, weapon, fake_wesnoth::CHOOSE_WEAPON) } else { fake_wesnoth::guess_combat (state, &attacker, defender, weapon, fake_wesnoth::CHOOSE_WEAPON) }; evaluate_move (state, &fake_wesnoth::Move::Move {src_x, src_y, dst_x, dst_y, moves_left: 0}, parameters) + random::<f64>() + stats_badness (&defender, &stats.combatants [1]) - parameters.aggression*stats_badness (&attacker, &stats.combatants [0]) } &fake_wesnoth::Move::Recruit {dst_x, dst_y, unit_type} => { let mut example = state.map.config.unit_type_examples.get (unit_type).unwrap().clone(); example.side = state.current_side; example.x = dst_x; example.y = dst_y; random::<f64>()+100.0 }, &fake_wesnoth::Move::EndTurn => 0.0, } } pub fn evaluate_state (state: & State)->Vec<f64> { let mut ally_values = vec![0.0; state.sides.len()]; let mut enemy_values = vec![0.0; state.sides.len()]; for location in state.locations.iter() { if let Some(unit) = location.unit.as_ref() { let constant_value = unit.unit_type.cost as f64 + if unit.canrecruit {50.0} else {0.0}; let value = constant_value*(1.0 + unit.hitpoints as f64/unit.unit_type.max_hitpoints as f64)/2.0; for index in 0..state.sides.len() { if state.is_enemy (unit.side, index) { enemy_values[index] += value; } else { ally_values[index] += value; } } } if let Some(owner) = location.village_owner { let value = 9.0; for index in 0..state.sides.len() { if state.is_enemy (owner, index) { enemy_values[index] += value; } else { ally_values[index] += value; } } } } (0..state.sides.len()).map(|side| { let ally = ally_values[side]; let enemy = enemy_values[side]; let diff = ally-enemy; let tot = ally+enemy; let ratio = diff/tot; ratio.abs().powf(1.0/3.0)*ratio.signum() }).collect() } use std::collections::BinaryHeap; use std::rc::Rc; use std::cell::Cell; use std::cmp::Ordering; use smallvec::SmallVec; use typed_arena::Arena; pub struct PlayTurnFastParameters { pub allow_combat: bool, pub stop_at_combat: bool, pub exploit_kills: bool, pub pursue_villages: bool, pub evaluate_move_parameters: EvaluateMoveParameters, } impl Default for PlayTurnFastParameters { fn default()->Self {PlayTurnFastParameters { allow_combat: false, stop_at_combat: false, exploit_kills: false, pursue_villages: true, evaluate_move_parameters: Default::default(), }} } pub fn play_turn_fast (state: &mut State, parameters: PlayTurnFastParameters)->Vec<Move> { #[derive (Clone)] struct Action { evaluation: f64, action: Move, source: [i32; 2], destination: Option<[i32; 2]>, valid: Cell<bool>, } struct ActionReference<'a> (&'a Action); struct LocationInfo<'a> { choices: Vec<&'a Action>, moves_attacking: Vec<&'a Action>, last_update: usize, distance_to_target: i32, } struct Info<'a> { locations: Vec<LocationInfo<'a>>, actions: BinaryHeap <ActionReference<'a>>, last_update: usize, parameters: PlayTurnFastParameters, } impl<'a> Ord for ActionReference<'a> { fn cmp(&self, other: &Self) -> Ordering { self.0.evaluation.partial_cmp (&other.0.evaluation).unwrap() } } impl<'a> PartialEq for ActionReference<'a> { fn eq(&self, other: &Self) -> bool { self.0.evaluation == other.0.evaluation } } impl<'a> Eq for ActionReference<'a> {} impl<'a> PartialOrd for ActionReference<'a> { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } #[inline] fn index (state: & State, x: i32,y: i32)->usize {((x-1)+(y-1)*state.map.width) as usize} let action_arena = Arena::with_capacity(1000); let mut info = Info { locations: (0..state.locations.len()).map(|_| LocationInfo { choices: Vec::new(), moves_attacking: Vec::new(), last_update: 0, distance_to_target: i32::max_value(), }).collect(), actions: BinaryHeap::new(), last_update: 0, parameters }; fn evaluate (info: &Info, state: & State, action: & Move)-> f64 { let evaluation = evaluate_move (state, & action, info.parameters.evaluate_move_parameters); match action { &fake_wesnoth::Move::Move {src_x, src_y, dst_x, dst_y, ..} => { if !state.get (src_x, src_y).unit.as_ref().unwrap().canrecruit { let distance_1 = info.locations [index (state, src_x, src_y)].distance_to_target; let distance_2 = info.locations [index (state, dst_x, dst_y)].distance_to_target; let yay = distance_1 - distance_2 - 2; //printlnerr!("{:?}", ((src_x, src_y), distance_1, ( dst_x, dst_y), distance_2)); if yay > 0 { //printlnerr!("{:?}", ((src_x, src_y), distance_1, ( dst_x, dst_y), distance_2)); return evaluation + 5.0+yay as f64 } } }, _=>(), } evaluation } fn generate_action<'a, 'b, 'c: 'a+'b> (info: &'a mut Info<'b>, action_arena: &'c Arena<Action>, state: & State, unit: & Unit, action: Move) { let evaluation = evaluate (info, state, & action); if evaluation < 0.0 {return} let result = action_arena.alloc (Action { evaluation, action: action.clone(), valid: Cell::new (true), source: [unit.x, unit.y], destination: match action { fake_wesnoth::Move::Move {dst_x, dst_y, ..} | fake_wesnoth::Move::Attack {dst_x, dst_y, ..} | fake_wesnoth::Move::Recruit {dst_x, dst_y, ..} => Some([dst_x, dst_y]), _=>None, } }); info.actions.push (ActionReference (result)) ; match action { fake_wesnoth::Move::Attack {attack_x, attack_y, ..} => { info.locations [index (state, attack_x, attack_y)].moves_attacking.push (result); }, _=>() } info.locations [index (state, unit.x, unit.y)].choices.push (result); } fn reevaluate_action<'a, 'b, 'c: 'a+'b> (info: &'a mut Info<'b>, action_arena: &'c Arena<Action>, state: & State, action: & Action) { if !action.valid.get() { return } let mut new_action = (*action).clone(); action.valid.set (false); new_action.evaluation = evaluate (info, state, & action.action); let new_action = action_arena.alloc (new_action); info.actions.push (ActionReference (new_action)) ; match action.action { fake_wesnoth::Move::Attack {attack_x, attack_y, ..} => { info.locations [index (state, attack_x, attack_y)].moves_attacking.push (new_action); }, _=>() } info.locations [index (state, action.source[0], action.source[1])].choices.push (new_action); } fn generate_reach<'a, 'b, 'c: 'a+'b> (info: &'a mut Info<'b>, action_arena: &'c Arena<Action>, state: & State, unit: & Unit) { let reach = fake_wesnoth::find_reach (state, unit); for &(location, moves_left) in reach.list.iter() { if state.geta (location).unit.as_ref().map_or (false, | unit | unit.side != state.current_side || unit.moves == 0) {continue} if location != [unit.x, unit.y] { generate_action (info, action_arena, state, unit, fake_wesnoth::Move::Move { src_x: unit.x, src_y: unit.y, dst_x: location [0], dst_y: location [1], moves_left: 0 }); } if info.parameters.allow_combat && unit.attacks_left >0 { for adjacent in fake_wesnoth::adjacent_locations (& state.map, location) { if let Some(neighbor) = state.geta (adjacent).unit.as_ref() { if state.is_enemy (unit.side, neighbor.side) { for index in 0..unit.unit_type.attacks.len() { generate_action (info, action_arena, state, unit, fake_wesnoth::Move::Attack { src_x: unit.x, src_y: unit.y, dst_x: location [0], dst_y: location [1], attack_x: adjacent [0], attack_y: adjacent [1], weapon: index }); } } } } } } if info.parameters.allow_combat && unit.canrecruit { for location in recruit_hexes (state, [unit.x, unit.y]) { for & recruit in state.sides [unit.side].recruits.iter() { if state.sides [unit.side].gold >= state.map.config.unit_type_examples [recruit].unit_type.cost { generate_action (info, action_arena, state, unit, fake_wesnoth::Move::Recruit{ dst_x: location [0], dst_y: location [1], unit_type: recruit }); } } } } } let mut target_frontier = Vec::with_capacity(32); let mut next_frontier = Vec::with_capacity(32); for y in 1..(state.map.height+1) { for x in 1..(state.map.width+1) { let location = state.get (x,y); if let Some(unit) = location.unit.as_ref() { if unit.canrecruit && state.is_enemy (unit.side, state.current_side) { info.locations [index (state, x,y)].distance_to_target = 0; target_frontier.push ([unit.x, unit.y]); } } if info.parameters.pursue_villages && state.map.config.terrain_info [location.terrain].village && location.village_owner.map_or (true, | owner | state.is_enemy (owner, state.current_side)) { info.locations [index (state, x,y)].distance_to_target = 0; target_frontier.push ([x,y]); } }} while !target_frontier.is_empty() { for location in target_frontier.iter() { let distance = info.locations [index (state, location [0], location [1])].distance_to_target; for adjacent in fake_wesnoth::adjacent_locations (& state.map, *location) { let other_distance = &mut info.locations [index (state, adjacent [0], adjacent [1])].distance_to_target; if *other_distance >distance + 1 { *other_distance = distance + 1; next_frontier.push (adjacent) ; } } //printlnerr!("{:?}", (location, distance)); } mem::swap(&mut target_frontier, &mut next_frontier); next_frontier.clear(); } for y in 1..(state.map.height+1) { for x in 1..(state.map.width+1) { let location = state.get (x,y); if let Some(unit) = location.unit.as_ref() { if unit.side == state.current_side && (unit.moves > 0 || unit.attacks_left > 0) { generate_reach (&mut info, &action_arena, state, unit); } } }} fn update_info_after_move<'a, 'b, 'c: 'a+'b> (info: &'a mut Info<'b>, action_arena: &'c Arena<Action>, state: & State, action: &Action) { match action.action { fake_wesnoth::Move::Move {src_x, src_y, dst_x, dst_y, moves_left} => { for other_action in info.locations [index (state, action.source [0], action.source [1])].choices.drain(..) { other_action.valid.set (false); } }, fake_wesnoth::Move::Attack {src_x, src_y, dst_x, dst_y, attack_x, attack_y, weapon} => { for other_action in info.locations [index (state, action.source [0], action.source [1])].choices.drain(..) { other_action.valid.set (false); } let killed = state.get (attack_x, attack_y).unit.is_none(); if killed && info.parameters.exploit_kills { let modified: Vec<_> = info.locations [index(state, attack_x, attack_y)].moves_attacking.drain(..).filter (|m|m.valid.get()).map (| m| m.source).collect(); info.last_update += 1; for source in modified { let index = index(state, source[0], source[1]); if info.locations [index].last_update < info.last_update { info.locations [index].last_update = info.last_update; for other_action in info.locations [index].choices.drain(..) { other_action.valid.set (false); } generate_reach (info, action_arena, state, state.geta (source).unit.as_ref().unwrap()); } } } else if killed { for other_action in ::std::mem::replace(&mut info.locations [index(state, attack_x, attack_y)].moves_attacking, Vec::new()) { other_action.valid.set (false); } } else { for other_action in ::std::mem::replace(&mut info.locations [index(state, attack_x, attack_y)].moves_attacking, Vec::new()) { reevaluate_action (info, action_arena, state, &other_action); } } }, fake_wesnoth::Move::Recruit {dst_x, dst_y, ref unit_type} => { }, fake_wesnoth::Move::EndTurn => {}, } } let mut result = Vec::new() ; loop { let choice; let mut temporarily_invalid_choices: SmallVec<[ActionReference; 8]> = SmallVec::new() ; loop { let candidate = match info.actions.pop() { Some(a)=>a, _=>{ result.push (fake_wesnoth::Move::EndTurn); fake_wesnoth::apply_move (state, &mut Vec::new(), & fake_wesnoth::Move::EndTurn) ; return result }, }; if !candidate.0.valid.get() {continue} if let Some(destination) = candidate.0.destination { if let Some(unit) = state.geta (destination).unit.as_ref() { if unit.side == state.current_side && unit.moves > 0 { temporarily_invalid_choices.push (candidate); } continue; } } if let fake_wesnoth::Move::Recruit {unit_type, ..} = candidate.0.action { if state.sides [state.current_side].gold < state.map.config.unit_type_examples [unit_type].unit_type.cost { continue; } } choice = candidate.0; break } result.push (choice.action.clone() ); if info.parameters.stop_at_combat && match choice.action {fake_wesnoth::Move::Attack {..} => true, _=>false} { return result } info.actions.extend (temporarily_invalid_choices); fake_wesnoth::apply_move (state, &mut Vec::new(), & choice.action) ; if state.scores.is_some() { return result } update_info_after_move (&mut info, &action_arena, &*state, & choice) ; } }
C++
UTF-8
2,237
2.6875
3
[ "Apache-2.0" ]
permissive
// // Created by Erez on 15/05/20. // #include "PointLight.h" #include <glm/glm.hpp> #include <glm/vec3.hpp> #include <glm/mat4x4.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/matrix_transform.hpp> #include <android/log.h> PointLight::PointLight() :t(){ mSize = 5.0f; mat =nullptr; } PointLight::~PointLight(){ if(nullptr != mat){ delete mat; } } bool PointLight::setup(){ const char vertex_shader[] = "shaders/vertex/point_vertex_shader.glsl"; const char fragment_shader[] = "shaders/fragment/point_fragment_shader.glsl"; mat = Material::makeMaterial( vertex_shader, fragment_shader); __android_log_print(ANDROID_LOG_INFO, "PointLight", "done setup light material."); return (nullptr != mat && mat->isInitilized()); } void PointLight::setColor(const glm::vec3& color){ mColor = glm::vec3(color); } void PointLight::setPointSize(const float s){ mSize = s; } void PointLight::updatePosition(long time){ float angleInDegrees = (360.0f / 10000.0f) * ((int) time); float radians = glm::radians(angleInDegrees); t.identity(); t.translate(glm::vec3(0, 0, -5)); t.rotate(radians, glm::vec3(1.0f, 1.0f, 0.0f)); t.translate(glm::vec3(0, 0, 2)); } void PointLight::render(const glm::mat4& view, const glm::mat4& projection) { __android_log_print(ANDROID_LOG_INFO, "POINTLIGHT", "entering render"); mat->activate();//glUseProgram(mPointProgramHandle); // Pass in the mPosition glVertexAttrib3f(mat->getAttrib("a_Position"), .0f, .0f, .0f); // Pass in the model*view*projection matrix. glUniformMatrix4fv( mat->getUniform("u_MVPMatrix"), 1, GL_FALSE, glm::value_ptr(projection*view*t.get()) ); //Pass in light color glUniform3fv(mat->getUniform("u_Color"), 1, glm::value_ptr(mColor)); //Pass light size glUniform1f( mat->getUniform("u_pointSize"), mSize); glDrawArrays(GL_POINTS, 0, 1); mat->deactivate(); __android_log_print(ANDROID_LOG_INFO, "POINTLIGHT", "leaving render"); } glm::vec4 PointLight::position(){ return (t.get()*glm::vec4(.0f, .0f, .0f, 1.0)); }; void PointLight::setTransform(Transform &other) { t = other.get(); }
Swift
UTF-8
71
2.65625
3
[]
no_license
func doubleArray3 (xs : [Int]) -> [Int] { return xs.map{x in 2 * x} }
C++
UTF-8
457
2.8125
3
[]
no_license
#ifndef COUNTY_H #define COUNTY_H #include <string> using namespace std; class County { private: string countyName; string stateName; int rVote; int dVote; int oVote; public: County( string countyName, string stateName, int rVote, int dVote, int oVote ); County( string line, string stateName ); virtual ~County(); string getCountyName(); string getStateName(); int getRVote(); int getDVote(); int getOVote(); }; #endif
Java
UTF-8
92
1.6875
2
[]
no_license
package tictactoe.exceptions; public class TicTakToeException extends RuntimeException { }
JavaScript
UTF-8
876
2.953125
3
[]
no_license
import { Component } from 'react'; export default class CardDeckStorage extends Component { static cards = []; static grabCards(cardRequestAmount) { const requestCardList = []; let cardsLeft = this.cards.length; if (cardsLeft > 0 && cardsLeft > cardRequestAmount) { for (let i = 0; i < cardRequestAmount; i++) { let card = this.cards.shift(); requestCardList.push(card); } return requestCardList; } else { console.log("insufficient number of cards"); } } static queueCards(deck_id) { return fetch(`https://deckofcardsapi.com/api/deck/${deck_id}/draw/?count=52`) .then(response => response.json()) .then(result => { result.cards.map(index => this.cards.push(index)); }); } }
Markdown
UTF-8
711
2.890625
3
[]
no_license
# Variable & Funtion Name BUILDER A Group project for Shark Hack Hackathon ## Team Members: Alexandra Kollarova Shraddha Kharche Sonali Ganatra Brian Vannah ## Link: [Variable & Funtion Name BUILDER](https://alexandrakollarova.github.io/Variable-Name-Builder/) ## Description: This app allows you to generate descriptive variable and function names for your project. ## In action: ### Step 1 ### Choose your programming language ![alt text](images/visual1.png) ### Step 2 ### Describe what you're looking for ![alt text](images/visual2.png) ### Get Results ![alt text](images/visual3.png) ## Tech Used: - JavaScript - jQuery - HTML - CSS - Python ## Progress The project is still in progress. Working on machine learning part..
C#
UTF-8
1,978
2.6875
3
[ "MIT" ]
permissive
using System.Linq; using System.Net.Mail; using System.Threading; using System.Threading.Tasks; namespace DddDotNet.Infrastructure.Notification.Email.SmtpClient { public class SmtpClientEmailNotification : IEmailNotification { private readonly SmtpClientOptions _options; public SmtpClientEmailNotification(SmtpClientOptions options) { _options = options; } public async Task SendAsync(IEmailMessage emailMessage, CancellationToken cancellationToken = default) { var mail = new MailMessage(); mail.From = new MailAddress(emailMessage.From); emailMessage.Tos?.Split(';') .Where(x => !string.IsNullOrWhiteSpace(x)) .ToList() .ForEach(x => mail.To.Add(x)); emailMessage.CCs?.Split(';') .Where(x => !string.IsNullOrWhiteSpace(x)) .ToList() .ForEach(x => mail.CC.Add(x)); emailMessage.BCCs?.Split(';') .Where(x => !string.IsNullOrWhiteSpace(x)) .ToList() .ForEach(x => mail.Bcc.Add(x)); mail.Subject = emailMessage.Subject; mail.Body = emailMessage.Body; mail.IsBodyHtml = true; var smtpClient = new System.Net.Mail.SmtpClient(_options.Host); if (_options.Port.HasValue) { smtpClient.Port = _options.Port.Value; } if (!string.IsNullOrWhiteSpace(_options.UserName) && !string.IsNullOrWhiteSpace(_options.Password)) { smtpClient.Credentials = new System.Net.NetworkCredential(_options.UserName, _options.Password); } if (_options.EnableSsl.HasValue) { smtpClient.EnableSsl = _options.EnableSsl.Value; } await smtpClient.SendMailAsync(mail, cancellationToken); } } }
Java
UTF-8
7,754
2.09375
2
[ "MIT" ]
permissive
package cms; import http.FormPart; import http.HttpRequest; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import util.Logger; import util.Utils; import d2o.UploadFileRecord; import d2o.FlushingDb; public class FileHive { private static boolean initiated = false; private static FileHive current; private Logger log; private File hive_dir; private String index_file; private FlushingDb filedb; private static final String prefix = "file"; public static FileHive getFileHive() { if (initiated) { return current; } else { initiated = true; current = new FileHive(); return current; } } private FileHive() { log = new Logger("FileHive"); hive_dir = Cgicms.uploaded_dir; index_file = "file_index"; filedb = new FlushingDb(index_file); log.info("init hive[" + hive_dir.getName() + "]"); } public boolean addFile(String user, boolean public_access, String access_groups, String category, FormPart part) { UploadFileRecord record = new UploadFileRecord(); record.filename = part.getFilename(); if (filedb.pol(record.filename)) { log.info("file [" + record.filename + "] allready in db"); String oldname = record.filename; String newname = null; String prefix; String postfix; int t = oldname.lastIndexOf('.'); if(t == -1){ prefix = oldname; postfix= ""; }else{ prefix = oldname.substring(0, t); if(oldname.length() == t-1){ postfix = ""; }else{ postfix = oldname.substring(t); } } for(int i = 1; i < 1000; i++){ String temp = prefix+"("+Utils.addLeading(i, 1)+")"+postfix; log.info("pol name ["+temp+"]"); if(!filedb.pol(temp)){ newname = temp; break; } } if(newname == null){ log.fail("could not generate new name ["+prefix+"]#["+postfix+"]"); return false; } log.info("new name for ["+oldname+"] -> ["+newname+"]"); record.filename = newname; } record.stored_name = genNewStoredName(); record.size = part.bytes.length; record.content_type = part.getContentType(); record.content_encoding = part.getContentEncoding(); record.content_disposition = part.getContentDisposition(); record.upload_user = user; record.upload_date = System.currentTimeMillis(); record.download_count = 0; record.public_access = public_access; record.category = category; record.access_groups = (access_groups == null ? "" : access_groups); if (!filedb.add(record.filename, record.toArray())) { log.fail("could not add record to db"); return false; } if (!FileOps.write(new File(hive_dir, record.stored_name), part.bytes, false)) { log.fail("could not write file content to disk"); return false; } return true; } public boolean deleteFile(String filename) { log.info("removing file and index entry from uploads"); if (!filedb.pol(filename)) { log.fail("file not found in index"); return false; } UploadFileRecord record = new UploadFileRecord(filedb.get(filename)); File target = new File(hive_dir, record.stored_name); if (target.exists()) { if (!target.delete()) { log.fail("could not delete target file"); return false; } } else { log.info("target file does not exist. removing index + meta"); } if (!filedb.del(filename)) { log.fail("could not remove file from index"); return false; } return true; } public boolean renameFile(String filename, String newname){ log.info("renaming file ["+filename+"] -> ["+newname+"]"); if(!filedb.pol(filename)) { log.fail("file not found in index"); return false; } if(filedb.pol(newname)){ log.fail("cannot rename, new name in use"); return false; } //TODO:check newname; return filedb.ren(filename, newname); } public String getFileResponse(String filename, boolean attach) { if (!filedb.pol(filename)) return null; UploadFileRecord record = new UploadFileRecord(filedb.get(filename)); String data = getFileContents(record.stored_name); if(data == null){ log.fail("source file["+record.stored_name+ "] for ["+filename+"] not found"); return null; } StringBuilder sb = new StringBuilder("Content-Type: " + record.content_type); if(attach) sb.append("\nContent-Disposition: attachment; filename=\"" + record.filename + "\""); sb.append('\n'); sb.append('\n'); sb.append(data); return sb.toString(); } public List<UploadFileRecord> getFileRecords() { ArrayList<UploadFileRecord> records = new ArrayList<UploadFileRecord>(); for(String[] raw : filedb.all()){ records.add(new UploadFileRecord(raw)); } return records; } public UploadFileRecord getFileRecord(String filename) { if(filedb.pol(filename)) return new UploadFileRecord(filedb.get(filename)); return null; } public boolean hasFile(String filename) { return filedb.pol(filename); } private String genNewStoredName() { HashSet<String> names = new HashSet<String>(); for (String[] raw : filedb.all()) { UploadFileRecord record = new UploadFileRecord(raw); names.add(record.stored_name); } for (int postfix = 0; postfix < 999; postfix++) { if (!names.contains(prefix + Utils.addLeading(postfix, 4))) { return prefix + Utils.addLeading(postfix, 4); } } log.fail("could not find suitable name for storing the file"); return null; } private String getFileContents(String file) { try { BufferedReader bin = new BufferedReader( new InputStreamReader(new FileInputStream(new File( hive_dir, file)), "ISO-8859-1")); StringBuilder sbuf = new StringBuilder(); int last; while ((last = bin.read()) > -1) { sbuf.append((char) last); } bin.close(); return sbuf.toString(); } catch (IOException ioe) { log.fail("error reading data: " + ioe); } return null; } /** * sendFile is used for encapsulating a file within a httprequest * and used only in the --servefile operation mode of cms * * @param request existing request which will serve this file * @return true if file is loaded without exceptions, false if there is\ * no PATH_INFO or it is erroneous, or if ioexception occurs */ public boolean sendFile(HttpRequest request) { log.info("sendFile()..."); String pathi; if ((pathi = System.getenv("PATH_INFO")) == null) { return false; } log.info("pathi: " + pathi); pathi = pathi.substring(1, pathi.length()); // -> /scan.txt log.info(" ->" + pathi); if (pathi.contains("/")) { return false; } String file = pathi; String data = getFileResponse(file, true); try { BufferedWriter bout = new BufferedWriter(new OutputStreamWriter( System.out, "ISO-8859-1")); bout.write(data); bout.close(); } catch (IOException ioe) { log.fail("error while sending raw data: " + ioe); return false; } return true; } public boolean updateFileRecord(UploadFileRecord record){ return filedb.mod(record.filename, record.toArray()); } public void up(String filename) { if (!filedb.pol(filename)) { return; } UploadFileRecord record = new UploadFileRecord(filedb.get(filename)); record.download_count++; filedb.mod(record.filename, record.toArray()); } }
Markdown
UTF-8
9,981
2.734375
3
[ "MIT" ]
permissive
--- title: VSCode 快捷键 date: 2020-01-30 21:00:00 tags: 'VSCode' categories: - ['使用说明', '软件'] permalink: vscode-hot-keys photo: --- ## 简介 > VSCode 快捷键偏向 Emacs 类型 其中比较常用的快捷键, 都是批量替换偏多的操作 - `Ctrl + D`: 快速选择单词 - `Ctrl + G`: 跳转行 - `Shift + Alt + I`: 快速选择所有选中行 <!-- more --> ## 通用快捷键 | 快捷键 | 作用 | | ------------------- | ---------------------- | | Ctrl + Shift + P,F1 | 展示全局命令面板 | | Ctrl + P | 快速打开最近打开的文件 | | Ctrl + Shift + N | 打开新的编辑器窗口 | | Ctrl + Shift + W | 关闭编辑器 | ## 基础编辑 | 快捷键 | 作用 | | -------------------- | ------------------------ | | Ctrl + X | 剪切 | | Ctrl + C | 复制 | | Alt + up/down | 移动行上下 | | Shift + Alt up/down | 在当前行上下复制当前行 | | Ctrl + Shift + K | 删除行 | | Ctrl + Enter | 在当前行下插入新的一行 | | Ctrl + Shift + Enter | 在当前行上插入新的一行 | | Ctrl + Shift + | 匹配花括号的闭合处,跳转 | | | Ctrl + ] / [ | 行缩进 | | Home | 光标跳转到行头 | | End | 光标跳转到行尾 | | Ctrl + Home | 跳转到页头 | | Ctrl + End | 跳转到页尾 | | Ctrl + up/down | 行视图上下偏移 | | Alt + PgUp/PgDown | 屏视图上下偏移 | | Ctrl + Shift + [ | 折叠区域代码 | | Ctrl + Shift + ] | 展开区域代码 | | Ctrl + K Ctrl + [ | 折叠所有子区域代码 | | Ctrl + k Ctrl + ] | 展开所有折叠的子区域代码 | | Ctrl + K Ctrl + 0 | 折叠所有区域代码 | | Ctrl + K Ctrl + J | 展开所有折叠区域代码 | | Ctrl + K Ctrl + C | 添加行注释 | | Ctrl + K Ctrl + U | 删除行注释 | | Ctrl + / | 添加关闭行注释 | | Shift + Alt +A | 块区域注释 | | Alt + Z | 添加关闭词汇包含 | ## 导航 | 快捷键 | 作用 | | ------------------ | ------------------------ | | Ctrl + T | 列出所有符号 | | Ctrl + G | 跳转行 | | Ctrl + P | 跳转文件 | | Ctrl + Shift + O | 跳转到符号处 | | Ctrl + Shift + M | 打开问题展示面板 | | F8 | 跳转到下一个错误或者警告 | | Shift + F8 | 跳转到上一个错误或者警告 | | Ctrl + Shift + Tab | 切换到最近打开的文件 | | Alt + left / right | 向后, 向前 | | Ctrl + M | 进入用Tab来移动焦点 | ## 查询和替换 | 快捷键 | 作用 | | ----------------- | ------------------------------------------- | | Ctrl + F | 查询 | | Ctrl + H | 替换 | | F3 / Shift + F3 | 查询下一个/上一个 | | Alt + Enter | 选中所有出现在查询中的 | | Ctrl + D | 匹配当前选中的词汇或者行,再次选中-可操作 | | Ctrl + K Ctrl + D | 移动当前选择到下个匹配选择的位置 (光标选定) | | Alt + C / R / W | 切换使用区分大小写方式查找 | ## 多行光标操作 | 快捷键 | 作用 | | -------------------------------- | ---------------------------------------- | | Alt + Click | 插入光标-支持多个 | | Ctrl + Alt + up/down | 上下插入光标-支持多个 | | Ctrl + U | 撤销最后一次光标操作 | | Shift + Alt + I | 插入光标到选中范围内所有行结束符 | | Ctrl + I | 选中当前行 | | Ctrl + Shift + L | 选择所有出现在当前选中的行-操作 | | Ctrl + F2 | 选择所有出现在当前选中的词汇-操作 | | Shift + Alt + right | 从光标处扩展选中全行 | | Shift + Alt + left | 收缩选择区域 | | Shift + Alt + (drag mouse) | 鼠标拖动区域,同时在多个行结束符插入光标 | | Ctrl + Shift + Alt + (Arrow Key) | 也是插入多行光标的 (方向键控制) | | Ctrl + Shift + Alt + PgUp/PgDown | 也是插入多行光标的 (整屏生效) | ## 语言操作 | 快捷键 | 作用 | | -------------------- | ------------------------------ | | Ctrl + Space | 输入建议 (智能提示) | | Ctrl + Shift + Space | 参数提示 | | Tab | Emmet指令触发/缩进 | | Shift + Alt + F | 格式化代码 | | Ctrl + K Ctrl + F | 格式化选中部分的代码 | | F12 | 跳转到定义处 | | Alt + F12 | 代码片段显示定义 | | Ctrl + K F12 | 在其他窗口打开定义处 | | Ctrl + . | 快速修复部分可以修复的语法错误 | | Shift + F12 | 显示所有引用 | | F2 | 重命名符号 | | Ctrl + Shift + . / , | 替换下个值 | | Ctrl + K Ctrl + X | 移除空白字符 | | Ctrl + K M | 更改页面文档格式 | ## 编辑器管理 | 快捷键 | 作用 | | -------------------------- | ------------------------ | | Ctrl + F4, Ctrl + W | 关闭编辑器 | | Ctrl + k F | 关闭当前打开的文件夹 | | Ctrl + | 切割编辑窗口 | | | Ctrl + 1/2/3 | 切换焦点在不同的切割窗口 | | Ctrl + K Ctrl <-/-> | 切换焦点在不同的切割窗口 | | Ctrl + Shift + PgUp/PgDown | 切换标签页的位置 | | Ctrl + K <-/-> | 切割窗口位置调换 | ## 文件管理 | 快捷键 | 作用 | | ------------------ | ------------------------------------- | | Ctrl + N | 新建文件 | | Ctrl + O | 打开文件 | | Ctrl + S | 保存文件 | | Ctrl + Shift + S | 另存为 | | Ctrl + K S | 保存所有当前已经打开的文件 | | Ctrl + F4 | 关闭当前编辑窗口 | | Ctrl + K Ctrl + W | 关闭所有编辑窗口 | | Ctrl + Shift + T | 撤销最近关闭的一个文件编辑窗口 | | Ctrl + K Enter | 保持开启 | | Ctrl + Shift + Tab | 调出最近打开的文件列表,重复按会切换 | | Ctrl + Tab | 与上面一致,顺序不一致 | | Ctrl + K P | 复制当前打开文件的存放路径 | | Ctrl + K R | 打开当前编辑文件存放位置 (文件管理器) | | Ctrl + K O | 在新的编辑器中打开当前编辑的文件 | ## 显示 | 快捷键 | 作用 | | ---------------- | ----------------------------- | | F11 | 切换全屏模式 | | Shift + Alt + 1 | 切换编辑布局 (目前无效) | | Ctrl + =/- | 放大 / 缩小 | | Ctrl + B | 侧边栏显示隐藏 | | Ctrl + Shift + E | 资源视图和编辑视图的焦点切换 | | Ctrl + Shift + F | 打开全局搜索 | | Ctrl + Shift + G | 打开Git可视管理 | | Ctrl + Shift + D | 打开DeBug面板 | | Ctrl + Shift + X | 打开插件市场面板 | | Ctrl + Shift + H | 在当前文件替换查询替换 | | Ctrl + Shift + J | 开启详细查询 | | Ctrl + Shift + V | 预览Markdown文件 (编译后) | | Ctrl + K v | 在边栏打开渲染后的视图 (新建) | ## 调试 | 快捷键 | 作用 | | ----------------- | ------------------- | | F9 | 添加解除断点 | | F5 | 启动调试, 继续 | | F11 / Shift + F11 | 单步进入 / 单步跳出 | | F10 | 单步跳过 | | Ctrl + K Ctrl + I | 显示悬浮 | ## 集成终端 | 快捷键 | 作用 | | --------------------- | -------------------- | | Ctrl + ` | 打开集成终端 | | Ctrl + Shift + ` | 创建一个新的终端 | | Ctrl + Shift + C | 复制所选 | | Ctrl + Shift + V | 复制到当前激活的终端 | | Shift + PgUp / PgDown | 页面上下翻屏 | | Ctrl + Home / End | 滚动到页面头部或尾部 | ## 引用 - [VS Code折腾记 - (2) 快捷键大全,没有更全](https://blog.csdn.net/crper/article/details/54099319)
Swift
UTF-8
2,075
2.6875
3
[]
no_license
// // ViewController.swift // Prework // // Created by Daniel Astudillo on 1/14/21. // import UIKit class ViewController: UIViewController { @IBOutlet weak var billAmountTextField: UITextField! @IBOutlet weak var tipControl: UISegmentedControl! @IBOutlet weak var tipAmountLabel: UILabel! @IBOutlet weak var totalLabel: UILabel! @IBOutlet weak var tipAmount: UILabel! @IBOutlet weak var tipSlider: UISlider! @IBOutlet weak var sliderRate: UILabel! @IBOutlet weak var totalAmount: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func onTap(_ sender: Any) { view.endEditing(true) } // alternative method for making keyboard disappear: a little more complicated. // override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { // view.endEditing(true) // super.touchesBegan(touches, with: event) // } @IBAction func setRate(_ sender: Any) { sliderRate.text = String(format: "%.2f",tipSlider.value) + "%" sliderRate.sizeToFit() let bill = Double(billAmountTextField.text!) ?? 0 let tip = bill * Double(tipSlider.value / 100) tipAmount.text = String(format: "$%.2f",tip) let newTotal = bill + tip totalAmount.text = String(format: "$%.2f",newTotal) tipAmount.sizeToFit() totalAmount.sizeToFit() } @IBAction func calculateTip(_ sender: Any) { let bill = Double(billAmountTextField.text!) ?? 0 let tipPercentages = [0.15,0.18,0.2] let tip = bill * tipPercentages[tipControl.selectedSegmentIndex] let total = bill + tip tipAmount.text = String(format: "$%.2f",tip) sliderRate.text = String(format: "%.2f",tipPercentages[tipControl.selectedSegmentIndex] * 100) + "%" sliderRate.sizeToFit() totalAmount.text = String(format: "$%.2f",total) tipAmount.sizeToFit() totalAmount.sizeToFit() } }
Python
UTF-8
1,475
3.8125
4
[]
no_license
class Solution: def nextPermutation(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ l = len(nums) index = 0 reverse = True if l > 1: for i in range(l-2,-1,-1): if nums[i] < nums[i+1]: index = i reverse = False break if not reverse: for i in range(l-1, index, -1): if nums[i] > nums[index]: nums[i], nums[index] = nums[index], nums[i] nums[index+1:] = list(reversed(nums[index+1:])) break else: nums.reverse() '''是找当前列表按照字典顺序排序的下一个排列。思路是从右往左遍历,若找到一个数比右边的数小, 则记录该数的index。再次从右往左遍历,找到第一个比记录值大的数,然后将两个数交换,再将index 右边所有数整体reverse。时间复杂度:O(n) 空间复杂度:O(n) Corner Case在于如果初始列表长度 小于2,那就不需要任何操作;如果列表内数为递减,则要将整个列表reverse。陷阱在于,将两个数交换 后,不太能理解将之后部分的数组reverse,因为这个字典顺序排序里的下一个排序,所以之后部分数组要 做到是最小值,也就是将原来的递减变换为递增。'''
Java
UTF-8
1,803
2.296875
2
[]
no_license
package web.client; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import service.impl.BusinessServiceImpl; import domain.Cart; import domain.User; @WebServlet("/client/OrderServlet") public class OrderServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try{ User user = (User) request.getSession().getAttribute("user"); if(user == null){ request.setAttribute("message", "对不起,请先登录"); request.getRequestDispatcher("/message.jsp").forward(request, response); return; } String address = request.getParameter("address"); String bookid = request.getParameter("bookid"); Cart cart = (Cart) request.getSession().getAttribute("cart"); BusinessServiceImpl service = new BusinessServiceImpl(); service.createSimpleOrder(cart,user,bookid,address); //service.createOrder(cart, user); request.setAttribute("message", "订单已生成"); //request.getSession().removeAttribute("cart");//清空购物车,因为点购买后,如果不清空购物车,前端点击查看购物车又出现了 request.getRequestDispatcher("/message.jsp").forward(request, response); }catch(Exception e){ e.printStackTrace(); request.setAttribute("message", e.getMessage()); request.getRequestDispatcher("/message.jsp").forward(request, response); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
C
UTF-8
3,304
2.734375
3
[ "MIT" ]
permissive
#include "vector3d.h" #include "fmgr.h" ///////////////////////////VECTOR GENERATION METHODS//////////////////////////// // PG_FUNCTION_INFO_V1(vector3d_constant); Datum vector3d_constant(PG_FUNCTION_ARGS) { double value = PG_GETARG_FLOAT8(0); PG_RETURN_ARRAYTYPE_P(Vector3dConstant(value)); } // PG_FUNCTION_INFO_V1(vector3d_random); Datum vector3d_random(PG_FUNCTION_ARGS) { PG_RETURN_ARRAYTYPE_P(Vector3dRandom()); } //////////////////////////////VECTOR ARITHMETIC///////////////////////////////// // VECTOR ADDITION PG_FUNCTION_INFO_V1(vector3d_add); Datum vector3d_add(PG_FUNCTION_ARGS) { ArrayType *a1 = PG_GETARG_ARRAYTYPE_P(0); ArrayType *a2 = PG_GETARG_ARRAYTYPE_P(1); PG_RETURN_ARRAYTYPE_P(Vector3dAdd(a1,a2)); } // VECTOR SUBTRACTION PG_FUNCTION_INFO_V1(vector3d_subtract); Datum vector3d_subtract(PG_FUNCTION_ARGS) { ArrayType *a1 = PG_GETARG_ARRAYTYPE_P(0); ArrayType *a2 = PG_GETARG_ARRAYTYPE_P(1); PG_RETURN_ARRAYTYPE_P(Vector3dSubtract(a1,a2)); } // VECTOR DIVISION BY SCALAR PG_FUNCTION_INFO_V1(vector3d_scalar_division); Datum vector3d_scalar_division(PG_FUNCTION_ARGS) { ArrayType *array = PG_GETARG_ARRAYTYPE_P(0); double scalar = PG_GETARG_FLOAT8(1); PG_RETURN_ARRAYTYPE_P(Vector3dScalarDivision(array, scalar)); } // VECTOR MULTIPLICATION BY SCALAR PG_FUNCTION_INFO_V1(vector3d_scalar_product); Datum vector3d_scalar_product(PG_FUNCTION_ARGS) { ArrayType *array = PG_GETARG_ARRAYTYPE_P(0); double scalar = PG_GETARG_FLOAT8(1); PG_RETURN_ARRAYTYPE_P(Vector3dScalarProduct(array, scalar)); } // VECTOR DOT PRODUCT PG_FUNCTION_INFO_V1(vector3d_dot); Datum vector3d_dot(PG_FUNCTION_ARGS) { ArrayType *a1 = PG_GETARG_ARRAYTYPE_P(0); ArrayType *a2 = PG_GETARG_ARRAYTYPE_P(1); PG_RETURN_FLOAT8(Vector3dDot(a1,a2)); } // VECTOR CROSS PRODUCT PG_FUNCTION_INFO_V1(vector3d_cross); Datum vector3d_cross(PG_FUNCTION_ARGS) { ArrayType *a1 = PG_GETARG_ARRAYTYPE_P(0); ArrayType *a2 = PG_GETARG_ARRAYTYPE_P(1); PG_RETURN_ARRAYTYPE_P(Vector3dCross(a1, a2)); } // CALCULATES THE NORM/LENGTH OF THE VECTOR PG_FUNCTION_INFO_V1(vector3d_norm); Datum vector3d_norm(PG_FUNCTION_ARGS) { ArrayType *vector3d = PG_GETARG_ARRAYTYPE_P(0); PG_RETURN_FLOAT8(Vector3dNorm(vector3d)); } // RETURNS THE NORMALIZED VECTOR PG_FUNCTION_INFO_V1(vector3d_normalized); Datum vector3d_normalized(PG_FUNCTION_ARGS) { ArrayType *array = PG_GETARG_ARRAYTYPE_P(0); PG_RETURN_ARRAYTYPE_P(Vector3dNormalized(array)); } // DISTANCE BETWEEN VECTORS PG_FUNCTION_INFO_V1(vector3d_distance); Datum vector3d_distance(PG_FUNCTION_ARGS) { ArrayType *a1 = PG_GETARG_ARRAYTYPE_P(0); ArrayType *a2 = PG_GETARG_ARRAYTYPE_P(1); PG_RETURN_FLOAT8(Vector3dDistance(a1,a2)); } // ANGLE BETWEEN VECTORS PG_FUNCTION_INFO_V1(vector3d_angle); Datum vector3d_angle(PG_FUNCTION_ARGS) { ArrayType *a1 = PG_GETARG_ARRAYTYPE_P(0); ArrayType *a2 = PG_GETARG_ARRAYTYPE_P(1); PG_RETURN_FLOAT8(Vector3dAngle(a1,a2)); } // ABSOLUTE ANGLE BETWEEN VECTORS PG_FUNCTION_INFO_V1(vector3d_abs_angle); Datum vector3d_abs_angle(PG_FUNCTION_ARGS) { ArrayType *a1 = PG_GETARG_ARRAYTYPE_P(0); ArrayType *a2 = PG_GETARG_ARRAYTYPE_P(1); PG_RETURN_FLOAT8(Vector3dAbsAngle(a1,a2)); }
Markdown
UTF-8
2,983
2.515625
3
[]
no_license
# Projeto 2 - Criando segmentos de clientes Segundo projeto do NanoDegree de Engenheiro Machine Learning da Udacity. Consiste em aplicar técnicas de aprendizagem supervisionada sobre os dados coletados pelo censo dos Estados Unidos para ajudar a CharityML (uma instituição de caridade fictícia) a identificar as pessoas com maior probabilidade de doar à causa deles. # Objetivo do Projeto Usar técnicas de aprendizagem não supervisionada em dados sobre gastos, coletados de clientes de uma distribuidora atacadista em Lisboa, para identificar segmentos de clientes ocultos nos dados. # Destaques do Projeto Este projeto foi desenvolvido para você ter experiência prática com aprendizagem não supervisionada e trabalhar desenvolvendo conclusões para um cliente em potencial com um conjunto de dados do mundo real. Muitas empresas, hoje, colhem uma vasta quantidade de dados sobre clientes, e eles têm um forte desejo de entender o significado das relações escondidos em sua clientela. Ter essa informação pode ajudar o engenheiro da empresa com futuros produtos e serviços que melhor satisfazem as demandas ou necessidades de seus clientes. O que você aprenderá ao concluir este projeto: Como aplicar técnicas de pré-processamento, como dimensionamento de atributos e detecção de valores aberrantes. Como interpretar dados que foram dimensionados, transformados ou reduzidos por meio de PCA. Como analisar as dimensões de PCA e construir um novo espaço de atributos. Como agrupar de forma ótima um conjunto de dados para encontrar padrões ocultos. Como avaliar informações dadas pelos dados segmentados e utilizá-los de maneira significativa. # Algoritmos Usados no Projeto DecisionTree e K-Algoritmos. # Resultados dos Modelos Nós estabelecemos dois clusters iniciais e o score foi realmente melhor com apenas 2 clusters. Definimos eles como Restaurante e Supermercado, generalizando. Restaurantes, ou estabelecimentos que vendem comidas prontas, precisam ser abastecidos quase todo dia. Precisam de reposição de produtos e sem falta. Acho que esse tipo de cliente não ficaria satisfeito com uma diminuição de entrega de 5 para 3 dias na semana. Já um estabelecimento de supermercado, não precisa de um reabastecimento de mercadorias com tanta frequencia. Talvez de alguns produtos específicos, mas olhando por cima, acho que daria pra fazer um acordo e uma entrega de 3 dias por semana não os afetariam. Com isso, os testes A/B poderiam ser feitos em clientes do segundo segmento, facilitando a escolha dos clientes e os testes também e, depois, verificar a satisfação deles. # Explicação do Modelo Escolhido Vou utilizar o K-Means, apesar do MMG ser melhor com dados não lineares, vimos que os 2 primeiros principais componentes são responsáveis pos quase 72% da variância. Então já sabemos que precisaremos de 2 clusters. No caso do modelo MMG, poderíamos aplicar se não tivéssemos um número de cluster já definido.
Python
UTF-8
14,508
2.671875
3
[ "Apache-2.0" ]
permissive
""" Gaitmate.py Code by Sammy Haq https://github.com/sammyhaq Class for pulling all of the libraries defined in this folder together. Contains everything, from the primary assignment of pins to creating a save buffer to save the data collected. Basically, this .py acts as the front end for all of the other code. This may be the first thing to try to edit if something goes wrong. """ # Machine Learning stuff. from sklearn.tree import DecisionTreeClassifier from sklearn.externals import joblib from sklearn.metrics import classification_report, confusion_matrix # File manipulation, command line execution, etc. import sys # For the Automaton structure this code is designed around. from Automata.State import State # Raspberry Pi GPIO library. import RPi.GPIO as GPIO # For sleeping, delays, etc. import time # Component code of my own design. from HaqPi.Component.OutputComponent import OutputComponent from HaqPi.Component.MPU6050 import MPU6050 from HaqPi.Component.Button import Button from HaqPi.Component.LED import LED from HaqPi.Component.Buzzer import Buzzer # Helps save and write log files. from FileHelper.SaveFileHelper import SaveFileHelper from FileHelper.LoadFileHelper import LoadFileHelper # For math/matrix operations. import numpy as np # For doing multiple things at once. from multiprocessing import Process, Pipe # Just to make the command-line execution look pretty. from HaqPyTools import UI # Loading variables specified in InitSettings.py.. from InitSettings import InitSettings as settings # For audio-to-bluetooth purposes. import pyaudio import wave class Gaitmate: def __init__(self, gyroAddress, buzzerPin, hapticPin, buttonPin, laserPin, ledPin): self.gyroAddress = gyroAddress self.buzzerPin = buzzerPin self.hapticPin = hapticPin self.hapticPin2 = None if (settings.enableSecondHaptic): self.hapticPin2 = settings.secondaryHapticPin self.buttonPin = buttonPin self.laserPin = laserPin self.ledPin = ledPin self.state = State(State.StateType.PAUSED) self.gyro = MPU6050(self.gyroAddress) self.buzzer = Buzzer(self.buzzerPin) self.haptic = OutputComponent(self.hapticPin) self.haptic2 = None if (settings.enableSecondHaptic): self.haptic2 = OutputComponent(self.hapticPin2) self.button = Button(self.buttonPin) self.laser = OutputComponent(self.laserPin) self.led = LED(self.ledPin) self.metronomeDelay = ((float(60)/settings.numberOfSteps) - (settings.stepdownDelay)) if (self.metronomeDelay <= 0): print("\t**ERROR** Not a valid numberOfSteps defined in" + " InitSettings.py. Exiting..") sys.exit(0) self.clf = joblib.load( '/home/pi/gaitmate/pi/MachineLearn/dTreeExport.pkl') self.predictedResult = None self.prevPredictedResult = None # Component accessors. def buzzerAction(self): return self.buzzer def gyroAction(self): return self.gyro def hapticAction(self): return self.haptic def haptic2Action(self): return self.haptic2 def buttonAction(self): return self.button def laserAction(self): return self.laser def ledAction(self): return self.led def writerAction(self): return self.writer # # Assigns/Retrives input integer to the the pin of the corresponding part. # Important for successful state operation. # def getBuzzerPin(self): return self.buzzerPin def getHapticPin(self): return self.hapticPin def getHaptic2Pin(self): return self.hapticPin2 def getButtonPin(self): return self.buttonPin def getGyroAddress(self): return self.gyroAddress def getState(self): return self.state # Collects Data for a certain period of time at a certain frequency. # Returns true if the button is not pressed. Returns false if the button is # pressed. def collectData(self, duration, collectionFrequency, accuracy): if (collectionFrequency == 0): collectionFrequency = 1 # default to 1 collection per second if (duration == 0): return # Initializing write file to have the name of the local time and date. fileName = time.strftime( "/home/pi/gaitmate/pi/logs/%m-%d-%y_%H%M%S", time.localtime()) # print("Creating " + fileName + "..") self.writer = SaveFileHelper(fileName) timerEnd = time.time() + duration delay = 1.0/float(collectionFrequency) while (time.time() < timerEnd): self.writerAction().appendToBuffer( self.gyroAction().getAccel_X(accuracy), self.gyroAction().getAccel_Y(accuracy), self.gyroAction().getAccel_Z(accuracy)) # Code that stops script when button is pressed. if (self.buttonAction().isPressed()): self.ledAction().toggleOff() self.writerAction().dumpBuffer() return False time.sleep(delay) # print("Saving and creating a new filename..") self.writerAction().dumpBuffer() return True # # Test Code. Previously separate main() files, consolidated here. # def testBuzzer(self): print("Testing buzzer..") self.buzzerAction().metronome(self.metronomeDelay, 5, settings.stepdownDelay) print("\t.. done.\n") def testGyro(self): print("Testing Gyro..") timerEnd = time.time() + 5 while time.time() < timerEnd: print(self.gyroAction().acceleration_toString(4)) time.sleep(1) print("\t.. done.\n") def testHaptic(self): print("Testing haptics..") p1 = Process(target=self.hapticAction().metronome, args=(self.metronomeDelay, 5, settings.stepdownDelay)) p1.start() if (settings.enableSecondHaptic): p2 = Process(target=self.haptic2Action().metronome, args=(self.metronomeDelay, 5, settings.stepdownDelay)) p2.start() print("secondary haptic enabled. Joining processes..") p1.join() p2.join() print("\t.. done.\n") def testButton(self): print("Testing Button..") print("Will loop continuously. Press ctrl+c to exit.") try: while True: if (self.buttonAction().isPressed()): print("Button is pressed!") else: print("Button is not pressed.") time.sleep(0.2) except KeyboardInterrupt: print("\t.. done.\n") def testLaser(self): print("Testing Laser..") print("Will turn on/off continuously. Press ctrl+c to exit.") try: while True: if (settings.laserToggle): self.laserAction().step(0.2) else: print("\tLaserToggle is set to off in InitSettings.py. " + "Exiting..") break except KeyboardInterrupt: print("\t.. done.\n") def testLED(self): print("Testing LED..") print("Will pulse continuously. Press ctrl+c to exit.") try: self.ledAction().metronome(self.metronomeDelay, 5) except KeyboardInterrupt: print("\t.. done.\n") # # Main Execution loop of the Gaitmate. # def execute(self): while True: if (self.getState().isWalking()): self.doWalkingState() if (self.getState().isVibrating()): self.doVibratingState() if (self.getState().isRecovering()): self.doRecoveringState() if (self.getState().isPaused()): self.doPausedState() # # Walking State driver code # def doWalkingState(self): UI.box(["Entering Walking State"]) time.sleep(settings.walkingState_entryDelay) self.state.changeState(self.state.StateType.WALKING) self.ledAction().toggleOn() self.laserAction().toggleOff() recv_end, send_end = Pipe(False) isWalkOk = self.checkWalking(send_end) if (isWalkOk): # If walking okay, do walking state. self.doWalkingState() else: # if walking badly, do vibrating state. self.doVibratingState() # # Vibrating State driver code # def doVibratingState(self): UI.box(["Entering Vibrating State"]) time.sleep(settings.vibrationState_entryDelay) self.state.changeState(self.state.StateType.VIBRATING) self.ledAction().toggleOn() recv_end, send_end = Pipe(False) p1 = Process(target=self.hapticAction().metronome, args=(self.metronomeDelay, settings.vibrationState_Duration ) ) p1.start() p2 = Process(target=self.checkWalking, args=(send_end, settings.vibrationState_Duration ) ) p2.start() if (settings.enableSecondHaptic): p3 = Process(target=self.haptic2Action().metronome, args=(self.metronomeDelay, settings.vibrationState_Duration ) ) p3.start() p1.join() p2.join() p3.join() else: p1.join() p2.join() if (recv_end.recv()): # If walking okay, do walking state. self.doWalkingState() else: # If walking badly, do recovery state. self.doRecoveringState() # # Recovery State driver code # def doRecoveringState(self): UI.box(["Entering Recovering State"]) self.state.changeState(self.state.StateType.RECOVERING) self.ledAction().toggleOn() if (settings.laserToggle): self.laserAction().toggleOn() else: self.laserAction().toggleOff() recv_end, send_end = Pipe(False) p1 = Process(target=self.hapticAndBuzzerMetronome, args=(self.metronomeDelay, settings.stepdownDelay)) p1.start() while True: p2 = self.checkWalking(send_end, process=p1) if (recv_end.recv()): # If walking okay, do walking state. p1.terminate() self.hapticAction().toggleOff() if (settings.enableSecondHaptic): self.haptic2Action().toggleOff() self.buzzerAction().toggleOff() self.doWalkingState() else: # If walking badly, do recovery state. recv_end, send_end = Pipe(False) # Buzzer and haptic driver code as one singular process, to cut down on # multiprocessing time. def hapticAndBuzzerMetronome(self, delay, stepdownDelay=0.375): while True: GPIO.output(self.hapticPin, GPIO.HIGH) if (settings.enableSecondHaptic): GPIO.output(self.hapticPin2, GPIO.HIGH) GPIO.output(self.buzzerPin, GPIO.HIGH) time.sleep(stepdownDelay) GPIO.output(self.hapticPin, GPIO.LOW) if (settings.enableSecondHaptic): GPIO.output(self.hapticPin2, GPIO.LOW) GPIO.output(self.buzzerPin, GPIO.LOW) time.sleep(delay) # # Paused State driver code # def doPausedState(self): UI.box(["Entering Paused State"]) self.ledAction().toggleOff() self.laserAction().toggleOff() time.sleep(settings.pausedState_entryDelay) self.state.changeState(self.state.StateType.PAUSED) # button checking time reduced because data collection is discarded # here. Only important thing is button press boolean buttonNotPressed = self.collectData(settings.checkDuration, 4, 4) while True: time.sleep(0.5) if (not buttonNotPressed): self.doWalkingState() else: buttonNotPressed = self.collectData(settings.checkDuration, 4, 4) def checkWalking(self, send_end, duration=settings.checkDuration, process=None): print("\tChecking gait..") # Collect Data for 5 seconds. buttonNotPressed = self.collectData(duration, 4, 4) filename = self.writerAction().filename self.writerAction().closeWriter() # button not pressed returns true if the button wasn't pressed during # collection. if (buttonNotPressed): # Checking to see if patient is walking okay. loader = LoadFileHelper(filename) loader.parseData() X = [loader.getDataVariance_X(), loader.getDataVariance_Y(), loader.getDataVariance_Z()] self.prevPredictedResult = self.predictedResult self.predictedResult = self.clf.predict( np.array(X).reshape(1, -1))[0] if ((self.predictedResult == "standing" and self.prevPredictedResult == "standing") or (self.predictedResult == "shuffling" and self.prevPredictedResult == "shuffling")): send_end.send(False) return False else: send_end.send(True) return True # If button is pressed, change to paused state. else: if process is not None: process.terminate() self.hapticAction().toggleOff() if (settings.enableSecondHaptic): self.haptic2Action().toggleOff() self.buzzerAction().toggleOff() self.doPausedState()
Java
UTF-8
1,276
2.078125
2
[]
no_license
package com.bootdo.biz.domain; import java.io.Serializable; import java.util.Date; /** * 产品与品牌的关系; InnoDB free: 10240 kB * * @author tzy * @email tangzhiyu@vld-tech.com * @date 2019-04-05 14:14:36 */ public class BrandProductDO implements Serializable { private static final long serialVersionUID = 1L; // private Long id; // private Long pid; // private Long prodId; private String prodName; private String Image; private String xinghao1; public String getImage() { return Image; } public void setImage(String image) { Image = image; } public String getXinghao1() { return xinghao1; } public void setXinghao1(String xinghao1) { this.xinghao1 = xinghao1; } public String getProdName() { return prodName; } public void setProdName(String prodName) { this.prodName = prodName; } /** * 设置: */ public void setId(Long id) { this.id = id; } /** * 获取: */ public Long getId() { return id; } /** * 设置: */ public void setPid(Long pid) { this.pid = pid; } /** * 获取: */ public Long getPid() { return pid; } /** * 设置: */ public void setProdId(Long prodId) { this.prodId = prodId; } /** * 获取: */ public Long getProdId() { return prodId; } }
Java
UTF-8
1,356
3.015625
3
[]
no_license
package crl.action; import crl.actor.Actor; import crl.item.Item; import crl.player.Player; public class SwitchWeapons extends Action{ public int getCost() { return 25; } public String getID(){ return "SwitchWeapons"; } public void execute(){ Player aPlayer = (Player) performer; Item secondary = aPlayer.getSecondaryWeapon(); if (secondary == null){ /*aPlayer.getLevel().addMessage("You don't have a secondary weapon"); return;*/ Item primary = aPlayer.getWeapon(); aPlayer.setWeapon(null); aPlayer.getLevel().addMessage("You attack unarmed"); if (primary != null){ aPlayer.setSecondaryWeapon(primary); } return; } Item primary = aPlayer.getWeapon(); aPlayer.setWeapon(secondary); if (primary != null){ aPlayer.setSecondaryWeapon(primary); aPlayer.getLevel().addMessage("You switch your "+primary.getDescription()+" for your "+secondary.getDescription()); } else { aPlayer.setSecondaryWeapon(null); aPlayer.getLevel().addMessage("You equip your "+secondary.getDescription()); } } public boolean canPerform(Actor a){ /*Player aPlayer = (Player) a; Item secondary = aPlayer.getSecondaryWeapon(); if (secondary == null){ invalidationMessage = "You don't have a secondary weapon"; return false; }*/ return true; } }
C#
UTF-8
1,009
3.46875
3
[]
no_license
using System; namespace Task2 { class Program { static void Main(string[] args) { Console.WriteLine("Return minimum value, please type two numbers"); Console.Write("type number 1/2: "); int numberA; string userInput = Console.ReadLine(); numberA = int.Parse(userInput); Console.Write("type number 2/2: "); int numberB; userInput = Console.ReadLine(); numberB = int.Parse(userInput); Console.WriteLine($"Syotetyistä luvuista pienempi on {Minimum(numberA,numberB)}"); Console.ReadKey(); } static int Minimum(int numberX, int numberY) { // ehto ? true_value : false_value; return (numberX < numberY) ? numberX : numberY; /*if (numberX < numberY) return numberX; else return numberY; */ } } }
Java
UTF-8
487
3.203125
3
[]
no_license
public class Circle3 extends Shape3 { public Circle3(double x, double y, double radius) { super(x, y); this.radius = radius; } public double get_radius() { return radius; } public double get_area() { return Math.PI * radius * radius; } public double get_perimeter() { return 2 * Math.PI * radius; } public void scale(double sc_factor) { radius *= sc_factor; } // x and y are the coordinates of the center protected double radius; }
C++
UTF-8
783
3.34375
3
[]
no_license
// Time complexity o(nlogn) #include<iostream> #include<algorithm> void majority(int arr[], int n){ std::sort(arr, arr+n); if(n%2 == 0){ for(int i=0; i< n/2; i++){ if(arr[i] == arr[n/2+i]){ std::cout << arr[i] << '\n'; return; } } } else{ for(int i=0; i<= n/2; i++){ if(arr[i] == arr[n/2+i]){ std::cout << arr[i] << '\n'; return; } } } std::cout << "-1"<< '\n'; } int main(){ int *arr,t, n; std::cin >> t; while(t--){ std::cin >> n; arr = new int[n]; for(int i=0; i< n ; i++){ std::cin >> arr[i]; } majority(arr,n); delete[] arr; } }
Ruby
EUC-JP
951
3.4375
3
[]
no_license
#!/usr/local/bin/ruby -Ke # kconv饤֥KconvƤΤɤ߹ࡣ require 'kconv' # Ruby 1.8Kconv.guess֤Τǥܥ֤᥽åɤ򼫺롣 class String def guess_encoding case Kconv.guess(self) when Kconv::ASCII then :ASCII when Kconv::BINARY then :BINARY when Kconv::EUC then :EUC when Kconv::JIS then :JIS when Kconv::SJIS then :SJIS when Kconv::UTF16 then :UTF16 when Kconv::UTF32 then :UTF32 when Kconv::UTF8 then :UTF8 when Kconv::UNKNOWN then :UNKNOWN else raise "unexpected input" end end end euc = "⥷ܥ֤Ƥۤ" sjis = NKF.nkf("-Es", euc) utf8 = NKF.nkf("-Ew", euc) # ܥ֤褦ˤʤä euc.guess_encoding # => :EUC sjis.guess_encoding # => :SJIS utf8.guess_encoding # => :UTF8 "ascii".guess_encoding # => :ASCII
Markdown
UTF-8
857
3.234375
3
[]
no_license
## New York City Taxi Trip Duration Prediction The purpose of this analysis is to accurately predict the duration of taxi trips in New York City. This work is for a [Kaggle competition](https://www.kaggle.com/c/nyc-taxi-trip-duration). ## How the problem is solved: * Developed a Machine Learning model to predict the trip duration of the rides using Linear Regression and Random Forest. * Eliminated the outliers, preprocessed the dataset and performed feature engineering and feature selection to improve our model. * Performed EDA to get some valuable insights, calculated the trip distance from longitude and latitude using Havershine Algorithm and Clustered the prime locations using Folium library of Python * Evaluated and trained all the models using 10 K-Fold cross validation and discovered Random Forest performs better with ~80% accuracy.
Java
UTF-8
658
2.140625
2
[]
no_license
package com.mis.persistence; import java.util.List; import com.mis.domain.BookstoreVO; import com.mis.domain.SearchCriteria; public interface BookstoreDAO { public void create(BookstoreVO vo) throws Exception; public BookstoreVO read(int bookstoreNum) throws Exception; public void update(BookstoreVO vo) throws Exception; public void delete(int bookstoreNum) throws Exception; // 페이징, 검색할 수 있는 list public List<BookstoreVO> listSearch(SearchCriteria cri) throws Exception; // 페이징, 검색 하기 위한 게시물 수 반환 public int listSearchCount(SearchCriteria cri) throws Exception; }
JavaScript
UTF-8
3,982
3.0625
3
[ "MIT" ]
permissive
const { threadedClass, ThreadedClassManager } = require('../dist') const testData = require('./testData.js') const { TestClass } = require('./testClass.js') const CLASS_PATH = './testClass.js' // This is the path to the js-file (not a ts-file!) that contains the class async function runTests () { var t = {} let totalSingle = 0 let totalThreaded = 0 let totalCount = 0 const sum = () => { totalSingle += t.org totalThreaded += t.thread totalCount++ } console.log('Thread mode: ' + ThreadedClassManager.getThreadMode()) console.log('Node version: ' + process.version) console.log('Simplest function calls:') printResultHeader() t = await simple(); printResult(t); sum(); t = await simple(); printResult(t); sum(); t = await simple(); printResult(t); sum(); console.log('Data flowing one way:') printResultHeader() t = await oneWay(testData.string); printResult(t); sum(); t = await oneWay(testData.number); printResult(t); sum(); t = await oneWay(testData.object); printResult(t); sum(); console.log('Data flowing in both directions:') printResultHeader() t = await twoWay(testData.string); printResult(t); sum(); t = await twoWay(testData.number); printResult(t); sum(); t = await twoWay(testData.object); printResult(t); sum(); const averageSingle = totalSingle / totalCount const averageThreaded = totalThreaded / totalCount console.log(`Average single-threaded time: ${averageSingle} ms / call`) console.log(`Average multi-threaded time: ${averageThreaded} ms / call`) const averageSingleBaseline = 0.0000685 // This is recorded on Johan's machine 2022-04-08 const averageThreadedBaseline = 0.0549 // This is recorded on Johan's machine 2022-04-08 const percentageSingle = Math.round((1 - (averageSingle / averageSingleBaseline)) * 100) const percentageThreaded = Math.round((1 - (averageThreaded / averageThreadedBaseline)) * 100) if (percentageSingle >= 0) console.log(`Single-threaded performance is ${percentageSingle}% faster than the baseline (${averageSingleBaseline})`) else console.log(`Single-threaded performance is ${Math.abs(percentageSingle)}% slower than the baseline (${averageSingleBaseline})`) if (percentageThreaded >= 0) console.log(`Multi-threaded performance is ${percentageThreaded}% faster than the baseline (${averageThreadedBaseline})`) else console.log(`Multi-threaded performance is ${Math.abs(percentageThreaded)}% slower than the baseline (${averageThreadedBaseline})`) // (Optional) Clean up & close all threads: await ThreadedClassManager.destroyAll() console.log('Done') process.exit(0) } function printResultHeader () { console.log(` Single-thread Multi-thread`) } function printResult (t) { console.log(` ${slice(t.org, 8)} ${slice(t.thread, 8)} ms / call`) } function slice (str, length) { return (str + '').slice(0, length) } function pad (str, length) { str = (str+'') return (' '.slice(0, length - str.length) + str) } async function simple () { return await prepareTest('simple') } async function oneWay (data) { return await prepareTest('oneWay', data) } async function twoWay (data) { return await prepareTest('twoWay', data) } async function prepareTest (fcnName, data) { let original = new TestClass() let threaded = await threadedClass(CLASS_PATH, 'TestClass', []) var orgFcn = original[fcnName] var threadFcn = threaded[fcnName] var t = { org: await runTest(() => { return orgFcn(data) }), thread: await runTest(() => { return threadFcn(data) }) } return t } async function runTest (fcn, checkIteration) { if (!checkIteration) checkIteration = 100 const minElapsedTime = 2000 var runCount = 0 var startTime = Date.now() var elapsedTime = 0 while (elapsedTime < minElapsedTime) { for (var i = 0; i < checkIteration; i++) { await fcn() } runCount += 100 elapsedTime = Date.now() - startTime } return elapsedTime / runCount } runTests() .catch(console.log)
Markdown
UTF-8
83
2.546875
3
[]
no_license
# Ecommerce-purchase-days-difference avg days differences between purchases - Ecom
Markdown
UTF-8
1,414
2.78125
3
[]
no_license
The project MscP3_Product_image_and_text_classificationn is a data scientist MSc student project. The objective is to make a classification of products from a market place with their images and text descriptions. - The input files are NOT present into the Git. It consists into 1050 images. They can be dowloaded at https://s3-eu-west-1.amazonaws.com/static.oc-static.com/prod/courses/files/Parcours_data_scientist/Projet+-+Textimage+DAS+V2/Dataset+projet+pre%CC%81traitement+textes+images.zip They have to be put in the folder input/images/ and you have to remove the read_me.txt file (present mostly to maintain the empty folder in github) - The code Market_place.ipynb takes this pictures and descriptions present in the flipkart_com-ecommerce_sample_1050.csv file to make a classification. - The temp folder will contains temporary files produced by the code. in function of options it could be really long (18hours) so I have made files with punctual results to read if they are present and to compute if they are not. - The python notebook is converted into HTML file Market_place.html available at : http://htmlpreview.github.io/?https://github.com/DavidJulienMillet/MscP3_Product_image_and_text_classification/blob/master/Market_place.html - The environment.yml contains the conda environment used. The other projects are described and available on my portfolio https://www.millet-david.com
C#
UTF-8
2,383
3.078125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OS3981 { class LRU { public string Name { get; set; } public int Value { get; set; } static int s = 3; public static List<LRU> Pages = new List<LRU>(s); public LRU(string name) { if (hasplace()) { Pages.Add(new LRU(name, 0)); AddAll(name); return; } if (Contain(name)) { return; } else { Kickout(name); } } LRU(string name, int v) { this.Value = v; Name = name; } bool Contain(string name) { foreach (LRU item in Pages) { if (item.Name==name) { item.Value = 0; AddAll(name); return true; } } return false; } void AddAll(string name) { foreach (LRU item in Pages) { if (item.Name != name) { item.Value++; } } } void Kickout(string name) { int max = -1; int index=0; for (int i = 0; i < Pages.Count; i++) { if (max<Pages[i].Value) { max = Pages[i].Value; index = i; } } Pages[index].Name = name; Pages[index].Value = 0; AddAll(name); } bool hasplace() { return (Pages.Count < s); } public static string GetPages() { string res=""; foreach (var item in Pages) { res += item.ToString()+"\n"; } res += ("------------------\n"); return res; } public override string ToString() { return Name+" ("+Value.ToString()+")"; } } }
PHP
UTF-8
1,297
2.90625
3
[ "MIT" ]
permissive
<?php /** * Class Iso88591. * * @author Raphael Horber * @version 01.08.2019 */ namespace Rhorber\ID3rw\Encoding; /** * Implementation of EncodingInterface for 'ISO-8859-1'. * * @author Raphael Horber * @version 01.08.2019 */ class Iso88591 implements EncodingInterface { /** * Returns the encoding's code (0x00). * * @return string Code byte. * @access public * @author Raphael Horber * @version 01.08.2019 */ public function getCode(): string { return "\x00"; } /** * Returns the encoding's name ('ISO-8859-1'). * * @return string Code byte. * @access public * @author Raphael Horber * @version 01.08.2019 */ public function getName(): string { return "ISO-8859-1"; } /** * Returns the encoding's delimiter (0x00). * * @return string Delimiter byte(s). * @access public * @author Raphael Horber * @version 01.08.2019 */ public function getDelimiter(): string { return "\x00"; } /** * Returns whether a BOM is used with this encoding or not. * * @return false * @access public * @author Raphael Horber * @version 01.08.2019 */ public function hasBom(): bool { return false; } }
JavaScript
UTF-8
3,573
2.53125
3
[]
no_license
import React from 'react'; import PropTypes from 'prop-types'; class MyAccountForm extends React.Component { constructor(props) { super(props); this.emptyState = { username: '', oldPassword: '', newPassword: '', oldRecoveryQuestion: '', oldRecoveryAnswer: '', newRecoveryQuestion: '', newRecoveryAnswer: '', }; this.state = this.emptyState; } handleChange(event) { event.preventDefault(); const { name, value } = event.target; this.setState({ [name]: value, }); } handleSubmit(event) { event.preventDefault(); console.log(this.state); this.setState(this.emptyState); } render() { const { token } = this.props; return ( <section className="create-form"> <form onSubmit={this.handleSubmit.bind(this)}> <li> <label htmlFor="username">Username</label> <input name="username" placeholder={token ? token[0].username : null} type="text" value={this.state.username} onChange={this.handleChange.bind(this)} /> </li> <li> <label htmlFor="oldPassword">Old Password</label> <input name="oldPassword" placeholder="&bull; &bull; &bull; &bull; &bull; &bull; &bull; &bull;" type="password" value={this.state.oldPassword} onChange={this.handleChange.bind(this)} /> </li> <li> <label htmlFor="newPassword">New Password</label> <input name="newPassword" placeholder="new password" type="password" value={this.state.newPassword} onChange={this.handleChange.bind(this)} /> </li> <li> <label htmlFor="oldRecoveryQuestion">Old Recovery Question</label> <input name="oldRecoveryQuestion" placeholder={token ? token[0].recoveryQuestion : null} type="text" value={this.state.oldRecoveryQuestion} onChange={this.handleChange.bind(this)} /> </li> <li> <label htmlFor="oldRecoveryAnswer">Old Recovery Answer</label> <input name="oldRecoveryAnswer" placeholder="&bull; &bull; &bull; &bull; &bull; &bull; &bull; &bull;" type="text" value={this.state.oldRecoveryAnswer} onChange={this.handleChange.bind(this)} /> </li> <li> <label htmlFor="newRecoveryQuestion">New Recovery Question</label> <input name="newRecoveryQuestion" placeholder="new recovery question" type="text" value={this.state.newRecoveryQuestion} onChange={this.handleChange.bind(this)} /> </li> <li> <label htmlFor="newRecoveryAnswer">New Recovery Answer</label> <input name="newRecoveryAnswer" placeholder="new recovery answer" type="password" value={this.state.newRecoveryAnswer} onChange={this.handleChange.bind(this)} /> </li> <button type="submit">Update Account Info</button> </form> </section> ); } } MyAccountForm.propTypes = { token: PropTypes.array, }; export default MyAccountForm;
Java
UTF-8
1,740
2.71875
3
[]
no_license
package com.chinaedustar.publish.label; import com.chinaedustar.publish.PublishContext; import com.chinaedustar.publish.itfc.LabelHandler; import com.chinaedustar.template.TemplateConstant; import com.chinaedustar.template.core.AbstractLabelElement; import com.chinaedustar.template.core.InternalProcessEnvironment; /** * 简单 LabelHandler 实现,其 getLabelHandler() 方法返回自己。 * 派生类必须自己实现 handleLabel 方法。 * @author liujunxing * */ abstract class AbstractSimpleLabelHandler implements Cloneable, LabelHandler, TemplateConstant { /* * (non-Javadoc) * @see com.chinaedustar.publish.itfc.LabelHandler#getLabelHandler(com.chinaedustar.publish.PublishContext, com.chinaedustar.template.core.InternalProcessEnvironment, com.chinaedustar.template.core.AbstractLabelElement) */ public LabelHandler getLabelHandler(PublishContext pub_ctxt, InternalProcessEnvironment env, AbstractLabelElement label) { return this; } /** * 格式化一个日期输出,从 label 中获取 format='' 属性。 * @param value * @param label * @return */ public static String formatDateValue(java.util.Date value, AbstractLabelElement label) { if (value == null) return ""; String format = label == null ? null : label.getAttributes().safeGetStringAttribute("format", null); if (format == null || format.length() == 0) format = "yyyy-MM-dd hh:mm:ss"; // 缺省格式。 try { java.text.SimpleDateFormat formater = new java.text.SimpleDateFormat(format); return formater.format(value); } catch (IllegalArgumentException ex) { @SuppressWarnings("deprecation") String result = value.toLocaleString(); return result; } } }
C++
UTF-8
1,464
2.734375
3
[]
no_license
//UVa Problem-10089(Repackaging) //Accepted //Running time: 0.060 sec #include<iostream> using namespace std; const long long maxn=1001; bool repackage(long long pkgs[][3],long long npkgs){ for(long long i=0;i<npkgs;++i){ pkgs[i][0]-=pkgs[i][2]; pkgs[i][1]-=pkgs[i][2]; } long long x1=pkgs[0][0],y1=pkgs[0][1],x2=pkgs[0][0],y2=pkgs[0][1]; for(long long i=1;i<npkgs;++i){ long long x=pkgs[i][0],y=pkgs[i][1]; long long a1=y1*x,b1=x1*y,a2=y2*x,b2=x2*y; if (a1==b1) if(x1*x+y1*y<=0) return true; else continue; if(a2==b2) if(x2*x+y2*y<=0) return true; else continue; if(a1<b1){ x1=x; y1=y; } if(a2>b2){ x2=x; y2=y; } if(x1==x2 && y1==y2) return true; if(y1*x2==y2*x1) if(x1*x2+y1*y2<=0) return true; else continue; if(y1*x2<y2*x1) return true; } return false; } int main(){ long long pkgs[maxn][3]; for(long long npkgs;cin>>npkgs && npkgs!=0;){ for(long long i=0;i<npkgs;++i) cin>>pkgs[i][0]>>pkgs[i][1]>>pkgs[i][2]; if(repackage(pkgs,npkgs)) cout<<"Yes\n"; else cout<<"No\n"; } return 0; }
Java
UTF-8
768
3.453125
3
[]
no_license
package com.tcwgq.singletonpattern; /** * 单例模式: * 饿汉式:类一加载就创建对象 * 懒汉式:用的时候,才去创建对象 * * 面试题:单例模式的思想是什么?请写一个代码体现。 * * 开发:饿汉式(是不会出问题的单例模式) * 面试:懒汉式(可能会出问题的单例模式) * A:懒加载(延迟加载) * B:线程安全问题 * a:是否多线程环境 是 * b:是否有共享数据 是 * c:是否有多条语句操作共享数据 是 */ public class Singleton1 { private static Singleton1 s = null; private Singleton1() { super(); } public synchronized static Singleton1 getSingleton() { if (s == null) { s = new Singleton1(); } return s; } }
C#
UTF-8
1,630
2.546875
3
[ "MIT" ]
permissive
using CoreAnimation; using CoreGraphics; using UIKit; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; namespace Skor.Controls.iOS.Extensions { public static class BackgroundExtension { public static CAGradientLayer CreateBackgroundGradientLayer(float height, float width, float corner, UIColor startColor, UIColor endColor, UIColor centerColor, CGPoint[] direction = null) { var gradientLayer = new CAGradientLayer(); if (centerColor.ToColor() != Color.Transparent) { gradientLayer.Colors = new[] { startColor.CGColor,centerColor.CGColor, endColor.CGColor }; } else { gradientLayer.Colors = new[] { startColor.CGColor, endColor.CGColor }; } var d = direction ?? new CGPoint[] { new CGPoint(0, 0), new CGPoint(1, 0) }; gradientLayer.StartPoint = d[0]; gradientLayer.EndPoint = d[1]; gradientLayer.Frame = new CGRect(0, 0, width, height); gradientLayer.CornerRadius = corner; return gradientLayer; } public static CALayer CreateBackgroundImage(float height, float width, float corner, string source) { var cALayer = new CALayer(); var image = new UIImage(source).CGImage; cALayer.Frame = new CGRect(0, 0, width, height); cALayer.Contents = image; cALayer.CornerRadius = corner; cALayer.Opacity = 0.4f; cALayer.MasksToBounds = true; return cALayer; } } }
Shell
UTF-8
382
3.359375
3
[]
no_license
#!/bin/bash START="/etc/init.d/tomcat7 start" STOP="/etc/init.d/tomcat7 stop" LOGFILE="/var/lib/tomcat7/logs/catalina.out" SEARCHTERM="Server startup in" $STOP rm -rf /var/lib/tomcat7/work/* $START while read LINE; do if [[ $LINE =~ $SEARCHTERM ]]; then echo "Tomcat7 started OK!" break fi done < <(tail -f $LOGFILE) echo "Tomcat Restart Complete"
JavaScript
UTF-8
369
2.5625
3
[ "MIT" ]
permissive
let http = require('http') // Para criar um servidor http.createServer(function(req, res){ res.end('Hello world') }).listen(8081) console.log('servidor rodando'); // http://localhost:8081/ // servidor aberto na porta 8081 // a cada alteração e nescessário fechar o servidor // e rodar novamente // ctrl + c -> para o servidor // no code runner ctrl + Alt + m
JavaScript
UTF-8
644
2.875
3
[]
no_license
const fs = require('fs') const dir = process.argv[2] console.log(dir) console.log(process.argv[3]) fs.readdir(dir, (err, files) => { if (err) console.log(err); else { files.filter(file => { (file.includes('.md')) && console.log(file) }) } }) // const fs = require('fs') // const path = require('path') // const folder = process.argv[2] // const ext = '.' + process.argv[3] // fs.readdir(folder, function (err, files) { // if (err) return console.error(err) // files.forEach(function (file) { // if (path.extname(file) === ext) { // console.log(file) // } // }) // })
PHP
UTF-8
1,648
2.71875
3
[ "MIT" ]
permissive
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class UpdateInstitutionPost extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'id'=>'required|integer', 'rut'=>'required|max:20', 'institution_name'=>'required|max:100', 'reason_social'=>'required|max:150', 'address'=>'required|max:200', ]; } public function messages(){ return [ 'id.required'=>'El campo id es requerido', 'id.integer'=>'El campo id es invalido', 'rut.required'=>'El campo rut de la institución es requerido', 'rut.max'=>'El campo rut solo acepta un maximo de 20 caracteres', 'institution_name.required'=>'El campo nombre de la institución es requerido', 'institution_name.max'=>'El campo nombre de la institución solo acepta un maximo de 100 caracteres', 'reason_social.required'=>'El campo razón social de la institución es requerido', 'reason_social.max'=>'El campo razón social de la institución solo acepta un maximo de 150 caracteres', 'address.required'=>'El campo dirección de la institución es requerido', 'address.max'=>'El campo dirección de la institución solo acepta un maximo de 200 caracteres', ]; } }
C++
UTF-8
291
2.765625
3
[]
no_license
void setup() { // put your setup code here, to run once: Serial.begin(115200); } void loop() { // put your main code here, to run repeatedly: char *words[] = {"dash", "dot"}; Serial.println(words[0]); if (words[0]=="dash"){ Serial.println("OMG"); } Serial.println(sizeof(words)); }
PHP
UTF-8
4,482
2.6875
3
[]
no_license
<?php /** * Uploader Online Tests * * @version $Id: Uploader.php 537 2008-12-09 23:32:59Z edwardotis $ * @copyright 2005 */ require_once 'PHPUnit/Framework/TestCase.php'; require_once 'Phlickr/Tests/constants.inc'; require_once 'Phlickr/Uploader.php'; require_once 'Phlickr/AuthedUser.php'; // to verify that photo count increments require_once 'Phlickr/AuthedPhoto.php'; // to verify that photos exist class Phlickr_Tests_Online_Uploader extends PHPUnit_Framework_TestCase { var $api; var $uploader; function setUp() { $this->api = new Phlickr_Api(TESTING_API_KEY, TESTING_API_SECRET, TESTING_API_TOKEN); $this->uploader = new Phlickr_Uploader($this->api); } function tearDown() { unset($this->uploader); unset($this->api); } function testUpload_BadLoginThrows() { $this->api->setAuthToken('BADTOKEN'); try { $this->uploader->Upload(TESTING_FILE_NAME_JPG); } catch (Phlickr_Exception $ex) { return; } catch (Exception $ex) { $this->fail('threw the wrong type ('.get_class($ex).') of exception.'); } $this->fail('an exception should have been thrown'); } function testUpload_WithoutMeta() { $user = new Phlickr_User($this->api, $this->api->getUserId()); $oldPhotoCount = $user->getPhotoCount(); // upload it $result = $this->uploader->Upload(TESTING_FILE_NAME_JPG); // ensure the photo count increases $user->refresh(); $this->assertEquals($oldPhotoCount + 1, $user->getPhotoCount(), 'Photocount should have increased.'); // verify the returned id $this->assertType('string', $result, 'Returned the wrong type.'); $photo = new Phlickr_Photo($this->api, $result); $this->assertNotNull($photo, "Couldn't load a photo from the result id."); $this->assertEquals('small_sample', $photo->getTitle()); $this->assertEquals('', $photo->getDescription()); $this->assertEquals(array(), $photo->getTags()); $this->assertTrue($photo->isForPublic()); $this->assertTrue($photo->isForFriends()); $this->assertTrue($photo->isForFamily()); } function testUpload_WithMeta() { $user = new Phlickr_User($this->api, $this->api->getUserId()); $oldPhotoCount = $user->getPhotoCount(); $this->uploader->setPerms(true, false, false); // upload it $result = $this->uploader->Upload(TESTING_FILE_NAME_JPG, 'testing title', 'a description', 'atag btag'); // ensure the photo count increases $user->refresh(); $this->assertEquals($oldPhotoCount + 1, $user->getPhotoCount(), 'Photocount should have increased.'); // verify the returned id $this->assertType('string', $result, 'Returned the wrong type.'); $photo = new Phlickr_Photo($this->api, $result); $this->assertNotNull($photo, "Couldn't load a photo from the result id."); $this->assertEquals('testing title', $photo->getTitle()); $this->assertEquals('a description', $photo->getDescription()); $this->assertEquals(array('atag', 'btag'), $photo->getTags()); $this->assertTrue($photo->isForPublic()); $this->assertFalse($photo->isForFriends()); $this->assertFalse($photo->isForFamily()); } function testUpload_WithClassTags() { $this->uploader->setTags(array('classtag', 'barf')); // upload it $result = $this->uploader->Upload(TESTING_FILE_NAME_JPG, 'testing title', 'a description', 'atag btag'); $this->assertType('string', $result, 'Returned the wrong type.'); $photo = new Phlickr_Photo($this->api, $result); $this->assertEquals(array('classtag', 'barf', 'atag', 'btag'), $photo->getTags()); } function testUpload_WithClassPermissions() { $this->uploader->setPerms(false, false, false); // upload it $result = $this->uploader->Upload(TESTING_FILE_NAME_JPG, 'testing title', 'a description', 'atag btag'); // verify the returned id $this->assertType('string', $result, 'Returned the wrong type.'); $photo = new Phlickr_Photo($this->api, $result); $this->assertFalse($photo->isForPublic()); $this->assertFalse($photo->isForFriends()); $this->assertFalse($photo->isForFamily()); } }
Java
UTF-8
1,235
2.546875
3
[]
no_license
package con.juancarlos.dao.Equipo; import com.j256.ormlite.dao.Dao; import com.j256.ormlite.dao.DaoManager; import con.juancarlos.db.DBConnectionORM; import con.juancarlos.entities.Equipo; import java.sql.SQLException; import java.util.List; public class DAOEquipoORM implements DAOEquipo{ Dao<Equipo, String> daorecetasORM; public DAOEquipoORM() throws SQLException { this.daorecetasORM = DaoManager.createDao( DBConnectionORM.getInstance(), Equipo.class ); DaoManager.registerDao( DBConnectionORM.getInstance(), daorecetasORM); } @Override public Equipo add(Equipo equipo) { try { daorecetasORM.create(equipo); }catch (SQLException throwables){ throwables.printStackTrace(); } return equipo; } @Override public List<Equipo> getall() { try { return daorecetasORM.queryForAll(); } catch (SQLException throwables) { return null; } } @Override public void clear() { try { daorecetasORM.delete(getall()); }catch (SQLException throwables) { } } }
JavaScript
UTF-8
1,052
2.6875
3
[]
no_license
const fs = require('fs') const passagersCsv = fs.readFileSync('NombrePassagersTransportes.csv', 'utf-8') const kmsCsv = fs.readFileSync('NombreKMParcourus.csv', 'utf-8') const removeSemiColons = d => Array.from(d).filter(letter => letter !== ';').join('') const fixLine = line => line.trim().split(',') .map(removeSemiColons) .map(d => isNaN(Number(d)) ? "-" : Number(d)) const [ kmHead, ...kmLines] = kmsCsv.split('\n').map(fixLine) const [ pHead, ...pLines ] = passagersCsv.split('\n') .map(line => line.split(',').map(d => isNaN(Number(d)) ? "-" : Number(d))) const ajouterCles = prefix => d => ({ annee: d[0], [`${prefix}_train`]: d[1], [`${prefix}_tpr`]: d[2], [`${prefix}_bateau`]: d[3], }) const passagers = pLines.map(ajouterCles('passagers')) const km = kmLines.map(ajouterCles('km')) const chercherValeursKm = annee => km.find(d => d.annee === annee) const resultat = passagers.map(d => ({ ...d, ...chercherValeursKm(d.annee) })) console.log( JSON.stringify(resultat, null, 2) ) //isNaN(Number(d)) ? 0 : Number(d)
Python
UTF-8
797
4.0625
4
[]
no_license
#python 3 #Cleiton Piccini #Algoritmo do metódo de Newton para encontrar raizes de funções. import math # Função def funcao (x): #x = (x / (math.e**(10*x))) - (1 / (math.e ** 5)) x = math.cos(50 * x + 10) - math.sin(50 * x - 10) return x # Derivada da Função def derivada (x): #x = (math.e**(-10*x)) * (1 - 10 * x) x = -50 * (math.sin(50 * x + 10) + math.cos(50 * x - 10)) return x # Metodo de Newton def newton(x, i, erro): # i = i + 1 x_funcao = funcao (x) x_derivada = derivada (x) x_novo = x - (x_funcao / x_derivada) # if abs((x_novo - x) / x_novo) < erro or x_derivada == 0.0: print("Iterações = ",i) return x_novo else : return newton (x_novo, i, erro) # '''_Main_''' i = 0 x = -0.5 erro = 0.0000000001 x = newton (x, i, erro) print("Raiz = ",x)
Python
UTF-8
1,105
3.453125
3
[]
no_license
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: """Track replacement with HashMap on both directions. """ p, q = {}, {} for x, y in zip(s, t): if (x in p) and (y in q): if not (p[x] == y and q[y] == x): return False elif (x in p) ^ (y in q): return False else: p[x] = y q[y] = x return True class Solution: def isIsomorphic(self, s: str, t: str) -> bool: return len(set(zip(s, t))) == len(set(s)) == len(set(t)) class Solution: def isIsomorphic(self, s: str, t: str) -> bool: return [s.find(i) for i in s] == [t.find(j) for j in t] class Solution: def isIsomorphic(self, s: str, t: str) -> bool: return list(map(s.find, s)) == list(map(t.find, t)) if __name__ == '__main__': solver = Solution() cases = [ ("", ""), ("a", "a"), ("a", "b"), ("bar", "foo"), ("foo", "bar"), ("add", "egg"), ("paper", "title"), ] rslts = [solver.isIsomorphic(s, t) for s, t in cases] for cs, rs in zip(cases, rslts): print(f"case: {cs} | solution: {rs}")
PHP
UTF-8
1,006
2.703125
3
[]
no_license
<?php namespace Pingu\Core\Traits\Models; use Illuminate\Support\Str; trait HasRouteSlug { /** * Boot trait */ public static function bootHasRouteSlug() { static::registered(function ($model) { if ($model->shouldRegisterRouteSlug()) { \RouteSlugs::registerSlugFromObject($model); } }); } /** * Should this class register its route slug. * This can be turned off if the model gets his route slug from a parent class. * * @return bool */ public function shouldRegisterRouteSlug(): bool { return true; } /** * Route slug (plural) * * @return string */ public static function routeSlugs(): string { return str_plural(static::routeSlug()); } /** * Route slug (singular) * * @return string */ public static function routeSlug(): string { return class_machine_name(static::class); } }
PHP
UTF-8
368
2.859375
3
[]
no_license
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class CircleController extends Controller { public function show(int $radius) { return [ "type" => "circle", "radius" => $radius, "surface" => ($radius * $radius) * 3.14, #12.56, "circumference" => 2 * 3.14 * $radius, ]; } }
Java
UTF-8
818
1.984375
2
[]
no_license
package zone.wim.item.tokens; import zone.wim.coding.DecodeAdapter; import zone.wim.coding.EncodeAdapter; import zone.wim.coding.SelfCoding; import zone.wim.coding.temporal.TemporalMark; import zone.wim.item.Item; import java.util.List; import java.util.Stack; enum SupportedCodecs { ISO_8601, TEMPORENC; } public class TemporalToken extends TemporalMark { public static char TEMPORAL_CHAR = Item.TIMESTAMP_CHAR; public static TemporalToken decode(DecodeAdapter adapter) { Stack<Object> preCoded = adapter.preCoded(); while (!preCoded.isEmpty()) { String format = (String)preCoded.pop(); // if (format == Item.TIMESTAMP_CHAR) { // // } } } @Override public void encode(EncodeAdapter adapter) { } }
JavaScript
UTF-8
682
2.734375
3
[]
no_license
import React from 'react'; export default class Sum extends React.Component { constructor(props){ super(props); console.log(props); console.log('constructor'); } componentWillReceiveProps(nextProps){ console.log(this.props); console.log(nextProps); } shouldComponentUpdate(nextProps){ return false; return (nextProps.x + nextProps.y >= 1,5); } componentWillMount(){ console.log('cwm'); } componentDidMount(){ console.log('cdm'); } render(){ console.log('render'); const {x, y} = this.props; //const x = this.props.x; //const y = this.props.y; return ( <p>{Number(x)+Number(y)}</p> ) } }
Python
UTF-8
2,672
4
4
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
# lex.py # Python Lisp LEXer from string import whitespace def lex(characters): "Convert a string of characters into a list of tokens." tokens = [] current_token = "" pos = 0 while pos < len(characters): # returns immediately if there are 0 tokens # By default, just add the current character to current_token # Finding any other single-char token, like whitespace or a (, # commits the contents of current_token to a token and # begins anew. # This is most of the state in the lexer, along with position. # Whitespace - discard, but commit current_token if characters[pos] in whitespace: # Discard all whitespace if len(current_token) > 0: tokens.append(current_token) current_token = "" # Quote token - commit current_token and commit a '( elif characters[pos] == "'": # Quote if len(current_token) > 0: tokens.append(current_token) current_token = "" if characters[pos + 1] == '(': pos += 1 tokens.append("'(") else: current_token += "'" # Open paren token - commit current_token and commit a ( elif characters[pos] == "(": # Open paren if len(current_token) > 0: tokens.append(current_token) current_token = "" tokens.append("(") # Close paren token - commit current_token and commit a ) elif characters[pos] == ")": # Close paren if len(current_token) > 0: tokens.append(current_token) current_token = "" tokens.append(")") # Strings: doubles quotes make string literals elif characters[pos] == '"': # Commit current_token if len(current_token) > 0: tokens.append(current_token) current_token = "" # Do a string literal initial_pos = pos # +1 here so that the token gets the quote closing_pos = characters.find('"', pos+1) + 1 if closing_pos > pos: # A complete string was found. It is a single token. tokens.append(characters[pos:closing_pos]) pos = closing_pos - 1 else: # No complete string was found. raise SyntaxError("Quote mismatch in string literal.") else: # Something else current_token += characters[pos] pos += 1 return tokens
Java
UTF-8
8,024
2.203125
2
[]
no_license
package com.saiwei.recorder.logic; import java.io.File; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Set; import android.app.Application; import android.media.CamcorderProfile; import android.util.Log; import com.autonavi.xmgd.utility.FileComparator; import com.autonavi.xmgd.utility.Logutil; import com.autonavi.xmgd.utility.Storage; import com.autonavi.xmgd.utility.Util; import com.saiwei.recorder.CarRecorder; import com.saiwei.recorder.MyMediaRecorder; import com.saiwei.recorder.R; import com.saiwei.recorder.application.MyApplication; import com.saiwei.recorder.application.Recorder_Global; /** * 单件, 处理业务逻辑 * * @author wei.chen * */ public class RecorderLogic { private static final String TAG = "chenwei.RecorderLogic"; private static boolean DEBUG = true; private static final int QUALITY_NORMAL = 0; //正常 private static final int QUALITY_FINE = 1; //精细 private static final int QUALITY_HYPERFINE = 2; //超精细 private Application mApplication; private static RecorderLogic instance = null; private MyMediaRecorder mMediaRecorder; public static RecorderLogic getInstance(Application application) { if (instance == null) { instance = new RecorderLogic(application); } return instance; } /** * 构造函数 * @param application */ private RecorderLogic(Application application){ Logutil.i(TAG, "RecorderLogic() 构造函数"); if(application == null){ return; } mApplication = application; deleteTempFile(); } /** * 单件的释放 */ public static void freeInstance(){ if(instance!=null){ instance.onDestroy(); instance= null; } } /** * 单件销毁 */ private void onDestroy(){ if(instance != null){ checkVideoFiles(); instance = null; } } /** * 删除头像的缓存文件 */ private void deleteTempFile(){ File dir = new File(Storage.DEFAULT_DIRECTORY); if(!dir.exists()){ return; } File[] files = dir.listFiles(); if(files!=null){ for(int i=0;i<files.length;i++){ if(files[i].getName().startsWith("navi_")){ files[i].delete(); } } } } private ArrayList<File> mListFiles = null; /** * 检查DCIM/Camera/Navi里总共有几个视频文件, 只保留定义的保存个数,把多余的删除了 */ public void checkVideoFiles(){ new Thread(new Runnable() { @Override public void run() { File dir = new File(Recorder_Global.mCurFilePath); if (!dir.exists()) { return; } File[] files = dir.listFiles(); mListFiles = new ArrayList<File>(Arrays.asList(files)); //按时间排序 Collections.sort(mListFiles, new FileComparator()); if(mListFiles.size() > Recorder_Global.SAVE_FILE_NUM){ for(int i=Recorder_Global.SAVE_FILE_NUM;i<mListFiles.size();i++){ File f = mListFiles.get(i); if(!f.exists()){ continue; } f.delete(); } } } }).start(); } /** * 获取录像周期 * @return */ public int getVideoRate(){ int value = MyApplication.cache_recoder_video .getInt(Recorder_Global.SHARE_PREFERENCE_VIDEO_RECORD_RATE, Recorder_Global.DEFAULT_VIDEO_RECORD_RATE); String[] strs = mApplication.getResources().getStringArray(R.array.video_record_rate); String str = strs[value]; int i = Integer.parseInt(str); Logutil.i(TAG, "录像周期 i="+i); int lVideoRate = i * 60 * 1000; if(CarRecorder.DEBUG){ return (int)(0.5 * 60 * 1000); } return lVideoRate; } /** * 获取视频品质 [包括: 视频分辨率 和 录制质量] * @return */ public CamcorderProfile getVideoProfile(int[] screensize){ int tempQualityValue ,tempQualityId = -1; //录制质量 tempQualityValue = MyApplication.cache_recoder_video .getInt(Recorder_Global.SHARE_PREFERENCE_VIDEO_QUALITY, Recorder_Global.DEFAULT_VIDEO_QUALITY); CamcorderProfile profile = null; //quality_id tempQualityId = MyApplication.cache_recoder_video .getInt(Recorder_Global.SHARE_PREFERENCE_VIDEO_QUALITY_ID, Recorder_Global.DEFAULT_VIDEO_QUALITY_ID); Log.i(TAG, "tempQualityId="+tempQualityId); if(tempQualityId == -1){ tempQualityId = getAdaptScreen(screensize); MyApplication.cache_recoder_video.edit() .putInt(Recorder_Global.SHARE_PREFERENCE_VIDEO_QUALITY_ID, tempQualityId).commit(); } try { profile = CamcorderProfile.get(tempQualityId); } catch (Exception e) { profile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH); } // Log.i(TAG, "screensize[] = "+screensize[0]+","+screensize[1]); // Log.i(TAG, "profile.videoFrameHeight="+profile.videoFrameHeight+","+profile.videoFrameWidth); editProfile(profile, tempQualityValue); return profile; } /** * 获取视频文件具体路径 * @return */ public String getVideoFilePathDetail(){ String filepath = MyApplication.cache_recoder_video .getString(Recorder_Global.SHARE_PREFERENCE_VIDEO_FILE_PATH_DETAIL, Recorder_Global.DEFAULT_VIDEO_FILE_PATH_DETAIL); //创建文件夹 Util.createFolder(filepath); if(Util.isFileExist(filepath)){ return filepath; } else { MyApplication.setDefaultFilePath(MyApplication.cache_recoder_video); return Recorder_Global.DEFAULT_VIDEO_FILE_PATH_DETAIL; } } private HashMap<Float, Integer> profiles = new HashMap<Float, Integer>(); /** * 获取自适应屏幕的 QUALITY id * @param screensize * @return */ private int getAdaptScreen(int[] screensize){ if(screensize == null){ return CamcorderProfile.QUALITY_HIGH; } profiles.clear(); CamcorderProfile profile = null; String profile_frame = ""; float temp = 0; for(int i=CamcorderProfile.QUALITY_LOW;i<CamcorderProfile.QUALITY_QVGA;i++){ try { profile = CamcorderProfile.get(i); profile_frame = profile.videoFrameHeight+","+profile.videoFrameWidth; // Log.i(TAG, "i="+i+" ,profile_frame="+profile_frame); // Log.i(TAG, "profile.videoBitRate="+profile.videoBitRate); temp = profile.videoFrameHeight*profile.videoFrameWidth; if(temp>(screensize[0]*screensize[1])){ continue; } profiles.put(temp,i); } catch (Exception e) { } } Set<Float> keyset = profiles.keySet(); Object[] ff = keyset.toArray(); //默认从小到大 Arrays.sort(ff); Float tt= (Float) ff[ff.length-1]; int quality = profiles.get(tt); // Log.i(TAG, "quality="+quality); return quality; } /** * 调整视频码率 * @param profile * @param factor */ private void changeVideoBitRate(CamcorderProfile profile,double factor){ int temp = profile.videoBitRate; profile.videoBitRate = (int) (temp*factor); } private void editProfile(CamcorderProfile profile ,int videoQuality){ if(profile == null){ return ; } switch (videoQuality) { case QUALITY_NORMAL: //正常 changeVideoBitRate(profile,0.5); break; case QUALITY_FINE: //精细 changeVideoBitRate(profile,0.75); break; case QUALITY_HYPERFINE: //超精细 changeVideoBitRate(profile,1); break; default: break; } } /** * 创建文件名 * @param dateTaken * @return */ public String createFileName(long dateTaken) { Date date = new Date(dateTaken); SimpleDateFormat dateFormat = new SimpleDateFormat( mApplication.getString(R.string.video_file_name_format)); return dateFormat.format(date); } }
SQL
UTF-8
4,553
3.15625
3
[]
no_license
-- MySQL dump 10.13 Distrib 5.1.30, for apple-darwin9.5.0 (i386) -- -- Host: localhost Database: timelis -- ------------------------------------------------------ -- Server version 5.1.30 /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `activity` -- DROP TABLE IF EXISTS `activity`; SET @saved_cs_client = @@character_set_client; SET character_set_client = utf8; CREATE TABLE `activity` ( `id` int(11) NOT NULL AUTO_INCREMENT, `masterID` int(11) DEFAULT '0', `project_id` int(11) NOT NULL, `name` varchar(50) DEFAULT NULL, `enabled` tinyint(4) DEFAULT '0', PRIMARY KEY (`id`), KEY `ProjectID` (`project_id`), CONSTRAINT `fk_activity_project` FOREIGN KEY (`project_id`) REFERENCES `project` (`ID`) ) ENGINE=InnoDB AUTO_INCREMENT=41 DEFAULT CHARSET=utf8; SET character_set_client = @saved_cs_client; -- -- Table structure for table `day` -- DROP TABLE IF EXISTS `day`; SET @saved_cs_client = @@character_set_client; SET character_set_client = utf8; CREATE TABLE `day` ( `id` int(11) NOT NULL AUTO_INCREMENT, `startTime` datetime DEFAULT NULL, `endTime` datetime DEFAULT NULL, `reportingHours` int(11) DEFAULT '-1', `modified` tinyint(4) DEFAULT '-1', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1068 DEFAULT CHARSET=utf8; SET character_set_client = @saved_cs_client; -- -- Table structure for table `event` -- DROP TABLE IF EXISTS `event`; SET @saved_cs_client = @@character_set_client; SET character_set_client = utf8; CREATE TABLE `event` ( `id` int(11) NOT NULL AUTO_INCREMENT, `time` datetime DEFAULT NULL, `trigger` datetime DEFAULT NULL, `text` text, `fired` tinyint(4) DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; SET character_set_client = @saved_cs_client; -- -- Table structure for table `pause` -- DROP TABLE IF EXISTS `pause`; SET @saved_cs_client = @@character_set_client; SET character_set_client = utf8; CREATE TABLE `pause` ( `id` int(11) NOT NULL AUTO_INCREMENT, `day_id` int(11) NOT NULL, `begin` datetime DEFAULT NULL, `end` datetime DEFAULT NULL, PRIMARY KEY (`id`), KEY `fk_pause_day` (`day_id`), CONSTRAINT `fk_pause_day` FOREIGN KEY (`day_id`) REFERENCES `day` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=981 DEFAULT CHARSET=utf8; SET character_set_client = @saved_cs_client; -- -- Table structure for table `project` -- DROP TABLE IF EXISTS `project`; SET @saved_cs_client = @@character_set_client; SET character_set_client = utf8; CREATE TABLE `project` ( `id` int(11) NOT NULL AUTO_INCREMENT, `masterID` int(11) DEFAULT '0', `name` varchar(50) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8; SET character_set_client = @saved_cs_client; -- -- Table structure for table `task` -- DROP TABLE IF EXISTS `task`; SET @saved_cs_client = @@character_set_client; SET character_set_client = utf8; CREATE TABLE `task` ( `id` int(11) NOT NULL AUTO_INCREMENT, `day_id` int(11) NOT NULL, `activity_id` int(11) NOT NULL, `officialDescription` varchar(255) DEFAULT NULL, `privateDescription` varchar(255) DEFAULT NULL, `minutes` int(11) DEFAULT '0', PRIMARY KEY (`id`), KEY `fk_task_day` (`day_id`), KEY `fk_task_activity` (`activity_id`), CONSTRAINT `fk_task_day` FOREIGN KEY (`day_id`) REFERENCES `day` (`id`), CONSTRAINT `fk_task_activity` FOREIGN KEY (`activity_id`) REFERENCES `activity` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1321 DEFAULT CHARSET=utf8; SET character_set_client = @saved_cs_client; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2008-12-29 10:24:29
Rust
UTF-8
9,936
2.71875
3
[ "Apache-2.0", "MIT" ]
permissive
//! The radio capsule provides userspace applications with the ability //! to send and receive 802.15.4 packets // System call interface for sending and receiving 802.15.4 packets. // // Author: Philip Levis // Date: Jan 12 2017 // use core::cell::Cell; use kernel::{AppId, Driver, Callback, AppSlice, Shared}; use kernel::common::take_cell::{MapCell, TakeCell}; use kernel::hil::radio; use kernel::returncode::ReturnCode; struct App { tx_callback: Option<Callback>, rx_callback: Option<Callback>, cfg_callback: Option<Callback>, app_read: Option<AppSlice<Shared, u8>>, app_write: Option<AppSlice<Shared, u8>>, } pub struct RadioDriver<'a, R: radio::Radio + 'a> { radio: &'a R, busy: Cell<bool>, app: MapCell<App>, kernel_tx: TakeCell<'static, [u8]>, } impl<'a, R: radio::Radio> RadioDriver<'a, R> { pub fn new(radio: &'a R) -> RadioDriver<'a, R> { RadioDriver { radio: radio, busy: Cell::new(false), app: MapCell::empty(), kernel_tx: TakeCell::empty(), } } pub fn config_buffer(&mut self, tx_buf: &'static mut [u8]) { self.kernel_tx.replace(tx_buf); } } impl<'a, R: radio::Radio> Driver for RadioDriver<'a, R> { fn allow(&self, _appid: AppId, allow_num: usize, slice: AppSlice<Shared, u8>) -> ReturnCode { match allow_num { 0 => { let appc = match self.app.take() { None => { App { tx_callback: None, rx_callback: None, cfg_callback: None, app_read: Some(slice), app_write: None, } } Some(mut appc) => { appc.app_read = Some(slice); appc } }; self.app.replace(appc); ReturnCode::SUCCESS } 1 => { let appc = match self.app.take() { None => { App { tx_callback: None, rx_callback: None, cfg_callback: None, app_read: None, app_write: Some(slice), } } Some(mut appc) => { appc.app_write = Some(slice); appc } }; self.app.replace(appc); ReturnCode::SUCCESS } _ => ReturnCode::ENOSUPPORT, } } fn subscribe(&self, subscribe_num: usize, callback: Callback) -> ReturnCode { match subscribe_num { 0 /* transmit done*/ => { let appc = match self.app.take() { None => App { tx_callback: Some(callback), rx_callback: None, cfg_callback: None, app_read: None, app_write: None, }, Some(mut appc) => { appc.tx_callback = Some(callback); appc } }; self.app.replace(appc); ReturnCode::SUCCESS }, 1 /* receive */ => { let appc = match self.app.take() { None => App { tx_callback: None, rx_callback: Some(callback), cfg_callback: None, app_read: None, app_write: None, }, Some(mut appc) => { appc.rx_callback = Some(callback); appc } }; self.app.replace(appc); ReturnCode::SUCCESS }, 2 /* config */ => { let appc = match self.app.take() { None => App { tx_callback: None, rx_callback: None, cfg_callback: Some(callback), app_read: None, app_write: None, }, Some(mut appc) => { appc.cfg_callback = Some(callback); appc } }; self.app.replace(appc); ReturnCode::SUCCESS } _ => ReturnCode::ENOSUPPORT } } // 0: check if present // 1: set 16-bit address // 2: set PAN id // 3: set channel // 4: set tx power // 5: transmit packet fn command(&self, cmd_num: usize, arg1: usize, _: AppId) -> ReturnCode { match cmd_num { 0 /* check if present */ => ReturnCode::SUCCESS, 1 /* set 16-bit address */ => { self.radio.config_set_address(arg1 as u16); ReturnCode::SUCCESS }, 2 /* set PAN id */ => { self.radio.config_set_pan(arg1 as u16); ReturnCode::SUCCESS }, 3 /* set channel */ => { // not yet supported self.radio.config_set_channel(arg1 as u8) }, 4 /* set tx power */ => { // not yet supported let mut val = arg1 as i32; val = val - 128; // Library adds 128 to make unsigned self.radio.config_set_tx_power(val as i8) }, 5 /* tx packet */ => { // Don't transmit if we're busy, the radio is off, or // we don't have a buffer yet. if self.busy.get() { return ReturnCode::EBUSY; } else if !self.radio.is_on() { return ReturnCode::EOFF; } else if self.kernel_tx.is_none() { return ReturnCode::ENOMEM; } else if self.app.is_none() { return ReturnCode::ERESERVE; } // The argument packs the 16-bit destination address // and length in the 32-bit argument. Bits 0-15 are // the address and bits 16-23 are the length. let mut rval = ReturnCode::SUCCESS; self.app.map(|app| { let mut blen = 0; // If write buffer too small, return app.app_write.as_mut().map(|w| { blen = w.len(); }); let len: usize = (arg1 >> 16) & 0xff; let addr: u16 = (arg1 & 0xffff) as u16; if blen < len { rval = ReturnCode::ESIZE; return; } let offset = self.radio.payload_offset(false, false) as usize; // Copy the packet into the kernel buffer self.kernel_tx.map(|kbuf| { app.app_write.as_mut().map(|src| { for (i, c) in src.as_ref()[0..len].iter().enumerate() { kbuf[i + offset] = *c; } }); }); let transmit_len = len as u8 + self.radio.header_size(false, false); let kbuf = self.kernel_tx.take().unwrap(); rval = self.radio.transmit(addr, kbuf, transmit_len, false); if rval == ReturnCode::SUCCESS { self.busy.set(true); } }); rval }, 6 /* check if on */ => { if self.radio.is_on() { ReturnCode::SUCCESS } else { ReturnCode::EOFF } } 7 /* commit config */ => { self.radio.config_commit() } _ => ReturnCode::ENOSUPPORT, } } } impl<'a, R: radio::Radio> radio::TxClient for RadioDriver<'a, R> { fn send_done(&self, buf: &'static mut [u8], acked: bool, result: ReturnCode) { self.app.map(move |app| { self.kernel_tx.replace(buf); self.busy.set(false); app.tx_callback .take() .map(|mut cb| { cb.schedule(usize::from(result), acked as usize, 0); }); }); } } impl<'a, R: radio::Radio> radio::RxClient for RadioDriver<'a, R> { fn receive(&self, buf: &'static mut [u8], len: u8, result: ReturnCode) { if self.app.is_some() { self.app.map(move |app| { if app.app_read.is_some() { let offset = self.radio.payload_offset(false, false) as usize; let dest = app.app_read.as_mut().unwrap(); let d = &mut dest.as_mut(); for (i, c) in buf[offset..len as usize].iter().enumerate() { d[i] = *c; } app.rx_callback .take() .map(|mut cb| { cb.schedule(usize::from(result), 0, 0); }); } self.radio.set_receive_buffer(buf); }); } else { self.radio.set_receive_buffer(buf); } } } impl<'a, R: radio::Radio> radio::ConfigClient for RadioDriver<'a, R> { fn config_done(&self, result: ReturnCode) { self.app.map(move |app| { app.cfg_callback.take().map(|mut cb| { cb.schedule(usize::from(result), 0, 0); }); }); } }
C#
UTF-8
4,101
2.59375
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xunit; namespace LimeBean.Tests { public class CustomKeysTests : IDisposable { BeanApi _api; public CustomKeysTests() { _api = SQLitePortability.CreateApi(); } public void Dispose() { _api.Dispose(); } [Fact] public void Assigned_FrozenMode() { _api.Exec("create table foo (pk, prop)"); _api.Key("foo", "pk", false); var bean = _api.Dispense("foo"); bean["pk"] = "pk1"; bean["prop"] = "value1"; var key = _api.Store(bean); Assert.Equal("pk1", key); bean["prop"] = "value2"; Assert.Equal(key, _api.Store(bean)); bean = _api.Load("foo", key); Assert.Equal(key, bean["pk"]); Assert.Equal("value2", bean["prop"]); _api.Trash(bean); Assert.Equal(0, _api.Count("foo")); } [Fact] public void Assigned_Null() { _api.Key("foo", "any", false); Assert.Throws<InvalidOperationException>(delegate() { _api.Store(_api.Dispense("foo")); }); } [Fact] public void Assigned_Modification() { _api.EnterFluidMode(); _api.Key("foo", "pk", false); var bean = _api.Dispense("foo"); bean["pk"] = 1; _api.Store(bean); bean["pk"] = 2; _api.Store(bean); Assert.Equal(2, _api.Count("foo")); // moral: keys should be immutable } [Fact] public void AssignedCompound_FrozenMode() { _api.Exec("create table foo (pk1, pk2, pk3, prop)"); _api.Key("foo", "pk1", "pk2", "pk3"); var bean = _api.Dispense("foo"); bean["pk1"] = 1; bean["pk2"] = 2; bean["pk3"] = 3; bean["prop"] = "value1"; var key = _api.Store(bean) as CompoundKey; Assert.Equal("pk1=1, pk2=2, pk3=3", key.ToString()); bean["prop"] = "value2"; Assert.Equal("pk1=1, pk2=2, pk3=3", _api.Store(bean).ToString()); bean = _api.Load("foo", key); Assert.Equal(1L, bean["pk1"]); Assert.Equal(2L, bean["pk2"]); Assert.Equal(3L, bean["pk3"]); Assert.Equal("value2", bean["prop"]); _api.Trash(bean); Assert.Equal(0, _api.Count("foo")); } [Fact] public void CustomAutoIncrement_FluidMode() { _api.EnterFluidMode(); _api.Key("foo", "custom field"); _api.Store(_api.Dispense("foo")); Assert.Equal(1, _api.Count("foo", "where [custom field]=1")); } [Fact] public void AssignedCompound_FluidMode() { _api.EnterFluidMode(); _api.Key("foo", "a", "b"); var bean = _api.Dispense("foo"); bean["a"] = 1; bean["b"] = 2; _api.Store(bean); Assert.Equal(1, _api.Count("foo", "where a=1 and b=2")); } [Fact] public void AssignedCompound_Load() { _api.Exec("create table foo (k1, k2, v)"); _api.Exec("insert into foo values (1, 'a', 'ok')"); _api.Key("foo", "k1", "k2"); var bean = _api.Load("foo", 1, "a"); Assert.Equal("ok", bean["v"]); } [Fact] public void AssignedCompound_Malformed() { _api.EnterFluidMode(); _api.Key("foo", "k1", "k2"); var bean = _api.Dispense("foo"); bean["k1"] = 1; Assert.Throws<ArgumentNullException>(delegate() { _api.Store(bean); }); } [Fact] public void AssignedCompound_Empty() { Assert.Throws<ArgumentException>(delegate() { _api.Key("foo"); }); } } }
C
UTF-8
4,594
3.84375
4
[]
no_license
/* Manage orders for a waiter/waitress (including sorting). Lecture: IE-B1-SO1 (Software construction 1) Author: Marc Hensel */ #include <stdio.h> #include <stdlib.h> /* Enumerated types */ typedef enum { WATER, SOFT_DRINK, JUICE, BEER, COFFEE, TEA } drink; /* Structured types */ typedef struct orderItem { int table; drink drinkID; int quantity; struct orderItem *next; } orderItem; /* Function prototypes */ const char *drinkToString(const drink); void printOrders(const orderItem *, int); orderItem *addOrder(orderItem **, int, drink, int); void sortOrders(orderItem **); void removeOrders(orderItem **, int); orderItem *freeOrderList(orderItem *); /* Main function */ int main(void) { orderItem *orders = NULL; /* Fill list with some orders */ printf("Taking some orders ...\n"); addOrder(&orders, 6, TEA, 2); addOrder(&orders, 1, BEER, 3); addOrder(&orders, 1, SOFT_DRINK, 2); addOrder(&orders, 6, WATER, 3); addOrder(&orders, 1, WATER, 1); addOrder(&orders, 4, BEER, 4); addOrder(&orders, 1, COFFEE, 1); addOrder(&orders, 1, SOFT_DRINK, 1); printOrders(orders, 0); /* Sort orders by table and dring enumeration */ printf("Sorting orders ...\n"); sortOrders(&orders); printOrders(orders, 0); /* Clean-up memory */ orders = freeOrderList(orders); getchar(); return 0; } /* Get corresponding string for enumerated drink constants */ const char *drinkToString(const drink id) { switch (id) { case WATER: return "Water"; case SOFT_DRINK: return "Soft drink"; case JUICE: return "Juice"; case BEER: return "Beer"; case COFFEE: return "Coffee"; case TEA: return "Tea"; default: return "Unknown item"; } } /* Print orders for a specific table (or all orders for table = 0) to the console */ void printOrders(const orderItem *orders, int table) { printf("Table | Order\n"); printf("------+-----------------\n"); if (orders != NULL) { do { if ((table == 0) || (table == orders->table)) printf("%5d | %-10s (%dx)\n", orders->table, drinkToString(orders->drinkID), orders->quantity); } while ((orders = orders->next) != NULL); putchar('\n'); } } /* Add an order to a list of orders */ orderItem *addOrder(orderItem **listPtr, int table, drink menuID, int count) { orderItem *listNode = *listPtr; orderItem *newNode; // Allocate and initialize new node if ((newNode = (orderItem *)malloc(sizeof(orderItem))) != NULL) { newNode->table = table; newNode->drinkID = menuID; newNode->quantity = count; newNode->next = NULL; } // Append node to end of list if (listNode) { while (listNode->next) listNode = listNode->next; listNode->next = newNode; } else *listPtr = newNode; return newNode; } /* Sort orders by table and drink enumeration (simple approach) */ void sortOrders(orderItem **listPtr) { orderItem **ppNode = listPtr; // Address of pointer to current node (i.e., address of list pointer or address &priorNode->next) orderItem *node = *listPtr; // Current node: *ppNode orderItem *next; // Next node: node->next while (node && (next = node->next)) { int isSwapTable = node->table > next->table; int isSwapDrink = (node->table == next->table) && (node->drinkID > next->drinkID); // If nodes node and next in incorrect order if (isSwapTable || isSwapDrink) { // Swap nodes *ppNode = next; // Prior node points to next node (=> Skips current node) node->next = next->next; // Current node points to node after next node (=> Skips next node) next->next = node; // Next node points to current node (=> Invert order) // Start again from beginning of list ppNode = listPtr; // List in calling function points to first node node = *listPtr; } // Else move to next element else { ppNode = &node->next; node = node->next; } } } /* Remove all orders for a specific table from a list of orders */ void removeOrders(orderItem **listPtr, int table) { orderItem *prior, *node; // Remove matching nodes at beginning of list while (*listPtr && ((*listPtr)->table == table)) { node = *listPtr; *listPtr = (*listPtr)->next; free(node); } prior = *listPtr; // No matching table in this item // Run through rest of list while (prior && (node = prior->next)) { // Remove item, if table matches if (node->table == table) { prior->next = node->next; free(node); } prior = prior->next; } } /* Empty list of orders */ orderItem *freeOrderList(orderItem *orders) { orderItem *node = orders; while (node) { orderItem *freeNode = node; node = node->next; free(freeNode); } return NULL; }
Java
UTF-8
898
2.328125
2
[]
no_license
package org.kaleta.lolstats.ex.graph.line.data; import org.kaleta.lolstats.ex.entities.GameRecord; import java.util.List; /** * User: Stanislav Kaleta * Date: 12.6.2015 */ public interface LineDataModel { /** * * @param records */ public void initData(List<GameRecord> records); /** * * @param ker * @param im * @param func */ public void setUpModel(Object[] ker, Object[] im, Integer[][] func); /** * * @return */ public Integer getXSize(); /** * * @param i * @return */ public String getXMark(int i); /** * * @return */ public Integer getYSize(); /** * * @param i * @return */ public String getYMark(int i); /** * * @param x * @param var * @return */ public Integer getFunctionValue(int x, int var); }