language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
689
3.625
4
[]
no_license
import java.util.Scanner; class Main { public static void main(String[] args) { Scanner myScanner = new Scanner(System.in); int[] myArray = new int[6]; int firstHalf = 0; int secondHalf = 0; String[] numbers = myScanner.next().split(""); for (int i = 0; i < 6; i++) { myArray[i] = Integer.parseInt(numbers[i]); if (i < 3) { firstHalf += myArray[i]; } else { secondHalf += myArray[i]; } } if (secondHalf == firstHalf) { System.out.println("Lucky"); } else { System.out.println("Regular"); } } }
SQL
UTF-8
881
3.4375
3
[]
no_license
create or replace procedure update_pembelian_by_id( p_id in pembelian.id%type, p_id_produk in pembelian.id_produk%type, p_banyak_produk in pembelian.banyak_produk%type, p_harga_produk in pembelian.harga_produk%type, p_id_pemasok pembelian.id_pemasok%type ) as v_kode pembelian.kode%type; v_created_at pembelian.created_at%type; begin select kode, created_at into v_kode, v_created_at from pembelian where id = p_id; delete pembelian where id = p_id; insert into pembelian( id, kode, id_produk, banyak_produk, harga_produk, id_pemasok, created_at, updated_at ) values( p_id, v_kode, p_id_produk, p_banyak_produk, p_harga_produk, p_id_pemasok, to_timestamp(v_created_at, 'dd-mon-yyyy hh.mi.ss.FF AM'), sysdate ); commit; end update_pembelian_by_id; /
C#
UTF-8
756
3.25
3
[]
no_license
using System; namespace Part1_2 { class Program { static void Main(string[] args) { var startPosition = Console.ReadLine(); var finishPosition = Console.ReadLine(); int stNum = int.Parse(startPosition[1].ToString()); int fshNum = int.Parse(finishPosition[1].ToString()); if (startPosition[0] == finishPosition[0]) { if (Math.Abs(stNum - fshNum) == 1 && (stNum != 1 || stNum != 8)) Console.WriteLine("Yes"); else if (Math.Abs(stNum - fshNum) == 2 && (stNum == 2 || stNum == 7)) Console.WriteLine("Yes"); else Console.WriteLine("No"); } else Console.WriteLine("No"); } } }
C++
UTF-8
1,160
2.765625
3
[ "MIT" ]
permissive
#ifndef __SCOPE_H #define __SCOPE_H #include "abstract.h" // --------------------------------------------------------------------------------------------------------------------- // Struct definitions /// a scope is the context in which the compiler and runtime environment resolve references /// and add new references. /// [ReferencesIndex] contains all references available in the scope /// [InheritedScope] is a link to the parent scope and to inherited references struct Scope { std::vector<Reference*> ReferencesIndex; Scope* InheritedScope; bool IsDurable; /// new scope std::vector<Call*> CallsIndex; }; // --------------------------------------------------------------------------------------------------------------------- // Constructors/Destructors /// create a new scope with [inheritedScope] Scope* ScopeConstructor(Scope* inheritedScope); /// destroys the [scope] void ScopeDestructor(Scope* scope); /// DEP: void AddReferenceToScope(Reference* ref, Scope* scope); /// add [call] to [scope] void AddCallToScope(Call* call, Scope* scope); /// return a deep copy of [scp] Scope* CopyScope(Scope* scp); #endif
Markdown
UTF-8
1,323
2.734375
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- description: "Learn more about: Compiler Error C3408" title: "Compiler Error C3408" ms.date: "11/04/2016" f1_keywords: ["C3408"] helpviewer_keywords: ["C3408"] ms.assetid: 1f5ea979-fb1e-4214-b310-6fd6ca8249b1 --- # Compiler Error C3408 'attribute': attribute is not allowed on template definitions Attributes cannot be applied to template definitions. ## Example The following sample generates C3408. ```cpp // C3408.cpp // compile with: /c template <class T> struct PTS { enum { IsPointer = 0, IsPointerToDataMember = 0 }; }; template <class T> [coclass] // C3408 struct PTS<T*> { enum { IsPointer = 1, IsPointerToDataMember = 0 }; }; template <class T, class U> struct PTS<T U::*> { enum { IsPointer = 1, IsPointerToDataMember = 1 }; }; struct S{}; extern "C" int printf(const char*,...); int main() { S s, *pS; int S::*ptm; printf("PTS<S>::IsPointer == %d PTS<S>::IsPointerToDataMember == %d\n", PTS<S>::IsPointer, PTS<S>:: IsPointerToDataMember); printf("PTS<S*>::IsPointer == %d PTS<S*>::IsPointerToDataMember == %d\n", PTS<S*>::IsPointer, PTS<S*>:: IsPointerToDataMember); printf("PTS<int S::*>::IsPointer == %d PTS<int S::*>::IsPointerToDataMember == %d\n", PTS<int S::*>::IsPointer, PTS<int S::*>:: IsPointerToDataMember); } ```
Java
UTF-8
1,924
2.296875
2
[]
no_license
package br.edu.ifsp.spo.bulls.users.api.domain; import javax.persistence.*; import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import java.io.Serializable; import java.time.LocalDateTime; import java.util.UUID; @Data @Entity @ApiModel(value = "Objeto de domínio: Login ") @Table(name = "users") public class User implements Serializable { /** * */ private static final long serialVersionUID = -3104545566617263249L; @Id @ApiModelProperty(value = "Identificador") @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id", updatable = false, unique = true, nullable = false) private UUID id; @ApiModelProperty(value = "Nome de usuário") @NotBlank(message = "UserName is mandatory") private String userName; @ApiModelProperty(value = "Email") @NotBlank(message = "Email is mandatory") @Email(message = "Email format is invalid") private String email; @ApiModelProperty(value = "Senha") @NotBlank(message = "Password is mandatory") private String password; @ApiModelProperty(value = "Token de login") private String token; @ApiModelProperty(value = "Token de login com o google") private String idSocial; @ApiModelProperty(value = "Data de criação") private LocalDateTime creationDate; @ApiModelProperty(value = "Indica se o usuário tem o cadastro confirmado") private Boolean verified ; @PrePersist public void prePersist() { creationDate = LocalDateTime.now(); verified = false; } public User(String userName, @NotBlank(message = "Email is mandatory") String email, @NotBlank(message = "Password is mandatory") String password) { super(); this.userName = userName; this.email = email; this.password = password; } public User() { } }
Markdown
UTF-8
2,514
3.703125
4
[]
no_license
#### 第三章 函数 把简单的事情做到极致,功到自然成,最终“止于至善”。 ——秋山利辉《匠人精神》 ### 1 什么是函数 - 函数(function)作为数学概念,最早由我国清朝数学家李善兰翻译,出自其著作《代数学》。 - 之所以这么翻译,他给出的理由是“**凡此变数中函彼变数者,则此为彼之函数**”,即函数指一个量随着另一个量的变化而变化,或者说一个量中包含另一个量。 ### 2 软件中的函数 #### 2.1 计算机中函数的定义 在计算机编程中,函数的作用和数学中的定义类似。函数是**一组代码的集合**,是程序中**最小的功能模块**,一次函数调用包括接收参数输入、数据处理、返回结果。 #### 2.2 函数参数 - 最理想的参数数量是零(零参数函数),其次是一(一元函数),再次是二(二元函数),应尽量避免三(三元函数)。有足够特殊的理由,才能用3个以上参数(多元函数)。当然凡事也不是绝对的,关键还是`看场景`,在程序设计中,一大忌讳就是教条 - 总体上来说,参数越少,越容易理解,函数也越容易使用和测试,因为各种参数的不同组合的测试用例是一个笛卡儿积。 ### 3 短小的函数 - Robert C. Martin有一个信条:**函数的第一规则是要短小,第二规则是要更短小**。 - 有时保持代码的逻辑不变,只是把长方法改成`多个短方法`,代码的可读性就能提高很多。 ### 4 职责单一 - 一个方法只做一件事情,也就是函数级别的`单一职责原则`(Single Responsibility Principle,SRP)。 - 遵循SRP不仅可以提升代码的`可读性`,还能提升代码的`可复用性`。因为职责越单一,功能越内聚,就越有可能被复用 ### 5 精简辅助代码 - 所谓的辅助代码(Assistant Code),是程序运行中必不可少的代码,但又不是处理业务逻辑的核心代码,比如判空、打印日志、鉴权、降级和缓存检查等。 - 让函数中的代码能直观地体现业务逻辑,而不是让业务代码淹没在辅助代码中。 ### 6 本章小结 - 函数是软件系统中的核心要素,无论采用哪种编程范式和编程语言,程序逻辑都是写在函数中的,因此编写好函数是编写好代码的基础。 - 一个系统容易腐化的部分正是函数,不解决函数的复杂性,就很难解决系统的复杂性。
Python
UTF-8
2,105
2.84375
3
[]
no_license
class DeliveryDTO(object): user_email = "" courier_name = "" product_type = "" product = "" city = "" region = "" street = "" marketing_source = "" home = 1 building = 1 delivery_order_date_time = "" delivery_complete_date_time = "" total_sum = 0 # The class "constructor" - It's actually an initializer def __init__(self, user_email, courier_name, product_type, product, city, region, street, marketing_source, home, building, delivery_order_date_time, delivery_complete_date_time, total_sum): self.user_email = user_email self.courier_name = courier_name self.product_type = product_type self.product = product self.city = city self.region = region self.street = street self.marketing_source = marketing_source self.home = home self.building = building self.delivery_order_date_time = delivery_order_date_time self.delivery_complete_date_time = delivery_complete_date_time self.total_sum = total_sum @staticmethod def make_delivery(user_email, courier_name, product_type, product, city, region, street, marketing_source, home, building, delivery_order_date_time, delivery_complete_date_time, total_sum): delivery_obj = DeliveryDTO(user_email, courier_name, product_type, product, city, region, street, marketing_source, home, building, delivery_order_date_time, delivery_complete_date_time, total_sum) return delivery_obj
C++
UTF-8
886
2.796875
3
[ "MIT" ]
permissive
/* ------------------------------------------------------------------------------ This software is in the public domain, furnished "as is", without technical support, and with no warranty, express or implied, as to its usefulness for any purpose. File: Player.h Author: Joshua Churning Date: January 28, 2016 ------------------------------------------------------------------------------ */ #ifndef PLAYER_H #define PLAYER_H #include "GamePlayed.h" #include <string> #include <vector> using namespace std; class Player { public: int id; string name; vector<int> friends; vector<GamePlayed> gamesPlayed; int gamerscore; Player (int, string); }; /*----------------------------------------------------------------- CONSTRUCTOR -----------------------------------------------------------------*/ Player::Player (int x, string y) { id = x; name = y; gamerscore = 0; } #endif
JavaScript
UTF-8
1,203
2.59375
3
[]
no_license
const Cohort = require('../models/cohort.model'); const router = require('express').Router(); // Middle ware const auth = require('./middleware/auth'); // @route GET /cohorts/ // @desc Returns all coherts // @access Public router.route('/').get((req, res) => { Cohort.find({}) .then(coherts => res.send(coherts)); }) router.route('/:id').get((req, res) => { Cohort.findById(req.params.id) .then(cohort => res.send(cohort)) .catch(err => res.json({msg: 'Cohort does not exists'})); }); // @route GET /cohorts/ // @desc Deletes all cohorts, TEMP // @access Public router.route('/').delete((req, res) => { Cohort.deleteMany({}) .then(cohorts => res.send('All cohorts deleted')); }) // @route POST /cohorts/ // @desc Creates a new cohert // @access Public for now, going to change it to a private path router.route('/').post((req, res) => { const {cohortName, cohortSchool, cohortOrg, adminUser} = req.body; const newCohort = new Cohort({cohortName, cohortSchool, cohortOrg, adminUser}); newCohort.save() .then(newRegCohort => { res.send('Success'); }) .catch (err => res.status(400).json('Error: ' + err)); }) module.exports = router;
Rust
UTF-8
5,060
3.203125
3
[]
no_license
use tetra::graphics::{self, Color, DrawParams, Texture, Rectangle, Camera}; use tetra::math::Vec2; use tetra::{Context, ContextBuilder, State, Event}; use std::collections::HashMap; use serde::{Serialize, Deserialize}; use std::fs::File; use std::io::Read; #[derive(Serialize, Deserialize)] struct MapData { image: String, tiles: HashMap<i32, TileData>, width: usize, height: usize, low: [[i32; 10]; 10], mid: [[i32; 10]; 10], high: [[i32; 10]; 10], } #[derive(Serialize, Deserialize)] struct Clip { x: i32, y: i32, width: i32, height: i32, } impl Clip { fn as_rectangle(&self) -> Rectangle { Rectangle { x: self.x as f32 * ISO_WIDTH, y: self.y as f32 * ISO_HEIGHT, width: self.width as f32, height: self.height as f32 } } } #[derive(Serialize, Deserialize)] struct Point { x: i32, y: i32, } #[derive(Serialize, Deserialize)] struct TileData { clip: Clip, origin: Point, } struct Map { tiles: HashMap<i32, Tile>, low: [[i32; 10]; 10], mid: [[i32; 10]; 10], high: [[i32; 10]; 10], } impl Map { fn from_json(ctx: &mut Context, filename: &str) -> Self { let map_json = read_file(filename); let map_data: MapData = serde_json::from_str(&map_json).unwrap(); let texture = Texture::new(ctx, map_data.image).unwrap(); let mut tiles = HashMap::new(); for (index, tile) in map_data.tiles { tiles.insert(index, Tile { texture: texture.clone(), clip: tile.clip.as_rectangle(), origin: Vec2::new(tile.origin.x as f32, tile.origin.y as f32), }); } Self { low: map_data.low, mid: map_data.mid, high: map_data.high, tiles, } } } pub fn read_file(filepath: &str) -> String { let mut file = File::open(filepath) .expect("could not open file"); let mut contents = String::new(); file.read_to_string(&mut contents).unwrap(); contents } const ISO_WIDTH: f32 = 64.0; const ISO_HEIGHT: f32 = 64.0; struct Tile { texture: Texture, clip: Rectangle, origin: Vec2<f32>, } impl Tile { fn draw(&self, ctx: &mut Context, x: i32, y: i32) { let position = cartesian_to_isometric(Vec2::new(x,y)); graphics::draw( ctx, &self.texture, DrawParams::new() .position(position) .origin(self.origin) .clip(self.clip), ); } } fn cartesian_to_isometric(cartesian_position: Vec2<i32>) -> Vec2<f32> { Vec2::new( (cartesian_position.x - cartesian_position.y) as f32, (cartesian_position.x + cartesian_position.y) as f32 / 2.0 ) } fn isometric_to_cartesian(isometric_position: Vec2<f32>) -> Vec2<i32> { Vec2::new( (2.0 * isometric_position.y + isometric_position.x) as i32 / 2, (2.0 * isometric_position.y - isometric_position.x) as i32 / 2 ) } struct GameState { camera: Camera, map: Map, } impl GameState { fn new(ctx: &mut Context) -> tetra::Result<GameState> { let mut camera = Camera::with_window_size(ctx); camera.position.x = 32.0; camera.position.y = 48.0; camera.set_viewport_size(640.0, 480.0); camera.update(); let map = Map::from_json(ctx, "./resources/lake.json"); Ok(GameState { camera, map, }) } } impl State for GameState { fn draw(&mut self, ctx: &mut Context) -> tetra::Result { graphics::clear(ctx, Color::rgb(0.0, 0.0, 0.0)); graphics::set_transform_matrix(ctx, self.camera.as_matrix()); for row in 0..10 { for col in 0..10 { let x = (col * 32) as i32; let y = (row * 32) as i32; let tile_index = self.map.low[row][col]; if tile_index > 0 { let tile = &self.map.tiles[&tile_index]; tile.draw(ctx, x, y); } let tile_index = self.map.mid[row][col]; if tile_index > 0 { let tile = &self.map.tiles[&tile_index]; tile.draw(ctx, x, y); } let tile_index = self.map.high[row][col]; if tile_index > 0 { let tile = &self.map.tiles[&tile_index]; tile.draw(ctx, x, y); } } } Ok(()) } fn event(&mut self, _: &mut Context, event: Event) -> tetra::Result { if let Event::Resized { width, height } = event { self.camera.set_viewport_size(width as f32, height as f32); self.camera.update(); } Ok(()) } } fn main() -> tetra::Result { ContextBuilder::new("Rendering a Texture", 640, 480) .resizable(true) .quit_on_escape(true) .build()? .run(GameState::new) }
C++
UTF-8
51,485
2.65625
3
[]
no_license
#include "common.h" #include <numeric> #include <future> #include <stack> #include <unordered_map> #include <unordered_set> #include <bitset> #include <set> #include <queue> #include <assert.h> #include <iostream> #include <vector> #include <map> #include <algorithm> #include <thread> #include <functional> #include <mutex> #include <string> using namespace std; typedef long long ll; /* typedef pair<int, int> ii; const int N = 1e5 + 10; vector<ii> a[N]; int dfn[N], low[N]; int bcc[N]; int stamp; void DFS(int u, int up_edge, vector<vector<int>>& ret) { static stack<int> S; low[u] = dfn[u] = stamp++; S.push(u); for (auto& it : a[u]) { if (it.second == up_edge) continue; int v = it.first; if (dfn[v] == 0) { DFS(v, it.second, ret); low[u] = min(low[u], low[v]); if (low[v] > dfn[u]) { ret.push_back({ u, v }); while (S.top() != v) { bcc[S.top()] = v; S.pop(); } bcc[v] = v; S.pop(); } } else { low[u] = min(low[u], dfn[v]); } } } class Solution { public: //1192. Critical Connections in a Network vector<vector<int>> criticalConnections(int n, vector<vector<int>>& connections) { for (int i = 0; i < n; ++i) { a[i].clear(); dfn[i] = 0; } for (int k = 0; k < connections.size(); ++k) { int x = connections[k][0]; int y = connections[k][1]; a[x].push_back({ y, k }); a[y].push_back({ x, k }); } stamp = 1; vector<vector<int>> ret; DFS(0, -1, ret); return ret; } }; */ class BIT { int lowbit(int x) { return x & (-x); } int n; public: vector<int> a; BIT(int n) : a(n + 1, 0), n(n) { } int add(int i, int v) { while (i <= n) { a[i] = max(a[i], v); i += lowbit(i); } return 0; } int query(int i) { int ans = 0; while (i > 0) { ans = max(ans, a[i]); i -= lowbit(i); } return ans; } }; struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; //1195. Fizz Buzz Multithreaded class FizzBuzz { private: int n; condition_variable cv; mutex mtx; int i; bool finish; public: FizzBuzz(int n) : i(1), finish(false) { this->n = n; } // printFizz() outputs "fizz". void fizz(function<void()> printFizz) { int last = -1; while (true) { unique_lock<mutex> lck(mtx); cv.wait(lck, [&]() { return (i % 3 == 0 && i % 5 && i != last) || finish; }); if (finish) break; printFizz(); last = i; } } // printBuzz() outputs "buzz". void buzz(function<void()> printBuzz) { int last = -1; while (true) { unique_lock<mutex> lck(mtx); cv.wait(lck, [&]() { return (i % 5 == 0 && i % 3 && last != i) || finish; }); if (finish) break; printBuzz(); last = i; } } // printFizzBuzz() outputs "fizzbuzz". void fizzbuzz(function<void()> printFizzBuzz) { int last = -1; while (true) { unique_lock<mutex> lck(mtx); cv.wait(lck, [&]() { return (last != i && i % 3 == 0 && i % 5 == 0) || finish; }); if (finish) break; printFizzBuzz(); last = i; } } // printNumber(x) outputs "x", where x is an integer. void number(function<void(int)> printNumber) { for (; i <= n; ++i) { if (i % 3 == 0 || i % 5 == 0) { cv.notify_all(); } else { printNumber(i); } } finish = true; cv.notify_all(); } }; //1226. The Dining Philosophers class DiningPhilosophers { public: DiningPhilosophers() { } void wantsToEat(int philosopher, function<void()> pickLeftFork, function<void()> pickRightFork, function<void()> eat, function<void()> putLeftFork, function<void()> putRightFork) { int l = philosopher; int r = (philosopher + 1) % 5; if (philosopher % 2 == 0) { lock[r].lock(); lock[l].lock(); pickLeftFork(); pickRightFork(); } else { lock[l].lock(); lock[r].lock(); pickLeftFork(); pickRightFork(); } eat(); putRightFork(); putLeftFork(); lock[l].unlock(); lock[r].unlock(); } private: std::mutex lock[5]; }; //1244. Design A Leaderboard class Leaderboard { public: map<int, int> sc; map<int, set<int>> mem_top; Leaderboard() { } void addScore(int id, int c) { if (sc.count(id)) { mem_top[sc[id]].erase(id); if (mem_top[sc[id]].empty()) { mem_top.erase(sc[id]); } } sc[id] += c; mem_top[sc[id]].insert(id); } int top(int K) { auto it = mem_top.rbegin(); int ans = 0; while (K > 0) { ans += it->first * min(K, (int)it->second.size()); K -= it->second.size(); if (it == mem_top.rend()) break; it++; } return ans; } void reset(int id) { int old = sc[id]; mem_top[old].erase(id); if (mem_top[old].empty()) { mem_top.erase(old); } sc[id] = 0; mem_top[sc[id]].insert(id); } }; //1261. Find Elements in a Contaminated Binary Tree class FindElements { public: set<int> nums; void dfs(TreeNode* u, int val) { if (!u) return; nums.insert(val); u->val = val; dfs(u->left, val * 2 + 1); dfs(u->right, val * 2 + 2); } FindElements(TreeNode* root) { nums.clear(); dfs(root, 0); } bool find(int target) { return nums.count(target); } }; /* //1263. Minimum Moves to Move a Box to Their Target Location int dr[] = { 0, 1, 0, -1 }; int dc[] = { 1, 0, -1, 0 }; int idr[] = { 0, -1, 0, 1 }; int idc[] = { -1, 0, 1, 0 }; class Solution { public: int n, m; bool ok(int x, int y) { return 0 <= x && x < n && 0 <= y && y < m; } int check(vector<vector<char>>& g, int sx, int sy, int ex, int ey) { if (g[sx][sy] == '#') return -1; if (sx == ex && sy == ey) return 0; queue<pair<int, int>> q; q.push({ sx, sy }); vector<vector<bool>> vis(n, vector<bool>(m)); vis[sx][sy] = true; int level = 0; while (!q.empty()) { int size = q.size(); level++; while (size--) { auto [x, y] = q.front(); q.pop(); for (int d = 0; d < 4; ++d) { int nx = x + dr[d], ny = y + dc[d]; if (ok(nx, ny) && g[nx][ny] == '.' && !vis[nx][ny]) { if (nx == ex && ny == ey) { return level; } vis[nx][ny] = 1; q.push({ nx, ny }); } } } } return -1; } struct State { int x, y; int px, py; bool operator < (const State& rhs) const { if (x != rhs.x) return x < rhs.x; if (y != rhs.y) return y < rhs.y; if (px != rhs.px) return px < rhs.px; //if (py != rhs.py) return py < rhs.py; return py < rhs.py; } }; int minPushBox(vector<vector<char>>& g) { n = g.size(), m = g[0].size(); State st; int tx, ty; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (g[i][j] == 'B') { st.x = i; st.y = j; g[i][j] = '.'; } if (g[i][j] == 'S') { st.px = i; st.py = j; g[i][j] = '.'; } if (g[i][j] == 'T') { tx = i; ty = j; g[i][j] = '.'; } } } queue<State> q; q.push(st); map<State, int> dp; dp[st] = 0; int ans = 0; while (!q.empty()) { int size = q.size(); ans++; while (size--) { auto curr = q.front(); auto [x, y, px, py] = q.front(); q.pop(); int cost = dp[curr]; for (int d = 0; d < 4; ++d) { int nx = x + dr[d], ny = y + dc[d]; int pnx = x + idr[d], pny = y + idc[d]; if (ok(nx, ny) && ok(pnx, pny) && g[nx][ny] != '#' && g[pnx][pny] != '#') { g[px][py] = 'S'; g[x][y] = 'B'; int move = check(g, px, py, pnx, pny); g[px][py] = '.'; g[x][y] = '.'; if (move != -1) { if (nx == tx && ny == ty) { return ans; } State nxt = { nx, ny, x, y }; if (!dp.count(nxt)) { dp[nxt] = cost + 1; q.push(nxt); } else if (dp[nxt] > cost + 1) { dp[nxt] = cost + 1; q.push(nxt); } } } } } } return -1; } }; */ /* //1258. Synonymous Sentences class Solution { public: map<string, string> fa; map<string, set<string>> order; vector<string> split(string& s) { int i = 0, n = s.size(); string u; vector<string> ans; while (i < n) { while (i < n && s[i] == ' ') ++i; while (i < n && s[i] != ' ') { u.push_back(s[i++]); } if (!u.empty()) { ans.push_back(u); u.clear(); } } if (!u.empty()) { ans.push_back(u); u.clear(); } return ans; } string find(string& s, map<string, string>& fa) { if (fa[s] != s) return fa[s] = find(fa[s], fa); return s; } void merge(string& u, string& v, map<string, string>& fa) { auto fu = find(u, fa), fv = find(v, fa); fa[fu] = fv; } void dfs(string u, int i, vector<string>& tokens, vector<string>& ans) { if (i == tokens.size()) { if (!u.empty()) u.pop_back(); ans.push_back(u); return; } auto& val = tokens[i]; if (fa.count(val)) { auto fval = find(val, fa); for (auto& sub_value : order[fval]) { dfs(u + sub_value + " ", i + 1, tokens, ans); } } else { dfs(u + val + " ", i + 1, tokens, ans); } } vector<string> generateSentences(vector<vector<string>>& sy, string text) { vector<string> tokens = split(text); fa.clear(); order.clear(); for (auto& e : sy) { auto& u = e[0], & v = e[1]; if (!fa.count(u)) fa[u] = u; if (!fa.count(v)) fa[v] = v; merge(u, v, fa); } for (auto& e : sy) { auto& u = e[0], & v = e[1]; auto fu = find(u, fa); order[fu].insert(u); order[fu].insert(v); } vector<string> ans; dfs("", 0, tokens, ans); return ans; } }; */ /* //1268. Search Suggestions System class TrieNode { public: char v; int isword; TrieNode() :isword(0), next{ nullptr } {} TrieNode(int c) :v(c), isword(0), next{ nullptr } {} TrieNode* next[26]; }; class Trie { public: TrieNode* root; Trie() { root = new TrieNode(); } void add(string word) { TrieNode* cur = root; for (char i : word) { if (cur->next[i - 'a'] == nullptr) cur->next[i - 'a'] = new TrieNode(i); cur = cur->next[i - 'a']; } cur->isword++; } void search(string& s, vector<string>& res, TrieNode* u) { if (!u) return; if (u->isword > 0) { int num = min(int(3 - res.size()), u->isword); for (int i = 0; i < num; ++i) { res.push_back(s); } if (res.size() == 3) return; } for (int i = 0; i < 26; ++i) { if (u->next[i]) { s.push_back(i + 'a'); search(s, res, u->next[i]); s.pop_back(); if (res.size() == 3) return; } } } TrieNode* topThree(char c, TrieNode* u, string& prefix, vector<string>& res) { if (!u) return u; prefix.push_back(c); res.clear(); search(prefix, res, u->next[c - 'a']); return u->next[c - 'a']; } }; class Solution { public: vector<vector<string>> suggestedProducts(vector<string>& products, string searchWord) { Trie tr; for (auto& e : products) { tr.add(e); } vector<vector<string>> res; string prefix; TrieNode* u = tr.root; for (auto& c : searchWord) { vector<string> cur; u = tr.topThree(c, u, prefix, cur); res.push_back(cur); } return res; } }; */ class Solution { public: //1196. How Many Apples Can You Put into the Basket int maxNumberOfApples(vector<int>& a) { int n = a.size(); sort(a.begin(), a.end()); int u = 0; int const maxn = 5000; int ans = 0; for (int i = 0; i < n; ++i) { u += a[i]; if (u > maxn) break; ans++; } return ans; } //1197. Minimum Knight Moves int minKnightMoves(int X, int Y) { vector <int> dr = { -2, -2, -1, 1, 2, 2, 1, -1 }; vector <int> dc = { 1, -1, -2, -2, -1, 1, 2, 2 }; X = abs(X); Y = abs(Y); int x = min(X, Y); int y = max(X, Y); if (x == 0 && y == 0) { return 0; } if (x == 0 && y == 2) { return 2; } if (x == 1 && y == 1) { return 2; } if (x == 1 && y == 3) { return 2; } if (x == 3 && y == 4) { return 3; } return 1 + minKnightMoves(x - 1, y - 2); } //1198. Find Smallest Common Element in All Rows int smallestCommonElement(vector<vector<int>>& a) { int n = a.size(); int m = a[0].size(); for (int i = 0; i < m; ++i) { bool f = true; for (int j = 1; f && j < n; ++j) { auto it = lower_bound(a[j].begin(), a[j].end(), a[0][i]); if (it == a[j].end() || *it != a[0][i]) { f = false; } } if (f) return a[0][i]; } return -1; } //1200. Minimum Absolute Difference vector<vector<int>> minimumAbsDifference(vector<int>& a) { int n = a.size(); sort(a.begin(), a.end()); int diff = INT_MAX; for (int i = 1; i < n; ++i) { diff = min(diff, a[i] - a[i - 1]); } vector<vector<int>> ans; for (int i = 1; i < n; ++i) { if (a[i] - a[i - 1] == diff) { ans.push_back({ a[i - 1], a[i] }); } } return ans; } ll check_1201(ll n, ll a, ll b, ll c) { ll ans = 0; ans += n / a; ans += n / b; ans += n / c; ans -= n / lcm(a, b); ans -= n / lcm(a, c); ans -= n / lcm(b, c); ans += n / lcm(lcm(a, b), c); return ans; } //1201. Ugly Number III int nthUglyNumber(int n, int a, int b, int c) { ll l = 1, r = 2 * 10e9; while (l < r) { ll m = (l + r) / 2; ll tot = check_1201(m, a, b, c); if (tot >= n) { r = m; } else { l = m + 1; } } return l; } void dfs_1202(int u, vector<vector<int>>& g, vector<int>& vis, int color) { if (vis[u]) return; vis[u] = color; for (auto& v : g[u]) { dfs_1202(v, g, vis, color); } } //1202. Smallest String With Swaps string smallestStringWithSwaps(string s, vector<vector<int>>& a) { int n = s.size(); vector<vector<int>> g(n); for (auto& e : a) { int u = e[0], v = e[1]; g[u].push_back(v); g[v].push_back(u); } int color = 1; vector<int> vis(n); for (int i = 0; i < n; ++i) { if (vis[i] == 0) { dfs_1202(i, g, vis, color++); } } vector<vector<int>> index(color); vector<vector<int>> value(color); for (int i = 0; i < n; ++i) { int c = vis[i]; index[c].push_back(i); value[c].push_back(s[i]); } for (auto& e : value) { sort(e.begin(), e.end()); } for (int i = 0; i < index.size(); ++i) { for (int j = 0; j < index[i].size(); ++j) { int idx = index[i][j]; char val = value[i][j]; s[idx] = val; } } return s; } //1199. Minimum Time to Build Blocks int minBuildTime(vector<int>& a, int split) { priority_queue<int, vector<int>, greater<int>> pq(a.begin(), a.end()); int ans = 0; while (pq.size() >= 2) { int x = pq.top(); pq.pop(); int y = pq.top(); pq.pop(); pq.push(split + y); } return pq.top(); } bool topoSort(vector<vector<int>>& a, vector<int>& level) { int n = a.size(); vector<int> order(n); vector<vector<int>> g(n); for (int i = 0; i < n; ++i) { order[i] = a[i].size(); for (auto& v : a[i]) { g[v].push_back(i); } } queue<int> q; vector<bool> vis(n); level.resize(n); fill(level.begin(), level.end(), 0); for (int i = 0; i < n; ++i) { if (order[i] == 0) { vis[i] = 1; q.push(i); } } int cur = 0; while (!q.empty()) { int size = q.size(); cur++; while (size--) { auto u = q.front(); q.pop(); for (auto& v : g[u]) { if (vis[v]) continue; if (--order[v] == 0) { q.push(v); level[v] = cur; vis[v] = 1; } } } } for (auto& e : order) { if (e) { return false; } } return true; } //1203. Sort Items by Groups Respecting Dependencies vector<int> sortItems(int n, int m, vector<int>& group, vector<vector<int>>& beforeItems) { for (int& e : group) { if (e == -1) { e = m++; } } vector<int> item_level; if (!topoSort(beforeItems, item_level)) return {}; vector<vector<int>> gps(m); for (int i = 0; i < n; ++i) { gps[group[i]].push_back(i); } vector<vector<int>> g_before(m); for (int i = 0; i < m; ++i) { for (auto& j : gps[i]) { for (auto& v : beforeItems[j]) { if (group[v] == i) continue; g_before[i].push_back(group[v]); } } } for (auto& e : g_before) { sort(e.begin(), e.end()); e.erase(unique(e.begin(), e.end()), e.end()); } vector<int> g_level; topoSort(g_before, g_level); for (auto& e : gps) { sort(e.begin(), e.end(), [&](int a, int b) { return item_level[a] < item_level[b]; }); } vector<int> gps_idx(m); iota(gps_idx.begin(), gps_idx.end(), 0); sort(gps_idx.begin(), gps_idx.end(), [&](int a, int b) { return g_level[a] < g_level[b]; }); vector<int> ans; ans.reserve(n); for (auto& i : gps_idx) { for (auto& e : gps[i]) { ans.push_back(e); } } return ans; } //1207. Unique Number of Occurrences bool uniqueOccurrences(vector<int>& a) { map<int, int> cnt; for (auto& e : a) { cnt[e] ++; } set<int> pre; for (auto& e : cnt) { if (pre.count(e.second)) return false; pre.insert(e.second); } return true; } //1208. Get Equal Substrings Within Budget int equalSubstring(string s, string t, int V) { int n = s.size(); vector<int> cost(n); for (int i = 0; i < n; ++i) cost[i] = abs(s[i] - t[i]); int j = 0; int cur = 0, ans = 0; for (int i = 0; i < n; ++i) { cur += cost[i]; while (cur > V) { cur -= cost[j++]; } ans = max(ans, i - j + 1); } return ans; } //1209. Remove All Adjacent Duplicates in String II string removeDuplicates(string s, int k) { vector<pair<char, int>> stk; for (auto& e : s) { if (!stk.empty() && stk.back().first == e) { if (++stk.back().second == k) { stk.pop_back(); } } else { stk.push_back({ e, 1 }); } } string ans; for (auto& e : stk) { ans += string(e.second, e.first); } return ans; } //1210. Minimum Moves to Reach Target with Rotations int minimumMoves(vector<vector<int>>& grid) { int f[105][105][2]; int n = grid.size(), i, j, ans; memset(f, 127, sizeof(f)); f[0][0][0] = 0; for (i = 0; i < n; i++) for (j = 0; j < n; j++) if (!grid[i][j]) { if (i + 1 < n && j + 1 < n && !grid[i + 1][j] && !grid[i][j + 1] && !grid[i + 1][j + 1]) { f[i][j][0] = min(f[i][j][0], f[i][j][1] + 1); f[i][j][1] = min(f[i][j][1], f[i][j][0] + 1); f[i + 1][j][0] = min(f[i + 1][j][0], f[i][j][0] + 1); f[i][j + 1][1] = min(f[i][j + 1][1], f[i][j][1] + 1); } if (j + 2 < n && !grid[i][j + 1] && !grid[i][j + 2]) f[i][j + 1][0] = min(f[i][j + 1][0], f[i][j][0] + 1); if (i + 2 < n && !grid[i + 1][j] && !grid[i + 2][j]) f[i + 1][j][1] = min(f[i + 1][j][1], f[i][j][1] + 1); } ans = f[n - 1][n - 2][0]; if (ans == 2139062143) ans = -1; return ans; } //1213. Intersection of Three Sorted Arrays vector<int> arraysIntersection(vector<int>& a, vector<int>& b, vector<int>& c) { set<int> ins; for (auto& e : a) { auto it = lower_bound(b.begin(), b.end(), e); if (it != b.end() && *it == e) { ins.insert(e); } } vector<int> ans; for (auto& e : c) { if (ins.count(e)) { ans.push_back(e); } } ans.erase(unique(ans.begin(), ans.end()), ans.end()); return ans; } void dfs_1214(TreeNode* u, vector<int>& out) { if (!u) return; dfs_1214(u->left, out); out.push_back(u->val); dfs_1214(u->right, out); } //1214. Two Sum BSTs bool twoSumBSTs(TreeNode* root1, TreeNode* root2, int target) { vector<int> a, b; dfs_1214(root1, a); dfs_1214(root2, b); int n = a.size(), m = b.size(); vector<int> c(n + m); vector<int> pos(n + m); int i = 0, j = 0, k = 0; while (i < n || j < m) { if (i < n && j < m) { if (a[i] < b[j]) { pos[k] = 1; c[k++] = a[i++]; } else { pos[k] = 2; c[k++] = b[j++]; } } else if (i < n) { pos[k] = 1; c[k++] = a[i++]; } else { pos[k] = 2; c[k++] = b[j++]; } } for (i = 0, j = 1; j < n + m; ++j) { if (c[i] != c[j]) { c[++i] = c[j]; pos[i] = pos[j]; } else { pos[i] |= pos[j]; } } j = 0; while (j < i) { int v = c[j] + c[i]; if (v == target) return (pos[j] | pos[i]) == 3; else if (v > target) --i; else ++j; } return false; } void dfs_1215(ll num, int pre, int low, int high, set<int>& ans) { if (num > high) return; if (low <= num && num <= high) { ans.insert(num); } if (pre + 1 < 10) dfs_1215(num * 10 + pre + 1, pre + 1, low, high, ans); if (pre - 1 >= 0) dfs_1215(num * 10 + pre - 1, pre - 1, low, high, ans); } //1215. Stepping Numbers vector<int> countSteppingNumbers(int low, int high) { set<int> nums; for (int i = 0; i < 10; ++i) { dfs_1215(i, i, low, high, nums); } vector<int> ans(nums.begin(), nums.end()); return ans; } //1216. Valid Palindrome III bool isValidPalindrome(string s, int k) { int n = s.size(); vector<vector<int>> dp(n, vector<int>(n)); for (int i = 0; i < n; ++i) { dp[i][i] = 1; if (i + 1 < n) { dp[i][i + 1] = 1 + (s[i] == s[i + 1]); } } for (int l = 3; l <= n; ++l) { for (int i = 0, j = i + l - 1; j < n; ++i, ++j) { if (s[i] == s[j]) { dp[i][j] = dp[i + 1][j - 1] + 2; } else { dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]); } } } return dp[0][n - 1] + k >= n; } //1217. Play with Chips int minCostToMoveChips(vector<int>& a) { int ans = 0, n = a.size(); for (auto& e : a) ans += e % 2; return min(ans, n - ans); } //1218. Longest Arithmetic Subsequence of Given Difference int longestSubsequence(vector<int>& a, int diff) { int const maxn = 1e4; int const offset = maxn; vector<int> dp(maxn * 2 + 1); for (auto e : a) { e += offset; if (e - diff >= 0 && e - diff < maxn * 2) { dp[e] = max(dp[e], dp[e - diff] + 1); } dp[e] = max(dp[e], 1); } return *max_element(dp.begin(), dp.end()); } //1220. Count Vowels Permutation int countVowelPermutation(int n) { int const mod = 1e9 + 7; vector<long long> dp(5, 1); for (int i = 1; i < n; ++i) { vector<long long> nx(5); nx[0] = dp[1]; nx[1] = (dp[0] + dp[2]) % mod; nx[2] = (dp[0] + dp[1] + dp[3] + dp[4]) % mod; nx[3] = (dp[2] + dp[4]) % mod; nx[4] = dp[0]; dp = nx; } return accumulate(dp.begin(), dp.end(), 0ll) % mod; } int dfs_1219(int x, int y, vector<vector<int>>& g, vector<vector<bool>>& vis) { static int dr[] = { 0, 1, 0, -1 }; static int dc[] = { 1, 0, -1, 0 }; int ans = g[x][y]; vis[x][y] = 1; int n = g.size(), m = g.size(); for (int d = 0; d < 4; ++d) { int nx = x + dr[d], ny = y + dc[d]; if (0 <= nx && nx < n && 0 <= ny && ny < m && vis[nx][ny] == 0 && g[nx][ny] > 0) { ans = max(ans, g[x][y] + dfs_1219(nx, ny, g, vis)); } } vis[x][y] = 0; return ans; } //1219. Path with Maximum Gold int getMaximumGold(vector<vector<int>>& g) { int ans = 0; int n = g.size(), m = g.size(); vector<vector<bool>> vis(n, vector<bool>(m)); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (g[i][j]) { ans = max(ans, dfs_1219(i, j, g, vis)); } } } return ans; } //1221. Split a String in Balanced Strings int balancedStringSplit(string s) { int ans = 0; int cur = 0; for (auto& c : s) { if (c == 'L') cur++; else cur--; ans += cur == 0; } return ans; } //1222. Queens That Can Attack the King vector<vector<int>> queensAttacktheKing(vector<vector<int>>& qs, vector<int>& ks) { int x = ks[0], y = ks[1]; const int n = 8; set<pair<int, int>> pos; for (auto& e : qs) pos.insert({ e[0], e[1] }); vector<vector<int>> ans; for (int dx = -1; dx <= 1; dx += 1) { for (int dy = -1; dy <= 1; dy += 1) { if (dx == 0 && dy == 0) continue; int nx = x + dx, ny = y + dy; while (0 <= nx && nx < n && 0 <= ny && ny < n) { if (pos.count({ nx, ny })) { ans.push_back({ nx, ny }); break; } nx += dx; ny += dy; } } } return ans; } //1223. Dice Roll Simulation int dieSimulator(int n, vector<int> rollMax) { long divisor = (long)pow(10, 9) + 7; vector<vector<long long>> dp(n, vector<long long>(7)); for (int i = 0; i < 6; i++) { dp[0][i] = 1; } dp[0][6] = 6; for (int i = 1; i < n; i++) { long sum = 0; for (int j = 0; j < 6; j++) { dp[i][j] = dp[i - 1][6]; if (i - rollMax[j] < 0) { sum = (sum + dp[i][j]) % divisor; } else { if (i - rollMax[j] - 1 >= 0) dp[i][j] = (dp[i][j] - (dp[i - rollMax[j] - 1][6] - dp[i - rollMax[j] - 1][j])) % divisor + divisor; else dp[i][j] = (dp[i][j] - 1) % divisor; sum = (sum + dp[i][j]) % divisor; } } dp[i][6] = sum; } return (int)(dp[n - 1][6]); } //1224. Maximum Equal Frequency int maxEqualFreq(vector<int>& nums) { vector<int> cnt(100001, 0), fre(100001, 0); int maxcnt = 0, ans = 0; for (int i = 0; i < nums.size(); ++i) { int num = nums[i]; ++cnt[num]; ++fre[cnt[num]]; maxcnt = max(maxcnt, cnt[num]); if ((fre[maxcnt] == 1 && maxcnt + (fre[maxcnt - 1] - 1) * (maxcnt - 1) == i + 1) || (fre[maxcnt] * maxcnt + 1 == i + 1) ) ans = i + 1; } if (maxcnt == 1) return nums.size(); return ans; } //1227. Airplane Seat Assignment Probability double nthPersonGetsNthSeat(int n) { if (n == 1) return 1.0; //return 1.0 / n + (n - 2.0) / n * nthPersonGetsNthSeat(n - 1); return 0.5; } //1228. Missing Number In Arithmetic Progression int missingNumber(vector<int>& a) { //int n = a.size(); //int first = a[0], last = a[0], sum = 0; //for (auto& e : a) //{ // first = min(first, e); // last = max(last, e); // sum += e; //} //return (first + last) * (n + 1) / 2 - sum; int n = a.size(), d = (a[n - 1] - a[0]) / n, left = 0, right = n; while (left < right) { int mid = (left + right) / 2; if (a[mid] == a[0] + d * mid) left = mid + 1; else right = mid; } return a[0] + d * left; } //1229. Meeting Scheduler vector<int> minAvailableDuration(vector<vector<int>>& a, vector<vector<int>>& b, int k) { //int n = a.size(), m = b.size(); //sort(a.begin(), a.end()); //sort(b.begin(), b.end()); //int j = 0; //int nj = 0; //for (int i = 0; i < n; ++i) //{ // if (a[i][1] - a[i][0] < k) continue; // while (j < m && b[j][1] < a[i][0]) j++; // while (j < m && b[j][0] <= a[i][1]) // { // if (i + 1 < n && b[j][1] < a[i + 1][0]) // { // nj = j; // } // int t = min(a[i][1], b[j][1]); // int s = max(a[i][0], b[j][0]); // int len = t - s; // if (len >= k) return { s, s + k }; // j++; // } // j = nj; //} //return {}; sort(a.begin(), b.end()); // sort increasing by start time (default sorting by first value) sort(b.begin(), b.end()); // sort increasing by start time (default sorting by first value) int i = 0, j = 0; int n1 = a.size(), n2 = b.size(); while (i < n1 && j < n2) { // Find intersect between slots1[i] and slots2[j] int intersectStart = max(a[i][0], b[j][0]); int intersectEnd = min(a[i][1], b[j][1]); if (intersectStart + k <= intersectEnd) // Found the result return { intersectStart, intersectStart + k }; else if (a[i][1] < b[j][1]) i++; else j++; } return {}; } bool check_1231(vector<int>& a, int val, int k) { int cur = 0, cnt = 0; for (auto& e : a) { cur += e; if (cur >= val) { cnt++; cur = 0; } } return cnt >= k; } //1231. Divide Chocolate int maximizeSweetness(vector<int>& a, int k) { int l = INT_MAX, r = 0; for (auto& e : a) { l = min(l, e); r += e; } if (k == 0) { return r; } k++; while (l < r) { int m = l + (r - l) / 2; if (!check_1231(a, m, k)) { r = m; } else { l = m + 1; } } return l - 1; } //1230. Toss Strange Coins double probabilityOfHeads(vector<double>& prob, int m) { int n = prob.size(); vector<double> dp(m + 1); dp[0] = 1.0; for (int i = 0; i < n; ++i) { for (int j = min(m, i + 1); j >= 0; --j) { dp[j] = dp[j] * (1 - prob[i]); if (j > 0) { dp[j] += dp[j - 1] * prob[i]; } } } return dp[m]; } //1232. Check If It Is a Straight Line bool checkStraightLine(vector<vector<int>>& a) { int n = a.size(); if (n <= 2) return true; sort(a.begin(), a.end()); for (int i = 2; i < n; ++i) { if ((a[1][1] - a[0][1]) * (a[i][0] - a[0][0]) != (a[i][1] - a[0][1]) * (a[1][0] - a[0][0])) return false; } return true; } //1233. Remove Sub-Folders from the Filesystem vector<string> removeSubfolders(vector<string>& a) { sort(a.begin(), a.end()); vector<string> ans; for (auto& e : a) { if (ans.empty()) ans.push_back(e); else { if (e.size() >= ans.back().size() && e.substr(0, ans.back().size()) == ans.back() && (e.size() == ans.size() || e[ans.back().size()] == '/')) { } else { ans.push_back(e); } } } return ans; } bool valid_1234(vector<int>& cnt, int n) { for (auto& e : cnt) { if (e > n / 4) return false; } return true; } //1234. Replace the Substring for Balanced String int balancedString(string s) { int n = s.size(); vector<int> cnt(4); map<char, int> idx; idx['Q'] = 0; idx['W'] = 1; idx['E'] = 2; idx['R'] = 3; int i = 0, j = 0; for (auto& c : s) { cnt[idx[c]] ++; } if (valid_1234(cnt, n)) return 0; int ans = n; for (; i < n; ++i) { cnt[idx[s[i]]] --; while (j <= i && valid_1234(cnt, n)) { ans = min(ans, i - j + 1); cnt[idx[s[j++]]] ++; } } return ans; } int jobScheduling(vector<int>& st, vector<int>& ed, vector<int>& pf) { int n = st.size(); vector<int> pts(st.begin(), st.end()); for (auto& e : ed) pts.push_back(e); sort(pts.begin(), pts.end()); pts.erase(unique(pts.begin(), pts.end()), pts.end()); int tot = pts.size(); map<int, int> idx; for (int i = 0; i < tot; ++i) { idx[pts[i]] = i + 1; } vector<vector<int>> a(n, vector<int>(3)); for (int i = 0; i < n; ++i) { a[i] = { idx[ed[i]], idx[st[i]], pf[i] }; } sort(a.begin(), a.end()); BIT bt(tot + 1); int ans = 0; vector<int> dp(tot); for (int i = 0; i < n; ++i) { int s = a[i][1], t = a[i][0], p = a[i][2]; int last = bt.query(s); if ((i > 0 && dp[i - 1] < p + last) || i == 0) { dp[i] = p + last; } else if (i > 0) { dp[i] = dp[i - 1]; } bt.add(t, dp[i]); } return dp[n - 1]; } //bool check(string& s, string& p) //{ // return s == p || (s.size() > p.size() && s.substr(0, p.size()) == p && s[p.size()] == '/'); //} //1236. Web Crawler //vector<string> crawl(string startUrl, HtmlParser htmlParser) { // string domain = "http://"; // for (int i = 7; i < startUrl.size(); ++i) // { // if (startUrl[i] == '/') break; // domain.push_back(startUrl[i]); // } // queue<string> urls; // urls.push(startUrl); // set<string> vis; // vector<string> ans; // ans.push_back(startUrl); // vis.insert(startUrl); // while (!urls.empty()) // { // auto u = urls.front(); // urls.pop(); // for (auto& sub : htmlParser.getUrls(u)) // { // if (!vis.count(sub) && check(sub, domain)) // { // vis.insert(sub); // ans.push_back(sub); // urls.push(sub); // } // } // } // return ans; //} //1237. Find Positive Integer Solution for a Given Equation //vector<vector<int>> findSolution(CustomFunction& fun, int z) { // vector<vector<int>> ans; // int const N = 1000; // for (int i = 1; i <= N; ++i) // { // int l = 1, r = 1000; // while (l <= r) // { // int m = (l + r) / 2; // int val = fun.f(i, m); // if (val == z) // { // ans.push_back({ i, m }); // break; // } // else if (val > z) // { // r = m - 1; // } // else // { // l = m + 1; // } // } // } // return ans; //} //1238. Circular Permutation in Binary Representation vector<int> circularPermutation(int n, int start) { int cnt = (1 << n); vector<int> ans(cnt); vector<int> tmp; int offset = 0; bool f = true; for (int i = 0; i < cnt; ++i) { ans[i] = (i ^ (i / 2)); if (ans[i] == start) { offset = i; f = false; } if (f) { tmp.push_back(ans[i]); } } int j = 0; for (int i = offset; i < cnt; ++i) { ans[j++] = ans[i]; } for (int i = 0; i < tmp.size(); ++i) { ans[j++] = tmp[i]; } return ans; } int convert_1239(string& s) { int ret = 0; for (auto& c : s) { int mask = (1 << (c - 'a')); if (ret & mask) return -1; ret |= mask; } return ret; } int dfs_1239(int u, int s, int len, vector<pair<int, int>>& a) { if (u == len) return 0; int ans = 0; for (int i = u; i < len; ++i) { if (s & a[i].first) continue; ans = max(ans, a[i].second + dfs_1239(i + 1, s | a[i].first, len, a)); } return ans; } //1239. Maximum Length of a Concatenated String with Unique Characters int maxLength(vector<string>& arr) { int n = arr.size(); vector<pair<int, int>> a; for (int i = 0; i < n; ++i) { int ret = convert_1239(arr[i]); if (ret != -1) { a.push_back({ ret, static_cast<int>(arr[i].length()) }); } } return dfs_1239(0, 0, a.size(), a); } //1240. Tiling a Rectangle with the Fewest Squares int tilingRectangle(int n, int m) { static vector<vector<int>> M = { {1 }, {2, 1 }, {3, 3, 1 }, {4, 2, 4, 1 }, {5, 4, 4, 5, 1 }, {6, 3, 2, 3, 5, 1 }, {7, 5, 5, 5, 5, 5, 1 }, {8, 4, 5, 2, 5, 4, 7, 1 }, {9, 6, 3, 6, 6, 3, 6, 7, 1 }, {10, 5, 6, 4, 2, 4, 6, 5, 6, 1 }, {11, 7, 6, 6, 6, 6, 6, 6, 7, 6, 1 }, {12, 6, 4, 3, 6, 2, 6, 3, 4, 5, 7, 1 }, {13, 8, 7, 7, 6, 6, 6, 6, 7, 7, 6, 7, 1 }, {14, 7, 7, 5, 7, 5, 2, 5, 7, 5, 7, 5, 7, 1 }, {15, 9, 5, 7, 3, 4, 8, 8, 4, 3, 7, 5, 8, 7, 1}, }; if (n < m) swap(n, m); return M[n - 1][m - 1]; } //1246. Palindrome Removal int minimumMoves(vector<int>& a) { int n = a.size(); vector<vector<int>> dp(n, vector<int>(n)); for (int i = 0; i < n; ++i) dp[i][i] = 1; for (int l = 2; l <= n; ++l) { for (int i = 0, j = i + l - 1; j < n; ++i, ++j) { dp[i][j] = INT_MAX; if (a[i] == a[j]) { dp[i][j] = l > 2 ? dp[i + 1][j - 1] : 1; } for (int k = i; k + 1 <= j; ++k) { dp[i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j]); } } } return dp[0][n - 1]; } //1243. Array Transformation vector<int> transformArray(vector<int>& a) { int n = a.size(); bool change = true; while (change) { change = false; auto nx = a; for (int i = 1; i < n - 1; ++i) { if (a[i] > a[i - 1] && a[i] > a[i + 1]) { nx[i] --; change = true; } else if (a[i] < a[i - 1] && a[i] < a[i + 1]) { nx[i] ++; change = true; } } a = nx; } return a; } //1245. Tree Diameter int treeDiameter(vector<vector<int>>& es) { int n = es.size() + 1; vector<vector<int>> g(n); for (auto& e : es) { int u = e[0], v = e[1]; g[u].push_back(v); g[v].push_back(u); } int st = 0; queue<int> q; q.push(st); vector<bool> vis(n); vis[st] = 1; int last = -1; while (!q.empty()) { int size = q.size(); while (size--) { auto u = q.front(); q.pop(); last = u; for (auto& v : g[u]) { if (vis[v] == 0) { vis[v] = 1; q.push(v); } } } } int level = 0; st = last; q.push(st); for (int i = 0; i < n; ++i) vis[i] = 0; vis[st] = 1; while (!q.empty()) { int size = q.size(); level++; while (size--) { auto u = q.front(); q.pop(); for (auto& v : g[u]) { if (!vis[v]) { vis[v] = 1; q.push(v); } } } } return level - 1; } //1247. Minimum Swaps to Make Strings Equal int minimumSwap(string s1, string s2) { int n = s1.size(); int c0 = 0, c1 = 0; for (int i = 0; i < n; ++i) { if (s1[i] == s2[i]) continue; else if (s1[i] == 'x') c0++; else c1++; } int ans = 0; ans += c0 / 2 + c1 / 2; c0 %= 2; c1 %= 2; if (c0 && c1 || c0 == 0 && c1 == 0) { ans += c0 * 2; return ans; } return -1; } //1248. Count Number of Nice Subarrays int numberOfSubarrays(vector<int>& nums, int k) { int n = nums.size(); vector<int> sums(n + 1); for (int i = 0; i < n; ++i) { sums[i + 1] = sums[i] + nums[i] % 2; } vector<int> cnt(n + 1); int ans = 0; cnt[0] = 1; for (int i = 0; i < n; ++i) { int val = sums[i + 1] - k; if (val >= 0) ans += cnt[val]; cnt[sums[i + 1]] ++; } return ans; } //1250. Check If It Is a Good Array bool isGoodArray(vector<int>& nums) { int n = nums.size(); for (int i = 0; i < n; ++i) { if (nums[i] == 1) return true; } if (n < 2) return false; int g = nums[0]; for (int i = 1; i < n; ++i) { g = gcd(g, nums[i]); if (g == 1) return true; } return false; } //1249. Minimum Remove to Make Valid Parentheses string minRemoveToMakeValid(string s) { stack<int> st; for (auto i = 0; i < s.size(); ++i) { if (s[i] == '(') st.push(i); if (s[i] == ')') { if (!st.empty()) st.pop(); else s[i] = '*'; } } while (!st.empty()) { s[st.top()] = '*'; st.pop(); } s.erase(remove(s.begin(), s.end(), '*'), s.end()); return s; } //1252. Cells with Odd Values in a Matrix int oddCells(int n, int m, vector<vector<int>>& a) { vector<int> row(n), col(m); for (auto& e : a) { row[e[0]] ^= 1; col[e[1]] ^= 1; } int cntrow = 0, cntcol = 0; for (int i = 0; i < n; ++i) { cntrow += row[i]; } for (int j = 0; j < m; ++j) { cntcol += col[j]; } return m * cntrow + n * cntcol - 2 * cntrow * cntcol; } //1253. Reconstruct a 2-Row Binary Matrix vector<vector<int>> reconstructMatrix(int upper, int lower, vector<int>& colsum) { int n = colsum.size(); vector<vector<int>> ans(2, vector<int>(n)); for (int i = 0; i < n; ++i) { if (colsum[i] == 2) { upper--; lower--; ans[0][i] = 1; ans[1][i] = 1; } else if (colsum[i] == 1) { if (upper > lower) { upper--; ans[0][i] = 1; } else { lower--; ans[1][i] = 1; } } else return {}; } if (upper == 0 && lower == 0) { return ans; } else return {}; } void dfs_1254(vector<vector<int>>& g, int x, int y, int color) { static int dr[] = { 0, 1, 0, -1 }; static int dc[] = { 1, 0, -1, 0 }; g[x][y] = color; int n = g.size(), m = g[0].size(); for (int d = 0; d < 4; ++d) { int nx = x + dr[d], ny = y + dc[d]; if (0 <= nx && nx < n && 0 <= ny && ny < m && g[nx][ny] == 0) { dfs_1254(g, nx, ny, color); } } } //1254. Number of Closed Islands int closedIsland(vector<vector<int>>& grid) { int n = grid.size(), m = grid[0].size(); int ans = 0; for (int i = 0; i < n; ++i) { if (grid[i][0] == 0) { dfs_1254(grid, i, 0, -1); } if (grid[i][m - 1] == 0) { dfs_1254(grid, i, m - 1, -1); } } for (int j = 1; j < m - 1; ++j) { if (grid[0][j] == 0) { dfs_1254(grid, 0, j, -1); } if (grid[n - 1][j] == 0) { dfs_1254(grid, n - 1, j, -1); } } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (grid[i][j] == 0) { ans++; dfs_1254(grid, i, j, 3); } } } return ans; } int dfs_1255(int u, vector<string>& ws, vector<int>& cnt, vector<int>& sc) { if (u > ws.size()) return 0; int ans = 0; for (int i = u; i < ws.size(); ++i) { vector<int> tmp(26); int value = 0; for (auto& c : ws[i]) { tmp[c - 'a'] ++; value += sc[c - 'a']; } bool valid = true; for (int i = 0; i < 26; ++i) { if (tmp[i] > cnt[i]) { valid = false; break; } } if (valid) { for (int i = 0; i < 26; ++i) { cnt[i] -= tmp[i]; } ans = max(ans, value + dfs_1255(i + 1, ws, cnt, sc)); for (int i = 0; i < 26; ++i) { cnt[i] += tmp[i]; } } } return ans; } //1255. Maximum Score Words Formed by Letters int maxScoreWords(vector<string>& words, vector<char>& letters, vector<int>& score) { vector<int> cnt(26); for (auto& c : letters) { cnt[c - 'a'] ++; } return dfs_1255(0, words, cnt, score); } //1256. Encode Number string encode_1256(int n) { return n > 0 ? encode_1256((n - 1) / 2) + "10"[n % 2] : ""; } //string encode_1256(int num) { // if (num == 0) return ""; // long len = 0; // long cur = 0; // while (cur + (1ll << len) <= num) // { // cur += (1 << len); // len++; // } // int tmp = num - cur; // string n; // while (tmp) // { // n.push_back(tmp % 2 + '0'); // tmp /= 2; // } // reverse(n.begin(), n.end()); // return (len > n.size() ? string(len - n.size(), '0') : "") + n; //} string lca_1257(string& u, string& a, string& b, map<string, vector<string>>& g) { if (u == a || u == b) return u; vector<string> rets; for (auto& v : g[u]) { auto ret = lca_1257(v, a, b, g); if (!ret.empty()) { rets.push_back(ret); } } if (rets.empty()) return ""; else if (rets.size() == 1) return rets[0]; else if (rets.size() == 2) return u; return ""; } //1257. Smallest Common Region string findSmallestRegion(vector<vector<string>>& regions, string region1, string region2) { map<string, vector<string>> g; map<string, int> indegree; for (auto& e : regions) { auto name = e[0]; for (int i = 1; i < e.size(); ++i) { g[name].push_back(e[i]); indegree[e[i]] ++; } } for (auto& e : regions) { auto name = e[0]; if (indegree.count(name)) continue; auto ret = lca_1257(name, region1, region2, g); if (!ret.empty()) { return ret; } } return ""; } //1259. Handshakes That Don't Cross int numberOfWays(int n) { vector<int> dp(n + 1); dp[0] = 1; int const mod = 1e9 + 7; for (int i = 2; i <= n; i += 2) { for (int l = 0; l <= i - 2; l += 2) { int r = i - 2 - l; dp[i] = (dp[i] + static_cast<long long>(dp[l]) * dp[r]) % mod; } } return dp[n]; } //1260. Shift 2D Grid vector<vector<int>> shiftGrid(vector<vector<int>>& g, int k) { int n = g.size(), m = g[0].size(); vector<int> tmp(n * m); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { tmp[i * m + j] = g[i][j]; } } k %= (n * m); for (int i = 0; i < n * m - k; ++i) { int offset = i + k; int x = offset / m, y = offset % m; g[x][y] = tmp[i]; } for (int i = n * m - k; i < n * m; ++i) { int offset = i - (n * m - k); int x = offset / m, y = offset % m; g[x][y] = tmp[i]; } return g; } //1262. Greatest Sum Divisible by Three int maxSumDivThree(vector<int>& nums) { int n = nums.size(); vector<vector<int>> dp(n, vector<int>(3, -1)); dp[0][nums[0] % 3] = nums[0]; for (int i = 1; i < n; ++i) { dp[i] = dp[i - 1]; dp[i][nums[i] % 3] = max(dp[i][nums[i] % 3], nums[i]); for (int j = 0; j < 3; ++j) { if (dp[i - 1][j] == -1) continue; int k = (j + nums[i] % 3) % 3; dp[i][k] = max(dp[i - 1][k], dp[i - 1][j] + nums[i]); } } return dp[n - 1][0] == -1 ? 0 : dp[n - 1][0]; } //1271. Hexspeak string toHexspeak(string num) { vector<char> valid = { 'A', 'B', 'C', 'D', 'E', 'F', 'I', 'O' }; set<char> sv(valid.begin(), valid.end()); long long v = 0; for (auto& c : num) v = v * 10 + c - '0'; string s; while (v) { int x = v % 16; if (x < 10) s.push_back(x + '0'); else s.push_back(x - 10 + 'A'); v /= 16; } reverse(s.begin(), s.end()); for (auto& c : s) { if (c == '0') c = 'O'; else if (c == '1') c = 'I'; } for (auto& c : s) if (!sv.count(c)) return "ERROR"; return s; } vector<vector<int>> minus_1272(int s, int t, int st, int ed) { if (t < st || s >= ed) return { {s, t} }; int it = min(ed, t); int is = max(s, st); //if (is >= it) return { {s,t} }; vector<vector<int>> ans; if (s < is) ans.push_back({ s, is }); if (it < t) ans.push_back({ it, t }); return ans; } //1272. Remove Interval vector<vector<int>> removeInterval(vector<vector<int>>& ins, vector<int>& rem) { int st = rem[0], ed = rem[1]; int n = ins.size(); vector<vector<int>> ans; for (int i = 0; i < n; ++i) { for (auto& e : minus_1272(ins[i][0], ins[i][1], st, ed)) { ans.push_back(e); } } return ans; } class Node_1273 { public: int val; vector<Node_1273*> nx; Node_1273() : val(-1) {} Node_1273(int v) : val(v) {} }; pair<int, int> remove_1273(Node_1273* u) { if (!u) return { 0, 0 }; int sum = u->val, cnt = 1; for (auto& e : u->nx) { auto [sum_e, cnt_e] = remove_1273(e); sum += sum_e; cnt += cnt_e; } if (sum == 0) { return { 0, 0 }; } else { return { sum, cnt }; } } //1273. Delete Tree Nodes int deleteTreeNodes(int nodes_, vector<int>& parent, vector<int>& value) { int n = nodes_; Node_1273* root; vector<Node_1273*> nodes(n), idx(n); for (int i = 0; i < n; ++i) { nodes[i] = new Node_1273(value[i]); } for (int i = 1; i < n; ++i) { int par = parent[i]; nodes[par]->nx.push_back(nodes[i]); } root = nodes[0]; return remove_1273(root).second; } class Sea { public: bool hasShips(vector<int> topRight, vector<int> bottomLeft) { return 0; } }; int check_1274(Sea sea, int sx, int sy, int tx, int ty) { if (sx > tx || sy > ty) return 0; if (!sea.hasShips({ tx, ty }, { sx, sy })) return 0; if ((abs(tx - sx) + 1) <= 1 || (abs(ty - sy) + 1) <= 1) { int ans = 0; int fx = tx - sx >= 0 ? 1 : -1; int fy = ty - sy >= 0 ? 1 : -1; for (int i = sx; i <= fx * tx; i += fx) { for (int j = sy; j <= fy * ty; j += fy) { ans += sea.hasShips({ i, j }, { i, j }); } } return ans; } int dx = tx - sx, dy = ty - sy; int ox = dx / 2, oy = dy / 2; /* (sx, ty) (sx + ox, ty) (tx, ty) (sx, sy + oy) (sx + ox, sy + oy) (tx, sy + oy) (sx, sy) (sx + ox, sy) (tx, sy) */ int ans = 0; ans += check_1274(sea, sx, sy, sx + ox - 1, sy + oy); ans += check_1274(sea, sx, sy + oy + 1, sx + ox, ty); ans += check_1274(sea, sx + ox + 1, sy + oy, tx, ty); ans += check_1274(sea, sx + ox, sy, tx, sy + oy - 1); ans += sea.hasShips({ sx + ox, sy + oy }, { sx + ox, sy + oy }); return ans; } //1274. Number of Ships in a Rectangle int countShips(Sea sea, vector<int> tr, vector<int> bl) { int sx = bl[0], sy = bl[1]; int tx = tr[0], ty = tr[1]; return check_1274(sea, sx, sy, tx, ty); } bool check(vector<vector<char>>& b) { int n = 3; for (int i = 0; i < n; ++i) { bool win = true; if (b[i][0] == ' ') continue; for (int j = 1; j < n; ++j) { if (b[i][j] != b[i][0]) { win = false; break; } } if (win) return true; } for (int j = 0; j < n; ++j) { bool win = true; if (b[0][j] == ' ') continue; for (int i = 1; i < n; ++i) { if (b[i][j] != b[0][j]) { win = false; break; } } if (win) return true; } { if (b[0][0] != ' ') { bool win = true; for (int i = 1; i < n; ++i) { if (b[i][i] != b[0][0]) { win = false; } } if (win) return true; } } { if (b[0][n - 1] != ' ') { bool win = true; for (int i = 1; i < n; ++i) { int j = n - 1 - i; if (b[i][j] != b[0][n - 1]) { win = false; break; } } if (win) return true; } } return false; } //1275. Find Winner on a Tic Tac Toe Game string tictactoe(vector<vector<int>>& moves) { vector<vector<char>> b(3, vector<char>(3, ' ')); int n = moves.size(); for (int i = 0; i < n; ++i) { b[moves[i][0]][moves[i][1]] = 'A' + i % 2; if (check(b)) { string ret; ret.push_back('A' + i % 2); return ret; } if (i >= 8) return "Draw"; } return "Pending"; } //1276. Number of Burgers with No Waste of Ingredients vector<int> numOfBurgers(int ts, int cs) { int tmp = ts - cs * 2; if (tmp % 2) return {}; int x = tmp / 2; int y = cs - x; if (y < 0 || x < 0) return {}; return { x, y }; } //1277. Count Square Submatrices with All Ones int countSquares(vector<vector<int>>& a) { int n = a.size(), m = a[0].size(); NumMatrix nm(a); int ans = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { ans += a[i][j]; } } for (int l = 2; l <= min(n, m); ++l) { for (int i = 0; i + l - 1 < n; ++i) { for (int j = 0; j + l - 1 < m; ++j) { if (nm.sumRegion(i, j, i + l - 1, j + l - 1) == l * l) ans++; } } } return ans; } //1278. Palindrome Partitioning III int palindromePartition(string s, int k) { int n = s.size(); vector<vector<int>> change(n, vector<int>(n)); for (int l = 1; l <= n; ++l) { for (int i = 0, j = i + l - 1; j < n; ++j, ++i) { if (l == 1) change[i][j] = 0; else if (l == 2) { if (s[i] == s[j]) change[i][j] = 0; else change[i][j] = 1; } else { change[i][j] = change[i + 1][j - 1] + (s[i] != s[j]); } } } vector<vector<int>> dp(k + 1, vector<int>(n + 1, n)); for (int i = 0; i < n; ++i) { dp[0][i] = change[0][i]; } for (int j = 0; j < k; ++j) { for (int i = 0; i < n; ++i) { for (int m = i + 1; m < n; ++m) { dp[j + 1][m] = min(dp[j + 1][m], dp[j][i] + change[i + 1][m]); } } } return dp[k - 1][n - 1]; } //1281. Subtract the Product and Sum of Digits of an Integer int subtractProductAndSum(int n) { int sum = 0, mul = 1; while (n) { sum += n % 10; mul *= n % 10; n /= 10; } return mul - sum; } //1282. Group the People Given the Group Size They Belong To vector<vector<int>> groupThePeople(vector<int>& a) { map<int, vector<int>> members; int n = a.size(); vector<vector<int>> ans; for (int i = 0; i < n; ++i) { int mem = a[i]; if (members[mem].size() < mem) { members[mem].push_back(i); if (members[mem].size() == mem) { ans.push_back(members[mem]); members[mem].clear(); } } } return ans; } //1283. Find the Smallest Divisor Given a Threshold int smallestDivisor(vector<int>& nums, int threshold) { int l = 1, r = 0; for (auto& e : nums) r = max(r, e); while (l < r) { int m = (l + r) / 2; long long t = 0; for (auto& e : nums) { t += e / m; if (e % m) t++; } if (t <= threshold) { r = m; } else { l = m + 1; } } return l; } //1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix int minFlips(vector<vector<int>>& a) { typedef bitset<9> ele; int n = a.size(), m = a[0].size(); ele st; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { st[i * m + j] = a[i][j]; } } auto modify = [](ele s, int i, int j, int n, int m) { s[i * m + j].flip(); if (i + 1 < n) s[(i + 1) * m + j].flip(); if (i - 1 >= 0) s[(i - 1) * m + j].flip(); if (j + 1 < m) s[i * m + j + 1].flip(); if (j - 1 >= 0) s[i * m + j - 1].flip(); return s; }; queue<ele> q; q.push(st); if (st == 0) return 0; set<int> vis; vis.insert(st.to_ulong()); int ans = 0; while (!q.empty()) { ans++; int size = q.size(); while (size--) { auto u = q.front(); q.pop(); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { auto nx = modify(u, i, j, n, m); if (nx.to_ulong() == 0) { return ans; } if (!vis.count(nx.to_ulong())) { q.push(nx); vis.insert(nx.to_ulong()); } } } } } return -1; } }; int main() { return 0; }
Python
UTF-8
3,315
2.90625
3
[]
no_license
#!/usr/bin/env python3 # coding: utf-8 from __future__ import print_function import pandas as pd from seq2seq_model import Embedding_Seq2SeqSummarizer import numpy as np import pickle from nltk.translate.bleu_score import sentence_bleu from nltk import word_tokenize import numpy as np from nltk.translate.bleu_score import SmoothingFunction import time import re import json from rouge import Rouge def main(): smoothie = SmoothingFunction().method4 data_dir_path = 'data' model_dir_path = 'models' print('loading csv file ...') df = pd.read_csv(data_dir_path + "/lenta_test.csv") X = df['text'] Y = df['title'] # loading our model model_path = Embedding_Seq2SeqSummarizer.get_config_file_path(model_dir_path=model_dir_path) with open(model_path, 'rb') as data: config = pickle.load(data) summarizer = Embedding_Seq2SeqSummarizer(config) summarizer.load_weights(weight_file_path=Embedding_Seq2SeqSummarizer.get_weight_file_path(model_dir_path=model_dir_path)) print('start predicting ...') result = '' bleus = [] beam_bleus = [] rouge = Rouge() refs, greedy_hyps, beam_hyps = [], [], [] # some decent examples demo = [3, 5, 31, 36, 37, 47, 54, 55, 99, 19, 39, 119] for i in demo: # for i in range(50): x = X[i] actual_headline = Y[i] refs.append(actual_headline) headline = summarizer.summarize(x) greedy_hyps.append(headline) beam_headline = summarizer.beam_search(x, 3) beam_hyps.append(beam_headline) bleu = sentence_bleu([word_tokenize(actual_headline.lower())], word_tokenize(headline), smoothing_function=smoothie) bleus.append(bleu) beam_bleu = sentence_bleu([word_tokenize(actual_headline.lower())], word_tokenize(beam_headline), smoothing_function=smoothie) beam_bleus.append(beam_bleu) # if i % 200 == 0 and i != 0: # print(i) # print("BLEU: ", np.mean(np.array(bleus))) # print("BEAM BLEU: ", np.mean(np.array(beam_bleus))) print(f'№ {i}') # print('Article: ', x) print('Original Headline: ', actual_headline) print('Generated Greedy Headline: ', headline) print('Generated Beam Headline: ', beam_headline) print('\n') print ('__________METRICS SUMMARY____________') avg_greedy_scores = rouge.get_scores(greedy_hyps, refs, avg=True) rouge1f = avg_greedy_scores['rouge-1']['f'] rouge2f = avg_greedy_scores['rouge-2']['f'] rougelf = avg_greedy_scores['rouge-l']['f'] score = np.mean([rouge1f, rouge2f, rougelf]) print('Greedy Rouge (Dialogue 2019): ', score) avg_beam_scores = rouge.get_scores(beam_hyps, refs, avg=True) rouge1f = avg_beam_scores['rouge-1']['f'] rouge2f = avg_beam_scores['rouge-2']['f'] rougelf = avg_beam_scores['rouge-l']['f'] score = np.mean([rouge1f, rouge2f, rougelf]) print('Beam search Rouge (Dialogue 2019): ', score) def average(lst): return float(sum(lst)) / float(len(lst)) print("Greedy Bleu: ", average(bleus)) print("Beam search Bleu: ", average(beam_bleus)) print ('_____________________________________') if __name__ == '__main__': main()
Java
UTF-8
292
2.390625
2
[]
no_license
package com.approxinfinity.retrofitexample.exceptions; import retrofit.RetrofitError; public class NotFoundException extends BaseException { public NotFoundException(RetrofitError error) { super(error); } public NotFoundException() { super(); } }
Markdown
UTF-8
1,305
3.609375
4
[]
no_license
# Baymax's Shopping Trip Baymax has a problem, it is Hiro's birthday and he would like to get him his favorite candy bar. The local store is having a sale, where for every `n` candybars that Baymax buys he gets one free. This sale is especially good in that each free candybar he gets counts as another candybar purchased. For example Baymax has 10 dollars, the candybar cost 2 dollars each, and the sale is buy 2 get one free. In this senario Baymax initially gets 5 candybars, then because he bought more than 4 candybars he gets 2 more for free. These 2 free ones in turn count as another 2 purchased giving him another 1 bar. This means that in this seario Baymax can get a total of 8 total bars. Can you help Baymax find out how many candybars he can get in different senarios? ------------------------ ## Input Format 1. `t` is the number of senarios Baymax wishes to run 2. `n` is the money Baymax has (in whole numbers) 3. `c` is the cost of the candybars (whole number) 4. `m` is the number of bars to purchase to get one free ### `t` `n` `c` `m` ### Constraints - 1 < `t` < 1000 - 2 < `n` < 10^5 - 1 < `c` < n - 2 < `m` < n ### Sample Input 3 10 2 2 9 2 3 20 3 5 ### Sample Output 8 5 7 ------------------------ - Note: This is a question that is solvible by CS 1 students
PHP
UTF-8
1,693
2.53125
3
[]
no_license
<?php namespace App\Models; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Contracts\Auth\MustVerifyEmail; class User extends Authenticatable implements MustVerifyEmail { use Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', 'is_admin', 'avatar', 'email_verified_at' ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; protected static function boot() { parent::boot(); // TODO: Change the autogenerated stub } public function articles() { return $this->hasMany(Article::class); } /** * 文章点赞 * * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function likes() { return $this->belongsToMany(Article::class, 'article_user') ->where('article_user.type', 'like') ->withTimestamps(); } /** * 评论点赞 * * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function commentLikes() { return $this->belongsToMany(Comment::class, 'comment_user') ->withTimestamps(); } public function comments() { return $this->hasMany(Comment::class); } public function collections() { return $this->belongsToMany(Article::class, 'article_user') ->where('article_user.type', 'collection') ->withTimestamps(); } }
Python
UTF-8
2,010
3.671875
4
[]
no_license
# Step 1. Import the necessary libraries import pandas as pd import numpy as np # Step 2. Create the DataFrame with the following values: raw_data = {'regiment': ['Nighthawks', 'Nighthawks', 'Nighthawks', 'Nighthawks', 'Dragoons', 'Dragoons', 'Dragoons', 'Dragoons', 'Scouts', 'Scouts', 'Scouts', 'Scouts'], 'company': ['1st', '1st', '2nd', '2nd', '1st', '1st', '2nd', '2nd','1st', '1st', '2nd', '2nd'], 'name': ['Miller', 'Jacobson', 'Ali', 'Milner', 'Cooze', 'Jacon', 'Ryaner', 'Sone', 'Sloan', 'Piger', 'Riani', 'Ali'], 'preTestScore': [4, 24, 31, 2, 3, 4, 24, 31, 2, 3, 2, 3], 'postTestScore': [25, 94, 57, 62, 70, 25, 94, 57, 62, 70, 62, 70]} # Step 3. Assign it to a variable called regiment. # Don't forget to name each column regiment = pd.DataFrame.from_dict(raw_data) # Step 4. What is the mean preTestScore from the regiment Nighthawks? print (regiment[regiment.regiment == 'Nighthawks'].preTestScore.mean()) # Step 5. Present general statistics by company print (regiment.groupby('company').describe()) # Step 6. What is the mean each company's preTestScore? print (regiment.groupby('company').preTestScore.mean()) # Step 7. Present the mean preTestScores grouped by regiment and company print (regiment.groupby(['regiment', 'company']).preTestScore.mean()) # Step 8. Present the mean preTestScores grouped by regiment and company without heirarchical indexing print (regiment.groupby(['regiment', 'company']).preTestScore.mean().unstack(level = 'company')) # Step 9. Group the entire dataframe by regiment and company print (regiment.groupby(['regiment', 'company']).mean()) # Step 10. What is the number of observations in each regiment and company print (regiment.groupby(['regiment', 'company']).size()) # Step 11. Iterate over a group and print the name and the whole data from the regiment for name, group in regiment.groupby('regiment'): # print the name of the regiment print(name) # print the data of that regiment print(group)
Python
UTF-8
763
4.59375
5
[ "CC-BY-4.0" ]
permissive
#!/usr/bin/python3 simple_array = [1,2,3] my_array = [] my_array.append(1) # Should log: [1,2,3] print(simple_array) # Should log: [1] print(my_array) # Should log: 1 print(len(my_array)) # Basic for in statement. Following : you need a new line with 4 spaces # In this case, there are 4 spaces ahead of print() for thing in simple_array: print('the current ele ment in my array is ', thing) brother2, brother1 = ["Nick", "Jeff"] print(brother2, "is the younger brother") print(brother1, "is the older brother") # Key value pairs students = { 'one': 'Vanessa', 'two': "Jeff" } # Print information in students print(students) print(students.get('two')) print(students.values()) for key, value in students.items(): print('key:',key,'| value:',value)
Python
UTF-8
155
2.9375
3
[]
no_license
id="ilovepython" s=input("아이디를 입력하시오:") if s==id: print("환영합니다.") else: print("아이디를 찾을 수 없습니다.")
Java
UTF-8
1,397
3.3125
3
[]
no_license
/** * */ package maps; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import sets.Pays; /** * @author fla * */ public class MapPays { /** * @param args */ public static void main(String[] args) { // creez une map permettant de stocker les instances de pays (valeur)en // fonction de leur nom (clé) Map<String, Pays> mapPays = new HashMap<>(); mapPays.put("USA", new Pays(331883986, 62641)); mapPays.put("France", new Pays(66992699, 41464)); mapPays.put("Allemagne", new Pays(83042235, 48196)); mapPays.put("UK", new Pays(66465641, 42491)); mapPays.put("Italie", new Pays(60494785, 34318)); mapPays.put("Japon", new Pays(126330302, 39287)); mapPays.put("Chine", new Pays(1394112547, 9771)); mapPays.put("Russie", new Pays(146716295, 11289)); mapPays.put("Inde", new Pays(1358408567, 2016)); // Recherchez et supprimez le pays qui a le moins d’habitant long nbrMin = Long.MAX_VALUE; Iterator<Pays> iterator = mapPays.values().iterator(); while (iterator.hasNext()) { Pays pays = iterator.next(); if (pays.getNbHab() < nbrMin) { // long l =(new Double(pays.getNbHab()).longValue()); nbrMin = (new Double(pays.getNbHab()).longValue()); iterator.remove(); } } // Affichez l’ensemble des pays restants. System.out.println(mapPays); } }
C
UTF-8
200
3.0625
3
[]
no_license
#include<stdio.h> #include<conio.h> void main() { char k,ascii; clrscr(); printf("\nEnter a key from keyboard:"); scanf("%c",&k); printf("ASCII value of %c = %d",k,k); getch(); }
Java
UTF-8
347
1.703125
2
[]
no_license
package cn.edu.sdut.comm; public class CommonUtils { public interface UserInfo{ String USERDAO = "sdut.userdao"; } public interface BillInfo{ String BILLDAO = "sdut.billdao"; } public interface GoodsInfo{ String GOODSDAO = "sdut.goodsdao"; } public interface GoodsTypeInfo{ String TYPEDAO = "sdut.typedao"; } }
Python
UTF-8
3,211
2.53125
3
[ "LicenseRef-scancode-public-domain" ]
permissive
#!/usr/bin/env python3 MASTER_COMMIT = "8fd8f49595389c9198d206fbbb3c06b09e9fbd00" SECRET_PART = "dd02c" FILES_TO_CHANGE = ["main.py"] import pygit2 import sys import os from gitcourselib import check_commit, _logprint # Initialize Repository object repo_path = pygit2.discover_repository(os.getcwd()) repo = pygit2.Repository(repo_path) # Commit to check against MASTER_COMMIT_OBJ = repo.get(MASTER_COMMIT) # Argument 1 is refs/heads/<branch-name> ref = sys.argv[1] ref_obj = repo.references[ref] if str(repo.merge_base(MASTER_COMMIT, ref_obj.target)) != MASTER_COMMIT: _logprint("[{ref_obj.name}] Branch incompatible with 'master' - please rebase...", ref) sys.exit(2) def check_secret(commit): tree = commit.tree # Check against previous from the splitted commit (does not contain 'about' yet) diff = tree.diff_to_tree(commit.parents[0].tree) patches = [p for p in diff] # Looking for the patch against 'main.py' checked_patch = None for p in patches: if p.delta.new_file.path == "main.py": checked_patch = p break if checked_patch is None: return False, f"[{commit.id}] commit has not changed the 'main.py' file." # Examine all commited hunks for lines # All changed lines must not contain the hardcoded secret commit_code = "" for hunk in checked_patch.hunks: for l in hunk.lines: # print(l.origin, l.content, hunk) if l.new_lineno == -1: # print(l.origin, l.content, hunk) commit_code += l.content if SECRET_PART in commit_code: return False, f"[{commit.id}] Commit seems to still contain the secret." return True, f"[{commit.id}] Hardcoded secret not found!" def check_diff(ref_obj): tree = ref_obj.peel().tree diff = tree.diff_to_index(repo.index) patches = [p for p in diff] if len(patches) > 2: return False, f"[{ref_obj.name}] Fixing a hardcoded secret should not require a new file." files_changed = {} # {filepath: similarity-ratio} for p in patches: if (p.delta.old_file.path != p.delta.new_file.path): return False, f"[{ref_obj.name}] Renaming a file should not be required." if p.delta.similarity != 0: files_changed[p.delta.old_file.path] = p.delta.similarity for f in files_changed.keys(): if f not in FILES_TO_CHANGE: return False, f"[{ref_obj.name}] Looks like the file '{f}' is not modified." else: if files_changed[f] < 50 : return False, f"[{ref_obj.name}] Looks like the file '{f}' is modified too much." return True, f"[{ref_obj.name}] passes!" checked_commits = 0 for commit in repo.walk(ref_obj.target, pygit2.GIT_SORT_TOPOLOGICAL): # If the master commit was found - stop traversing if str(commit.id) == MASTER_COMMIT: break checked_commits += 1 # Check all commits for formatting pass_, message = check_commit(commit) _logprint(message, ref) if not pass_ : sys.exit(1) if commit.message.lower().startswith("[routes]"): pass_, message = check_secret(commit) _logprint(message, ref) if not pass_ : sys.exit(1) print() # Check the final patch for sanity pass_, message = check_diff(ref_obj) _logprint(message, ref) if not pass_ : sys.exit(1) sys.exit(0)
JavaScript
UTF-8
2,178
2.65625
3
[]
no_license
var assert = require('assert'); function arry2buffer (arry) { var ret = new Buffer(arry.length); for (var i=0; i<arry.length; i++) { ret[i] = arry[i]; } return ret; } function testBuffer () { return arry2buffer([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 1, 2, 3, 4, 1, 2, 3, 0, 0, 2, 3, 4, 1, 2, 3, 4]); } function go (execlib, bufferlib) { 'use strict'; var testlogic = new (bufferlib.SynchronousLogic)([ 'Char', 'Byte', 'UInt16LE', 'UInt16BE', 'UInt32LE', 'UInt32BE', 'UInt48LE', 'UInt48BE', 'UInt64LE', 'UInt64BE', 'Int16LE', 'Int16BE', 'Int32LE', 'Int32BE', 'Int48LE', 'Int48BE', 'Int64LE', 'Int64BE' ]), tb = testBuffer(), dcd = testlogic.decode(tb); console.log(tb, '=>', dcd); assert(dcd[0] === String.fromCharCode(1)); assert(dcd[1] === 2); assert(dcd[2] === 4*256+3); assert(dcd[3] === 1*256+2); assert(dcd[4] === 3+4*256+1*256*256+2*256*256*256); assert(dcd[5] === 3*256*256*256+4*256*256+1*256+2); assert(dcd[6] === 3+4*256+1*256*256+2*256*256*256+3*256*256*256*256+4*256*256*256*256*256); assert(dcd[7] === 1*256*256*256*256*256+2*256*256*256*256+3*256*256*256+4*256*256+1*256+2); assert(dcd[8] === 3+4*256+1*256*256+2*256*256*256+3*256*256*256*256+4*256*256*256*256*256+1*256*256*256*256*256*256+2*256*256*256*256*256*256*256); assert(dcd[9] === 3*256*256*256*256*256*256*256+4*256*256*256*256*256*256+1*256*256*256*256*256+2*256*256*256*256+3*256*256*256+4*256*256+1*256+2); assert(dcd[16] === 1 + 2*256+ 3*256*256+ 4*256*256*256+ 1*256*256*256*256+ 2*256*256*256*256*256+ 3*256*256*256*256*256*256+ 0*256*256*256*256*256*256*256 ); assert(dcd[17] === 4 + 3*256+ 2*256*256+ 1*256*256*256+ 4*256*256*256*256+ 3*256*256*256*256*256+ 2*256*256*256*256*256*256+ 0*256*256*256*256*256*256*256 ); } function main (execlib) { 'use strict'; go(execlib, require('../index')(execlib)); } module.exports = main;
Java
UTF-8
159
1.75
2
[ "Apache-2.0" ]
permissive
package com.example.blockcoverage; public class HasExceptionsTestee { public static void foo(){ String x = null; int y =x.length(); y++; } }
Python
UTF-8
1,459
2.53125
3
[]
no_license
import keras from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D, BatchNormalization, Input def get_cnn_model(input_shape): print("input_shape: " + str(input_shape)) model = Sequential() model.add(Conv2D(64, kernel_size=(3, 3), activation='relu', input_shape=input_shape)) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(BatchNormalization()) model.add(Conv2D(128, kernel_size=(3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(BatchNormalization()) model.add(Conv2D(256, kernel_size=(3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(BatchNormalization()) model.add(Conv2D(512, kernel_size=(3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(BatchNormalization()) model.add(Conv2D(512, kernel_size=(3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(BatchNormalization()) model.add(Flatten()) model.add(Dropout(0.25)) model.add(Dense(4096, activation='relu')) model.add(BatchNormalization()) model.add(Dropout(0.25)) model.add(Dense(1000, activation='relu')) model.add(BatchNormalization()) model.add(Dropout(0.4)) model.add(Dense(2, activation='tanh')) model.compile(loss=keras.losses.mean_squared_error, optimizer=keras.optimizers.Adadelta()) return model
Markdown
UTF-8
3,964
2.546875
3
[]
permissive
--- layout: post title: "CKEditor 5 in Nuxt(Vue.js)" subtitle: "Nuxt 에서 ckeditor 적용하기" author: "코마" date: 2019-02-25 01:00:00 +0900 categories: [ "vue", "ckeditor" ] excerpt_separator: <!--more--> --- 안녕하세요 코마입니다. 오늘은 CKEditor 를 Vue.js 에 적용하도록 하겠습니다. CKEditor 는 널리 사용되는 에디터 중에 하나입니다. CKEditor 를 통해 사용자는 게시글을 쉽게 꾸밀 수 있습니다. 만약, 단순 textarea, Text Input 에 질리셨다면 이 에디터를 적용해 보길 권합니다. <!--more--> # 개요 CKEditor 는 Vue.js 를 위한 npm 을 지원하고 있습니다. 저는 Nuxt 를 이용해 개발을 하고 있으므로 Nuxt 에서 적용하는 방식을 소개해 드리도록 하겠습니다. # 설치 Nuxt 어플리케이션이 이미 준비되어 있다면 여러분은 아래의 명령어를 통해서 vue 전용 ckeditor 를 설치할 수 있습니다. ```bash npm install --save @ckeditor/ckeditor5-vue @ckeditor/ckeditor5-build-classic ``` ## 플러그인 설정 Nuxt의 plugin 폴더에서 Vue.use 를 이용하면 Ckeditor 를 전역적으로 등록하고 사용할 수 있습니다. 저는 `/plugins/ckeditor-plugin.js` 경로를 만들어 아래의 코드를 적용하였습니다. ```js import Vue from 'vue'; import CKEditor from '@ckeditor/ckeditor5-vue'; Vue.use( CKEditor ); ``` # nuxt.config.js 설정 nuxt.config.js 는 nuxt 의 전체 설정을 담고있는 환경설정 파일입니다. 이 파일을 통해 작성한 플러그인을 등록하고 nuxt 명령을 재실행해줍니다. ```js module.exports = { mode: 'spa', // 중략 plugins: [ { src: "~/plugins/ckeditor-plugin", ssr: false }, ], // 중략 } ``` ```bash $ nuxt ``` ## 주의할 점 nuxt 의 mode 설정은 기본적으로 `universal` 입니다. 즉, SSR (Server Side Rendering) 을 지원하게 됩니다. 즉, express 서버에서 SEO 등의 이유로 인해 미리 파일을 생성하여 검색엔진이 식별하기 좋도록 렌더링된 데이터를 내려주는 것입니다. 그러나 이는 **javascript 가 browser 에서만 동작할 것이라고 가정한 ckeditor 에게는 독이됩니다.** 따라서 ckeditor 를 제대로 적용하기 위해서는 SSR 을 off 해주거나 universal 모드로 포팅을 해야합니다. 저의 경우 SEO 를 신경쓰지 않아도 되는 상황입니다. (내부 환경에서 사용하기 때문에 SPA 로도 충분합니다.) 따라서 `nuxt.config.js` 파일에 `mode: 'spa',` 를 설정하였습니다. 이 경우 `document is undefined` 라는 에러가 발생하지 않습니다. ## ckeditor 적용 이제 실제 코드상에서 ckeditor 를 적용해 보도록 하겠습니다. 물론 걱정마세요 순수 vue 를 위한 코드를 별도로 준비해 놓았습니다. 여러분은 안심하고 이를 복사해서 사용하면됩니다. 그러나 먼저 nuxt 에서 적용하는 방법을 간단히 소개해 보도록 하겠습니다. 아래의 컴포넌트를 만들어 주세요. ```html <template> <div> <ckeditor :editor="editor" v-model="editorData" :config="editorConfig"></ckeditor> <div class="ck-content" v-html="getData"></div> </div> </template> <script> import ClassicEditor from "@ckeditor/ckeditor5-build-classic"; export default { components: { Toc, }, data() { return { editor: ClassicEditor, editorData: "<p>Content of the editor.</p>", editorConfig: { // The configuration of the editor. // plugins: [ Paragraph, Bold, Italic ], extraPlugins: [ MyCustomUploadAdapterPlugin ], } }; }, mounted() { }, computed: { getData() { return this.editorData; } } }; </script> ``` 작성이 완료된 컴포넌트들을 바탕으로 구현을 하면 아래와 같은 형태가 나온다. 코드펜으로 구현 내용을 첨부하였다. <!-- 왜 여기서 멈추었지? -->
Java
UTF-8
174
1.53125
2
[]
no_license
package com.legaoyi.platform.service; import java.util.Map; public interface SecurityService { public Map<?, ?> getUserAccount(String userAccount) throws Exception; }
Java
UTF-8
93
1.765625
2
[]
no_license
package cl.test.todolist.defaultModel; public interface DefaultModel<T> { T create(); }
Java
UTF-8
261
1.875
2
[ "MIT" ]
permissive
package com.jaigo.agfxengine.view.listeners; // OnDragListener // // Created by Jeff Gosling on 08/01/2015 import com.jaigo.agfxengine.view.BaseView; public interface OnDragListener { public boolean onDrag(BaseView view, float dragPercentX, float dragPercentY); }
C++
UTF-8
485
2.765625
3
[ "MIT" ]
permissive
#ifndef UI_MENU_H #define UI_MENU_H #pragma once #include <string> #include <vector> #include "ui_component.h" #include "menu_item.h" namespace ui { class Menu { public: Menu(std::string name, const std::vector<MenuItem>& items) : _name(name), _child(items) {} ~Menu() {} void set_name(const std::string name) { _name = name; } const std::string& get_name(void) const { return _name; } private: std::string _name; std::vector<MenuItem> _child; }; } #endif // !UI_MENU_H
Python
UTF-8
12,034
2.859375
3
[ "MIT" ]
permissive
import copy import json import os import sys import warnings from typing import Any, Dict, IO, Iterator, List, Optional, Union from jsonschema import Draft4Validator, RefResolver, ValidationError from pkg_resources import resource_filename package_name = 'starfish' class SpaceTxValidator: def __init__(self, schema: str) -> None: """create a validator for a json-schema compliant spaceTx specification file Parameters ---------- schema : str file path to schema """ self._schema: Dict = self.load_json(schema) self._validator: Draft4Validator = self._create_validator(self._schema) @staticmethod def _create_validator(schema: Dict) -> Draft4Validator: """resolve $ref links in a loaded json schema and return a validator Parameters ---------- schema : Dict loaded json schema Returns ------- Draft4Validator : json-schema validator specific to the supplied schema, with references resolved """ experiment_schema_path = resource_filename( package_name, "spacetx_format/schema/experiment.json") package_root = os.path.dirname(os.path.dirname(experiment_schema_path)) base_uri = 'file://' + package_root + '/' resolver = RefResolver(base_uri, schema) return Draft4Validator(schema, resolver=resolver) @staticmethod def load_json(json_file: str) -> Dict: with open(json_file, 'rb') as f: return json.load(f) @staticmethod def _recurse_through_errors(error_iterator: Iterator[ValidationError], level: int=0, filename: str=None) -> None: """Recurse through ValidationErrors, printing message and schema path Parameters ---------- error_iterator : Iterator[ValidationError] iterator over ValidationErrors that occur during validation level : int current level of recursion filename: str informational string regarding the source file of the given object """ fmt = "\n{stars} {message}\n" fmt += "\tSchema: \t{schema}\n" fmt += "\tSubschema level:\t{level}\n" fmt += "\tPath to error: \t{path}\n" if filename: fmt += "\tFilename: \t{filename}\n" for error in error_iterator: message = fmt.format( stars="***" * level, level=str(level), path="/".join([str(x)for x in error.absolute_schema_path]), message=error.message, cause=error.cause, schema=error.schema.get("$id", "unknown"), filename=filename, ) warnings.warn(message) if error.context: level += 1 SpaceTxValidator._recurse_through_errors(error.context, level=level) def validate_file(self, target_file: str) -> bool: """validate a target file, returning True if valid and False otherwise Parameters ---------- target_file : str path or URL to a target json object to be validated against the schema passed to this object's constructor Returns ------- bool : True, if object valid, else False Examples -------- Validate a codebook file:: >>> from pkg_resources import resource_filename >>> from starfish.spacetx_format.util import SpaceTxValidator >>> schema_path = resource_filename( "starfish", "spacetx_format/schema/codebook/codebook.json") >>> validator = SpaceTxValidator(schema_path) >>> if not validator.validate_file(your_codebook_filename): >>> raise Exception("invalid") """ target_object = self.load_json(target_file) return self.validate_object(target_object, target_file) def validate_object( self, target_object: Union[dict, list], target_file: str=None, ) -> bool: """validate a loaded json object, returning True if valid, and False otherwise Parameters ---------- target_object : Dict loaded json object to be validated against the schema passed to this object's constructor target_file : str informational string regarding the source file of the given object Returns ------- bool : True, if object valid, else False Examples -------- Validate an experiment json string :: >>> from pkg_resources import resource_filename >>> from starfish.spacetx_format.util import SpaceTxValidator >>> schema_path = resource_filename("starfish", "spacetx_format/schema/experiment.json") >>> validator = SpaceTxValidator(schema_path) >>> if not validator.validate_object(your_experiment_object): >>> raise Exception("invalid") """ if self._validator.is_valid(target_object): return True else: es: Iterator[ValidationError] = self._validator.iter_errors(target_object) self._recurse_through_errors(es, filename=target_file) return False def fuzz_object( self, target_object: Union[dict, list], target_file: str=None, out: IO=sys.stdout, ) -> None: """performs mutations on the given object and tests for validity. A representation of the validity is printed to the given output stream. Parameters ---------- target_object : Dict loaded json object to be validated against the schema passed to this object's constructor target_file : str informational string regarding the source file of the given object out : IO output stream for printing """ if target_file: out.write(f"> Fuzzing {target_file}...\n") else: out.write("> Fuzzing unknown...\n") fuzzer = Fuzzer(self._validator, target_object, out) fuzzer.fuzz() class Fuzzer(object): def __init__(self, validator: Draft4Validator, obj: Any, out: IO=sys.stdout) -> None: """create a fuzzer which will check different situations against the validator Parameters ---------- validator : SpaceTxValidator validator which should match the given object type obj : Any JSON-like object which will be checked against the validator out : IO output stream for printing """ self.validator = validator self.obj = obj self.out = out self.stack: Optional[List[Any]] = None def fuzz(self) -> None: """prints to the out field the state of the object tree after types of fuzzing Each line is prefixed by the output of {state()} followed by a YAML-like representation of the branch of the object tree. """ header = f"{self.state()}" header += "If the letter is present, mutation is valid!" self.out.write(f"{header}\n") self.out.write("".join([x in ("\t", "\n") and x or "-" for x in header])) self.out.write("\n") self.stack: List[Any] = [] try: self.descend(self.obj) finally: self.stack = None def state(self) -> str: """primary driver for the checks of individual trees Returns ------- str : space-separated representation of the fuzzing conditions. If a letter is present, then mutation leaves the tree in a valid state: A: inserting a fake key or appending to a list D: deleting a key or index I: converting value to an integer I: converting value to a string M: converting value to an empty dict L: converting value to an empty list """ rv = [ Add().check(self), Del().check(self), Change("I", lambda *args: 123456789).check(self), Change("S", lambda *args: "fake").check(self), Change("M", lambda *args: dict()).check(self), Change("L", lambda *args: list()).check(self), ] return ' '.join(rv) + "\t" def descend(self, obj: Any, depth: int=0, prefix: str="") -> None: """walk a JSON-like object tree printing the state of the tree at each level. A YAML representation is used for simplicity. Parameters ---------- obj : Any JSON-like object tree depth : int depth in the tree that is currently being evaluated prefix : str value which should be prepended to printouts at this level """ if self.stack is None: raise Exception("invalid state") if isinstance(obj, list): for i, o in enumerate(obj): depth += 1 self.stack.append(i) self.descend(o, depth, prefix="- ") self.stack.pop() depth -= 1 elif isinstance(obj, dict): for k in obj: # This is something of a workaround in that we need a special # case for object keys since no __getitem__ method will suffice. self.stack.append((k,)) self.out.write(f"{self.state()}{' ' * depth}{prefix}{k}:\n") self.stack.pop() if prefix == "- ": prefix = " " depth += 1 self.stack.append(k) self.descend(obj[k], depth, prefix=" " + prefix) self.stack.pop() depth -= 1 else: self.out.write(f"{self.state()}{' ' * depth}{prefix}{obj}\n") class Checker(object): @property def LETTER(self) -> str: return "?" def check(self, fuzz: Fuzzer) -> str: """create a copy of the current state of the object tree, mutate it, and run it through is_valid on the validator. Parameters ---------- fuzz : Fuzzer the containing instance Returns ------- str : A single character string representation of the check """ # Don't mess with the top level if fuzz.stack is None: return self.LETTER if not fuzz.stack: return "-" # Operate on a copy for mutating dupe = copy.deepcopy(fuzz.obj) target = dupe for level in fuzz.stack[0:-1]: target = target.__getitem__(level) self.handle(fuzz, target) valid = fuzz.validator.is_valid(dupe) return valid and self.LETTER or "." def handle(self, fuzz, target): raise NotImplementedError() class Add(Checker): @property def LETTER(self) -> str: return "A" def handle(self, fuzz, target): if isinstance(target, dict): target["fake"] = "!" elif isinstance(target, list): target.append("!") else: raise Exception("unknown") class Del(Checker): @property def LETTER(self) -> str: return "D" def handle(self, fuzz, target): key = fuzz.stack[-1] if isinstance(key, tuple): key = key[0] target.__delitem__(key) class Change(Checker): @property def LETTER(self) -> str: return self.letter def __init__(self, letter, call): self.letter = letter self.call = call def handle(self, fuzz, target): key = fuzz.stack[-1] if isinstance(key, tuple): key = key[0] target.__setitem__(key, self.call())
JavaScript
UTF-8
5,981
2.921875
3
[ "MIT" ]
permissive
window.onload = initialize; //Espera a que se cargué la página para llamar a la función ==> function initialize(){} var formBookings; var refBookings; var tbodyTableBookings; var CREATE = "DONE"; var UPDATE = "MODIFY"; var modo = CREATE; var refBookingToEdit; function initialize() { formBookings = document.getElementById("form-bookings"); formBookings.addEventListener("submit", sendBookingToFirebase, false); tbodyTableBookings = document.getElementById("tbody-table-bookings"); refBookings = firebase.database().ref().child("Bookings"); showBookingsFromFirebase(); } var rowsToShow; var data; function showBookingsFromFirebase() { refBookings.on("value", function (snap) { //Me devuelve el valor correspondiente a cada convalidación data = snap.val(); //Me da los valores de firebase que existen dentro de la referencia remBookings rowsToShow = ""; for (var key in data) { rowsToShow += "<tr>" + "<td>" + data[key].name + "</td>" + "<td>" + data[key].surname + "</td>" + "<td>" + data[key].phoneNumber + "</td>" + "<td>" + data[key].adultQuestion + "</td>" + "<td>" + data[key].identityDocument + "</td>" + "<td>" + data[key].customers + "</td>" + "<td>" + '<button class ="btn tbn-dafault edit" data-booking="' + key + '">' + '<i class="fas fa-pen"></i>' + '</button>' + "</td>" + "<td>" + '<button class ="btn tbn-danger delete" data-booking="' + key + '">' + '<i class="fas fa-trash"></i>' + '</button>' + "</td>" + "<td>" + "</td>" + "</tr>" } tbodyTableBookings.innerHTML = rowsToShow; if (rowsToShow != "") { var editElements = document.getElementsByClassName("edit"); for (var i = 0; i < editElements.length; i++) { editElements[i].addEventListener("click", editBookingFromFirebase, false); } var deleteElements = document.getElementsByClassName("delete"); for (var i = 0; i < deleteElements.length; i++) { deleteElements[i].addEventListener("click", deleteBookingFromFirebase, false); } } }); } function editBookingFromFirebase() { var keyFromBookingsToEdit = this.getAttribute("data-booking"); refBookingsToEdit = refBookings.child(keyFromBookingsToEdit); refBookingsToEdit.once("value", function (snap) { var data = snap.val(); document.getElementById("name").value = data.name; document.getElementById("surname").value = data.surname; document.getElementById("phone-number").value = data.phoneNumber; document.getElementById("adult-question").value = data.adultQuestion; document.getElementById("identity-document").value = data.identityDocument; document.getElementById("customers").value = data.customers; }); document.getElementById("button-send-booking").value = UPDATE; modo = UPDATE; } /* (function () { var formulario = document.getElementsByTagName('completeForm')[0], elementos = document.formulario.elements; var boton = document.getElementById("button-send-booking"); var validarNombre = function () { if (document.formulario.name.value == "") { alert("completa el campo nombre"); } }; var validar = function () { validarNombre(); }; document.formulario.addEventListener("submit", validar); })(); */ function validation() { var name, surname, phone, adult, identity, customer; name = document.getElementById("name").value; surname = document.getElementById("surname").value; phone = document.getElementById("phone-number").value; adult = document.getElementById("adult-question").value; identity = document.getElementById("identity-document").value; customer = document.getElementById("customers").value; if (name == "" || surname == "" || phone == "" || adult == "" || identity == "" || customer == "") { document.getElementById("fill-in").style.display = 'block'; clearInterval(refBookings); } else if (name.length > 20) { document.getElementById("long-name").style.display = 'block'; clearInterval(refBookings); } else if (surname.length > 20) { document.getElementById("long-surname").style.display = 'block'; clearInterval(refBookings); } else if (phone.length > 9 || phone.length < 9 || isNaN(phone)) { document.getElementById("wrong-number").style.display = 'block'; clearInterval(refBookings); } else if (identity.length > 9 || identity.length < 9) { document.getElementById("wrong-identity").style.display = 'block'; clearInterval(refBookings); } } var keyFromBookingDelete var refBookingToDelete function deleteBookingFromFirebase() { keyFromBookingDelete = this.getAttribute("data-booking"); refBookingToDelete = refBookings.child(keyFromBookingDelete); refBookingToDelete.remove(); } function sendBookingToFirebase(event) { event.preventDefault();//Esto nos sirve para prevenir el comportamiento por defecto que causa window.onload = initialize switch (modo) { case CREATE: refBookings.push({ //Aquí añado el registro, el objeto janson name: event.target.name.value, surname: event.target.surname.value, phoneNumber: event.target.phoneNumber.value, adultQuestion: event.target.adultQuestion.value, identityDocument: event.target.identityDocument.value, customers: event.target.customers.value }); break; case UPDATE: refBookingsToEdit.update({ name: event.target.name.value, surname: event.target.surname.value, phoneNumber: event.target.phoneNumber.value, adultQuestion: event.target.adultQuestion.value, identityDocument: event.target.identityDocument.value, customers: event.target.customers.value }); modo = CREATE; document.getElementById("button-send-booking").value = CREATE; break; } formBookings.reset(); }
JavaScript
UTF-8
1,245
2.8125
3
[]
no_license
const request = require('request'); const cheerio = require('cheerio'); /** * функция парcинга сайта, возвращает промисс * @param {string} url * @param {number} count */ function getNews(category, count) { const URL = 'https://habrahabr.ru/flows/' + category; return new Promise((resolve, reject) => { request(URL, (error, response, body) => { if (error) { reject(error); } if (response.statusCode !== 200) { reject(response.statusCode); } const $ = cheerio.load(body); const posts = []; $('.post').each( (i, item) => { let post = {}; if (i < count) { post.author = $(item).find('.user-info__nickname').text(); post.title = $(item).find('.post__title_link').text(); post.link = $(item).find('.post__title_link').attr('href'); post.time = $(item).find('.post__time').text(); posts.push(post) }; }) resolve(posts) }) }) }; module.exports = getNews;
C#
UTF-8
1,761
2.578125
3
[]
no_license
namespace Project2020 { using System.Collections; using UnityEngine; public class Door : MonoBehaviour, IInteractable { [SerializeField] private Animator m_Animator = null; [SerializeField] private GameObject m_Player = null; // Depending from which direction you open the door // change animation // testing animation // not sure how I want to trigger animations private void Open() { m_Animator.SetBool("Open", true); } private void Close() { m_Animator.SetBool("Open", false); } private IEnumerator Closing(float time) { yield return new WaitForSeconds(time); Close(); } private void OpenBackwards() { m_Animator.SetBool("OpenBackwards", true); } private void CloseBackwards() { m_Animator.SetBool("OpenBackwards", false); } private IEnumerator ClosingBackwards(float time) { yield return new WaitForSeconds(time); CloseBackwards(); } public void Interact() { if (m_Animator.IsInTransition(0)) return; if (m_Player) { if (m_Player.transform.forward.z < 0f) { OpenBackwards(); StartCoroutine(ClosingBackwards(3f)); } else { Open(); StartCoroutine(Closing(3f)); } } } public bool IsInAnimation() { return m_Animator.IsInTransition(0); } } }
Markdown
UTF-8
11,198
2.8125
3
[]
no_license
--- title: MySQL · 引擎特性 · Group Replication内核解析 category: default tags: - mysql.taobao.org created_at: 2020-09-14 16:18:18 original_url: http://mysql.taobao.org/monthly/2017/08/01/ --- [ # 数据库内核月报 - 2017 / 08 ](http://mysql.taobao.org/monthly/2017/08) [›](http://mysql.taobao.org/monthly/2017/08/02/) * [当期文章](#) ## MySQL · 引擎特性 · Group Replication内核解析 ## 背景 为了创建高可用数据库系统,传统的实现方式是创建一个或多个备用的数据库实例,原有的数据库实例通常称为主库master,其它备用的数据库实例称为备库或从库slave。当master故障无法正常工作后,slave就会接替其工作,保证整个数据库系统不会对外中断服务。master与slaver的切换不管是主动的还是被动的都需要外部干预才能进行,这与数据库内核本身是按照单机来设计的理念悉悉相关,并且数据库系统本身也没有提供管理多个实例的能力,当slave数目不断增多时,这对数据库管理员来说就是一个巨大的负担。 ## MySQL的传统主从复制机制 MySQL传统的高可用解决方案是通过binlog复制来搭建主从或一主多从的数据库集群。主从之间的复制模式支持异步模式(async replication)和半同步模式(semi-sync replication)。无论哪种模式下,都是主库master提供读写事务的能力,而slave只能提供只读事务的能力。在master上执行的更新事务通过binlog复制的方式传送给slave,slave收到后将事务先写入relay log,然后重放事务,即在slave上重新执行一次事务,从而达到主从机事务一致的效果。 ![pic](assets/1600071498-4cd36b7f29945640bc0c0dc887bd19dc.png) 上图是异步复制(Async replication)的示意图,在master将事务写入binlog后,将新写入的binlog事务日志传送给slave节点,但并不等待传送的结果,就会在存储引擎中提交事务。 ![pic](assets/1600071498-a40638a23a1f00d26fc1daf50cd6bc85.png) 上图是半同步复制(Semi-sync replication)的示意图,在master将事务写入binlog后,将新写入的binlog事务日志传送给slave节点,但需要等待slave返回传送的结果;slave收到binlog事务后,将其写入relay log中,然后向master返回传送成功ACK;master收到ACK后,再在存储引擎中提交事务。 MySQL基于两种复制模式都可以搭建高可用数据库集群,也能满足大部分高可用系统的要求,但在对事务一致性要求很高的系统中,还是存在一些不足,主要的不足就是主从之间的事务不能保证时刻完全一致。 * 基于异步复制的高可用方案存在主从不一致乃至丢失事务的风险,原因在于当master将事务写入binlog,然后复制给slave后并不等待slave回复即进行提交,若slave因网络延迟或其它问题尚未收到binlog日志,而此时master故障,应用切换到slave时,本来在master上已经提交的事务就会丢失,因其尚未传送到slave,从而导致主从之间事务不一致。 * 基于semi-sync复制的高可用方案也存在主备不一致的风险,原因在于当master将事务写入binlog,尚未传送给slave时master故障,此时应用切换到slave,虽然此时slave的事务与master故障前是一致的,但当主机恢复后,因最后的事务已经写入到binlog,所以在master上会恢复成已提交状态,从而导致主从之间的事务不一致。 ## Group Replication应运而生 为了应对事务一致性要求很高的系统对高可用数据库系统的要求,并且增强高可用集群的自管理能力,避免节点故障后的failover需要人工干预或其它辅助工具干预,MySQL5.7新引入了Group Replication,用于搭建更高事务一致性的高可用数据库集群系统。基于Group Replication搭建的系统,不仅可以自动进行failover,而且同时保证系统中多个节点之间的事务一致性,避免因节点故障或网络问题而导致的节点间事务不一致。此外还提供了节点管理的能力,真正将整个集群做为一个整体对外提供服务。 ## Group Replication的实现原理 Group Replication由至少3个或更多个节点共同组成一个数据库集群,事务的提交必须经过半数以上节点同意方可提交,在集群中每个节点上都维护一个数据库状态机,保证节点间事务的一致性。Group Replication基于分布式一致性算法Paxos实现,允许部分节点故障,只要保证半数以上节点存活,就不影响对外提供数据库服务,是一个真正可用的高可用数据库集群技术。 Group Replication支持两种模式,单主模式和多主模式。在同一个group内,不允许两种模式同时存在,并且若要切换到不同模式,必须修改配置后重新启动集群。 在单主模式下,只有一个节点可以对外提供读写事务的服务,而其它所有节点只能提供只读事务的服务,这也是官方推荐的Group Replication复制模式。单主模式的集群如下图所示: ![pic](assets/1600071498-513e41b7f385143653d5c2c3c5910003.png) 在多主模式下,每个节点都可以对外提供读写事务的服务。但在多主模式下,多个节点间的事务可能有比较大的冲突,从而影响性能,并且对查询语句也有更多的限制,具体限制可参见使用手册。多主模式的集群如下图所示: ![pic](assets/1600071498-815a1cec4b078f2e2d5ad3c964984f6d.png) MySQL Group Replication是建立在已有MySQL复制框架的基础之上,通过新增Group Replication Protocol协议及Paxos协议的实现,形成的整体高可用解决方案。与原有复制方式相比,主要增加了certify的概念,如下图所示: ![pic](assets/1600071498-21a80fc34643f01ef6a01e67309648ff.png) certify模块主要负责检查事务是否允许提交,是否与其它事务存在冲突,如两个事务可能修改同一行数据。在单机系统中,两个事务的冲突可以通过封锁来避免,但在多主模式下,不同节点间没有分布式锁,所以无法使用封锁来避免。为提高性能,Group Replication乐观地来对待不同事务间的冲突,乐观的认为多数事务在执行时是没有并发冲突的。事务分别在不同节点上执行,直到准备提交时才去判断事务之间是否存在冲突。下面以具体的例子来解释certify的工作原理: ![pic](assets/1600071498-8d1da69de4393fd8664694043165cc6a.png) 在上图中由3个节点形成一个group,当在节点s1上发起一个更新事务UPDATE,此时数据库版本dbv=1,更新数据行之后,准备提交之前,将其修改的数据集(write set)及事务日志相关信息发送到group,Write set中包含更新行的主键和此事务执行时的快照(由gtid\_executed组成)。组内的每个节点收到certification请求后,进入certification环节,每个节点的当前版本cv=1,与write set相关的版本dbv=1,因为dbv不小于cv,也就是说事务在这个write set上没有冲突,所以可以继续提交。 下面是一个事务冲突的例子,两个节点同时更新同一行数据。如下图所示, ![pic](assets/1600071498-995a47a9b60b6aaa1b62c28c9ace7ae9.png) 在节点s1上发起一个更新事务T1,几乎同时,在节点s2上也发起一个更新事务T2,当T1在s1本地完成更新后,准备提交之前,将其writeset及更新时的版本dbv=1发送给group;同时T2在s2本地完成更新后,准备提交之前,将其writeset及更新时的版本dbv=1也发送给group。 此时需要注意的是,group组内的通讯是采用基于paxos协议的xcom来实现的,它的一个特性就是消息是有序传送,每个节点接收到的消息顺序都是相同的,并且至少保证半数以上节点收到才会认为消息发送成功。xcom的这些特性对于数据库状态机来说非常重要,是保证数据库状态机一致性的关键因素。 本例中我们假设先收到T1事务的certification请求,则发现当前版本cv=1,而数据更新时的版本dbv=1,所以没有冲突,T1事务可以提交,并将当前版本cv修改为2;之后马上又收到T2事务的certification请求,此时当前版本cv=2,而数据更新时的版本dbv=1,表示数据更新时更新的是一个旧版本,此事务与其它事务存在冲突,因此事务T2必须回滚。 ## 核心组件XCOM的特性 MySQL Group Replication是建立在基于Paxos的XCom之上的,正因为有了XCom基础设施,保证数据库状态机在节点间的事务一致性,才能在理论和实践中保证数据库系统在不同节点间的事务一致性。 Group Replication在通讯层曾经历过一次比较大的变动,早期通讯层采用是的Corosync,而后来才改为XCom。 ![pic](assets/1600071498-ab5975b8114421c6a87b9a21e35245eb.png) 主要原因在于corosync无法满足MySQL Group Replication的要求,如 1. MySQL支持各种平台,包括windows,而corosync不都支持; 2. corosync不支持SSL,而只支持对称加密方式,安全性达不到MySQL的要求; 3. corosync采用UDP,而在云端采用UDP进行组播或多播并不是一个好的解决方案。 此外MySQL Group Replication对于通讯基础设施还有一些更高的要求,最终选择自研xcom,包括以下特性: * 闭环(closed group):只有组内成员才能给组成员发送消息,不接受组外成员的消息。 * 消息全局有序(total order):所有XCOM传递的消息是全局有序(在多主集群中或是偏序),这是构建MySQL 一致性状态机的基础。 * 消息的安全送达(Safe Delivery):发送的消息必须传送给所有非故障节点,必须在多数节点确认收到后方可通知上层应用。 * 视图同步(View Synchrony):在成员视图变化之前,每个节点都以相同的顺序传递消息,这保证在节点恢复时有一个同步点。实际上,组复制并不强制要求消息传递必须在同一个节点视图中。 ## 总结 MySQL Group Replication旨在打造一款事务强一致性金融级的高可用数据库集群产品,目前还存在一些功能限制和不足,但它是未来数据库发展的一个趋势,从传统的主从复制到构建数据库集群,MySQL也在不断的前进,随着产品的不断完善和发展,必将成为引领未来数据库系统发展的潮流。 [阿里云RDS-数据库内核组](http://mysql.taobao.org/) [欢迎在github上star AliSQL](https://github.com/alibaba/AliSQL) 阅读: - [![知识共享许可协议](assets/1600071498-8232d49bd3e964f917fa8f469ae7c52a.png)](http://creativecommons.org/licenses/by-nc-sa/3.0/) 本作品采用[知识共享署名-非商业性使用-相同方式共享 3.0 未本地化版本许可协议](http://creativecommons.org/licenses/by-nc-sa/3.0/)进行许可。 --------------------------------------------------- 原网址: [访问](http://mysql.taobao.org/monthly/2017/08/01/) 创建于: 2020-09-14 16:18:18 目录: default 标签: `mysql.taobao.org`
Python
UTF-8
2,663
2.9375
3
[]
no_license
# Yokeder.py # -*- coding:utf-8 -*- import socket import random import sys import threading from scapy.all import * print('...Yok eder Scriptini kullandığınız için teşekkürler web sitemizi ziyaret etmeyi unutmayın!!! :bilgisayaradair.ml') usage ="""############# HELP ################# python Yokeder.py tcp ip port flag count python Yokeder.py udp ip port count python Yokeder.py icmp ip count ####################################""" def SpoofIP(): return "%i.%i.%i.%i"%(random.randint(1,254),random.randint(1,254),random.randint(1,254),random.randint(1,254)) def SpoofPort(): return "%i"%(random.randint(1,254)) def TCPPacket(data): #print data src_ip = SpoofIP() src_port = SpoofPort() network_layer = IP(src=src_ip , dst=data[0]) transport_layer = TCP(sport=int(src_port) , dport=int(data[1]) , flags=str(data[2])) print "TCP -> SRC IP : {} DST IP : {} SRC PORT : {} DST PORT : {} FLAG : {}".format(src_ip.ljust(15," ") , data[0] , str(src_port).ljust(5 ," ") , data[1] , data[2]) send(network_layer/transport_layer,verbose=False) def UDPPacket(data): src_ip = SpoofIP() src_port = SpoofPort() network_layer = IP(src=src_ip , dst=data[0]) transport_layer = UDP(sport=int(src_port) , dport=int(data[1])) print "UDP -> SRC IP : {} DST IP : {} SRC PORT : {} DST PORT : {}".format(src_ip.ljust(15," ") , data[0] , str(src_port).ljust(5 ," ") , data[1]) send(network_layer/transport_layer,verbose=False) def ICMPPacket(data): src_ip = SpoofIP() src_port = SpoofPort() network_layer = IP(src=src_ip , dst=data[0])/ICMP() print "ICMP -> SRC IP : {} DST IP : {} ".format(src_ip.ljust(15," "),data[0]) send(network_layer,verbose=False) if __name__ == "__main__": if len(sys.argv) < 2 or len(sys.argv)> 6: print usage sys.exit(1) else: tmp = sys.argv[1:] if str(tmp[0]).lower() == "tcp" and len(tmp) == 5: tmp = tmp[1:] for i in range(int(tmp[3])): TCPPacket(tmp) elif str(tmp[0]).lower() == "udp" and len(tmp) == 4: tmp = tmp[1:] for i in range(int(tmp[2])): UDPPacket(tmp) elif str(tmp[0]).lower() == "icmp" and len(tmp) == 3: tmp = tmp[1:] for i in range(int(tmp[1])): ICMPPacket(tmp) else: print usage sys.exit(1)
PHP
UTF-8
354
2.59375
3
[]
no_license
<?php declare(strict_types=1); namespace GuldenWallet\Backend\Application\Settings; use RuntimeException; class SettingNotFoundException extends RuntimeException { /** * @param string $key * @return self */ public static function forKey(string $key): self { return new static("Setting '{$key}' not found."); } }
Shell
UTF-8
4,771
3.4375
3
[ "MIT" ]
permissive
#!/usr/bin/env bash set -o noclobber set -o errexit set -o pipefail set -o nounset ambit_db_user="${AMBIT_DB_USER:-ambit}" ambit_db_pass="${AMBIT_DB_PASS:-ambit}" ambit_users_db="${AMBIT_USERS_DB:-ambit_users}" ambit_databases="${AMBIT_DATABASES:-ambit}" ambit_base='/opt/ambit' ambit_tmp="${ambit_base}/tmp" ambit_sql_tables="${ambit_tmp}/create_tables.sql" ambit_sql_users="${ambit_tmp}/users.sql" ambit_sql_data_import="${ambit_base}/data_import" declare -a procedure_list=( 'findByProperty' 'deleteDataset' 'createBundleCopy' 'createBundleVersion' ) declare -A public_db_import_urls=( ['calibrate']='https://zenodo.org/record/7193516/files/calibrate.sql.xz' ['gracious']='https://zenodo.org/record/7777590/files/gracious.sql.xz' ['nanoreg1']='https://zenodo.org/record/3467016/files/nanoreg_nrfiles.sql.xz' ['nanoreg2']='https://zenodo.org/record/4713745/files/nanoreg2.sql.xz' ) initdb_d_base='/docker-entrypoint-initdb.d' initdb_d_init_databases="${initdb_d_base}/00-init-databases.sql" initdb_d_create_ambit_tables="${initdb_d_base}/01-create-ambit-tables.sql" initdb_d_create_ambit_user_tables="${initdb_d_base}/02-create-ambit-user-tables.sql" initdb_d_init_procedure_grants="${initdb_d_base}/03-init-procedure-grants.sql" initdb_d_populate_databases="${initdb_d_base}/04-populate-databases.sql" # Run the initialization process if both are true: # * the initialization has not already been performed; # * no custom command is passed or it's only an option for MariaDB/MySQL. mysql_datadir="$(mysqld --verbose --help --log-bin-index=/dev/null 2>/dev/null \ | awk '/^datadir[[:blank:]]/ { print $2 }')" if [[ ! -d ${mysql_datadir}mysql && ( -z ${1} || ${1:0:1} = '-' ) ]]; then # Create the AMBIT user and the AMBIT users database. # FIXME: We also need the 'guest'@'localhost' user. guest_pass="$(openssl rand -base64 32)" { echo "CREATE USER 'guest'@'localhost' IDENTIFIED BY '${guest_pass}';" echo "CREATE USER '${ambit_db_user}'@'%' IDENTIFIED BY '${ambit_db_pass}';" echo "CREATE DATABASE \`${ambit_users_db}\` CHARACTER SET utf8;" echo "GRANT ALL ON \`${ambit_users_db}\`.* TO '${ambit_db_user}'@'%';" } >"${initdb_d_init_databases}" # Create the AMBIT database(s) and the associated grants. for ambit_db in ${ambit_databases}; do echo "CREATE DATABASE \`${ambit_db}\` CHARACTER SET utf8;" echo "GRANT ALL ON \`${ambit_db}\`.* TO '${ambit_db_user}'@'%';" echo "GRANT TRIGGER ON \`${ambit_db}\`.* TO '${ambit_db_user}'@'%';" done >>"${initdb_d_init_databases}" # Initialize the AMBIT databases. for ambit_db in ${ambit_databases}; do echo "USE \`${ambit_db}\`;" cat "${ambit_sql_tables}" done >"${initdb_d_create_ambit_tables}" # Initialize the AMBIT users database. { echo "USE \`${ambit_users_db}\`;" sed 's|"/ambit2"|"/ambit"|g' "${ambit_sql_users}" } >"${initdb_d_create_ambit_user_tables}" # Set up the execute procedure grants. for ambit_db in ${ambit_databases}; do for procedure in "${procedure_list[@]}"; do echo "GRANT EXECUTE ON PROCEDURE \`${ambit_db}\`.${procedure} TO '${ambit_db_user}'@'%';" done done >"${initdb_d_init_procedure_grants}" # If well-known public databases are defined, populate them. echo '[Entrypoint AMBIT] Populating databases...' for ambit_db in ${ambit_databases}; do set +o nounset if [[ -r ${ambit_sql_data_import}/${ambit_db}.sql.xz ]]; then set -o nounset echo "USE \`${ambit_db}\`;" xzcat "${ambit_sql_data_import}/${ambit_db}.sql.xz" # Well-known DB names (e.g. "nanoreg1") could be set as keys in the associative array # ${public_db_import_urls}, with the URI to fetch the (compressed) SQL from as value. elif [[ ${public_db_import_urls[${ambit_db}]} ]]; then set -o nounset import_url="${public_db_import_urls[${ambit_db}]}" echo "USE \`${ambit_db}\`;" curl -s "${import_url}" | xzcat else set -o nounset echo "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *" >/dev/stderr echo >/dev/stderr echo "WARNING: Missing SQL import file for database \"${ambit_db}\"" >/dev/stderr echo >/dev/stderr echo "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *" >/dev/stderr fi done >"${initdb_d_populate_databases}" # Clean up. rm -r "${ambit_tmp}" # End the initialization "if" block. fi # Switch to the upstream Docker image entrypoint script. exec /usr/local/bin/docker-entrypoint.sh "$@"
Markdown
UTF-8
7,527
3.1875
3
[]
no_license
## 1. 逻辑回归 ### Q1 LR与线性回归的区别与联系 逻辑回归是一种广义线性模型,它引入了Sigmoid函数,是非线性模型,但本质上还是一个线性回归模型,因为除去Sigmoid函数映射关系,其他的算法都是线性回归的。 逻辑回归和线性回归首先都是广义的线性回归,在本质上没多大区别,区别在于逻辑回归多了个Sigmoid函数,使样本映射到[0,1]之间的数值,从而来处理分类问题。另外逻辑回归是假设变量服从伯努利分布,线性回归假设变量服从高斯分布。逻辑回归输出的是离散型变量,用于分类,线性回归输出的是连续性的,用于预测。逻辑回归是用最大似然法去计算预测函数中的最优参数值,而线性回归是用最小二乘法去对自变量量关系进行拟合。 ### Q2 连续特征的离散化:在什么情况下将连续的特征离散化之后可以获得更好的效果?例如CTR预估中,特征大多是离散的,这样做的好处在哪里? 答:在工业界,很少直接将连续值作为逻辑回归模型的特征输入,而是将连续特征离散化为一系列0、1特征交给逻辑回归模型,这样做的优势有以下几点: 离散特征的增加和减少都很容易,易于模型的快速迭代,容易扩展; 离散化后的特征对异常数据有很强的鲁棒性:比如一个特征是年龄>30是1,否则0。如果特征没有离散化,一个异常数据“年龄300岁”会给模型造成很大的干扰; 逻辑回归属于广义线性模型,表达能力受限;单变量离散化为N个后,每个变量有单独的权重,相当于为模型引入了非线性,能够提升模型表达能力,加大拟合。具体来说,离散化后可以进行特征交叉,由`M+N`个变量变为`M*N`个变量; 特征离散化后,模型会更稳定,比如如果对用户年龄离散化,20-30作为一个区间,不会因为一个用户年龄长了一岁就变成一个完全不同的人。当然处于区间相邻处的样本会刚好相反,所以怎么划分区间是门学问。 ### Q3 逻辑回归在训练的过程当中,如果有很多的特征高度相关,或者说有一个特征重复了100遍,会造成怎样的影响? 先说结论,如果在损失函数最终收敛的情况下,其实就算有很多特征高度相关也不会影响分类器的效果。可以认为这100个特征和原来那一个特征扮演的效果一样,只是可能中间很多特征的值正负相消了。 为什么我们还是会在训练的过程当中将高度相关的特征去掉? 去掉高度相关的特征会让模型的可解释性更好 可以大大提高训练的速度。如果模型当中有很多特征高度相关的话,就算损失函数本身收敛了,但实际上参数是没有收敛的,这样会拉低训练的速度。其次是特征多了,本身就会增大训练的时间。 ## 2. SVM ### Q1 SVM 原理 SVM 是一种二类分类模型。它的基本模型是在特征空间中寻找间隔最大化的分离超平面的线性分类器。 当训练样本线性可分时,通过硬间隔最大化,学习一个线性分类器,即线性可分支持向量机; 当训练数据近似线性可分时,引入松弛变量,通过软间隔最大化,学习一个线性分类器,即线性支持向量机; 当训练数据线性不可分时,通过使用核技巧及软间隔最大化,学习非线性支持向量机。 以上各种情况下的数学推到应当掌握,硬间隔最大化(几何间隔)、学习的对偶问题、软间隔最大化(引入松弛变量)、非线性支持向量机(核技巧)。 ### Q2 SVM 为什么采用间隔最大化(与感知机区别) 当训练数据线性可分时,存在无穷个分离超平面可以将两类数据正确分开。感知机利用误分类最小策略,求得分离超平面,不过此时的解有无穷多个。线性可分支持向量机利用间隔最大化求得最优分离超平面,这时,解是唯一的。另一方面,此时的分隔超平面所产生的分类结果是最鲁棒的,对未知实例的泛化能力最强。可以借此机会阐述一下几何间隔以及函数间隔的关系。 ### Q3 为什么要将求解 SVM 的原始问题转换为其对偶问题 一是对偶问题往往更易求解,当我们寻找约束存在时的最优点的时候,约束的存在虽然减小了需要搜寻的范围,但是却使问题变得更加复杂。为了使问题变得易于处理,我们的方法是把目标函数和约束全部融入一个新的函数,即拉格朗日函数,再通过这个函数来寻找最优点。二是可以自然引入核函数,进而推广到非线性分类问题。 ### Q4 为什么 SVM 要引入核函数 <img src="https://pic2.zhimg.com/80/v2-f7925eb608413733723b3480ab043611_720w.jpg"/> 当样本在原始空间线性不可分时,可将样本从原始空间映射到一个更高维的特征空间,使得样本在这个特征空间内线性可分。而引入这样的映射后,所要求解的对偶问题的求解中,无需求解真正的映射函数,而只需要知道其核函数。核函数的定义:K(x,y)=<ϕ(x),ϕ(y)>,即在特征空间的内积等于它们在原始样本空间中通过核函数 K 计算的结果。一方面数据变成了高维空间中线性可分的数据,另一方面不需要求解具体的映射函数,只需要给定具体的核函数即可,这样使得求解的难度大大降低。 ### Q5 为什么SVM对缺失数据敏感 这里说的缺失数据是指缺失某些特征数据,向量数据不完整。SVM 没有处理缺失值的策略。而 SVM 希望样本在特征空间中线性可分,所以特征空间的好坏对SVM的性能很重要。缺失特征数据将影响训练结果的好坏。 ### Q6 SVM 核函数之间的区别 一般选择线性核和高斯核,也就是线性核与 RBF 核。 线性核:主要用于线性可分的情形,参数少,速度快,对于一般数据,分类效果已经很理想了。 RBF 核:主要用于线性不可分的情形,参数多,分类结果非常依赖于参数。有很多人是通过训练数据的交叉验证来寻找合适的参数,不过这个过程比较耗时。 如果 Feature 的数量很大,跟样本数量差不多,这时候选用线性核的 SVM。 如果 Feature 的数量比较小,样本数量一般,不算大也不算小,选用高斯核的 SVM。 以上是几个问题在面试中遇到 SVM 算法时,几乎是必问的问题,另外,大家一定要做到自己可以推导集合间隔、函数间隔以及对偶函数,并且理解对偶函数的引入对计算带来的优势。 ### Q7 SVM的优缺点 + 优点: 由于SVM是一个凸优化问题,所以求得的解一定是全局最优而不是局部最优。 不仅适用于线性线性问题还适用于非线性问题(用核技巧)。 拥有高维样本空间的数据也能用SVM,这是因为数据集的复杂度只取决于支持向量而不是数据集的维度,这在某种意义上避免了“维数灾难”。 理论基础比较完善(例如神经网络就更像一个黑盒子)。 + 缺点: 二次规划问题求解将涉及m阶矩阵的计算(m为样本的个数), 因此SVM不适用于超大数据集。(SMO算法可以缓解这个问题) 只适用于二分类问题。(SVM的推广SVR也适用于回归问题;可以通过多个SVM的组合来解决多分类问题)
Java
UTF-8
817
3.34375
3
[]
no_license
package classworks.march2018.mar062018.homework.task2; public class DepositAccountRunner { public static void main(String[] args) { DepositAccount.setYearInterest(4); DepositAccount saver1 = new DepositAccount(2000); DepositAccount saver2 = new DepositAccount(3000); printInformation(saver1, saver2); DepositAccount.setYearInterest(5); printInformation(saver1, saver2); } private static void printInformation(DepositAccount saver1, DepositAccount saver2) { System.out.println(String.format("Year interest %.2f, Month interest %.4f", DepositAccount.getYearInterest(), DepositAccount.getMonthInterest())); System.out.println(saver1.getAccountInformation()); System.out.println(saver2.getAccountInformation()); } }
JavaScript
UTF-8
1,115
3.046875
3
[]
no_license
var count = 0; function AddItemToList() { var Item = document.getElementById('input').value; var CreateList = document.createElement("li"); var checkBox = document.createElement("input"); var deleteBtn = document.createElement("input"); var listId = "list" + count; var Task = document.createTextNode(Item); if (Item == "") { alert("Must Enter something .."); } else { checkBox.type = "checkbox"; deleteBtn.type = "button"; deleteBtn.id = "btn" + count; deleteBtn.name = listId; deleteBtn.value = "Delete"; document.getElementById("list").appendChild(CreateList); CreateList.id = listId; CreateList.appendChild(checkBox); CreateList.appendChild(Task); CreateList.appendChild(deleteBtn); input.value = null; } document.getElementById("btn" + count).addEventListener("click", Deletelistitem()); function Deletelistitem() { var ul = document.getElementById("list"); var li = ul.children; }; count++; }
Markdown
UTF-8
395
3.40625
3
[ "MIT" ]
permissive
# repeat Repeats the given element by the given count of times. ## Type signature <!-- prettier-ignore-start --> ```typescript (count: number) => (value: any) => any[] ``` <!-- prettier-ignore-end --> ## Examples <!-- prettier-ignore-start --> ```javascript repeat(3)("test"); // ⇒ ["test", "test", "test"] ``` <!-- prettier-ignore-end --> ## Questions - How to repeat a value N times?
C#
UTF-8
3,088
3.1875
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; //CS8ex - Juan Marquez- CIS162AD /* This project uses classes to calculate gross and net pay. Shared (static) variables are used in class to accumulate totals. */ namespace CS8ex { public partial class frmCS8ex : Form { public frmCS8ex() { InitializeComponent(); } private void btnCalculate_Click(object sender, EventArgs e) { try { //Create an instance of clsEmployee //Assign values in textboxes to class variables using the overloaded constructor clsEmployee cobjEmployee = new clsEmployee (txtName.Text, int.Parse(txtHours.Text), decimal.Parse(txtRate.Text)); //Test the calculations methods cobjEmployee.calcGross(); cobjEmployee.setUnionDues(); cobjEmployee.calcNetPay(); //Update the totals in shared variables. cobjEmployee.accumulateTotals(); //Test the Get property methods lblGross.Text = cobjEmployee.Gross.ToString("C"); lblUnionDues.Text = cobjEmployee.UnionDues.ToString("C"); lblNetPay.Text = cobjEmployee.NetPay.ToString("C"); //Shared properties are accessed using class name //Test the Get Property methods of ReadOnly Shared properties lblTotalGross.Text = clsEmployee.TotalGross.ToString("C"); lblTotalNetPay.Text = clsEmployee.TotalNetPay.ToString("C"); lblTotalCount.Text = clsEmployee.TotalCount.ToString("N0"); } catch (Exception ex) { MessageBox.Show("Error :" + ex.Message + "\n" + ex.StackTrace, "Try/Catch - Unexpected Error", MessageBoxButtons.OK, MessageBoxIcon.Error); }//end try }//end of btnCalculate private void btnClearForm_Click(object sender, EventArgs e) { //Use Clear or null string "" for TextBoxes, but //only use null string "" for Labels txtName.Clear(); txtHours.Clear(); //Clear txtRate.Clear(); lblGross.Text = ""; //null string lblUnionDues.Text = ""; lblNetPay.Text = ""; lblTotalGross.Text = ""; lblTotalNetPay.Text = ""; lblTotalCount.Text = ""; chkUnionMember.Checked = false; //Reset Totals in class shared variables clsEmployee.resetTotals(); txtName.Focus(); }//end of btnClearForm private void btnExit_Click(object sender, EventArgs e) { this.Close(); } }//end of class }//end of namespace
Python
UTF-8
426
3.109375
3
[]
no_license
class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ start = max_length = 0 hash = {} for i, v in enumerate(s): if v in hash and start <= hash[v]: start = hash[v] + 1 else: max_length = max(max_length, i - start + 1) hash[v] = i return max_length
C++
UTF-8
5,503
2.890625
3
[]
no_license
/* * File: DHT11.cpp * Author: natalia * * Created on 4 de Dezembro de 2019, 09:05 */ #include "DHT11.h" #include "GPIO.h" //----- Auxiliary data ----------// enum DHT_Status_t __DHT_STATUS; #define __DHT_Temperature_Min 0 #define __DHT_Temperature_Max 50 #define __DHT_Humidity_Min 20 #define __DHT_Humidity_Max 90 #define __DHT_Delay_Read 50 #define Low 0 #define High !Low //-------------------------------// //----- Prototypes ----------------------------// static double ExtractTemperature(uint8_t Data3, uint8_t Data4); static double ExtractHumidity(uint8_t Data1, uint8_t Data2); //---------------------------------------------// //----- Functions -----------------------------// //Setup sensor. void DHT_Setup() { _delay_ms(__DHT_Delay_Setup); __DHT_STATUS = DHT_Ok; } //Get sensor status. enum DHT_Status_t DHT_GetStatus() { return (__DHT_STATUS); } //Read raw buffer from sensor. enum DHT_Status_t DHT_ReadRaw(uint8_t Data[4]) { uint8_t buffer[5] = {0, 0, 0, 0, 0}; uint8_t retries, i; int8_t j; __DHT_STATUS = DHT_Ok; retries = i = j = 0; GPIO PinMode(DHT_Pin, GPIO::OUTPUT); //DHT_PIN = Output //----- Step 1 - Start communication ----- if (__DHT_STATUS == DHT_Ok) { //Request data PinMode.set(Low); //DHT_PIN = 0 _delay_ms(__DHT_Delay_Read); // //Setup DHT_PIN as input with pull-up resistor so as to read data // GPIO DigitalWrite(DHT_Pin, High); //DHT_PIN = 1 (Pull-up resistor) // GPIO PinMode(DHT_Pin, GPIO::INPUT); //DHT_PIN = Input //Wait for response for 20-40us retries = 0; while (PinMode.get()) { _delay_us(2); retries += 2; if (retries > 60) { __DHT_STATUS = DHT_Error_Timeout; //Timeout error break; } } } //---------------------------------------- //----- Step 2 - Wait for response ----- if (__DHT_STATUS == DHT_Ok) { //Response sequence began //Wait for the first response to finish (low for ~80us) retries = 0; while (!(PinMode.get()) { _delay_us(2); retries += 2; if (retries > 100) { __DHT_STATUS = DHT_Error_Timeout; //Timeout error break; } } //Wait for the last response to finish (high for ~80us) retries = 0; while(PinMode.get()) { _delay_us(2); retries += 2; if (retries > 100) { __DHT_STATUS = DHT_Error_Timeout; //Timeout error break; } } } //-------------------------------------- //----- Step 3 - Data transmission ----- if (__DHT_STATUS == DHT_Ok) { //Reading 5 bytes, bit by bit for (i = 0 ; i < 5 ; i++) for (j = 7 ; j >= 0 ; j--) { //There is always a leading low level of 50 us retries = 0; while(!PinMode.get()) { _delay_us(2); retries += 2; if (retries > 70) { __DHT_STATUS = DHT_Error_Timeout; //Timeout error j = -1; //Break inner for-loop i = 5; //Break outer for-loop break; //Break while loop } } if (__DHT_STATUS == DHT_Ok) { //We read data bit || 26-28us means '0' || 70us means '1' _delay_us(35); //Wait for more than 28us if (PinMode.get()) //If HIGH BitSet(buffer[i], j); //bit = '1' retries = 0; while(PinMode.get()) { _delay_us(2); retries += 2; if (retries > 100) { __DHT_STATUS = DHT_Error_Timeout; //Timeout error break; } } } } } //-------------------------------------- //----- Step 4 - Check checksum and return data ----- if (__DHT_STATUS == DHT_Ok) { if (((uint8_t)(buffer[0] + buffer[1] + buffer[2] + buffer[3])) != buffer[4]) { __DHT_STATUS = DHT_Error_Checksum; //Checksum error } else { //Build returning array //data[0] = Humidity (int) //data[1] = Humidity (dec) //data[2] = Temperature (int) //data[3] = Temperature (dec) //data[4] = Checksum for (i = 0 ; i < 4 ; i++) Data[i] = buffer[i]; } } //--------------------------------------------------- return DHT_GetStatus(); } //Read temperature in Celsius. enum DHT_Status_t DHT_GetTemperature(double *Temperature) { double *waste = 0; return DHT_Read(Temperature, waste); } //Read humidity percentage. enum DHT_Status_t DHT_GetHumidity(double *Humidity) { double *waste = 0; return DHT_Read(waste, Humidity); } //Read temperature and humidity. enum DHT_Status_t DHT_Read(double *Temperature, double *Humidity) { uint8_t data[4] = { 0, 0, 0, 0 }; //Read data enum DHT_Status_t status = DHT_ReadRaw(data); //If read successfully if (status == DHT_Ok) { //Calculate values *Temperature = ExtractTemperature(data[2], data[3]); *Humidity = ExtractHumidity(data[0], data[1]); //Check values if ((*Temperature < __DHT_Temperature_Min) || (*Temperature > __DHT_Temperature_Max)) __DHT_STATUS = DHT_Error_Temperature; else if ((*Humidity < __DHT_Humidity_Min) || (*Humidity > __DHT_Humidity_Max)) __DHT_STATUS = DHT_Error_Humidity; } return DHT_GetStatus(); } //Convert temperature from Celsius to Fahrenheit. double DHT_CelsiusToFahrenheit(double Temperature) { return (Temperature * 1.8 + 32); } //Convert temperature from Celsius to Kelvin. double DHT_CelsiusToKelvin(double Temperature) { return (Temperature + 273.15); } //Convert temperature data to double temperature. static double ExtractTemperature(uint8_t Data2, uint8_t Data3) { double temp = 0.0; temp = Data2; return temp; } static double ExtractHumidity(uint8_t Data0, uint8_t Data1) { double hum = 0.0; hum = Data0; return hum; }
Java
UTF-8
381
2.34375
2
[]
no_license
package graphics.font; import org.eclipse.swt.widgets.Display; public class Bug271024_DeviceLoadFont { public static void main(String[] args) { Display display = new Display(); if(display.loadFont("garbage.ttf")) { System.out.println("Should not have got here!"); } else { System.out.println("OK, this graphics.font does not exist."); } display.dispose(); } }
C++
UTF-8
1,646
2.65625
3
[]
no_license
#include "BallCushionCollision.h" #include "Cushion.h" #include "R3.h" #include "SnooCommons.h" BallCushionCollision::BallCushionCollision( double t, BallPosition & _ball, Cushion & _cushion): Collision(t), ball(_ball), cushion(_cushion) { } void BallCushionCollision::apply(void) { #define CUSHION_LOSS 0.9 #define MU_BOUND (MU / 100.0) #define COLLISION_TIME 0.1 // normalna bandy R3 normal = cushion.calculateNormal(ball).unit(); // efektywna predkosc wzgledem bandy R3 veff = ball.v + ball.w.crossProd(normal) * BALL_RADIUS; // sila nacisku na bande R3 vn = ball.v.projected(normal); R3 fn = vn * BALL_M * (1.0 + CUSHION_LOSS) / COLLISION_TIME; // a - przyspieszenie wynikajace z sil tarcia R3 a = - (veff-veff.projected(normal)).unit() * MU_BOUND * fn.length(); // moment sily R3 M = (normal * BALL_RADIUS).crossProd(a * BALL_M); // przyspieszenie katowe R3 e = M / BALL_I; // zmiana predkosci R3 dv = a * COLLISION_TIME; R3 dw = e * COLLISION_TIME; R3 dw2 = dw + ball.w.projected(dw); // czy przyspieszenia wplynie na zwrot predkosci katowej if (dw2.dotProd(ball.w) < 0) { dw -= dw2; dv = dv.unit() * dw.length() * BALL_I / BALL_M / BALL_RADIUS; } #ifdef DEBUG std::cout << "dv " << dv << " >> dw " << dw << std::endl; #endif ball.v += dv; ball.w += dw; ball.v[2] = 0.0; ball.v -= ball.v.projected(normal) * 2; ball.v *= CUSHION_LOSS; ball.w *= CUSHION_LOSS; #ifdef DEBUG std::cout << "po V: " << ball.v << std::endl; std::cout << "po W: " << ball.w << std::endl; #endif }
C++
UTF-8
902
3.359375
3
[]
no_license
#include "binary_search_deluxe.hpp" int binary_search_deluxe::first_index_of(const std::vector<term> &a, const term &key, const term::Func &comparator) { int leftBound = -1; int rightBound = a.size(); while (leftBound + 1 != rightBound) { int middle = (leftBound + rightBound) / 2; if (!comparator(a[middle], key)) { rightBound = middle; } else { leftBound = middle; } } return rightBound; } int binary_search_deluxe::last_index_of(const std::vector<term> &a, const term &key, const term::Func &comparator) { int leftBound = -1; int rightBound = a.size(); while (leftBound + 1 != rightBound) { int middle = (leftBound + rightBound) / 2; if (comparator(key, a[middle])) { rightBound = middle; } else { leftBound = middle; } } return rightBound; }
Go
UTF-8
3,993
3.078125
3
[ "MIT" ]
permissive
package library import ( "reflect" "testing" ) func Test_replaceByKey(t *testing.T) { type args struct { msg *FluentMsg v string } msgOrig := &FluentMsg{ Message: map[string]interface{}{ "a": "aaaa", "b": "bbbb", "LA": "AAAA", "LB": "BBBB", "int": 123, "float": 1.21, "in": map[string]interface{}{ "ia": "iaaaa", "ib": "ibbbb", "iLA": "iAAAA", "iLB": "iBBBB", }, }, ID: 123, Tag: "test", } msgArg := &FluentMsg{ Message: map[string]interface{}{ "a": "aaaa", "b": "bbbb", "LA": "AAAA", "LB": "BBBB", "int": 123, "float": 1.21, "in": map[string]interface{}{ "ia": "iaaaa", "ib": "ibbbb", "iLA": "iAAAA", "iLB": "iBBBB", }, }, ID: 123, Tag: "test", } tests := []struct { name string args args want string }{ {"0", args{msgArg, "a"}, "a"}, {"1", args{msgArg, "%{a}"}, "aaaa"}, {"2", args{msgArg, "%{in}"}, "map[iLA:iAAAA iLB:iBBBB ia:iaaaa ib:ibbbb]"}, {"3", args{msgArg, "%{ii}"}, ""}, {"4", args{msgArg, "%{in.ia}"}, "iaaaa"}, {"5", args{msgArg, "%{in.iLB}"}, "iBBBB"}, {"6", args{msgArg, "%{in.ilB}"}, ""}, {"7", args{msgArg, "%{@upper:a}"}, "AAAA"}, {"8", args{msgArg, "%{@lower:LA}"}, "aaaa"}, {"9", args{msgArg, "%{@upper:in.ia}"}, "IAAAA"}, {"10", args{msgArg, "%{@lower:in.iLA}"}, "iaaaa"}, {"11", args{msgArg, "a%{a}"}, "aaaaa"}, {"12", args{msgArg, "a%{a}a"}, "aaaaaa"}, {"13", args{msgArg, "v%{a}v"}, "vaaaav"}, {"14", args{msgArg, "v%%{a}v"}, "v%aaaav"}, {"15", args{msgArg, "v%{{a}v"}, "v%{{a}v"}, {"16", args{msgArg, "v%{a}}v"}, "vaaaa}v"}, {"17", args{msgArg, "%{a}%{a}"}, "aaaaaaaa"}, {"18", args{msgArg, "%{a}%{b}%{a}"}, "aaaabbbbaaaa"}, {"19", args{msgArg, "%{int}"}, "123"}, {"20", args{msgArg, "%{float}"}, "1.21"}, {"21", args{msgArg, "%{@tag}"}, "test"}, {"22", args{msgArg, "%{@id}"}, "123"}, } for _, tt := range tests { if got := ReplaceStrByMsg(tt.args.msg, tt.args.v); got != tt.want { t.Fatalf("[%s] ReplaceStrByMsg() = %v, want %v", tt.name, got, tt.want) } } if !reflect.DeepEqual(msgOrig, msgArg) { t.Fatal("should not change msg in the arg") } } func TestGetValFromMap(t *testing.T) { type args struct { m interface{} key string } tests := []struct { name string args args want interface{} }{ {"0", args{map[string]string{"a": "b"}, "a"}, "b"}, {"1", args{map[string]string{"a": "b"}, "a."}, nil}, {"2", args{map[string]string{"a": "b"}, "a.b"}, nil}, {"3", args{map[string]string{"a": "b"}, "a."}, nil}, {"4", args{map[string]string{"a": "b"}, "b"}, nil}, {"5", args{map[string]string{"a": "b"}, ""}, nil}, {"6", args{map[string]string{"a": "b", "b": "a"}, "a"}, "b"}, {"7", args{map[string]string{"a": "b", "b": "a"}, "b"}, "a"}, {"8", args{map[string]string{"a": "b", "b": "a"}, "b.a"}, nil}, {"9", args{map[string]string{"a": "b", "b": "a"}, "b."}, nil}, {"10", args{map[string]string{"a": "b", "b": "a"}, "c"}, nil}, {"11", args{map[string]string{"a": "b", "b": "a"}, ""}, nil}, {"12", args{map[string]interface{}{"a": "b"}, "a"}, "b"}, {"13", args{map[string]interface{}{"a": "b"}, "b"}, nil}, {"14", args{map[string]interface{}{"a": "b"}, ""}, nil}, {"15", args{map[string]interface{}{"a": "b"}, "a.b"}, nil}, {"16", args{map[string]interface{}{"a": "b", "b": "a"}, "a"}, "b"}, {"17", args{map[string]interface{}{"a": "b", "b": "a"}, "b"}, "a"}, {"18", args{map[string]interface{}{"a": "b", "b": map[string]string{"a": "b"}}, "b"}, map[string]string{"a": "b"}}, {"19", args{map[string]interface{}{"a": "b", "b": map[string]string{"a": "b"}}, "b.a"}, "b"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := GetValFromMap(tt.args.m, tt.args.key); !reflect.DeepEqual(got, tt.want) { // if got := GetValFromMap(tt.args.m, tt.args.key); !interfaceStringEqual(got, tt.want) { t.Fatalf("GetValFromMap() = %v, want %v", got, tt.want) } }) } }
Swift
UTF-8
4,051
2.75
3
[ "Apache-2.0" ]
permissive
// // FilePersistentStorage.swift // DigiMeSDK // // Created on 23/02/2022. // Copyright © 2022 digi.me Limited. All rights reserved. // import Foundation public class FilePersistentStorage { private var location: FileManager.SearchPathDirectory = .documentDirectory public required init(with location: FileManager.SearchPathDirectory) { self.location = location } private func getURL() -> URL? { guard let url = FileManager.default.urls(for: location, in: .userDomainMask).first else { return nil } return url } public func store(data: Data, fileName: String) { guard Thread.isMainThread else { DispatchQueue.main.async { self.store(data: data, fileName: fileName) } return } guard !data.isEmpty, let url = getURL()?.appendingPathComponent(fileName, isDirectory: false) else { return } if dataPersist(for: fileName) { try? FileManager.default.removeItem(at: url) } FileManager.default.createFile(atPath: url.path, contents: data, attributes: nil) } public func store(file: File) { guard Thread.isMainThread else { DispatchQueue.main.async { self.store(file: file) } return } guard let url = getURL()?.appendingPathComponent(file.identifier, isDirectory: false) else { return } if dataPersist(for: file.identifier) { try? FileManager.default.removeItem(at: url) } if let newData = try? file.encoded(dateEncodingStrategy: .millisecondsSince1970, keyEncodingStrategy: .convertToSnakeCase), let jsonStr = String(data: newData, encoding: .utf8) { try? jsonStr.write(to: url, atomically: true, encoding: .utf8) } } public func store(object: Any, fileName: String, options: JSONSerialization.WritingOptions = []) { guard Thread.isMainThread else { DispatchQueue.main.async { self.store(object: object, fileName: fileName, options: options) } return } guard let url = getURL()?.appendingPathComponent(fileName, isDirectory: false) else { return } if dataPersist(for: fileName) { try? FileManager.default.removeItem(at: url) } if JSONSerialization.isValidJSONObject(object as Any), let newData = try? JSONSerialization.data(withJSONObject: object, options: options), let jsonStr = String(data: newData, encoding: .utf8) { try? jsonStr.write(to: url, atomically: true, encoding: .utf8) } } public func loadData(for fileName: String) -> Data? { guard let url = getURL()?.appendingPathComponent(fileName, isDirectory: false), let data = FileManager.default.contents(atPath: url.path) else { return nil } return data } public func reset(fileName: String) { guard Thread.isMainThread else { DispatchQueue.main.async { self.reset(fileName: fileName) } return } guard let url = getURL()?.appendingPathComponent(fileName, isDirectory: false) else { return } if FileManager.default.fileExists(atPath: url.path) { try? FileManager.default.removeItem(at: url) } } public func dataPersist(for fileName: String) -> Bool { guard let url = getURL()?.appendingPathComponent(fileName, isDirectory: false) else { return false } return FileManager.default.fileExists(atPath: url.path) } }
Java
UTF-8
4,882
2.609375
3
[]
no_license
package fr.ensimag.deca.tree; import fr.ensimag.deca.DecacCompiler; import fr.ensimag.deca.context.ContextualError; import fr.ensimag.deca.tools.IndentPrintStream; import fr.ensimag.ima.pseudocode.Line; import fr.ensimag.ima.pseudocode.Label; import fr.ensimag.ima.pseudocode.instructions.WSTR; import fr.ensimag.ima.pseudocode.instructions.WNL; import fr.ensimag.ima.pseudocode.instructions.TSTO; import fr.ensimag.ima.pseudocode.instructions.ERROR; import fr.ensimag.ima.pseudocode.instructions.ADDSP; import fr.ensimag.ima.pseudocode.instructions.HALT; import fr.ensimag.ima.pseudocode.instructions.BOV; import bytecode.BytegenError; import java.io.PrintStream; import org.apache.commons.lang.Validate; import org.apache.log4j.Logger; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; /** * Deca complete program (class definition plus main block) * * @author gl56 * @date 01/01/2017 */ public class Program extends AbstractProgram { private static final Logger LOG = Logger.getLogger(Program.class); public Program(ListDeclClass classes, AbstractMain main) { Validate.notNull(classes); Validate.notNull(main); this.classes = classes; this.main = main; } public ListDeclClass getClasses() { return classes; } public AbstractMain getMain() { return main; } private ListDeclClass classes; private AbstractMain main; @Override public void verifyProgram(DecacCompiler compiler) throws ContextualError { LOG.debug("verify program: start"); classes = getClasses(); main = getMain(); // PASS 1 classes.verifyListClass(compiler); // PASS 2 classes.verifyListClassMembers(compiler); // PASS 3 classes.verifyListClassBody(compiler); main.verifyMain(compiler); // LOG.debug("verify program: end"); } public void createLabel(DecacCompiler compiler, String nomError, String messageError) { if(!compiler.getCompilerOptions().getNoCheck()) { Label erreurLabel = new Label(nomError); compiler.addLabel(erreurLabel); compiler.addInstruction(new WSTR(messageError)); compiler.addInstruction(new WNL()); compiler.addInstruction(new ERROR()); } } @Override public void codeGenProgram(DecacCompiler compiler) { getClasses().codeGenListDeclClass(compiler); compiler.addComment("Main program"); main.codeGenMain(compiler); compiler.addInstruction(new HALT()); compiler.addComment("End main program"); compiler.addComment("Method codes of classes"); getClasses().codeGenListDeclClassMethods(compiler); compiler.addFirst(new Line(new ADDSP(compiler.getVariableGlobales()))); if(!compiler.getCompilerOptions().getNoCheck()) compiler.addFirst(new Line(new BOV(new Label("stack_overflow_error")))); compiler.addFirst(new Line(new TSTO(compiler.getVariableTemporaireMax() + compiler.getVariableGlobales()))); compiler.addComment("Messages d'erreurs"); createLabel(compiler, "overflow_error", "Error: Overflow during arithmetic operation"); createLabel(compiler, "stack_overflow_error", "Error: Stack Overflow"); createLabel(compiler, "dereferencement.null", "Error : dereferencement de null"); createLabel(compiler, "divide_by_zero", "Error : you divided by zero"); } @Override public void byteGenProgram(DecacCompiler compiler) throws BytegenError { // creates a MethodWriter for the (implicit) constructor MethodVisitor mw = compiler.getCW().visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null); // pushes the 'this' variable mw.visitVarInsn(Opcodes.ALOAD, 0); // invokes the super class constructor mw.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false); mw.visitInsn(Opcodes.RETURN); // Automatic setting for the stack size and local variables mw.visitMaxs(0, 0); mw.visitEnd(); if (!classes.isEmpty()){ classes.byteGenListDeclClass(compiler); //throw new BytegenError("Bytegen with Objects is not yet implemented", getLocation()); } main.byteGenMain(compiler); } @Override public void decompile(IndentPrintStream s) { getClasses().decompile(s); getMain().decompile(s); } @Override protected void iterChildren(TreeFunction f) { classes.iter(f); main.iter(f); } @Override protected void prettyPrintChildren(PrintStream s, String prefix) { classes.prettyPrint(s, prefix, false); main.prettyPrint(s, prefix, true); } }
Shell
UTF-8
2,518
4.21875
4
[ "Apache-2.0" ]
permissive
#!/bin/bash # # # Usage: Test execdir srcdir file1 ... filen # # Like regression testing, except we display the CPU time. # if [ $# -lt 1 ]; then echo "Usage: $0 <exec> test1 test2 ..." echo "Runs executable on each test file and compares execution times." exit fi btotal="0" utotal="0" current=`pwd` prefix=`mktemp $current/prefix.XXXXXXXX` suffix=`mktemp $current/suffix.XXXXXXXX` # # Helper function: # Runs the input file passed as an argument, # and displays the time required to run. # TimeOne() { current=`pwd` d=`dirname $1` b=`basename $1` cd $SRCDIR/$d printf " %-30s " $1 if [ -f $TESTDIR/$b.time ]; then read btime < $TESTDIR/$b.time if [ $btime ]; then printf "(%6d ms ) " $btime btotal=$[ $btotal + $btime ] else btime=" " printf "( ????? ms ) " fi else btime=" " printf "( ) " fi utime=`$current/$SMART $prefix $b $suffix` if [ ! -f $TESTDIR/$b.time ]; then echo $utime > $TESTDIR/$b.time fi printf " %6d ms " $utime utotal=$[ $utotal + $utime ] # Compare times and give alerts for changes if [ "$btime" != " " ]; then delta=$[ $utime - $btime ] dten=$[ $delta * 10 ] dnten=$[ $delta * -10 ] if [ "$dten" -gt 10 -a "$dten" -gt "$btime" ]; then printf ">" fi if [ "$dnten" -gt 10 -a "$dnten" -gt "$btime" ]; then printf "<" fi fi printf "\n" cd $current } # # determine executable paths # SMART=$1/smart ICP=$1/icp shift # # determine source path # SRCDIR=$1 shift # # determine test path # TESTDIR=`pwd` if [ ! -f $SMART ]; then printf "Smart executable not found: $SMART\n" exit 1 fi cat <<EOF > $prefix cond(error_file("/dev/null"),null,exit(1)); cond(warning_file("/dev/null"),null,exit(1)); cond(output_file("/dev/null"),null,exit(1)); start_timer(0); EOF cat <<EOF > $suffix compute(output_file(null)); print(int(1000.0*stop_timer(0)), "\n"); EOF # Run the tests for file in $@ do # only benchmarks for smart at the moment... ext=`echo $file | awk -F. '{print $NF}'` if [ "$ext" != "sm" ]; then continue fi fullfile=$SRCDIR/$file if [ -f "$fullfile.out" ]; then if [ -f "$file.diffs" ]; then continue fi if [ -f "$file.test" ]; then continue fi TimeOne $file fi done printf " %-30s ============ =========\n" "=========================" printf " %-30s " "Total: " printf "(%6d ms ) " $btotal printf " %6d ms\n" $utotal # Cleanup rm -f $prefix $suffix echo Done!
Python
UTF-8
6,488
2.84375
3
[]
no_license
from helper import build_corpus, process import glob, nltk, os import matplotlib.pyplot as plt # Gather corpora base_dir = '/Users/jtim/Dropbox/Academic/sources/corpora/' bahaullah = build_corpus('{}bahai-works/data/'.format(base_dir), ['bahaullah'], ['ar']) abdulbaha = build_corpus('{}bahai-works/data/'.format(base_dir), ['abdulbaha'], ['ar']) bab = build_corpus('{}bahai-works/data/'.format(base_dir), ['bab'], ['ar']) murtada_ansari = glob.glob('/Users/jtim/Dropbox/Academic/sources/corpora/open-arabic-1300AH/data/1281MurtadaAnsari/*/arc/*.txt') bahaullah_baghdad = ['bahaullah-anbka-15-ar.txt', # سورة الذكر 'bahaullah-aqa2-67-ar.txt', # جواهر الاسرار 'bahaullah-aqa2-93-ar.txt', # سورة القدير 'bahaullah-aqa2-76-ar.txt', # سورة الله 'bahaullah-aqa2-101-ar.txt', # لوح الحورية 'bahaullah-km-1-ar.txt', # الكلمات المكنونة العربية 'bahaullah-st-010-1-ar.txt', # الحروفات العاليات 'bahaullah-st-029-ar.txt', # (لوح آية النور (تفسير الحروفات المقطعة 'bahaullah-st-037-ar.txt', # لوح الفتنة 'bahaullah-st-041-ar.txt', # لوح الحق 'bahaullah-st-052-ar.txt', # لوح كل الطعام 'bahaullah-st-087-ar.txt', # لوح مدينة الرضا 'bahaullah-st-088-ar.txt', # لوح مدينة التوحيد 'bahaullah-st-100-ar.txt', # لوح سبحان ربي الاعلى 'bahaullah-st-133-ar.txt', # سورة النصح 'bahaullah-st-138-ar.txt', # (سورة الصبر (لوح ايوب 'bahaullah-st-144-ar.txt' # تفسير هو ] # Update items in bahaullah_baghdad to full file path for idx, item in enumerate(bahaullah_baghdad): item = "{}bahai-works/data/bahaullah/text/{}".format(base_dir, item) bahaullah_baghdad[idx] = item # Map corpora names to corpora corpora = {"Bahá'u'llah": bahaullah, "Bahá'u'llah's Arabic Baghdad Writings": bahaullah_baghdad, "`Abdu'l-Bahá": abdulbaha, "the Báb": bab, "al-Shaykh Murtaḍá al-Ánsárí": murtada_ansari} # Read files into string, remove junk, remove diacritics, normalize characters def read_files_into_string(filenames): strings = [] for filename in filenames: with open(filename) as f: strings.append(process(f.read())) return '\n'.join(strings) # Compare a list of candidate authors to a relative corpus using the chi-squared method def chi_squared(relative_corpus, authors = []): by_author = {} for key, files in corpora.items(): by_author[key] = read_files_into_string(files) # Transform the authors' corpora into lists of word tokens by_author_tokens = {} by_author_length_distributions = {} for author in by_author: tokens = by_author[author].split() # Filter out punctuation by_author_tokens[author] = ([process(token) for token in tokens if any(c.isalpha() for c in token)]) for author in authors: # First, build a joint corpus and identify the 500 most frequent words in it joint_corpus = (by_author_tokens[author] + by_author_tokens[relative_corpus]) joint_freq_dist = nltk.FreqDist(joint_corpus) most_common = list(joint_freq_dist.most_common(500)) # What proportion of the joint corpus is made up of the candidate # author's tokens? author_share = (len(by_author_tokens[author]) / len(joint_corpus)) # Now, let's look at the 500 most common words in the candidate # author's corpus and compare the number of times they can be observed # to what would be expected if the author's writings and the relative # corpus were both random samples from the same distribution. chisquared = 0 for word, joint_count in most_common: # How often do we really see this common word? author_count = by_author_tokens[author].count(word) relative_count = by_author_tokens[relative_corpus].count(word) # How often should we see it? expected_author_count = joint_count * author_share expected_joint_count = joint_count * (1-author_share) # Add the word's contribution to the chi-squared statistic chisquared += ((author_count-expected_author_count) * (author_count-expected_author_count) / expected_author_count) chisquared += ((relative_count-expected_joint_count) * (relative_count-expected_joint_count) / expected_joint_count) print("The Chi-squared statistic for", author, "compared to", relative_corpus, "is", chisquared) def main(): directory = '/Users/jtim/Dropbox/Academic/research/dissertation/research/output/' if not os.path.exists(directory): os.makedirs(directory) ### Chi-squared tests ### # Test 1: Compare the distance of Bahá'u'lláh's full corpus to His Baghdad writings # and the distance of Shaykh Murtaḍá's writings to Bahá'u'lláh's Baghdad writings. authors_one = ["Bahá'u'llah", "al-Shaykh Murtaḍá al-Ánsárí"] chi_squared("Bahá'u'llah's Arabic Baghdad Writings", authors_one) # Test 2: Now consider the relative distance between the writings of `Abdu'l-Bahá`, # the Báb, and Shaykh Murtaḍá compared to those of Bahá'u'lláh. authors_two = ["`Abdu'l-Bahá", "al-Shaykh Murtaḍá al-Ánsárí", "the Báb"] chi_squared("Bahá'u'llah", authors_two) # Test 3: Now consider the relative distance between the writings of `Abdu'l-Bahá`, # and Shaykh Murtaḍá compared to those of the Báb. authors_three = ["`Abdu'l-Bahá", "al-Shaykh Murtaḍá al-Ánsárí"] chi_squared("the Báb", authors_three) # Test 4: Finally, consider the relative distance between the writings of `Abdu'l-Bahá`, # and those of Shaykh Murtaḍá. authors_four = ["`Abdu'l-Bahá"] chi_squared("al-Shaykh Murtaḍá al-Ánsárí", authors_four) if __name__ == "__main__": main()
Python
UTF-8
762
3.75
4
[]
no_license
name= input("Enter a name: ") place= input("Enter a place: ") adjective1= input("Enter an adjective: ") food1= input("Enter a food: ") food2= input("Enter another food: ") verb= input ("Enter a verv: ") adverb= input("Enter an adverb: ") noun= input("Enter a noun: ") adjective2= input("Enter an adjective: ") print ("Let's play Silly Sentences!") print(name + "was planning a dream vacation to " + place + ".") print(name + "was especially looking forward to trying the local cuisine, including " + adjective1 + food1 + "and" + food2 + ".") print(name + "will have to practice the language " + "to make it easier to " + verb + "with people.") print(name + "has a long list of sights to see, including the " + noun + "museum and the " + adjective2 + "park.")
Java
UTF-8
23,062
1.523438
2
[]
no_license
package com.c323proj10.jillpena; import com.c323proj10.jillpena.R; import android.Manifest; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Build; import android.support.annotation.NonNull; import android.support.constraint.ConstraintLayout; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v4.view.GestureDetectorCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.telephony.SmsManager; import android.util.Log; import android.view.GestureDetector; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.ExecutionException; public class MainActivity extends AppCompatActivity { private final String apiKey= "7bfab2d91646137766a69251ab55afb1"; private final int MY_PERMISSIONS_REQUEST = 1; LocationManager mLocationManager; LocationListener mLocationListener; ProgressDialog progressDialog; String jsonData = ""; TextView tempTextView; TextView weatherDetailsTextView; TextView dateTextView; ImageView currentWeather; private ArrayList<Weather> weatherList; RecyclerView rv; Location currLocation; Boolean switchUnits = false; RVAdapter adapter; private GestureDetectorCompat gestureDetectorCompat = null; ArrayList<Integer> imageList = new ArrayList<>();; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tempTextView = findViewById(R.id.textViewTemp); weatherDetailsTextView = findViewById(R.id.TextViewWeatherDetails); dateTextView = findViewById(R.id.textViewDate); weatherList = new ArrayList<>(); currentWeather = findViewById(R.id.imageView); imageList.clear(); imageList.add(0, R.mipmap.clear_day_round); imageList.add(1, R.mipmap.cloud_day_round); imageList.add(2, R.mipmap.rain_day_round); imageList.add(3, R.mipmap.snow_day_round); FloatingActionButton fab = findViewById(R.id.floatingActionButton); MyGestureDetector gestureDetector = new MyGestureDetector(); gestureDetector.setActivity(this); gestureDetectorCompat = new GestureDetectorCompat(this, gestureDetector); // ConstraintLayout constraintLayout = findViewById(R.layout.myLayoutMain); requestLocationPermission(); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { switchUnits = !switchUnits; getWeatherFromLocation(); if (switchUnits) { Toast.makeText(getApplicationContext(), "Units changed to imperial", Toast.LENGTH_SHORT).show(); } else{ Toast.makeText(getApplicationContext(), "Units changed to metric", Toast.LENGTH_SHORT).show(); } } }); } @Override public boolean onTouchEvent(MotionEvent event) { gestureDetectorCompat.onTouchEvent(event); return true; } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == MY_PERMISSIONS_REQUEST){ requestLocationPermission(); } } public void requestLocationPermission() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST); } else { ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST); } } else { try { Toast.makeText(this, "Getting Location...", Toast.LENGTH_LONG).show(); mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); currLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); setLocationListener(); mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000 * 60 * 60 * 3, 10, mLocationListener); Toast.makeText(this, "Location Found.", Toast.LENGTH_LONG).show(); getWeatherFromLocation(); }catch(Exception e){ e.printStackTrace(); Toast.makeText(this, "Could Not Get Location.", Toast.LENGTH_LONG).show(); } } } else { try { Toast.makeText(this, "Getting Location...", Toast.LENGTH_LONG).show(); mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); currLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); setLocationListener(); mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000 * 60 * 60 * 3, 10, mLocationListener); Toast.makeText(this, "Location Found.", Toast.LENGTH_LONG).show(); getWeatherFromLocation(); }catch (Exception e){ e.printStackTrace(); Toast.makeText(this, "Could Not Get Location.", Toast.LENGTH_LONG).show(); } } } public void setLocationListener(){ mLocationListener = new LocationListener() { public void onLocationChanged(Location location) { Log.i("WEATHER", "New Location Found."); currLocation = location; getWeatherFromLocation(); } public void onStatusChanged(String provider, int status, Bundle extras) {} public void onProviderEnabled(String provider) {} public void onProviderDisabled(String provider) {} }; } public void getWeatherFromLocation(){ String apiCall = ""; if (switchUnits) { apiCall = "https://api.openweathermap.org/data/2.5/forecast?lat=" + currLocation.getLatitude() + "&lon=" + currLocation.getLongitude() + "&units=metric" + "&appid=" + apiKey; } else{ apiCall = "https://api.openweathermap.org/data/2.5/forecast?lat=" + currLocation.getLatitude() + "&lon=" + currLocation.getLongitude() + "&units=imperial" + "&appid=" + apiKey; } Log.i("WEATHER", "api call: " + apiCall); Log.i("WEATHER", "current location: " + currLocation.getLatitude() + ", " + currLocation.getLongitude()); getWebResponse(apiCall); parseJSONData(); initalizeList(); } private void initalizeList() { rv = findViewById(R.id.recycler_view); rv.setHasFixedSize(true); LinearLayoutManager llm = new LinearLayoutManager(this); llm.setOrientation(LinearLayoutManager.VERTICAL); rv.setLayoutManager(llm); adapter = new RVAdapter(weatherList); rv.setAdapter(adapter); } private void getWebResponse(String stringURL) { progressDialog = ProgressDialog.show(this, "Weather App", "Connecting, Please wait ...", true, true); ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { try { jsonData = new DownloadWebpageTask().execute(stringURL).get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } else { Toast.makeText(this, "No network connection available!", Toast.LENGTH_SHORT).show(); } } public void parseJSONData() { if (!jsonData.isEmpty()){ weatherList.clear(); try { JSONObject jsonRootObject = new JSONObject(jsonData); JSONArray jsonArrayList = jsonRootObject.getJSONArray("list"); JSONObject jsonObject0 = jsonArrayList.getJSONObject(0); JSONObject mainObject0 = jsonObject0.getJSONObject("main"); String currTemp = mainObject0.get("temp").toString(); JSONArray WeatherArray0 = jsonObject0.getJSONArray("weather"); JSONObject WeatherObject0 = WeatherArray0.getJSONObject(0); String description0 = WeatherObject0.get("description").toString().toUpperCase(); String date0 = jsonObject0.get("dt_txt").toString(); Log.i("WEATHER", "current weather data: " + "temp: " + currTemp + ", description: " + description0 + ", date: " + date0); //Toast.makeText(this, "About to set textViews", Toast.LENGTH_SHORT).show(); if (switchUnits) { tempTextView.setText(currTemp + " °C"); } else{ tempTextView.setText(currTemp + " °F"); } if (description0.toLowerCase().contains("rain")){ currentWeather.setImageResource(imageList.get(2)); Log.i("WEATHER", "image changed to rain"); } else if(description0.toLowerCase().contains("cloud")){ currentWeather.setImageResource(imageList.get(1)); Log.i("WEATHER", "image changed to clouds"); } else if (description0.toLowerCase().contains("snow")){ currentWeather.setImageResource(imageList.get(3)); Log.i("WEATHER", "image changed to snow"); }else if (description0.toLowerCase().contains("clear")){ currentWeather.setImageResource(imageList.get(0)); Log.i("WEATHER", "image changed to clear"); } weatherDetailsTextView.setText(description0); SimpleDateFormat parser2 = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss"); //Date date0Date = parser2.parse(date0); String[] date0Array = date0.split(" "); Date newDate = new Date(); String newDate0 = parser2.format(newDate); dateTextView.setText(newDate0); for(int i =0; i<jsonArrayList.length(); i++){ JSONObject jsonObject = jsonArrayList.getJSONObject(i); JSONObject mainObject = jsonObject.getJSONObject("main"); String tempNow = mainObject.get("temp").toString(); JSONArray WeatherArray = jsonObject0.getJSONArray("weather"); JSONObject WeatherObject = WeatherArray.getJSONObject(0); String description = WeatherObject.get("description").toString().toUpperCase(); String date = jsonObject.get("dt_txt").toString(); // Date dateDate = parser2.parse(date); String[] dateArray = date.split(" "); if (date.contains("12:00:00") /*&& !date0Array[0].equals(dateArray[0])*/) { Log.i("WEATHER", "data: " + "temp: " + tempNow + ", description: " + description + ", date: " + date); String tempWithUnits = tempNow; if (switchUnits) { tempWithUnits = tempNow.concat(" °C"); } else { tempWithUnits = tempNow.concat(" °F"); } weatherList.add(new Weather(tempWithUnits, date, description)); } } } catch (JSONException e) { e.printStackTrace(); Toast.makeText(this, "Could not parse JSON DATA: " + e.getMessage(), Toast.LENGTH_SHORT).show(); } } else{ Toast.makeText(this, "jsondata is empty", Toast.LENGTH_SHORT).show(); } } public class RVAdapter extends RecyclerView.Adapter<RVAdapter.MyViewHolder> { public class MyViewHolder extends RecyclerView.ViewHolder { public TextView weatherTextView; public MyViewHolder(View view) { super(view); weatherTextView = view.findViewById(R.id.textViewWeather); } } public RVAdapter(ArrayList<Weather> list) { weatherList = list; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.weather_item_layout,parent, false); return new MyViewHolder(v); } @Override public void onBindViewHolder(MyViewHolder holder, int position) { Weather curr = weatherList.get(position); holder.weatherTextView.setText(curr.getTemp() + " " + curr.getDetails() + " " + curr.getDate()); } @Override public int getItemCount() { return weatherList.size(); } } private class DownloadWebpageTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... urls) { jsonData = downloadFromURL(urls[0]); return jsonData; } private String downloadFromURL(String url) { InputStream is = null; StringBuffer result = new StringBuffer(); URL myUrl = null; try { myUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) myUrl.openConnection(); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.setRequestMethod("GET"); //not needed any more , GET is default conn.connect(); int response = conn.getResponseCode(); Log.i("WEATHER", "The response is: "+response); is = conn.getInputStream(); progressDialog.dismiss(); BufferedReader reader = new BufferedReader((new InputStreamReader(is, "UTF-8"))); String line = ""; while((line = reader.readLine()) != null){ result.append(line); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (ProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Log.i("WEATHER", "The result is: "+ result.toString()); return result.toString(); } @Override protected void onPostExecute(String result) { super.onPostExecute(result); Log.i("WEATHER", "The result is: "+result); } } private class MyGestureDetector extends SimpleOnGestureListener { private MainActivity activity = null; private int MIN_SWIPE_DISTANCE_X = 100; private int MAX_SWIPE_DISTANCE_X = 1000; public MainActivity getActivity() { return activity; } public void setActivity(MainActivity activity) { this.activity = activity; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { float deltaX = e1.getX() - e2.getX(); float deltaXAbs = Math.abs(deltaX); String currentDate = dateTextView.getText().toString(); SimpleDateFormat parser = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss"); Date current = null; try { current = parser.parse(currentDate); } catch (ParseException e) { e.printStackTrace(); } int size = weatherList.size(); int i = size-1; int j = 0; if((deltaXAbs >= MIN_SWIPE_DISTANCE_X) && (deltaXAbs <= MAX_SWIPE_DISTANCE_X)) { if(deltaX > 0) { //Toast.makeText(getActivity(), "Swipe to left", Toast.LENGTH_SHORT).show(); while (j < size){ Weather w = weatherList.get(j); Date newDate = null; try { newDate = parser.parse(w.getDate()); if (newDate.after(current)){ tempTextView.setText(w.getTemp()); dateTextView.setText(w.getDate()); if (w.getDetails().toLowerCase().contains("rain")){ currentWeather.setImageResource(imageList.get(2)); Log.i("WEATHER", "image changed to rain"); } else if(w.getDetails().toLowerCase().contains("cloud")){ currentWeather.setImageResource(imageList.get(1)); Log.i("WEATHER", "image changed to clouds"); } else if (w.getDetails().toLowerCase().contains("snow")){ currentWeather.setImageResource(imageList.get(3)); Log.i("WEATHER", "image changed to snow"); }else if (w.getDetails().toLowerCase().contains("clear")){ currentWeather.setImageResource(imageList.get(0)); Log.i("WEATHER", "image changed to clear"); } weatherDetailsTextView.setText(w.getDetails()); break; } } catch (ParseException e) { e.printStackTrace(); break; } j++; } }else { //Toast.makeText(getActivity(), "Swipe to right", Toast.LENGTH_SHORT).show(); while (i > 0){ Weather w = weatherList.get(i); Date newDate = null; try { newDate = parser.parse(w.getDate()); if (newDate.before(current)){ tempTextView.setText(w.getTemp()); dateTextView.setText(w.getDate()); if (w.getDetails().toLowerCase().contains("rain")){ currentWeather.setImageResource(imageList.get(2)); Log.i("WEATHER", "image changed to rain"); } else if(w.getDetails().toLowerCase().contains("cloud")){ currentWeather.setImageResource(imageList.get(1)); Log.i("WEATHER", "image changed to clouds"); } else if (w.getDetails().toLowerCase().contains("snow")){ currentWeather.setImageResource(imageList.get(3)); Log.i("WEATHER", "image changed to snow"); }else if (w.getDetails().toLowerCase().contains("clear")){ currentWeather.setImageResource(imageList.get(0)); Log.i("WEATHER", "image changed to clear"); } weatherDetailsTextView.setText(w.getDetails()); break; } } catch (ParseException e) { e.printStackTrace(); break; } i--; } } } return true; } } }
Java
UTF-8
3,116
2.171875
2
[]
no_license
package com.notepoint.stackoverflowmvc.screens.questionDetails; /* Created by Suman on 5/13/2020. */ import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView; import androidx.appcompat.widget.Toolbar; import com.notepoint.stackoverflowmvc.R; import com.notepoint.stackoverflowmvc.questions.QuestionDetails; import com.notepoint.stackoverflowmvc.screens.common.ViewMvcFactory; import com.notepoint.stackoverflowmvc.screens.common.toolbar.ToolbarViewMvc; import com.notepoint.stackoverflowmvc.screens.common.views.BaseObservableViewMvc; import com.notepoint.stackoverflowmvc.screens.common.views.BaseViewMvc; import com.notepoint.stackoverflowmvc.screens.common.views.ObservableViewMvc; public class QuestionDetailViewMvcImpl extends BaseObservableViewMvc<QuestionDetailViewMvc.Listener> implements QuestionDetailViewMvc { private TextView mTxtQuestionTitle; private TextView mTxtQuestionBody; private ProgressBar mProgress; private final ToolbarViewMvc mToolbarViewMvc; private final Toolbar mToolbar; public QuestionDetailViewMvcImpl(LayoutInflater layoutInflater, ViewGroup parent, ViewMvcFactory viewMvcFactory) { setRootView(layoutInflater.inflate(R.layout.activity_question_details, parent, false)); mTxtQuestionTitle = findViewById(R.id.question_header_text); mTxtQuestionBody = findViewById(R.id.question_body_text); mProgress = findViewById(R.id.progress_bar); /* For adding toolbar */ mToolbar = findViewById(R.id.toolbar); mToolbarViewMvc = viewMvcFactory.getToolBarViewMvc(mToolbar); initToolbar(); } private void initToolbar(){ mToolbarViewMvc.setToolbarTitle(getString(R.string.question_details_screen_title)); mToolbar.addView(mToolbarViewMvc.getRootView()); mToolbarViewMvc.enableUpButtonAndListen(new ToolbarViewMvc.NavigateUpClickListener() { @Override public void onNavigateUpClicked() { for (Listener listener: getmListener()){ listener.onNavigationUpClicked(); } } }); } @Override public void bindQuestionDetail(QuestionDetails questionDetails) { String questionTitle = questionDetails.getTitle(); String questionBody = questionDetails.getBody(); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) { mTxtQuestionTitle.setText(Html.fromHtml(questionTitle, Html.FROM_HTML_MODE_LEGACY)); mTxtQuestionBody.setText(Html.fromHtml(questionBody, Html.FROM_HTML_MODE_LEGACY)); } else { mTxtQuestionTitle.setText(Html.fromHtml(questionTitle)); mTxtQuestionBody.setText(Html.fromHtml(questionBody)); } } @Override public void hideProgressBar() { mProgress.setVisibility(View.GONE); } @Override public void showProgressBar() { mProgress.setVisibility(View.VISIBLE); } }
Java
UTF-8
3,212
2.296875
2
[]
no_license
package br.gov.deputados; import java.util.HashMap; import java.util.Map; import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.html.HtmlElement; import com.gargoylesoftware.htmlunit.html.HtmlPage; public class LerSiteTerraEleicoes2010 { public Map<String, String> mapEstados = new HashMap<String, String>(); { mapEstados.put("AC", "acre"); mapEstados.put("AL", "alagoas"); mapEstados.put("AP", "amapa"); mapEstados.put("AM", "amazonas"); mapEstados.put("BA", "bahia"); mapEstados.put("CE", "ceara"); mapEstados.put("DF", "distrito-federal"); mapEstados.put("ES", "espirito-santo"); mapEstados.put("GO", "goias"); mapEstados.put("MA", "maranhao"); mapEstados.put("MT", "mato-grosso"); mapEstados.put("MS", "mato-grosso-do-sul"); mapEstados.put("MG", "minas-gerais"); mapEstados.put("PA", "para"); mapEstados.put("PB", "paraiba"); mapEstados.put("PR", "parana"); mapEstados.put("PE", "pernambuco"); mapEstados.put("PI", "piaui"); mapEstados.put("RJ", "rio-de-janeiro"); mapEstados.put("RN", "rio-grande-do-norteR"); mapEstados.put("RS", "rio-grande-do-sul"); mapEstados.put("RO", "rondonia"); mapEstados.put("RR", "roraima"); mapEstados.put("SC", "santa-catarina"); mapEstados.put("SE", "sergipe"); mapEstados.put("SP", "sao-paulo"); mapEstados.put("TO", "tocantins"); } public static void main(String[] args) throws Exception { new LerSiteTerraEleicoes2010().getDeputadosEleicoes2010(); } public void getDeputadosEleicoes2010() throws Exception { WebClient webClient = new WebClient(); HtmlPage page = null; try { page = (HtmlPage) webClient .getPage("http://eleicoes.terra.com.br/apuracao/2010/1turno/acre/#/deputado-federal/"); } catch (Exception e) { } HtmlElement elemento = (HtmlElement) page .getHtmlElementById("mod-482-gov"); Iterable<HtmlElement> allHtmlChildElements = elemento .getChildElements(); for (HtmlElement htmlElement : allHtmlChildElements) { Deputado deputado = new Deputado(); int fim = 0; boolean isDeputadoValido = false; String linha = htmlElement.asText(); if (linha.contains("Gabinete")) { isDeputadoValido = true; deputado.setDeputadoEmExercicio(true); fim = linha.indexOf("\r\n"); deputado.setNome(linha.substring(0, fim)); linha = linha.substring(fim + 2); fim = linha.indexOf("\r\n"); deputado.setEmail(linha.substring(fim + 2)); linha = linha.substring(0, fim); String[] subLinha = linha.split(":"); String[] partidoEsdado = subLinha[1].split("/"); deputado.setPartido(partidoEsdado[0]); deputado.setEstado(partidoEsdado[1].split("-")[0]); deputado.setGabiente(subLinha[3]); deputado.setTelefoneGabinete(subLinha[5]); } else if (linha.contains("licenciado")) { isDeputadoValido = true; deputado.setDeputadoEmExercicio(false); fim = linha.indexOf("\r\n"); deputado.setNome(linha.substring(0, fim)); linha = linha.substring(fim + 2); String[] partidoEsdado = linha.split(":")[1].split("/"); deputado.setPartido(partidoEsdado[0]); String[] estado = partidoEsdado[1].split(" "); deputado.setEstado(estado[0]); } } } }
Java
UTF-8
1,754
2.234375
2
[]
no_license
package edu.poly.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import edu.poly.exception.NotFoundException; import edu.poly.model.DanhGia; import edu.poly.model.LoaiHang; @RestController @RequestMapping("/danhgia") public class DanhGiaController { // // @Autowired // private DanhGiaService danhgiaservice; // // // hiển thị danh gia theo id // @GetMapping("/get/{id}") // public DanhGia get(@PathVariable Integer id) { // DanhGia danhgia = danhgiaservice.findById(id).orElseThrow(()->new NotFoundException()); // return danhgia; // } // // //Save danh gia // @PostMapping("save") // public DanhGia save(@RequestBody DanhGia danhgia) { // return danhgiaservice.save(danhgia); // } // // //hiển thị tất cả danh gia // @GetMapping("list") // public List<DanhGia> listAll(){ // return (List<DanhGia>) danhgiaservice.findAll(); // } // // @PutMapping("update/{id}") // public DanhGia update(@PathVariable Integer id, @RequestBody DanhGia danhgias) { // return danhgiaservice.findById(id) // .map(danhgia ->{ // danhgia.setSoSao(danhgias.getSoSao()); // danhgia.setNgayDanhGia(danhgias.getNgayDanhGiap()); // // return danhgiaservice.save(danhgia); // }).get(); // } }
C++
UTF-8
5,467
3
3
[ "MIT" ]
permissive
/** * @file MPIWrapper.h * @author Argishti Ayvazyan (ayvazyan.argishti@gmail.com) * @brief Declaration for MPIWrapper. * @date 12-11-2020 * @copyright Copyright (c) 2020 */ #pragma once #include <string> #include <vector> #include <map> #include <optional> #include <span> namespace mpi { /** * @class MPIWrapper * @brief The wrapper class for MPI helps for working in multiprocess flow. */ class MPIWrapper { using TValueType = float; using TTable = std::vector<std::vector<TValueType>>; using TDifferenceType = std::iterator_traits<std::vector<TValueType>::iterator>::difference_type; static constexpr int mainPID = 0; public: MPIWrapper(int* argc, char*** argv); ~MPIWrapper(); /** * @brief Gets the current process rank. * @return The rank. */ [[nodiscard]] int rank() const noexcept { return m_iMPIRank; } /** * @brief Checks, the current process is main or not. * @return True the current process is main, otherwise false. */ [[nodiscard]] bool isMain() const noexcept { return 0 == rank(); } /** * @brief The number of available processor. * @return The number of processor. */ [[nodiscard]] int numOfProcessor() const noexcept { return m_iMPISize; } /** * @brief Checks, running in the multi process flow. * @return True running in the multi process flow, otherwise false. */ [[nodiscard]] bool isMPF() const noexcept { return numOfProcessor() > 1; } /** * @brief Gets the current processor name. * * @return The processor name. */ [[nodiscard]] const std::string& processorName() const noexcept { return m_strProcessorName; } /** * @brief Distributes the query and dataSet to all processes. * * @param query The query vectors. * @param dataSet The data set. */ void distributeTask(const TTable& query, const TTable& dataSet); /** * @brief Returns the query vectors for current processor. * @return The query vectors. */ TTable receiveQuery(); /** * @brief Returns the data set for current processor. * @return The data set. */ TTable receiveDataSet(); /** * @brief Sends the distance matrix to the main processor. * * @param distanceMatrix The matrix of distance. */ void sendDistanceMatrix(const TTable& distanceMatrix); /** * @brief Receives the child processors distance matrices. * @return The matrix of distance. */ TTable receiveDistanceMatrix(); private: /** * @brief Distributes the query to all processes. * @param query The query vectors. */ void distributeQuery(const TTable& query); /** * @brief Sends the dataSet to all processes. * @param dataSet The data set. */ void sendDataSet(const TTable& dataSet); /** * @brief Registrations the new variable. * * @param varName The variable name. * @return The variable tag. */ int registerVariable (std::string&& varName); /** * @brief Computes and returns the optimal count of processes and query block size for one process. * @param length The number of query vectors. * @return The std::pair, first the block size, second number of process. */ [[nodiscard]] std::pair<size_t, size_t> getBlockSize(size_t length) const; /** * @brief Converts matrix to flat matrix. * * @param table The matrix. * @return The flat matrix. */ static std::vector<TValueType> toFlatMatrix(std::span<const std::vector<TValueType>> table); /** * @brief Converts the flat matrix to the normal matrix. * * @param flatMatrix The flat matrix. * @param rowSize The size of row. * @return The matrix. */ static TTable splitFlatMatrix(const std::vector<TValueType>& flatMatrix, size_t rowSize); /** * @brief Gets the tag for variable. * * @throw \ref dbgh::CAssertException if variable is not exists. * * @param name The name of variable. * @return The variable tag. */ [[nodiscard]] int getVariableTag (const std::string& name) const; /** * @internal * @brief Registrations of the variables for sync into processes. */ void registerParamsForSync(); private: /** * @brief The current process rank. */ int m_iMPIRank{}; /** * @brief The count of available processes. */ int m_iMPISize{}; /** * @brief The current procesor name. */ std::string m_strProcessorName; /** * @brief The variable name to tag map. */ std::map <std::string, int> m_mapVarNameToID; /** * @brief The query vectors for current process. */ TTable m_selfQuery; /** * @brief The computed distance matrix. */ TTable m_selfDistanceMatrix; /** * @brief The vectors size. */ std::optional<size_t> m_vectorSize; /** * @brief The num of vectors in query. */ std::optional<size_t> m_querySize; /** * @brief The num of vectors in dataSet. */ std::optional<size_t> m_dataSetSize; }; } // namespace mpi
SQL
UTF-8
4,864
4.09375
4
[ "MIT" ]
permissive
DB::select('cod_services.cod as codigo','cod_services.description as descricao','services.id','services.active','services.requirer')->from('services')->join('cod_services', function($join) {$join->on('services.cod_service_id', '=', 'cod_services.id');})->where('services.requirer', '=', 'nailson')->get(); DB::table('services', 'cod_services')->pluck('cod_services.cod as codigo','cod_services.description as descricao','services.id','services.active','services.requirer')->join('cod_services', 'cod_service_id', '=', 'cod_services.id')->select('services.*', 'cod_services.description')->get(); DB::table('services')->join('cod_services', function ($join) { $join->on('services.cod_service_id', '=', 'cod_services.id')->where('services.requirer', '=', 'teste');})->select('cod_services.cod as codigo','cod_services.description as descricao','services.id','services.active','services.requirer')->get(); DB::table('services')->join('cod_services', function ($join) { $join->on('services.cod_service_id', '=', 'cod_services.id')->where('services.service_order_id', '=', 81);})->select('cod_services.cod as cod_service','cod_services.description as description','services.*')->get(); -- A query utilizada foi a seguinte: DB::table('services')->join('cod_services', function ($join) use($serviceOrder) { $join->on('services.cod_service_id', '=', 'cod_services.id')->where('services.service_order_id', '=', $serviceOrder->id);})->select('cod_services.cod as cod_service','cod_services.description as description','services.*')->get(); DICAS SQL Tabela countries id countryName 1 Brasil 2 EUA 3 Japão Tabela states id countryId stateName 1 1 São Paulo 2 1 Rio Grande do Sul 3 1 Minas Gerais 4 2 California 5 2 Pensilvania 6 0 Corunha -- Inner Join mostra dados com o valor da chave em ambas as tabelas. SELECT * FROM `countries` INNER JOIN states ON countries.id = states.countryId RESULTADO id countryName id countryId stateName 1 Brasil 1 1 São Paulo 1 Brasil 2 1 Rio Grande do Sul 1 Brasil 3 1 Minas Gerais 2 EUA 4 2 California 2 EUA 5 2 Pensilvania -- Left Join vai mostrar tudo da tabela da esquerda e só os correspondentes da direita SELECT * FROM `countries` LEFT JOIN states ON countries.id = states.countryId RESULTADO id countryName id countryId stateName 1 Brasil 1 1 São Paulo 1 Brasil 2 1 Rio Grande do Sul 1 Brasil 3 1 Minas Gerais 2 EUA 4 2 California 2 EUA 5 2 Pensilvania 3 Japão null null null -- Corunha não foi retornado -- Right Join vai mostrar tudo da tabela da direita e só os correspondentes da esquerda SELECT * FROM `countries` RIGHT JOIN states ON countries.id = states.countryId RESULTADO id countryName id countryId stateName 1 Brasil 1 1 São Paulo 1 Brasil 2 1 Rio Grande do Sul 1 Brasil 3 1 Minas Gerais 2 EUA 4 2 California 2 EUA 5 2 Pensilvania null null 6 0 Corunha -- Japão não foi retornado -- Query para relacionar uma OS com os serviços alocados à mesma. -- Ao selecionar uma OS, a combo de "Serviço" vai apresentar apenas os itens relacionados. -- O id passado no Where é o id da OS. -- Os dois últimos campos são concatenados para aparecerem no mesmo valor do combo. SELECT services.cod_service_id, CONCAT(cod_services.cod, " - ", cod_services.description) as description FROM services LEFT JOIN cod_services on services.cod_service_id = cod_services.id WHERE services.service_order_id = 104; -- Query montada pelo site www.midnightcowboycoder.com -- Não funciona na minha versão do Laravel (5.1) DB::select('services.cod_service_id','cod_services.cod','cod_services.description')->from('services')->join('cod_services', function($join) {$join->on('services.cod_service_id', '=', 'cod_services.id');})->where('services.service_order_id', '=', 104)->get(); -- Query adaptada do site e funcionando DB::table('services')->join('cod_services', function($join) { $join->on('services.cod_service_id', '=', 'cod_services.id');})->where('services.service_order_id', '=', 105)->select('services.cod_service_id', 'cod_services.cod', 'cod_services.description')->get(); -- Query adaptada com passagem de parâmetro e concatenando os dois campos -- cod_services.cod " - " cod_services.description DB::table('services')->join('cod_services', function($join) use($serviceOrder) { $join->on('services.cod_service_id', '=', 'cod_services.id');})->where('services.service_order_id', '=', $serviceOrder->id)->select('services.cod_service_id', DB::raw('CONCAT(cod_services.cod, " - ", cod_services.description) as description'))->get();
C++
UTF-8
1,124
2.796875
3
[]
no_license
#pragma once #include <glm/gtc/matrix_transform.hpp> #include <glm/mat4x4.hpp> #include <vector> #include "ev_math.h" namespace ev { using std::tuple; class Body; class Shape { public: Vec2 m_pos{}; Vec2 m_velocity{}; }; class Polygon : public Shape { private: real m_rotation{}; void compute_face_normals(); public: Polygon(std::vector<Vec2> vertices, real rotation_rad = 0.0f); Polygon(real half_width, real half_height, real rotation_rad = 0.0f); void set_rect(real half_width, real half_height); Vec2 getExtremePoint(Vec2 dir); real inline rotation() const { return m_rotation; } Vec2 inline vertex(int index) const { return m_vertices[index]; } Vec2 inline normal(int index) const { return m_normals[index]; } size_t inline vertex_count() const { return m_vertices.size(); } std::vector<Vec2> m_vertices{}; std::vector<Vec2> m_normals{}; // Returns {mass, angular_mass} tuple tuple<real, real> compute_mass(real density); }; class Circle : public Shape { public: real radius; real compute_mass(real density); real compute_angular_mass(real mass); }; } // namespace ev
C++
UTF-8
705
2.640625
3
[ "Unlicense", "LicenseRef-scancode-public-domain" ]
permissive
#include <cstdio> const int numbers[10][2] = { { 6, 8 }, { 35, 49 }, { 204, 288 }, { 1189, 1681 }, { 6930, 9800 }, { 40391, 57121 }, { 235416, 332928 }, { 1372105, 1940449 }, { 7997214, 11309768 }, { 46611179, 65918161 } }; int main() { for (int i = 0; i < 10; ++i) printf("%10d%10d\n", numbers[i][0], numbers[i][1]); return 0; } #if 0 #include <cmath> #include <cstdio> typedef long long i64; int main() { int cnt = 0; for (i64 i = 2; cnt < 10; ++i) { i64 p = i*(i+1) / 2; i64 sp = sqrt(p); if (sp*sp == p) { printf("%lld %lld\n", sp, i); ++cnt; } } return 0; } #endif
Python
UTF-8
756
4.34375
4
[ "MIT" ]
permissive
# Powerful digit counts; problem 63 from ProjectEuler # =Problem Description= # The 5-digit number, 16807=7^5, is also a fifth power. Similarly, the 9-digit # number, 134217728=8^9, is a ninth power. # How many n-digit positive integers exist which are also an nth power? # import sys # sys.setrecursionlimit(1001) def size(n,e): num = n**e l = len(str(num)) if (l == e): print("len =",l, " ",n,"^", e, "=", num) return True return False total = 0 n = 25 # for e in range(1,n): # for i in range(1,n): # if (size(i,e)): # total += 1 # print() for i in range(1,n): for e in range(1,n): if (size(i,e)): total += 1 print() print("total =", total, "for n =", n)
Java
UTF-8
7,647
2.078125
2
[]
no_license
package cn.com.deepdata.streamflume.interceptor; import java.io.UnsupportedEncodingException; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.flume.Context; import org.apache.flume.Event; import org.apache.flume.event.EventBuilder; import org.apache.flume.interceptor.Interceptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cn.com.deepdata.streamflume.util.ZipUtil; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonSyntaxException; import com.google.gson.reflect.TypeToken; class Parser implements Interceptor { private static final Logger logger = LoggerFactory.getLogger(Parser.class); public static class HYEvent { public HashMap<String, Object> headers; public String body; public byte[] getBody() { // if (body == null) // Log.info(headers.toString()); if (body == null || body.length() == 0) return "Null Body".getBytes(); return body.getBytes(); } } public static class ErrorEvent { static public Event Create(String info, String content) { Map<String, String> errorHeader = new HashMap<String, String>(0); errorHeader.put("scc_errorInfo", info); StackTraceElement[] stacks = Thread.currentThread().getStackTrace(); if (stacks.length > 2) { StackTraceElement stack = stacks[2]; errorHeader.put("scc_errorPos", stack.getClassName() + " (line " + stack.getLineNumber() + ")"); } errorHeader.put("action", "addLogError"); return EventBuilder.withBody(content.getBytes(), errorHeader); } } double contentcompressrate = 0; long contentcompresscount = 0; double listcompressrate = 0; long listcompresscount = 0; int recvedEvent = 0; private final Type listType = new TypeToken<ArrayList<HYEvent>>() { }.getType(); private final Gson gson = new GsonBuilder().disableHtmlEscaping().create(); public void close() { // TODO Auto-generated method stub } public void initialize() { // TODO Auto-generated method stub } public int byteArrayToInt(byte[] bRefArr, int off, int len) { int iOutcome = 0; byte bLoop; for (int i = off; i < off + len; i++) { bLoop = bRefArr[i]; iOutcome += (bLoop & 0xFF) << (8 * i); } return iOutcome; } private List<Event> getSimpleEvents(List<HYEvent> events) { List<Event> newEvents = new ArrayList<Event>(events.size()); for (HYEvent e : events) { HashMap<String, Object> headers = e.headers; if (headers.containsKey("action") == false || headers.get("action") == null) { logger.error("no action in event: {}", new Gson().toJson(headers)); continue; } try { byte[] body = e.getBody(); String strBody = new String(body, "UTF-8"); if (!strBody.equals("Null Body")) headers.put("scc_content", strBody); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block // e1.printStackTrace(); logger.error("UnsupportedEncodingException:{}", e1); } byte[] newBody = new Gson().toJson(headers).getBytes(); if (newBody.length > 1000000) { logger.error("Message is too large. length: " + newBody.length); logger.error("Message title: " + headers.get("scc_title")); } else { newEvents.add(EventBuilder.withBody(newBody, new HashMap<String, String>(0))); } } return newEvents; } public List<Event> interceptList(Event event) { // TODO Auto-generated method stub byte[] bytes = event.getBody(); int byteLen = Integer.parseInt(event.getHeaders().get("bodySize")); if (byteLen == 0) return null; ArrayList<HYEvent> eventList = new ArrayList<HYEvent>(0); String json = ""; try { int version = byteArrayToInt(bytes, 0, 4); double compressrate = 1; if (version == 1) { byte[] uncompress = null; int compType = byteArrayToInt(bytes, 4, 2); uncompress = new byte[byteLen - 6]; System.arraycopy(bytes, 6, uncompress, 0, byteLen - 6); if (compType == 3) {// bzip2 uncompress = ZipUtil.bunzip2(uncompress); double ratio = (byteLen - 6) * 1.0 / uncompress.length; compressrate = ratio; } else if (compType == 2) {// zip uncompress = ZipUtil.unzip(uncompress); double ratio = (byteLen - 6) * 1.0 / uncompress.length; compressrate = ratio; } json = new String(uncompress, 0, uncompress.length, "UTF-8"); } else if (version == 0x32) { byte[] uncompress = new byte[byteLen - 4]; System.arraycopy(bytes, 4, uncompress, 0, byteLen - 4); json = new String(uncompress, 0, uncompress.length, "UTF-8"); } logger.debug("original request json: {}", json); eventList = gson.fromJson(json, listType); if (eventList == null || eventList.size() == 0) return new ArrayList<Event>(0); HYEvent hyEvent = eventList.get(0); if (hyEvent.headers.containsKey("links")) { listcompressrate += compressrate; listcompresscount++; } else { contentcompressrate += compressrate; contentcompresscount++; } } catch (JsonSyntaxException ex) { logger.error("JsonSyntaxException"); logger.error("json:{}", json); logger.error("ex:{}", ex); List<Event> ret = new ArrayList<Event>(0); ret.add(ErrorEvent.Create(ex.toString(), json)); return ret; } catch (UnsupportedEncodingException ex) { // TODO Auto-generated catch block logger.error("UnsupportedEncodingException"); logger.error("json:{}", json); logger.error("ex:{}", ex); List<Event> ret = new ArrayList<Event>(0); ret.add(ErrorEvent.Create(ex.toString(), json)); return ret; } return getSimpleEvents(eventList); } public Event intercept(Event arg0) { // TODO Auto-generated method stub return null; } public List<Event> intercept(List<Event> events) { // TODO Auto-generated method stub List<Event> newEvents = new ArrayList<Event>(); for (Event event : events) { List<Event> eventsList = interceptList(event); if (eventsList != null && eventsList.size() > 0) { newEvents.addAll(eventsList); recvedEvent += eventsList.size(); } } return newEvents; } public static class Builder implements Interceptor.Builder { public Interceptor build() { return new Parser(); } public void configure(Context arg0) { // TODO Auto-generated method stub } } }
Java
UTF-8
1,011
2.015625
2
[ "Apache-2.0" ]
permissive
package com.example.imetu.imet.Activity; import android.graphics.Bitmap; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import com.example.imetu.imet.Image.ResultHolder; import com.example.imetu.imet.R; public class ImagePreview extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_image_preview); Bitmap bitmap = ResultHolder.getImage(); if (bitmap == null){ setResult(RESULT_CANCELED); finish(); return; } ImageView imageView = (ImageView)findViewById(R.id.ivImagePreview); imageView.setImageBitmap(bitmap); } public void ImageOK(View view) { setResult(RESULT_OK); finish(); } public void ImageCancel(View view) { setResult(RESULT_CANCELED); finish(); } }
JavaScript
UTF-8
1,065
2.859375
3
[ "MIT" ]
permissive
const fs = require("fs"); var fetch = require("node-fetch"); import { loadingFile, missingSession, inputFetching } from "../constants"; async function fetchInput( year = 2019, day = 1, session = "", path = "./input.txt" ) { const data = await fetch( `https://adventofcode.com/${year}/day/${day}/input`, { headers: { cookie: `session=${session}`, }, } ).then((res) => res.text()); if (data) { fs.writeFile(path, data, (err) => { if (err) throw err; console.log("New input file has been created"); }); } return data; } export async function getAocInput(year, day, session) { let data = null; const folder = `./src/days/day${day}`; const file = "/input.txt"; const path = `${folder}${file}`; if (fs.existsSync(path)) { console.log(loadingFile); data = fs.readFileSync(path, "utf8"); } else if (!session) { console.log(missingSession); data = ""; } else { console.log(inputFetching); data = await fetchInput(year, day, session, path); } return data; }
Python
UTF-8
4,916
3.328125
3
[]
no_license
from copy import deepcopy from box import Box class Sudoku: def __init__(self, initial_grid): self.initial_grid = initial_grid # une grille de box def solve(self): print("Starting sudoku resolution") res = self.backtracking_search(deepcopy(self.initial_grid)) if res: print("Sudoku solved !") else: print("Sudoku could not be solved") return res def backtracking_search(self, csp): """ Backtracking is equivalent to DFS with a variable per node """ return self.recursive_backtracking(list(), csp) def recursive_backtracking(self, assignment, csp): print('.') if len(assignment) == len(self.initial_grid): # Assignment is complete return assignment if not self.ac3(csp): return False node = self.select_unasigned_variable(csp) for val in self.order_domain_values(node): if Sudoku.is_value_consistent_with_asignment(val, node): node.set_value(val) csp.remove(node) assignment.append(node) result = self.recursive_backtracking(deepcopy(assignment), deepcopy(csp)) if result: return result node.set_value(None) csp.append(node) # TODO: See if append_left improves performance here assignment.remove(node) return False def select_unasigned_variable(self, csp): min_nodes = self.mrv(csp) if len(min_nodes) == 1: return min_nodes[0] elif len(min_nodes) > 1: return self.degree_heuristic(min_nodes) else: raise Exception("No node selected after MRV ans Degree heuristic") @staticmethod def mrv(node_list): """ Minimum Remaining Values """ min_val = 10 min_nodes = list() for node in node_list: if len(node.get_possible_values()) < min_val: min_val = len(node.get_possible_values()) min_nodes = [node] elif len(node.get_possible_values()) == min_val: min_nodes.append(node) return min_nodes @staticmethod def degree_heuristic(node_list): if len(node_list) == 1: return node_list min_val = 21 # Number of constraints for any nodes + 1 min_node = None for node in node_list: nb_constraints = sum([1 if n.is_assigned() else 0 for n in node.get_constraint_nodes()]) if nb_constraints < min_val: min_val = nb_constraints min_node = node return min_node @staticmethod def order_domain_values(node): """ Least constraining value Here the least constraining value is the one that is least present in the constraint nodes possible values """ vals = dict() for val in node.get_possible_values(): vals[val] = 1 for n in node.get_constraint_nodes(): for val in n.get_possible_values(): if val in vals: vals[val] += 1 sorted_list = sorted(vals.items(), key=lambda kv: kv[1]) # print("sorted:", sorted_list) return [key for key, val in sorted_list] @staticmethod def is_value_consistent_with_asignment(val: int, node: Box): """ Check that none of the boxes constrained to the box already have this value """ for n in node.get_constraint_nodes(): nval = n.get_value() if nval is not None and nval == val: return False return True def ac3(self, csp): """ Arc Consistency 3 Algorithm, Possibly reduces CSP domains """ q = [] for nodea in csp: # Initially add all arcs in the queue for nodeb in nodea.get_constraint_nodes(): # if (nodea, nodeb) not in q and (nodeb, nodea) not in q: if (nodea, nodeb) not in q: q.append((nodea, nodeb)) while not len(q) == 0: nodea, nodeb = q.pop() if self.remove_inconsistent_values(nodea, nodeb): if len(nodea.get_possible_values()) == 0: return False for nodec in nodea.get_constraint_nodes(): if nodec != nodeb: q.append((nodec, nodea)) return True @staticmethod def remove_inconsistent_values(nodea, nodeb): """ Returns true if some inconsistent values were found and removed """ if nodeb.get_value() is not None and nodeb.get_value() in nodea.get_possible_values(): nodea.remove_possible_value(nodeb.get_value()) return True else: return False def get_initial_grid(self): return self.initial_grid
Markdown
UTF-8
4,607
3.5
4
[ "MIT" ]
permissive
# Jest Axios ## Introduction Jest Axios is a [Jest](https://jestjs.io/) plugin that simplifies the process of mocking [axios](https://github.com/axios/axios) requests during testing. It fully utilizes Jest's built-in capabilities for mocking functions, and will automatically override requests made using axios throughout your application. It does this with three main features: 1. Easy configuration for defining functions to return data for specific endpoints and request methods. 2. An internal database for storing data to serve via endpoint mocks. 3. Providing tools that minimize boilerplate when mocking data for data models and collections of models. ### Why is this Useful? It can be difficult to test JavaScript packages and complex web applications that fetch data from external services. Jest provides good [tools](https://jestjs.io/docs/en/mock-functions) for mocking data, but those tools aren't scalable for `axios` specifically or easy to configure for common REST API patterns. The result is a lot of unnecessary boilerplate in Jest tests, which can cause confusion and increase the maintenance burden of a test suite. This package simplifies that process by providing users a tool to quickly and robustly spin up mocked API services that will serve real data when `axios` requests are made throughout an application. ### Prerequisites This documentation assumes users have at least a practical understanding of [ES6](https://www.freecodecamp.org/news/write-less-do-more-with-javascript-es6-5fd4a8e50ee2/) syntax and constructs. This documentation has code examples heavily utilizing ES6 constructs. ## Quickstart The documentation that follows details how to mock a REST API for a minimal [todo list](https://vuejs.org/v2/examples/todomvc.html) application. First, we'll define configuration for mocking requests in our application, and will then use axios in `jest` tests to showcase the mocked requests. For more detailed documentation about how to define and configure mock REST API services with this library, see the [Guide](/guide/) section of the documentation. To start, here is the syntax for configuring a server to mock requests: ```javascript // contents of tests/index.test.js import axios from 'axios'; import { Server } from 'jest-axios'; class App extends Server { data() { return { todos: [ { name: 'foo', done: false }, { name: 'bar', done: true }, ], }; } api() { return { '/todos': this.collection('todos'), '/todos/:id': this.model('todos'), '/todos/:id/complete': { post: id => this.db.todos.update(id, { done: true }); }, }; } } ``` Once we have this defined, we need to configure our tests to initialize the server and mock axios: ```javascript // contents of tests/index.test.js ... server = App('todo-app'); jest.mock('axios'); server.init(axios); ``` With the server initialized, let's run some tests to show the mocked requests: ```javascript // contesnts of tests/index.test.js ... test('api.test', async () => { // issue request const response = await axios.get('/todos'); // check status code assert.equal(response.status, 200); // check payload assert.equal(response.data, [ { id: 1, name: 'foo', done: false }, { id: 2, name: 'bar', done: true }, ]); // issue missing request and check error try { await axios.get('/missing'); assert.fail('Endpoint `/missing` should have returned error.'); } catch (err) { assert.equal(err.status, 404); } // get specific todo item let todo = await axios.get('/todos/1').then(response => response.data); assert.equal(todo, { name: 'foo', done: false }); // complete todo item and check again await axios.post('/todos/1/complete'); todo = await axios.get('/todos/1').then(response => response.data); assert.equal(todo.done, true); }); ``` That's it! This library will also automatically mock any `axios` requests you make throughout your project, so you don't need to directly make `axios` calls inside tests to benefit from this package. This simple example showcases only a small portion of the features available in the package. For more detailed examples and explanations, see the [Usage](/guide/) section of the documentation. For API documentation, see the [API](/api/) section of the documentation. ## Table of Contents - [Setup](/setup/) - [Usage](/guide/) - [API](/api/) ## Additional Resources - [Jest](https://jestjs.io/) - [Jest Mocking Tools](https://jestjs.io/docs/en/mock-functions) - [Axios](https://github.com/axios/axios)
PHP
UTF-8
762
2.984375
3
[]
no_license
<?php include 'credentials.php'; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $input = json_decode(file_get_contents('php://input'), true); foreach ($input as $tank) { //Speichert die Werte beider Tanks $starttime = $tank['starttime']; if ($starttime == null) { $id = $tank['id']; $sql = "UPDATE header SET starttime= NULL WHERE id='$id'"; $result = $conn->query($sql); if ($conn->query($sql) === TRUE) { echo "Record updated successfully"; } else { echo "Error updating record: " . $conn->error; } } } $conn->close(); ?>
Java
UTF-8
2,328
2.875
3
[]
no_license
package com.tong.test; import java.util.List; import java.util.Scanner; import com.tong.biz.EmpBiz; import com.tong.biz.impl.EmpBizImpl; import com.tong.entity.Emp; public class Test { public static void main(String[] args) { Scanner scan = new Scanner(System.in); EmpBiz empbiz = new EmpBizImpl(); /*System.out.println("请输入您要删除的员工姓名:"); String name = scan.next(); if(empbiz.deleteEmp(name)!=0){ System.out.println("删除成功"); }else{ System.out.println("删除失败"); }*/ /*System.out.println("请输入员工姓名:"); String name = scan.next(); System.out.println("请输入员工电话:"); String phone = scan.next(); System.out.println("请输入部门ID:"); int dept = scan.nextInt(); Emp emp = new Emp(name, phone, dept); //调用业务逻辑层的添加的方法 if(empbiz.insertEmp(emp)!=0){ System.out.println("添加成功"); }else{ System.out.println("该员工已存在"); }*/ /*List<Emp> list = empbiz.queryAll(); for (Emp emp : list) { System.out.println(emp.getEmp_id()+"---"+emp.getEmp_name()+"---"+emp.getEmp_phone()+"---"+emp.getDept_name()); }*/ /*System.out.println("请输入员工id:"); int id = scan.nextInt(); Emp emp = null; if((emp = empbiz.queryById(id))!=null){ System.out.println(emp.getEmp_name()+"---"+emp.getEmp_phone()+"---"+emp.getDept_name()); }else{ System.out.println("未找到"); }*/ /*System.out.println("请输入员工姓名:"); String name = scan.next(); Emp emp = null; if((emp = empbiz.queryByName(name))!=null){ System.out.println(emp.getEmp_id()+"---"+emp.getEmp_phone()+"---"+emp.getDept_name()); }else{ System.out.println("未找到"); }*/ System.out.println("请输入员工ID:"); int id = scan.nextInt(); System.out.println("请输入修改后的姓名:"); String name = scan.next(); System.out.println("请输入修改后的电话:"); String phone = scan.next(); System.out.println("请输入修改后的部门ID:"); int did = scan.nextInt(); Emp emp = new Emp(id, name, phone, did); if(empbiz.update(emp)!=0){ System.out.println("修改成功"); }else{ System.out.println("修改失败"); } } }
C++
UTF-8
1,476
3.6875
4
[]
no_license
#include <iostream> // the dimension must be a constant expression unsigned cnt = 42; // not a constant expression constexpr unsigned sz = 42; // constant expression // constexpr see § 2.4.4 (p. 66) int arr[10]; // array of ten ints int *parr[sz]; // array of 42 pointers to int string bad[cnt]; // error: cnt is not a constant expression string strs[get_size()]; // ok if get_size is constexpr, error otherwise int ia1[sz] = {0,1,2}; // array of three ints with values 0, 1, 2 int a2[] = {0, 1, 2}; // an array of dimension 3 int a3[5] = {0, 1, 2}; // equivalent to a3[] = {0, 1, 2, 0, 0} string a4[3] = {"hi", "bye"}; // same as a4[] = {"hi", "bye", ""} int a5[2] = {0,1,2}; // error: too many initializers // there is a null character at the end of a string literal char a1[] = {'C', '+', '+'}; // list initialization, no null char a2[] = {'C', '+', '+', '\0'}; // list initialization, explicit null char a3[] = "C++"; // null terminator added automatically const char a4[6] = "Daniel"; // error: no space for the null! // no copy or assignment to array; int a[] = {0, 1, 2}; // array of three ints int a2[] = a; // error: cannot initialize one array with another a2 = a; // error: cannot assign one array to another int *ptrs[10]; // ptrs is an array of ten pointers to int int &refs[10] = /* ? */; // error: no arrays of references int (*Parray)[10] = &arr; // Parray points to an array of ten ints int (&arrRef)[10] = arr; // arrRef refers to an array of ten ints
PHP
UTF-8
444
2.609375
3
[]
no_license
<?php /** * File was created 08.10.2015 19:11 */ namespace PeekAndPoke\Component\Slumber\Data\Addon\PublicReference; /** * @author Karsten J. Gerber <kontakt@karsten-gerber.de> */ interface PublicReferenceGenerator { public const SERVICE_ID = 'slumber.data.addon.public_reference.generator'; /** * @param mixed $subject The object to create a public unique reference for * * @return null|string */ public function create($subject); }
Markdown
UTF-8
1,725
3.921875
4
[ "BSD-3-Clause", "CC-BY-SA-4.0", "CC-BY-4.0" ]
permissive
--- title: Basic Syntax --- # Basic Syntax A PHP script can be placed anywhere in the document. A PHP script starts with `<?php` and ends with `?>` Below, we have an example of a simple PHP file, with a PHP script that uses a built-in PHP function "echo" to output the text "Hello World!" on a web page ````<!DOCTYPE html> <html> <body> <h1>My first PHP page</h1> <?php echo "Hello World!"; ?> </body> </html> ```` The output of that would be : ```` My first PHP page Hello World! ```` #### Note: PHP statements end with a semicolon (;). # Comments in PHP PHP supports several ways of commenting: ```` <!DOCTYPE html> <html> <body> <?php // This is a single-line comment # This is also a single-line comment /* This is a multiple-lines comment block that spans over multiple lines */ // You can also use comments to leave out parts of a code line $x = 5 /* + 15 */ + 5; echo $x; ?> </body> </html> ```` # PHP Case Sensitivity In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions are NOT case-sensitive. In the example below, all three echo statements are legal (and equal): ```` <!DOCTYPE html> <html> <body> <?php ECHO "Hello World!<br>"; echo "Hello World!<br>"; EcHo "Hello World!<br>"; ?> </body> </html> ```` ### However; all variable names are case-sensitive. In the example below, only the first statement will display the value of the $color variable (this is because $color, $COLOR, and $coLOR are treated as three different variables): ```` <!DOCTYPE html> <html> <body> <?php $color = "red"; echo "My car is " . $color . "<br>"; echo "My house is " . $COLOR . "<br>"; echo "My boat is " . $coLOR . "<br>"; ?> </body> </html> ````
C++
UTF-8
1,333
2.640625
3
[]
no_license
#include "gameCube.hpp" GameCube::GameCube(const std::string &name,GLuint programm,double size, glm::vec3 color,std::vector<glm::vec3> offset,const std::string &t): GameObject(name,programm,offset) { this->textureName = t; this->colorValue = color; } void GameCube::makeObject() { std::cout << "make Cube" <<std::endl; const float vertices[] = { -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0, // back -1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, -1.0, 1.0, -1.0 }; const unsigned int indexTab[] = { 0, 1, 2, 2, 3, 0, // top 3, 2, 6, 6, 7, 3, // back 7, 6, 5, 5, 4, 7, // bottom 4, 5, 1, 1, 0, 4, // left 4, 0, 3, 3, 7, 4, // right 1, 5, 6, 6, 2, 1 }; const float uvTab[] = { 0,0,1,0,1,1,0,0,1,1,0,1 }; for(int i=0;i<36;i++) index->push_back(indexTab[i]); for(int i=0;i<24;i+=3) { pos->push_back(glm::vec3(vertices[i],vertices[i+1],vertices[i+2])); color->push_back(glm::vec3(colorValue[0],colorValue[1],colorValue[2])); } int j=0; for(int i=0;i<6*6;i+=2) { if((i%12)==0) j=0; uvs->push_back(glm::vec2(uvTab[j],uvTab[j+1])); j+=2; } textureID =glGetUniformLocation(programm, "colormap"); texture = loadTGATexture(textureName); GameObject::makeObject(); } void GameCube::draw() { GameObject::draw(); }
Markdown
UTF-8
1,398
3.046875
3
[]
no_license
--- layout: post title: The importance of hand gestures in the communication --- In a recent [paper](https://royalsocietypublishing.org/doi/10.1098/rspb.2020.2419) researchers evaluated the effects of hand gestures on the effectiveness of communication. And apparently, people remember better if gestures are used when the speaker is talking. Molly Hanson summarised the findings in an article on [bigthink.com/surprising-science/talking-with-your-hands](https://bigthink.com/surprising-science/talking-with-your-hands). [Allan Pease speech at TedX](https://youtu.be/ZZZ7k8cMA-4) was also mentioned in the above article. He was talking about the position of palms when talking: * palms up - people will receive you positively; * palms down - power position, not the best choice in a neutral environment; * finger pointing would be something you'd like to avoid; * palms facing each other and only fingers of both hands touching - position of confidence. It is quite a powerful message in the context of public speaking. If hand gestures allow people to retain more information from the speech, and proper palm position is used, then you should create better outcomes. One crucial issue remains how these same techniques affect the person on the other hand of the computer screen? Does it mean we ought to show our torso in the video call as well (for the viewer to see our hands better)?
PHP
UTF-8
3,809
2.90625
3
[ "X11", "MIT" ]
permissive
<?php /** * @file Session.php * @brief The SessionManager class * @details This file contains the SessionManager class * @author Thibaud Canaud * @date 11-10-2016 * @par License * * * Copyright © 2016, Thibaud CANAUD * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files * (the “Software”), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * The Software is provided “as is”, without warranty of any kind, express * or implied, including but not limited to the warranties of * merchantability, fitness for a particular purpose and noninfringement. * In no event shall the authors or copyright holders X be liable for any * claim, damages or other liability, whether in an action of contract, * tort or otherwise, arising from, out of or in connection with the * software or the use or other dealings in the Software. * * Except as contained in this notice, the name of the Thibaud CANAUD * shall not be used in advertising or otherwise to promote the sale, * use or other dealings in this Software without prior written * authorization from the Thibaud CANAUD. */ namespace CT\Grapes\Session; /** * @brief The Session class * @author 0xCT */ class SessionManager extends Session { /** * @brief <I>string</I> — The name of item * @details This is a name of sub item used in session */ protected $item; /** * @brief Construct class * @param $item <I>string</I> — Name of sub item used * @par Source */ public function __construct($item) { parent::start(); $this->item = $item; } /** * @brief Set a subjet in subitem * @param $subject <I>string</I> — Name of subject * @param $value <I>string</I> — Value of subject * @param $type <I>string</I> — Type of subject. Default is string. * @par Source */ public function set($subject,$value,$type='string'){ parent::_set($this->item.'.'.$subject,$value,$type); return $this; } /** * @brief get a subjet in subitem * @param $subject <I>string</I> — Name of subject * @param $type <I>string</I> — Type of subject. Default is string. * @return <I>mixed</I> — The value of subject request * @par Source */ public function get($subject,$type='string'){ return parent::_get($this->item.'.'.$subject,$type); } /** * @brief Get item complet * @return <I>mixed</I> — All subjects of this item * @par Source */ public function getItem(){ $item = array(); foreach ($_SESSION as $key => $value) { if ( substr($key, 0, strlen($this->item)) == $this->item) $item[substr($key,strlen($this->item)+1)] = $value; } return $item; } /** * @brief Delete this item of session * @par Source */ public function delItem(){ foreach ($_SESSION as $key => $value) { if ( substr($key, 0, strlen($this->item)) == $this->item) unset($_SESSION[$key]); } } /** * @brief Delete a subject of this item * @par Source */ public function del($subject){ unset($_SESSION[$this->item.'.'.$subject]); } }
Markdown
UTF-8
16,860
2.703125
3
[]
no_license
###### Dethroning the dollar # America is weaponising its currency and financial system ##### Its use of sanctions could endanger the dollar in the long term ![image](images/20200118_BBD001_0.jpg) > Jan 18th 2020 EVER SINCE the dollar cemented its role as the world’s dominant currency in the 1950s, it has been clear that America’s position as the sole financial superpower gives it extraordinary influence over other countries’ economic destinies. But it is only under President Donald Trump that America has used its powers routinely and to their full extent, by engaging in financial warfare. The results have been awe-inspiring and shocking. They have in turn prompted other countries to seek to break free of American financial hegemony. In 2018 America’s Treasury put legal measures in place that prevented Rusal, a strategically important Russian aluminium firm, from freely accessing the dollar-based financial system—with devastating effect. Overnight it was unable to deal with many counterparties. Western clearing houses refused to settle its debt securities. The price of its bonds collapsed (the restrictions were later lifted). America now has over 30 active financial- and trade-sanctions programmes. On January 10th it announced measures that the treasury secretary, Steven Mnuchin, said would “cut off billions of dollars of support to the Iranian regime”. The State Department, meanwhile, said that Iraq could lose access to its government account at the Federal Reserve Bank of New York. That would restrict Iraq’s use of oil revenues, causing a cash crunch and flattening its economy. America is uniquely well positioned to use financial warfare in the service of foreign policy. The dollar is used globally as a unit of account, store of value and medium of exchange. At least half of cross-border trade invoices are in dollars. That is five times America’s share of world goods imports, and three times its share of exports. The dollar is the preferred currency of central banks and capital markets, accounting for close to two-thirds of global securities issuance and foreign-exchange reserves. The world’s financial rhythm is American: when interest rates move or risk appetite on Wall Street shifts, global markets respond. The world’s financial plumbing has Uncle Sam’s imprint on it, too. Most international transactions are ultimately cleared in dollars through New York by American “correspondent” banks. America has a tight grip on the main cross-border messaging system used by banks, SWIFT, whose members ping each other 30m times a day. Another part of the US-centric network is CHIPS, a clearing house that processes $1.5trn-worth of payments daily. America uses these systems to monitor activity. Denied access to this infrastructure, an organisation becomes isolated and, usually, financially crippled. Individuals and institutions across the planet are thus subject to American jurisdiction—and vulnerable to punishment. America began to flex its financial muscles after the terrorist attacks of September 11th 2001. It imposed huge fines on foreign banks for money-laundering and sanctions-busting; in 2014 a $9bn penalty against BNP Paribas shook the French establishment. Mr Trump has taken the weaponisation of finance to a new level (see chart). He has used sanctions to throttle Iran, North Korea, Russia, Turkey (briefly), Venezuela and others. His arsenal also includes tariffs and legal assaults on companies, most strikingly Huawei, which Mr Trump accuses of spying for China. “Secondary” sanctions target other countries’ companies that trade with blacklisted states. After America pulled out of a nuclear deal with Iran in 2018, European firms fled Iran, even as the EU encouraged them to stay. SWIFT quickly fell into line when America threatened action if it did not cut off Iranian banks after the reimposition of sanctions in 2018. ![image](images/20200118_BBC087.png) Using the dollar to extend the reach of American law and policy fits Mr Trump’s “America first” credo. Other countries view it as an abuse of power. That includes adversaries such as China and Russia; Russia’s president, Vladimir Putin, talks of the dollar being used as a “political weapon”. And it includes allies, such as Britain and France, who worry that Mr Trump risks undermining America’s role as guarantor of orderliness in global commerce. It may eventually lead to the demise of America’s financial hegemony, as other countries seek to dethrone its mighty currency. The new age of international monetary experimentation features the de-dollarisation of assets, trade workarounds using local currencies and swaps, and new bank-to-bank payment mechanisms and digital currencies. In June the Chinese and Russian presidents said they would expand settlement of bilateral trade in their own currencies. On the sidelines of a recent summit, leaders from Iran, Malaysia, Turkey and Qatar proposed using cryptocurrencies, national currencies, gold and barter for trade. Such activity marks an “inflection point”, says Tom Keatinge of RUSI, a think-tank. Countries that used merely to gripe about America’s financial might are now pushing back. Russia has gone furthest. It has designated expendable entities to engage in commerce with countries America considers rogue, in order to avoid putting important banks and firms at risk. State-backed Promsvyazbank PJSC is used for trade in arms so as to shield bigger banks like Sberbank and VTB from the threat of sanctions. Russia has also been busy de-dollarising parts of its financial system. Since 2013 its central bank has cut the dollar share of its foreign-exchange reserves from over 40% to 24%. Since 2018 the bank’s holdings of American Treasury debt have fallen from nearly $100bn to under $10bn. Russia’s finance ministry recently announced plans to lower the dollar share of its $125bn sovereign-wealth fund. “We aren’t aiming to ditch the dollar,” Mr Putin has said. “The dollar is ditching us.” Elvira Nabiullina, Russia’s central-bank governor, says the move was partly motivated by American sanctions (which were imposed after Russia’s annexation of Crimea in 2014), but also by a desire to diversify currency risk. “I see a global shift in mood,” she says. “We are gradually moving towards a more multi-currency international monetary system.” Ms Nabiullina echoes Mark Carney, the governor of the Bank of England, who said in August that the dollar-centric system “won’t hold”. Russia’s debt is being de-dollarised, too. New issuance is often in roubles or euros, and the government is exploring selling yuan-denominated bonds. Russian companies have shrunk their foreign debts by $260bn since 2014; of that, $200bn was dollar-denominated. Conversely, Russian firms and households retain a fondness for dollars when it comes to holding international assets: they have $80bn more than they did in 2014. Dmitry Dolgin of ING, a bank, finds this “puzzling”, but suspects it could be that the interest rates on dollar assets, higher than on euro equivalents, outweigh the perceived risk from sanctions. Dasvidaniya, dollar ING expects 62% of Russia’s goods and services exports to have been settled in dollars in 2019, down from 80% in 2013. Its trade with China was almost all in dollars in 2013; now less than half is. Trade with India, much of it in the sanctions-sensitive defence sector, shifted from almost all dollars to almost all roubles over that period. One reason for this shift, say Russian officials, is that it speeds trade up, since dollar payments can be delayed for weeks as financial intermediaries run sanctions checks. Energy and commodities firms are among Russia’s most active de-dollarisers. The greenback is the global benchmark currency for oil trading, and escaping its grip is hard. “The key thing to understand is that risk management, the entire derivatives complex, is in dollars,” explains the boss of a global energy firm. “So if you want to have risk management—as an oil trader, buyer or producer—you have to have contact with the dollar system.” Nonetheless Rosneft, a state-backed producer that accounts for over 40% of Russia’s crude output, has denominated its tender contracts in euros. Surgutneftegas, another producer, still prices in dollars but has added a clause to contracts saying they can be switched to euros at its request—“a back-up plan in case Trump throws shit at the fan”, says a trader. Last March Gazprom priced a natural-gas shipment to western Europe in roubles for the first time. The cost of switching out of dollars is modest, says an executive at a global oil-trading firm: “an extra person in the finance department and a bit more currency risk.” Will China follow the trail blazed by Russia? Mr Trump has exposed China’s profound vulnerability to the dollar-centric financial system. America’s ability to blacklist or hobble Chinese tech firms, such as Huawei, ultimately rests on punishing suppliers and other counterparties who do business with them through the dollar-based banking and payments system. An American legal case against a senior Huawei executive, who is fighting extradition from Canada, reportedly relies in part on evidence from an American-appointed overseer at HSBC, an Asia-centric bank run from London. In October America sanctioned eight cutting-edge Chinese tech firms for alleged human-rights abuses in Xinjiang province. The administration has threatened to block listings by Chinese firms in New York and restrict purchases by American investors of Chinese shares. China’s first attempt to bypass the dollar was bungled. After the financial crisis in 2007-09 it promoted the international use of the yuan and pressed for it to become part of the IMF’s “Special Drawing Rights”, in effect receiving the fund’s imprimatur as a reserve currency. China set up currency swap deals with foreign central banks (it has done over 35). There was heady talk of the yuan challenging the dollar for the top spot by 2020. Then came a stockmarket panic in 2015 and the government clumsily tightened capital controls. The yuan’s share of global payment by value has stayed at about 2% for several years. Zhou Xiaochuan, a former governor of China’s central bank, has said that yuan internationalisation, which he promoted while in office, was “a premature baby”. America’s display of financial firepower and new technologies are changing the calculus again. China has some of the building blocks to become more autonomous. It has its own domestic payments and settlement infrastructure, called CIPS. Launched in 2015, it has so far complemented SWIFT (which it uses for interbank messaging). It is tiny, processing less in 2018 than SWIFT does each day. But it simplifies cross-border payments in yuan, giving banks lots of nodes for settlements. Reports suggest that China, India and others may be exploring a jointly run SWIFT alternative. A will and a Huawei Parts of the world’s consumer-finance system are coming under China’s sway thanks to its digital-platform firms, which have globalised faster than its conventional banks. Payments through Alibaba (and its affiliate Ant Financial) are accepted by merchants in 56 countries. The Alipay logo is, in some places, as common as Visa’s. In capital markets, in 2018 China introduced a yuan-denominated crude-oil futures contract on a Shanghai exchange. Known as the “petroyuan”, it is seen by some as a potential rival to the dollar in pricing oil. China has encouraged important firms listed in America to list their shares closer to home as well. On November 26th Alibaba, China’s most valuable company, which in 2014 floated in New York rather than in Hong Kong or Shanghai, completed a $13.4bn additional listing in Hong Kong (the funds were raised in Hong Kong dollars). “As a result of the continuous innovation and changes to the Hong Kong capital market, we are able to realise what we regrettably missed out on five years ago,” said Daniel Zhang, Alibaba’s chief executive. China’s central bank is reported to be working on a new digital currency, though details are sparse. Some speculate that it wants to get a head-start on America in building whatever international system emerges for managing payments in central bank-issued digital currencies. It discussed creating a common cryptocurrency with other BRICS countries (Brazil, Russia, India and South Africa) at a recent summit. China may end up doing Bitcoin with an authoritarian twist: instead of anonymity it may want all data to be trackable and centrally stored. That America’s geopolitical rivals want to escape the dollar’s dominance is no surprise. Perhaps more striking is that its allies are flirting with it, too. In her manifesto for 2019-24, Ursula von der Leyen, the new president of the European Commission, said: “I want to strengthen the international role of the euro.” Jean-Claude Juncker, her predecessor, has called the dollar’s dominance in European energy trade an “aberration” (when just 2% of imports come from America). The commission is working on a new action plan, part of which involves encouraging EU countries to eliminate “undue reference” to the dollar in payments and trade invoicing, according to a staffer. ![image](images/20200118_BBD002_0.jpg) So far the EU’s main initiative has involved Iran. It has tried to create a way for its banks and firms to trade with it, while shielding them from America’s wrath. But Instex, a clearing house created for this purpose by Britain, France and Germany, with the commission’s support, is crude and limited. It is essentially a barter mechanism and does not cover oil sales (it is limited to non-sanctioned humanitarian trade). It was structured to allow firms to engage in commerce without resort to the dollar or SWIFT. But they have stayed away for fear of incurring secondary sanctions. The stuttering performance of Instex reflects the sheer scope of America’s reach. As Adam M. Smith, a sanctions expert at Gibson Dunn, a law firm, points out, America can claim jurisdiction if a transaction has any American “nexus”, even if it is not denominated in dollars. This includes transactions that rely on banks under American jurisdiction, or where a foreign counterparty relies on American nationals to approve, facilitate or process the transaction, or where one party uses a back-end payment, accounting or email system that is stored on servers in America. Despite this, some European officials remain optimistic. On November 29th six more EU states said they planned to join Instex. “It’s a ten-to-twenty-year thing, and hopefully not only covering Iran. You can’t undo decades of policy in a year,” says a French official. And, if Europe manages to reform the inner workings of the euro, its financial reach will expand. “We need to complete the project first: banking union, fiscal integration, genuine capital-markets union, and so on,” another French official says. European powers are likely to play a leading role in central-bank efforts to create a global electronic currency. Last year Mr Carney floated the idea of a network of central-bank digital monies that could serve as a global invoicing currency. If it happens America may not be invited. A haven above The true test of any reserve currency is a financial crisis. Eswar Prasad of Cornell University, the author of “The Dollar Trap”, notes that the greenback benefits during times of turmoil. The 2007-09 crisis, which originated in America, paradoxically strengthened its status as a safe haven. When global trade, saving, borrowing and reserves are largely in one currency, these strengths are mutually reinforcing. No other capital market comes close to America’s for depth and liquidity, a key factor when choosing a currency for commerce. Yet financial supremacy depends on a heady mix of economic clout, incumbency and legitimacy. And the martial approach that America has adopted threatens the dollar’s dominance, reckons Jeffrey Frankel of Harvard University. A former American treasury secretary agrees. In 2016, while still in office, Jack Lew told an audience in Washington: “It is a mistake to think that [sanctions] are low-cost. And if they make the business environment too complicated, or unpredictable, or if they excessively interfere with the flow of funds worldwide, financial transactions may begin to move outside of the United States entirely—which could threaten the central role of the US financial system globally, not to mention the effectiveness of our sanctions in the future.” As the Trump administration continues to use sanctions aggressively, efforts to circumvent them will accelerate. America does not have a monopoly on financial ingenuity.■
Markdown
UTF-8
1,063
2.671875
3
[]
no_license
# Projeto Estoque Básico Descrição ------- ``` Este programa permite cadastrar, editar e excluir itens, a fim de criar um banco de dados conforme a necessidade do usuário. *O cadastro conta com os seguintes campos: - Nome - N° de Itens em Estoque - Preço Unitário - Categorias *Por padrão, estão cadastradas 5 categorias (1, 2, 3, 4 e 5), no entanto esta podem ser facilmente editadas, de acordo com a vontade do usuário. ``` Observações ------- ``` Existe um limite de 1M (1.000.000) de cadastro, não expansivel Este programa esta temporariamente em memória volatil Cadastrar dois itens com o mesmo nome não é possivel (foi bloqueado) Tela tamanho HD (1280x720), não sendo possivel redimensina-la ``` Novas Implemetações ------- ``` Permitida a sincronização de filtros simultaneos Correção de bugs ``` Futuras Implementações ------- ``` Salvar permanentemente informações ``` Código para Teste ------- ``` 6Wmc-7K0g-7jn1-4mrS-Ig1I ``` By ----- ``` Guilherme Fontana Aluno do segundo ano do ensino médio 2018 ```
Shell
UTF-8
1,935
3.28125
3
[]
no_license
DATE="$(date +"%Y.%b.%d_%H.%M")" echo "running: flow_prepare_for_development.sh" echo "--------- dropbox status" dropbox status echo " " echo "1. Cleaning" echo -n " 1.1 delete logs to obtain space (rm -rf ~/Dropbox/my_code/RoR/code/aptana/flow/log/*)..." rm -rf ~/Dropbox/my_code/RoR/code/aptana/flow/log/* echo "done." echo -n " 1.2 delete tmp files to obtain space (rm -rf ~/Dropbox/my_code/RoR/code/aptana/flow/tmp/*)..." rm -rf ~/Dropbox/my_code/RoR/code/aptana/flow/tmp/* echo "done." echo " " echo "2. backup dev flow to home" echo -n " 2.1 creating directory ~/flowbackup/$DATE/" echo -n " ..." mkdir -p ~/flowbackup/$DATE/ echo "done." echo -n " 2.2 copying directory ~/Dropbox/my_code/RoR/code/aptana/flow/ to ~/flowbackup/$DATE/" echo -n " ..." cp -R ~/Dropbox/my_code/RoR/code/aptana/flow/ ~/flowbackup/$DATE/ echo "done." echo " " echo "3. backup dev flow to dropbox" echo -n " 3.1 creating directory ~/Dropbox/my_code/RoR/code/backup/flow/$DATE/" echo -n " ..." mkdir -p ~/Dropbox/my_code/RoR/code/backup/flow/$DATE/ echo "done." echo -n " 3.2 copying directory ~/Dropbox/my_code/RoR/code/aptana/flow/ to ~/Dropbox/my_code/RoR/code/backup/flow/$DATE/" echo -n " ..." cp -R ~/Dropbox/my_code/RoR/code/aptana/flow/ ~/Dropbox/my_code/RoR/code/backup/flow/$DATE/ echo "done." echo " " printf "4. Do you want to get the hot sqlite3 DB to develop? (y/n): " read INPT if [ "$INPT" = "y" ]; then echo -n " copy hot sqlite3 (cp -R ~/Dropbox/my_code/RoR/htdocs/flow/db/development.sqlite3 to ~/Dropbox/my_code/RoR/code/aptana/flow/db/development.sqlite3)..." cp -R ~/Dropbox/my_code/RoR/htdocs/flow/db/development.sqlite3 ~/Dropbox/my_code/RoR/code/aptana/flow/db/development.sqlite3 echo "done." echo " " else echo " keeping development database." echo " " fi #echo "5. running test suite" #cd ~/Dropbox/my_code/RoR/code/aptana/flow/ #rake test:units echo "Happy coding George!!"
Python
UTF-8
1,510
4.25
4
[ "MIT" ]
permissive
upper=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"] upper_new=[] lower=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"] lower_new=[] number=["0","1","2","3","4","5","6","7","8","9"] number_new=[] character=["$","#","@"] character_new=[] while True: password=list(input("Enter Password: ")) if len(password)<6: print("Password is too short") continue elif len(password)>16: print("Password is too long") continue else: for i in password: if i in upper: upper_new.append(i) elif i in lower: lower_new.append(i) elif i in number: number_new.append(i) elif i in character: character_new.append(i) if len(upper_new)==0: print("Password Must Contain At Least 1 Uppercase Alphabet") continue elif len(lower_new)==0: print("Password Must Contain At Least 1 Lowercase Alphabet") continue elif len(character_new)==0: print("Password Must Contain At Least 1 Special Character") continue elif len(number_new)==0: print("Password Must Contain At Least 1 Number Between 0-9") continue else: print("Congratulations ! You Entered A Valid Password") break
PHP
UTF-8
744
2.71875
3
[]
no_license
<?php namespace MyString\View\Helper; use Zend\View\Helper\AbstractHelper; class FormHelper extends AbstractHelper { /** * @var string */ private $action; /** * @var string */ private $submit; public function __invoke($action, $submit) { $this->action = $action; $this->submit = $submit; return $this->render(); } private function render() { return ' <form id="cadenaForm" action="' . $this->action . '" method="post"> <input type="string" name="str1"><br> <input type="string" name="str2"><br> <input type="submit" value="' . $this->submit . '"> </form> '; } }
C++
UTF-8
3,380
2.875
3
[]
no_license
#include "FragTrap.hpp" #include "ClapTrap.hpp" #include <ctime> FragTrap::FragTrap(void) : ClapTrap(100, 100, 100, 100, 1, "default name", 30, 20, 5) { std::cout << "FR4G-TP : Booting sequence complete. Hello! I am your new steward bot. Designation: " << this->_name << "." << std::endl; } FragTrap::FragTrap(std::string const name) : ClapTrap(100, 100, 100, 100, 1, name, 30, 20, 5) { std::cout << "FR4G-TP : Booting sequence complete. Hello! I am your new steward bot. Designation: " << this->_name << "." << std::endl; } FragTrap::FragTrap(FragTrap const & src) : ClapTrap(src._hitPoints, src._mHitPoints, src._energyPoints, src._mEnergyPoints, src._level, src._name, src._meleeAttackDamage, src._rangedAttackDamage, src._armorDamageReduction) { std::cout << "FR4G-TP : Booting sequence complete. Hello! I am your new steward bot. Designation: " << this->_name << ". I have been cloned !" << std::endl; } FragTrap::~FragTrap(void) { std::cout << this->_name << ": I'M DEAD I'M DEAD OHMYGOD I'M DEAD!" << std::endl; } FragTrap & FragTrap::operator=(FragTrap const & rhs) { this->_hitPoints = rhs._hitPoints; this->_mHitPoints = rhs._mHitPoints; this->_energyPoints = rhs._energyPoints; this->_mEnergyPoints = rhs._mEnergyPoints; this->_level = rhs._level; this->_name = rhs._name; this->_meleeAttackDamage = rhs._meleeAttackDamage; this->_rangedAttackDamage = rhs._rangedAttackDamage; this->_armorDamageReduction = rhs._armorDamageReduction; return *this; } void FragTrap::rangedAttack(std::string const & target) const { std::cout << "FR4G-TP " << this->_name << " attacks " << target << " at range, causing " << this->_rangedAttackDamage << " points of damage !" << std::endl; } void FragTrap::meleeAttack(std::string const & target) const { std::cout << "FR4G-TP " << this->_name << " attacks " << target << " at melee, causing " << this->_meleeAttackDamage << " points of damage !" << std::endl; } void FragTrap::vhClapInTheBox(std::string const & target) { std::cout << this->_name << ": Performing Clap In The Box attack on " << target << "." << std::endl; } void FragTrap::vhGunWizard(std::string const & target) { std::cout << this->_name << ": Performing Gun Wizard attack on " << target << "." << std::endl; } void FragTrap::vhTorgueFiesta(std::string const & target) { std::cout << this->_name << ": Performing Torgue Fiesta attack on " << target << "." << std::endl; } void FragTrap::vhPirateShipMode(std::string const & target) { std::cout << this->_name << ": Performinging Pirate Ship Mode attack on " << target << "." << std::endl; } void FragTrap::vhLaserInferno(std::string const & target) { std::cout << this->_name << ": Performing Laser Inferno attack on " << target << "." << std::endl; } void FragTrap::vaulthunter_dot_exe(std::string const & target) { if (this->_energyPoints < 25) { std::cout << this->_name << ": I don't have enough energy points to launch my super attack :(." << std::endl; } else { this->_energyPoints -= 25; std::cout << this->_name << ": This time it'll be awesome, I promise! But now i have only " << this->_energyPoints << " energy point(s) !" << std::endl; void(FragTrap::*tab[5]) (std::string const &) = {&FragTrap::vhClapInTheBox, &FragTrap::vhGunWizard, &FragTrap::vhTorgueFiesta, &FragTrap::vhPirateShipMode, &FragTrap::vhLaserInferno}; (this->*(tab[rand() % 5]))(target); } }
Java
UTF-8
2,630
2.203125
2
[ "AFL-3.0" ]
permissive
// // Copyright (c) 2007, Brian Frank and Andy Frank // Licensed under the Academic Free License version 3.0 // // History: // 26 Dec 07 Brian Frank Creation // package fan.std; import java.util.regex.*; import fan.sys.*; import fanx.main.Sys; import fanx.main.Type; /** * RegexMatcher */ public final class RegexMatcher extends FanObj { ////////////////////////////////////////////////////////////////////////// // Constructors ////////////////////////////////////////////////////////////////////////// RegexMatcher(Matcher matcher) { this.matcher = matcher; } ////////////////////////////////////////////////////////////////////////// // Identity ////////////////////////////////////////////////////////////////////////// private static Type type; public Type typeof() { if (type == null) Sys.findType("std::RegexMatcher"); return type; } ////////////////////////////////////////////////////////////////////////// // Methods ////////////////////////////////////////////////////////////////////////// public final boolean matches() { return matcher.matches(); } public final boolean find() { return matcher.find(); } public final String replaceFirst(String replacement) { return matcher.replaceFirst(replacement); } public final String replaceAll(String replacement) { return matcher.replaceAll(replacement); } public final long groupCount() { return matcher.groupCount(); } public final String group() { return group(0L); } public final String group(long group) { try { return matcher.group((int)group); } catch (IllegalStateException e) { throw Err.make(e.getMessage()); } catch (IndexOutOfBoundsException e) { throw IndexErr.make(""+group); } } public final long start() { return start(0L); } public final long start(long group) { try { return matcher.start((int)group); } catch (IllegalStateException e) { throw Err.make(e.getMessage()); } catch (IndexOutOfBoundsException e) { throw IndexErr.make(""+group); } } public final long end() { return end(0L); } public final long end(long group) { try { return (matcher.end((int)group)); } catch (IllegalStateException e) { throw Err.make(e.getMessage()); } catch (IndexOutOfBoundsException e) { throw IndexErr.make(""+group); } } ////////////////////////////////////////////////////////////////////////// // Fields ////////////////////////////////////////////////////////////////////////// Matcher matcher; }
Python
UTF-8
363
3.0625
3
[ "WTFPL", "MIT" ]
permissive
w, h = 4, 100 list_of_gedung = [[0 for x in range(w)] for y in range(h)] def load_gedung(filename): x = 0 with open(filename) as file: for line in file: titik = [int(n) for n in line.strip().split(',')] list_of_gedung[x//4][x%4] = titik x = x + 1 print(x//4) load_gedung('itb_coordinate.txt')
SQL
UTF-8
4,063
3.296875
3
[]
no_license
-- PRE: You are running APEX 5.0 or higher. -- Oracle Express 11gR2 comes with APEX 4.0.2. The apex_json stuff DNE here. -- https://www.oracle.com/technetwork/developer-tools/apex/learnmore/upgrade-apex-for-xe-154969.html -- Yup, I was able to upgrade to APEX 5.0.4. -- -- The API reference for apex_json is here: -- https://docs.oracle.com/cd/E59726_01/doc.50/e39149/apex_json.htm#AEAPI29660 set serveroutput on; declare value varchar2(256); v_path varchar2(256); bvalue boolean; v_count number; v_number number; parsed_json apex_json.t_values; -- List of members of an object. v_members wwv_flow_t_varchar2; -- List of JSON paths. paths apex_t_varchar2; -- JSON representing a request to reclassify some transactions. request_json varchar2(32767) := ' { "request": { "id": "1", "requester_pidm": "54321", "completed": true, "approved": false, "ops": [ { "seq": 1, "type": "reclassify", "to_acct": "13", "orig_trans_id": "T32" }, { "seq": 2, "type": "reclassify", "to_acct": "14", "orig_trans_id": "T57" }, { "seq": 3, "type": "move", "from_index": "I80", "from_acct": "217", "to_index": "I15", "from_acct": "1011", "orig_trans_id": "T222" }, { "seq": 4, "type": "reverse", "orig_trans_id": "T321" } ] } }'; BEGIN -- Yup, it's this easy. dbms_output.put_line('Let''s parse some JSON!'); -- This creates a g_values of type apex_json.t_values. -- The subsequent apex_json.get_varchar2() calls read from that value by default. -- You can call an overload of parse to supply a destination value as the first arg. -- apex_json.parse(request_json); value := apex_json.get_varchar2('request.id'); dbms_output.put_line(value); -- This uses 1-based indexes. -- By default, these functions read from g_values. -- You can supply a 3rd argument to read from another parsed JSON object. value := apex_json.get_varchar2('request.ops[%d].orig_trans_id', 1); dbms_output.put_line(value); -- Get a boolean value. bvalue := apex_json.get_boolean('request.completed'); if bvalue then dbms_output.put_line('The request has been completed.'); end if; -- Get a numberic value. v_path := 'request.ops[2].seq'; v_number := apex_json.get_number(v_path); dbms_output.put_line(v_path || ' == ' || v_number); -- Get number of elements in a array. Loop over each op in the request. v_count := apex_json.get_count('request.ops'); dbms_output.put_line('The request contains ' || v_count || ' operations.'); for i in 1 .. v_count loop value := apex_json.get_varchar2('request.ops[%d].type', i); dbms_output.put_line(value); end loop; -- Check if something exists at a given path. if apex_json.does_exist('request.ops[%d].to_acct', 2) then dbms_output.put_line('request.ops[2].to_acct exists'); end if; -- Get the names of all members of an object. dbms_output.put_line('Members of request.ops[3]'); v_members := apex_json.get_members('request.ops[3]'); for i in 1 .. v_members.count loop dbms_output.put_line(v_members(i)); end loop; -- Get a list of related paths. -- We want to find all transaction reclassification operations within the request. -- Note that we're using parsed_json instead of the default g_values here. -- Basically, we return a list of all request.ops[*] paths for which request.ops[i].type == 'reclassify'. apex_json.parse(parsed_json, request_json); paths := apex_json.find_paths_like ( p_values => parsed_json, -- The parsed JSON (g_values by default). p_return_path => 'request.ops[%]', -- The path starts to search and return. p_subpath => '.type', -- A subpath to query. p_value => 'reclassify' -- The specific value to find. ); -- Print the seq # of each reclassification operation. dbms_output.put_line('Reclassification operations:'); for i in 1 .. paths.count loop dbms_output.put_line(apex_json.get_varchar2(p_values => parsed_json, p_path => paths(i) || '.seq')); end loop; END; /
Markdown
UTF-8
951
2.609375
3
[]
no_license
# Three.js Blender Import/Export Imports and exports Three.js' ASCII JSON format. ## Installation Copy the io_mesh_threejs folder to the scripts/addons folder. If it doesn't exist, create it. The full path is OS-dependent (see below). Once that is done, you need to activate the plugin. Open Blender preferences, look for Addons, search for `three`, enable the checkbox next to the `Import-Export: three.js format` entry. Goto Usage. ### Windows Should look like this: C:\Users\USERNAME\AppData\Roaming\Blender Foundation\Blender\2.6X\scripts\addons ### OSX Depends on where blender.app is. Assuming you copied it to your Applications folder: /Applications/Blender/blender.app/Contents/MacOS/2.6X/scripts/addons ### Linux By default, this should look like: /home/USERNAME/.blender/2.6X/scripts/addons ## Usage Use the regular Import and Export menu within Blender, select `Three.js (js)`.
Python
UTF-8
92
2.890625
3
[]
no_license
import copy a = [1,2,[3, 4]] b = copy.deepcopy(a) b[2][0] = -100 print('a:',a) print('b:',b)
JavaScript
UTF-8
697
3.609375
4
[]
no_license
//Lista de Compras let listaDeCompras = ["redbull", "uva", "leite", "carne", "batata"]; console.log("O método pop"); console.log(listaDeCompras.pop()); console.log(listaDeCompras); console.log("\n"); console.log("O método push"); console.log(listaDeCompras.push("milho", "sabão em pó")); console.log(listaDeCompras); console.log("\n"); console.log("O método shift"); console.log(listaDeCompras.shift()); console.log(listaDeCompras); console.log("\n"); console.log("O método unshift"); console.log(listaDeCompras.unshift("ração de gato")); console.log(listaDeCompras); console.log("\n"); console.log("O método join"); console.log(listaDeCompras.join("-")); console.log(listaDeCompras);
JavaScript
UTF-8
582
3.703125
4
[]
no_license
let arr = ['a', 'o', 'e', 'u', 'i']; let arr1 = []; let count = 0; let a = prompt("nhập ký tự"); function checkSoKyTu(string) { for (let i = 0; i < string.length; i++) { for (let j = 0; j < arr.length; j++) { if (string[i] === arr[j]) { arr1.push(string[i]); count++; } } } if (arr1.length == 0) { alert("Chuỗi tự bạn nhập không có ký tự nguyên âm") } else { alert("Chuỗi tự bạn nhập có " + count + " ký tự nguyên âm") } } checkSoKyTu(a);
Java
UTF-8
2,361
2.53125
3
[]
no_license
package my.chat.logging; import my.chat.commons.FilePaths; import my.chat.commons.Helper; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; public class Log { private static final Logger LOGGER; static { PropertyConfigurator.configure(FilePaths.LOG_PROPERTIES); LOGGER = Logger.getLogger("chat"); } public static void info(Object callerClass, String message, Object... params) { LOGGER.info(makeMessage(callerClass, message, params)); } public static <T extends Throwable> void info(Object callerClass, T throwable, String message, Object... params) { LOGGER.info(makeMessage(callerClass, message, params), throwable); } public static void debug(Object callerClass, String message, Object... params) { LOGGER.debug(makeMessage(callerClass, message, params)); } public static <T extends Throwable> T debug(Object callerClass, T throwable, String message, Object... params) { LOGGER.debug(makeMessage(callerClass, message, params), throwable); return throwable; } public static void warn(Object callerClass, String message, Object... params) { LOGGER.warn(makeMessage(callerClass, message, params)); } public static <T extends Throwable> T warn(Object callerClass, T throwable, String message, Object... params) { LOGGER.warn(makeMessage(callerClass, message, params), throwable); return throwable; } public static void error(Object callerClass, String message, Object... params) { LOGGER.error(makeMessage(callerClass, message, params)); } public static <T extends Throwable> T error(Object callerClass, T throwable, String message, Object... params) { LOGGER.error(makeMessage(callerClass, message, params), throwable); return throwable; } public static <T extends Throwable> T error(Object callerClass, T throwable) { LOGGER.error(throwable.getMessage(), throwable); return throwable; } private static String makeMessage(Object callerClass, String message, Object... params) { message = Helper.makeMessage(message, params); return (callerClass == null ? "" : callerClass.getClass().getName() + ": ") + message; } }
JavaScript
UTF-8
1,592
3.109375
3
[]
no_license
//Class WaveShaper export default class WaveShaper{ //DISTORTION BRO constructor(audioCtx){ this.audioCtx=audioCtx this.distortion = audioCtx.createWaveShaper(); this.distortion.curve = this.makeDistortionCurve(400); //check how it sounds and map the value from 0 to maybe something this.distortion.oversample = '4x'; return this; } makeDistortionCurve=function(amount) { var k = typeof amount === 'number' ? amount : 50, n_samples = 44100, curve = new Float32Array(n_samples), deg = Math.PI / 180, i = 0, x; for ( ; i < n_samples; ++i ) { x = i * 2 / n_samples - 1; curve[i] = ( 3 + k ) * x * 20 * deg / ( Math.PI + k * Math.abs(x) ); } return curve; }; getNode=function(){ return this.distortion } updateParameters=function(jsonobj){ if(jsonobj.updatetype=="curve"){ if(jsonobj.val>=this.getDetails().curve.min && jsonobj.val<=this.getDetails().curve.max){ this.distortion.curve=this.makeDistortionCurve(jsonobj.val) console.log("ClassWaveShaper: Updated",jsonobj) return true; }else{ return false; } } else if(jsonobj.updatetype=="oversample"){ if(this.getDetails().oversample.includes(jsonobj.val)){ this.distortion.oversample = jsonobj.val; console.log("ClassWaveShaper: Updated",jsonobj) return true; }else{ return false; } } } getDetails=function(){ return {"oversample":["none","2x","4x"], "curve":{"min":0,"max":1000,"default":400}}; } }//WaveShaper ends
Java
UTF-8
322
1.804688
2
[]
no_license
package cn.wolfcode.crm.mapper; import cn.wolfcode.crm.domain.CustomerTransferHistory; import cn.wolfcode.crm.query.QueryObject; import java.util.List; public interface CustomerTransferHistoryMapper { int insert(CustomerTransferHistory record); List<CustomerTransferHistory> selectForList(QueryObject qo); }
JavaScript
UTF-8
486
3.0625
3
[ "MIT" ]
permissive
var MODERN_ACTIVITY= 15; var HALF_LIFE_PERIOD= 5730; var k = 0.693 / HALF_LIFE_PERIOD; module.exports = function dateSample(sampleActivity) { var b = parseFloat(sampleActivity) if (/[a-zA-z]/.test(sampleActivity) == true){ return false } if (sampleActivity > MODERN_ACTIVITY) return false; if (sampleActivity <= 0) return false; if (typeof sampleActivity !== 'string'){ return false } var age = Math.ceil(Math.log(MODERN_ACTIVITY/b) / k); return age };
JavaScript
UTF-8
610
2.53125
3
[]
no_license
/* eslint-disable no-console */ import { status, json, endPoint, options, } from './api'; import createList from './data'; const loadingApi = () => { const content = document.getElementById('content'); content.innerHTML = '<img src="./images/additional/loading-api.gif" alt="loading" class="loading">'; content.style.display = 'flex'; content.style.justifyContent = 'center'; }; const getData = (url) => { fetch(endPoint(url), options) .then(loadingApi()) .then(status) .then(json) .then((data) => { createList(data.restaurants); }); }; export { getData, loadingApi };
C++
UTF-8
1,217
3.890625
4
[]
no_license
#include<iostream> using namespace std; //Program which declares whether or not a meeting may go ahead //If it's legal, it tells you how many additional people are allowed //If it contravenes fire regulations, it tells you how many need to be excluded //This program allows the user to enter the calculation as many times as they desire int main() { int max_capacity = 0; int attendee_number = 0; char check = 'y'; while (check == 'y'||check =='Y') { cout << "What is the maximum capacity?\n"; cin >> max_capacity; cout << "And how many will be attending this meeting?\n"; cin >> attendee_number; if (attendee_number == max_capacity) cout << "Meeting allowed, but it is at maximum capacity!\n"; else if (attendee_number < max_capacity) cout << "Meeting allowed, and you may have up to " << max_capacity - attendee_number << " additional attendees if you wish.\n"; else cout << "Meeting verboten! You will need to get rid of " << attendee_number - max_capacity << " more to be compliant with fire regulations.\n"; cout << "Do you want another calculation?"<< endl << "Enter 'y' or 'Y' if so, and anything else to exit\n"; cin >> check; } return 0; }
Python
UTF-8
681
3.953125
4
[]
no_license
# 1. В диапазоне натуральных чисел от 2 до 99 определить, сколько из них кратны каждому из чисел в диапазоне от 2 до 9. # Примечание: 8 разных ответов. # Создадим словарь, где ключами будут цифры, кратность которым мы проверяем, а значениями - счетчики. divs = dict.fromkeys(range(2, 10), 0) for key, value in divs.items(): for num in range(2, 100): if not num % key: divs[key] += 1 print(f'Чисел, кратных {key} - {divs[key]} штук.')
Java
UTF-8
4,629
3.046875
3
[]
no_license
package com.dzidzoiev.opencv; import java.awt.image.BufferedImage; import java.awt.image.DataBufferByte; import org.opencv.core.Mat; import javafx.application.Platform; import javafx.beans.property.ObjectProperty; import javafx.embed.swing.SwingFXUtils; import javafx.scene.image.Image; import javafx.scene.*; import javafx.scene.control.*; /** * Provide general purpose methods for handling OpenCV-JavaFX data conversion. * Moreover, expose some "low level" methods for matching few JavaFX behavior. * * @author <a href="mailto:luigi.derussis@polito.it">Luigi De Russis</a> * @author <a href="http://max-z.de">Maximilian Zuleger</a> * @version 1.0 (2016-09-17) * @since 1.0 * */ public final class Utils { /** * Convert a Mat object (OpenCV) in the corresponding Image for JavaFX * * @param frame * the {@link Mat} representing the current frame * @return the {@link Image} to show */ public static Image mat2Image(Mat frame) { try { return SwingFXUtils.toFXImage(matToBufferedImage(frame), null); } catch (Exception e) { System.err.println("Cannot convert the Mat obejct: " + e); return null; } } /** * Generic method for putting element running on a non-JavaFX thread on the * JavaFX thread, to properly update the UI * * @param property * a {@link ObjectProperty} * @param value * the value to set for the given {@link ObjectProperty} */ public static <T> void onFXThread(final ObjectProperty<T> property, final T value) { Platform.runLater(() -> { property.set(value); }); } /** * Find a {@link Node} within a {@link Parent} by it's ID. * <p> * This might not cover all possible {@link Parent} implementations but it's * a decent crack. {@link Control} implementations all seem to have their * own method of storing children along side the usual * {@link Parent#getChildrenUnmodifiable()} method. * * @param parent * The parent of the node you're looking for. * @param id * The ID of node you're looking for. * @return The {@link Node} with a matching ID or {@code null}. */ @SuppressWarnings("unchecked") public static <T> T getChildByID(Parent parent, String id) { String nodeId = null; if(parent instanceof TitledPane) { TitledPane titledPane = (TitledPane) parent; Node content = titledPane.getContent(); nodeId = content.idProperty().get(); if(nodeId != null && nodeId.equals(id)) { return (T) content; } if(content instanceof Parent) { T child = getChildByID((Parent) content, id); if(child != null) { return child; } } } for (Node node : parent.getChildrenUnmodifiable()) { nodeId = node.idProperty().get(); if(nodeId != null && nodeId.equals(id)) { return (T) node; } if(node instanceof SplitPane) { SplitPane splitPane = (SplitPane) node; for (Node itemNode : splitPane.getItems()) { nodeId = itemNode.idProperty().get(); if(nodeId != null && nodeId.equals(id)) { return (T) itemNode; } if(itemNode instanceof Parent) { T child = getChildByID((Parent) itemNode, id); if(child != null) { return child; } } } } else if(node instanceof Accordion) { Accordion accordion = (Accordion) node; for (TitledPane titledPane : accordion.getPanes()) { nodeId = titledPane.idProperty().get(); if(nodeId != null && nodeId.equals(id)) { return (T) titledPane; } T child = getChildByID(titledPane, id); if(child != null) { return child; } } } else if(node instanceof Parent) { T child = getChildByID((Parent) node, id); if(child != null) { return child; } } } return null; } /** * Support for the {@link mat2image()} method * * @param original * the {@link Mat} object in BGR or grayscale * @return the corresponding {@link BufferedImage} */ private static BufferedImage matToBufferedImage(Mat original) { // init BufferedImage image = null; int width = original.width(), height = original.height(), channels = original.channels(); byte[] sourcePixels = new byte[width * height * channels]; original.get(0, 0, sourcePixels); if (original.channels() > 1) { image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR); } else { image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY); } final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData(); System.arraycopy(sourcePixels, 0, targetPixels, 0, sourcePixels.length); return image; } }
JavaScript
UTF-8
2,271
3.203125
3
[]
no_license
class Board extends React.Component { constructor() { super(); this.state = { items: [ { text: "focus", state: 1 }, { text: "learn react", state: 2 }, { text: "clean up", state: 0 }, { text: "take break", state: 0 } ] }; }; // Using an anonymous arrow function to bind 'this' correctly nextCol = (itemIndex) => { // Best practice: the immutable way let itemscopy = [...this.state.items]; itemscopy[itemIndex].state++; this.setState({ items: itemscopy }); }; render() { return ( <div id="theboard" className="border"> <div id="firstCol"> <h4>to do</h4> {this.state.items.map((item, idx) => { if (item.state == 0) { return <Item // Passing method reference down to the component - nice click={() => this.nextCol(idx)} todo={item.text} key={item.text} /> } })} </div> <div id="secondCol"> <h4>in progress</h4> {this.state.items.map((item, idx) => { if (item.state == 1) { return <Item click={() => this.nextCol(idx)} todo={item.text} key={item.text} /> } })} </div> <div id="thirdCol"> <h4>done</h4> {this.state.items.map((item, idx) => { if (item.state == 2) { return <Item click={() => this.nextCol(idx)} todo={item.text} key={item.text} /> } })} </div> </div> ); }; }; ReactDOM.render(<Board />, document.querySelector('#board'));
C#
UTF-8
5,911
3.3125
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using TressFXLib.Numerics; namespace TressFXLib { class Utilities { private static Random rand = new Random(); //-------------------------------------------------------------------------------------- // // GetTangentVectors // // Create two arbitrary tangent vectors (t0 and t1) perpendicular to the input normal vector (n). // //-------------------------------------------------------------------------------------- public static void GetTangentVectors(Vector3 n, out Vector3 t0, out Vector3 t1) { t0 = new Vector3(); t1 = new Vector3(); if (Mathf.Abs(n.z) > 0.707f) { float a = n.y * n.y + n.z * n.z; float k = 1.0f / Mathf.Sqrt(a); t0.x = 0; t0.y = -n.z * k; t0.z = n.y * k; t1.x = a * k; t1.y = -n.x * t0.z; t1.z = n.x * t0.y; } else { float a = n.x * n.x + n.y * n.y; float k = 1.0f / Mathf.Sqrt(a); t0.x = -n.y * k; t0.y = n.x * k; t0.z = 0; t1.x = -n.z * t0.y; t1.y = n.z * t0.x; t1.z = a * k; } } public static float GetRandom(float Min, float Max) { return ((float)rand.NextDouble())* (Max - Min) + Min; } public static string[] ReadAllLines(BinaryReader reader) { List<string> strings = new List<string>(); StringBuilder temp = new StringBuilder(); char lastChar = reader.ReadChar(); // an EndOfStreamException here would propogate to the caller try { while (true) { char newChar = reader.ReadChar(); if (lastChar == '\r' && newChar == '\n') { strings.Add(temp.ToString()); } temp.Append(lastChar); lastChar = newChar; } } catch (EndOfStreamException) { temp.Append(lastChar); strings.Add(temp.ToString()); return strings.ToArray(); } } /// <summary> /// Executes the given action on every strand on the hair. /// </summary> /// <param name="hair"></param> /// <param name="action"></param> public static void StrandLevelIteration(Hair hair, Action<HairStrand> action) { foreach (HairMesh m in hair.meshes) if (m != null) foreach (HairStrand s in m.strands) action(s); } /// <summary> /// Executes the given action on every vertex on the hair. /// </summary> /// <param name="hair"></param> /// <param name="action"></param> public static void StrandLevelIteration(Hair hair, Action<HairStrand, HairStrandVertex> action) { foreach (HairMesh m in hair.meshes) if (m != null) foreach (HairStrand s in m.strands) foreach (HairStrandVertex v in s.vertices) action(s, v); } /// <summary> /// Gets the vector3 for the given distance to root for the given strand. /// /// If the dist to root is > than the hair length, the last vertex is returned, if its shorter then the first hair vertex is returned. /// </summary> /// <param name="strand"></param> /// <param name="distToRoot"></param> /// <returns></returns> public static Vector3 GetPositionOnStrand(HairStrand strand, float distToRoot) { // Get strand root Vector3 strandRoot = strand.vertices[0].position; float strandLength = strand.length; if (distToRoot <= 0) return strandRoot; else if (distToRoot >= strandLength) return strand.vertices[strand.vertices.Count-1].position; // Loop variables float rootDist = 0; Vector3 lastPos = strandRoot; int lineSegment = -1; float[] rootDists = new float[strand.vertices.Count]; // Find the line segment for (int i = 1; i < strand.vertices.Count; i++) { Vector3 curPos = strand.vertices[i].position; // Calculate root dists rootDist += (lastPos - curPos).Length; rootDists[i] = rootDist; if (rootDist > distToRoot) { // We found the segment lineSegment = i; break; } lastPos = curPos; } if (lineSegment == -1 || lineSegment == 0) throw new KeyNotFoundException("Could not find the line segment for dist to root = " + distToRoot + "!"); // Sample position Vector3 segmentStart = strand.vertices[lineSegment-1].position; Vector3 segmentEnd = strand.vertices[lineSegment].position; // Build lerp t factor float segmentStartDist = rootDists[lineSegment-1]; float segmentEndDist = rootDists[lineSegment]; float segmentLength = segmentEndDist - segmentStartDist; float lerpT = (distToRoot - segmentStartDist) / segmentLength; return Vector3.Lerp(segmentStart, segmentEnd, lerpT); } } }