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
PHP
UTF-8
1,024
4.15625
4
[]
no_license
<?php class Triangle extends Shape { private $side1 = 1.0; private $side2 = 1.0; private $side3 = 1.0; public function __construct($name, $side1, $side2, $side3) { parent::__construct($name); $this->side1 = $side1; $this->side2 = $side2; $this->side3 = $side3; } public function getPerimeter() { return $this->side1 + $this->side2 + $this->side3; } public function getArea() { return pow(0.5 * $this->getPerimeter() * (0.5 * $this->getPerimeter() - $this->side1) * (0.5 * $this->getPerimeter() - $this->side2) * (0.5 * $this->getPerimeter() - $this->side3), 0.5); } public function toString() { echo "side 1 is: ".$this->side1."<br>"; echo "side 2 is: ".$this->side2."<br>"; echo "side 3 is: ".$this->side3."<br>"; echo "Triangle has Perimeter is: " . $this->getPerimeter() . "<br>"; echo "Triangle has Area is: " . $this->getArea() . "<br>"; } }
Python
UTF-8
2,544
2.875
3
[ "MIT" ]
permissive
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Reddening functions used when simulating observations. """ from __future__ import (print_function, division) import six from six.moves import range import sys import os import warnings import math import numpy as np import warnings __all__ = ["_madau_t1", "_madau_tau1", "_madau_tau2", "madau_teff"] def _madau_t1(wave, z, l, coeff): """ Applies attenuation from the IGM at a particular set of wavelengths `wave` at redshift `z` from an line with wavelength `l` based on coefficients `coeff`. """ zlambda = l * (1 + z) # redshift wavelength tau = np.zeros_like(wave) sel = wave < zlambda # selecting all wavelengths < zlambda tau[sel] = coeff * (wave[sel] / l) ** 3.46 # optical depth contribution return tau def _madau_tau1(wave, z): """ Applies attenuation from the IGM from 912-1216 Angstroms at a particular set of wavelengths `wave` at redshift `z`. """ tau1 = np.zeros_like(wave) lines = [1216.0, 1026.0, 973.0, 950.0, 938.1, 931.0, 926.5, 923.4, 921.2, 919.6, 918.4] # n->1 transitions (n=2,3,...,12) coeffs = [0.0037, 0.00177, 0.00106, 0.000584, 0.00044, 0.00040, 0.00037, 0.00035, 0.00033, 0.00032, 0.00031] # coefficients # Apply attenuation from absorption lines. for l, c in zip(lines, coeffs): tau1 += _madau_t1(wave, z, l, c) return tau1 def _madau_tau2(wave, z): """ Applies attenuation from the IGM at <912 Angstroms at a particular set of wavelengths `wave` at redshift `z`. """ zlambda = 912.0 * (1 + z) tau2 = np.zeros_like(wave) sel = wave < zlambda xc = wave[sel] / 912.0 # (1+z) factors assuming this was at 912A xem = 1. + z # observed (1+z) tau2[sel] = ((0.25 * (xc**3) * (xem**0.46 - xc**0.46)) + (9.4 * (xc**1.5) * (xem**0.18 - xc**0.18)) - (0.7 * (xc**3) * (xc**-1.32 - xem**-1.32)) - (0.023 * (xem**1.68 - xc**1.68))) # compute optical depth tau2[tau2 < 0.] = 0. # set floor to 0. return tau2 def madau_teff(wave, z): """ Applies attenuation from the IGM at <1216 Angstroms at a particular set of wavelengths `wave` at redshift `z`. Returns the **effective transmission**. """ # Compute optical depth by splicing together <912 and 912-1216 components. tau = _madau_tau1(wave, z) + _madau_tau2(wave, z) # Convert to **effective transmission**. teff = np.exp(-tau) return teff
TypeScript
UTF-8
891
3.28125
3
[ "Apache-2.0" ]
permissive
import * as lambda from '@aws-cdk/aws-lambda'; /** * Properties to configure an API Gateway resource handler. * * The expectation is that you have a file that matches, e.g. * * This resource: * * new ResourceHandlerProps('user', 'get'); * * is implemented in this file: * * lambda/user-get.ts */ export class ResourceHandlerProps { /** * @param {string} resourceName The name of the resource, e.g. 'user' * @param {string} verb The HTTP verb, e.g. 'get' or 'post' * @param {boolean} requireAuth If true, require cognito auth, otherwise the resource is open * @param {lambda.Function} grantAccess A function that grants the lambda function access */ constructor( public resourceName: string, public verb: string, public requireAuth: boolean, public grantAccess: (f: lambda.Function) => any ) {} }
C#
UTF-8
579
3.21875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Prime { class Program { static void Main(string[] args) { int num = int.Parse(Console.ReadLine()); if (IsPrime(num)==true) } static bool IsPrime(int num) { for (int i = 2; i <= Math.Sqrt(num); i++) { if (num % i == 0) return false; } return true; } } }
Java
UTF-8
8,329
2.53125
3
[]
no_license
package com.huangxj.common.core.utils; import com.huangxj.common.core.model.OptionVo; import org.apache.commons.collections.CollectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanWrapper; import org.springframework.beans.BeanWrapperImpl; import java.lang.reflect.Field; import java.util.*; /** * @ClassName BeanConverter * @Author: huangxj * @Create: 2018/11/24 **/ public class BeanConverter { private static final Logger logger = LoggerFactory.getLogger(BeanConverter.class); /** * 单个对象转换 */ public static <DO, VO> VO convert(DO from, Class<VO> clazz, String... ignoreProperties) { if (from == null) { return null; } VO to = null; try { to = clazz.newInstance(); } catch (Exception e) { logger.error("初始化{}对象失败。", clazz, e); } BeanUtils.copyProperties(from, to, ignoreProperties); return to; } /** * 单个对象转换 */ public static <DO, VO> VO convert(DO from, VO to, String... ignoreProperties) { if (from == null) { return null; } try { if (to == null) { Class<VO> clazz = (Class<VO>) to.getClass(); to = clazz.newInstance(); } } catch (Exception e) { logger.error("初始化{}对象失败。", to.getClass(), e); } BeanUtils.copyProperties(from, to, ignoreProperties); return to; } /** * 批量对象转换 */ public static <DO, VO> List<VO> convert(List<DO> fromList, Class<VO> clazz, String... ignoreProperties) { if (CollectionUtils.isEmpty(fromList)) { return new ArrayList<VO>(); } List<VO> toList = new ArrayList<VO>(); for (DO from : fromList) { toList.add(convert(from, clazz, ignoreProperties)); } return toList; } /** * 将列表转为树 * Vo中必须有id,parentId,List<Vo> children */ public static <Vo> List listToTree(Integer parent, List<Vo> list, Class<Vo> clazz) { if (list == null) { return null; } List<Vo> ret = new ArrayList<>(); try { Field idField = clazz.getDeclaredField("id"); Field parentIdField = clazz.getDeclaredField("parentId"); Field childrenField = clazz.getDeclaredField("children"); parentIdField.setAccessible(true); childrenField.setAccessible(true); idField.setAccessible(true); for (Vo item : list) { Integer parentId = (Integer) parentIdField.get(item); Integer id = (Integer) idField.get(item); if (Objects.equals(parent, parentId)) { childrenField.set(item, listToTree(id, list, clazz)); ret.add(item); } } } catch (Exception e) { return null; } if (ret.size() > 0) { return ret; } else { return null; } } /** * fjr * 转换二级菜单实体类 * * @param list * @param clazz * @param value * @param label * @param parentValue * @return */ public static List<OptionVo> convertVo(List list, Class clazz, String value, String label, String parentValue) { if (list == null) { return null; } List<OptionVo> listOptionVo = new ArrayList<>(); Field valueField = null; Field labelField = null; Field parentValueField = null; try { if (!StringUtils.isEmpty(value)) { valueField = clazz.getDeclaredField(value); valueField.setAccessible(true); } if (!StringUtils.isEmpty(label)) { labelField = clazz.getDeclaredField(label); labelField.setAccessible(true); } if (!StringUtils.isEmpty(parentValue)) { parentValueField = clazz.getDeclaredField(parentValue); parentValueField.setAccessible(true); } for (Object o : list) { OptionVo optionVo = new OptionVo(); if (!StringUtils.isEmpty(value)) { Object oValueField = valueField.get(o); optionVo.setValue(oValueField); } if (!StringUtils.isEmpty(label)) { Object oLabelField = labelField.get(o); optionVo.setLabel(oLabelField); } if (!StringUtils.isEmpty(parentValue)) { Object oParentValueField = parentValueField.get(o); optionVo.setParentValue(oParentValueField); } listOptionVo.add(optionVo); } } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } if (listOptionVo.size() > 0) { return listOptionVo; } else { return null; } } /** * fjr * 两个父子关系的List集合合并成一个List * * @param listRoot * @param listchildren * @return */ public static List<OptionVo> converToListOptionVo(List<OptionVo> listRoot, List<OptionVo> listchildren) { //将两个父子关系的List集合合并成一个List List<OptionVo> listRootVo = new ArrayList<>(); int i = 0; for (OptionVo oRoot : listRoot) { OptionVo optionVo = new OptionVo(); optionVo.setId(i++); optionVo.setValue(oRoot.getValue()); optionVo.setLabel(oRoot.getLabel()); List<OptionVo> listChildrenVo = new ArrayList<>(); for (OptionVo children : listchildren) { if (Objects.equals(oRoot.getValue(), children.getParentValue())) { OptionVo childrenVo = new OptionVo(); childrenVo.setId(i++); childrenVo.setValue(children.getValue()); childrenVo.setLabel(children.getLabel()); listChildrenVo.add(childrenVo); } } if (listChildrenVo.size() > 0) { optionVo.setChildren(listChildrenVo); } listRootVo.add(optionVo); } if (listRootVo.size() > 0) { return listRootVo; } else { return null; } } /** * 将实体类转化为map * * @param obj * @return */ public static Map convertObjToMap(Object obj) { Map<String, Object> map = new HashMap<>(); if (Objects.isNull(obj)) { return null; } Field[] fields = obj.getClass().getDeclaredFields(); for (Field field : fields) { try { Field f = obj.getClass().getDeclaredField(field.getName()); f.setAccessible(true); Object o = f.get(obj); map.put(field.getName(), o); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } return map; } public static String[] getNullPropertyNames(Object source) { final BeanWrapper src = new BeanWrapperImpl(source); java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors(); Set<String> emptyNames = new HashSet<String>(); for (java.beans.PropertyDescriptor pd : pds) { Object srcValue = src.getPropertyValue(pd.getName()); if (srcValue == null) { emptyNames.add(pd.getName()); } } String[] result = new String[emptyNames.size()]; return emptyNames.toArray(result); } /** * 单个对象转换,忽略空值 */ public static <DO, VO> VO convertIgnoreNull(DO from, VO to) { return convert(from, to, getNullPropertyNames(from)); } }
TypeScript
UTF-8
424
3.21875
3
[]
no_license
function mergeSimilarItems(items1: number[][], items2: number[][]): number[][] { let vwMap = new Map() //vw abbreviates value weight for (let [value, weight] of items1.concat(items2)) { if (!vwMap.has(value)) { vwMap.set(value, weight) } else { vwMap.set(value, vwMap.get(value) + weight) } } return Array.from(vwMap.entries()).sort((a,b) => a[0] - b[0]) };
PHP
UTF-8
15,294
2.828125
3
[ "MIT" ]
permissive
<?php /** * * This class has all the necessary code for making API calls thru curl library * @category Helper * @author Original Author <adrian@socialdiabetes.com> * @link https://github.com/AdrianVillamayor/CurlHelper * */ declare(strict_types=1); namespace Adrii; class CurlHelper { public string $user_agent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36"; public int $timeout = 30; /** * @var \CurlHandle */ protected $ch; protected ?string $url; protected ?string $mime = null; protected array $mime_type = array( 'MIME_X_WWW_FORM' => 'application/x-www-form-urlencoded', 'MIME_FORM_DATA' => 'multipart/form-data', 'MIME_JSON' => 'application/json', 'MIME_XML' => 'application/xml', 'MIME_BINARY' => 'application/binary' ); protected bool $utf8 = FALSE; protected string $content_type; protected array $get_data = []; protected array $post_data = []; protected array $put_data = []; protected array $delete_data = []; protected ?string $post_raw; protected array $headers = []; /** * @var mixed */ protected $response; protected int $header_size; /** * @var mixed */ protected $sent; protected string $error; protected int $errno; public int $http_code; /** * @var mixed */ public $debug; public bool $is_debug = FALSE; public function __construct() { $this->ch = curl_init(); } public function setUrl(string $url): void { $this->url = $url; } public function setMime(string $mime = null): void { switch ($mime) { case 'form': case 'x-www-form-urlencoded': $this->mime = $this->mime_type['MIME_X_WWW_FORM']; break; case 'multipart': case 'multipart/form-data': $this->mime = $this->mime_type['MIME_FORM_DATA']; break; case 'json': $this->mime = $this->mime_type['MIME_JSON']; break; case 'xml': $this->mime = $this->mime_type['MIME_XML']; break; case 'binary': $this->mime = $this->mime_type['MIME_BINARY']; break; default: $this->mime = $this->mime_type['MIME_JSON']; break; } } public function setUtf8(): void { $this->utf8 = TRUE; } public function setHeaders(array $data, bool $parse = TRUE): void { foreach ($data as $key => $val) { if ($parse) { $this->headers[$this->parseStringHeader($key)] = $val; } else { $this->headers[$key] = $val; } } } public function setOptions(array $options): void { foreach ($options as $key => $value) { curl_setopt($this->ch, $key, $value); } } /** * @param mixed $raw */ public function setPostRaw($raw): void { $this->post_raw = (is_array($raw)) ? http_build_query($raw) : $raw; } public function setPostParams(array $data): void { $this->post_data = array_merge($this->post_data, $data); } public function setPostFiles(array $files, bool $form = FALSE): void { $c_files_array = array(); if ($form) { $c_files_array = $this->prefabFromFiles($files, $c_files_array); } else { $c_files_array = $this->prefabFiles($files, $c_files_array); } $this->setPostParams($c_files_array); } public function setGetParams(array $data): void { $this->get_data = array_merge($this->get_data, $data); } public function setPutParams(array $data): void { $this->put_data = array_merge($this->put_data, $data); } public function setDeleteParams(array $data): void { $this->delete_data = array_merge($this->delete_data, $data); } public function setDebug(): void { $this->is_debug = TRUE; } /** * This method will perform an action/method thru HTTP/API calls * * @param string $method POST, PUT, GET etc * @param string $url * @param string $mime Type of data (form, multipart, json) * @param array $data Array * @param bool $debug Default False * * @return void */ public function execute(): void { //- POST if (!empty($this->post_data)) { curl_setopt($this->ch, CURLOPT_POST, TRUE); $post_data = ($this->mime === $this->mime_type['MIME_JSON']) ? json_encode($this->post_data) : $this->post_data; curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post_data); $this->headers['Content-Type'] = $this->parseMimeType(); } //- POST RAW elseif (isset($this->post_raw)) { curl_setopt($this->ch, CURLOPT_POST, TRUE); curl_setopt($this->ch, CURLOPT_POSTFIELDS, $this->post_raw); $this->headers['Content-Type'] = $this->parseMimeType(); $this->headers['Content-Length'] = strlen($this->post_raw); } // - PUT elseif (!empty($this->put_data)) { curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($this->ch, CURLOPT_POSTFIELDS, http_build_query($this->put_data)); $this->headers['Content-Type'] = $this->parseMimeType(); } // - DELETE elseif (!empty($this->delete_data)) { curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($this->ch, CURLOPT_POSTFIELDS, http_build_query($this->delete_data)); $this->headers['Content-Type'] = $this->parseMimeType(); } // - GET elseif (!empty($this->get_data)) { curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, "GET"); $this->url = sprintf("%s?%s", $this->url, http_build_query($this->get_data)); } else { curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, "GET");; } $url = $this->generateUrl(); curl_setopt($this->ch, CURLOPT_URL, $url); curl_setopt($this->ch, CURLOPT_USERAGENT, $this->user_agent); if (!empty($this->headers)) { $data = []; foreach ($this->headers as $k => $v) { if (is_array($v)) { foreach ($v as $val) { $data[] = "$k: $val"; } } else { $data[] = "$k: $v"; } } curl_setopt($this->ch, CURLOPT_HTTPHEADER, $data); } curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, TRUE); $this->response = curl_exec($this->ch); $this->http_code = curl_getinfo($this->ch, CURLINFO_HTTP_CODE); $this->header_size = curl_getinfo($this->ch, CURLINFO_HEADER_SIZE); $this->sent = curl_getinfo($this->ch, CURLINFO_HEADER_OUT); $this->error = curl_error($this->ch); $this->errno = curl_errno($this->ch); if ($this->is_debug) { $this->debug = curl_getinfo($this->ch); } curl_close($this->ch); } public function http_code(): int { return $this->http_code; } public function debug(): array { return array("Debug" => $this->debug, "Error" => $this->error, "Errno" => $this->errno, "Out" => $this->sent, "Code" => $this->http_code, "Size" => $this->header_size); } public function response(string $format = 'array'): ?array { switch ($format) { case 'obj': $response = json_decode($this->response, FALSE, 512, JSON_BIGINT_AS_STRING); break; case 'array': $response = json_decode($this->response, TRUE, 512, JSON_BIGINT_AS_STRING); break; case 'xml': $xml = simplexml_load_string($this->response); $json = json_encode($xml); $response = json_decode($json, TRUE, 512, JSON_BIGINT_AS_STRING); break; } if (json_last_error() == JSON_ERROR_NONE) { return (array) $response; } if ($this->response == "" || empty($this->response)) { return null; } if (is_string($this->response)) { return null; } return $response; } /** * @return array $error, $msg */ public function parseCode(): array { $error = TRUE; switch ($this->http_code) { case 100: $msg = 'Continue'; break; case 101: $msg = 'Switching Protocols'; break; case 200: $msg = 'OK'; $error = FALSE; break; case 201: $msg = 'Created'; $error = FALSE; break; case 202: $msg = 'Accepted'; $error = FALSE; break; case 203: $msg = 'Non-Authoritative Information'; $error = FALSE; break; case 204: $msg = 'No Content'; $error = FALSE; break; case 205: $msg = 'Reset Content'; $error = FALSE; break; case 206: $msg = 'Partial Content'; $error = FALSE; break; case 300: $msg = 'Multiple Choices'; break; case 301: $msg = 'Moved Permanently'; break; case 302: $msg = 'Moved Temporarily'; break; case 303: $msg = 'See Other'; break; case 304: $msg = 'Not Modified'; break; case 305: $msg = 'Use Proxy'; break; case 400: $msg = 'Bad Request'; break; case 401: $msg = 'Unauthorized'; break; case 402: $msg = 'Payment Required'; break; case 403: $msg = 'Forbidden'; break; case 404: $msg = 'Not Found'; break; case 405: $msg = 'Method Not Allowed'; break; case 406: $msg = 'Not Acceptable'; break; case 407: $msg = 'Proxy Authentication Required'; break; case 408: $msg = 'Request Time-out'; break; case 409: $msg = 'Conflict'; break; case 410: $msg = 'Gone'; break; case 411: $msg = 'Length Required'; break; case 412: $msg = 'Precondition Failed'; break; case 413: $msg = 'Request Entity Too Large'; break; case 414: $msg = 'Request-URI Too Large'; break; case 415: $msg = 'Unsupported Media Type'; break; case 500: $msg = 'Internal Server Error'; break; case 501: $msg = 'Not Implemented'; break; case 502: $msg = 'Bad Gateway'; break; case 503: $msg = 'Service Unavailable'; break; case 504: $msg = 'Gateway Time-out'; break; case 505: $msg = 'HTTP Version not supported'; break; default: $msg = "Unknown http status code " . $this->http_code; break; } return array($error, $msg); } protected function generateUrl(): string { $parsed_string = ''; $url = parse_url($this->url); if (!empty($url['query'])) { parse_str($url['query'], $get_data); $url['query'] = http_build_query(array_merge($get_data, $this->get_data)); } else { $url['query'] = http_build_query($this->get_data); } if (isset($url['scheme'])) { $parsed_string .= $url['scheme'] . '://'; } if (isset($url['user'])) { $parsed_string .= $url['user']; if (isset($url['pass'])) { $parsed_string .= ':' . $url['pass']; } $parsed_string .= '@'; } if (isset($url['host'])) { $parsed_string .= $url['host']; } if (isset($url['port'])) { $parsed_string .= ':' . $url['port']; } if (!empty($url['path'])) { $parsed_string .= $url['path']; } else { $parsed_string .= '/'; } if (!empty($url['query'])) { $parsed_string .= '?' . $url['query']; } if (isset($url['fragment'])) { $parsed_string .= '#' . $url['fragment']; } return $parsed_string; } // - Fix strings to Mime-Type protected function parseMimeType(): string { $mime = ($this->utf8) ? $this->mime . "; charset=utf-8 ;" : $this->mime; return $mime; } // - Fix strings to Proper-Case protected function parseStringHeader(string $str): string { $str = explode('-', $str); foreach ($str as &$word) { $word = ucfirst($word); } return implode('-', $str); } // - Prepare local file data to the CURLFile model protected function prefabFiles(array $files, array $c_files_array): array { if (!empty($files)) { foreach ($files as $key) { $mime = mime_content_type($key); $info = pathinfo($key); $name = $info['basename']; $c_files_array[] = new CURLFile($key, $mime, $name); } } return $c_files_array; } // - Prepare data from $_FILES to the CURLFile model protected function prefabFromFiles(array $files, array $c_files_array) { if (!empty($files)) { for ($i = 0; $i < count($files['tmp_name']); $i++) { $filename = $files['tmp_name'][$i]; $mime = $files['type'][$i]; $name = $files['name'][$i]; $c_files_array[] = new CURLFile($filename, $mime, $name); } } return $c_files_array; } }
C++
UTF-8
790
2.5625
3
[]
no_license
#include<iostream> #include<queue> #include<cstring> using namespace std; int K[200+5],vis[200+5]={0},dir[2]={-1,1}; int N,A,B; struct fl{ int floor,min_count; }; int bfs(){ queue<fl>q; fl s1={A,0},s2; vis[s1.floor] = 1; q.push(s1); while(!q.empty()){ s1 = q.front(); if(s1.floor == B){ cout << s1.min_count << endl; return 0; } else{ for(int i = 0 ;i < 2;i++){ s2.floor = s1.floor + (dir[i] * K[s1.floor]); if(s2.floor > 0 && s2.floor <= N && !vis[s2.floor]){ vis[s2.floor] = 1; s2.min_count = s1.min_count + 1; q.push(s2); } } } q.pop(); } return -1; } int main(){ while(cin>>N && N){ cin>>A>>B; memset(vis,0,sizeof(vis)); for(int i = 1;i <= N;i++){ cin>>K[i]; } int p = bfs(); if(p)cout<<p<<endl; } return 0; }
C++
UTF-8
267
2.921875
3
[ "Unlicense" ]
permissive
#include "container/union_find.hpp" int main() { int n, q; cin >> n >> q; UnionFind uf(n); for (int i = 0; i < q; ++i) { int p, a, b; cin >> p >> a >> b; if (p == 0) uf.unite(a, b); else cout << (uf.equal(a, b) ? "Yes" : "No") << endl; } }
Java
UTF-8
11,507
1.835938
2
[]
no_license
package org.dainst.gazetteer.controller; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.dainst.gazetteer.converter.JsonPlaceDeserializer; import org.dainst.gazetteer.dao.PlaceChangeRecordRepository; import org.dainst.gazetteer.dao.PlaceRepository; import org.dainst.gazetteer.dao.UserRepository; import org.dainst.gazetteer.domain.Place; import org.dainst.gazetteer.domain.PlaceChangeRecord; import org.dainst.gazetteer.domain.User; import org.dainst.gazetteer.domain.ValidationResult; import org.dainst.gazetteer.helpers.IdGenerator; import org.dainst.gazetteer.helpers.LanguagesHelper; import org.dainst.gazetteer.helpers.ProtectLocationsService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.support.RequestContext; import org.springframework.web.servlet.view.RedirectView; @Controller public class DocumentController { private static final Logger logger = LoggerFactory.getLogger(DocumentController.class); @Autowired private PlaceRepository placeDao; @Autowired private UserRepository userDao; @Autowired private PlaceChangeRecordRepository changeRecordDao; @Autowired private JsonPlaceDeserializer jsonPlaceDeserializer; @Autowired private ProtectLocationsService protectLocationsService; @Autowired private IdGenerator idGenerator; @Autowired private LanguagesHelper langHelper; @Value("${baseUri}") private String baseUri; @Value("${googleMapsApiKey}") private String googleMapsApiKey; @RequestMapping(value="/doc/{placeId}", method=RequestMethod.GET) public ModelAndView getPlace(@PathVariable String placeId, @RequestParam(required=false) String layout, @RequestParam(defaultValue="10") int limit, @RequestParam(defaultValue="0") int offset, @RequestParam(required=false) String q, @RequestParam(required=false) String fuzzy, @RequestParam(required=false, defaultValue="map,table") String view, @RequestParam(required=false) boolean createParentsList, @RequestHeader("User-Agent") String userAgent, @RequestHeader("Accept") String accept, HttpServletRequest request) { RequestContext requestContext = new RequestContext(request); Locale locale = requestContext.getLocale(); ModelAndView mav; String suffix = ""; String uri = request.getRequestURI(); logger.debug("uri: " + uri); if (uri.lastIndexOf(".") > 0) { suffix = uri.substring(uri.lastIndexOf(".")); logger.debug("suffix: " + suffix); } // redirect browsers to app logger.debug("User-Agent: {}", userAgent); logger.debug("Accept: {}", accept); if ( (accept.contains("text/html") && suffix.isEmpty()) || ".html".equals(suffix) && !userAgent.contains("bot")) { RedirectView redirectView = new RedirectView(baseUri + "app/#!/show/" + placeId, true, true); redirectView.setStatusCode(HttpStatus.MOVED_PERMANENTLY); logger.debug("Redirecting to app ..."); return new ModelAndView(redirectView); } long time = System.currentTimeMillis(); Place place = placeDao.findOne(placeId); logger.debug("findOne: {}", System.currentTimeMillis() - time); time = System.currentTimeMillis(); if (place == null) { throw new ResourceNotFoundException(); } else if (place.getReplacedBy() != null && !place.getReplacedBy().isEmpty()) { RedirectView redirectView = new RedirectView("/doc/" + place.getReplacedBy() + suffix, true, true); redirectView.setStatusCode(HttpStatus.MOVED_PERMANENTLY); mav = new ModelAndView(redirectView); // places that need to be reviewed should not be available to the public } else if (place.isNeedsReview()) { throw new ResourceNotFoundException(); } else { logger.debug("findByParent: {}", System.currentTimeMillis() - time); time = System.currentTimeMillis(); List<Place> relatedPlaces = placeDao.findByIdIn(place.getRelatedPlaces()); logger.debug("findByIdIn: {}", System.currentTimeMillis() - time); time = System.currentTimeMillis(); User user = null; Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal instanceof User) user = (User) principal; protectLocationsService.protectLocations(user, place); List<Place> parents = new ArrayList<Place>(); if (createParentsList) { createParentsList(place, parents); for (Place parent : parents) { protectLocationsService.protectLocations(user, parent); } } mav = new ModelAndView("place/get"); if (layout != null) { mav.setViewName("place/"+layout); } mav.addObject("place", place); mav.addObject("relatedPlaces", relatedPlaces); if (createParentsList) mav.addObject("parents", parents); mav.addObject("baseUri", baseUri); mav.addObject("language", locale.getISO3Language()); mav.addObject("limit", limit); mav.addObject("offset", offset); mav.addObject("view", view); mav.addObject("q", q); mav.addObject("nativePlaceName", place.getNameMap().get(locale.getISO3Language())); mav.addObject("userDao", userDao); mav.addObject("changeRecordDao", changeRecordDao); mav.addObject("placeDao", placeDao); mav.addObject("googleMapsApiKey", googleMapsApiKey); mav.addObject("languages", langHelper.getLocalizedLanguages(locale)); } return mav; } @RequestMapping(value="/doc", method={RequestMethod.POST, RequestMethod.PUT}) public ModelAndView createPlace(@RequestBody Place place, HttpServletResponse response) throws Exception { place.setId(idGenerator.generate(place)); Place existingPlace = placeDao.findOne(place.getId()); if (existingPlace == null) { placeDao.save(place); } else { throw new IllegalStateException("Could not create place! Generated ID already exists: " + place.getId()); } place = placeDao.save(place); changeRecordDao.save(createChangeRecord(place, "create")); logger.debug("created place {}", place); increaseChildrenCount(place); response.setStatus(201); response.setHeader("Location", baseUri + "place/" + place.getId()); ModelAndView mav = new ModelAndView("place/get"); mav.addObject("place", place); mav.addObject("baseUri", baseUri); return mav; } @RequestMapping(value="/doc/{placeId}", method={RequestMethod.POST, RequestMethod.PUT}) public ModelAndView updateOrCreatePlace(@RequestBody Place place, @PathVariable String placeId, HttpServletResponse response) throws Exception { Place placeToCheck = place; while (placeToCheck.getParent() != null && !placeToCheck.getParent().equals("")) { placeToCheck = placeDao.findOne(placeToCheck.getParent()); if (placeToCheck.getId().equals(place.getId())) { ModelAndView mav = new ModelAndView("place/validation"); ValidationResult result = new ValidationResult(); result.setSuccess(false); result.setMessage("parentError"); response.setStatus(422); mav.addObject("result", result); return mav; } } if (!checkPlaceAccess(place)) { ModelAndView mav = new ModelAndView("place/validation"); ValidationResult result = new ValidationResult(); result.setSuccess(false); result.setMessage("accessDeniedError"); response.setStatus(403); mav.addObject("result", result); return mav; } if (placeDao.exists(place.getId())) changeRecordDao.save(createChangeRecord(place, "edit")); else changeRecordDao.save(createChangeRecord(place, "create")); place.setId(placeId); place = placeDao.save(place); logger.debug("saved place {}", place); increaseChildrenCount(place); response.setStatus(201); response.setHeader("Location", baseUri + "place/" + place.getId()); ModelAndView mav = new ModelAndView("place/validation"); mav.addObject("result", new ValidationResult()); return mav; } @ExceptionHandler(HttpMessageNotReadableException.class) public ModelAndView handleValidationException(HttpMessageNotReadableException e, HttpServletResponse response) { ValidationResult result = new ValidationResult(); result.setSuccess(false); result.setMessage(e.getCause().getMessage()); response.setStatus(400); ModelAndView mav = new ModelAndView("place/validation"); mav.addObject("result", result); return mav; } @RequestMapping(value="/doc/{placeId}", method=RequestMethod.DELETE) public void deletePlace(@PathVariable String placeId, HttpServletResponse response) { List<Place> children = placeDao.findByParent(placeId); List<Place> relatedPlaces = placeDao.findByRelatedPlaces(placeId); Place place = placeDao.findOne(placeId); if (children.size() > 0 || relatedPlaces.size() > 0 || !checkPlaceAccess(place)) { response.setStatus(409); } else { place.setDeleted(true); placeDao.save(place); changeRecordDao.save(createChangeRecord(place, "delete")); response.setStatus(204); } } // add count for children (for scoring) private void increaseChildrenCount(Place place) { if (place.getParent() == null) return; Place parent = placeDao.findOne(place.getParent()); while (parent != null) { parent.setChildren(parent.getChildren()+1); placeDao.save(parent); logger.debug("updated children of {} count: {}", parent.getId(), parent.getChildren()); if (parent.getParent() != null) { parent = placeDao.findOne(parent.getParent()); } else { parent = null; } } } private PlaceChangeRecord createChangeRecord(Place place, String changeType) { User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); PlaceChangeRecord changeRecord = new PlaceChangeRecord(); changeRecord.setUserId(user.getId()); changeRecord.setPlaceId(place.getId()); changeRecord.setChangeType(changeType); changeRecord.setChangeDate(new Date()); return changeRecord; } private boolean checkPlaceAccess(Place place) { User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (place.getRecordGroupId() != null && !place.getRecordGroupId().isEmpty() && (user == null || !user.getRecordGroupIds().contains(place.getRecordGroupId()))) return false; else return true; } private void createParentsList(Place place, List<Place> parents) { if (place.getParent() != null && !place.getParent().isEmpty()) { Place parent = placeDao.findOne(place.getParent()); if (parent != null) { parents.add(parent); createParentsList(parent, parents); } } } }
TypeScript
UTF-8
438
2.703125
3
[ "MIT", "LicenseRef-scancode-generic-cla" ]
permissive
export interface PushNotification { message: string | null; title: string | null; customProperties?: { [name: string]: string }; } export interface PushListener { onPushNotificationReceived?: (pushNotification: PushNotification) => void; } export function isEnabled(): Promise<boolean>; export function setEnabled(enabled: boolean): Promise<void>; export function setListener(pushListener?: PushListener): Promise<void>;
JavaScript
UTF-8
383
2.546875
3
[]
no_license
function CastMoviAPI(movieId) { const key = '6c43de172bd11aba3555d5548a35dbd3'; return fetch( `https://api.themoviedb.org/3/movie/${movieId}/credits?api_key=${key}&language=en-US`, ).then(response => { if (response.ok) { return response.json(); } return Promise.reject(new Error(`Ничего не найдено`)); }); } export default CastMoviAPI;
Java
UTF-8
20,002
2.203125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package mypackage; import java.awt.HeadlessException; import java.sql.*; import java.sql.Connection; import java.sql.Statement; import java.text.SimpleDateFormat; import java.util.Calendar; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JProgressBar; import javax.swing.JTextField; /** * * @author Abhinav */ public class Reciverdetails extends javax.swing.JFrame { /** * Creates new form Reciverdetails */ JFrame refFrame; String pwdString; String acbalString; String acidString; String nameString; public Reciverdetails() { initComponents(); } public Reciverdetails(JFrame tempFrame,String pwdString,String acbalString,String acidString,String nameString) { initComponents(); refFrame=tempFrame; this.acbalString=acbalString; this.pwdString=pwdString; this.acidString=acidString; this.nameString=nameString; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); acnotxt = new javax.swing.JTextField(); nametxt = new javax.swing.JTextField(); btnhome = new javax.swing.JButton(); jLabel4 = new javax.swing.JLabel(); amttxt = new javax.swing.JTextField(); btnsubmit = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setUndecorated(true); jPanel1.setBackground(new java.awt.Color(204, 255, 204)); jLabel1.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N jLabel1.setForeground(new java.awt.Color(0, 0, 0)); jLabel1.setText("Enter Recipent's Details "); jLabel2.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N jLabel2.setForeground(new java.awt.Color(0, 0, 0)); jLabel2.setText("Recipent's Name:"); jLabel3.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N jLabel3.setForeground(new java.awt.Color(0, 0, 0)); jLabel3.setText("Account No"); acnotxt.setForeground(new java.awt.Color(0, 0, 0)); acnotxt.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { acnotxtActionPerformed(evt); } }); nametxt.setForeground(new java.awt.Color(0, 0, 0)); nametxt.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { nametxtActionPerformed(evt); } }); btnhome.setFont(new java.awt.Font("Agency FB", 1, 18)); // NOI18N btnhome.setForeground(new java.awt.Color(0, 0, 0)); btnhome.setText("<< HOME"); btnhome.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true)); btnhome.setOpaque(true); btnhome.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnhomeActionPerformed(evt); } }); jLabel4.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N jLabel4.setForeground(new java.awt.Color(0, 0, 0)); jLabel4.setText("Amount :"); amttxt.setForeground(new java.awt.Color(0, 0, 0)); amttxt.setText("300"); btnsubmit.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N btnsubmit.setForeground(new java.awt.Color(0, 0, 0)); btnsubmit.setText("Submit"); btnsubmit.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true)); btnsubmit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnsubmitActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(40, 40, 40) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnhome, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(33, 33, 33) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(acnotxt) .addComponent(nametxt) .addComponent(amttxt, javax.swing.GroupLayout.DEFAULT_SIZE, 184, Short.MAX_VALUE))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(75, 75, 75) .addComponent(btnsubmit, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 222, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(103, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(43, 43, 43) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(acnotxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(23, 23, 23) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(nametxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(amttxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 33, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(btnsubmit, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnhome)) .addGap(24, 24, 24)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void acnotxtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_acnotxtActionPerformed // TODO add your handling code here: }//GEN-LAST:event_acnotxtActionPerformed private void btnhomeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnhomeActionPerformed // TODO add your handling code here: refFrame.setVisible(true); dispose(); }//GEN-LAST:event_btnhomeActionPerformed private void btnsubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnsubmitActionPerformed // TODO add your handling code here: String id=acnotxt.getText(); Double amounttrans=Double.parseDouble(amttxt.getText()); Double amountavalable=0.0; Double recipacbalDouble; String recipent_nameString=nametxt.getText(); try { Connection connection= CommonFunction.addConection(); String querystrString="select * from accounts where Account_ID= "+acidString; Statement statement=connection.createStatement(); ResultSet resultSet; resultSet=statement.executeQuery(querystrString); if(resultSet.first()) { amountavalable=Double.parseDouble(resultSet.getString("account_bal")); } } catch (Exception e) { System.out.println("error "+e); } if(amounttrans>amountavalable) { JOptionPane.showMessageDialog(null, "Insufficient Balance","Error",JOptionPane.ERROR_MESSAGE); } else { try { Connection connection= CommonFunction.addConection(); String querystrString="select * from accounts where Account_ID= "+id; Statement statement=connection.createStatement(); ResultSet resultSet; resultSet=statement.executeQuery(querystrString); if(resultSet.first()) { recipacbalDouble=Double.parseDouble(resultSet.getString("account_bal")); String passwordString; JPasswordField pfField=new JPasswordField(); int ans=JOptionPane.showConfirmDialog(this, pfField, "Enter Password", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if (ans == JOptionPane.OK_OPTION) { passwordString= new String(pfField.getPassword()); System.out.println("User pasword is "+pwdString+"\n"); if(passwordString.equals("")) { JOptionPane.showMessageDialog(this, "Password field is empty","Error",JOptionPane.ERROR_MESSAGE); } else { if(passwordString.equals(pwdString)) { updateBalanceandInsertTrans(amountavalable,amounttrans,id,recipacbalDouble); progressbar obj=new progressbar(this,refFrame); obj.setVisible(true); // refFrame.setVisible(true); // dispose(); } else { JOptionPane.showMessageDialog(this,"Incorrect Password","Error",JOptionPane.ERROR_MESSAGE); //here validation no of wrong attempt can be done } } } } else { JOptionPane.showMessageDialog(this, "Inavalid Ac Number","Error",JOptionPane.ERROR_MESSAGE); } } catch (HeadlessException | SQLException e) { System.out.println("Error"+e); } } }//GEN-LAST:event_btnsubmitActionPerformed private void updateBalanceandInsertTrans(Double acbalofsender,Double transamount ,String id,Double recipentbal) { //acidstring is sender //id is reciver // amttxt is amouunt of transation Calendar cal=Calendar.getInstance(); java.util.Date date=cal.getTime(); SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy/MM/dd"); String dateString= formatter1.format(date); String senderbal=String.valueOf(acbalofsender-transamount); String recipentbalString=String.valueOf(transamount+recipentbal); System.out.println("Sender balance is "+senderbal+"\n Recipnt balance is "+recipentbalString); // System.out.println(amtString); try { Connection connection=CommonFunction.addConection(); Statement statement=connection.createStatement(); String queryString="update accounts set account_bal= '"+senderbal+"' where Account_ID='"+acidString+"' "; statement.executeUpdate(queryString); // queryString="update accounts set account_bal= '"+recipentbalString+"' where Account_ID='"+id+"' "; statement.executeUpdate(queryString); queryString="INSERT INTO `bank_system`.`transactions` ( `date`, `amount`, `Account_ID_sender`, `Account_ID_reciver`, `Recipent's name`, `Status`)" + " VALUES ( '"+dateString+"', '"+transamount+"', '"+acidString+"', '"+id+"', '"+nametxt.getText()+"', 'Sent')"; statement.executeUpdate(queryString); queryString="INSERT INTO `bank_system`.`transactions` ( `date`, `amount`, `Account_ID_sender`, `Account_ID_reciver`, `Recipent's name`, `Status`)" + " VALUES ( '"+dateString+"', '"+transamount+"', '"+id+"', '"+acidString+"', '"+nameString+"', 'Recived')"; statement.executeUpdate(queryString); } catch (Exception e) { System.out.println("Error" +e); } } public Reciverdetails(JFrame refFrame, String pwdString, String acbalString, JTextField acnotxt, JTextField amttxt, JButton btnhome, JButton btnsubmit, JLabel jLabel1, JLabel jLabel2, JLabel jLabel3, JLabel jLabel4, JPanel jPanel1, JTextField nametxt) throws HeadlessException { this.refFrame = refFrame; this.pwdString = pwdString; this.acbalString = acbalString; this.acnotxt = acnotxt; this.amttxt = amttxt; this.btnhome = btnhome; this.btnsubmit = btnsubmit; this.jLabel1 = jLabel1; this.jLabel2 = jLabel2; this.jLabel3 = jLabel3; this.jLabel4 = jLabel4; this.jPanel1 = jPanel1; this.nametxt = nametxt; } private void nametxtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nametxtActionPerformed // TODO add your handling code here: }//GEN-LAST:event_nametxtActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Reciverdetails.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Reciverdetails.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Reciverdetails.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Reciverdetails.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Reciverdetails().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField acnotxt; private javax.swing.JTextField amttxt; private javax.swing.JButton btnhome; private javax.swing.JButton btnsubmit; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JPanel jPanel1; private javax.swing.JTextField nametxt; // End of variables declaration//GEN-END:variables }
Python
UTF-8
1,449
2.9375
3
[]
no_license
import time import datetime DELTA_DEFAULT_DAYS = 180 # 6 months class CommitCutoff(object): def reset(self): pass def cutoff(self, commit): return False class MultipleCommitCutoff(CommitCutoff): def __init__(self, *cutoffs): self.cutoffs = cutoffs def reset(self): for cutoff in self.cutoffs: cutoff.reset() def cutoff(self, commit): for cutoff in self.cutoffs: if cutoff.cutoff(commit): return True return False class MaxIterationsCommitCutoff(CommitCutoff): def __init__(self, max_iterations): self.max_iterations = max_iterations self.reset() def reset(self): self.iterations = 0 def cutoff(self, commit): self.iterations += 1 return self.iterations > self.max_iterations class TimeSpanCommitCutoff(CommitCutoff): def __init__(self, *delta_args, **delta_kwargs): if len(delta_args) == 0 and len(delta_kwargs) == 0: delta_kwargs['days'] = DELTA_DEFAULT_DAYS self.delta = datetime.timedelta(*delta_args, **delta_kwargs) self.reset() def reset(self): self.end = None def cutoff(self, commit): if self.end == None: self.end = datetime.datetime.fromtimestamp(commit.committed_date) start = datetime.datetime.fromtimestamp(commit.committed_date) return abs(self.end - start) > self.delta
C++
UTF-8
515
3.09375
3
[ "BSD-3-Clause", "GPL-1.0-or-later", "LGPL-2.0-only", "LGPL-2.1-only", "MIT", "Zlib", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
#pragma once namespace av { class Rect { public: Rect(); Rect(int width, int height); Rect(int x, int y, int width, int height); void setX(int x) { this->x = x; } void setY(int y) { this->y = y; } void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } int getX() { return x; } int getY() { return y; } int getWidth() { return width; } int getHeight() { return height; } private: int x; int y; int width; int height; }; } // ::av
Java
UTF-8
1,334
2.1875
2
[]
no_license
package com.grabbddemoapp.data.model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; /** * Developer: Sandy */ public class AppVersion { @SerializedName("latestAndroidVersion") @Expose private int latestAndroidVersion; @SerializedName("criticalAndroidVersion") @Expose private int criticalAndroidVersion; @SerializedName("updateMessageAtPopup") @Expose private String updateMessageAtPopup; @SerializedName("updateTitleAtPopup") @Expose private String updateTitleAtPopup; /** * Gets latest android version. * * @return the latest android version */ public int getLatestAndroidVersion() { return latestAndroidVersion; } /** * Gets critical android version. * * @return the critical android version */ public int getCriticalAndroidVersion() { return criticalAndroidVersion; } /** * Gets update message at popup. * * @return the update message at popup */ public String getUpdateMessageAtPopup() { return updateMessageAtPopup; } /** * Gets update title at popup. * * @return the update title at popup */ public String getUpdateTitleAtPopup() { return updateTitleAtPopup; } }
Python
UTF-8
1,573
2.828125
3
[]
no_license
#!/usr/bin/python3 ''' This is the '2-do_deploy_web_static module. 2-do_deploy_web_static uses Fabric to distribute an archive to selected web servers. This module contains 1 function: do_deploy(). ''' from fabric.api import * env.hosts = ['34.207.77.115', '54.208.161.26'] def do_deploy(archive_path): '''This is the do_deploy function. do_deploy has 1 parameter: the path to a given archive. The function distributes an archive to a web server, or returns False. ''' try: # upload archive to /tmp directory of web server put(archive_path, "/tmp") path = archive_path.strip("versions/") s1 = "sudo mkdir -p /data/web_static/releases/" + path run(s1) # uncompress archive s2 = "sudo tar -xzf /tmp/" + path + " -C /data/web_static/releases/" s2 += path run(s2) # delete archive from web server run("rm /tmp/" + path) # delete symlink /data/web_server/current from web server s3 = "sudo mv /data/web_static/releases/" + path s3 += "/web_static/* /data/web_static/releases/" + path + "/" run(s3) s4 = "sudo rm -rf /data/web_static/releases/" + path + "/web_static" run(s4) run("sudo rm -rf /data/web_static/current") # create new symlink /data/web_server/current to new version of code s5 = "sudo ln -s /data/web_static/releases/" + path s5 += "/ /data/web_static/current" run(s5) return(True) except Exception as e: print(e) return(False)
C++
GB18030
3,525
2.5625
3
[]
no_license
#pragma once #include "system.h" #include <map> #include <string> #include "TexFrame.h" #include "physicslib.h" namespace sys { struct ImageDefine; struct TextDefine; } namespace render { class Texture; class Texture2D; class TextureCubeMap; // class TextureCache { public: TextureCache(); ~TextureCache(); public: // void addTexture2D(const std::string& path, Texture2D* texture); // Ƴ void removeTexture(Texture* texture); // Ƴ void removeTexture2D(const std::string& path); // Ƴ void removeAllTextures(); // ȡ Texture2D* getTexture2D(const std::string& path); public: // void addTexAtlas(const std::string& imagePath, const std::string& atlasPath, const sys::ImageTextureAtlas& texAtlas); // void addTexAtlas(const std::string& imagePath, const std::string& atlasPath, const Texture* texture, const sys::ImageTextureAtlas& texAtlas); // ȡַ, preloadǷԤ std::string getFrameName(const std::string& atlasPath, const std::string& name, bool preload = true); // ȡͼ const sys::ImageTextureAtlas* getTexAtlas(const std::string& atlasPath) const; // Ƴ void removeTexAtlas(const std::string& atlasPath); // Ƿ bool containsTexAtlas(const std::string& atlasPath) const; public: // void addTexFrame(const std::string& atlasPath, const TexFrame* texFrame, bool cleanup = true); // void addTexFrame(const std::string& atlasPath, const Texture* texture, const std::string& name, const math::Rect& rect, bool rotate = false, bool cleanup = true); // ȡƬ const TexFrame* getTexFrame(const std::string& atlasPathName, bool preload = true); // ȡƬ const TexFrame* getTexFrame(const std::string& atlasPath, const std::string name, bool preload = true); // ƳƬ void removeTexFrame(const std::string& atlasPathName); public: // һ2d Texture2D* createTexture2D(const phy::Color4B& color); // һ2d Texture2D* createTexture2D(const sys::ImageDefine& imageDefine); // һ2d Texture2D* createTexture2D(const std::string& path); // һı Texture2D* createTexture2D(const sys::TextDefine& textDefine); // һ TextureCubeMap* createTextureCubeMap(int count, const std::string* images); public: // ͼƬϢ sys::ImageDetail* loadImageDetail(const std::string& path); // ͼƬϢ sys::ImageDetail* loadImageDetail(const sys::ImageDefine& imageDefine); private: // ȡַ, preloadǷԤ std::string _getFrameName(const std::string& atlasPath, const std::string& name) const; // ȡƬ const TexFrame* _getTexFrame(const std::string& atlasPathName) const; // ԤƬ void _preloadTexFrame(const std::string& atlasPath, const std::string& name); private: // 2d std::map<std::string, Texture2D*> _texture2Ds; // std::map<uint32_t, Texture*> _textures; // ,{ͼ[], Ϣ} std::map<std::string, TexFrame*> _texAtlasFrames; // ,{ͼ, Ϣ} std::map<std::string, sys::ImageTextureAtlas> _texAtlas; }; #define G_TEXTURE_CACHE sys::Instance<render::TextureCache>::getInstance() }
Python
UTF-8
2,132
2.71875
3
[]
no_license
import sys import math sys.path.append('/home/abhinav/Desktop/Academics/Summer/Python') import numpy as np import matplotlib.pyplot as plt import time from spin import * from benchmark_ising import * kb = 1.0 m = 4 n = 4 p = 1 if p > 1: d = '3d' elif p == 1: d = '2d' tp = 'ising' qv = 0.0 jv = [0.0]*3 jv[0] = 1.0 iterations = 250000 step = 5000 innerloop = int(2*m*n*p) print "Model: ",tp print "J:", jv print "Q:", qv print "Total Iterations: ", iterations print "Measurement Step: ", step print "Inner Loop (Iterations within each Iterations): ", (innerloop/(m*n*p)),"* Total Lattice Points" temp_i = 0.0 temp_step = 0.25 temp_f = 6.0 n0 = int((temp_f - temp_i)/temp_step) M = [0.0]*n0 b_M = [0.0]*n0 Ms = [0.0]*n0 b_Ms = [0.0]*n0 M_error = [0.0]*n0 Ms_error = [0.0]*n0 rj = [0.0]*n0 Difference = [0.0]*n0 start_time = time.time() for i in range(n0): #def simulation(i): temperature = temp_i + i*temp_step if temperature == 0.0: beta = math.pow(10.0,50) else: beta = 1.0/(temperature*kb) r1 = spin(jv,qv,iterations,m,n,p,d,temperature,tp,step,temp_step,innerloop,beta) if tp == 'ising': benchmark = benchmark_i(jv,qv,m,n,p,d,temperature,beta) M[i] = r1[0] Ms[i] = r1[1] b_M[i] = benchmark[0] b_Ms[i] = benchmark[1] M_error[i] = r1[2] Ms_error[i] = r1[3] rj[i] = r1[4] Difference[i] = M[i] - Ms[i] x = np.arange(temp_i,temp_f,temp_step) print "\n-----------------------------------------------\n\nFinal Values for all Temperatures:" print "Ferromagnetic Moment, M: ", M print "Anti-ferromagnetic Moment, Ms: ", Ms plt.figure() plt.errorbar(x, Ms, yerr=Ms_error, fmt='-o', uplims=True, lolims=True) plt.plot(x, b_Ms, 'r-o') plt.title('Ms vs T') plt.savefig('Ms vs T.jpg') plt.figure() plt.errorbar(x, M, yerr=M_error, fmt='-o', uplims=True, lolims=True) plt.plot(x, b_M, 'r-o') plt.title('M vs T') plt.savefig('M vs T.jpg') plt.figure() plt.plot(x,rj,'b-o') plt.title('Rejectance') plt.savefig('Rejectance.jpg') plt.figure() plt.plot(x,Difference,'bo') plt.title('Difference b/w M and Ms') plt.savefig('Difference.jpg') print "\nRuntime: %s seconds" % (time.time() - start_time)
JavaScript
UTF-8
330
3.53125
4
[]
no_license
// Create an HTML page with a large element on the page // that says "Don't hover over me" inside of it. // When you hover over the element, send an alert to the user // that says, "Hey, I told you not to hover over me!" document.getElementById('alert').onmouseover = function (){ alert('Hey, I told you not to hover me!!') }
Java
UTF-8
1,191
2.6875
3
[]
no_license
package hr.fer.zemris.java.servleti.colors; 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; /** * Servlet that looks in the parameters and depending on it sets * the seesion attribute of the application to string value of that color. * And after setting session color it looks up for the path stored under * key referer and redirects the application to that path. * * * @author Marko * */ @WebServlet("/setcolor") public class SetColorServlet extends HttpServlet{ /** * */ private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String color = req.getParameter("color"); if(color != null) { req.getSession().setAttribute("pickedBgCol", color); } else { req.getSession().setAttribute("pickedBgCol", "white"); } resp.sendRedirect((String) req.getSession().getAttribute("referer")); } }
Java
UTF-8
1,910
2.140625
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2016-2017 Axioma srl. * * 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.holonplatform.datastore.jdbc.test.expression; import java.util.Arrays; import java.util.List; import com.holonplatform.core.ConstantConverterExpression; import com.holonplatform.core.TypedExpression; import com.holonplatform.core.query.QueryFunction; public class IfNullFunction<T> implements QueryFunction<T, T> { private final TypedExpression<T> nullableValue; private final TypedExpression<T> fallbackValue; public IfNullFunction(TypedExpression<T> nullableValue, TypedExpression<T> fallbackValue) { super(); this.nullableValue = nullableValue; this.fallbackValue = fallbackValue; } public IfNullFunction(TypedExpression<T> nullableValue, T fallbackValue) { this(nullableValue, ConstantConverterExpression.create(fallbackValue, nullableValue.getType())); } @Override public Class<? extends T> getType() { return nullableValue.getType(); } @Override public void validate() throws InvalidExpressionException { if (nullableValue == null) { throw new InvalidExpressionException("Missing nullable expression"); } if (fallbackValue == null) { throw new InvalidExpressionException("Missing fallback expression"); } } @Override public List<TypedExpression<? extends T>> getExpressionArguments() { return Arrays.asList(nullableValue, fallbackValue); } }
Markdown
UTF-8
6,303
2.953125
3
[]
no_license
<br> This webpage contains complementary material to the research paper: | <a href="#img1"><img src="bannercolor.jpg" width="100" height="10"></a>| <a href="#img1"><img src="bannercolor.jpg" width="750" height="10"></a>| |:---:|:---| |[<img src="icon-pdf.png" width="50">](https://doi.org/10.1016/j.patcog.2021.108198)|[J. Sáez, E. Corchado, ANCES: A novel method to repair attribute noise in classification problems, Pattern Recognition 121 (2022) 108198.](https://doi.org/10.1016/j.patcog.2021.108198)| | <a href="#img1"><img src="bannercolor.jpg" width="100" height="10"></a>| <a href="#img1"><img src="bannercolor.jpg" width="750" height="10"></a>| <br> The web is organized according to the following summary: 1. [Abstract](#Abstract) 2. [Datasets](#Datasets) - [Real-world datasets](#Realworld) - [Synthetic datasets](#Synthetic) 3. [Performance results](#Performance) <br> ## <a name="Abstract"></a> 1. Abstract Noise negatively affects the complexity and performance of models built in classification problems. The most common approach to mitigate its consequences is the usage of preprocessing techniques, known as noise filters, which are designed to remove noisy samples from the training data. Nevertheless, they are specifically oriented to deal with errors affecting class labels. Their employment may not always result in an improvement when noise affects attribute values. In these cases, correcting the errors is an interesting alternative to traditional noise filtering that has not been enough studied so far in the specialized literature. This research proposes an attribute noise correction method with the final aim of increasing the performance of the classification algorithms used later. The identification of noisy data is based on an error score assigned to each one of the attribute values in the dataset, which are then passed through an optimization process to correct their potential noise. The validity of the proposed method is studied in an exhaustive experimental study, in which it is compared to several well-known preprocessing methods to deal with noisy datasets. The results obtained show the suitability of attribute noise correction with respect to the other alternatives when data suffer from attribute noise. <br> ## <a name="Datasets"></a> 2. Datasets ### <a name="Realworld"></a> 2.1. Real-world datasets The experimentation is based on 30 real-world datasets, in which attribute noise is introduced. The following table shows these datasets, where *sa* refers to the number of samples, *at* to the number of attributes and *cl* to the number of classes. Samples containing missing values are removed from the datasets before their usage. <center> <a href="#img2"><img src="data.jpg" width="600"></a> </center> These datasets can be downloaded from the webpage of the [UCI Machine Learning Repository](https://archive.ics.uci.edu/ml/index.php). <br> ### <a name="Synthetic"></a> 2.2. Synthetic datasets The sensitivity analysis of parameters in ANCES has been performed using synthetic datasets. They have been created following the procedure proposed by Qiu and Joe (2006). Completely clean datasets (without noise, outliers or overlapping) are created considering a different number of classes (2, 5 and 8), attributes (10, 20 and 30) and samples (500, 750 and 1000). They are built completely balanced, that is, the samples are evenly distributed among the classes. The complete details about the data generation method and the source code used to generate the synthetic datasets can be downloaded below: |<a href="#img1"><img src="bannercolor.jpg" width="750" height="10"></a>|<a href="#img1"><img src="bannercolor.jpg" width="100" height="10"></a>| |:---|:---:| |**Description** |**File**| |W. Qiu and H. Joe. **Generation of random clusters with specified degree of separation**. *Journal of Classification*, 23(2):315–334, 2006.| [<img src="icon-pdf.png" width="50">](https://raw.github.com/joseasaezm/mlrs-cce/master/docs/2006-JC-Qiu.pdf)| |Source code of the synthetic data generation method of Qiu and Joe (2006)| [<img src="icon-method2.png" width="50">](https://cran.r-project.org/web/packages/clusterGeneration/index.html)| |<a href="#img1"><img src="bannercolor.jpg" width="750" height="10"></a>|<a href="#img1"><img src="bannercolor.jpg" width="100" height="10"></a>| <br> ## <a name="Performance"></a> 3. Performance results |<a href="#img1"><img src="bannercolor.jpg" width="750" height="10"></a>|<a href="#img1"><img src="bannercolor.jpg" width="100" height="10"></a>| |:---|:---:| |&nbsp;&nbsp;&nbsp;<a href="#img"><img src="green1.png" width="15"></a> *5% attribute noise* | [<img src="icon-excel.png" width="50">](https://raw.github.com/joseasaezm/ances/master/docs/5an.xls)| |&nbsp;&nbsp;&nbsp;<a href="#img"><img src="green1.png" width="15"></a> *10% attribute noise* | [<img src="icon-excel.png" width="50">](https://raw.github.com/joseasaezm/ances/master/docs/10an.xls)| |&nbsp;&nbsp;&nbsp;<a href="#img"><img src="green1.png" width="15"></a> *15% attribute noise* | [<img src="icon-excel.png" width="50">](https://raw.github.com/joseasaezm/ances/master/docs/15an.xls)| |&nbsp;&nbsp;&nbsp;<a href="#img"><img src="green1.png" width="15"></a> *20% attribute noise* | [<img src="icon-excel.png" width="50">](https://raw.github.com/joseasaezm/ances/master/docs/20an.xls)| |&nbsp;&nbsp;&nbsp;<a href="#img"><img src="green1.png" width="15"></a> *25% attribute noise* | [<img src="icon-excel.png" width="50">](https://raw.github.com/joseasaezm/ances/master/docs/25an.xls)| |&nbsp;&nbsp;&nbsp;<a href="#img"><img src="green1.png" width="15"></a> *30% attribute noise* | [<img src="icon-excel.png" width="50">](https://raw.github.com/joseasaezm/ances/master/docs/30an.xls)| |&nbsp;&nbsp;&nbsp;<a href="#img"><img src="green1.png" width="15"></a> *35% attribute noise* | [<img src="icon-excel.png" width="50">](https://raw.github.com/joseasaezm/ances/master/docs/35an.xls)| |&nbsp;&nbsp;&nbsp;<a href="#img"><img src="green1.png" width="15"></a> *40% attribute noise* | [<img src="icon-excel.png" width="50">](https://raw.github.com/joseasaezm/ances/master/docs/40an.xls)| |<a href="#img1"><img src="bannercolor.jpg" width="750" height="10"></a>|<a href="#img1"><img src="bannercolor.jpg" width="100" height="10"></a>|
Java
UTF-8
152
2.09375
2
[ "Apache-2.0" ]
permissive
// "Escape trailing whitespace characters" "true" class StringTemplate1 { String s = STR.""" \{}one\s two four"\s"""; }
Python
UTF-8
83
3.484375
3
[]
no_license
def asteriscos(numero): y = '*'*numero return y n = 7 print(asteriscos(n))
C++
UTF-8
2,471
2.875
3
[]
no_license
#ifndef CONSTANT_NODE_H_ #define CONSTANT_NODE_H_ #include <graph/Node.h> namespace jags { /** * @short Top-level Node with constant value * * Constant nodes are the top-level nodes in any directed acyclic * graph (i.e. they have no parents). They have a fixed value that is * defined when they are constructed and which is shared across all * chains. * * JAGS distinguishes between two classes of ConstantNode. Those * defined explicitly as constants in the BUGS language description of * the model are constructed with the parameter observed=false, and * are not considered random variables. Constant nodes that are * implicitly defined (i.e. they only appear on the left hand side of * any relation and their values are determined by the user-supplied * data) are constructed with the parameter observed=true and are * considered to represent observed randmo variables. */ class ConstantNode : public Node { const bool _observed; public: /** * Constructs a scalar constant node and sets its value. The value * is fixed and is shared between all chains. */ ConstantNode(double value, unsigned int nchain, bool observed); /** * Constructs a multi-dimensional constant node */ ConstantNode(std::vector<unsigned int> const &dim, std::vector<double> const &value, unsigned int nchain, bool observed); /** * Indicates whether a ConstantNode is discrete-valued */ bool isDiscreteValued() const; /** * This function does nothing. It exists only so that objects * inheriting from ConstantNode can be instantiated. */ void deterministicSample(unsigned int); /** * This function does nothing. The value of the constant node is * not changed and the state of the RNG remains the same. */ void randomSample(RNG*, unsigned int); /** * Constant nodes have no parents. This function always returns true. */ bool checkParentValues(unsigned int) const; /** * A constant node is named after its value */ std::string deparse(std::vector<std::string> const &parents) const; /** * A constant node is always fixed. */ bool isFixed() const; /** * The RVStatus of a ConstantNode is determined by the parameter * "observed" passed to the constructor. */ RVStatus randomVariableStatus() const; void unlinkParents(); }; } /* namespace jags */ #endif /* CONSTANT_NODE_H_ */
Python
UTF-8
1,019
2.609375
3
[]
no_license
import math n = int(input()) rank = [] for i in range(n): s, p, f, o = map(int, input().split()) s = -1 * s o = -1 * o rank.append((s, p, f, o, i)) rank.sort() score = [100, 75, 60, 50, 45, 40, 36, 32, 29, 26, 24, 22, 20, 18, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] finalscore = [] buffer = [] bufferscore = 0 prev = (1, -1, -1) for i in range(n): t = rank[i] cur = (t[0], t[1], t[2]) if cur == prev or buffer == []: buffer.append(t) if i < 30: bufferscore += score[i] else: sc = math.ceil(bufferscore/len(buffer)) for b in buffer: finalscore.append((b[4], sc-b[3])) buffer = [] if i < 30: bufferscore = score[i] else: bufferscore = 0 buffer.append(t) prev = cur if len(buffer) > 0: sc = math.ceil(bufferscore/len(buffer)) for b in buffer: finalscore.append((b[4], sc-b[3])) finalscore.sort() for f in finalscore: print(f[1])
C#
UTF-8
16,028
2.71875
3
[]
no_license
using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Booklovers.Data; using System; using System.Linq; using NLog.Web; using NLog; namespace Booklovers.Models { public static class SeedData { private static Logger logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); public static void Initialize(IServiceProvider serviceProvider) { using (var context = new BookloverBookContext( serviceProvider.GetRequiredService< DbContextOptions<BookloverBookContext>>())) { DateTime currentTime = DateTime.Now; // Look for any data availability. If not add data to the table if (!context.Author.Any()) { logger.Debug("Seeding authors data"); context.Author.AddRange( new Author { Name = "Robert T. Kiyosaki", ImageUrl = "https://images-na.ssl-images-amazon.com/images/I/31H4fUBky1L._US230_.jpg", Bio = "Robert Kiyosaki, author of Rich Dad Poor Dad - the international runaway bestseller that has held a top spot on the New York Times bestsellers list for over six years - is an investor, entrepreneur and educator whose perspectives on money and investing fly in the face of conventional wisdom.", CreatedTime = currentTime, ModifiedTime = currentTime }, new Author { Name = "Delia Owens", ImageUrl = "https://i2.wp.com/www.mysterytribune.com/wp-content/uploads/2019/01/Delia-Owens-Profile-Of-Where-the-Crawdads-Sing-Author.jpg?fit=770%2C954&ssl=1", Bio = "Delia Owens is an American author and zoologist. Her debut novel Where the Crawdads Sing topped The New York Times Fiction Best Sellers of 2019 for several weeks. The book has been on the New York Times Bestsellers list for more than a year.", CreatedTime = currentTime, ModifiedTime = currentTime }, new Author { Name = "Dalai Lama", ImageUrl = "https://images-na.ssl-images-amazon.com/images/I/31vccKBNfgL._US230_.jpg", Bio = "His Holiness the Fourteenth Dalai Lama, Tenzin Gyatso, was born in 1935 to a peasant family in northeastern Tibet and was recognized at the age of two as the reincarnation of his predecessor, the Thirteenth Dalai Lama.", CreatedTime = currentTime, ModifiedTime = currentTime }, new Author { Name = "Michelle Obama", ImageUrl = "https://images-na.ssl-images-amazon.com/images/I/81gqDyw-wvL._US230_.jpg", Bio = "Michelle Robinson Obama served as First Lady of the United States from 2009 to 2017. A graduate of Princeton University and Harvard Law School, Mrs. Obama started her career as an attorney at the Chicago law firm Sidley & Austin, where she met her future husband, Barack Obama. ", CreatedTime = currentTime, ModifiedTime = currentTime }, new Author { Name = "David Allen", ImageUrl = "https://images-na.ssl-images-amazon.com/images/I/41qA2b-WslL._US230_.jpg", Bio = "David Allen is widely recognized as the world's leading expert on personal and organizational productivity. His thirty-year pioneering research and coaching to corporate managers and CEOs of some of America's most prestigious corporations and institutions has earned him Forbes' recognition as one of the top five executive coaches in the U.S. and Business 2.0 magazine's inclusion in their 2006 list of the '50 Who Matter Now.'", CreatedTime = currentTime, ModifiedTime = currentTime }, new Author { Name = "J. K. Rowling", ImageUrl = "https://images-na.ssl-images-amazon.com/images/S/amzn-author-media-prod/fvh43djng407r1iq142ng0sk5f._US230_.jpg", Bio = "J.K. Rowling is the author of the record-breaking, multi-award-winning Harry Potter novels. Loved by fans around the world, the series has sold more than 500 million copies, been translated into 80 languages and made into eight blockbuster films.", CreatedTime = currentTime, ModifiedTime = currentTime }, new Author { Name = "Simon Sinek", ImageUrl = "https://images-na.ssl-images-amazon.com/images/I/51yMIHz8PSL._US230_.jpg", Bio = "Simon Sinek is an optimist. He teaches leaders and organizations how to inspire people. From members of Congress to foreign ambassadors, from small businesses to corporations like Microsoft and 3M, from Hollywood to the Pentagon, he has presented his ideas about the power of why.", CreatedTime = currentTime, ModifiedTime = currentTime } ); context.SaveChanges(); } if (!context.Book.Any()) { logger.Debug("Seeding books data"); context.Book.AddRange( new Book { Title = "Where the Crawdads Sing", Thumbnail = "https://images-na.ssl-images-amazon.com/images/I/51qtXBoiv8L.jpg", AuthorId = 2, Price = 13, CreatedTime = currentTime, ModifiedTime = currentTime }, new Book { Title = "The Book of Joy: Lasting Happiness in a Changing World", Thumbnail = "https://images-na.ssl-images-amazon.com/images/I/91XrIUJA9aL.jpg", AuthorId = 3, Price = 9, CreatedTime = currentTime, ModifiedTime = currentTime } , new Book { Title = "Becoming", Thumbnail = "https://images-na.ssl-images-amazon.com/images/I/81h2gWPTYJL.jpg", AuthorId = 4, Price = 13, CreatedTime = currentTime, ModifiedTime = currentTime } , new Book { Title = "Rich Dad Poor Dad", Thumbnail = "https://images-na.ssl-images-amazon.com/images/I/91VokXkn8hL.jpg", AuthorId = 1, Price = 13, CreatedTime = currentTime, ModifiedTime = currentTime } , new Book { Title = "Rich Dad's CASHFLOW Quadrant: Rich Dad's Guide to Financial Freedom", Thumbnail = "https://images-na.ssl-images-amazon.com/images/I/41aJnFuCBWL.jpg", AuthorId = 1, Price = 12, CreatedTime = currentTime, ModifiedTime = currentTime } , new Book { Title = "Rich Dad's Guide to Investing", Thumbnail = "https://images-na.ssl-images-amazon.com/images/I/916O61iZWVL.jpg", AuthorId = 1, Price = 11, CreatedTime = currentTime, ModifiedTime = currentTime } , new Book { Title = "Getting Things Done: The Art of Stress-Free Productivity", Thumbnail = "https://images-na.ssl-images-amazon.com/images/I/51bGhYfO9KL._SX342_.jpg", AuthorId = 5, Price = 14, CreatedTime = currentTime, ModifiedTime = currentTime } , new Book { Title = "Making It All Work: Winning at the game of work and the business of life", Thumbnail = "https://images-na.ssl-images-amazon.com/images/I/51BVTXhMgKL.jpg", AuthorId = 5, Price = 9, CreatedTime = currentTime, ModifiedTime = currentTime } , new Book { Title = "Harry Potter and the Goblet of Fire: The Illustrated Edition", Thumbnail = "https://images-na.ssl-images-amazon.com/images/I/61Me3ePpM9L._SX421_BO1,204,203,200_.jpg", AuthorId = 6, Price = 13, CreatedTime = currentTime, ModifiedTime = currentTime } , new Book { Title = "Harry Potter and the Chamber of Secrets", Thumbnail = "https://images-na.ssl-images-amazon.com/images/I/51OihdkhSBL._SX329_BO1,204,203,200_.jpg", AuthorId = 6, Price = 15, CreatedTime = currentTime, ModifiedTime = currentTime } , new Book { Title = "Harry Potter and the Sorcerer's Stone", Thumbnail = "https://images-na.ssl-images-amazon.com/images/I/51HSkTKlauL._SX346_BO1,204,203,200_.jpg", AuthorId = 6, Price = 13, CreatedTime = currentTime, ModifiedTime = currentTime } , new Book { Title = "Start with Why: How Great Leaders Inspire Everyone to Take Action", Thumbnail = "https://images-na.ssl-images-amazon.com/images/I/71QUhm-AnIL.jpg", AuthorId = 7, Price = 13, CreatedTime = currentTime, ModifiedTime = currentTime } , new Book { Title = "The Infinite Game", Thumbnail = "https://images-na.ssl-images-amazon.com/images/I/41xC6fNkf2L._SX294_BO1,204,203,200_.jpg", AuthorId = 7, Price = 8, CreatedTime = currentTime, ModifiedTime = currentTime } , new Book { Title = "Leaders Eat Last: Why Some Teams Pull Together and Others Don't", Thumbnail = "https://images-na.ssl-images-amazon.com/images/I/518JdacNycL._SX330_BO1,204,203,200_.jpg", AuthorId = 7, Price = 13, CreatedTime = currentTime, ModifiedTime = currentTime } , new Book { Title = "The Art of Happiness, 10th Anniversary Edition: A Handbook for Living", Thumbnail = "https://images-na.ssl-images-amazon.com/images/I/71zNTPjajaL.jpg", AuthorId = 3, Price = 13, CreatedTime = currentTime, ModifiedTime = currentTime } , new Book { Title = "Beyond Religion: Ethics for a Whole World", Thumbnail = "https://images-na.ssl-images-amazon.com/images/I/51-W1m2z4WL.jpg", AuthorId = 3, Price = 11, CreatedTime = currentTime, ModifiedTime = currentTime } , new Book { Title = "The Dalai Lama's Cat", Thumbnail = "https://images-na.ssl-images-amazon.com/images/I/41BsepZU24L.jpg", AuthorId = 3, Price = 18, CreatedTime = currentTime, ModifiedTime = currentTime } , new Book { Title = "The Tales of Beedle the Bard: The Illustrated Edition (Harry Potter)", Thumbnail = "https://images-na.ssl-images-amazon.com/images/I/71Nav-k%2B71L.jpg", AuthorId = 6, Price = 16, CreatedTime = currentTime, ModifiedTime = currentTime } , new Book { Title = "Harry Potter Paperback Box Set (Books 1-7)", Thumbnail = "", AuthorId = 6, Price = 52, CreatedTime = currentTime, ModifiedTime = currentTime } , new Book { Title = "Rich Dad's Increase Your Financial IQ: Get Smarter with Your Money", Thumbnail = "https://images-na.ssl-images-amazon.com/images/I/514j-05vuZL._SX342_.jpg", AuthorId = 1, Price = 13, CreatedTime = currentTime, ModifiedTime = currentTime } ); context.SaveChanges(); } } } } }
Python
UTF-8
1,780
4.125
4
[]
no_license
#30th January class import random as r print(r.random()) #between 0 and 1 random value is generateed print(r.uniform(1,10)) dice = [1,2,3,4,5,6]; print(r.choice(dice)) print(r.choice([1,2,3,4,5,6])) print (r.sample(dice,2)) # population and size it takes #it will take 2 values from the dice r.shuffle(dice) print (dice) #shufffe modifies the original data itself, does not return any value #-----------------------------------------Strings begin--------------------------------------------- '''There are three kinds of strings - 1) "" or '' must be in a single line the whole string because the python interpreter treats the nerw line character as a end of string ''' #2)d = ''' this is #a multiline string ''' d= ''' this is a multi line string''' print (d) #3) Documentation string - __doc__ will store the first triple quote string in the programming print(__doc__) print (r.seed.__doc__) #4)Raw String - does not interpret a new kine character s='abc\ndef' print (s) # simple string will treat \n as new line character s=r'abc\ndef' print(s) #operations -- #length - len() #concatenate - + #replicate - * #access : indexing - 0 based indexing ''' _0_1_2_3_4_5_6________ |G|o|o|d|b|y|e| ''' #slicing - s='Goodbye' print(len(s)) #len is a free function - free function is a function which is available to all the #objects i.e. it can be used for any collection of data print (s[1:5],s) #slicing print (s[1:5:2],s) #extended slicing str[start:stop:step] print(s[5:1:-2],s) #negaitve step #if the step is not given in the avve exapmle then it will print an empty string #negative indexing print(s[-1]) #print(s[len(s)-1]) print ("Hello") print(s[-1:-5:-1]) #give the reverse string print(s[::-1]) #reverse the entire string, start as -1 and end as -8
JavaScript
UTF-8
921
4.125
4
[]
no_license
// This parse - args file should export a single function to parse your command line arguments.The function should accept an array containing the arguments passed on the command line. Convert these arguments to an object with a count and sides property. 'use strict'; module.exports = (args) => { let count = null; let sides = null; // if there are no arguments passed in, roll one six-sided dice if(args.length === 0){ count = 1; sides = 6; } else if (args.length === 1) { // if only one arguemnt is passed in, that becomes the number of sides on the dice count = 1; sides = args[0]; } else if (args.length === 2){ // if two arguments are passed in, the first one is the number of times you roll the dice and the second argument is the number of sides count = args[0]; sides = args[1]; } else { return console.log("Please pass in no more than two numbers!") } let dice = {count, sides}; return dice; }
Java
UTF-8
5,908
2.546875
3
[]
no_license
package logic; import android.util.JsonReader; import com.google.gson.Gson; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import data.model.Incidencia; import data.model.Ruta; public class ParserJSON { // Clase para aislar el Leer un JSON del Direction Finder, y usarla en las incidencias. // -------- GSON -------- (OPCIONAL) // Parser JSON para la RUTA - GSON (Se ha añadido el 'compile' en el gradle y la librería) public List<Ruta> leerFlujoJsonRuta(InputStream in) throws IOException { // Nueva instancia de la clase Gson Gson gson = new Gson(); JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8")); List<Ruta> rutas = new ArrayList<>(); // Iniciar el array reader.beginArray(); while (reader.hasNext()) { // Lectura de objetos Ruta ruta = gson.fromJson(String.valueOf(reader), Ruta.class); // Era sin valueOf, para corregir el error lo he puesto. rutas.add(ruta); } reader.endArray(); reader.close(); return rutas; } // ------- JSON ------- // Parser JSON para las INCIDENCIAS public List<Incidencia> leerFlujoJsonIncidencia(InputStream in) throws IOException { // Nueva instancia JsonReader JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8")); try { // Leer Array return leerArrayIncidencias(reader); } finally { reader.close(); } } public List<Incidencia> leerArrayIncidencias(JsonReader reader) throws IOException { // Lista temporal ArrayList<Incidencia> incidencias = new ArrayList<>(); reader.beginArray(); while (reader.hasNext()) { // Leer objeto incidencias.add(leerIncidencia(reader)); } reader.endArray(); return incidencias; } public Incidencia leerIncidencia(JsonReader reader) throws IOException { // Variables locales String carretera = null; Integer estado = null; String alias = null; String sentido = null; Double PK = null; String tipo = null; Double lng = null; String codEle = null; Double lat = null; String precision = null; String fecha = null; String poblacion = null; String descripcion = null; String fechaFin = null; String tipoInci = null; Integer pkFinal = null; String provincia = null; String causa = null; String hora = null; Integer pkIni = null; String icono = null; String horaFin = null; String nivel = null; // Iniciar objeto reader.beginObject(); // Lectura de cada atributo while (reader.hasNext()) { String name = reader.nextName(); switch (name) { case "carretera": carretera = reader.nextString(); break; case "estado": estado = reader.nextInt(); break; case "alias": alias = reader.nextString(); break; case "sentido": sentido = reader.nextString(); break; case "PK": PK = reader.nextDouble(); break; case "tipo": tipo = reader.nextString(); break; case "lng": lng = reader.nextDouble(); break; case "codEle": codEle = reader.nextString(); break; case "lat": lat = reader.nextDouble(); break; case "precision": precision = reader.nextString(); break; case "fecha": fecha = reader.nextString(); break; case "poblacion": poblacion = reader.nextString(); break; case "descripcion": descripcion = reader.nextString(); break; case "fechaFin": fechaFin = reader.nextString(); break; case "tipoInci": tipoInci = reader.nextString(); break; case "pkFinal": pkFinal = reader.nextInt(); break; case "provincia": provincia = reader.nextString(); break; case "causa": causa = reader.nextString(); break; case "hora": hora = reader.nextString(); break; case "pkIni": pkIni = reader.nextInt(); break; case "icono": icono = reader.nextString(); break; case "horaFin": horaFin = reader.nextString(); break; case "nivel": nivel = reader.nextString(); break; default: reader.skipValue(); break; } } reader.endObject(); return new Incidencia(carretera, estado, alias, sentido, PK, tipo, lng, codEle, lat, precision, fecha, poblacion, descripcion, fechaFin, tipoInci, pkFinal, provincia, causa, hora, pkIni, icono, horaFin, nivel); } }
C
UTF-8
1,355
2.75
3
[ "MIT" ]
permissive
#include "unity.h" #include "HttpRequest.h" #include <string.h> #include <stdio.h> #include <stdlib.h> void setUp(){ } void tearDown(){ } void parseHeaderTest_GET(void){ char const req[] = "GET / HTTP/1.1\r\n\ Host: 192.168.1.65:5001\r\n\ User-Agent: curl/7.55.0\r\n\ Accept: */*\r\n\ Content-Type: application/x-www-form-urlencoded"; HttpHeader *header = parseHeader(req); TEST_ASSERT_EQUAL(0, strcmp(header->path, "/")); TEST_ASSERT_EQUAL(0, header->contentLength); TEST_ASSERT_EQUAL(HTTP_REQ_GET, header->method); freeHttpHeader(header); } void parseHeaderTest_POST(void){ char const req[] = "POST /led HTTP/1.1\r\n\ Host: 192.168.1.65:5001\r\n\ User-Agent: curl/7.55.0\r\n\ Accept: */*\r\n\ Content-Length: 26\r\n\ Content-Type: application/x-www-form-urlencoded\r\n\r\n\ red=on&green=on&orange=off"; HttpHeader *header = parseHeader(req); TEST_ASSERT_EQUAL(0, strcmp(header->path, "/led")); TEST_ASSERT_EQUAL(26, header->contentLength); TEST_ASSERT_EQUAL(HTTP_REQ_POST, header->method); TEST_ASSERT_EQUAL(0, strcmp(header->contentType, "application/x-www-form-urlencoded")); // Must discount escape characters TEST_ASSERT_EQUAL(154, header->bodyStart); freeHttpHeader(header); } int main(void) { UNITY_BEGIN(); RUN_TEST(parseHeaderTest_GET); RUN_TEST(parseHeaderTest_POST); return UNITY_END(); }
JavaScript
UTF-8
720
2.625
3
[]
no_license
const express = require('express'); const app = express() app.use(express.json()); app.listen(3000, () => console.log('Example app listening on port 3000!')) app.get('/', (req, res) => { console.log("started!") }) app.post('/', function (req, res) { console.log(req); // let action = req.body.queryResult.action; // console.log(action); //let responseJson = {}; //responseJson.fulfillmentText = 'Hit the webhook!'; // displayed response var responseJson= { "fulfillmentMessages": [ { "text": { "text": [ "Text response from webhook" ] } } ] } res.send(responseJson) })
C#
UTF-8
1,800
2.625
3
[ "Apache-2.0" ]
permissive
// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // 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. namespace Castle.Components.DictionaryAdapter { using System; using System.Collections.Generic; public class GenericDictionaryAdapter<TValue> : AbstractDictionaryAdapter { private readonly IDictionary<string, TValue> dictionary; public GenericDictionaryAdapter(IDictionary<string, TValue> dictionary) { this.dictionary = dictionary; } public override bool IsReadOnly { get { return dictionary.IsReadOnly; } } public override bool Contains(object key) { return dictionary.Keys.Contains(GetKey(key)); } public override object this[object key] { get { TValue value; return dictionary.TryGetValue(GetKey(key), out value) ? value : default(TValue); } set { dictionary[GetKey(key)] = (TValue)value; } } private static string GetKey(object key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } return key.ToString(); } } public static class GenericDictionaryAdapter { public static GenericDictionaryAdapter<TValue> ForDictionaryAdapter<TValue>(this IDictionary<string, TValue> dictionary) { return new GenericDictionaryAdapter<TValue>(dictionary); } } }
Rust
UTF-8
2,206
2.640625
3
[ "MIT" ]
permissive
use core::str; use spin::Mutex; pub use self::debug::DebugDisplay; use self::display::Display; pub mod debug; pub mod display; pub static FONT: &[u8] = include_bytes!("../../../res/unifont.font"); pub static DEBUG_DISPLAY: Mutex<Option<DebugDisplay>> = Mutex::new(None); pub static FRAMEBUFFER: Mutex<(usize, usize, usize)> = Mutex::new((0, 0, 0)); pub fn init(env: &[u8]) { println!("Starting graphical debug"); let mut phys = 0; let mut virt = 0; let mut width = 0; let mut height = 0; let mut stride = 0; //TODO: should errors be reported? for line in str::from_utf8(env).unwrap_or("").lines() { let mut parts = line.splitn(2, '='); let name = parts.next().unwrap_or(""); let value = parts.next().unwrap_or(""); if name == "FRAMEBUFFER_ADDR" { phys = usize::from_str_radix(value, 16).unwrap_or(0); } if name == "FRAMEBUFFER_VIRT" { virt = usize::from_str_radix(value, 16).unwrap_or(0); } if name == "FRAMEBUFFER_WIDTH" { width = usize::from_str_radix(value, 16).unwrap_or(0); } if name == "FRAMEBUFFER_HEIGHT" { height = usize::from_str_radix(value, 16).unwrap_or(0); } if name == "FRAMEBUFFER_STRIDE" { stride = usize::from_str_radix(value, 16).unwrap_or(0); } } *FRAMEBUFFER.lock() = (phys, virt, stride * height * 4); if phys == 0 || virt == 0 || width == 0 || height == 0 || stride == 0 { println!("Framebuffer not found"); return; } println!("Framebuffer {}x{} stride {} at {:X} mapped to {:X}", width, height, stride, phys, virt); { let display = Display::new(width, height, stride, virt as *mut u32); let debug_display = DebugDisplay::new(display); *DEBUG_DISPLAY.lock() = Some(debug_display); } } pub fn init_heap() { if let Some(debug_display) = &mut *DEBUG_DISPLAY.lock() { debug_display.display.offscreen = Some( debug_display.display.onscreen.to_vec().into_boxed_slice() ); } } pub fn fini() { DEBUG_DISPLAY.lock().take(); println!("Finished graphical debug"); }
PHP
UTF-8
533
2.625
3
[]
no_license
<?php session_start(); include_once('connection.php'); if($_POST['name'] == NULL || $_POST['quote'] == NULL) { $_SESSION['message'] = "Please fill out all information in fields"; header("Location: quotingdojoindex.php"); exit(); // exits the page if either field is left empty. } else //add to our database. { $query = "INSERT INTO quotes (name, text, created_at) VALUES('{$_POST['name']}', '{$_POST['quote']}', NOW())"; run_mysql_query($query); header("Location: main.php"); exit(); } ?>
Markdown
UTF-8
217
2.640625
3
[]
no_license
# Heat Equation Used Python to Solve the heat equation below using the methods: - The Forward Time Centered Space Method(Explicit); - The Backward Time Centered Space Method(Implicit); - Crank-Nicolson(Implicit);
C
UTF-8
4,646
2.96875
3
[ "MIT" ]
permissive
#include <stdlib.h> #include <string.h> #include <math.h> #include "blackjack.h" typedef enum blackjack_result_t_ { BLACKJACK_DEALER_BUST = 2, BLACKJACK_WIN = 1, BLACKJACK_DRAW = 0, BLACKJACK_LOSE = -1, BLACKJACK_PLAYER_BUST = -2 } blackjack_result_t; int blackjack_get_hand_score( blackjack_card_t *hand, int hand_length ) { int aces, score, i; for (i = 0, score = 0, aces = 0; i < hand_length; i++) { switch (hand[i]) { case BLACKJACK_JACK: case BLACKJACK_QUEEN: case BLACKJACK_KING: score += 10; break; case BLACKJACK_ACE: score += 11; aces++; break; default: score += hand[i]; break; } } while (score > 21 && aces > 0) { score -= 10; aces--; } return score; } blackjack_result_t blackjack_get_result( blackjack_card_t *hand, int hand_length, blackjack_card_t *dealer_hand, int dealer_hand_length ) { int player_score, dealer_score; player_score = blackjack_get_hand_score(hand, hand_length); dealer_score = blackjack_get_hand_score(dealer_hand, dealer_hand_length); if (player_score > 21) { return BLACKJACK_PLAYER_BUST; } if (dealer_score > 21) { return BLACKJACK_DEALER_BUST; } if (player_score > dealer_score) { return BLACKJACK_WIN; } if (player_score < dealer_score) { return BLACKJACK_LOSE; } return BLACKJACK_DRAW; } void blackjack_simulate_dealer( blackjack_card_t *deck, int deck_length, blackjack_card_t *dealer_hand, int *dealer_hand_length ) { while (blackjack_get_hand_score(dealer_hand, *dealer_hand_length) <= 16) { dealer_hand[*dealer_hand_length] = *deck; (*dealer_hand_length)++, deck++, deck_length--; } } blackjack_result_t blackjack_simulate_stand( blackjack_card_t *deck, int deck_length, blackjack_card_t *hand, int hand_length, blackjack_card_t dealer_card ) { blackjack_card_t dealer_hand[BLACKJACK_MAX_HAND_LENGTH]; int dealer_hand_length = 1; dealer_hand[0] = dealer_card; blackjack_simulate_dealer(deck, deck_length, dealer_hand, &dealer_hand_length); return blackjack_get_result(hand, hand_length, dealer_hand, dealer_hand_length); } blackjack_result_t blackjack_simulate_hit( blackjack_card_t *deck, int deck_length, blackjack_card_t *hand, int hand_length, blackjack_card_t dealer_card ) { blackjack_card_t dealer_hand[BLACKJACK_MAX_HAND_LENGTH]; int dealer_hand_length = 1; dealer_hand[0] = dealer_card; hand[hand_length] = *deck; hand_length++, deck++, deck_length--; blackjack_simulate_dealer(deck, deck_length, dealer_hand, &dealer_hand_length); return blackjack_get_result(hand, hand_length, dealer_hand, dealer_hand_length); } void blackjack_shuffle_cards( blackjack_card_t *cards, int length ) { blackjack_card_t temp; int i, j, k; for (k = 0; k < 10; k++) { for (i = 0; i < length; i++) { j = rand() % length; temp = cards[i % length]; cards[i] = cards[j]; cards[j] = temp; } } } void blackjack_run_simulations( blackjack_card_t *deck, int deck_length, blackjack_card_t *hand, int hand_length, blackjack_card_t dealer_card, blackjack_simulation_results_t *results, int simulations ) { blackjack_result_t result; memset(results, 0, sizeof(blackjack_simulation_results_t)); while (simulations--) { blackjack_shuffle_cards(deck, deck_length); result = blackjack_simulate_stand(deck, deck_length, hand, hand_length, dealer_card); switch (result) { case BLACKJACK_DEALER_BUST: results->stand_dealer_bust++; // fall through case BLACKJACK_WIN: results->stand_wins++; break; case BLACKJACK_DRAW: results->stand_draws++; break; case BLACKJACK_PLAYER_BUST: // shouldn't happen, fall through case BLACKJACK_LOSE: results->stand_loses++; break; } result = blackjack_simulate_hit(deck, deck_length, hand, hand_length, dealer_card); switch (result) { case BLACKJACK_DEALER_BUST: results->hit_dealer_bust++; // fall through case BLACKJACK_WIN: results->hit_wins++; break; case BLACKJACK_DRAW: results->hit_draws++; break; case BLACKJACK_PLAYER_BUST: results->hit_bust++; // fall through case BLACKJACK_LOSE: results->hit_loses++; break; } } }
JavaScript
UTF-8
2,924
2.90625
3
[]
no_license
/*Funcao de mascara campos */ function mascaravalor(src, mask){ var i = src.value.length; var saida = mask.substring(1,2); var texto = mask.substring(i); if (texto.substring(0,1) != saida){ src.value += texto.substring(0,1); } } function confirmarRemover() { if( confirm("Deseja realmente excluir ?") ) { return true; } return false; } function Limpar(valor, validos) { // retira caracteres invalidos da string var result = ""; var aux; for (var i=0; i < valor.length; i++) { aux = validos.indexOf(valor.substring(i, i+1)); if (aux>=0) { result += aux; } } return result; } function entra(){ document.getElementById("cliente:botaobuscar").click(); } function avisobordero(){ if (cont == 1){ window.alert("ANTES DE INSERIR UM OU MAIS BORDEROS POR FAVOR CLICK NO BOT�O ATUALIZAR DA PRIMEIRA ABA PELOS MENOS UMA VEZ!"); cont++; } } function avisografico(){ if(cont1==1){ window.alert("ANTES DE GERAR OS GRÁFICOS POR FAVOR CLICK NO BOT�O ATUALIZAR DA PRIMEIRA ABA PELO MENOS UMA VEZ!"); cont1++; } } function sair() { window.alert("Obrigado por usar o sistema de consulta de cobran�a via web volte sempre."); } /** function verificavazio(form){ var campo=form[form.id+":obs1"].value; if(campo==""){ window.alert("Atencao o campo esta vazio"); return false; }else{ return true; form.submit(); } } */ function fechajanela(janela){ window.close(); } function fecha(){ window.close(); } function relertela(){ location.reload(true); } function verificavazio(campo){ if (campo==""){ window.alert("O campo "+campo+" está vazio"); return false; } else{ return true; } } //Mostra a solitacao finalizada function Finalizada(){ window.alert("Sua solicião foi finalizada com sucesso!!"); } //Verifica a hora da solicitacao function VerificaHora(campo){ var hora=campo.value; var min=campo.value; var num = parseInt(hora.substring(0,2)); var min2 = parseInt(min.substring(3,5)); if ((num > 19 || num < 7) || min2 > 60){ window.alert("A HORA ESTA FORA DE PADRAO!"); return false; }else{ return true; } } //Esconde o tipo //Escode uma div function escondetiposoli(divesconde,valor) { // var valor = $(divesconde +" option:selected"); var recebe=$(valor +" option:selected"); var rec = recebe.text().search("AUDIENCIA"); if (rec==0) { $(divesconde).show().delay(2000).fadeIn(); } else if (rec==-1) { $(divesconde).hide().delay(2000).fadeOut(); } } //Escode uma div function esconde1(divesconde,esconde) { var valor = $(divesconde +" option:selected"); if (valor.val() == 3) { $(esconde).show(); } else { $(esconde).hide(); } } //Copia valor function copiavalor(valororigem,valordestino){ var select = $(valororigem+" option:selected"); $(valordestino).val(select.text()); }
Swift
UTF-8
4,976
2.828125
3
[]
no_license
// // BaseView.swift // CurvedTabBar // // Created by Kritbovorn Taweeyossak on 28/9/2563 BE. // import SwiftUI struct BaseView<Content: View>: View { var content: Content var indexSelected: Binding<Int> init(index: Binding<Int>, @ViewBuilder content: () -> Content) { self.content = content() self.indexSelected = index } var body: some View { GeometryReader { main in VStack(spacing: 0) { // FIXME: - First GeometryReader { first in VStack(spacing: 0) { // FIXME: - Content content } .ignoresSafeArea(.all, edges: .top) } .frame(height: main.size.height * 0.92) // FIXME: - Second GeometryReader { second in CustomTabs(metric: second, index: indexSelected) .frame(width: second.size.width, height: second.size.height) } .frame(height: main.size.height * 0.08) .background(Color.white) } .padding(.top, UIApplication.shared.windows.first?.safeAreaInsets.top) .background(Color.black.opacity(0.05)) .ignoresSafeArea(.all, edges: .all) } } } struct BaseView_Previews: PreviewProvider { static var previews: some View { BaseView(index: .constant(0)) { Text("Boie") } } } // FIXME: - Button TabViews struct CustomTabs: View { var metric: GeometryProxy @Binding var index: Int func proxyHeight(for metric: GeometryProxy) -> CGFloat { let proxyHeight = metric.size.height * 0.26 return proxyHeight } func proxyHeightSelected(for metric: GeometryProxy) -> CGFloat { let proxyHeight = metric.size.height * 0.4 return proxyHeight } func proxyHeightest(for metric: GeometryProxy) -> CGFloat { let proxyHeight = metric.size.height * 0.9 return proxyHeight } var body: some View { HStack { ButtonTabView(metric: metric, imageName: "house.fill", index: 0, indexSelected: $index) Spacer() ButtonTabView(metric: metric, imageName: "magnifyingglass.circle.fill", index: 1, indexSelected: $index) .offset(x: proxyHeightSelected(for: metric)) Spacer() // FIXME: - Plus Button Button(action: { }, label: { Image(systemName: "plus.circle.fill") .font(.system(size: proxyHeightest(for: metric), weight: .bold)) .foregroundColor(.blue) }) .padding() .background(Color.white) .clipShape(Circle()) .offset(y: -proxyHeight(for: metric) * 2) Spacer() ButtonTabView(metric: metric, imageName: "heart.circle", index: 2, indexSelected: $index) .offset(x: -proxyHeightSelected(for: metric)) Spacer() ButtonTabView(metric: metric, imageName: "person.fill", index: 3, indexSelected: $index) } .padding(.horizontal, proxyHeight(for: metric)) } } // FIXME: - Button Object struct ButtonTabView: View { var metric: GeometryProxy var imageName: String var index: Int @Binding var indexSelected: Int func proxyHeight(for metric: GeometryProxy) -> CGFloat { let proxyHeight = metric.size.height * 0.45 return proxyHeight } func proxyHeightSelected(for metric: GeometryProxy) -> CGFloat { let proxyHeight = metric.size.height * 0.55 return proxyHeight } var body: some View { Button(action: { withAnimation { indexSelected = index } }, label: { Image(systemName: imageName) .font(.system(size: index == indexSelected ? proxyHeightSelected(for: metric) : proxyHeight(for: metric), weight: .bold)) .foregroundColor(Color.black.opacity(index == indexSelected ? 1 : 0.3)) .frame(width: proxyHeight(for: metric), height: proxyHeight(for: metric) ) }) } } // FIXME: - 1. ต้อง ประกาศ ตัวแปร State private var : ไว้ที่หน้ารับค่า เพื่อ รับรู้ว่า อยู่ที่ index ตัวไหน // @State private var index: Int = 0
Python
UTF-8
385
3.40625
3
[]
no_license
a = int(input()) b = int(input()) c = int(input()) volume = a * b * c has_volume = True box = input() while not box == 'Done': box = int(box) volume -= box if volume < 0: has_volume = False break box = input() if has_volume: print(f'{volume} Cubic meters left.') else: print(f'No more free space! You need {abs(volume)} Cubic meters more.')
Python
UTF-8
1,436
2.765625
3
[]
no_license
from math import log, exp, sqrt from numpy import maximum, cumsum, mean from scipy import stats c = 0 def bsformula(callput, S0, K, r, T, sigma, q=0): global c c = c + 1 d1 = (log(S0) - log(K) + (r + 0.5 * sigma ** 2) * T) / (sigma * sqrt(T)) d2 = (log(S0) - log(K) + (r - 0.5 * sigma ** 2) * T) / (sigma * sqrt(T)) if callput == 1: value = (S0 * exp( - q * T ) * stats.norm.cdf(d1, 0.0, 1.0) - K * exp( - r * T ) * stats.norm.cdf(d2,0.0,1.0)) delta = stats.norm.cdf(d1) vega = (S0 * exp( - q * T) * stats.norm.pdf(d1) * (( - 1 / (sqrt(T) * sigma ** 2) * (log(S0) - log(K)) - r * sqrt(T)/sigma ** 2) + 0.5 * sqrt(T)) - K * exp(-r * T) * (-1/(sqrt(T) * sigma ** 2) * (log(S0) - log(K)) - r * sqrt(T) / sigma ** 2 - 0.5 * sqrt(T)) * stats.norm.pdf(d2)) elif callput == -1: value = K * exp(- r * T) * stats.norm.cdf(-d2, 0.0, 1.0) - S0 * exp(- q * T) * stats.norm.cdf(-d1, 0.0, 1.0) delta = -stats.norm.cdf(-d1) vega = (- S0 * exp( - q * T) * stats.norm.pdf( - d1) * ((1 / (sqrt(T) * sigma ** 2) * (log(S0) - log(K)) + r * sqrt(T) / sigma ** 2) - 0.5 * sqrt(T)) + K * exp(-r * T) * (1 / (sqrt(T) * sigma ** 2) * (log(S0) - log(K)) + r * sqrt(T) / sigma ** 2 + 0.5 * sqrt(T)) * stats.norm.pdf(-d2)) tuple = ('value', value, 'delta', delta, 'vega', vega) return tuple print(bsformula(1, 100, 105, 0.01, 1, 0.2, 0)) print(bsformula(-1, 100, 105, 0.01, 1, 0.2, 0))
Python
UTF-8
4,378
2.59375
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2020-03-12 11:41 # @Author : fgyong 简书:_兜兜转转_ https://www.jianshu.com/u/6d1254c1d145 # @Site : http://fgyong.cn 兜兜转转的技术博客 # @File : create.py # @Software: PyCharm from PIL import Image import os import sys import config import json savePath = "" jsonArr = [] def create(): im = originImg if len(sys.argv)<3: path = outPutPath# 创建文件夹 if not os.path.exists(outPutPath): os.mkdir(outPutPath) print( '\033[31m' +"已在桌面创建文件夹AppIcon" + '\033[0m') sizes = config.imageSizes for i in sizes: createSize(i, im, path=path,times=1) appJson(i,times=1) for i in config.imageSizesDouble: createSize(i, im, path=path,times=2) appJson(i, times=2) for i in config.imageSizesThree: createSize(i, im, path=path,times=3) appJson(i, times=3) print('\033[31m' +"✅ AppIcon 图片已生成 🍺🍺🍺🏃" + '\033[0m') print('\033[31m' + "✅ 目录为"+path+" 🍺🍺🍺🏃" + '\033[0m') lastDic = dict() lastDic["images"]=jsonArr lastDic["info"]= {"version":1, "athor":"xcode"} createjosn(path,lastDic) def createjosn(path,js): allpath = path+"Contents.json" # if os._exists(allpath): if os.path.isfile(allpath): os.remove(allpath)#删除旧文件 os.system('touch allpath') f = open(path+"Contents.json",'a') if f.write(json.dumps(js))>0: print('\033[31m' + "✅ json文件写入成功 🍺🍺🍺🏃" + '\033[0m') # 追加json 数据 def appJson(i,times): for index in range(2,len(i)): dic = dict() dic["size"] = str(i[0]) + "x" + str(i[1]) dic["filename"] = name(i, times=times) dic["scale"] = str(times) + "x" dic["idiom"] = i[index] jsonArr.append(dic) def createSize(size,im,path,times): im2 = im.resize((int(size[0] * times), int(size[1] * times))) # 创建缩略图 im2.save(path+name(size,times)) def name(size,times): if times == 1: return "APPIcon"+str(size[0]) +"X" +str(size[1])+".png" else: return "APPIcon"+str(size[0]) +"X" +str(size[1])+"@"+str(times)+".png" try: from PIL import Image except: print ('\033[31m' + '缺少Image模块,正在安装Image模块,请等待...' + '\033[0m') success = os.system('python -m pip install Image') if success == 0: print('\033[7;32m' + 'Image模块安装成功.' + '\033[0m') from PIL import Image else: print ('\033[31m' + 'Image安装失败,请手动在终端执行:\'python -m pip install Image\'重新安装.' + '\033[0m') quit() outPutPath = os.path.expanduser('~') + '/Desktop/AppIcon/' # if not os.path.exists(outPutPath): # os.mkdir(outPutPath) # if len(sys.argv) <= 1: # print ('\033[31m' + '请输入图片路径,eg: python autoExportAppIcon.py /path/xxx.png' + '\033[0m') # quit() # # ImageName = sys.argv[1] # # print('图片名字为:' + ImageName) originImg = Image.open('/Users/Jerry/Desktop/12.jpeg') # try: # originImg = Image.open(ImageName) # except: # print ('\033[31m' + '\'' + ImageName + '\'' + ',该文件不是图片文件,请检查文件路径.' + '\033[0m') # quit() # 检查第三方包是否安装 def check_requirement(package): try: exec("import {0}".format(package)) except ModuleNotFoundError: inquiry = input("This script requires {0}. Do you want to install {0}? [y/n]".format(package)) while (inquiry != "y") and (inquiry != "n") and (inquiry != "N") and (inquiry != "Y") : inquiry = input("This script requires {0}. Do you want to install {0}? [y/n]".format(package)) if inquiry == "y" or inquiry == "Y": import os print("Execute commands: pip install {0}".format(package)) if int(sys.version.split('.')[0])==2: os.system("pip install {0}".format(package)) elif int(sys.version.split('.')[0])==3: os.system("pip3 install {0}".format(package)) else: print("{0} is missing, so the program exits!".format(package)) exit(-1) if __name__ == '__main__': check_requirement('PIL') for i in sys.argv: print(i) create()
JavaScript
UTF-8
1,169
2.53125
3
[]
no_license
import React, { Component } from 'react' import axios from 'axios' class PhotoForm extends Component { constructor(props) { super(props) this.state = { name: this.props.photo.name } } handleInput = (e) => { this.setState({[e.target.name]: e.target.value}) } handleBlur = () => { const photo = { name: this.state.name } axios.put( `http://localhost:3001/api/v1/photos/${this.props.photo.id}`, { photo: photo }) .then(response => { console.log(response) this.props.updatePhoto(response.data) }) .catch(error => console.log(error)) } render() { return ( <div className="frame"> <form onBlur={this.handleBlur} > <input className='input' type="text" name="name" placeholder='Enter a url' value={this.state.name} onChange={this.handleInput} /> </form> </div> ); } } export default PhotoForm
C#
UTF-8
1,062
2.515625
3
[]
no_license
using System; using System.Collections.Generic; using System.Text; using CompactFormatter.Attributes; using CompactFormatter.Interfaces; namespace iPH.Commons.Functions { [CompactFormatter.Attributes.Serializable] public class PresentationSendFunction: BaseFunction { #region Singleton private static PresentationSendFunction mySelf; public static PresentationSendFunction Intance { get { if (mySelf == null) mySelf = new PresentationSendFunction(); return mySelf; } } #endregion #region Ctor public PresentationSendFunction() : base() { } #endregion #region Name & Description protected override string GetName() { return "Presentation Send Function"; } protected override string GetDescription() { return "Ability to send presentation itens."; } #endregion } }
Python
UTF-8
563
4
4
[]
no_license
import pandas data = pandas.read_csv("nato_phonetic_alphabet.csv") nato_data_frame = pandas.DataFrame(data) # Keyword Method with iterrows() # {new_key:new_value for (index, row) in df.iterrows()} #TODO 1. Create a dictionary in this format: nato_dict = {row.letter:row.code for (index, row) in nato_data_frame.iterrows()} #TODO 2. Create a list of the phonetic code words from a word that the user inputs. user_input = input("Please insert a word of your choice: \n").upper() user_phonetic = [nato_dict[letter] for letter in user_input] print(user_phonetic)
Go
UTF-8
799
4
4
[]
no_license
package main import "fmt" /** 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。 示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] */ func main() { a := []int{1, 2, 3, 5, 7, 12} b := 12 c := twoSum(a, b) fmt.Println(c) } func twoSum(nums []int, target int) []int { var result []int Lable1: for i := 0; i < len(nums); i++ { for j := i + 1; j < len(nums); j++ { if nums[i]+nums[j] == target { result = append(result, i) result = append(result, j) break Lable1 } } } return result }
Python
UTF-8
2,397
2.625
3
[]
no_license
import os.path import numpy as np import torch from torch.utils.data import Dataset class AG_News(Dataset): num_classes=4 class_weights=None ignored_index=-100 dim = 768 def __init__(self, root=os.path.expanduser('~/datasets/AGNEWS/'), train=True, transform=None, target_transform=None, download=False): if download: raise ValueError("Please run the data preparation scripts and set `download=False`") if transform is not None: raise ValueError("Transform should be `None`") if train: path = os.path.join(root, "ag_news_train.npz") else: path = os.path.join(root, "ag_news_test.npz") data_labels = np.load(path) data, labels = data_labels["encodings"], data_labels["labels"] data = torch.from_numpy(data) labels = torch.from_numpy(labels) if train: self.train_data = data self.train_labels = labels else: self.test_data = data self.test_labels = labels self.train = train def __len__(self): if self.train: return len(self.train_labels) else: return len(self.test_labels) def __getitem__(self, idx): if self.train: return self.train_data[idx], self.train_labels[idx] else: return self.test_data[idx], self.test_labels[idx] class YAHOO(Dataset): num_classes=10 class_weights=None ignored_index=-100 dim = 768 def __init__(self, root=os.path.expanduser('~/datasets/YAHOO/'), train=True): super().__init__() train_path = os.path.join(root, "yahoo_train.npz") test_path = os.path.join(root, "yahoo_test.npz") train_data = np.load(train_path) test_data = np.load(test_path) self.X_train, self.y_train = train_data["encodings"], train_data["labels"] self.X_test, self.y_test = test_data["encodings"], test_data["labels"] self.X_test = self.X_test[:10000] self.y_test = self.y_test[:10000] self.X = torch.from_numpy(self.X_train if train else self.X_test).float() self.Y = torch.from_numpy(self.y_train if train else self.y_test).long() def __len__(self): return self.X.shape[0] def __getitem__(self, idx): return self.X[idx],self.Y[idx]
JavaScript
UTF-8
163
2.703125
3
[]
no_license
function getDaysOfMonth(year,month){ var date=new Date(year,month,0); var days=date.getDate(); return days; } module.exports = { getDaysOfMonth };
Java
UTF-8
848
2.75
3
[]
no_license
package testerClasses; import generalClasses.P3Utils; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.util.ArrayList; import dataManagement.Document; import dataManagement.WordInDocument; /** * tests document * @author carlosgrivera * */ public class DocumentTester3 { public static void main(String[] args) throws IOException { String fName = "doc1"; File fPath = P3Utils.validateDocumentFile(fName); RandomAccessFile file = new RandomAccessFile(fPath, "rw"); Document doc = new Document(file); ArrayList<Long> wp = new ArrayList<>(); /**/ for (WordInDocument w : doc) { if (w.getWord().equalsIgnoreCase("file")) wp.add(w.getLocation()); } /**/ doc.displayDocumentContent(wp, 0); file.close(); } }
Java
UTF-8
307
2.578125
3
[]
no_license
package designs.creational.abstractfactory.factories; import designs.creational.abstractfactory.object.Bank; import designs.creational.abstractfactory.object.Loan; public abstract class AbstractFactory { public abstract Bank getBank(String bank); public abstract Loan getLoan(String loanType); }
JavaScript
UTF-8
3,907
3.453125
3
[]
no_license
var fs = require("fs"); var inquirer = require("inquirer"); var BasicCard = require("./BasicCard.js"); var ClozeCard = require("./ClozeCard.js"); var log = require("./log.json"); function LetsBegin(){ console.log("***************************************************************"); console.log("----------------------FLASH CARD MANIA ------------------------"); console.log("***************************************************************"); } LetsBegin(); inquirer .prompt ([{ name: "choose", type: "list", message: ("Choose the flashcard option you would like to execute:"), choices: [{ name: "Create A New Flashcard" },{ name:"Random Pick" },{ name: "Show All" },{ name: "Exit" }] }]) .then(function(response){ if(response.choose === "Create A New Flashcard"){ createCard(); } else if (response.choose === "Random Pick"){ randomPick(); } else if (response.choose === "Show All"){ showYourCards(); } else if (response.choose === "Exit"){ process.exit(); } }); var createCard = function(){ inquirer.prompt([{ name: 'cardType', message: 'What type of flashcard would you like to create?', type: "list", choices: [{ name: 'A Basic Flashcard' },{ name: 'A Cloze Flashcard' }] }]) .then(function(answer){ if(answer.cardType === 'A Basic Flashcard') { inquirer.prompt([{ name: "front", message: "Enter a factual question." }, { name: "back", message: "Please provide the answer to your question here.", }]) .then(function(answer){ var newBasicCard = new BasicCard(answer.front, answer.back); // newBasicCard.create(); log.push(newBasicCard); fs.writeFile('./log.json',JSON.stringify(log,null,2),function(err){ if (err){ return console.log(err); } }); next(); }); } else if (answer.cardType === "A Cloze Flashcard"){ inquirer.prompt([{ type: 'input', name: 'text', message: 'Please enter the full text statement.' },{ type: 'input', name: "cloze", message: "Please provide the words in your sentence you would like omitted." }]) .then(function(answer){ var newCloze = new ClozeCard(answer.text, answer.cloze); console.log(newCloze); log.push(newCloze); fs.writeFile('./log.json',JSON.stringify(log,null,2),function(err){ if (err){ return console.log(err); } }); next(); }); } }); }; var next = function(){ inquirer.prompt([{ name: 'next', message: 'What would you like to do next?', type: 'list', choices: [{ name: 'Create A New Card' },{ name: 'Show All Cards' }, { name: 'Exit' }] }]) .then(function(answer){ if(answer.next === 'Create A New Card'){ createCard(); } else { if(answer.next === 'Show All Cards'){ showYourCards(); } else if(answer.next === "Exit"){ return; } } }); }; var showYourCards = function(){ for(var i = 0; i < log.length; i++){ var count = 0; var questions = log[i]; if (log[i].type === 'basic') { var qText = log[i].front; var cAnswer = log[i].back; } else if (log[i].type === 'cloze') { var qText = log[i].clozeDelete; var cAnswer = log[i].cloze; } } inquirer.prompt([{ name: 'response', message: qText }]) .then(function(answer) { if (answer.response === cAnswer) { console.log('Good Answer!'); count++; showYourCards(); } else { console.log('Bad! Very, very Bad!! Now try again!!!'); count++; showYourCards(); } }); };
C
UTF-8
1,899
2.890625
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <kcorrect.h> /* * k_filter_struct * * Deal with the filter structure. * * Mike Blanton * 6/2003 */ typedef struct { double lambda; double pass; } FILTER_STRUCT; void k_print_filter_struct(void **input_struct, int nrows) { int i; FILTER_STRUCT **ptr_struct; ptr_struct=(FILTER_STRUCT **) input_struct; for(i=0;i<nrows;i++) printf("%e %e\n",ptr_struct[i]->lambda,ptr_struct[i]->pass); } void k_add_row_filter_struct(void ***input_struct, int *nrows, char *columns[], int ncolumns, char **wrd, int nwrds) { int i; FILTER_STRUCT **ptr_struct; ptr_struct=(FILTER_STRUCT **) (*input_struct); (*nrows)++; ptr_struct=(FILTER_STRUCT **) realloc((void **) ptr_struct, (*nrows)*sizeof(FILTER_STRUCT *)); ptr_struct[(*nrows)-1]=(FILTER_STRUCT *) malloc(sizeof(FILTER_STRUCT)); for(i=0;i<nwrds;i++) { if(!strcmp("lambda",columns[i])) ptr_struct[(*nrows)-1]->lambda=atof(wrd[i]); if(!strcmp("pass",columns[i])) ptr_struct[(*nrows)-1]->pass=atof(wrd[i]); } /* end for */ (*input_struct)=(void **) ptr_struct; } void k_copy_filter_struct(void **filter_struct, int filter_n, float *filter_lambda, float *filter_pass) { int i; FILTER_STRUCT **ptr_struct; ptr_struct=(FILTER_STRUCT **) filter_struct; for(i=0;i<filter_n;i++) { filter_lambda[i]=ptr_struct[i]->lambda; filter_pass[i]=ptr_struct[i]->pass; } } void k_free_filter_struct(void ***input_struct, int nrows) { int i; if(input_struct!=NULL) { if(*input_struct!=NULL) { for(i=0;i<nrows;i++) { if((*input_struct)[i]!=NULL) free((*input_struct)[i]); (*input_struct)[i]=NULL; } free((*input_struct)); } (*input_struct)=NULL; } }
JavaScript
UTF-8
1,658
3.109375
3
[]
no_license
var meuArray = [10, 14, 20, 9, 16, 22]; console.log(meuArray); console.log(meuArray[0]); console.log(meuArray[1]); console.log(meuArray[2]); console.log(meuArray[3]); console.log(meuArray[4]); console.log(meuArray[5]); console.log(meuArray[0] + meuArray[0]); console.log(meuArray[0] + meuArray[1]); console.log(meuArray[0] + meuArray[2]); console.log(meuArray[0] + meuArray[3]); console.log(meuArray[0] + meuArray[4]); console.log(meuArray[0] + meuArray[5]); console.log(meuArray[1] + meuArray[0]); console.log(meuArray[1] + meuArray[1]); console.log(meuArray[1] + meuArray[2]); console.log(meuArray[1] + meuArray[3]); console.log(meuArray[1] + meuArray[4]); console.log(meuArray[1] + meuArray[5]); console.log(meuArray[2] + meuArray[0]); console.log(meuArray[2] + meuArray[1]); console.log(meuArray[2] + meuArray[2]); console.log(meuArray[2] + meuArray[3]); console.log(meuArray[2] + meuArray[4]); console.log(meuArray[2] + meuArray[5]); console.log(meuArray[3] + meuArray[0]); console.log(meuArray[3] + meuArray[1]); console.log(meuArray[3] + meuArray[2]); console.log(meuArray[3] + meuArray[3]); console.log(meuArray[3] + meuArray[4]); console.log(meuArray[3] + meuArray[5]); console.log(meuArray[4] + meuArray[0]); console.log(meuArray[4] + meuArray[1]); console.log(meuArray[4] + meuArray[2]); console.log(meuArray[4] + meuArray[3]); console.log(meuArray[4] + meuArray[4]); console.log(meuArray[4] + meuArray[5]); console.log(meuArray[5] + meuArray[0]); console.log(meuArray[5] + meuArray[1]); console.log(meuArray[5] + meuArray[2]); console.log(meuArray[5] + meuArray[3]); console.log(meuArray[5] + meuArray[4]); console.log(meuArray[5] + meuArray[5]);
C++
UTF-8
683
2.859375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; vector <int>prime; void bitwiseseive(int n){ int arr[(n/64)+1]; memset(arr,0,sizeof(arr)); for (int i = 3; i*i < n; i+=2) { if(!(arr[i/64] & (1 << ((i >> 1)& 31)))){ for (int j = i*i; j < n; j+= 2*i) { arr[j/64] |= (1 << ((j >> 1) & 31)); } } } prime.push_back(2); for (int i = 3; i < n; i+=2) { if(!(arr[i/64] & (1<< ((i >> 1)&31)))){ prime.push_back(i); } } } int main() { int n; scanf("%d", &n); prime.clear(); bitwiseseive(n); printf("%ld\n",prime.size()); }
Python
UTF-8
108
3.28125
3
[]
no_license
a = int(input()) sum=0 i=1 while(i<=4): sum=int(sum+int(a%10)) a=int(a/10) i=i+1 print(sum)
C#
UTF-8
3,523
2.875
3
[]
no_license
using System.Collections.Generic; using System.Data.SqlClient; using System.IO; using System.Linq; using Dapper; using Microsoft.Extensions.Configuration; using Utils.Interfaces; using Utils.Models; namespace DataAccessDapper { public class SaleRepoDapper : ISaleRepository { private readonly string connection = string.Empty; public SaleRepoDapper() { Directory.SetCurrentDirectory("../../../"); var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .Build(); connection = configuration.GetConnectionString("DefaultConnection"); } public IList<Sale> GetAllSale() { using (SqlConnection sqlConnection = new SqlConnection(connection)) { var selection = "select sale.order_id as 'Order', c.name as 'Customer', p.name as 'Product', sale.quantity, sale.sales " + "from sale " + "INNER JOIN customer c on sale.customer_id = c.id " + "INNER JOIN product p on sale.product_id = p.id " + "group by sale.order_id, c.name, p.name, sale.quantity, sale.sales"; var sales = sqlConnection.Query<Sale>(selection).AsList(); return sales; } } public Sale GetSaleById(int id) { using (SqlConnection sqlConnection = new SqlConnection(connection)) { var selection = "select sale.order_id as 'Order', c.name as 'Customer', p.name as 'Product', sale.quantity, sale.sales " + "from sale " + "INNER JOIN customer c on sale.customer_id = c.id " + "INNER JOIN product p on sale.product_id = p.id " + "WHERE sale.id = @id " + "group by sale.order_id, c.name, p.name, sale.quantity, sale.sales"; var sale = sqlConnection.Query<Sale>(selection, new {id}).First(); return sale; } } public int InsertSale(SaleInsert saleInsert) { using (SqlConnection sqlConnection = new SqlConnection(connection)) { var selection = "INSERT INTO sale(order_id, customer_id, product_id, sales, quantity, discount, profit) " + "VALUES (@order_id, @customer_id, @product_id, @sales, @quantity, @discount, @profit)"; var count = sqlConnection.Execute(selection, new { order_id = saleInsert.OrderId, customer_id = saleInsert.CustomerId, product_id = saleInsert.ProductId, sales = saleInsert.Sales, quantity = saleInsert.Quantity, discount = saleInsert.Discount, profit = saleInsert.Profit }); return count; } } public int DeleteSaleById(int id) { using (SqlConnection sqlConnection = new SqlConnection(connection)) { var deleteSelection = "Delete from sale where id = @id"; var count = sqlConnection.Execute(deleteSelection, new {id}); return count; } } } }
PHP
UTF-8
6,284
2.515625
3
[]
no_license
<?php use function PHPSTORM_META\type; include_once('../php/default.php'); require_once('../php/checksession.php'); require_once("../php/connect.php"); $starttime = $endtime = $startdate = $enddate = $repeattype = $uid = ""; if($_SERVER["REQUEST_METHOD"] == "POST") { global $equipment; global $room; global $starttime; global $endtime; global $startdate; global $enddate; global $repeattype; global $uid; if(isset($_POST['room'])) { $room = $_POST['room']; } else if(isset($_POST['equipment'])) { $equipment = $_POST['equipment']; } if(isset($_POST['starttime'])) { $starttime = $_POST['starttime']; } if(isset($_POST['endtime'])) { $endtime = $_POST['endtime']; } if(isset($_POST['date'])) { $startdate = $_POST['date']; } if(isset($_POST['repeattype'])) { $repeattype = $_POST['repeattype']; } if(isset($_POST['enddate'])) { $enddate = $_POST['enddate']; } if(isset($_SESSION['uid'])) { $uid = $_SESSION['uid']; } $conn = connectDB(); if(!$conn) { exit("Unable to connect to DB"); } if(isset($room)) { reserve($startdate, $enddate, $starttime, $endtime, $repeattype, $room, $conn, $uid, "room"); sendToConf($room,$starttime,$endtime,$startdate,$enddate,$repeattype, "room"); } else if(isset($equipment)) { reserve($startdate, $enddate, $starttime, $endtime, $repeattype, $equipment, $conn, $uid,"equipment"); sendToConf($equipment,$starttime,$endtime,$startdate,$enddate,$repeattype,"equipment"); } $conn->close(); //header('Location:../pages/conf.php'); } /*else { header('Location:../index.php'); }*/ function reserve($startdate, $enddate, $starttime, $endtime, $repeattype, $id, $conn, $uid, $type) { $repeatnum = $repeatinterval = ""; $sd = date_create($startdate); $ed = date_create($enddate); $timediff = $sd->diff($ed); switch($repeattype) { case 0: $repeatinterval = " days"; $repeatnum = 0; break; case 1: $repeatinterval = " days"; $repeatnum = $timediff->format('%a'); break; case 2: $repeatinterval = " weeks"; $repeatnum = $timediff->format('%a')/7; break; case 3: $repeatinterval = " months"; $repeatnum = $timediff->format('%m'); break; case 4: $repeatinterval = " years"; $repeatnum = $timediff->format('%y'); break; } for($i=0;$i<=$repeatnum;$i++) { $date = date_create($startdate); $interval = $i.$repeatinterval; date_add($date, date_interval_create_from_date_string($interval)); $reservestart = $date->format('y-m-d')." ".$starttime.":00"; $reserveend = $date->format('y-m-d')." ".$endtime.":00"; if(checkifavailable($reservestart, $reserveend, $id, $conn, $type)) { if($type == "room") { $query = "INSERT INTO `roomreservation` (`roomResNum`, `roomID`, `reservationStart`, `reservationEnd`, `userID`) VALUES (NULL, '$id', '$reservestart', '$reserveend', '$uid')"; //REPLACE UID } else if($type == "equipment") { $query = "INSERT INTO `equipreservation` (`eReservationNum`, `equipID`, `reservationStart`, `reservationEnd`, `userID`) VALUES (NULL, '$id', '$reservestart', '$reserveend', '$uid')"; //REPLACE UID } $result = $conn->query($query); //echo "<br />Room reserved on ".$date->format('y-m-d'); } else { //echo "<br />Room not available on ".$date->format('y-m-d'); } } } function checkifavailable($stime, $etime, $id, $conn, $type) { if($type == "room") { $query = "SELECT * FROM `roomreservation` WHERE roomID = $id AND '$stime' >= reservationStart AND '$etime' <= reservationEnd"; } if($type == "equipment") { $query = "SELECT * FROM `equipreservation` WHERE equipID = $id AND '$stime' >= reservationStart AND '$etime' <= reservationEnd"; } $result = $conn->query($query); if(!$result) die("Error."); $rows=$result->num_rows; if($rows>0) { return false; } else { return true; } } function sendToConf($r,$st,$et,$sd,$ed,$rt,$type) { $repeating = 0; $conn = connectDB(); $user = $_SESSION['email']; if($type == "room") { $result = $conn->query("SELECT `roomNum`,`roomType`, `building` FROM `room` WHERE roomID = $r"); $outputResult = $result->fetch_assoc(); $output = $outputResult['roomNum']; $building = $outputResult['building']; $roomSelected = $outputResult['roomType']; } else if($type == "equipment") { $result = $conn->query("SELECT `equipName` FROM `equipment` WHERE equipID = $r"); $outputResult = $result->fetch_assoc(); $equipName = $outputResult['equipName']; $equipType = $outputResult['equipType']; } switch ($rt) { case 0: $repeating = " Never"; break; case 1: $repeating = " Daily"; break; case 2: $repeating = " Weekly"; break; case 3: $repeating = " Monthly"; break; case 4: $repeating = " Yearly"; break; } if($type == "room") { echo " <form action = \"../pages/conf.php\" method = \"POST\" id = \"form1\"> <input type = \"hidden\" name = \"room1\" value = \"$r\"> <input type = \"hidden\" name = \"start\" value = \"$st\"> <input type = \"hidden\" name = \"end\" value = \"$et\"> <input type = \"hidden\" name = \"sdate\" value = \"$sd\"> <input type = \"hidden\" name = \"edate\" value = \"$ed\"> <input type = \"hidden\" name = \"rep\" value = \"$rt\"> </form> <script type = \"text/javascript\"> document.getElementById('form1').submit(); </script>"; mail($user,"Reservation Confirmation", "Room Type: $roomSelected\nDate: $sd\nTime: $st-$et\nRoom Number: $building $output\nRepeating:$repeating","From: reservations@irissoln.com"); } else if($type == "equipment") { echo " <form action = \"../pages/conf.php\" method = \"POST\" id = \"form1\"> <input type = \"hidden\" name = \"equipment\" value = \"$r\"> <input type = \"hidden\" name = \"start\" value = \"$st\"> <input type = \"hidden\" name = \"end\" value = \"$et\"> <input type = \"hidden\" name = \"sdate\" value = \"$sd\"> <input type = \"hidden\" name = \"edate\" value = \"$ed\"> <input type = \"hidden\" name = \"rep\" value = \"$rt\"> </form> <script type = \"text/javascript\"> document.getElementById('form1').submit(); </script>"; mail($user,"Reservation Confirmation", "Equipment Type: $equipType\nDate: $sd\nTime: $st-$et\nEquipment: $equipName\nRepeating:$repeating","From: reservations@irissoln.com"); } } ?>
C++
UTF-8
742
2.671875
3
[]
no_license
#pragma once #include "IConnection.h" namespace echo { class EchoConnection final : public std::enable_shared_from_this<EchoConnection>, public IConnection { public: explicit EchoConnection(boost::asio::io_context& context); auto Start() noexcept -> void override; auto Socket() noexcept -> boost::asio::ip::tcp::socket& override; auto Shutdown() noexcept -> void override; private: auto HandleWrite() noexcept -> void; auto HandleRead(const boost::system::error_code& error, size_t bytes_transferred) noexcept -> void; auto DoRead() noexcept -> void; auto DoWrite(size_t count) noexcept -> void; private: boost::asio::ip::tcp::socket socket_; enum { kMaxLength = 1024 }; char data_[kMaxLength]; }; }
PHP
UTF-8
190
3.265625
3
[]
no_license
<?php $cont=0; $num=2; $suma=0; while($cont<3){ $suma=0; for($i=1;$i<$num;$i++){ if(($num%$i)==0){ $suma+=$i; } } if($num==$suma) { echo $num."<br>"; $cont++; } $num++; } ?>
PHP
UTF-8
1,175
3
3
[]
no_license
<?php error_reporting(E_ALL); ini_set('display_errors', 1); ?> <!DOCTYPE html> <html> <head> <title>Laet Static Binding</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!-- Popper JS --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script> <!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script> </head> <!-- In late static binding we use static::$variable in place self::$variable or Employee::$variable static:: will the get the value of current object --> <body> <?php Class DB { protected static $table = 'employee'; public function select(){ echo "select * from ".static::$table;//this is late static binding static will bind in run time } } Class subClass extends DB { protected static $table = 'employeeDetails'; } $db = new subClass; $db->select(); ?> </body> </html>
C++
UTF-8
368
2.6875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int countOccurrences(string s, intl) { int n = s.length(); int C, c1 = 0, c2 = 0; for (int i = 0; i < n; i++) { if (s[i] == 'a') c1++; if (s[i] == 'b') { c2++; C += c1; } } return C * l + (l * (l - 1) / 2) * c1 * c2; } int main() { string S = "abcb"; int l = 2; cout << countOccurrences(S, k) << endl; return 0; }
C#
UTF-8
3,369
2.75
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public class RodentAI : MonoBehaviour { #region singleton public static RodentAI instance; void Awake() { instance = this; } #endregion //Player public GameObject indiana; [Tooltip("How close Indy can get to the Jungle Rodent")] public float runDistance; // The current distance between the rodent and Indy. float currentDistance; // The jungle rodent's NavMeshAgent. NavMeshAgent agent; // The available waypoints the rodent can run to. public GameObject[] waypoints; // The waypoint where the rodent will run to when whipped in the correct spot. public GameObject whipWaypoint; // The current destination of the rodent; public GameObject currentWaypoint; // Was the rodent whipped? private bool wasWhipped = false; public bool WasWhipped { get { return wasWhipped; } set { wasWhipped = value; OnGameEvent whipped = OnWhipped; if(wasWhipped && whipped != null) { whipped(); } } } // Delegate is called when the rodent is whipped. public OnGameEvent OnWhipped; // Flag for if the rodent can run or not. [SerializeField] bool canRun = true; // Allows for teleportation without the rodent getting in a teleport loop. private bool canTeleport; public bool CanTeleport { get { return canTeleport; } set { canTeleport = value; } } void Start () { // Allow the rodent to be able to run straight away. canTeleport = true; //Sets the variable to the rodent's NavMeshAgent agent = GetComponent<NavMeshAgent>(); // Sets a point for the rodent to go to right away. currentWaypoint = waypoints[0]; SetNewDest(currentWaypoint.transform.position); } void Update () { // Checks the distance between the Indy and the rodent currentDistance = Vector3.Distance(transform.position, indiana.transform.position); // Allows the rodent to run if it can and Indy is close enough if (currentDistance < runDistance && canRun || canRun && wasWhipped) { /* Set the flag to false so that it doesn't continally find a new waypoint to go to while Indy is less than the runDistance */ canRun = false; wasWhipped = false; // Look for a new waypoint to go to. FindNewPoint(); } // If Indy is out of range reset the flag to true. if (currentDistance > runDistance) canRun = true; } void FindNewPoint() { if (currentWaypoint == waypoints[0]) currentWaypoint = waypoints[1]; else if (currentWaypoint == waypoints[1]) currentWaypoint = waypoints[2]; else if (currentWaypoint == waypoints[2]) currentWaypoint = waypoints[0]; // Set the new destination to the new current waypoint. SetNewDest(currentWaypoint.transform.position); } // Helper Method to set a new destination. public void SetNewDest(Vector3 newDest) { agent.SetDestination(newDest); } }
C++
UTF-8
754
3.625
4
[]
no_license
#define LED_PIN 12 // the setup function runs once when you press reset or power the board void setup() { // initialize digital pin LED_BUILTIN as an output. pinMode(LED_PIN, OUTPUT); // initialize communication over serial port Serial.begin(9600); } // the loop function runs over and over again forever void loop() { String command; if (Serial.available() > 0) { command = Serial.readStringUntil(' '); } if (command == "on") { Serial.write("turning the LED on\n"); digitalWrite(LED_PIN, HIGH); // turn the LED on (HIGH is the voltage level) } else if (command == "off") { Serial.write("turning the LED off\n"); digitalWrite(LED_PIN, LOW); // turn the LED off by making the voltage LOW } delay(100); }
Python
UTF-8
1,976
2.828125
3
[]
no_license
import socket class App: urls = {} def __init__(self): self.client_connection = None self.client_address = None def run_server(self, host='localhost', port=9005): serv_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serv_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) serv_socket.bind((host, port)) serv_socket.listen() while True: self.client_connection, self.client_address = serv_socket.accept() parsed_request = self._parse_request( self.client_connection.recv(1024)) if parsed_request: self._response(parsed_request) def _parse_request(self, request): if request: headers = request.decode("utf-8").splitlines() first_line = headers.pop(0) (verb, url, version) = first_line.split() parsed_request = {'method': verb, 'url': url, 'version': version} for h in headers: h = h.split(': ') if len(h) < 2: continue field = h[0] value = h[1] parsed_request[field] = value return parsed_request def _response(self, parsed_request): if parsed_request['url'] in self.urls: content = self.urls.get(parsed_request['url']) response = '{version} 200 OK\n\n {content}'.format( version=parsed_request['version'], content=content ) else: response = '{version} 404 Not Found\n\nNot found!'.format( version=parsed_request['version']) self.client_connection.sendall(str.encode(response)) self.client_connection.close() def add_to_url_map(self, url): def wrapper(func): if url not in self.urls: response = func() self.urls.update({url: response}) return wrapper
Python
UTF-8
1,173
2.703125
3
[ "MIT" ]
permissive
import sys import os.path sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from Code.MathLib import regression_b0 import test_common import pytest upper_x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] upper_y = [793029, 689403, 389032, 203819, 2, -182039, -403290, -584039, -859302, -1029329] lower_x = [1, 2, 4, 5, 7, 8, 10, 12, 14, 17, 20] lower_y = [0, 240.2, 403.2, 670.32, 883.29231, 1000, 2039.53, 2394.392, 5039.322332, 9999.9999, 1200] invalid_x = [1, 2] invalid_y = [0, 0, 0] upper_b1 = -206732.6060606 lower_b1 = 306.94441413099815 upper_b0 = 1038757.9333332 lower_b0 = -620.3804428272556 def test_regression_b0_lower_bound(): print(regression_b0(lower_x, lower_y, lower_b1)) assert test_common.isclose(regression_b0(lower_x, lower_y, lower_b1), lower_b0), "Lower regression (b0) bound test" def test_regression_b0_upper_bound(): print(regression_b0(upper_x, upper_y, upper_b1)) assert test_common.isclose(regression_b0(upper_x, upper_y, upper_b1), upper_b0), "Upper regression (b0) bound test" def test_regression_b0_invalid(): with pytest.raises(TypeError, message="Invalid regression (b0) test"): regression_b0(invalid_x, invalid_y, 0)
Java
UTF-8
3,276
2.21875
2
[ "Apache-2.0", "BSD-3-Clause", "EPL-1.0", "CDDL-1.1", "MIT", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.iotdb.library.drepair.util; import org.apache.iotdb.library.util.Util; import org.apache.iotdb.udf.api.access.Row; import org.apache.iotdb.udf.api.access.RowIterator; import org.apache.iotdb.udf.api.exception.UDFException; import java.util.ArrayList; public abstract class ValueRepair { protected int n; protected long[] time; protected double[] original; protected double[] repaired; protected ValueRepair(RowIterator dataIterator) throws Exception { ArrayList<Long> timeList = new ArrayList<>(); ArrayList<Double> originList = new ArrayList<>(); while (dataIterator.hasNextRow()) { Row row = dataIterator.next(); Double v = Util.getValueAsDouble(row); timeList.add(row.getTime()); if (!Double.isFinite(v)) { originList.add(Double.NaN); } else { originList.add(v); } } time = Util.toLongArray(timeList); original = Util.toDoubleArray(originList); n = time.length; repaired = new double[n]; processNaN(); } public abstract void repair(); private void processNaN() throws UDFException { int index1 = 0; int index2; while (index1 < n && Double.isNaN(original[index1])) { index1++; } index2 = index1 + 1; while (index2 < n && Double.isNaN(original[index2])) { index2++; } if (index2 >= n) { throw new UDFException("At least two non-NaN values are needed"); } for (int i = 0; i < index2; i++) { original[i] = original[index1] + (original[index2] - original[index1]) * (time[i] - time[index1]) / (time[index2] - time[index1]); } for (int i = index2 + 1; i < n; i++) { if (!Double.isNaN(original[i])) { index1 = index2; index2 = i; for (int j = index1 + 1; j < index2; j++) { original[j] = original[index1] + (original[index2] - original[index1]) * (time[j] - time[index1]) / (time[index2] - time[index1]); } } } for (int i = index2 + 1; i < n; i++) { original[i] = original[index1] + (original[index2] - original[index1]) * (time[i] - time[index1]) / (time[index2] - time[index1]); } } public long[] getTime() { return time; } public double[] getRepaired() { return repaired; } }
Python
UTF-8
568
3.71875
4
[]
no_license
"""Load a dictionary file as a list. Arguments: -dictionary file name Exceptions: -IOError -Requires import sys """ import sys def load(filename): """Open dict text file, check for errors, & make word list.""" try: with open(filename) as my_file: my_list = my_file.read().strip().split('\n') my_list = [x.lower() for x in my_list] return my_list except IOError as e: print("Error opening {}.\n Terminating program {}.".format(filename, e), file=sys.stderr) sys.exit(1)
Java
UTF-8
4,256
3.1875
3
[]
no_license
package lexeme.java.tree.expression.statement; import java.util.Optional; import lexeme.java.intervals.Parenthesis; import lexeme.java.tree.expression.Expression; import lexeme.java.tree.expression.ExpressionVisitor; import lexeme.java.tree.expression.statement.operators.binary.BinaryOperator; import lexeme.java.tree.expression.statement.operators.unary.prefix.PrefixUnaryOperator; import lexeme.java.tree.expression.statement.primitivetypes.PrimitiveValue; import lombok.Getter; import tokenizer.CodeLocator.CodeBranch; import tokenizer.CodeLocator.CodeLocation; /** * Represents a statement in the body of a method. Those represent entities, so * can be chained with ".", be assigned or passed. */ @Getter public abstract class Statement extends Expression { public Statement(CodeLocation location) { super(location); } /** * Tells if this statement can receive a value. * * @return true if it can */ public abstract boolean isAssignable(); /** * Attempts to build a Statement. * * @param input * the input text (will be mutated if object is built) * @return optionally, a Statement */ public static Optional<? extends Statement> build(CodeBranch input) {// Try parenthesis grouping CodeBranch fork = input.fork(); // Try a prefix operator Optional<? extends Statement> prefix = PrefixUnaryOperator.buildUnaryPrefix(fork); if (prefix.isPresent()) { return prefix; } // Try a lone statement Optional<? extends Statement> simple = buildSimple(fork); if (!simple.isPresent()) { return Optional.empty(); } // A minimal Statement has been found! // Chain [field access / method access / array access] greedily Optional<? extends Statement> chain = attemptChain(simple.get(), fork); if (!chain.isPresent()) { chain = simple; // no chain, just use the simple statement } // Try a binary operator Optional<? extends BinaryOperator> binary = BinaryOperator.build(chain.get(), fork); fork.commit(); // commit regardless if (binary.isPresent()) { return binary; } else { return chain; } } /** * Attempts to chain statements with ".". * * @param source * the subject of the "." operator * @param input * the input text (will be mutated if object is built) * @return optionally, an {@link ChainedAccess} */ public static Optional<? extends Statement> attemptChain(Statement source, CodeBranch input) { // Whatever the simple statement is, it may be chained ? Optional<ChainedAccess> chain = ChainedAccess.build(source, input); if (chain.isPresent()) { return chain; } Optional<ArrayAccess> arrayAccess = ArrayAccess.build(source, input); // TODO why test for arrays ? if (arrayAccess.isPresent()) { return attemptChain(arrayAccess.get(), input); } else { return Optional.empty(); } } private static Optional<? extends Statement> buildSimple(CodeBranch input) { if (Parenthesis.open(input)) { // Statement in parenthesis Optional<? extends Statement> statement = Statement.build(input); Parenthesis.close(input); return statement; } // Try a base type value (int, string, float...) Optional<? extends Statement> optional = PrimitiveValue.build(input); if (optional.isPresent()) { return optional; } // Try a new Instance() optional = NewInstance.build(input); if (optional.isPresent()) { return optional; } // Try a reference to this or to super optional = SelfReference.build(input); if (optional.isPresent()) { return optional; } // Try straight method invocation optional = MethodInvocation.build(input); if (optional.isPresent()) { return optional; } // Try variable reference optional = VariableReference.build(input); if (optional.isPresent()) { return optional; } // Nothing found return Optional.empty(); } @Override public <T> T acceptExpressionVisitor(ExpressionVisitor<T> visitor) { return visitor.visit(this); } /** * Accept a {@link StatementVisitor}. * * @param <T> * the type of the returned object * @param visitor * the visitor * @return the returned object */ public abstract <T> T acceptStatementVisitor(StatementVisitor<T> visitor); }
JavaScript
UTF-8
420
3.203125
3
[]
no_license
var T = readline() var res = [] for(var i = 0; i < T; i++){ var group = readline().split(' ') var N = group[0] var K = group[1] var data = readline().split(' ') var sum = 0 for(var j = 0; j < N; j++){ if(data[j] <= 0){ sum += 1 } } if(sum < K){ res.push('YES') }else{ res.push('NO') } } for(var z = 0; z < T; z++){ print(res[z]) }
Java
UTF-8
1,674
2.640625
3
[]
no_license
package com.github.eoinf.jiggen.TemplateCreator.components; import com.badlogic.gdx.graphics.Pixmap; public abstract class TemplateCreatorComponent { private TemplateCreatorComponent nextComponent; protected TemplateCreatorData data; // Top level component TemplateCreatorComponent() { this.data = new TemplateCreatorData(); } // Connector component TemplateCreatorComponent(TemplateCreatorComponent nextComponent) { this(); this.nextComponent = nextComponent; } // Root component TemplateCreatorComponent(TemplateCreatorData baseData, TemplateCreatorComponent nextComponent) { this(nextComponent); this.setData(baseData); } public void setData(TemplateCreatorData newData) { if (shouldRecalculate(newData)) { newData = calculate(newData); } this.data = newData; if (nextComponent != null) { nextComponent.setData(newData); } } public Pixmap getPixmap() { if (nextComponent != null) { Pixmap nextPixmap = nextComponent.getPixmap(); if (nextPixmap != null) { return nextPixmap; } } return this.data.pixmap; } public TemplateCreatorData getData() { if (nextComponent != null) { TemplateCreatorData nextData = nextComponent.getData(); return nextData != null ? nextData: this.data; } else { return this.data; } } abstract boolean shouldRecalculate(TemplateCreatorData newData); abstract TemplateCreatorData calculate(TemplateCreatorData newData); }
Java
UTF-8
16,909
2.09375
2
[]
no_license
package me.oggunderscore.Utils; import java.util.ArrayList; import org.bukkit.ChatColor; import org.bukkit.Color; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.configuration.Configuration; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.LeatherArmorMeta; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import me.oggunderscore.Core.Main; public class Kits { public static final ArrayList<Player> DEFAULT = new ArrayList<Player>(); public static final ArrayList<Player> TANK = new ArrayList<Player>(); public static final ArrayList<Player> ARES = new ArrayList<Player>(); public static final ArrayList<Player> BERSERKER = new ArrayList<Player>(); public static final ArrayList<Player> THOR = new ArrayList<Player>(); public static final ArrayList<Player> HADES = new ArrayList<Player>(); public static final ArrayList<Player> APOLLO = new ArrayList<Player>(); public static final ArrayList<Player> NINJA = new ArrayList<Player>(); static Configuration config = Main.getPlugin(Main.class).getConfig(); public static void setKitDefault(Player p) { ItemStack Helmet = new ItemStack(Material.IRON_HELMET); ItemMeta hm = Helmet.getItemMeta(); hm.setUnbreakable(true); Helmet.setItemMeta(hm); ItemStack Chestplate = new ItemStack(Material.IRON_CHESTPLATE); ItemMeta cm = Chestplate.getItemMeta(); cm.setUnbreakable(true); Chestplate.setItemMeta(cm); ItemStack Leggings = new ItemStack(Material.IRON_LEGGINGS); ItemMeta lm = Leggings.getItemMeta(); lm.setUnbreakable(true); Leggings.setItemMeta(lm); ItemStack Boots = new ItemStack(Material.IRON_BOOTS); ItemMeta bm = Boots.getItemMeta(); bm.setUnbreakable(true); Boots.setItemMeta(bm); ItemStack Sword = new ItemStack(Material.IRON_SWORD); ItemMeta sm = Sword.getItemMeta(); ArrayList<String> lore1 = new ArrayList<String>(); lore1.add(ChatColor.YELLOW + "Your loyal Iron Blade."); sm.setLore(lore1); sm.setUnbreakable(true); sm.setDisplayName(ChatColor.RED + "" + ChatColor.BOLD + "DASH"); Sword.setItemMeta(sm); ItemStack Bow = new ItemStack(Material.BOW); ItemMeta bowm = Bow.getItemMeta(); ArrayList<String> lore2 = new ArrayList<String>(); lore2.add(ChatColor.YELLOW + "Your loyal Long Bow."); bowm.setLore(lore1); bowm.setUnbreakable(true); Bow.setItemMeta(bowm); if (config.getConfigurationSection(p.getName()).get("HOTBARMODE").equals(1)) { p.getInventory().setItem(0, Sword); p.getInventory().setItem(1, new ItemStack (Material.ARROW, 64)); p.getInventory().setItem(2, Bow); } else if (config.getConfigurationSection(p.getName()).get("HOTBARMODE").equals(2)) { p.getInventory().setItem(0, Sword); p.getInventory().setItem(1, Bow); p.getInventory().setItem(2, new ItemStack (Material.ARROW, 64)); } p.getInventory().setHelmet(Helmet); p.getInventory().setChestplate(Chestplate); p.getInventory().setLeggings(Leggings); p.getInventory().setBoots(Boots); p.getInventory().setItem(4, ItemStacks.getItem("kitpvpButton")); p.playSound(p.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1, 1); DEFAULT.add(p); } public static void setKitTank(Player p) { ItemStack Helmet = new ItemStack(Material.DIAMOND_HELMET); ItemMeta hm = Helmet.getItemMeta(); hm.setUnbreakable(true); Helmet.setItemMeta(hm); ItemStack Chestplate = new ItemStack(Material.DIAMOND_CHESTPLATE); ItemMeta cm = Chestplate.getItemMeta(); cm.setUnbreakable(true); Chestplate.setItemMeta(cm); ItemStack Leggings = new ItemStack(Material.DIAMOND_LEGGINGS); ItemMeta lm = Leggings.getItemMeta(); lm.setUnbreakable(true); Leggings.setItemMeta(lm); ItemStack Boots = new ItemStack(Material.DIAMOND_BOOTS); ItemMeta bm = Boots.getItemMeta(); bm.setUnbreakable(true); Boots.setItemMeta(bm); ItemStack Sword = new ItemStack(Material.WOODEN_SWORD); ItemMeta sm = Sword.getItemMeta(); ArrayList<String> lore1 = new ArrayList<String>(); lore1.add(ChatColor.YELLOW + "Your loyal Woodem Blade."); sm.setLore(lore1); sm.setUnbreakable(true); Sword.setItemMeta(sm); p.getInventory().addItem(Sword); p.getInventory().setHelmet(Helmet); p.getInventory().setChestplate(Chestplate); p.getInventory().setLeggings(Leggings); p.getInventory().setBoots(Boots); p.playSound(p.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1, 1); p.getInventory().setItem(4, ItemStacks.getItem("kitpvpButton")); TANK.add(p); } public static void setKitAres(Player p) { ItemStack AresHelmet = new ItemStack(Material.LEATHER_HELMET); LeatherArmorMeta ahm = (LeatherArmorMeta) AresHelmet.getItemMeta(); ahm.setColor(Color.ORANGE); ahm.setUnbreakable(true); AresHelmet.setItemMeta(ahm); ItemStack AresChestplate = new ItemStack(Material.LEATHER_CHESTPLATE); LeatherArmorMeta acm = (LeatherArmorMeta) AresChestplate.getItemMeta(); acm.setColor(Color.ORANGE); acm.setUnbreakable(true); AresChestplate.setItemMeta(acm); ItemStack AresLeggings = new ItemStack(Material.LEATHER_LEGGINGS); LeatherArmorMeta alm = (LeatherArmorMeta) AresLeggings.getItemMeta(); alm.setColor(Color.ORANGE); alm.setUnbreakable(true); AresLeggings.setItemMeta(alm); ItemStack AresBoots = new ItemStack(Material.LEATHER_BOOTS); LeatherArmorMeta abm = (LeatherArmorMeta) AresBoots.getItemMeta(); abm.setColor(Color.ORANGE); abm.setUnbreakable(true); AresBoots.setItemMeta(abm); ItemStack Sword = new ItemStack(Material.STONE_SWORD); ItemMeta sm = Sword.getItemMeta(); ArrayList<String> lore1 = new ArrayList<String>(); lore1.add(ChatColor.LIGHT_PURPLE + "" + ChatColor.BOLD + "Enlightment"); lore1.add(ChatColor.YELLOW + "Leap in a direction and gain Absorbation!"); sm.setLore(lore1); sm.setDisplayName(ChatColor.GOLD + "" + ChatColor.BOLD + "Ares Sword"); sm.setUnbreakable(true); Sword.setItemMeta(sm); ItemStack Ignite = new ItemStack(Material.FIRE_CHARGE); ItemMeta im = Ignite.getItemMeta(); ArrayList<String> lore = new ArrayList<String>(); im.setDisplayName(ChatColor.RED + "" + ChatColor.BOLD + "Ignite"); lore.add(ChatColor.YELLOW + "Right Click to set nearby"); lore.add(ChatColor.YELLOW + "enemies on fire for 9 seconds!"); im.setLore(lore); Ignite.setItemMeta(im); Ignite.setAmount(1); ItemStack Regen = new ItemStack(Material.ROSE_BUSH); ItemMeta rm = Regen.getItemMeta(); ArrayList<String> lore2 = new ArrayList<String>(); rm.setDisplayName(ChatColor.RED + "" + ChatColor.BOLD + "Regeneration Flower"); lore2.add(ChatColor.YELLOW + "Right Click to gain"); lore2.add(ChatColor.YELLOW + "Regeneration 2 for 5 seconds!"); rm.setLore(lore2); Regen.setItemMeta(rm); p.getInventory().setHelmet(AresHelmet); p.getInventory().setChestplate(new ItemStack(Material.IRON_CHESTPLATE)); p.getInventory().setLeggings(new ItemStack(Material.CHAINMAIL_LEGGINGS)); p.getInventory().setBoots(new ItemStack(Material.CHAINMAIL_BOOTS)); p.getInventory().setHeldItemSlot(0); p.getInventory().setItem(0, Sword); p.getInventory().setItem(1, Ignite); p.getInventory().addItem(Regen); p.getInventory().setItem(4, ItemStacks.getItem("kitpvpButton")); p.getWorld().playSound(p.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1, 1); ARES.add(p); } public static void setKitBerserker(Player p) { ItemStack Helmet = new ItemStack(Material.IRON_HELMET); ItemMeta hm = Helmet.getItemMeta(); hm.setUnbreakable(true); Helmet.setItemMeta(hm); ItemStack Chestplate = new ItemStack(Material.IRON_CHESTPLATE); ItemMeta cm = Chestplate.getItemMeta(); cm.setUnbreakable(true); Chestplate.setItemMeta(cm); ItemStack Leggings = new ItemStack(Material.IRON_LEGGINGS); ItemMeta lm = Leggings.getItemMeta(); lm.setUnbreakable(true); Leggings.setItemMeta(lm); ItemStack Boots = new ItemStack(Material.LEATHER_BOOTS); LeatherArmorMeta bm = (LeatherArmorMeta) Boots.getItemMeta(); bm.setColor(Color.RED); bm.setUnbreakable(true); Boots.setItemMeta(bm); ItemStack Sword = new ItemStack(Material.STONE_AXE); ItemMeta sm = Sword.getItemMeta(); ArrayList<String> lore1 = new ArrayList<String>(); lore1.add(ChatColor.YELLOW + "Cleave through your enemies! Cost: 80 Energy"); sm.setLore(lore1); sm.setUnbreakable(true); sm.setDisplayName(ChatColor.RED + "" + ChatColor.BOLD + "CLEAVE"); Sword.addUnsafeEnchantment(Enchantment.DAMAGE_ALL, -1); Sword.setItemMeta(sm); ItemStack Ultimate = new ItemStack(Material.REDSTONE); ItemMeta um = Ultimate.getItemMeta(); ArrayList<String> lore = new ArrayList<String>(); lore.add(ChatColor.YELLOW + "Release a powerful ROAR! Cost: 100 Energy"); um.setLore(lore); um.setUnbreakable(true); um.setDisplayName(ChatColor.RED + "" + ChatColor.BOLD + "ROAR"); Ultimate.setItemMeta(um); ItemStack QuickFix = new ItemStack(Material.LEATHER); ItemMeta qm = QuickFix.getItemMeta(); ArrayList<String> lore2 = new ArrayList<String>(); lore2.add(ChatColor.YELLOW + "Instantly Heal 2 hearts! Cost: 40 Energy"); qm.setLore(lore2); qm.setUnbreakable(true); qm.setDisplayName(ChatColor.GREEN + "" + ChatColor.BOLD + "Quick Fix"); QuickFix.setItemMeta(qm); p.getInventory().setItem(0, Sword); p.getInventory().setItem(1, QuickFix); p.getInventory().setItem(2, Ultimate); p.getInventory().setHelmet(Helmet); p.getInventory().setChestplate(Chestplate); p.getInventory().setLeggings(Leggings); p.getInventory().setBoots(Boots); p.playSound(p.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1, 1); p.getInventory().setItem(4, ItemStacks.getItem("kitpvpButton")); BERSERKER.add(p); } public static void setKitThor(Player p) { ItemStack Helmet = new ItemStack(Material.GOLDEN_HELMET); ItemMeta hm = Helmet.getItemMeta(); hm.setUnbreakable(true); Helmet.setItemMeta(hm); ItemStack Chestplate = new ItemStack(Material.IRON_CHESTPLATE); ItemMeta cm = Chestplate.getItemMeta(); cm.setUnbreakable(true); Chestplate.setItemMeta(cm); ItemStack Leggings = new ItemStack(Material.IRON_LEGGINGS); ItemMeta lm = Leggings.getItemMeta(); lm.setUnbreakable(true); Leggings.setItemMeta(lm); ItemStack Boots = new ItemStack(Material.GOLDEN_BOOTS); ItemMeta bm = Boots.getItemMeta(); bm.setUnbreakable(true); Boots.setItemMeta(bm); ItemStack Sword = new ItemStack(Material.IRON_AXE); ItemMeta sm = Sword.getItemMeta(); ArrayList<String> lore1 = new ArrayList<String>(); lore1.add(ChatColor.YELLOW + "Summon an Earthquake!"); sm.setLore(lore1); sm.setUnbreakable(true); sm.setDisplayName(ChatColor.RED + "" + ChatColor.BOLD + "EARTHQUAKE"); Sword.setItemMeta(sm); p.getInventory().setItem(0, Sword); p.getInventory().setHelmet(Helmet); p.getInventory().setChestplate(Chestplate); p.getInventory().setLeggings(Leggings); p.getInventory().setBoots(Boots); p.playSound(p.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1, 1); p.getInventory().setItem(4, ItemStacks.getItem("kitpvpButton")); THOR.add(p); } public static void setKitHades(Player p) { ItemStack Helmet = new ItemStack(Material.LEATHER_HELMET); LeatherArmorMeta hm = (LeatherArmorMeta) Helmet.getItemMeta(); hm.setColor(Color.PURPLE); hm.setUnbreakable(true); Helmet.setItemMeta(hm); ItemStack Chestplate = new ItemStack(Material.DIAMOND_CHESTPLATE); ItemMeta cm = Chestplate.getItemMeta(); cm.setUnbreakable(true); Chestplate.setItemMeta(cm); ItemStack Leggings = new ItemStack(Material.DIAMOND_LEGGINGS); ItemMeta lm = Leggings.getItemMeta(); lm.setUnbreakable(true); Leggings.setItemMeta(lm); ItemStack Boots = new ItemStack(Material.LEATHER_BOOTS); LeatherArmorMeta bm = (LeatherArmorMeta) Boots.getItemMeta(); bm.setColor(Color.PURPLE); bm.setUnbreakable(true); Boots.setItemMeta(bm); ItemStack Sword = new ItemStack(Material.IRON_AXE); ItemMeta sm = Sword.getItemMeta(); ArrayList<String> lore1 = new ArrayList<String>(); lore1.add(ChatColor.YELLOW + "Summon a Corrupted Orb!"); sm.setLore(lore1); sm.setUnbreakable(true); sm.setDisplayName(ChatColor.RED + "" + ChatColor.BOLD + "Corrupted Orb!"); Sword.setItemMeta(sm); p.getInventory().setItem(0, Sword); p.getInventory().setHelmet(Helmet); p.getInventory().setChestplate(Chestplate); p.getInventory().setLeggings(Leggings); p.getInventory().setBoots(Boots); p.playSound(p.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1, 1); p.getInventory().setItem(4, ItemStacks.getItem("kitpvpButton")); HADES.add(p); } public static void setKitApollo(Player p) { ItemStack Helmet = new ItemStack(Material.LEATHER_HELMET); LeatherArmorMeta hm = (LeatherArmorMeta) Helmet.getItemMeta(); hm.setColor(Color.YELLOW); hm.setUnbreakable(true); Helmet.setItemMeta(hm); ItemStack AresChestplate = new ItemStack(Material.LEATHER_CHESTPLATE); LeatherArmorMeta acm = (LeatherArmorMeta) AresChestplate.getItemMeta(); acm.setColor(Color.YELLOW); acm.setUnbreakable(true); AresChestplate.setItemMeta(acm); ItemStack Leggings = new ItemStack(Material.CHAINMAIL_LEGGINGS); ItemMeta lm = Leggings.getItemMeta(); lm.setUnbreakable(true); Leggings.setItemMeta(lm); ItemStack AresBoots = new ItemStack(Material.DIAMOND_BOOTS); ItemMeta abm = AresBoots.getItemMeta(); //LeatherArmorMeta abm = (LeatherArmorMeta) AresBoots.getItemMeta(); //abm.setColor(Color.YELLOW); abm.setUnbreakable(true); AresBoots.setItemMeta(abm); ItemStack Sword = new ItemStack(Material.BOW); ItemMeta sm = Sword.getItemMeta(); ArrayList<String> lore1 = new ArrayList<String>(); lore1.add(ChatColor.YELLOW + "LEFT CLICK AIR: Escape the Danger!"); lore1.add(ChatColor.YELLOW + "SNEAK + FIRE: Fire an Empowered Arrow."); lore1.add(ChatColor.YELLOW + "Cooldown: 13s"); sm.setLore(lore1); sm.setUnbreakable(true); sm.setDisplayName(ChatColor.RED + "" + ChatColor.BOLD + "Escape!"); sm.addEnchant(Enchantment.KNOCKBACK, 3, true); //sm.addEnchant(Enchantment.ARROW_FIRE, 1, true); sm.addEnchant(Enchantment.ARROW_INFINITE, 1, true); Sword.setItemMeta(sm); p.getInventory().setItem(0, Sword); p.getInventory().setItem(8, new ItemStack(Material.ARROW)); p.getInventory().setHelmet(Helmet); p.getInventory().setChestplate(AresChestplate); p.getInventory().setLeggings(Leggings); p.getInventory().setBoots(AresBoots); p.playSound(p.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1, 1); p.getInventory().setItem(4, ItemStacks.getItem("kitpvpButton")); APOLLO.add(p); } public static void setKitNinja(Player p) { ItemStack Helmet = new ItemStack(Material.LEATHER_HELMET); LeatherArmorMeta hm = (LeatherArmorMeta) Helmet.getItemMeta(); hm.setColor(Color.BLACK); hm.setUnbreakable(true); Helmet.setItemMeta(hm); ItemStack Chestplate = new ItemStack(Material.LEATHER_CHESTPLATE); LeatherArmorMeta cm = (LeatherArmorMeta) Helmet.getItemMeta(); cm.setColor(Color.BLACK); cm.setUnbreakable(true); Chestplate.setItemMeta(cm); ItemStack Leggings = new ItemStack(Material.LEATHER_LEGGINGS); LeatherArmorMeta lm = (LeatherArmorMeta) Leggings.getItemMeta(); lm.setColor(Color.BLACK); lm.setUnbreakable(true); Leggings.setItemMeta(lm); ItemStack Boots = new ItemStack(Material.LEATHER_BOOTS); LeatherArmorMeta bm = (LeatherArmorMeta) Boots.getItemMeta(); bm.setColor(Color.BLACK); bm.setUnbreakable(true); Boots.setItemMeta(bm); ItemStack Sword = new ItemStack(Material.DIAMOND_SWORD); ItemMeta sm = Sword.getItemMeta(); ArrayList<String> lore1 = new ArrayList<String>(); lore1.add(ChatColor.YELLOW + "Teleport a Distance!"); sm.setLore(lore1); sm.setUnbreakable(true); sm.setDisplayName("Blink!"); Sword.setItemMeta(sm); ItemStack Cloak = new ItemStack(Material.FIRE_CHARGE); ItemMeta cloakMeta = Cloak.getItemMeta(); ArrayList<String> cloakLore = new ArrayList<String>(); cloakLore.add(ChatColor.YELLOW + "Cloak for 7 Seconds!"); cloakMeta.setLore(cloakLore); cloakMeta.setUnbreakable(true); cloakMeta.setDisplayName(ChatColor.GREEN + "" + ChatColor.BOLD + "Cloak"); Cloak.setItemMeta(cloakMeta); p.getInventory().setItem(0, Sword); p.getInventory().setItem(1, Cloak); p.getInventory().setHelmet(Helmet); p.getInventory().setChestplate(Chestplate); p.getInventory().setLeggings(Leggings); p.getInventory().setBoots(Boots); p.playSound(p.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1, 1); PotionEffect speed = new PotionEffect(PotionEffectType.SPEED, 9999 * 20, 1); p.addPotionEffect(speed); p.getInventory().setItem(4, ItemStacks.getItem("kitpvpButton")); NINJA.add(p); } }
Python
UTF-8
773
2.59375
3
[ "MIT" ]
permissive
# -*- coding:utf-8 -*- """封装Request对象""" class Request(object): """框架内置请求对象, 设置请求信息""" def __init__(self, url, method='GET', headers=None, params=None, data=None, parse='parse', filter=True, meta=None): self.url = url self.method = method self.headers = headers self.params = params self.data = data # parse处理多级页面 self.parse = parse # 增量爬虫, 请求默认做去重filter = True self.filter = filter # True默认做去重-->在那里判断?-->schedule self.meta = meta # 请求发送的响应, 响应里面的数据, 请求里面的数据传给meta然后交给响应文件
Java
UTF-8
5,860
1.96875
2
[ "MIT" ]
permissive
package openmods.network; import io.netty.buffer.*; import io.netty.channel.*; import io.netty.channel.ChannelHandler.Sharable; import java.io.*; import java.util.Map; import java.util.NoSuchElementException; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import net.minecraft.network.INetHandler; import openmods.Log; import openmods.datastore.*; import com.google.common.base.Preconditions; import com.google.common.io.Closer; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.LoaderState; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.network.*; import cpw.mods.fml.common.network.FMLNetworkEvent.ClientConnectedToServerEvent; import cpw.mods.fml.common.network.FMLNetworkEvent.ClientDisconnectionFromServerEvent; import cpw.mods.fml.common.network.FMLNetworkEvent.CustomPacketRegistrationEvent; import cpw.mods.fml.common.network.internal.FMLProxyPacket; import cpw.mods.fml.relauncher.Side; public class IdSyncManager extends DataStoreManager { private static final String CHANNEL_NAME = "OpenMods|I"; private final Map<Side, FMLEmbeddedChannel> channels; public static final IdSyncManager INSTANCE = new IdSyncManager(); private class ServerHandshakeHijacker extends ChannelOutboundHandlerAdapter { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { ctx.writeAndFlush(msg); if (msg instanceof FMLProxyPacket) { FMLProxyPacket hijackedMsg = (FMLProxyPacket)msg; if (hijackedMsg.channel().equals("FML|HS")) { ByteBuf payload = hijackedMsg.payload(); byte discriminator = payload.readByte(); if (discriminator == 3 /* FMLHandshakeMessage.ModIdData */) { sendAllIds(ctx); ctx.pipeline().remove(this); } else if (discriminator == -1 /* FMLHandshakeMessage.HandshakeAck */) { ctx.pipeline().remove(this); } } } } } private class ClientHandshakeHijacker extends SimpleChannelInboundHandler<FMLProxyPacket> { @Override protected void channelRead0(ChannelHandlerContext ctx, FMLProxyPacket msg) throws Exception { if (msg.channel().equals(CHANNEL_NAME)) { channels.get(Side.CLIENT).writeInbound(msg); } else { ctx.fireChannelRead(msg); } } } @Sharable private class InboundHandler extends SimpleChannelInboundHandler<FMLProxyPacket> { @Override protected void channelRead0(ChannelHandlerContext ctx, FMLProxyPacket msg) throws Exception { ByteBuf buf = msg.payload(); try { Closer closer = Closer.create(); try { InputStream raw = closer.register(new ByteBufInputStream(buf)); InputStream compressed = closer.register(new GZIPInputStream(raw)); DataInput input = new DataInputStream(compressed); String keyId = input.readUTF(); Log.debug("Received data store for key %s, packet size = %d", keyId, buf.writerIndex()); DataStoreWrapper<?, ?> wrapper = getDataStoreMeta(keyId); DataStoreReader<?, ?> reader = wrapper.createReader(); reader.read(input); } finally { closer.close(); } } catch (IOException e) { throw new RuntimeException(e); } } } public class NetEventHandler { @SubscribeEvent public void onJoin(CustomPacketRegistrationEvent<? extends INetHandler> evt) { if (!evt.manager.isLocalChannel() && evt.registrations.contains(CHANNEL_NAME)) { ChannelHandler handler = (evt.side == Side.SERVER)? new ServerHandshakeHijacker() : new ClientHandshakeHijacker(); evt.manager.channel().pipeline().addAfter("fml:packet_handler", "openmods:id_injector", handler); } } @SubscribeEvent public void onHandshakeComplete(ClientConnectedToServerEvent evt) { if (!evt.manager.isLocalChannel()) { try { evt.manager.channel().pipeline().remove("openmods:id_injector"); } catch (NoSuchElementException e) { // NO-OP - possibly removed earlier } } } @SubscribeEvent public void onDisconnect(ClientDisconnectionFromServerEvent evt) { activateLocalData(); } } private static FMLProxyPacket serializeToPacket(DataStoreKey<?, ?> key, DataStoreWriter<?, ?> writer) { ByteBuf payload = Unpooled.buffer(); Closer closer = Closer.create(); try { try { OutputStream raw = closer.register(new ByteBufOutputStream(payload)); OutputStream compressed = closer.register(new GZIPOutputStream(raw)); DataOutput output = new DataOutputStream(compressed); output.writeUTF(key.id); writer.write(output); } finally { closer.close(); } } catch (IOException e) { throw new RuntimeException(e); } return new FMLProxyPacket(payload.copy(), CHANNEL_NAME); } private IdSyncManager() { this.channels = NetworkRegistry.INSTANCE.newChannel(CHANNEL_NAME, new InboundHandler()); } public <K, V> DataStoreBuilder<K, V> createDataStore(String domain, String id, Class<? extends K> keyClass, Class<? extends V> valueClass) { final String fullId = domain + ":" + id; return createDataStore(fullId, keyClass, valueClass); } @Override public <K, V> DataStoreBuilder<K, V> createDataStore(String id, Class<? extends K> keyClass, Class<? extends V> valueClass) { Preconditions.checkState(!Loader.instance().hasReachedState(LoaderState.POSTINITIALIZATION), "This method cannot be called in post-initialization state and later"); return super.createDataStore(id, keyClass, valueClass); } private void sendAllIds(ChannelHandlerContext ctx) { validate(); for (Map.Entry<DataStoreKey<?, ?>, DataStoreWrapper<?, ?>> e : dataStoreMeta.entrySet()) { FMLProxyPacket packet = serializeToPacket(e.getKey(), e.getValue().createWriter()); ctx.write(packet); } } public void finishLoading() { validate(); FMLCommonHandler.instance().bus().register(new NetEventHandler()); } }
C++
UTF-8
1,055
4.0625
4
[]
no_license
/* Idex: p.95 Title: Calculate Moving Average Description: Given N, let's calculate M months's moving average Time Complexity: O(N) */ #include <iostream> #include <vector> #include <ctime> #include <cstdlib> using namespace std; double getRandValue() { return rand() % 100 + 1; } vector<double> movingAverage2(const vector<double>& A, int M) { vector<double> ret; int N = A.size(); double partialSum = 0; for (int i = 0; i < M - 1; i++) { partialSum += A[i]; } for (int i = M - 1; i < N; i++) { // calculate moving average from A[i] to A[i-j] partialSum += A[i]; ret.push_back(partialSum / M); partialSum -= A[i - M + 1]; } return ret; } int main() { int N = 12; int M = 3; srand((unsigned int)time(NULL)); vector<double> value; // input for (int i = 0; i < N; i++) { value.push_back(getRandValue()); } // calculate vector<double> ret = movingAverage2(value, M); // output cout << M << " month(s) Moving Average: "; for (int i = 0; i < ret.size(); i++) { cout << ret.at(i) << " "; } cout << endl; return 0; }
Python
UTF-8
1,746
3.296875
3
[]
no_license
""" Initial file for stating the project.""" from block_development_officer import BlockDevelopmentOfficer from gram_panchayat_member import GramPanchayatMember from member import Member from schema import Schema import sqlite3 def sql_connection(): """ Setup connection with sqlite3 backend. :return: sqlite3 connection object """ return sqlite3.connect('database.db') class Run: def __init__(self, connection): self.conn = connection def login_menu(self): """ Display Login options for users to choose. :return: True """ print("\n**** LOGIN MENU ****") print("1. Login as BDO \n2. Login as GPM \n3. Login as Member\n4. Exit") choice = input("Choose: ") if choice == '1': BlockDevelopmentOfficer(self.conn).login_bdo() elif choice == '2': GramPanchayatMember(self.conn).login_gpm() elif choice == '3': Member(self.conn).login_member() elif choice == '4': print("\nExiting...") self.conn.close() else: print("\nWrong Input! Try again.") if choice != '4': self.login_menu() return True def main(): """ :return: True/False """ try: conn = sql_connection() if conn is None: print("Error while connecting with database") print("Retry after sometime!!!") else: Schema(conn).setup_admin() Schema(conn).create_tables() Run(conn).login_menu() conn.close() return True except sqlite3.Error as e: print(type(e), ": ", e) return False if __name__ == "__main__": main()
C
UTF-8
1,559
2.984375
3
[]
no_license
/*********************************************************************** *file: Lab1_test.c *synopsis: The argz functions use malloc/realloc to allocate/grow argz vectors, *and so any argz vector creating using these functions may be freed by using *free; conversely, any argz function that may grow a string expects that string *to have been allocated *using malloc those argz functions that only examine *their arguments or modify them in place *will work on any sort of memory). All *argz functions that do memory allocation have a return type of error_t, and *return 0 for success, and ENOMEM if an allocation error occurs. * These functions are declared in the include file "argz.h". *related files: none *author: Denys Fedorchenko *created: 24/09/2017 *last modified: 25/10/2017 ************************************************************************/ #include "Lab1_header.h" int main() { char *const string = "SHELL=/bin/bash:usr=monty:PWD=/bin/monty:LANG=en_US.UTF-8"; char *argz = 0, *iter = NULL; int argz_len; argz_create_sep(string, 58/*ASCII for : */, &argz, &argz_len); argz_print(argz, argz_len); argz_delete(&argz, &argz_len, "PWD"); argz_replace(&argz, &argz_len, "bash", ""); argz_add(&argz, &argz_len, "food=borshch"); argz_print(argz, argz_len); iter = argz_next(argz, argz_len, iter); iter = argz_next(argz, argz_len, iter); argz_insert(&argz, &argz_len, iter, "dog=boxer"); argz_print(argz, argz_len); printf("argz_count = %d\n", argz_count(argz, argz_len)); system("pause"); return 0; }
Shell
UTF-8
467
3.203125
3
[ "MIT" ]
permissive
#!/bin/bash for ROUTE in $(cat ../../../routes.json | jq -r '.[].path') do if [ ! -f ${ROUTE}.go ] then cat ../../templates/routes.tmpl | sed -e 's/ROUTEUPPER/'${ROUTE^}'/g' | sed -e 's/ROUTE/'${ROUTE}'/g' > ${ROUTE}.go fi if [ ! -d ${ROUTE} ] then mkdir ${ROUTE} cd ${ROUTE} cat ../../../templates/route-methods.tmpl | sed -e 's/ROUTEUPPER/'${ROUTE^}'/g' | sed -e 's/ROUTE/'${ROUTE}'/g' > ${ROUTE}.go fi done
C
UTF-8
3,723
2.8125
3
[]
no_license
#include<linux/futex.h> #include <sys/syscall.h> #include<sys/time.h> #include <unistd.h> #include <sys/ipc.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/stat.h> #include <fcntl.h> unsigned short xchg_8(void *ptr, unsigned char x) { __asm__ __volatile__("xchgb %0,%1" :"=r" (x) :"m" (*(volatile unsigned char *)ptr), "0" (x) :"memory"); return x; } unsigned short xchg(void *ptr, unsigned int x) { __asm__ __volatile__("xchg %0,%1" :"=r" (x) :"m" (*(volatile unsigned int *)ptr), "0" (x) :"memory"); return x; } //simple spin lock #define cpu_relax() asm volatile("pause\n": : :"memory") void simple_spin_init(char* lock){ *lock = 0; } void simple_spin_lock(char* lock){ while (true) { if (!xchg_8(lock, 1)) return; while (*lock) cpu_relax(); } } void simple_spin_unlock(char* lock){ asm("mfence"); xchg_8(lock, 0); } // optimized spin lock typedef struct{ int threadnum; int* waiting; char flag; }spinlock_t; void spin_init(spinlock_t* lock, int threadnum){ lock->threadnum = threadnum; lock->waiting = (int*)malloc(sizeof(int)*threadnum); for(int i = 0; i < threadnum; i++) lock->waiting[i] = 0; lock->flag = 0; } void spin_lock(spinlock_t* lock, int threadid){ lock->waiting[threadid] = 1; char acquire_lock = 1; while (lock->waiting[threadid] && acquire_lock) { acquire_lock = xchg_8(&lock->flag, 1); cpu_relax(); } lock->waiting[threadid] = 0; } void spin_unlock(spinlock_t* lock, int threadid){ asm("mfence"); int other = (threadid + 1) % lock->threadnum; while ((other != threadid) && !lock->waiting[other]) other = (other + 1) % lock->threadnum; if (other == threadid) xchg_8(&lock->flag, 0); else lock->waiting[other] = 0; } //mutex void mutex_lock(int* lock){ if(!xchg(lock, 1)) return; else{ syscall(SYS_futex, lock, FUTEX_WAIT, 1, 0, 0, 0); // lock = 1, goto waiting mutex_lock(lock); } } void mutex_unlock(int* lock){ asm("mfence"); xchg(lock, 0); syscall(SYS_futex, lock, FUTEX_WAKE, 1, 0, 0, 0); // 唤醒一个线程 } void mutex_init(int* lock){ *lock = 0; } // opt mutex typedef struct{ int threadnum; int* waiting; int flag; }mutexlock_t; void optmutex_lock(mutexlock_t* lock, int threadid){ /*lock->waiting[threadid] = 1; if (!lock->waiting[threadid] || !xchg(&lock->flag, 1)){ lock->waiting[threadid] = 0; return; } else{ syscall(SYS_futex, lock, FUTEX_WAIT, 1, 0, 0, 0); // lock = 1, goto waiting optmutex_lock(lock, threadid); }*/ lock->waiting[threadid] = 1; int acquire_lock = 1; while (lock->waiting[threadid] && acquire_lock) { acquire_lock = xchg(&lock->flag, 1); syscall(SYS_futex, lock, FUTEX_WAIT, 1, 0, 0, 0); // lock = 1, goto waiting } lock->waiting[threadid] = 0; } void optmutex_unlock(mutexlock_t* lock, int threadid){ asm("mfence"); int other = (threadid + 1) % lock->threadnum; while ((other != threadid) && !lock->waiting[other]) other = (other + 1) % lock->threadnum; if (other == threadid) xchg(&lock->flag, 0); else lock->waiting[other] = 0; syscall(SYS_futex, lock, FUTEX_WAKE, lock->threadnum-1, 0, 0, 0); // 唤醒线程 } void optmutex_init(mutexlock_t* lock, int threadnum){ lock->threadnum = threadnum; lock->waiting = (int*)malloc(sizeof(int)*threadnum); for(int i = 0; i < threadnum; i++) lock->waiting[i] = 0; lock->flag = 0; } // rwlock
Java
UTF-8
5,007
2.109375
2
[ "LicenseRef-scancode-ogc" ]
permissive
/* * GeoAPI - Java interfaces for OGC/ISO standards * http://www.geoapi.org * * Copyright (C) 2006-2021 Open Geospatial Consortium, Inc. * All Rights Reserved. http://www.opengeospatial.org/ogc/legal * * Permission to use, copy, and modify this software and its documentation, with * or without modification, for any purpose and without fee or royalty is hereby * granted, provided that you include the following on ALL copies of the software * and documentation or portions thereof, including modifications, that you make: * * 1. The full text of this NOTICE in a location viewable to users of the * redistributed or derivative work. * 2. Notice of any changes or modifications to the OGC files, including the * date changes were made. * * THIS SOFTWARE AND DOCUMENTATION IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE * NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED * TO, WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT * THE USE OF THE SOFTWARE OR DOCUMENTATION WILL NOT INFRINGE ANY THIRD PARTY * PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. * * COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR * CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE OR DOCUMENTATION. * * The name and trademarks of copyright holders may NOT be used in advertising or * publicity pertaining to the software without specific, written prior permission. * Title to copyright in this software and any associated documentation will at all * times remain with copyright holders. */ package org.opengis.filter; import java.util.List; import java.util.Collections; import org.opengis.util.ScopedName; import org.opengis.feature.Feature; import org.opengis.annotation.UML; import static org.opengis.annotation.Specification.ISO_19143; /** * Expression whose value is computed by retrieving the value indicated by a name in a resource. * {@code ValueReference} can used to specify the name of any property of an object whose value * shall be tested by a predicate in a filter expression. * The most common application of this is to retrieve a {@linkplain Feature feature}'s property * using a property name or an XPath expression. * * @author Chris Dillard (SYS Technologies) * @author Martin Desruisseaux (Geomatys) * @version 3.1 * * @param <R> the type of resources (e.g. {@link org.opengis.feature.Feature}) used as inputs. * @param <V> the type of values fetched by the expression. * * @since 3.1 */ @UML(identifier="ValueReference", specification=ISO_19143) public interface ValueReference<R,V> extends Expression<R,V> { /** * Returns the name of the value reference function. * The default implementation returns {@code "fes:ValueReference"}. * * @return {@code "ValueReference"} in a scope at implementation choice. */ @Override default ScopedName getFunctionName() { return Name.VALUE_REFERENCE; } /** * Returns an empty list since value references have no parameters. * * @return an empty list. */ @Override default List<Expression<? super R, ?>> getParameters() { return Collections.emptyList(); } /** * Returns the path to the property whose value will be returned by the {@code apply(R)} method. * If all characters are {@linkplain Character#isUnicodeIdentifierPart(int) Unicode identifier part}, * then the XPath expression is simply a property name. Otherwise * (i.e. if the returned path contains characters such as {@code `:`}, {@code `/`} or {@code '['}), * the returned string uses a simplified form of the XPath query language described below. * * <h4>XPath syntax</h4> * The path is relative to the resource element (e.g. the {@link Feature}), except in the case of * a join operation, in which case the path is relative to the parent of the resource element. * The following set of XPath rules shall be supported: * * <ul class="verbose"> * <li>Abbreviated form of the child axis specifier (i.e. the default form with no specifier).</li> * <li>Abbreviated form of the attribute axis specifier (i.e. the {@code '@'} character).</li> * <li>Predicate with a positive non-zero integer to indicate which child of the context node should be selected.</li> * <li>Predicate of the form {@code "child=value"} to identify a specific object property * by constraining the child elements of the property.</li> * </ul> * * <div class="note"><b>Example:</b> * {@code addresses[street="Oxfordstrasse"]/number} * </div> * * Implementations may support a larger set of XPath rules if desired. * * @return path to the property whose value will be returned by the {@code apply(R)} method. * * @see Feature#getPropertyValue(String) */ String getXPath(); }
C++
UTF-8
2,361
2.5625
3
[]
no_license
#include "operationview.h" OperationView::OperationView(QWidget *parent) : QDockWidget(parent) { widget = new QWidget(this); layout = new QGridLayout(widget); labelImage = new QLabel("图片区域",widget); labelName = new QLabel("图片名",widget); button = new QPushButton("导入图片",widget); labelBinarizationClass = new QLabel("二值化类型:",widget); combox = new QComboBox(widget); labelThreshold = new QLabel("阈值:",widget); scrollBar = new QScrollBar(Qt::Horizontal,widget); combox->addItem("二进制阈值化"); combox->addItem("反二进制阈值化"); layout->setSpacing(20); widget->setMaximumSize(250,250); labelThreshold->setText("阀值:" + QString::number(GlobalVariable::nThreshold)); scrollBar->setMaximum(255);//设置滚动条最大值 scrollBar->setMinimumWidth(100);//设置滚动条长度 scrollBar->setValue(GlobalVariable::nThreshold); layout->addWidget(labelImage,0,0,2,1); layout->addWidget(labelName,0,1,1,1); layout->addWidget(button,1,1,1,1); layout->addWidget(labelBinarizationClass,2,0,1,1); layout->addWidget(combox,2,1,1,1); layout->addWidget(labelThreshold,3,0,1,1); layout->addWidget(scrollBar,3,1,1,1); setWidget(widget); connect(button,SIGNAL(clicked()),this,SLOT(importImage())); connect(scrollBar,SIGNAL(valueChanged(int)),this,SLOT(thresholdChanged(int))); connect(combox,SIGNAL(currentIndexChanged(int)),this,SLOT(binarizationClassChanged(int))); } void OperationView::getImage(QString imageName) { labelName->setText(imageName); QPixmap *pixmap = new QPixmap(QPixmap::fromImage(GlobalVariable::imageSource->scaled(100,100))); labelImage->setPixmap(*pixmap); labelImage->resize(pixmap->size()); button->setText("重新导入图片"); emit refresh(); } void OperationView::thresholdChanged(int _scrollBarValue) { GlobalVariable::nThreshold = _scrollBarValue; labelThreshold->setText("阈值:" + QString::number(_scrollBarValue)); emit refresh(); } void OperationView::binarizationClassChanged(int index) { if(index == 0) GlobalVariable::binarizationClass = true; else GlobalVariable::binarizationClass = false; emit refresh(); }
Java
UTF-8
671
2.640625
3
[]
no_license
package com.example.azatsepin.theguardianreader.utils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public final class Utils { private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss yyyy-MM-dd"); private static SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); public static String formatDate(String dateFromApi) { Date date = null; try { date = simpleDateFormat2.parse(dateFromApi); } catch (ParseException e) { e.printStackTrace(); } return simpleDateFormat.format(date); } }
Rust
UTF-8
679
3.78125
4
[]
no_license
pub fn brackets_are_balanced(string: &str) -> bool { let mut stack: Vec<String> = Vec::new(); for elem in string.chars() { let elem = elem.to_string(); if elem == "{" || elem == "[" || elem == "(" { stack.push(elem.clone()); }; if elem == "}" || elem == "]" || elem == ")" { if stack.is_empty() || !is_matching_pair(&stack.pop().unwrap(), &elem.to_string()) { return false; } } } stack.is_empty() } fn is_matching_pair(c1: &str, c2: &str) -> bool { match c1 { "{" => c2 == "}", "(" => c2 == ")", "[" => c2 == "]", _ => false, } }
Python
UTF-8
1,092
3.046875
3
[]
no_license
from itertools import permutations, combinations, chain def solution(relation): answer = 0 column_cnt = len(relation[0]) tuple_cnt = len(relation) tmp = [i for i in range(column_cnt)] keys = [] for i in range(len(tmp)): for j in list(combinations(tmp, i+1)): if tuple_cnt == re_relation(relation, j): keys.append(j) tmp = [] print(keys) for i in range(len(keys)): for j in keys[i+1:]: if set(keys[i]) < set(j): tmp.append(j) for i in set(tmp): keys.remove(i) answer = len(keys) print(keys) return answer def re_relation(ori_relation, k): new_realation = [] for t in ori_relation: new_row = [] for i in k: new_row.append(t[i]) new_realation.append(new_row) return len(set(tuple(sorted(sub)) for sub in new_realation)) solution([["100","ryan","music","2"],["200","apeach","math","2"],["300","tube","computer","3"],["400","con","computer","4"],["500","muzi","music","3"],["600","apeach","music","2"]])
Markdown
UTF-8
2,568
2.75
3
[ "MIT" ]
permissive
+++ # About/Biography widget. widget = "about" active = true date = "2017-12-20T00:00:00" # Order that this section will appear in. weight = 5 +++ Building robust statistical infrastructure that ensure the collection and the analysis of statistical information to inform citizen, decision makers and scientists is a challenge for many country. Statistical systems have to balance the necessity of local relevance of the information they collect with the requirements of different levels of international norms. The mix of political and technical logics and constraints that have to be taken into account to design and implement national statistical stystems is increasingly complex to navigate, in a time when both innovations in data science and an evolving landscape of globalized actors radically redefine the global field of public measurement. My work and research is aimed at disentangling these dyamics in the field of Global Health. Most of this work is oriented towards enabling local actors of health systems in low-resource settings to build national health information systems that are adequate and efficient. The projects I typically work on are of three types: * **Tools development:** I develop tools for health systems, to improve routine data collection and analysis. This line of work encompasses the adaptation of global data definitions to specific health systems, the comprehensive mapping of data requirements, and the development of tools adapted to local conditions of user. * **Methods research:** The simplification of tools often requires a larger redistribution of the computational work in health information systems. This involves identifying the right level of aggregation for different metrics, developing innovative analytic approaches to make the best use of any data available, and testing and implementation new analytical methods. * **Strategic reflection:** Disentangling technical and political dimensions of statistical systems is essential to orient methodological research and tool development. Different stakeholders need to differentiate the methodological requirements from the domains in which power relationship are exerted or where negotiations should take place. I develop frameworks to guide this analysis for national and local players. In all of my projects, I aim at fostering the development of statistical systems as public goods. Such systems should serve most in need populations, by adequatly measuring their needs and by focusing on the proper representation of invisible and underserved populations.
C#
UTF-8
826
3.375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace assignment5._2 { class Fraction { public int Numerator; public int Denominator; public Fraction() { Numerator = 1; Denominator = 1; } public Fraction(int Numerator, int Denominator) { this.Numerator = Numerator; this.Denominator = Denominator; } public override string ToString() { return Numerator + "/" + Denominator; } public static Fraction operator +(Fraction p1, Fraction p2) { Fraction result = new Fraction(); result.Numerator = p1.Numerator * p2.Denominator + p2.Numerator * p1.Denominator; result.Denominator = p1.Denominator * p2.Denominator; return result; } } }
JavaScript
UTF-8
8,761
2.703125
3
[]
no_license
/*jslint browser: true, unparam: true*/ (function (tangelo, $) { 'use strict'; if (!$) { tangelo.AbstractMapLayer = tangelo.unavailable({ plugin: "AbstractMapLayer", required: ["JQuery"] }); return; } function abstractFunction () { tangelo.fatalError('AbstractMapLayer', 'Unimplemented abstract method called'); } // An abstract class defining a mapping layer interface tangelo.AbstractMapLayer = function () { var layers = {}, // all existing internal layers events = {}; // all events // an abstract representation of a position on the map // contains both pixel and gis coordinates with callbacks // for reprojecting... in the future, maybe add a means for // automatic reprojection based on map events this.Position = function () { this.x = abstractFunction; this.y = abstractFunction; this.lat = abstractFunction; this.lng = abstractFunction; this.reproject = abstractFunction; this.toString = function () { return 'Point(' + [this.x(), this.y()].join() + '), LatLng(' + [this.lng(), this.lat()].join() + ')'; }; }; // a position which is tied to a pixel on the screen this.Point = function (x, y) { var latLng; this.x = function () { return x; }; this.y = function () { return y; }; this.lat = function () { return latLng[0]; }; this.lng = function () { return latLng[1]; }; this.reproject = function () { latLng = this.pointToLatLng(x, y); return this; }; this.reproject(); }; this.Point.prototype = new this.Position(); // a position which is tied to a point on the map this.LatLng = function (lat, lng) { var point; this.lat = function () { return lat; }; this.lng = function () { return lng; }; this.x = function () { return point[0]; }; this.y = function () { return point[1]; }; this.reproject = function () { point = this.latLngToPoint(lat, lng); return this; }; this.reproject(); }; this.LatLng.prototype = new this.Position(); // represents a rectangle on the screen, the way it is // implemented the bounds of the map can returned by // // bds = new LatLngBounds( new Point(0, height), new Point(width, 0) ); // // the gis coordinates can then be updated with bds.reproject() // on drags and zooms this.LatLngBounds = function (southWest, northEast) { this.southWest = function () { return southWest; }; this.northEast = function () { return northEast; }; this.reproject = function () { southWest.reproject(); northEast.reproject(); return this; }; this.reproject(); // other methods? // this are largely implemented by both google maps and openlayers this.contains = abstractFunction; this.extend = abstractFunction; this.getCenter = abstractFunction; this.intersects = abstractFunction; this.union = abstractFunction; }; // event handling infrastructure exposed to allow the possibility to // register new events inside individual layers this.Event = function (name) { var callbacks = $.Callbacks(), // call backs are registered here evt = this; this.addCallback = function (f) { callbacks.add(f); return evt; }; this.trigger = function (context, args) { callbacks.fireWith(context, [args]); return evt; }; this.removeCallback = function (f) { callbacks.remove(f); return evt; }; }; // add standard events events = { drag: new this.Event('drag'), // fired continually during drag events zoom: new this.Event('zoom'), // fired on zoom out/in load: new this.Event('load') // fired once, when the map is finished loading }; // add a getter for events this.getEvent = function (eventType) { return events[eventType]; }; // standard mechanism for attaching callbacks to events // eventType: the named event from the events object // f: function to call this.on = function (eventType, f) { var that = this; if (!Array.isArray(eventType)) { eventType = [eventType]; } eventType.forEach(function (e) { if (!events.hasOwnProperty(e)) { tangelo.fatalError('abstractMapLayer.on', 'Unknown eventType ' + e); } if (e === 'load' && that.loaded()) { f( { load: true } ); } else { events[e].addCallback(f); } }); return this; }; // Create a new div element for a layer inside the map // Possibly add options to control creation of the div like z-index, etc. this.addLayer = function (name, options) { if (layers.hasOwnProperty(name)) { tangelo.fatalError('Trying to add a layer with a name that already exists'); } layers[name] = this.getInnerDiv(); return layers[name]; }; // Return a named layer this.layers = function (name) { return layers[name]; }; // methods to be implemented by inherited classes // Returns a pixel location from latitude/longitude: // function (latitude, longitude) { ...; return [x, y]; } this.pointToLatLng = abstractFunction; // Returns a latitude/longitude from pixel coordinates // function (x, y) { ...; return [latitude, longitude]; } this.latLngToPoint = abstractFunction; // Returns a LatLngBounds object representing the current map extent // function () { ...; return new LatLngBounds(...); } // note: could be implemented here with callbacks for x/y offsets // and width/height of map this.bounds = abstractFunction; // For the following, svg/canvas layers need to come from the map // in order to properly handle mouse events. // function (options) { ... return div; } // options.moving: layer drags with the map [default: true] this.getInnerDiv = abstractFunction; // Subclasses must also trigger the following events, with the // specified call signature: // // load: this.events.load.trigger(this, f) // function f() { {load: true} } // // zoom: this.events.zoom.trigger(this, f) // function f( {zoom: true, oldZoom: x, newZoom: y} ) // // drag: this.events.drag.trigger(this, f) // function f( {drag: true, mouseStart: Position, mouseNow: Position, // dragDelta: [dx, dy]} ) // gives the position at the start of the drag and the // current mouse position, dragDelta gives the number of pixels // the map has moved during the drag // Allows layers to query whether a drag event is occuring. // return true, if dragging // return false, if not dragging this.dragging = abstractFunction; // Returns true if the map is loaded and ready for interaction this.loaded = abstractFunction; // Pans the map to be centered at the indicated location // takes a this.LatLng object as an argument this.setCenter = abstractFunction; // Returns the coordinates of the center of the map as a // this.LatLng object. this.getCenter = abstractFunction; // Zooms the map to the indicated zoom level // takes an integer as input... the zoom level will be // truncated to the nearest valid zoom level this.setZoom = abstractFunction; // Returns the current zoom level of the map this.getZoom = abstractFunction; }; }(window.tangelo, window.$));
Python
UTF-8
471
2.671875
3
[]
no_license
import numpy as np from PIL import ImageFont, ImageDraw, Image import cv2 import time ## Make canvas and set the color def drawText(img, text, pos, fontSize, color=(255,255,255)): b,g,r = color fontpath = "./service/font/FC Iconic Bold.ttf" font = ImageFont.truetype(fontpath, fontSize) img_pil = Image.fromarray(img) draw = ImageDraw.Draw(img_pil) draw.text(pos, text, font = font, fill = (b, g, r)) img = np.array(img_pil) return img
Ruby
UTF-8
680
2.625
3
[ "MIT" ]
permissive
require_relative './util' notes_path = ENV['STANDUP_NOTES_PATH'] || 'daily/standup' note_type = 'standup' title = title_today('Standup') tags = %w[notes daily solstice standups] people = %w[Ugwem Cole Tyler Ekundayo] person_standup_template = <<~STT ### {{name}}: - yest: - - today: - - asks: - STT standup_template_content = people.map do |person_name| person_standup_template.gsub('{{name}}', person_name) end.join("\n") text = <<~TXT #{front_matter_yaml(title, tags)} # #{title} #{standup_template_content} TXT file_name = create_file_name(note_type, notes_path) write_file(file_name, text) puts "created standup file at: #{file_name}" open_file(file_name)
JavaScript
UTF-8
1,201
2.78125
3
[]
no_license
const Engine = Matter.Engine; const World= Matter.World; const Bodies = Matter.Bodies; const Body = Matter.Body; const Constraint = Matter.Constraint; var engine, world, body; //var bob1; function preload(){ } function setup(){ var canvas = createCanvas(windowWidth/1, windowHeight/1.5); engine = Engine.create(); world = engine.world; //fill("black"); bob1 = new Bob(300,150); rope1 = new Sling(bob1.body,{x:300,y:75}); bob2 = new Bob(350,150); rope2 = new Sling(bob2.body,{x:350,y:75}); bob3 = new Bob(400,150); rope3 = new Sling(bob3.body,{x:400,y:75}); bob4 = new Bob(450,150); rope4 = new Sling(bob4.body,{x:450,y:75}); bob5 = new Bob(500,150); rope5 = new Sling(bob5.body,{x:500,y:75}); Engine.run(engine); } function draw(){ background("lightGray"); Engine.update(engine); bob1.display(); rope1.display(); bob2.display(); rope2.display(); bob3.display(); rope3.display(); bob4.display(); rope4.display(); bob5.display(); rope5.display(); bobMove(); } function bobMove(){ if (keyCode === UP_ARROW) { Matter.Body.applyForce(bob1.body,bob1.body.position,{x:-10,y:0}); } }
Python
UTF-8
174
2.78125
3
[]
no_license
#!/usr/bin/python3 import math matrix_divided = __import__('2-matrix_divided').matrix_divided matrix = [ [1, 2] ] print(matrix_divided(matrix, math.inf)) print(matrix)
Python
UTF-8
4,077
2.546875
3
[ "Apache-2.0" ]
permissive
""" This is a template for creating custom RegexBasedColumnMapExpectations. For detailed instructions on how to use it, please see: https://docs.greatexpectations.io/docs/guides/expectations/creating_custom_expectations/how_to_create_custom_regex_based_column_map_expectations """ from typing import Dict, Optional from great_expectations.core.expectation_configuration import ExpectationConfiguration from great_expectations.exceptions.exceptions import ( InvalidExpectationConfigurationError, ) from great_expectations.expectations.regex_based_column_map_expectation import ( RegexBasedColumnMapExpectation, RegexColumnMapMetricProvider, ) class ExpectColumnValuesToBeValidArn(RegexBasedColumnMapExpectation): """Expect values in this column to be a valid amazon arn.""" # These values will be used to configure the metric created by your expectation regex_camel_name = "AmazonResourceName" regex = "^arn:(?P<Partition>[^:\n]*):(?P<Service>[^:\n]*):(?P<Region>[^:\n]*):(?P<AccountID>[^:\n]*):(?P<Ignore>(?P<ResourceType>[^:\/\n]*)[:\/])?(?P<Resource>.*)$" semantic_type_name_plural = "arns" # These examples will be shown in the public gallery. # They will also be executed as unit tests for your Expectation. examples = [ { "data": { "valid_arns": [ "arn:aws:s3:::my-bucket/my-object", "arn:partition:service:region:account-id:resource", ], "invalid_alphanumeric": [ "apz8", "bubba:arn:123", ], "invalid_arn": [ "arn:aws:::::::my-bucket/my-object", "arn::::", ], "empty": ["", None], }, "tests": [ { "title": "basic_positive_test", "exact_match_out": False, "include_in_gallery": True, "in": {"column": "valid_arns"}, "out": { "success": True, }, }, { "title": "basic_negative_test", "exact_match_out": False, "include_in_gallery": True, "in": {"column": "invalid_alphanumeric", "mostly": 1}, "out": { "success": False, }, }, { "title": "invalid_non_alphanumeric", "exact_match_out": False, "include_in_gallery": True, "in": {"column": "invalid_arn", "mostly": 1}, "out": { "success": False, }, }, { "title": "empty", "exact_match_out": False, "include_in_gallery": True, "in": {"column": "empty", "mostly": 1}, "out": { "success": False, }, }, ], } ] # Here your regex is used to create a custom metric for this expectation map_metric = RegexBasedColumnMapExpectation.register_metric( regex_camel_name=regex_camel_name, regex_=regex, ) # This object contains metadata for display in the public Gallery library_metadata = { "maturity": "experimental", "tags": [ "amazon", "arn", "expectation", ], # Tags for this Expectation in the Gallery "contributors": [ # Github handles for all contributors to this Expectation. "@rdodev", # Don't forget to add your github handle here! ], } if __name__ == "__main__": ExpectColumnValuesToBeValidArn().print_diagnostic_checklist()
Swift
UTF-8
1,429
2.734375
3
[]
no_license
// // DockWidgetView.swift // OpenTouchBar // // Created by Nikita Arutyunov on 13/01/2019. // Copyright © 2019 Nikita Arutyunov. All rights reserved. // class DockWidgetView: NSStackView { let dragTargetView: NSView! override open var intrinsicContentSize: NSSize { return NSSize(width: NSView.noIntrinsicMetric, height: NSView.noIntrinsicMetric) } override init(frame frameRect: NSRect) { let imageView = NSImageView(image: NSImage(named: "DragTarget") ?? NSImage()) imageView.wantsLayer = true imageView.layer?.opacity = 0.8 imageView.layer?.cornerRadius = 4 imageView.translatesAutoresizingMaskIntoConstraints = false imageView.autoresizingMask = .none imageView.isHidden = true self.dragTargetView = imageView super.init(frame: frameRect) self.addSubview(self.dragTargetView) } required init?(coder decoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func dragViewAtPoint(point: NSPoint) -> NSView? { let point = self.convert(point, from: nil) var view = self.hitTest(point) while view != nil { guard let currentView = view else { return nil } if currentView.isKind(of: DockWidgetItemView.self) || currentView.isKind(of: DockWidgetButton.self) { break } view = currentView.superview } return view } }
Java
UTF-8
156
1.664063
2
[]
no_license
public class marcaZap { String zapato1 = "Dr Martens"; String zapato2 = "Nike"; String zapato3 = "Vans"; String zapato4 = ""; }
C#
UTF-8
1,979
2.953125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FiddleFiddle.Logon { class NotImplementedFiddleTask : Exception { } interface ILogonTask { void DoTask(); } /// <summary> /// Logon 관련 Task 의 Factory 를 제공한다. /// </summary> public class FiddleTaskContrcutor { FiddleTaskContrcutor(bool predefined=true) { if (predefined) { } } IEnumerable<IFiddleTask> GetFiddleTasks() { List<IFiddleTask> tasks = new List<IFiddleTask>(); // 작업 추가 // tasks.Add(new JwtLogonTask()) // tasks.Add(new CacheTask()) // tasks.Add(new .... ) return tasks; } IEnumerable<IFiddleTask> GetFiddleTasks(IEnumerable<PreTaskItem> preTaskItems) { List<IFiddleTask> tasks = new List<IFiddleTask>(); // 작업 추가 foreach(var item in preTaskItems) { try { var task = GetNewTaskWithEnum(item); tasks.Add(task); } catch (NotImplementedFiddleTask) { } } return tasks; } IFiddleTask GetNewTaskWithEnum(PreTaskItem item) { switch (item) { case PreTaskItem.Logon: throw new NotImplementedFiddleTask(); default: throw new NotImplementedFiddleTask(); } } } public enum PreTaskItem { Logon, Cache } public interface IFiddleTask { void DoTask(); // Task 작업 시작 bool IsCompleted(); // Task 종료 체크 event EventHandler CompleteFiddleTasks; } }
Markdown
UTF-8
18
2.71875
3
[]
no_license
# 22may-001-public
Python
UTF-8
311
3
3
[]
no_license
from env import HEIGHT class Spot: def __init__(self, value_x=0, value_y=0, radius=5): self.value_x = value_x self.value_y = value_y self.radius = radius # self.pos_x = 0 # self.pos_y = 0 def get_pos(self): return int(self.value_x), int(self.value_y)
Java
UTF-8
1,980
2.796875
3
[ "MIT" ]
permissive
package com.firebase.androidchat; import java.util.ArrayList; import java.util.Map; import java.util.Scanner; import java.util.HashMap; public class Person { @SuppressWarnings("unused") private String name; private ArrayList<Person> friends; private ArrayList<Debt> debts; private ArrayList<Debt> loans; private final long time; Person(String nm) { name = nm; friends = new ArrayList<Person>(); debts = new ArrayList<Debt>(); loans = new ArrayList<Debt>(); time = System.currentTimeMillis(); } String getName() { return name; } void changeName(String nm) { name = nm; } void addFriend(Person friend) { if (!friends.contains(friend)) friends.add(friend); } void removeFriend(Person friend) { friends.remove(friend); } void addLoan(Debt loan) { if (!loans.contains(loan)) loans.add(loan); } void addDebt(Debt debt) { if (!debts.contains(debt)) debts.add(debt); } int getScore() { int total = 0, ontime = 0; for (Debt d : debts) { total++; if (d.getontime()) ontime++; } int size = debts.size(); long age = System.currentTimeMillis() - time; double score = 70 * ontime / total; if (size >= 10) score += 20; else score += 2 * size; if (age > 2628000000L * 12) score += 10; else score += 10 * (age / (2628000000L * 12)); int scr = (int) (300 + score * 5.5); return scr; } void deleteLoan(Debt loan) { for (Debt l : loans) if (l.equals(loan)) l.clear(); } void deleteDebt(Debt debt) { for (Debt d : debts) if (d.equals(debt)) d.clear(); } void poke(Person p) { p.getPoked(); } void getPoked() { } boolean equals(Person p) { return (p.name.equals(name) && p.time == time); } Map<String, Object> map() { Map<String, Object> map = new HashMap<String, Object>(); map.put("name", name); map.put("friends", friends); map.put("debts", debts); map.put("loans", loans); map.put("time", time); return map; } }
Java
UTF-8
357
2.296875
2
[]
no_license
package com.hcpurchase.util; import java.text.SimpleDateFormat; import java.util.Date; public class DateUtil { private static Date date = new Date(); private static final String str = "yyyyMMddhhmmss"; public static String getNowString() { SimpleDateFormat sdf = new SimpleDateFormat(str); String string = sdf.format(date); return string; } }
Ruby
UTF-8
668
2.859375
3
[]
no_license
module SAW module Entities # +SAW::Entities::UnitsPricing+ # # This entity represents an object with available rates for property # units: entity includes +units+ array which has unit rates and the # currency used for the current property # # Attributes # # +property_id+ - property id # +currency+ - currency code # +units+ - array of +SAW::Entities::UnitRate+ objects class UnitsPricing attr_reader :property_id, :units, :currency def initialize(property_id:, units:, currency:) @property_id = property_id @units = units @currency = currency end end end end