language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Python
UTF-8
281
3.734375
4
[]
no_license
import turtle ws = turtle.Screen() geekyTurtle = turtle.Turtle() t = turtle.Turtle() for i in range(6): geekyTurtle.forward(90) geekyTurtle.left(300) t.right(95) t.forward(75) r = 50 t.circle(r) t.left(55) t.forward(15) s= 50 for _ in range(4): t.forward(s) t.left(90)
Shell
UTF-8
811
2.75
3
[]
no_license
#!/bin/bash echo "-- Preparing WWW files --" [[ -e html ]] && rm -r html mkdir -p html/img mkdir -p html/js mkdir -p html/css # Join scripts DD=html_orig/jssrc cat $DD/chibi.js \ $DD/utils.js \ $DD/modal.js \ $DD/appcommon.js \ $DD/term.js \ $DD/wifi.js > html/js/app.js sass --sourcemap=none html_orig/sass/app.scss html_orig/css/app.css # No need to compress CSS and JS now, we run YUI on it later cp html_orig/css/app.css html/css/app.css cp html_orig/term.html html/term.tpl cp html_orig/wifi.html html/wifi.tpl cp html_orig/about.html html/about.tpl cp html_orig/help.html html/help.tpl cp html_orig/wifi_conn.html html/wifi_conn.tpl cp html_orig/img/loader.gif html/img/loader.gif cp html_orig/img/cvut.svg html/img/cvut.svg cp html_orig/favicon.ico html/favicon.ico
Rust
UTF-8
7,338
3.109375
3
[ "MIT" ]
permissive
//! Physical page allocator. use crate::addr::*; use crate::arch::PAGE_SIZE; use crate::error::*; use core::mem::{size_of, MaybeUninit}; use core::ops::{Deref, DerefMut}; use core::ptr::NonNull; use core::sync::atomic::{AtomicU64, Ordering}; use spin::Mutex; use core::convert::TryFrom; /// This number is chosen to ensure size_of::<AllocFrame>() == size_of::<Page>() . pub const PAGES_PER_ALLOC_FRAME: usize = PAGE_SIZE / size_of::<usize>() - 3; pub const PHYSICAL_PAGE_METADATA_BASE: u64 = 0xFFFFFFC000000000; /// A NonNull pointer to `AllocFrame` that implements `Send`. #[derive(Copy, Clone)] #[repr(transparent)] struct AllocFramePtr(pub NonNull<AllocFrame>); unsafe impl Send for AllocFramePtr {} /// A frame in the unused physical page stack. #[repr(C)] pub struct AllocFrame { /// A stack of unused physical addresses. elements: [PhysAddr; PAGES_PER_ALLOC_FRAME], /// Stack top, exclusively. `next_index == elements.len()` if the frame is full. next_index: usize, /// Link pointer to the previous AllocFrame, if any. prev_frame: Option<AllocFramePtr>, /// Link pointer to the next AllocFrame, if any. next_frame: Option<AllocFramePtr>, } static ALLOC_CURRENT: Mutex<Option<AllocFramePtr>> = Mutex::new(None); /// Takes an uninitialized NonNull<AllocFrame>, initializes and pushes it. /// /// Only used during initialization. pub unsafe fn init_clear_and_push_alloc_frame(mut frame: NonNull<AllocFrame>) { core::ptr::write(frame.as_ptr(), core::mem::zeroed()); let mut current = ALLOC_CURRENT.lock(); if let Some(ref mut ptr) = *current { let ptr = ptr.0.as_mut(); assert_eq!(ptr.next_index, ptr.elements.len()); assert!(ptr.next_frame.is_none()); ptr.next_frame = Some(AllocFramePtr(frame)); } frame.as_mut().prev_frame = *current; *current = Some(AllocFramePtr(frame)); } /// Pushes a physical page. Used during paging initialization. pub unsafe fn init_push_physical_page(addr: PhysAddr) { push_physical_page(addr) } /// Pushes a physical page. unsafe fn push_physical_page(addr: PhysAddr) { let mut current_locked = ALLOC_CURRENT.lock(); let mut current = current_locked.unwrap(); if current.0.as_ref().next_index == current.0.as_ref().elements.len() { let next = current.0.as_ref().next_frame; *current_locked = next; current = next.unwrap(); assert_eq!(current.0.as_ref().next_index, 0); } let current = current.0.as_mut(); current.elements[current.next_index] = addr; current.next_index += 1; } /// Pops a physical page. unsafe fn pop_physical_page() -> KernelResult<PhysAddr> { let mut current_locked = ALLOC_CURRENT.lock(); let mut current = current_locked.unwrap(); if current.0.as_ref().next_index == 0 { let prev = current.0.as_ref().prev_frame; if prev.is_none() { return Err(KernelError::OutOfMemory); } *current_locked = prev; current = prev.unwrap(); assert_eq!( current.0.as_ref().next_index, current.0.as_ref().elements.len() ); } let current = current.0.as_mut(); current.next_index -= 1; let addr = current.elements[current.next_index]; Ok(addr) } /// An owned, typed reference to a page. #[repr(transparent)] pub struct KernelPageRef<T>(NonNull<T>); #[repr(transparent)] pub struct UniqueKernelPageRef<T>(KernelPageRef<T>); unsafe impl<T: Send> Send for KernelPageRef<T> {} unsafe impl<T: Sync> Sync for KernelPageRef<T> {} impl<T> Clone for KernelPageRef<T> { fn clone(&self) -> Self { let phys = PhysAddr::from_phys_mapped_virt(VirtAddr::from_nonnull(self.0)).unwrap(); unsafe { inc_refcount(phys); } KernelPageRef(self.0) } } impl<T> KernelPageRef<T> { pub fn new(inner: T) -> KernelResult<Self> { assert!(size_of::<T>() <= PAGE_SIZE); let phys = unsafe { pop_physical_page()? }; unsafe { inc_refcount(phys); } let virt = VirtAddr::from_phys(phys); let ptr = virt.as_nonnull().unwrap(); unsafe { core::ptr::write(ptr.as_ptr(), inner); Ok(KernelPageRef(ptr)) } } pub fn new_uninit() -> KernelResult<MaybeUninit<Self>> { assert!(size_of::<T>() <= PAGE_SIZE); let phys = unsafe { pop_physical_page()? }; unsafe { inc_refcount(phys); } let virt = VirtAddr::from_phys(phys); let ptr = virt.as_nonnull().unwrap(); Ok(MaybeUninit::new(KernelPageRef(ptr))) } pub fn as_nonnull(&mut self) -> NonNull<T> { self.0 } pub fn into_raw(me: KernelPageRef<T>) -> NonNull<T> { let result = me.0; core::mem::forget(me); result } pub unsafe fn from_raw(x: NonNull<T>) -> KernelPageRef<T> { KernelPageRef(x) } } unsafe fn inc_refcount(phys: PhysAddr) -> u64 { let metadata = phys.page_metadata().as_nonnull().unwrap(); let metadata: &AtomicU64 = metadata.as_ref(); metadata.fetch_add(1, Ordering::Acquire) } unsafe fn dec_refcount(phys: PhysAddr) -> u64 { let metadata = phys.page_metadata().as_nonnull().unwrap(); let metadata: &AtomicU64 = metadata.as_ref(); metadata.fetch_sub(1, Ordering::Release) } impl<T> Drop for KernelPageRef<T> { fn drop(&mut self) { let phys = PhysAddr::from_phys_mapped_virt(VirtAddr::from_nonnull(self.0)).unwrap(); unsafe { let old_value = dec_refcount(phys); if old_value == 1 { core::ptr::drop_in_place(self.0.as_ptr()); push_physical_page(phys); } else if old_value == 0 { panic!("pagealloc::dec_refcount: old refcount is zero"); } } } } impl<T> Deref for KernelPageRef<T> { type Target = T; fn deref(&self) -> &T { unsafe { self.0.as_ref() } } } impl<T> TryFrom<KernelPageRef<T>> for UniqueKernelPageRef<T> { type Error = KernelError; fn try_from(that: KernelPageRef<T>) -> KernelResult<Self> { unsafe { let phys = PhysAddr::from_phys_mapped_virt(VirtAddr::from_nonnull(that.0)).unwrap(); let metadata = phys.page_metadata().as_nonnull().unwrap(); let metadata: &AtomicU64 = metadata.as_ref(); if metadata.load(Ordering::Relaxed) != 1 { return Err(KernelError::InvalidState); } Ok(UniqueKernelPageRef(that)) } } } impl<T> UniqueKernelPageRef<T> { pub fn new_uninit() -> KernelResult<MaybeUninit<Self>> { KernelPageRef::new_uninit().map(|x| unsafe { core::mem::transmute::<MaybeUninit<KernelPageRef<T>>, MaybeUninit<UniqueKernelPageRef<T>>>(x) }) } pub fn as_nonnull(&mut self) -> NonNull<T> { self.0.as_nonnull() } } impl<T> From<UniqueKernelPageRef<T>> for KernelPageRef<T> { fn from(that: UniqueKernelPageRef<T>) -> KernelPageRef<T> { that.0 } } impl<T> Deref for UniqueKernelPageRef<T> { type Target = T; fn deref(&self) -> &T { unsafe { (self.0).0.as_ref() } } } impl<T> DerefMut for UniqueKernelPageRef<T> { fn deref_mut(&mut self) -> &mut T { unsafe { (self.0).0.as_mut() } } }
Markdown
UTF-8
634
2.890625
3
[]
no_license
# FizzBuzz-TDD iOS app of FizzBuzz game built in TDD The aim of the game is to count up as high as you can, starting at 0. - If the next number is a multiple of 3, tap the “Fizz” button. - If the next number is a multiple of 5, tap the “Buzz” button. - If the next number is a multiple of 3 AND 5, tap the “FizzBuzz” button. - Else tap the number button <p align="center"> <img height="500" src="https://raw.githubusercontent.com/ludwig-pro/FizzBuzz-TDD/master/Capture%20d%E2%80%99%C3%A9cran%202020-04-06%20%C3%A0%2000.52.51.png"> </p> tutorial : https://medium.com/@ynzc/getting-started-with-tdd-in-swift-2fab3e07204b
Python
UTF-8
1,378
2.5625
3
[]
no_license
import rospy from geometry_msgs.msg import Twist, Point, Quaternion #import tf #from math import math,radians, copysign, sqrt, pow, pi, atan2 #from tf.transformations import euler_from_quaternion #import numpy as np import sys import time import math class Run(): def __init__(self): prog_start_time = time.time() rospy.init_node('turtlebot3_pointop_key', anonymous=False) self.cmd_vel = rospy.Publisher('cmd_vel', Twist, queue_size=5) position = Point() move_cmd = Twist() angular_dist = float(sys.argv[1]) move_cmd.linear.x = 0.0 move_cmd.angular.z = 0.0 init_speed=0.8 self.cmd_vel.publish(move_cmd) if angular_dist > 0.0: move_cmd.angular.z = init_speed elif angular_dist == 0: move_cmd.angular.z = 0.0 else: move_cmd.angular.z = -init_speed delay_angle = math.radians(abs(angular_dist))/init_speed start_time = time.time() print("delay_angle", delay_angle) time.sleep(0.03) while time.time()-start_time < delay_angle: self.cmd_vel.publish(move_cmd) time.sleep(0.03) move_cmd.linear.x = 0.0 move_cmd.angular.z = 0.0 self.cmd_vel.publish(move_cmd) print("TOTAL TIME: ",time.time()-start_time) if __name__ == '__main__': Run()
PHP
UTF-8
675
3.1875
3
[]
no_license
<?php namespace Report\Model; class DimensionsModel implements DimensionsModelInterface { protected $dimensionsList = []; protected $allowed = [ 'dateFrom', 'dateTo', ]; /** * add * * @param string $name * @throws \InvalidArgumentException */ public function add($name) { if (!is_string($name) || !in_array($name, $this->allowed)) { throw new \InvalidArgumentException('invalid dimension'); } $this->dimensionsList[] = $name; } /** * get * * @return string[] */ public function get() { return $this->dimensionsList; } }
C++
UTF-8
1,114
2.625
3
[]
no_license
#ifndef _CAPP_H_ #define _CAPP_H_ #include "CEvent.h" #include "CMenu.h" #include "CCore.h" class CApp : public CEvent { private: bool Running; bool Paused; SDL_Window* Win_Display; // Main Window SDL_Renderer* Win_Renderer; // Main Renderer SDL_Texture* Win_Texture; // Canvas Texture public: CApp(); int OnExecute(); public: // Initializes SDL, main window and renderer, and test/introductory graphics bool OnInit(); // Handles non-motion events from the user void OnEvent(SDL_Event* Event); // Terminates the application loop void OnExit(); // Handles app. manipulations and calculations in runtime void OnLoop(); // Renders graphics void OnRender(); void ClearTexture(); // Destroys all windows, textures, surfaces, renderers... void OnCleanup(); void OnKeyDown(SDL_Keycode sym, Uint16 mod); void OnKeyUp(SDL_Keycode sym, Uint16 mod); bool Lclick; bool Rclick; void OnLButtonDown(int mX, int mY); void OnLButtonUp(int mX, int mY); void OnRButtonDown(int mX, int mY); void OnRButtonUp(int mX, int mY); }; #endif
Python
UTF-8
941
2.640625
3
[ "MIT" ]
permissive
import shutil import skflow from sklearn import datasets, metrics, cross_validation iris = datasets.load_iris() X_train, X_test, y_train, y_test = cross_validation.train_test_split(iris.data, iris.target, train_size=0.2, random_state=42) classifier = skflow.TensorFlowDNNClassifier(hidden_units=[10,20,30,20,10], n_classes=3, steps=100000, learning_rate=0.01) classifier.fit(X_train, y_train) score = metrics.accuracy_score(classifier.predict(X_test), y_test) print('Accuracy: {0:f}'.format(score)) # Clean checkpoint folder if exists try: shutil.rmtree('./models/iris_custom_model') except OSError: pass # Save model, parameters and learned variables. classifier.save('./models/iris_custom_model') classifier = None ## Restore everything new_classifier = skflow.TensorFlowEstimator.restore('./models/iris_custom_model') score = metrics.accuracy_score(y_test, new_classifier.predict(X_test)) print('Accuracy: {0:f}'.format(score))
Python
UTF-8
1,736
2.921875
3
[]
no_license
""" Intersect multiple community partitions into a single partition. Communities in this "intersection partition" are the collections of people who were categorized into the same community in all input partitions. """ import argparse import collections import networkit as nk import graph_tools import utils parser = argparse.ArgumentParser() parser.add_argument("graph") parser.add_argument("in_communities", nargs="+") parser.add_argument("--out-communities") args = parser.parse_args() utils.log("Reading graph") G, names_db = graph_tools.load_graph_nk(args.graph) utils.log(f"Loaded graph with {G.numberOfNodes():_} nodes / {G.numberOfEdges():_} edges") utils.log(f"Reading {len(args.in_communities)} partitions") partitions = [nk.community.readCommunities(community_file) for community_file in args.in_communities] utils.log("Calculating the intersection of all partitions") intersect_partition = collections.defaultdict(list) node2comm = {} for node in G.iterNodes(): all_comms = [partition[node] for partition in partitions] intersect_name = ",".join(str(comm) for comm in all_comms) node2comm[node] = intersect_name intersect_partition[intersect_name].append(node) utils.log(f"Found {len(intersect_partition)} partition intersections") utils.log("Sorting intersections by size") size_part = [(len(nodes), name) for (name, nodes) in intersect_partition.items()] size_part.sort(reverse=True) name2index = {name: index for (index, (_, name)) in enumerate(size_part)} utils.log("Writing intersections") with open(args.out_communities, "w") as f: for node in G.iterNodes(): comm_name = node2comm[node] comm_index = name2index[comm_name] f.write(f"{comm_index}\n") utils.log("Finished")
C++
UTF-8
1,399
3.3125
3
[]
no_license
//Source code do curso Algoritmos com C++ por Fabio Galuppo //Ministrado em 2021 na Agit - https://www.agit.com.br/cursoalgoritmos.php //Fabio Galuppo - http://member.acm.org/~fabiogaluppo - fabiogaluppo@acm.org //Maio 2021 #ifndef SORTING_HEAPSORT_HPP #define SORTING_HEAPSORT_HPP #include "dynamic_array.hpp" #include <vector> #include <cstddef> #include <functional> #include <algorithm> namespace sorting_heapsort { namespace internal { template <typename Container, typename Compare> static inline void heapsort(Container& xs, Compare comp) { if (xs.size() > 1) { using ptr_type = typename Container::pointer; ptr_type beg_ptr = &xs[0]; ptr_type end_ptr = beg_ptr + xs.size(); std::make_heap(beg_ptr, end_ptr, comp); while (beg_ptr != end_ptr) { std::pop_heap(beg_ptr, end_ptr, comp); --end_ptr; } } } } template <typename T> static inline void heapsort(std::vector<T>& xs) { internal::heapsort(xs, std::less<T>()); } template <typename T> static inline void heapsort(dynamic_array::dynamic_array<T>& xs) { internal::heapsort(xs, std::less<T>()); } } #endif /* SORTING_HEAPSORT_HPP */
TypeScript
UTF-8
3,339
3.015625
3
[]
no_license
import { Pirate } from "./pirate"; export class PirateShip { name: string; pirateCrew: Pirate[]; captain: Pirate; constructor(name: string) { this.name = name; } public fillShip() { this.captain = new Pirate(`Captain ${this.name}`, true); let randomNum = Math.floor(Math.random() * Math.floor(9)) + 1; this.pirateCrew = []; for (let i = 0; i <= randomNum; i++) { this.pirateCrew.push(new Pirate(`${this.name} Pirate #${i + 1}`, false)); } } public shipInformations() { if (this.captain == undefined) { console.log(`The ${this.name} ship has no captain nor crew.`) } else { if (this.captain.isDead) { console.log(`${this.captain.name} is dead, he consumed ${this.captain.intoxication} rum.`) } else if (this.captain.isPassedOut) { console.log(`${this.captain.name} has passed out, he consumed ${this.captain.intoxication} rum.`) } else { console.log(`${this.captain.name} is alive, and he consumed ${this.captain.intoxication} rum.`) } let alivePirateNum: number = this.alivePirateCounter(); let drunkPirateNum: number = this.drunkPirateCounter(); let deadPirateNum: number = this.deadPirateCounter(); console.log(`Out of ${this.pirateCrew.length} pirates, ${alivePirateNum} can work, ${drunkPirateNum} are drunk, ${deadPirateNum} are dead.`) } } public battle(otherShip: PirateShip): boolean { let scoreShip: number = this.alivePirateCounter() - this.captain.intoxication; let scoreOtherShip: number = otherShip.alivePirateCounter() - otherShip.captain.intoxication; if (scoreShip > scoreOtherShip) { this.battleResolutions(this, otherShip); return true; } else { this.battleResolutions(otherShip, this); return false; } } public battleResolutions(winnerShip: PirateShip, loserShip: PirateShip) { loserShip.killingPirates(); loserShip.wakingPirates(); winnerShip.winningParty(); winnerShip.wakingPirates(); } public alivePirateCounter(): number { let alivePirateNum: number = 0; this.pirateCrew.forEach(x => x.isDead || x.isPassedOut ? 0 : alivePirateNum++); return alivePirateNum; } public drunkPirateCounter(): number { let drunkPirateNum: number = 0; this.pirateCrew.forEach(x => x.isPassedOut ? drunkPirateNum++ : 0); return drunkPirateNum; } public deadPirateCounter() { let deadPirateNum: number = 0; this.pirateCrew.forEach(x => x.isDead ? deadPirateNum++ : 0); return deadPirateNum; } public killingPirates() { let randomNumDeath: number = Math.floor(Math.random() * Math.floor(this.pirateCrew.length)); for (let i = 0; i < randomNumDeath + 1; i++) { this.pirateCrew[i].die(); } } public wakingPirates() { this.pirateCrew.forEach(x => x.isPassedOut ? x.wakeUpPirate() : 0); } public winningParty() { let randomRumCap: number = Math.floor(Math.random() * Math.floor(2)); for (let i = 0; i <= randomRumCap; i++) { this.captain.drinkSomeRum(); } let alivePirates: number = this.alivePirateCounter(); for (let i = 0; i < alivePirates; i++) { for (let j = 0; j <= Math.floor(Math.random() * Math.floor(2)); j++) { this.pirateCrew[i].drinkSomeRum(); } } } }
Shell
UTF-8
3,887
3.84375
4
[]
no_license
#!/bin/bash # mp - makepkg package building tasks # Activate debugging #set -x # Get local version and AUR version #aur_version() { # wget -q -O- "http://aur.archlinux.org/rpc.php?type=info&arg=${1}" | sed 's/.*"Version":"\([^"]*\)".*/\1/') #} #local_version() { # pacman -Q ${1} | cut -d\ -f2 #} # Text color variables txtbld=$(tput bold) # bold txtund=$(tput sgr 0 1) # underline bldblu='\e[1;34m' # blue bldred='\e[1;31m' # red bldwht='\e[1;37m' # white txtrst='\e[0m' # text reset info=${bldwht}*${txtrst} pass=${bldblu}*${txtrst} warn=${bldred}!${txtrst} # Add md5sums following source array in PKGBUILD md5add () { # Delete previous md5sum entries sed -i "/^.*'[a-z0-9]\{32\}'.*$/d" PKGBUILD sed -i "/^md5sums/,/$/d" PKGBUILD # Save then delete the build section sed -e '/^build().*$/,$!d' PKGBUILD > /tmp/PKGBUILD.tmp sed -i '/^build().*$/,$d' PKGBUILD # Remove trailing blank lines so md5sums line follows last line while [ "$(tail -n 1 PKGBUILD)" == "" ]; do sed -i '$d' PKGBUILD done # Add md5sums makepkg -g >> PKGBUILD # Add two blank lines to seperate variable and build section echo -e "\n" >> PKGBUILD # Re-append build section cat /tmp/PKGBUILD.tmp >> PKGBUILD # Remove trailing blank lines to clean up while [ "$(tail -n 1 PKGBUILD)" == "" ]; do sed -i '$d' PKGBUILD done } # Options case $1 in p ) if [ ! -f ./PKGBUILD ]; then echo -e "$warn No PKGBUILD in directory. (${txtund}$(pwd)${txtrst})" exit; else makepkg -sf # Move package to cache pkgname=$(grep "^pkgname" PKGBUILD | awk -F = '{ printf $2 }') pkgver=$(grep "^pkgver" PKGBUILD | awk -F = '{ printf $2 }') pkgrel=$(grep "^pkgrel" PKGBUILD | awk -F = '{ printf $2 }') pkgarchive=$pkgname-$pkgver-$pkgrel-$(arch).pkg.tar.gz pkglocdir="/var/cache/pacman/pkg-local/" if [ -f $pkgarchive ]; then cp $pkgarchive $pkglocdir echo -e "$pass Copying built package to cache" fi fi ;; r ) if [ ! -f ./PKGBUILD ]; then echo -e "$warn No PKGBUILD in directory. (${txtund}$(pwd)${txtrst})" exit; else if [ -d src ]; then rm -rf src/; fi makepkg -sf fi ;; s ) if [ ! -f ./PKGBUILD ]; then echo -e "$warn No PKGBUILD in directory. (${txtund}$(pwd)${txtrst})" exit 1; else echo "adding md5sums" md5add # sed -i '/^md5sums/,/).*$/d' PKGBUILD # makepkg -g >> PKGBUILD # sed -i 's/^md5sums/md5sums/' PKGBUILD # Add newline after md5sum # sed -i 's/\(^md5sums.*\)/\1\n/g' PKGBUILD # Add line before build line # sed -i 's/^\(build.*\)/\n&/g' PKGBUILD # Add line, two lines above 'build' line (works, haven't implement try) #sed '1{x;d};$H;/build/{x;s/^/\n/;b};x' PKGBUILD makepkg -f --source fi ;; t ) shift builddir=/var/abs/local/personal/ [ ! -d $builddir ] && mkdir -p $builddir echo $builddir cd $builddir [ -d "$@" ] && echo " package name already exists" && exit mkdir "$@" [ ! -f PKGBUILD.proto ] && cp /usr/share/pacman/PKGBUILD.proto . && \ echo "Using original PKGBUILD.proto (no template found in directory" cp PKGBUILD.proto "$@"/PKGBUILD sed -i "s/pkgname=.*/pkgname="$@"/" "$@"/PKGBUILD ;; h ) # Display help echo " ${0##*/} <option> - makepkg building tasks:" echo " p - build package (also installs dependencies)" echo " r - refresh (same ^ but remove src directory)" echo " s - build source-only tarball (adds md5sums, tars for submission)" echo " t <pkg-name> - create new PKGBUILDcopy PKGBUILD (t)emplate to current folder" exit ;; * ) makepkg "$@" ;; esac
Markdown
UTF-8
1,861
2.90625
3
[]
no_license
# About This was written in 2020 in response to the COVID19 pandemic making my haptics robotics course going virtual. hapticAlt acts as a dummy api for source code intended for the OpenHaptics platform / Phantom Omni haptic device. This repo allows the user to define their own haptic rendering in the "hapticCallback()" function of hapticAlt.cpp. The mouse position is tracked in the 2d plane of the screen (0,0 defined in top left corner, increasing right and down), and the velocity / acceleration are found through backwards differentiation (if used, some moving average or other filter can be implemented for smoothing). This repo was intentionaly kept as simple as possible with no external libraries and as few source files as possible to avoid installation problems for users unfamiliar with C++. The active plane can be swapped between XY, XZ, and ZY with the left and right arrow keys. Pseudo haptic feedback applied to the mouse can be enabled / disabled with 'T'. # Demo Functions There are two demo functions: hapticCallbackDampingPlaneFieldDemo() and hapticCallbackSphereDemo(). These demo functions can be tested in place of the standard hapticCallback call. To do so, change the "std::thread hapticRenderThread(hapticCallback);" call in main() to call one of the above demo functions. The hapticCallbackDampingPlaneFieldDemo() is shown below. Note the external forces (primarily in the y direction) are applied to the mouse when haptic feedback is enabled, pushing the mouse up on the screen in the beginning of the gif. Note that the primary force in this example is the reaction force of a horizontal xz plane, so when we change the operating plane to XZ the HIP is pushed out of the plane in the y axis and no further forces are applied to the mouse even when haptic feedback is set to 1 (true). ![hapticAlt demo](img/demo.gif)
Java
UTF-8
2,690
2.75
3
[]
no_license
package fi.tuni.cezaro; import fi.tuni.cezaro.exception.CredentialAcceptedExcepion; import fi.tuni.cezaro.exception.InvalidCredentialsException; import fi.tuni.cezaro.exception.UserNotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.annotation.PostConstruct; import javax.validation.ConstraintViolationException; /** * RestController to handle creating and deleting User entity from database. * Handles frontend fetch request of login and returns Exception if user Credentials was accepted. * * Uses UserRepository class for handling Entity User table. * * @author Saku Tynjala saku.tynjala@tuni.fi * @author Mikko Mustasaari mikko.mustasaari@tuni.fi * @version 0.3 * @since 0.3 */ @RestController public class UserController { @Autowired UserReporistory userRepo; /** * PostConstruct method for populating 2 user to database. */ @PostConstruct public void loadData() { userRepo.save(new User("Mikko", "admin1")); userRepo.save(new User("Saku", "admin2")); } /** * Login method for comparing given Json format of user to User table entities and * returns exception if user was found, credentials was accepted or not. * * @param user to be logged in to application. */ @RequestMapping(value = "/login", method = RequestMethod.POST) public void userLogin(@RequestBody User user) throws CredentialAcceptedExcepion, InvalidCredentialsException { if(userRepo.findByUserName(user.getUserName()).isPresent()) { User login = userRepo.findByUserName(user.getUserName()).get(); if (login.getPassword().equals(user.getPassword())) { throw new CredentialAcceptedExcepion(); } else { throw new InvalidCredentialsException(); } } else{ throw new UserNotFoundException(); } } /** * User creation method for adding user to database by given Json format of user. * Returns Exception based if user was added to database and Credentials was ok or * if attributes caused ConstraintViolationException and returns IncalidCredentialsException. * * @param user to be added in database. */ @RequestMapping(value = "/addUser", method = RequestMethod.POST) public void AddUser(@RequestBody User user) { try { userRepo.save(new User(user.getUserName(), user.getPassword())); throw new CredentialAcceptedExcepion(); }catch (ConstraintViolationException e){ throw new InvalidCredentialsException(); } } }
Markdown
UTF-8
339
2.546875
3
[]
no_license
Differences between class method and instance method: You should use Class Methods when the functionality you are writing does not belong to an instance of that class. ENV: it's some sort of way of storing information about the current operating environment. We can use it to inform our program as to which environment it's operating in.
Java
UTF-8
456
2.421875
2
[ "MIT" ]
permissive
package northwind.jpamodel; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class NextId { private String name; private long nextId; @Id @Column(length=50) public String getName() { return name; } public void setName(String name) { this.name = name; } public long getNextId() { return nextId; } public void setNextId(long nextId) { this.nextId = nextId; } }
Java
UTF-8
3,162
2.109375
2
[]
no_license
package com.intuit.billingcomm.billing.qbeshosting.jms; import com.intuit.billingcomm.billing.qbeshosting.TestHelpers; import com.intuit.billingcomm.billing.qbeshosting.exception.IncompleteEventException; import com.intuit.billingcomm.billing.qbeshosting.exception.UnsupportedEventException; import com.intuit.billingcomm.billing.qbeshosting.model.HostingSubscriptionEvent; import com.intuit.billingcomm.billing.qbeshosting.service.MessageParsingService; import com.intuit.billingcomm.billing.qbeshosting.service.SubscriptionService; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.messaging.Message; import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) public class SubscriptionEventListenerTest { @InjectMocks private SubscriptionEventListener listener; @Mock private MessageParsingService messageParsingService; @Mock private SubscriptionService subscriptionService; @Test public void receive_ValidMessage_Success() throws Exception { Message<String> message = TestHelpers.generateValidSubscriptionMessage(); HostingSubscriptionEvent event = TestHelpers.generateSubscriptionEvent(); Mockito.when(messageParsingService.parseMessage(message)).thenReturn(event); listener.receive(message); verify(subscriptionService, times(1)).processEvent(event); } @Test public void receive_UnsupportedMessage_Ignored() throws Exception { Message<String> message = TestHelpers.generateUnsupportedMessage(); Mockito.when(messageParsingService.parseMessage(message)).thenThrow(UnsupportedEventException.class); listener.receive(message); verify(subscriptionService, never()).processEvent(any(HostingSubscriptionEvent.class)); } @Test public void receive_IncompleteEvent_Ignored() throws Exception { Message<String> message = TestHelpers.generateUnsupportedMessage(); Mockito.when(messageParsingService.parseMessage(message)).thenThrow(IncompleteEventException.class); listener.receive(message); } @Test public void receive_IllegalArgument_NoExceptionRethrown() throws Exception { Message<String> message = TestHelpers.generateUnsupportedMessage(); Mockito.doThrow(IllegalArgumentException.class).when(subscriptionService).processEvent(any()); listener.receive(message); } @Test public void receive_IllegalState_NoExceptionRethrown() throws Exception { Message<String> message = TestHelpers.generateUnsupportedMessage(); Mockito.doThrow(IllegalStateException.class).when(subscriptionService).processEvent(any()); listener.receive(message); } @Test(expected = Exception.class) public void receive_RethrowException() throws Exception { Message<String> message = TestHelpers.generateValidSubscriptionMessage(); Mockito.doThrow(Exception.class).when(subscriptionService).processEvent(any()); listener.receive(message); } }
Markdown
UTF-8
294
2.671875
3
[]
no_license
## Automated Amazon Price Tracker Check the price of a product on Amazon and notify the user through email, if it falls below a certain value. ### Keywords: * Webscraping * HTTP requests * SMTP (Simple Mail Transfer Protocol) ### Course: "100 Days of Code" by Dr. Angela Yu ### Coded by: Jacob Rymsza
Python
UTF-8
254
2.890625
3
[]
no_license
# city = "Banglore" # # # # assert city == "Bangalore" import browser.openChrome as op op.driver.get("https://www.google.com") pageTitle = op.driver.title print(pageTitle) # actual === excepted assert pageTitle == "Facebook" op.driver.quit()
JavaScript
UTF-8
641
2.671875
3
[]
no_license
const axios = require('axios'); const getLugarLatLong = async( direccion ) => { const encodedURL = encodeURI(direccion); const instance = axios.create({ baseURL: `https://devru-latitude-longitude-find-v1.p.rapidapi.com/latlon.php?location=${ encodedURL }`, headers: { 'X-RapidAPI-Key': 'ee57b125f5mshe92629e07120271p18263ajsnf447673c1d7d' } }); const resp = await instance.get(); const data = resp.data.Results; const { name, lat, lon } = data[0]; if( data.length === 0) throw new Error(`No hay resultados para ${ direccion }`); return { name, lat, lon } } module.exports = { getLugarLatLong }
Java
UTF-8
2,872
3.140625
3
[]
no_license
package training.printing; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by sczerwinski on 2015-04-27. */ public class Printer<T extends ICartridge> implements Imachine {//extends Machine { private String modelNumber; private PaperTray paperTray = new PaperTray(); private Machine machine; private T cartridge; private List<Page> pages = new ArrayList<Page>(); private Map<Integer,Page> pagesMap = new HashMap<Integer, Page>(); public Printer(boolean isOn, String modelNumber,T cartridge) { //super(isOn); machine = new Machine(isOn); this.modelNumber = modelNumber; this.cartridge=cartridge; } @Override public boolean isOn() { return machine.isOn(); } public void print(int copies) { checkCopies(copies); System.out.println(cartridge.toString()); String onStatus = ""; if (machine.isOn()) onStatus = " is on!"; else onStatus = " is off!"; String textToPrint = modelNumber + onStatus; int pageNumber=1; while (copies > 0 && !paperTray.isEmpty()) { // System.out.println(textToPrint); // pages.add(new Page(textToPrint)); pagesMap.put(pageNumber,new Page(textToPrint + ":" + pageNumber)); copies--; paperTray.usePage(); pageNumber++; } if (paperTray.isEmpty()){ System.out.println("Load more paper"); } } //List public void outputPages(){ for (Page currentPage:pages){ System.out.println(currentPage.getText()); } } //Map public void outputPage(int pageNumber){ System.out.println(pagesMap.get(pageNumber).getText()); } private void checkCopies(int copies) { if (copies<=0){ throw new IllegalArgumentException ("Cannot print negative or 0 value of copies"); } } @Override public void turnOn() { // System.out.println("Warming up print engine"); //super.turnOn(); machine.turnOn(); } @Override public void turnOff() { // System.out.println("Turned off"); machine.turnOff(); } public void printColors(){ String[] colors = new String[]{"Red"}; for (String currentColor:colors){ System.out.println("Color: "+currentColor); } } public void loadPaper(int i) { paperTray.addPages(i); } public <U extends ICartridge> void printUsingCartridge(U cartridge, String message){ System.out.println(cartridge.toString()); System.out.println(message); System.out.println(cartridge.getFillPercentage()); } public T getCartridge() { return cartridge; } }
Java
UTF-8
856
2.84375
3
[ "MIT" ]
permissive
class Solution { public int removed = 0; public int deleteTreeNodes(int nodes, int[] parent, int[] value) { List<Integer> [] tree = new ArrayList[nodes]; for(int i = 0; i < nodes; ++i) tree[i] = new ArrayList<>(); for(int i = 0; i < nodes; ++i) { if (parent[i] != -1) tree[parent[i]].add(i); } removed = 0; postOrder(tree, value, 0); return nodes - removed; } private int[] postOrder(List<Integer>[] tree, int [] value, int node) { int count = 1, sum = value[node]; for(int child : tree[node]) { int [] p = postOrder(tree, value, child); count += p[0]; sum += p[1]; } if (sum == 0) { removed += count; count = 0; } return new int[] {count, sum}; } }
Java
UTF-8
881
2.671875
3
[]
no_license
package net.rainmore.platform.core.services.fixtures; import net.rainmore.platform.core.models.Person; import org.apache.commons.lang3.RandomStringUtils; import org.joda.time.LocalDate; import org.thymeleaf.util.StringUtils; import java.util.Random; public class PersonFixture { public Person getOne() { Person person = new Person(); person.setFirstName(StringUtils.capitalize(RandomStringUtils.randomAlphabetic(6))); person.setLastName(StringUtils.capitalize(RandomStringUtils.randomAlphabetic(9))); person.setDateOfBirth(dateOfBirth()); return person; } private LocalDate dateOfBirth() { Random random = new Random(); int month = random.nextInt(12) + 1; int year = random.nextInt(50) + 1; LocalDate date = LocalDate.now().minusMonths(month).minusYears(year); return date; } }
Java
UTF-8
993
2.34375
2
[]
no_license
package com.example.springhibernate_23_01_2020; import javax.annotation.Generated; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.Email; import org.hibernate.validator.constraints.Length; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter @NoArgsConstructor @Entity @Table(name = "USERDETAIL") public class UserDetail { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String uid; @Length(min = 5, max = 8) private String name; @Email(message = "Invalid Email") private String email; public UserDetail(String uid, String name, String email) { super(); this.uid = uid; this.name = name; this.email = email; } @Override public String toString() { return "UserDetail [id=" + id + ", uid=" + uid + ", name=" + name + ", email=" + email + "]"; } }
C++
UTF-8
1,479
3.421875
3
[]
no_license
#include "vred.hpp" #include "vect.hpp" Vect::Vect(const float x, const float y, const float z): x(x), y(y), z(z) { } float Vect::operator[](const int n) const { switch (n) { case 0: return x; case 1: return y; default: return z; // TODO: if (n >= 3) raise Exception; } } float& Vect::operator[](const int n) { switch (n) { case 0: return x; case 1: return y; default: return z; // TODO: if (n >= 3) raise Exception; } } Vect Vect::operator+(const Vect& v) const { return Vect(x + v.x, y + v.y, z + v.z); } Vect& Vect::operator+=(const Vect& v) { x += v.x; y += v.y; z += v.z; return *this; } Vect Vect::operator-(const Vect& v) const { return Vect(x - v.x, y - v.y, z - v.z); } Vect& Vect::operator-=(const Vect& v) { x -= v.x; y -= v.y; z -= v.z; return *this; } float Vect::operator*(const Vect& v) const { return (x * v.x + y * v.y + z * v.z); } Vect Vect::operator^(const Vect& v) const { return Vect(y * v.z -z * v.y, z * v.x - x * v.z, x * v.y - x * v.y); } void Vect::print() const { cout << "(" << x << ", " << y << ", " << z << ")" << endl; } Vect operator*(const float d, const Vect& v) { return Vect(d * v.x, d * v.y, d * v.z); } Vect& Vect::operator*=(float d) { x *= d; y *= d; z *= d; return *this; } bool Vect::operator==(const Vect& v) const { return ((x == v.x) && (y == v.y) && (z == v.z)); } const Vect Vect::null(0.0, 0.0, 0.0); const Vect Vect::unit(1.0, 1.0, 1.0);
Python
UTF-8
344
4.0625
4
[]
no_license
thisset = {"apple", "banana", "cherry"} thisset.remove("cherry") print(thisset) # Note: If the item to remove does not exist, remove() will raise an error. # You can also use the pop(), method to remove an item, but this method will remove the last item. # Remember that sets are unordered, so you will not know what item that gets removed.
C
UTF-8
1,390
3.359375
3
[ "Apache-2.0" ]
permissive
#include "openlibc/queue.h" /* * find the middle queue element if the queue has odd number of elements * or the first element of the queue's second part otherwise */ olc_queue_t * olc_queue_middle(olc_queue_t *queue) { olc_queue_t *middle, *next; middle = olc_queue_head(queue); if (middle == olc_queue_last(queue)) { return middle; } next = olc_queue_head(queue); for ( ;; ) { middle = olc_queue_next(middle); next = olc_queue_next(next); if (next == olc_queue_last(queue)) { return middle; } next = olc_queue_next(next); if (next == olc_queue_last(queue)) { return middle; } } } /* the stable insertion sort */ void olc_queue_sort(olc_queue_t *queue, olc_int_t (*cmp)(const olc_queue_t *, const olc_queue_t *)) { olc_queue_t *q, *prev, *next; q = olc_queue_head(queue); if (q == olc_queue_last(queue)) { return; } for (q = olc_queue_next(q); q != olc_queue_sentinel(queue); q = next) { prev = olc_queue_prev(q); next = olc_queue_next(q); olc_queue_remove(q); do { if (cmp(prev, q) <= 0) { break; } prev = olc_queue_prev(prev); } while (prev != olc_queue_sentinel(queue)); olc_queue_insert_after(prev, q); } }
C++
UTF-8
1,490
2.953125
3
[ "MIT" ]
permissive
#pragma once #ifndef ALGORITHM_MOVE_H #define ALGORITHM_MOVE_H // =================================================================================================================== // Includes // =================================================================================================================== #include <vector> #include "Globals.h" CORE_NAMESPACE_BEGIN // =================================================================================================================== // Class // This class is used as a linked list for queueing up possible moves when trying to obtain a complete solution. // A custom class is used to allow more flexibility with implementation. // =================================================================================================================== class AlgorithmMove { public: AlgorithmMove(int iValue); ~AlgorithmMove(void); int mValue; // Value associated with the move AlgorithmMove* mNextMove; // Next move to be tried private: AlgorithmMove(const AlgorithmMove& src); // Disabled copy constructor AlgorithmMove& operator=(const AlgorithmMove& rhs); // Disabled assignment operator }; // =================================================================================================================== // End // =================================================================================================================== CORE_NAMESPACE_END #endif
Markdown
UTF-8
1,515
2.71875
3
[ "Apache-2.0" ]
permissive
# TETRA Listener - Vagrant template This repository provides setup script to get [tetra-listener](https://github.com/itds-consulting/tetra-listener) up and running using Vagrant virtual environment manager ## Install Dependencies 1. Vagrant 1.6 and later 2. VMware Workstation or VMware Fusion (VirtualBox has been tested, but has performance problems) 3. Vagrant VMware plugins (see https://www.vagrantup.com/docs/vmware/installation.html) - `vagrant plugin install vagrant-vmware-fusion` - or `vagrant plugin install vagrant-vmware-workstation` ## Usage 1. `git clone https://github.com/itds-consulting/tetra-listener-vagrant` 2. `cd tetra-listener-vagrant` 3. edit `Vagrantfile` and change number of CPUs and allocated Memory if you have plenty 4. `vagrant up --provider vmware_fusion` (or `vmware_workstation`, depending on what you do have installed) - `vagrant up --provider virtualbox` if you want to try if your VirtualBox is better 5. wait for install to be finished (depending on your machine performance can take up to few hours) 6. `vagrant ssh` (to login into machine) 7. `tetra-listener` will be installed and ready to use in folder `/root/tetra-listener/` ## Access - username: vagrant / password: vagrant - enabled with sudo permissions (simply type sudo bash to get root shell) - mysql user: root (or tetra) / password: tetra ## Tetra-Listener documentation See repository https://github.com/itds-consulting/tetra-listener for documentation
Python
UTF-8
266
3.328125
3
[]
no_license
#python PAM while True: password=input("Enter password: ") if any(i.isdigit() for i in password) and any(i.upper() for i in password) and len(password) >= 5: print("Password is fine") break else: print("Password is not fine")
C
UTF-8
1,647
3.15625
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* helpers.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ghorvath <ghorvath@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/06/13 12:28:34 by ghorvath #+# #+# */ /* Updated: 2021/06/13 19:33:50 by ghorvath ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_header.h" /* ** FILE COUNTAINS: ft_putchar, ft_putnbr, ft_putstr, ft_strcmp */ void ft_putchar(char c) { write(1, &c, 1); } void ft_putnbr(int nb) { int last; long number; number = nb; if (number < 0) { number = number * (-1); ft_putchar('-'); } if (number >= 10) { last = number % 10; ft_putnbr(number / 10); ft_putchar(last + '0'); } else ft_putchar(number + '0'); } void ft_putstr(char *str) { int i; i = 0; while (str[i] != '\0') ft_putchar(str[i++]); } int ft_strcmp(char *s1, char *s2) { int i; int acc; i = 0; acc = 0; while (s1[i] != '\0') acc += s1[i++]; if (!acc) return (0 - s2[0]); i = 0; while (s1[i] != '\0') { if (s1[i] != s2[i]) return (s1[i] - s2[i]); i++; } return (0); }
Java
UTF-8
4,954
2.453125
2
[]
no_license
package com.example.proiectandroid; import android.os.AsyncTask; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; //----clasa care extrage cursul BNR la momentul curent public class ValutaCurenta extends AsyncTask<URL,Void, InputStream> { InputStream inputStream = null; public static String nodeEur; public static Moneda moneda=new Moneda(); public static String sbuf; @Override protected InputStream doInBackground(URL... urls) { HttpURLConnection connection=null; try { connection= (HttpURLConnection) urls[0].openConnection(); inputStream=connection.getInputStream(); //parsam xml ul pentru a obtine valorile ce trebuie parsareXML(inputStream); InputStreamReader inputStreamReader=new InputStreamReader(inputStream); BufferedReader bufferedReader=new BufferedReader(inputStreamReader); String linie = ""; while((linie = bufferedReader.readLine())!=null) { sbuf+=linie + "\n"; } } catch (IOException e) { e.printStackTrace(); } finally { if (connection!=null) connection.disconnect(); } return inputStream; } public Node getNode(String numeNodCautat,Node parentNode) { if(parentNode.getNodeName().equals(numeNodCautat)) { return parentNode; } NodeList listaCopii=parentNode.getChildNodes(); for(int i=0;i<listaCopii.getLength();i++) { //folosim recursivitatea pentru a cauta printre copiilor nodurilor copiilor,printre descendenti Node nodeCautat=getNode(numeNodCautat,listaCopii.item(i)); if(nodeCautat!=null) { return nodeCautat; } } return null; } //facem aici o metoda deoarece noi parsam si prin copii copiilor lui cube //pana cand ajungem la un textNode verificand daca fiecare copil al copilului lui cube are atributul currency // atunci cand ajungem la textNode inseamna ca nu mai accesa valoarea atributului currency,deoarece text nodurile nu au atirbute //si ca vom prelua continutul,adica textContexnt public static String getAttributeValue(Node nodeCopil, String atributCautat) { try { return ((Element)nodeCopil).getAttribute(atributCautat); } catch (Exception e) { return ""; } } public void parsareXML(InputStream inputStream) { DocumentBuilderFactory documentBuilderFactory=DocumentBuilderFactory.newInstance(); try { DocumentBuilder documentBuilder=documentBuilderFactory.newDocumentBuilder(); //obtinem DOM-ul Document document=documentBuilder.parse(inputStream); //structuram fisierul prin punerea textelor de tip nod sub nodul corespunzator document.getDocumentElement().normalize(); moneda =new Moneda(); //preluare nod radacina ce contine cursurile valutare curent-nodecube //nod parinte Node parentNode=document.getDocumentElement(); Node nodeCube=getNode("Cube",parentNode); if(nodeCube!=null) { nodeEur="Am gasit nodecube"; //parcugerea copiilor NodeList listaCopii=nodeCube.getChildNodes(); for(int i=0;i<listaCopii.getLength();i++) { Node nodeCopil=listaCopii.item(i); nodeEur=nodeCopil.getTextContent(); String tip_moneda=getAttributeValue(nodeCopil,"currency"); if(tip_moneda.equals("EUR")) { moneda.setEUR(Float.parseFloat(nodeCopil.getTextContent())); } if(tip_moneda.equals("GBP")) { moneda.setGBP(Float.parseFloat(nodeCopil.getTextContent())); } if(tip_moneda.equals("USD")) { moneda.setUSD(Float.parseFloat(nodeCopil.getTextContent())); } } } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
C++
UTF-8
1,409
3.5625
4
[]
no_license
// Smallest Positive missing number // https://practice.geeksforgeeks.org/problems/smallest-positive-missing-number/0 #include <bits/stdc++.h> using namespace std; int segregate(int a[], int n) { int j = 0; int i; for (int i = 0; i < n; i++) { if (a[i] <= 0) { swap(a[i], a[j]); j++; } } return j; } int solve(int a[], int n) { //segregate positive and negative int id = segregate(a, n); a = a + id; //separting positive and negative part of array n = n - id; // size of array must be reduced for (int i = 0; i < n; i++) { if (abs(a[i]) - 1 < n) { // if abs(a[i])-1 lies in range if (a[abs(a[i]) - 1] > 0) { a[abs(a[i]) - 1] = -a[abs(a[i]) - 1]; //visiting the particular index } } } int i=0; for (i = 0; i < n; i++) { if (a[i] > 0) { return i + 1; //missing number } } return i + 1; //missing number } using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; int a[n]; for (int i = 0; i < n; i++) cin >> a[i]; int res = solve(a, n); cout << "smallest missing number : " << res << endl; } return 0; } // input sample // //2 // 5 // 1 2 3 4 5 // 5 // 0 -10 1 3 -20
C
UTF-8
1,332
3.765625
4
[]
no_license
/** * Example client program that uses thread pool. */ #include <stdio.h> #include <unistd.h> #include "threadpool.h" struct data { int a; int b; }; void add(void *param) { struct data *temp; temp = (struct data*)param; sleep(3); printf("I add two values %d and %d result = %d\n",temp->a, temp->b, temp->a + temp->b); /*if (temp->a == 0 || temp->b == 0) printf("finish\n"); else { temp->b -= temp->a; add(temp); }*/ } int main(void) { // create some work to do struct data work; work.a = 1; work.b = 1; struct data work1; work1.a = 2; work1.b = 2; struct data work2; work2.a = 3; work2.b = 3; struct data work3; work3.a = 4; work3.b = 4; struct data work4; work4.a = 5; work4.b = 5; struct data work5; work5.a = 6; work5.b = 6; struct data work6; work6.a = 7; work6.b = 7; // initialize the thread pool pool_init(); // submit the work to the queue pool_submit(&add,&work); //sleep(3); pool_submit(&add, &work1); //sleep(3); pool_submit(&add, &work2); pool_submit(&add, &work3); pool_submit(&add, &work4); pool_submit(&add, &work5); pool_submit(&add, &work6); // may be helpful //sleep(3); pool_shutdown(); return 0; }
C++
UTF-8
6,829
2.9375
3
[]
no_license
#ifndef SUMMERENGINE_SEEVENT_H #define SUMMERENGINE_SEEVENT_H ///SE includes: #include <ids/SystemAndManagerIDList.h> #include <utility/Math.h> #include <utility/Typedefs.h> #include <ids/ComponentTypeList.h> namespace se { union event_data //Size is sizeof(Mat4f) which with default precision is 64 bytes { SEchar sechar; SEint seint; SEuint seuint; SEint32 seint32; SEuint64 seuint64; // COMPONENT_TYPE comp_type; // SEfloat sefloat; SEdouble sedouble; // char char_arr[32]; // void* void_ptr; // Vec2i vec2i; Vec3i vec3i; Vec4i vec4i; // Vec2u vec2u; Vec3u vec3u; Vec4u vec4u; // Vec2f vec2f; Vec3f vec3f; Vec4f vec4f; // Mat2f mat2f; Mat3f mat3f; Mat4f mat4f; }; union additional_event_data//Size is sizeof(SEuint64) and/or sizeof(void*). Should be 8 bytes on most platforms. void* varies depending from bitness { SEchar sechar; SEint seint; SEint seint_arr2[2]; SEuint seuint; SEint32 seint32; SEint32 seint32_arr2[2]; SEuint64 seuint64; // COMPONENT_TYPE comp_type; // SEfloat sefloat; SEdouble sedouble; // char char_arr[8]; // void* void_ptr; }; ///Brief: Base for all SE engine's events. ///type: Defines which type the event is. If deriving event doesn't change this, type is se_event_type_Default ///data: union which holds event's primary data. If deriving event doesn't change this, value is 0 ///additional_data: union which holds event's additional data. If deriving event doesn't change this, value is 0 using se_event_type = SEuint64; struct SE_Event { se_event_type type{ 0 }; ///Event's type and group as SEuint64. 32 most significant bits are for types, 32 least significant bits are for groups. See below event_data data{ 0 }; ///This can contain up to 64 bytes worth of data. Types described above additional_event_data additional_data{ 0 }; ///This can contain up to 8 bytes worth of data. Types described above }; namespace event_bits { ///These bits are used one per event group, giving us total of 32 event groups constexpr SEuint64 group_EngineEvents1 = SEuint64_value_1; ///Reserved for EngineEvents1 constexpr SEuint64 group_EngineEvents2 = SEuint64_value_1 << 1; ///Reserved for EngineEvents2 constexpr SEuint64 group_EngineEvents3 = SEuint64_value_1 << 2; ///Reserved for EngineEvents3 constexpr SEuint64 group_EngineEvents4 = SEuint64_value_1 << 3; ///Reserved for EngineEvents4 constexpr SEuint64 group_bit_5 = SEuint64_value_1 << 4; ///NOT YET IN USE constexpr SEuint64 group_bit_6 = SEuint64_value_1 << 5; ///NOT YET IN USE constexpr SEuint64 group_bit_7 = SEuint64_value_1 << 6; ///NOT YET IN USE constexpr SEuint64 group_bit_8 = SEuint64_value_1 << 7; ///NOT YET IN USE constexpr SEuint64 group_bit_9 = SEuint64_value_1 << 8; ///NOT YET IN USE constexpr SEuint64 group_bit_10 = SEuint64_value_1 << 9; ///NOT YET IN USE constexpr SEuint64 group_bit_11 = SEuint64_value_1 << 10; ///NOT YET IN USE constexpr SEuint64 group_bit_12 = SEuint64_value_1 << 11; ///NOT YET IN USE constexpr SEuint64 group_bit_13 = SEuint64_value_1 << 12; ///NOT YET IN USE constexpr SEuint64 group_bit_14 = SEuint64_value_1 << 13; ///NOT YET IN USE constexpr SEuint64 group_bit_15 = SEuint64_value_1 << 14; ///NOT YET IN USE constexpr SEuint64 group_EditorEvents1 = SEuint64_value_1 << 15; ///Reserved for EditorEvents1 constexpr SEuint64 group_EditorEvents2 = SEuint64_value_1 << 16; ///Reserved for EditorEvents2 constexpr SEuint64 group_bit_18 = SEuint64_value_1 << 17; ///NOT YET IN USE constexpr SEuint64 group_bit_19 = SEuint64_value_1 << 18; ///NOT YET IN USE constexpr SEuint64 group_bit_20 = SEuint64_value_1 << 19; ///NOT YET IN USE constexpr SEuint64 group_bit_21 = SEuint64_value_1 << 20; ///NOT YET IN USE constexpr SEuint64 group_bit_22 = SEuint64_value_1 << 21; ///NOT YET IN USE constexpr SEuint64 group_bit_23 = SEuint64_value_1 << 22; ///NOT YET IN USE constexpr SEuint64 group_bit_24 = SEuint64_value_1 << 23; ///NOT YET IN USE constexpr SEuint64 group_bit_25 = SEuint64_value_1 << 24; ///NOT YET IN USE constexpr SEuint64 group_bit_26 = SEuint64_value_1 << 25; ///NOT YET IN USE constexpr SEuint64 group_bit_27 = SEuint64_value_1 << 26; ///NOT YET IN USE constexpr SEuint64 group_ToBeSorted = SEuint64_value_1 << 27; ///Reserved for ToBeSortedEvents constexpr SEuint64 group_userEvents1 = SEuint64_value_1 << 28; ///Reserved for UserEvents1 constexpr SEuint64 group_userEvents2 = SEuint64_value_1 << 29; ///Reserved for UserEvents2 constexpr SEuint64 group_userEvents3 = SEuint64_value_1 << 30; ///Reserved for UserEvents3 constexpr SEuint64 group_userEvents4 = SEuint64_value_1 << 31; ///Reserved for UserEvents4 ///These type bits can each be used once in every event group, thus giving us 32*32 (1024) possible different events. constexpr SEuint64 type_bit_1 = SEuint64_value_1 << (0 + 32); constexpr SEuint64 type_bit_2 = SEuint64_value_1 << (1 + 32); constexpr SEuint64 type_bit_3 = SEuint64_value_1 << (2 + 32); constexpr SEuint64 type_bit_4 = SEuint64_value_1 << (3 + 32); constexpr SEuint64 type_bit_5 = SEuint64_value_1 << (4 + 32); constexpr SEuint64 type_bit_6 = SEuint64_value_1 << (5 + 32); constexpr SEuint64 type_bit_7 = SEuint64_value_1 << (6 + 32); constexpr SEuint64 type_bit_8 = SEuint64_value_1 << (7 + 32); constexpr SEuint64 type_bit_9 = SEuint64_value_1 << (8 + 32); constexpr SEuint64 type_bit_10 = SEuint64_value_1 << (9 + 32); constexpr SEuint64 type_bit_11 = SEuint64_value_1 << (10 + 32); constexpr SEuint64 type_bit_12 = SEuint64_value_1 << (11 + 32); constexpr SEuint64 type_bit_13 = SEuint64_value_1 << (12 + 32); constexpr SEuint64 type_bit_14 = SEuint64_value_1 << (13 + 32); constexpr SEuint64 type_bit_15 = SEuint64_value_1 << (14 + 32); constexpr SEuint64 type_bit_16 = SEuint64_value_1 << (15 + 32); constexpr SEuint64 type_bit_17 = SEuint64_value_1 << (16 + 32); constexpr SEuint64 type_bit_18 = SEuint64_value_1 << (17 + 32); constexpr SEuint64 type_bit_19 = SEuint64_value_1 << (18 + 32); constexpr SEuint64 type_bit_20 = SEuint64_value_1 << (19 + 32); constexpr SEuint64 type_bit_21 = SEuint64_value_1 << (20 + 32); constexpr SEuint64 type_bit_22 = SEuint64_value_1 << (21 + 32); constexpr SEuint64 type_bit_23 = SEuint64_value_1 << (22 + 32); constexpr SEuint64 type_bit_24 = SEuint64_value_1 << (23 + 32); constexpr SEuint64 type_bit_25 = SEuint64_value_1 << (24 + 32); constexpr SEuint64 type_bit_26 = SEuint64_value_1 << (25 + 32); constexpr SEuint64 type_bit_27 = SEuint64_value_1 << (26 + 32); constexpr SEuint64 type_bit_28 = SEuint64_value_1 << (27 + 32); constexpr SEuint64 type_bit_29 = SEuint64_value_1 << (28 + 32); constexpr SEuint64 type_bit_30 = SEuint64_value_1 << (29 + 32); constexpr SEuint64 type_bit_31 = SEuint64_value_1 << (30 + 32); constexpr SEuint64 type_bit_32 = SEuint64_value_1 << (31 + 32); }//namespace event_bits }//namespace se #endif
JavaScript
UTF-8
590
2.84375
3
[]
no_license
function createElement(type, props, ...children) { return { type, props: { ...props, children: children.map(child => { // 判断child是对象还是普通的文本 return typeof child === 'object' ? child : createTextElement(child) }) } } } function createTextElement(text) { return { type: "TEXT_ELEMENT", props: { nodeValue: text, children: [] } } } const React = { createElement, createTextElement } export default React
Markdown
UTF-8
2,497
2.71875
3
[ "MIT" ]
permissive
# IVM-OFFLINE-SIMULATOR ## Required: * nodejs ~8.9.1-lts ## How to use ```bash $ npm install -g https://github.com/TianyiLi/IVM-simulator.git ``` * Start sample server > default is working path ```bash $ sample-server ``` * Start SMC service ```bash $ smc-service ``` Or ``` $ git clone https://github.com/TianyiLi/IVM-simulator.git $ cd IVM-simulator > start live-server and stomp server $ node index.js --dist [path] > start smc service $ node smc.js ``` ### Custom Media folder service If you want to serve your own media data, you can use bellow argument to assign the folder path. ```bash $ sample-server --media=<path-to-media> ``` And, be sure of your folder as following structure ```bash ├── full │ └── test.mp4 └── standard └── test.png ``` Than, you can get the list from '/app/rest/media.cgi' ```json [ { "src": "http://localhost/media/full/test.mp4", "desc": "test.mp4", "position": "full", "type": "video", "title": "test.mp4", "id": 0 }, { "src": "http://localhost/media/standard/test.png", "desc": "test.png", "position": "standard", "type": "image", "title": "test.png", "id": 1, "duration": 10 }, ] ``` ### Custom stock list service If you want to serve your own stock list, you can create a folder which containing the products pictures that you want to serve. Then start the server by passing this argument ```bash sample-server --stock <path-to-folder> ``` Sometimes, you want to get your products with the channel list sort, this provide a sample can allow you to assign the channel length you want. And you can get the channel list from http://localhost/app/rest/channel.cgi ```bash sample-server --chno-length 20 ``` Specific the amount of the product ```bash sample-server --stock-length 20 ``` * Get more info ```bash $ sampler-server --help ``` ## URL |url| Description| |:---|:---:| |/ |Your index.html where you assigned to index.js | |/demo-simulator|Simulator console where can allow you to simulate the vending machine action| |/media/{full, standard}|media place| |/prod_img|Product image storing place| |/app/rest/stock.cgi|stock list| |/app/rest/media.cgi|media list| |/app/rest/channel.cgi|channel list| |/app/rest/sys.cgi|System error would display at here| |/demo|show the whole page which you serve on /| |/demo?dist=\<http url>|serve your own page which already on server| For more information please view the WIKI
Java
UTF-8
1,284
2.296875
2
[]
no_license
package litestruts; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; /** * Created by bdl19 on 2017/3/2. */ public class test { public static void main(String[] args) { SAXReader reader = new SAXReader(); try { Document document = reader.read("src/litestruts/struts.xml"); Element root = document.getRootElement(); System.out.println(root.elements().size()); /* String s = "login"; String string = "login"; System.out.println(root.getName()); Element action = root.element("action"); System.out.print(action.getName()); System.out.print(action.attribute("name").getText()); System.out.print(action.attribute("name").getText()); String str = action.attribute("name").getText(); if (str.equals(s)) { System.out.println(123123); System.out.println("123"); // Class clazz = Class.forName(action.attribute("class")); } System.out.println(s); System.out.println(str); */ } catch (DocumentException e) { e.printStackTrace(); } } }
PHP
UTF-8
591
2.546875
3
[]
no_license
<?php require_once("common.inc.php"); require_once("ApiControl.class.php"); class RequestGet { public function index() { if (isset($_GET["account"])) { try { $trade = new Trade(); $result = $trade->getTrade($_GET["account"]); $trade_info = array(); if (count($result) > 0) { $trade_info = array_shift($result); } echo json_encode(array("status" => "success", "trade" => $trade_info)); } catch (PDOException $e) { echo json_encode(array("status" => "fail", "error_msg" => $e->getMessage())); } } } } $api = new ApiControl(); $api->run(); ?>
Java
UTF-8
633
3.34375
3
[]
no_license
package synchronizedDemo; /** * 子类的同步方法调用父类的同步方法 * synchronized是可重复锁, 继承也是可以的 * @author ruwenbo * @version 1.0 * @date 2020/12/17 11:25 * @description */ public class Demo6 extends Parent { @Override synchronized void m() { System.out.println("child m start"); super.m(); System.out.println("child m end"); } public static void main(String[] args) { new Demo6().m(); } } class Parent { synchronized void m() { System.out.println("parent m start"); System.out.println("parent m end"); } }
Java
UTF-8
1,699
2.046875
2
[]
no_license
/** * Copyright © 2018 eSunny Info. Tech Ltd. All rights reserved. * * 功能描述: * @Package: com.itstyle.mail.web * @author: Administrator * @date: 2018年12月2日 下午10:24:18 */ package com.itstyle.mail.web; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.itstyle.mail.common.model.Result; import com.itstyle.mail.entity.Columns; import com.itstyle.mail.service.IColumnService; import io.swagger.annotations.Api; /** * Copyright: Copyright (c) 2018 LanRu-Caifu * * @ClassName: mailController.java * @Description: 该类的功能描述 * * @version: v1.0.0 * @author: Administrator * @date: 2018年12月2日 下午10:24:18 * * Modification History: * Date Author Version Description *---------------------------------------------------------* * 2018年12月2日 Administrator v1.0.0 修改原因 */ @Api(tags = "列管理") @RestController @RequestMapping("/column") public class ColumnController { @Autowired private IColumnService columnService; @PostMapping("listForPage") public Result listForPage(Columns column, int pageNumber, int pageSize) { return columnService.listForPage(column, pageNumber, pageSize); } @PostMapping("list") public Result list(Columns column) { return columnService.list(column); } @PostMapping("add") public Result add(Columns column) { return columnService.addColumn(column); } }
TypeScript
UTF-8
813
2.8125
3
[]
no_license
import Mocked = jest.Mocked; export function createMockInstance<T>(ctor: new (...args: any[]) => T): Mocked<T> { return stubMethods<T>(Object.create(ctor.prototype)); } function stubMethods<T>(obj: Mocked<T>, mock: Mocked<T> = obj, stubbed: Set<string> = new Set()): Mocked<T> { for (const prop of Object.getOwnPropertyNames(obj)) { if (!stubbed.has(prop)) { const descriptor = Object.getOwnPropertyDescriptor(obj, prop); if (obj !== Object.prototype && prop !== "constructor" && descriptor && typeof descriptor.value === "function") { Object.defineProperty(mock, prop, { ...descriptor, value: jest.fn() }); } stubbed.add(prop); } } const proto = Object.getPrototypeOf(obj); if (proto) { return stubMethods<T>(proto, mock, stubbed); } return mock; }
Python
UTF-8
367
3.46875
3
[]
no_license
import xlsxwriter # Create an new Excel file and add a worksheet. workbook = xlsxwriter.Workbook('images.xlsx') worksheet = workbook.add_worksheet() # Widen the first column to make the text clearer. worksheet.set_column('A:A', 30) # Insert an image. worksheet.write('A2', 'Insert an image in a cell:') worksheet.insert_image('B2', 'python.png') workbook.close()
PHP
UTF-8
3,235
2.765625
3
[ "MIT" ]
permissive
<?php include_once "../../../security/authentication/jtc_permission_authentication.php"; include_once "../../../security/database/jtc_connection_database.php"; /* * DataTables example server-side processing script. * * Please note that this script is intentionally extremely simply to show how * server-side processing can be implemented, and probably shouldn't be used as * the basis for a large complex system. It is suitable for simple use cases as * for learning. * * See http://datatables.net/usage/server-side for full details on the server- * side processing requirements of DataTables. * * @license MIT - http://datatables.net/license_mit */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Easy set variables */ // DB table to use $table = 'manufacturers'; // Table's primary key $primaryKey = 'id'; // Array of database columns which should be read and sent back to DataTables. // The `db` parameter represents the column name in the database, while the `dt` // parameter represents the DataTables column identifier - in this case object // parameter names $columns = array( array( 'db' => 'id', 'dt' => 'DT_RowId', 'formatter' => function( $d, $row ) { // Technically a DOM id cannot start with an integer, so we prefix // a string. This can also be useful if you have multiple tables // to ensure that the id is unique with a different prefix return 'row_'.$d; } ), array( 'db' => 'name', 'dt' => 'name' ), array( 'db' => 'cnpj', 'dt' => 'cnpj' ), array( 'db' => 'email', 'dt' => 'email' ), array( 'db' => 'phone', 'dt' => 'phone' ), array( 'db' => 'name', 'dt' => 'name', 'formatter' => function( $d, $row ) { return date( 'jS M y', strtotime($d)); } ), array( 'db' => 'phone', 'dt' => 'phone', 'formatter' => function( $d, $row ) { return '$'.number_format($d); } ) ); $sql_details = array( 'user' => 'root', 'pass' => 'root', 'db' => 'jtc_database', 'host' => '127.0.0.1' ); /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * If you just want to use the basic configuration for DataTables with PHP * server-side, there is no need to edit below this line. */ require( '../class.ssp.php' ); echo json_encode( SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns ) ); // $sql_select_manufacturers = "SELECT name, cnpj, email, phone FROM manufacturers"; // $sql_select_manufacturers_prepare = $dbconnection->prepare($sql_select_manufacturers); // $sql_select_manufacturers_prepare->execute(); // // $info = array( // "draw"=> 1, // "recordsTotal"=> 57, // "recordsFiltered"=> 57, // ); // while($sql_select_manufacturers_data = $sql_select_manufacturers_prepare->fetch()){ // $info["data"][] = array( // $sql_select_manufacturers_data["name"], // $sql_select_manufacturers_data["cnpj"], // $sql_select_manufacturers_data["email"], // $sql_select_manufacturers_data["phone"], // ); // } // echo json_encode($info); ;
Java
UTF-8
2,549
2.078125
2
[]
no_license
package com.example.sunflower_java.repository; import android.util.Config; import com.example.sunflower_java.App; import com.example.sunflower_java.config.DataBaseConfig; import com.example.sunflower_java.data.AppDataBase; import com.example.sunflower_java.data.Plant; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.internal.LinkedTreeMap; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import androidx.room.Database; /** * Time:2020/1/17 8:21 * Author: han1254 * Email: 1254763408@qq.com * Function: */ public class DataInitManager { private static Type type; static { type = new TypeToken<List<Plant>>(){}.getType(); } public static void initPlantData() { AppDataBase .databaseWriteExecutor.execute( () -> { try { List<Plant> plantList = new ArrayList<>(); Gson gson = new Gson(); InputStream inputStream = App.getAppContext().getAssets().open(DataBaseConfig.PLANT_DATA_FILE_NAME); Reader reader = new InputStreamReader(inputStream); plantList = gson.fromJson(reader, type); List<Plant> test = plantList; // JsonObject jsonObject = new JsonParser().parse(App.getAppContext().getAssets().open(DataBaseConfig.PLANT_DATA_FILE_NAME).toString()).getAsJsonObject(); // JsonArray jsonArray = jsonObject.getAsJsonArray(); // for (JsonElement jsonElement : // jsonArray ){ // Plant plant = (Plant) gson.fromJson(jsonElement, new TypeToken<List<Plant>>(){}.getRawType()); // plantList.add(plant); // } // List<Plant> finalList = new ArrayList<>(); // Iterator iterator = plantList.iterator(); // while(iterator.hasNext()) { // Plant item = (Plant) iterator.next(); // finalList.add(item); // } AppDataBase.getInstance(App.getAppContext()).getPlantDao().insertAll(plantList); } catch (IOException e) { e.printStackTrace(); } }); } }
Python
UTF-8
5,118
2.65625
3
[]
no_license
import hashlib from cli.torrentLogger import logger import os from bitarray import bitarray from peer.constants import BLOCK_SIZE from typing import List from parsing.File import File class Block: start: int size: int def __init__(self, start: int, size: int): self.start = start self.size = size class PieceCache: blockSize: int hasBlock: bitarray def __init__(self, piece): self.reset(piece) def writeBlock(self, blockIdx: int, block: bytes) -> bool: start = blockIdx self.rawBytes[start : start + len(block)] = block self.hasBlock[int(blockIdx / BLOCK_SIZE)] = True return self.hasBlock.all() def reset(self, piece): self.rawBytes = bytearray(piece.size) self.hasBlock = bitarray(len(piece.blocks)) self.hasBlock.setall(False) class PieceFile: file: File start: int end: int size: int def __init__(self, file: File, start: int, size: int): self.file = file self.start = start self.size = size self.end = start + size class Piece: hash: bytes size: int blocks: List[Block] files: List[PieceFile] cache: PieceCache downloaded: bool idx: int def __init__(self, hash: bytes, idx: int, torrent): self.hash = hash self.files = [] self.blocks = [] self.size = -1 self.torrent = torrent self.downloaded = False self.idx = idx def verify(self, piece: bytes) -> bool: hash_new = hashlib.sha1(piece).digest() return hash_new == self.hash def read(self) -> bytes: piece = b"" for file in self.files: p = file.file.getFilepath() if not os.path.exists(p): raise Exception("Piece not found") with open(file.file.getFilepath(), "rb") as f: f.seek(file.start) piece += f.read(file.size) if self.verify(piece): return piece else: raise Exception("Piece not found") def write(self, bytes): pieceAcc = 0 if self.verify(bytes): for file in self.files: with open( file.file.getFilepath(), "r+b" if os.path.exists(file.file.getFilepath()) else "wb", ) as f: f.seek(file.start) f.write(bytes[pieceAcc : pieceAcc + file.size]) pieceAcc += file.size return True else: return False def calc_blocks(self): for blockStart in range(0, self.size, BLOCK_SIZE): size = min(BLOCK_SIZE, self.size - blockStart) self.blocks.append(Block(blockStart, size)) self.cache = PieceCache(self) def writeBlock(self, blockIdx: int, block: bytes): if self.torrent.bitfield[self.idx]: logger.error("piece exists already") return 1 hasAllBlocks = self.cache.writeBlock(blockIdx, block) if hasAllBlocks: if self.write(bytes(self.cache.rawBytes)): self.torrent.bitfield[self.idx] = 1 self.torrent.downloaded = self.torrent.bitfield.all() self.torrent.pieceCounter += 1 self.torrent.progressBar.update(1) lenPieces = len(self.torrent.info.pieces.pieces) logger.info( f"Downloaded: {self.torrent.pieceCounter} / {lenPieces}, {round(self.torrent.pieceCounter / lenPieces * 100, 2)}%" ) self.cache.reset(self) return 1 else: return -1 else: return 0 def readBlock(self, blockIdx: int) -> bytes: piece = self.read() start = blockIdx * BLOCK_SIZE return piece[start : min(start + BLOCK_SIZE, len(piece))] class PieceList: pieces: List[Piece] def __init__(self, pieces: bytes, pieceSize: int, files: List[File], torrent): self.pieces = [] hashSize = 20 curFileIdx = 0 accFileSize = 0 for idx, start in enumerate(range(0, len(pieces), hashSize)): piece = Piece(pieces[start : start + hashSize], idx, torrent) accPieceSize = 0 while accPieceSize < pieceSize: if curFileIdx == len(files): break file = files[curFileIdx] fileStartPosition = idx * pieceSize - accFileSize + accPieceSize fileSize = pieceSize - accPieceSize fileEndPosition = fileStartPosition + fileSize if file.length <= fileEndPosition: fileSize = file.length - fileStartPosition curFileIdx += 1 accFileSize += file.length piece.files.append(PieceFile(file, fileStartPosition, fileSize)) accPieceSize += fileSize piece.size = accPieceSize piece.calc_blocks() self.pieces.append(piece)
PHP
UTF-8
1,028
2.5625
3
[]
no_license
<?php namespace App\Http\Controllers\Api\v1; use App\Http\Controllers\AbstractController; use App\Models\Profile; use App\Services\ProfileService; use Illuminate\Http\Request; class ProfileController extends AbstractController { /** * ProfileController constructor. * @param ProfileService $service */ public function __construct(ProfileService $service) { $this->service = $service; $this->model = Profile::class; } /** * @param Request $request * @return mixed * @throws \Illuminate\Auth\Access\AuthorizationException */ public function store(Request $request) { return parent::save($request); } /** * @param Request $request * @param $id * @return mixed * @throws \Illuminate\Auth\Access\AuthorizationException */ public function update(Request $request, $id) { return parent::updateAs($request, $id); } }
Java
UTF-8
388
1.789063
2
[]
no_license
package org.hongxi.spring.boot.service; import org.hongxi.spring.boot.OpenSpringAutoConfiguration; import org.hongxi.spring.boot.common.util.JarVersionUtils; /** * Created by shenhongxi on 2021/3/26. */ public class VersionService { public String getVersion() { return JarVersionUtils.getJarVersion(OpenSpringAutoConfiguration.class, "open-spring-boot-starter"); } }
Java
UTF-8
705
2.171875
2
[]
no_license
package org.turings.investigationapplicqation.Entity; import java.io.Serializable; import java.util.List; public class TopicBigType implements Serializable { private String textTopic; private List<TopicType> list; public TopicBigType() { } public TopicBigType(String textTopic, List<TopicType> list) { this.textTopic = textTopic; this.list = list; } public String getTextTopic() { return textTopic; } public void setTextTopic(String textTopic) { this.textTopic = textTopic; } public List<TopicType> getList() { return list; } public void setList(List<TopicType> list) { this.list = list; } }
C++
UTF-8
527
3.375
3
[]
no_license
#include<iostream> #include<algorithm> #include<array> using namespace std; int main(){ array<int,10> numbers; for(int i=0; i<numbers.size(); i++){ numbers[i] = rand()%1000; } cout << "original: "; for(int n: numbers){ cout << n << " "; } cout << endl; sort(numbers.begin(), numbers.end()); cout << "sorted : "; for(int i=0; i<numbers.size(); i++){ cout << numbers[i] << " "; } cout << endl; return 0; }
Markdown
UTF-8
714
2.53125
3
[]
no_license
# Phising-Game-Online # Mobile Legend & Clash of Clans tools phising untuk game : mobile legends & clash of clans => Installation : pkg install python2 -y pip2 install requests pkg install figlet -y pkg install nano -y pkg install git -y git clone https://github.com/CyberTCA/Fhising-Game => how to use : cd Phising-Game-Online python2 phising.py "pilih salah satunya" 1 = Clash of Clans 2 = Mobile Legends 3 = Exit (Keluar) kemudian copy linknya : http://127.0.0.1:8080 buka melalui browser (Google Chrome) Finish :) + Untuk melihat email & sandi nya di dalam folder : 1 = Clash of Clans 2 = Mobile Legends Subscribe My Channel : https://www.youtube.com/channel/UCbLBrpgM16II8bvznsnIs9g by Mr.Tcg Cyber
Python
UTF-8
1,886
2.890625
3
[]
no_license
''' Logsoftmax.py用于实现Log版本的softmax ''' import numpy as np from Module import Module class Logsoftmax(Module): def __init__(self): super(Logsoftmax, self).__init__() # input_shape=[batch, class_num] # 设置module打印格式 def extra_repr(self): s = () return s def cal_softmax(self, input_array): softmax = np.zeros(input_array.shape) # 对每个batch的数据求softmax exps_i = np.exp(input_array-np.max(input_array)) softmax = exps_i/np.sum(exps_i) # softmax[batch, class_num] return softmax def forward(self, input_array): self.input_shape = input_array.shape self.batchsize = self.input_shape[0] self.eta = np.zeros(self.input_shape) # prediction 可以表示从FC层输出的数据 [batch, class_num] 或者 [batch, [p1,p2,...,pk]] self.logsoftmax = np.zeros(input_array.shape) self.softmax = np.zeros(input_array.shape) # 对每个batch的数据求softmax for i in range(self.batchsize): self.softmax[i] = self.cal_softmax(input_array[i]) self.logsoftmax[i] = np.log(self.softmax[i]) # softmax[batch, class_num] return self.logsoftmax def gradient(self, eta): self.eta = eta self.eta_next = self.softmax.copy() # print('softmax :\n', self.eta_next) # y 的标签是 One-hot 编码 if self.eta.ndim>1: # one-hot for i in range(self.batchsize): self.eta_next[i] += self.eta[i] elif self.eta.ndim==1: # 非one-hot for i in range(self.batchsize): self.eta_next[i, -self.eta[i]] -= 1 # eta[batchsize, class_num] # 需要除以batchsize用于平均该批次的影响 self.eta_next /= self.batchsize return self.eta_next
C
GB18030
259
2.5625
3
[]
no_license
#include <stdio.h> int main() { int a = 10000; FILE* pf = fopen_s("test.txt", "w"); //ļָ fputc('a',pf);//дһַļ //fwrite(&a, 4, 1, pf);//Ƶʽдļ fclose_s(pf); pf = NULL; sysytem("pause"); return 0; }
Shell
UTF-8
2,071
2.953125
3
[]
no_license
# brew completions if [[ $(uname) == 'Darwin' ]]; then fpath=(/usr/local/share/zsh-completions $fpath) fi # The following lines were added by compinstall zstyle ':completion:*' auto-description 'specify: %d' zstyle ':completion:*' file-sort name zstyle ':completion:*' format 'Completing %d' zstyle ':completion:*' group-name '' zstyle ':completion:*' ignore-parents parent pwd .. directory zstyle ':completion:*' insert-unambiguous true zstyle ':completion:*' list-colors '' zstyle ':completion:*' list-prompt %SAt %p: Hit TAB for more, or the character to insert%s zstyle ':completion:*' menu select=0 zstyle ':completion:*' original true zstyle ':completion:*' preserve-prefix '//[^/]##/' zstyle ':completion:*' select-prompt $SScrolling active: current selection at %p%s zstyle ':completion:*' squeeze-slashes true zstyle ':completion:*' verbose true zstyle :compinstall filename '/Users/jrapakko/.zshrc' autoload -Uz compinit compinit # End of lines added by compinstall # Lines configured by zsh-newuser-install HISTFILE=~/.histfile HISTSIZE=1000 SAVEHIST=1000 setopt appendhistory unsetopt beep bindkey -v # End of lines configured by zsh-newuser-install # Paths # # OS X paths and architecture if [[ $(uname) == 'Darwin' ]]; then # path vars LOCALBIN=/usr/local/bin AVRBIN=/usr/local/avr/bin # ls colors export LSCOLORS=GxFxCxDxBxegedabagaced # Set architecture flags export ARCHFLAGS="-arch x86_64" # set path to use brew utils (more up-to-date than OS X system utils) # can be done in /etc/paths if needed system-wide # check if path already begins with /usr/local/bin echo $PATH | grep -q -s "^${LOCALBIN}" # if not, update path if [[ $? -eq 1 ]]; then PATH=$LOCALBIN:$PATH export PATH fi #### AVR BINUTILS/GCC/LIBC NOT BUILT FROM SOURCE ON THIS COMPUTER # # set path to use avr binutils, gcc & libc (built from source) # echo $PATH | grep -q -s "${AVRBIN}" # # if not, update path # if [[ $? -eq 1 ]]; then # PATH=$AVRBIN:$PATH # export PATH # fi fi # Aliases source $HOME/.zsh/aliases.zsh
JavaScript
UTF-8
4,339
3.078125
3
[]
no_license
import { nothing } from 'lit-html'; import { LitElement, html, css } from 'lit-element'; import { classMap } from 'lit-html/directives/class-map'; import { isEmpty as isArrayEmpty, insertItem } from './utils/array'; /** * <sortable-dnd> - Component for sortable Drag and Drop list. * Component implements HTML Drag and Drop API for arranging items. * * Usage: * <sortable-dnd * .items="${this.items}" * .onChange="${this.onChange}"></sortable-dnd> * * @class SortableDnd * @extends {LitElement} * @see https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API */ class SortableDnd extends LitElement { /** * Static getter properties. * * @returns {Object} */ static get properties() { return { /** * List of items * * @type {{items: Array}} */ items: { type: Array }, /** * Dragged item DOM node */ draggedItem: { attribute: false }, /** * Function called when item is dropped * * @type {{onChange: Function}} */ onChange: { type: Function } }; } /** * Static getter styles. * * @returns {Object} */ static get styles() { return css` .dnd-list { margin: 0; padding: 0; list-style-type: none; } .dnd-list__item--fade { opacity: 0.2; } `; } /** * Creates an instance of DNDList. */ constructor() { super(); // Initialize empty items this.items = []; // Initialize empty function this.onChange = (items) => { }; } /** * Render life cycle hook. * * @returns {customElement} */ render() { return html` <ul class="dnd-list"> ${isArrayEmpty(this.items) ? nothing : this.items.map((item, index) => { let isFaded = false; if (this.draggedItem) { isFaded = this.draggedItem.index === index; } return html` <li class="dnd-list__item ${classMap({ 'dnd-list__item--fade': isFaded })}" draggable="true" @dragstart="${this.handleDragStart}" @dragenter="${this.handleDragEnter}" @dragover="${this.handleDragOver}" @drop="${this.handleDrop}" @dragend="${this.handleDragEnd}" .index="${index}" > ${item} </li>`; })} </ul> `; } /** * Handle item dragstart event. * * @param {Event} event - dragstart event object */ handleDragStart(event) { this.draggedItem = event.target; event.dataTransfer.effectAllowed = 'move'; } /** * Handle item dragenter event. * Prevent default action of dragenter event. * * @param {Event} event - dragenter event object */ handleDragEnter(event) { event.preventDefault(); if (this.draggedItem) { this.setItems(this.draggedItem.index, event.target.index); this.draggedItem = event.target; } } /** * Handle item dragover event. * Prevent default action of dragover event only if group is defined. * * @param {Event} event - dragover event object */ handleDragOver(event) { event.preventDefault(); } /** * Handle item drop event. * * @param {Event} event - drop event object */ handleDrop(event) { event.preventDefault(); } /** * Handle item dragend event. * * @param {Event} event - Dragend event object */ handleDragEnd(event) { event.preventDefault(); const dropEffect = event.dataTransfer.dropEffect; if (dropEffect === 'move' && this.draggedItem) { this.onChange(this.items); } this.draggedItem = null; } /** * Position items in array according to dragged item and dropped over item. * * @param {Number} draggedItemIndex - Index of item dragged. * @param {Number} dropItemIndex - Index of item over which dragged item is dropped. * @returns {undefined} */ setItems(draggedItemIndex, dropItemIndex) { const undraggedItems = [...this.items.slice(0, draggedItemIndex), ...this.items.slice(draggedItemIndex + 1)]; this.items = insertItem(undraggedItems, this.items[draggedItemIndex], dropItemIndex); } } export default SortableDnd;
C++
UTF-8
802
3.0625
3
[]
no_license
// // main.cpp // 647 - Palindromic Substrings // // Created by Wu, Meng Ju on 2020/5/2. // Copyright © 2020 Pitt. All rights reserved. // #include <iostream> #include <string> using namespace std; class Solution { private: int expand(int i, int j, string s) { int candidates = 0; while (i >= 0 && j < s.size() && s[i] == s[j]) { candidates += 1; i -= 1; j += 1; } return candidates; } public: int countSubstrings(string s) { int candidates = 0; for (int i = 0; i < s.size(); i++) { candidates += expand(i, i, s); candidates += expand(i, i+1, s); } return candidates; } }; int main(int argc, const char * argv[]) { return 0; }
Java
UTF-8
606
3.46875
3
[]
no_license
package algorithm.dayOfTheProgrammer; public class DayOfTheProgrammer { public static String dayOfProgrammer(int year) { String result = ""; if(year >= 1700 && year <= 1917) { result = year % 4 == 0 ? "12.09."+year : "13.09."+year; } else if(year == 1918) { //28-14+1 = 15 + 215 = 256 - 230 = 26 result = "26.09."+year; } else if(year >= 1918 && year <= 2700) { result = (year % 400 == 0 || ((year % 4 == 0) && (year % 100 != 0))) ? "12.09."+year : "13.09."+year; } return result; } }
Ruby
UTF-8
845
2.890625
3
[ "MIT" ]
permissive
require 'necromancy' describe Necromancy do let(:l) { described_class.new } example do [:foo, :bar, :baz].map(&l.to_s . upcase). should == ["FOO", "BAR", "BAZ"] end example do [:foo, :hoge, :bar, :fuga].select(&l.to_s . length > 3). should == [:hoge, :fuga] end example do qstr = "hoge=fuga&foo=bar" Hash[qstr.split(?&).map &l.split(?=)]. should == {"hoge"=>"fuga", "foo"=>"bar"} end example do (1..5).map(&l ** 2). should == [1, 4, 9, 16, 25] end example do %w[c++ lisp].map(&(l + "er").upcase). should == ["C++ER", "LISPER"] end example do %w[c++ lisp].map(&l.upcase + "er"). should == ["C++er", "LISPer"] end example do procs = %w(succ pred odd?).map &l.to_sym . to_proc procs.map(&l.call(1)). should == [2, 0, true] end end
Python
UTF-8
1,907
4.0625
4
[]
no_license
def filter_six_digits(number) -> bool: return len(str(number)) == 6 def filter_adjacent_numbers(number) -> bool: #regex to match cases where some alphanumeric char appears atleast twice in row: # ((\d)\2{1,}) #modified from answer https://stackoverflow.com/a/7147979 import re return re.search(r'((\d)\2{1,})', str(number)) is not None def filter_two_adjacent_numbers(number) -> bool: import re match = re.findall(r'((\d)\2{1,})', str(number)) if match is not None: #some matches, return True if any of them has length of 2 return any(filter(lambda g: len(g[0]) == 2, match) ) else: #no matches return False def filter_never_decrease(number) -> bool: num = str(number) match = True for i in range(1, len(num)): if num[i] < num[i-1]: match = False return match def combine_filters(filters, numbers): valid_numbers = filter(lambda x: all(f(x) for f in filters), numbers) return list(valid_numbers) """ from https://stackoverflow.com/a/12386419 filters = (f1,f2,f3,f4) filtered_list = filter( lambda x: all(f(x) for f in filters), your_list ) """ if __name__ == "__main__": """ How many different passwords within the range given in your puzzle input meet these criteria? """ #Part 1 puzzle_input = range(278384, 824795) filters = (filter_six_digits, filter_adjacent_numbers, filter_never_decrease) valid_passwords = combine_filters(filters, puzzle_input) print(f'Space of possible passwords matching criteria contains {len(valid_passwords)} elements') #Part 2 puzzle_input = range(278384, 824795) filters = (filter_six_digits, filter_two_adjacent_numbers, filter_never_decrease) valid_passwords = combine_filters(filters, puzzle_input) print(f'Space of possible passwords matching strict criteria contains {len(valid_passwords)} elements')
Java
UTF-8
1,795
2.15625
2
[]
no_license
package com.desheng.app.toucai.model; import android.os.Parcel; import android.os.Parcelable; public class XunibiAddressBean implements Parcelable { /** * address : 0xf4C5F928d485d60091f9FEB1d494e666e831Ae7b * createTime : 1599301326000 * id : 6 * uin : 5927 */ private String address; private long createTime; private String id; private String uin; protected XunibiAddressBean(Parcel in) { address = in.readString(); createTime = in.readLong(); id = in.readString(); uin = in.readString(); } public static final Creator<XunibiAddressBean> CREATOR = new Creator<XunibiAddressBean>() { @Override public XunibiAddressBean createFromParcel(Parcel in) { return new XunibiAddressBean(in); } @Override public XunibiAddressBean[] newArray(int size) { return new XunibiAddressBean[size]; } }; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public long getCreateTime() { return createTime; } public void setCreateTime(long createTime) { this.createTime = createTime; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUin() { return uin; } public void setUin(String uin) { this.uin = uin; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(address); dest.writeLong(createTime); dest.writeString(id); dest.writeString(uin); } }
Python
UTF-8
1,412
2.921875
3
[ "MIT" ]
permissive
# Copyright 2009-2014 Ram Rachum. # This program is distributed under the MIT license. '''Defines various tools related to data structures.''' import collections import itertools import numbers from python_toolbox import nifty_collections @nifty_collections.LazyTuple.factory() def get_all_contained_counters(counter, use_lazy_tuple=True): ''' Get all counters that are subsets of `counter`. This means all counters that have amounts identical or smaller than `counter` for each of its keys. If `use_lazy_tuple=True` (default), value is returned as a `LazyTuple`, so it may be used both by lazily iterating on it *and* as a tuple. Otherwise an iterator is returned. ''' iterator = _get_all_contained_counters(counter) if use_lazy_tuple: return nifty_collections.LazyTuple(iterator) else: return iterator def _get_all_contained_counters(counter, use_lazy_tuple=True): assert isinstance(counter, collections.Counter) counter_type = type(counter) keys, amounts = zip( *((key, amount) for key, amount in counter.items() if amount) ) assert all(isinstance(amount, numbers.Integral) for amount in amounts) amounts_tuples = \ itertools.product(*map(lambda amount: range(amount+1), amounts)) for amounts_tuple in amounts_tuples: yield counter_type(dict(zip(keys, amounts_tuple)))
JavaScript
UTF-8
1,594
2.625
3
[ "MIT" ]
permissive
/** * responsemanager.js * * Response structure manager * * @package Parking Manager * @subpackage routers * @author Rahul N * @copyright 2020 Rahul * @version 0.0.1 * @since File available since Release 0.0.0 */ const info = { "Author" : process.env.AUTHOR, "Date" : new Date().toLocaleString() } /** * sendSucess * * Function to wrap response format for sucess * * @package Parking Manager * @subpackage routers * @author Rahul N * @copyright 2020 Rahul * @version 0.0.1 * @since Function available since Release 0.0.1 * @param res response object * @param data object | string (optional) * @param statuscode int (optional) * @return void */ function sendSucess(res, data = {}, statuscode = 200){ // TODO: Meta to manage counts of records ang paging information res.status(statuscode).send({ "meta" : info, "status" : "ok", "status_code": statuscode, data }) } /** * sendError * * Function to wrap response format for error * * @package Parking Manager * @subpackage routers * @author Rahul N * @copyright 2020 Rahul * @version 0.0.1 * @since Function available since Release 0.0.1 * @param res response object * @param error object | string (optional) * @param statuscode int (optional) * @return void */ function sendError(res, error = {}, statuscode = 500){ res.status(statuscode).send({ "meta": info, "status": "error", "status_code": statuscode, error }) } module.exports = { sendSucess, sendError }
C#
UTF-8
2,165
2.578125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using PDFService.Entities; using PDFService.Repository; namespace PDFService.Services.Entity { public sealed class TemplateEntityService { readonly ITemplateRepository _repository; public TemplateEntityService(ITemplateRepository repository) { _repository = repository; } ~TemplateEntityService() { _repository.Dispose(); } public List<Template> GetTemplates(string clientID) { try { return _repository.Get(t => t.ClientID == clientID) .ToList(); } catch (Exception ex) { throw ex; } } public Template GetTemplate(string clientID, int id) { try { return _repository.Get(t => t.ClientID == clientID && t.ID == id) .SingleOrDefault(); } catch (Exception ex) { throw ex; } } public async Task Save(Template template) { try { if (template.ID == default(int)) await _repository.AddAsync(template); else _repository.Update(template); await _repository.SaveAsync(); } catch (Exception ex) { throw ex; } } public async Task Delete(Template template) { try { _repository.Remove(template); await _repository.SaveAsync(); } catch (Exception ex) { throw ex; } } public async Task Delete(string clientID, int id) { try { _repository.Remove(t => t.ClientID == clientID && t.ID == id); await _repository.SaveAsync(); } catch (Exception ex) { throw ex; } } } }
C
UTF-8
328
2.96875
3
[]
no_license
/* Luiza de Almeida Gatti All rights reserved */ #include <stdio.h> #include <stdlib.h> void main() { char vendedor[100]; double salarioFixo, montante, final; scanf("%s", vendedor); scanf("%lf", &salarioFixo); scanf("%lf", &montante); final = (montante*0.15)+salarioFixo; printf("TOTAL = R$ %.2lf\n", final); }
C#
UTF-8
2,167
3.25
3
[]
no_license
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace JMR.Common { public static class Extensions { public static int Count(this IList collection) { return collection == null ? 0 : collection.Count; } public static IEnumerable<T> Cast<T>(this IList collection) { if (collection == null) { return Enumerable.Empty<T>(); } return collection.OfType<T>(); } public static IEnumerable<TTarget> CreateRange<TSource, TTarget>(this IEnumerable<TSource> sources, Func<TSource, TTarget> creator) { foreach (var source in sources) { yield return creator(source); } } public static void AddRange<T>(this ObservableCollection<T> collection, IEnumerable<T> items) { foreach (var item in items) { collection.Add(item); } } public static void InsertRange<T>(this ObservableCollection<T> collection, int index, IEnumerable<T> items) { foreach (var item in items) { collection.Insert(index++, item); } } public static void RemoveRange<T>(this ObservableCollection<T> collection, int start, int count) { for (int i = 0; i < count; i++) { collection.RemoveAt(start); } } public static void MoveRange<T>(this ObservableCollection<T> collection, int oldIndex, int oldCount, int newIndex, int newCount) { if (oldCount == 1) { collection.Move(oldIndex, newIndex); } else { var items = collection .Skip(oldIndex) .Take(oldCount) .ToList(); collection.RemoveRange(oldIndex, oldCount); collection.InsertRange(newIndex, items); } } } }
Markdown
UTF-8
992
2.5625
3
[ "MIT" ]
permissive
<p align="center"><img src="assets/cuis_web_logo.png" width="150" alt="Cuis web logo"></p> **Cuis Web** is a microframework web for [Cuis Smalltalk](https://github.com/Cuis-Smalltalk/Cuis-Smalltalk-Dev) that includes everything needed to create web applications according to the [Model-View-Controller (MVC) pattern](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller). ## Getting Started 1. You'll need to download Cuis Smalltalk, you can follow the [official Cuis Smalltalk guide](https://github.com/Cuis-Smalltalk/Cuis-Smalltalk-Dev#setting-up-cuis-in-your-machine). 2. Once you have Cuis Smalltalk running you have to drag and drop the [Cuis-Web.pck.st](https://github.com/gstn-caruso/cuis-web/blob/master/Cuis-Web.pck.st) inside Cuis. 3. Start the server performing `CuisWebApplication start` on a workspace. 4. Go to http://localhost:8080 ## I want to know more! You can go to [the wiki page](https://github.com/gstn-caruso/cuis-web/wiki) to learn how to do more.
C#
UTF-8
3,953
3.171875
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Diagnostics; namespace IALab406 { [Serializable] public class GeneticAlgorithm { public void GeneratePopulation(int density) { _population = new LinkedList<RobotChromosome>(); for (int i = 0; i < density; i++) _population.Add(new RobotChromosome(24, 10)); } public void ResetEntryDataIndex() { _entryDataIndex = 0; } public Tuple<RobotChromosome, double> Learn(int cycles, StreamReader dataReader) { Tuple<RobotChromosome, double> best = null; Random random = Globals.Instance.Random; for (int i = 0; i < _entryDataIndex; i++) dataReader.ReadLine(); for (int i = 0; i < cycles; i++) { Debug.WriteLine("Cycle {0}:", i); string[] data = dataReader.ReadLine().Split(','); double[] input = new double[24]; for (int j = 0; j < 24; j++) input[j] = double.Parse(data[j]); var sortedPopulationByFitness = _population.Select((chromosome) => new { Chromosome = chromosome, Fitness = Math.Abs(_ParseToInt(data[24]) - Math.Abs(Math.Round(chromosome.Apply(input)) % 4)) }).OrderBy((chromosome) => chromosome.Fitness); var first = sortedPopulationByFitness.ElementAt(random.Next(Math.Min(_population.Count, 20))); var second = sortedPopulationByFitness.ElementAt(random.Next(Math.Min(_population.Count, 20))); RobotChromosome newBorn = first.Chromosome.CrossOver(second.Chromosome).Mutate(); var candidate = new { Chromosome = newBorn, Fitness = Math.Abs(_ParseToInt(data[24]) - Math.Abs(Math.Round(newBorn.Apply(input)) % 4)) }; var last = sortedPopulationByFitness.Last(); if (last.Fitness <= candidate.Fitness) { Debug.WriteLine("|ROUND( {0} )| % 4, Fitness: {1}", candidate.Chromosome.ToString(), candidate.Fitness); Debug.WriteLine("is no good chromosome!"); Debug.WriteLine("population is unchanged!"); } else { _population = new HashSet<RobotChromosome>(_population.Take(_population.Count - 1).Concat(new RobotChromosome[] { candidate.Chromosome })); Debug.WriteLine("|ROUND( {0} )| % 4, Fitness: {1}", candidate.Chromosome.ToString(), candidate.Fitness); Debug.WriteLine("has replaced"); Debug.WriteLine("|ROUND( {0} )| % 4, Fitness: {1}", last.Chromosome.ToString(), last.Fitness); } best = new Tuple<RobotChromosome, double>(sortedPopulationByFitness.First().Chromosome, sortedPopulationByFitness.First().Fitness); } return best; } public int PopulationDensity { get { if (_population == null) return -1; else return _population.Count; } } private double _ParseToInt(string label) { switch (label) { case "Slight-Left-Turn": return 0; case "Move-Forward": return 1; case "Slight-Right-Turn": return 2; case "Sharp-Right-Turn": return 3; default: return 4; } } private int _entryDataIndex = 0; private ICollection<RobotChromosome> _population; } }
Python
UTF-8
872
3.15625
3
[]
no_license
import numpy as np class Dense: x = None def __init__(self, num1, num2, learning_rate=0.01, bias=True): self.mt = 2/num1 * np.random.randn(num1, num2) # new weights according to Andrew Ng self.bias = 2/num1 * np.random.randn(1, num2) self.lr = learning_rate def forward(self, data, bias=True, prnt=False): self.x = data.copy() t = np.matmul(self.x, self.mt) + (self.bias if bias else 0) if prnt: print(t, 'dense') return t def backward(self, loss, bias=True): #print(loss, 'dense bw') l = np.matmul(self.x.reshape(-1, 1), loss.reshape(1, -1)) self.mt -= l * self.lr if bias: self.bias -= loss * self.lr return np.sum(l, axis=1) if __name__ == '__main__': b = Dense(3, 5) x = b.forward(np.array([0, 0, 1])) print(x)
Java
UTF-8
1,939
3.875
4
[]
no_license
package kr.kirk.euler.p000; import java.util.ArrayList; import java.util.List; /* 어떤 수를 소수의 곱으로만 나타내는 것을 소인수분해라 하고, 이 소수들을 그 수의 소인수라고 합니다. 예를 들면 13195의 소인수는 5, 7, 13, 29 입니다. 600851475143의 소인수 중에서 가장 큰 수를 구하세요. The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? */ public class Problem003 { static List<Long> primes = new ArrayList<Long>(); static List<Long> p2 = new ArrayList<Long>(); public static void main(String[] args) { System.out.println(Problem003.solution(13195L)); System.out.println(Problem003.solution(600851475143L)); } private static long solution(long d) { if ( d < 4 ) return d; primes.clear(); p2.clear(); primes.add(2L); primes.add(3L); // 모든 소수는 6n+1 또는 6n+5 ( = 6n-1 ) 형태이다. for ( long i = 6; i<=d; i += 6) { if ( check(i - 1, d) ) break; if ( check(i + 1, d) ) break; } return primes.get(primes.size()-1); } private static boolean check(long l, long d) { if ( isPrime(l) ) { if ( d % l == 0 ) { p2.add(l); if (isOver(d)) { System.out.println("========================================================"); for ( long x : p2) System.out.print( x + ", "); System.out.println(""); return true; } } } return false; } private static boolean isOver(long d) { long s = 1; for ( long i : p2 ) s *= i; return d == s; } private static boolean isPrime(long i) { double sqrt = Math.sqrt(i); for ( long l : primes) { if ( i % l == 0 ) return false; if ( l > sqrt ) break; // 제곱근 범위 까지만 체크. } primes.add(i); System.out.println(primes.size() + " => " + i); return true; } }
JavaScript
UTF-8
350
2.6875
3
[]
no_license
class Hero{ constructor(x,y,width,height){ this.body= Bodies.rectangle(200,250,width,height); this.width= width; this.height=height; World.add(world,this.body); this.image=loadImage("spiderman1.png") } display(){ image(this.image, x,y, this.width, this.height) } }
Java
UTF-8
1,667
2.21875
2
[]
no_license
package fiit.hipstery.publisher.dto; import java.time.LocalDateTime; import java.util.Set; public class ArticleDetailedDTO extends AbstractDTO { protected String title; protected String content; protected LocalDateTime createdAt; protected Set<AppUserDTO> authors; protected Set<CategoryDTO> categories; protected PublisherDTO publisher; protected boolean liked; protected int likeCount; protected Set<CommentDTO> comments; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public LocalDateTime getCreatedAt() { return createdAt; } public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; } public Set<AppUserDTO> getAuthors() { return authors; } public void setAuthors(Set<AppUserDTO> authors) { this.authors = authors; } public Set<CategoryDTO> getCategories() { return categories; } public void setCategories(Set<CategoryDTO> categories) { this.categories = categories; } public PublisherDTO getPublisher() { return publisher; } public void setPublisher(PublisherDTO publisher) { this.publisher = publisher; } public int getLikeCount() { return likeCount; } public void setLikeCount(int likeCount) { this.likeCount = likeCount; } public Set<CommentDTO> getComments() { return comments; } public void setComments(Set<CommentDTO> comments) { this.comments = comments; } public boolean isLiked() { return liked; } public void setLiked(boolean liked) { this.liked = liked; } }
Python
UTF-8
461
3.359375
3
[]
no_license
import numpy as np x_1 = np.arange(12).reshape(3, 4) x_2 = np.arange(12, 24).reshape(3, 4) # print(x_1, x_2) # t_1 = np.arange(3).reshape(3, 1) t_1 = np.array([0 for i in range(x_1.shape[0])]).reshape(3, 1) y_1 = np.hstack((x_1, t_1)) # print(y_1) #! 1. 全为0全为1的数值 #! 2. 最大值的位置:np.argmax(t,axis=0) # ? numpy中随机数组:产生个2行3列的数组,每个元素值在0,10之间 p = np.random.randint(0, 10, (2, 3)) print(p)
Java
UTF-8
145
2.359375
2
[]
no_license
package abstractFactoryDesignPatternHelper; public interface EnemyShipFactory { public ESEngine addEngine(); public ESWeapon addWeapon(); }
C++
UTF-8
9,675
2.953125
3
[]
no_license
#ifndef MVRMTXIO_H #define MVRMTXIO_H #include "mvriaTypedefs.h" #include "MvrRobot.h" /** @brief Interface to digital and analog I/O and switched power outputs on MTX * core (used in Pioneer LX and other MTX-based robots). On Linux this class uses the <code>mtx</code> driver to interface with the MTX digital and analog IO, and control switched power outputs. The <code>mtx</code> driver module must be loaded for this interface to work. The <code>mtx</code> interface (<code>/dev/mtx</code>) is opened automatically in the MvrMTXIO constructor. If successful, isEnabled() will then return true. The MTX IO is organized as two sets of 8-bit "banks" of inputs, and two 8-bit "banks" of outputs. To read the state input, use getDigitalIOInputMon1() and getDigitalIOInputMon2(), or getDigitalBankInputs() with bank index 0 or 1. To set state of output, use setDigitalOutputControl1() and setDigitalOutputControl2(), or setDigitalBankOutputs() with bank index 2 or 3. Multile MvrMTXIO objects may be instatiated; a shared may be locked and unlocked by calling lock() and unlock(). @ingroup OptionalClasses @ingroup DeviceClasses @ingroup MTX @linuxonly */ class MvrMTXIO { public: enum Direction { DIGITAL_INPUT, DIGITAL_OUTPUT, INVALID }; /// Constructor MVREXPORT MvrMTXIO(const char * dev = "/dev/mtx"); /// Destructor MVREXPORT virtual ~MvrMTXIO(void); /// tries to close the device. Returns false if operation failed MVREXPORT bool closeIO(void); /// returns true if the device is opened and operational bool isEnabled(void) { return myEnabled; } /// returns true if analog values are supported MVREXPORT bool isAnalogSupported(void) { return myAnalogEnabled; } /// @note not yet implemented. bool getAnalogValue(int port, double *val) { return true; } /// @note not yet implemented bool getAnalogValueRaw(int port, int *val) { return true; } /// Get/set value of digital IO banks (see class description above) /// Banks are 0-indexed. /// @{ MVREXPORT Direction getDigitalBankDirection(int bank); MVREXPORT bool setDigitalBankOutputs(int bank, unsigned char val); MVREXPORT bool getDigitalBankInputs(int bank, unsigned char *val); MVREXPORT bool getDigitalBankOutputs(int bank, unsigned char *val); /// @} /// Set one bit of an output bank. @a bank and @a bit are 0-indexed. bool setDigitalOutputBit(int bank, int bit) { unsigned char val; if(!getDigitalBankOutputs(bank, &val)) return false; return setDigitalBankOutputs( bank, val | (1 << bit) ); } /// Get one bit of an input bank. @a bank and @a bit are 0-indexed. bool getDigitalInputBit(int bank, int bit) { unsigned char val = 0; getDigitalBankInputs(bank, &val); return val & (1 << bit); } /// get/set value of power output controls (see robot manual for information /// on what components and user outputs are controlled). Banks are 0-indexed. /// @{ MVREXPORT bool setPeripheralPowerBankOutputs(int bank, unsigned char val); MVREXPORT bool getPeripheralPowerBankOutputs(int bank, unsigned char *val); /// @} /// Set one power output. @a bank and @a bit are 0-indexed. bool setPowerOutput(int bank, int bit, bool on) { unsigned char val = 0; if(!getPeripheralPowerBankOutputs(bank, &val)) return false; if (on) return setPeripheralPowerBankOutputs(bank, val & (1 << bit)); else return setPeripheralPowerBankOutputs(bank, val ^ (1 << bit)); } /// Lock global (shared) mutex for all MvrMTXIO instances. /// This allows multiple access to MTX IO (through multiple MvrMTXIO objects). MVREXPORT int lock(void){ return(ourMutex.lock()); } /// Unlock global (shared) mutex for all MvrMTXIO instances. /// This allows multiple access to MTX IO (through multiple MvrMTXIO objects). MVREXPORT int unlock(void){ return(ourMutex.unlock()); } /// Try to lock without blocking (see MvrMutex::tryLock()) MVREXPORT int tryLock() {return(ourMutex.tryLock());} /// gets the Firmware Revision MVREXPORT unsigned char getFirmwareRevision() { return myFirmwareRevision; } /// gets the Firmware Version MVREXPORT unsigned char getFirmwareVersion() { return myFirmwareVersion; } /// gets the Compatibility Code MVREXPORT unsigned char getCompatibilityCode() { return myCompatibilityCode; } /// gets the MTX FPGA Type MVREXPORT unsigned char getFPGAType() { return myFPGAType; } /// gets the values of digital input/output monitoring registers 1 & 2 /// @{ MVREXPORT bool getDigitalIOInputMon1(unsigned char *val); MVREXPORT bool getDigitalIOInputMon2(unsigned char *val); MVREXPORT bool getDigitalIOOutputMon1(unsigned char *val); MVREXPORT bool getDigitalIOOutputMon2(unsigned char *val); /// @} /// get the Light Pole IO Output Control Register MVREXPORT bool getLightPole(unsigned char *val); /// sets the Light Pole IO Output Control Register MVREXPORT bool setLightPole(unsigned char *val); /// @internal MVREXPORT bool getLPCTimeUSec(MvrTypes::UByte4 *timeUSec); /// @internal MVREXPORT MvrRetFunctor1<bool, MvrTypes::UByte4 *> *getLPCTimeUSecCB(void) { return &myLPCTimeUSecCB; } /// gets/sets the Semaphore Registers /// @internal //@{ MVREXPORT bool setSemaphore1(unsigned char *val); MVREXPORT bool getSemaphore1(unsigned char *val); MVREXPORT bool setSemaphore2(unsigned char *val); MVREXPORT bool getSemaphore2(unsigned char *val); MVREXPORT bool setSemaphore3(unsigned char *val); MVREXPORT bool getSemaphore3(unsigned char *val); MVREXPORT bool setSemaphore4(unsigned char *val); MVREXPORT bool getSemaphore4(unsigned char *val); //@} /// gets the bumper Input Monitoring Reg /// @internal MVREXPORT bool getBumperInput(unsigned char *val); /// gets the Power Status Register /// @internal MVREXPORT bool getPowerStatus1(unsigned char *val); /// gets the Power Status Register 2 /// @internal MVREXPORT bool getPowerStatus2(unsigned char *val); /// gets the LIDAR Safety Status Register MVREXPORT bool getLIDARSafety(unsigned char *val); /// gets the ESTOP status Registers /// @internal //@{ MVREXPORT bool getESTOPStatus1(unsigned char *val); MVREXPORT bool getESTOPStatus2(unsigned char *val); MVREXPORT bool getESTOPStatus3(unsigned char *val); MVREXPORT bool getESTOPStatus4(unsigned char *val); /// Compares the high nibble of this byte against the passed in val, returns true if it matches MVREXPORT bool compareESTOPStatus4HighNibbleAgainst(int val); //@} /// gets/sets Digital IO Output Control Registers 1 &amp; 2 //@{ MVREXPORT bool getDigitalOutputControl1(unsigned char *val); MVREXPORT bool setDigitalOutputControl1(unsigned char *val); MVREXPORT bool getDigitalOutputControl2(unsigned char *val); MVREXPORT bool setDigitalOutputControl2(unsigned char *val); //@} /// gets/sets the Peripheral Power Control Regs 1 &amp; 2 /// These control power to core and robot components, and to user/auxilliary /// power outputs. Refer to robot manual for information on which components /// and outputs are controlled by which bits in the peripheral power bitmasks. //@{ MVREXPORT bool getPeripheralPower1(unsigned char *val); ///< bank 0 MVREXPORT bool setPeripheralPower1(unsigned char *val); ///< bank 0 MVREXPORT bool getPeripheralPower2(unsigned char *val); ///< bank 1 MVREXPORT bool setPeripheralPower2(unsigned char *val); ///< bank 1 MVREXPORT bool getPeripheralPower3(unsigned char *val); ///< bank 2 MVREXPORT bool setPeripheralPower3(unsigned char *val); ///< bank 2 //@} /// gets the motion power status MVREXPORT bool getMotionPowerStatus(unsigned char *val); /// gets/sets the LIDAR Control Reg /// @internal //@{ MVREXPORT bool getLIDARControl(unsigned char *val); MVREXPORT bool setLIDARControl(unsigned char *val); //@} /// gets analog Block 1 & 2 //@{ MVREXPORT bool getAnalogIOBlock1(int analog, unsigned short *val); MVREXPORT bool getAnalogIOBlock2(int analog, unsigned short *val); MVREXPORT bool setAnalogIOBlock2(int analog, unsigned short *val); //@} /// This returns a conversion of the bits to a decimal value, /// currently assumed to be in the 0-5V range /// @internal MVREXPORT bool getAnalogValue(double *val); /// @internal MVREXPORT bool getAnalogValueRaw(int *val); protected: bool getLPCTimer0(unsigned char *val); bool getLPCTimer1(unsigned char *val); bool getLPCTimer2(unsigned char *val); bool getLPCTimer3(unsigned char *val); static MvrMutex ourMutex; int myFD; bool myEnabled; bool myAnalogEnabled; unsigned char myFirmwareRevision; unsigned char myFirmwareVersion; unsigned char myCompatibilityCode; unsigned char myFPGAType; struct MTX_IOREQ{ unsigned short myReg; unsigned short mySize; union { unsigned int myVal; unsigned int myVal32; unsigned short myVal16; unsigned char myVal8; //unsigned char myVal128[16]; } myData; }; int myNumBanks; unsigned char myDigitalBank1; unsigned char myDigitalBank2; unsigned char myDigitalBank3; unsigned char myDigitalBank4; MvrRetFunctorC<bool, MvrMTXIO> myDisconnectCB; MvrRetFunctor1C<bool, MvrMTXIO, MvrTypes::UByte4 *> myLPCTimeUSecCB; }; //#endif // SWIG #endif // ARMTXIO_H
Python
UTF-8
26,039
2.90625
3
[ "MIT" ]
permissive
# This has several modification relative to previous code. Namely, `Mutation` has been split out. import pyrosetta import re, os, csv, json from typing import Optional, List, Dict, Union, Any, Callable, Tuple class Mutation: """ A mutation is an object that has all the details of the mutation. A variant, as interpreted in ``Model.score_mutations`` is a pose with a mutation. """ _name3 = {'A': 'ALA', 'C': 'CYS', 'D': 'ASP', 'E': 'GLU', 'F': 'PHE', 'G': 'GLY', 'H': 'HIS', 'I': 'ILE', 'L': 'LEU', 'K': 'LYS', 'M': 'MET', 'N': 'ASN', 'P': 'PRO', 'Q': 'GLN', 'R': 'ARG', 'S': 'SER', 'T': 'THR', 'V': 'VAL', 'W': 'TRP', 'Y': 'TYR'} def __init__(self, mutation_name: str, chain: str, pose: pyrosetta.Pose): self.mutation = self.parse_mutation(mutation_name) rex = re.match('(\w)(\d+)(\w)', self.mutation) self.pdb_resi = int(rex.group(2)) self.chain = chain self.from_resn1 = rex.group(1) self.from_resn3 = self._name3[rex.group(1)] self.to_resn1 = rex.group(3) self.to_resn3 = self._name3[rex.group(3)] pose2pdb = pose.pdb_info().pdb2pose self.pose_resi = pose2pdb(res=self.pdb_resi, chain=self.chain) if self.pose_resi != 0: self.pose_residue = pose.residue(self.pose_resi) self.pose_resn1 = self.pose_residue.name1() self.pose_resn3 = self.pose_residue.name3() else: self.pose_residue = None self.pose_resn1 = None self.pose_resn3 = None def parse_mutation(self, mutation): if mutation[:2] == 'p.': mutation = mutation.replace('p.', '') if mutation[1].isdigit(): return mutation else: value2key = lambda value: list(self._name3.keys())[list(self._name3.values()).index(value.upper())] return value2key(mutation[:3]) + mutation[3:-3] + value2key(mutation[-3:]) def is_valid(self): return self.pose_resn1 == self.from_resn1 def assert_valid(self): assert self.is_valid(), f'residue {self.pose_resi}(pose)/{self.pdb_resi}(pdb) ' + \ f'is a {self.pose_resn3}, not a {self.from_resn3}' def __str__(self): return self.mutation class Variant: """ Copy pasted from PI4KA <- GNB2 <- SnoopCatcher """ # https://www.rosettacommons.org/docs/latest/rosetta_basics/scoring/score-types term_meanings = { "fa_atr": "Lennard-Jones attractive between atoms in different residues (r^6 term, London dispersion forces).", "fa_rep": "Lennard-Jones repulsive between atoms in different residues (r^12 term, Pauli repulsion forces).", "fa_sol": "Lazaridis-Karplus solvation energy.", "fa_intra_rep": "Lennard-Jones repulsive between atoms in the same residue.", "fa_elec": "Coulombic electrostatic potential with a distance-dependent dielectric.", "pro_close": "Proline ring closure energy and energy of psi angle of preceding residue.", "hbond_sr_bb": "Backbone-backbone hbonds close in primary sequence.", "hbond_lr_bb": "Backbone-backbone hbonds distant in primary sequence.", "hbond_bb_sc": "Sidechain-backbone hydrogen bond energy.", "hbond_sc": "Sidechain-sidechain hydrogen bond energy.", "dslf_fa13": "Disulfide geometry potential.", "rama": "Ramachandran preferences.", "omega": "Omega dihedral in the backbone. A Harmonic constraint on planarity with standard deviation of ~6 deg.", "fa_dun": "Internal energy of sidechain rotamers as derived from Dunbrack's statistics (2010 Rotamer Library used in Talaris2013).", "p_aa_pp": "Probability of amino acid at Φ/Ψ.", "ref": "Reference energy for each amino acid. Balances internal energy of amino acid terms. Plays role in design.", "METHOD_WEIGHTS": "Not an energy term itself, but the parameters for each amino acid used by the ref energy term.", "lk_ball": "Anisotropic contribution to the solvation.", "lk_ball_iso": "Same as fa_sol; see below.", "lk_ball_wtd": "weighted sum of lk_ball & lk_ball_iso (w1*lk_ball + w2*lk_ball_iso); w2 is negative so that anisotropic contribution(lk_ball) replaces some portion of isotropic contribution (fa_sol=lk_ball_iso).", "lk_ball_bridge": "Bonus to solvation coming from bridging waters, measured by overlap of the 'balls' from two interacting polar atoms.", "lk_ball_bridge_uncpl": "Same as lk_ball_bridge, but the value is uncoupled with dGfree (i.e. constant bonus, whereas lk_ball_bridge is proportional to dGfree values).", "fa_intra_atr_xover4": "Intra-residue LJ attraction, counted for the atom-pairs beyond torsion-relationship.", "fa_intra_rep_xover4": "Intra-residue LJ repulsion, counted for the atom-pairs beyond torsion-relationship.", "fa_intra_sol_xover4": "Intra-residue LK solvation, counted for the atom-pairs beyond torsion-relationship.", "fa_intra_elec": "Intra-residue Coulombic interaction, counted for the atom-pairs beyond torsion-relationship.", "rama_prepro": "Backbone torsion preference term that takes into account of whether preceding amono acid is Proline or not.", "hxl_tors": "Sidechain hydroxyl group torsion preference for Ser/Thr/Tyr, supersedes yhh_planarity (that covers L- and D-Tyr only).", "yhh_planarity": "Sidechain hydroxyl group torsion preference for Tyr, superseded by hxl_tors" } def __init__(self, pose: pyrosetta.Pose, modelname: str, scorefxn: Optional[pyrosetta.ScoreFunction] = None, strict_about_starting_residue: bool = True, verbose: bool = False): self.pose = pose self.modelname = modelname self.strict_about_starting_residue = bool(strict_about_starting_residue) if scorefxn is None: self.scorefxn = pyrosetta.get_fa_scorefxn() else: self.scorefxn = scorefxn self.verbose = verbose @classmethod def from_file(cls, filename: str, params_filenames: Optional[List[str]] = None, **kwargs): return cls(pose=cls._load_pose_from_file(filename, params_filenames), **kwargs) @classmethod def _load_pose_from_file(cls, filename: str, params_filenames: Optional[List[str]] = None) -> pyrosetta.Pose: """ Loads a pose from filename with the params in the params_folder :param filename: :param params_filenames: :return: """ pose = pyrosetta.Pose() if params_filenames: params_paths = pyrosetta.rosetta.utility.vector1_string() params_paths.extend(params_filenames) pyrosetta.generate_nonstandard_residue_set(pose, params_paths) pyrosetta.rosetta.core.import_pose.pose_from_file(pose, filename) return pose def relax_around_mover(self, pose: pyrosetta.Pose, mutation: Optional[Mutation] = None, resi: int = None, chain: str = None, cycles=5, distance=5, cartesian=False, own_chain_only=False) -> None: """ Relaxes pose ``distance`` around resi:chain or mutation :param resi: PDB residue number. :param chain: :param pose: :param cycles: of relax (3 quick, 15 thorough) :param distance: :param cartesian: :return: """ if mutation is None and resi is None: raise ValueError('mutation or resi+chain required') elif mutation is not None: resi = mutation.pose_resi chain = None else: pass if pose is None: pose = self.pose movemap = pyrosetta.MoveMap() #### n = self.get_neighbour_vector(pose=pose, resi=resi, chain=chain, distance=distance, own_chain_only=own_chain_only) # print(pyrosetta.rosetta.core.select.residue_selector.ResidueVector(n)) movemap.set_bb(False) movemap.set_bb(allow_bb=n) movemap.set_chi(False) movemap.set_chi(allow_chi=n) movemap.set_jump(False) relax = pyrosetta.rosetta.protocols.relax.FastRelax(self.scorefxn, cycles) relax.set_movemap(movemap) relax.set_movemap_disables_packing_of_fixed_chi_positions(True) relax.cartesian(cartesian) relax.apply(pose) def get_neighbour_vector(self, pose: pyrosetta.Pose, resi: int, chain: str, distance: int, include_focus_in_subset: bool = True, own_chain_only: bool = False) -> pyrosetta.rosetta.utility.vector1_bool: resi_sele = pyrosetta.rosetta.core.select.residue_selector.ResidueIndexSelector() if chain is None: # pose numbering. resi_sele.set_index(resi) else: resi_sele.set_index(pose.pdb_info().pdb2pose(chain=chain, res=resi)) NeighborhoodResidueSelector = pyrosetta.rosetta.core.select.residue_selector.NeighborhoodResidueSelector neigh_sele = NeighborhoodResidueSelector(resi_sele, distance=distance, include_focus_in_subset=include_focus_in_subset) if own_chain_only and chain is not None: chain_sele = pyrosetta.rosetta.core.select.residue_selector.ChainSelector(chain) and_sele = pyrosetta.rosetta.core.select.residue_selector.AndResidueSelector(neigh_sele, chain_sele) return and_sele.apply(pose) else: return neigh_sele.apply(pose) def parse_mutation(self, mutation: Union[str, Mutation], chain, pose: pyrosetta.Pose = None): if pose is None: pose = self.pose if isinstance(mutation, str): mutant = Mutation(mutation, chain, pose) elif isinstance(mutation, Mutation): mutant = mutation else: raise TypeError(f'Does not accept mutation of type {mutation.__class__.__name__}') if mutant.pose_resi == 0: raise ValueError('Not in pose') if self.strict_about_starting_residue: mutant.assert_valid() return mutant def make_mutant(self, pose: pyrosetta.Pose, mutation: Union[str, Mutation], chain='A', distance: int = 10, cycles: int = 5 ) -> pyrosetta.Pose: """ Make a point mutant (``A23D``). :param pose: pose :param mutation: :param chain: :return: """ if pose is None: mutant = self.pose.clone() else: mutant = pose.clone() if isinstance(mutation, str): mutation = Mutation(mutation, chain, mutant) MutateResidue = pyrosetta.rosetta.protocols.simple_moves.MutateResidue MutateResidue(target=mutation.pose_resi, new_res=mutation.to_resn3).apply(mutant) self.relax_around_mover(mutant, mutation=mutation, distance=distance, cycles=cycles, own_chain_only=False) return mutant def score_interface(self, pose: pyrosetta.Pose, interface: str) -> Dict[str, float]: if pose is None: pose = self.pose assert self.has_interface(pose, interface), f'There is no {interface}' ia = pyrosetta.rosetta.protocols.analysis.InterfaceAnalyzerMover(interface) ia.apply(pose) return {'complex_energy': ia.get_complex_energy(), 'separated_interface_energy': ia.get_separated_interface_energy(), 'complexed_sasa': ia.get_complexed_sasa(), 'crossterm_interface_energy': ia.get_crossterm_interface_energy(), 'interface_dG': ia.get_interface_dG(), 'interface_delta_sasa': ia.get_interface_delta_sasa()} def has_interface(self, pose: pyrosetta.Pose, interface: str) -> bool: if pose is None: pose = self.pose pose2pdb = pose.pdb_info().pose2pdb have_chains = {pose2pdb(r).split()[1] for r in range(1, pose.total_residue() + 1)} want_chains = set(interface.replace('_', '')) return have_chains == want_chains def has_residue(self, pose: pyrosetta.Pose, resi: int, chain: str) -> bool: if pose is None: pose = self.pose pdb2pose = pose.pdb_info().pdb2pose r = pdb2pose(res=resi, chain=chain) return r != 0 def vector2list(self, vector: pyrosetta.rosetta.utility.vector1_bool) -> pyrosetta.rosetta.std.list_unsigned_long_t: rv = pyrosetta.rosetta.core.select.residue_selector.ResidueVector(vector) x = pyrosetta.rosetta.std.list_unsigned_long_t() assert len(rv) > 0, 'Vector is empty!' for w in rv: x.append(w) return x def CA_RMSD(self, poseA: pyrosetta.Pose, poseB: pyrosetta.Pose, resi: int, chain: str, distance: int) -> float: n = self.get_neighbour_vector(pose=poseA, resi=resi, chain=chain, distance=distance) residues = self.vector2list(n) return pyrosetta.rosetta.core.scoring.CA_rmsd(poseA, poseB, residues) def FA_RMSD(self, poseA: pyrosetta.Pose, poseB: pyrosetta.Pose, resi: int, chain: str, distance: int) -> float: n = self.get_neighbour_vector(pose=poseA, resi=resi, chain=chain, distance=distance, include_focus_in_subset=False) residues = self.vector2list(n) # pyrosetta.rosetta.core.scoring.automorphic_rmsd(residueA, residueB, False) return pyrosetta.rosetta.core.scoring.all_atom_rmsd(poseA, poseB, residues) def does_contain(self, mutation: Union[Mutation, str], chain: Optional[str] = None) -> bool: assert isinstance(mutation, Mutation) or chain is not None, 'mutation as str requires chain.' if isinstance(mutation, str): mutation = Mutation(mutation, chain, self.pose) if mutation.pose_resi == 0: return False if mutation.pose_resn1 not in mutation._name3.keys(): return False else: return True def score_mutation(self, mutation_name: str, chain: str, distance: int, cycles: int, interfaces, ref_interface_dG: Dict[str, float], final_func: Optional[Callable] = None, preminimise: bool = False) -> Tuple[Dict[str, float], pyrosetta.Pose, pyrosetta.Pose]: """ Scores the mutation ``mutation_name`` (str or Mutation instance) returning three objects: a dict of scores, the wt (may differ from pose if preminimise=True) and mutant pose :param mutation_name: :param chain: :param distance: :param cycles: :param interfaces: :param ref_interface_dG: :param final_func: :param preminimise: :return: """ mutation = self.parse_mutation(mutation_name, chain) if self.verbose: print(mutation) if not self.does_contain(mutation): raise ValueError('Absent') if preminimise: premutant = self.pose.clone() self.relax_around_mover(premutant, mutation=mutation, distance=distance, cycles=cycles) if self.verbose: print('preminimisation complete') else: premutant = self.pose n = self.scorefxn(premutant) variant = self.make_mutant(premutant, mutation=mutation, distance=distance, cycles=cycles) if self.verbose: print('mutant made') variant.dump_scored_pdb(f'variants/{self.modelname}.{mutation}.pdb', self.scorefxn) m = self.scorefxn(variant) data = {'model': self.modelname, 'mutation': str(mutation), 'complex_ddG': m - n, 'complex_native_dG': n, 'complex_mutant_dG': m, 'FA_RMSD': self.FA_RMSD(self.pose, variant, resi=mutation.pose_resi, chain=None, distance=distance), 'CA_RMSD': self.CA_RMSD(self.pose, variant, resi=mutation.pose_resi, chain=None, distance=distance) } # interfaces for interface_name, interface_scheme in interfaces: if self.has_interface(variant, interface_scheme): if preminimise: ref_interface_dG[interface_name] = self.score_interface(premutant, interface_scheme)[ 'interface_dG'] if self.verbose: print(f'{interface_name} ({interface_scheme}) applicable to {self.modelname}') i = self.score_interface(variant, interface_scheme)['interface_dG'] else: print(f'{interface_name} ({interface_scheme}) not applicable to {self.modelname}') i = float('nan') data[f'{interface_name}_interface_native_dG'] = ref_interface_dG[interface_name] data[f'{interface_name}_interface_mutant_dG'] = i data[f'{interface_name}_interface_ddG'] = i - ref_interface_dG[interface_name] if self.verbose: print('interface scored') # raw wt_scoredex = self.get_wscoredict(premutant) mut_scoredex = self.get_wscoredict(variant) delta_scoredex = self.delta_scoredict(mut_scoredex, wt_scoredex) if self.verbose: print('scores stored') # movement data['wt_rmsd'] = self.movement(original=premutant, resi=mutation.pdb_resi, chain=chain, distance=distance) data['mut_rmsd'] = self.movement(original=premutant, resi=mutation.pdb_resi, chain=chain, distance=distance) data['ratio_rmsd'] = data['mut_rmsd']/data['wt_rmsd'] if self.verbose: print('movement assessed') data = {**data, **self.prefix_dict(wt_scoredex, 'wt'), **self.prefix_dict(mut_scoredex, 'mut'), **self.prefix_dict(delta_scoredex, 'delta')} if final_func is not None: # callable final_func(data, premutant, variant) if self.verbose: print('extra step done.') return data, premutant, variant def get_scoredict(self, pose: pyrosetta.Pose) -> Dict[str, float]: """ Given a pose get the global scores. """ a = pose.energies().total_energies_array() return dict(zip(a.dtype.fields.keys(), a.tolist()[0])) def get_wscoredict(self, pose: pyrosetta.Pose) -> Dict[str, float]: scoredex = self.get_scoredict(pose) stm = pyrosetta.rosetta.core.scoring.ScoreTypeManager() return {k: scoredex[k] * self.scorefxn.get_weight(stm.score_type_from_name(k)) for k in scoredex} def delta_scoredict(self, minuend: Dict[str, float], subtrahend: Dict[str, float]) -> Dict[str, float]: """ minuend - subtrahend = difference given two dict return the difference -without using pandas. """ assert all([isinstance(v, float) for v in [*minuend.values(), *subtrahend.values()]]), 'Float only, please...' minuend_keys = set(minuend.keys()) subtrahend_keys = set(subtrahend.keys()) common_keys = minuend_keys & subtrahend_keys minuend_unique_keys = minuend_keys - subtrahend_keys subtrahend_unique_keys = minuend_keys - subtrahend_keys return {**{k: minuend[k] - subtrahend[k] for k in common_keys}, # common **{k: minuend[k] - 0 for k in minuend_unique_keys}, # unique **{k: 0 - subtrahend[k] for k in subtrahend_unique_keys} # unique } def prefix_dict(self, dex: Dict[str, Any], prefix: str) -> Dict[str, Any]: return {f'{prefix}_{k}': v for k, v in dex.items()} def score_mutations(self, mutations, chain='A', interfaces=(), # list of two: name, scheme preminimise=False, distance=10, cycles=5, final_func: Optional[Callable] = None) -> List[Dict[str, Union[float, str]]]: if not os.path.exists('variants'): os.mkdir('variants') data = [] ## wt ref_interface_dG = {} scores = {} # not written to csv file. if not preminimise: n = self.scorefxn(self.pose) for interface_name, interface_scheme in interfaces: ref_interface_dG[interface_name] = self.score_interface(self.pose, interface_scheme)['interface_dG'] else: pass # calculated for each. ## muts for mutation_name in mutations: try: datum, premutant, mutant = self.score_mutation(mutation_name=mutation_name, chain=chain, distance=distance, cycles=cycles, interfaces=interfaces, ref_interface_dG=ref_interface_dG, final_func=final_func, preminimise=preminimise) except Exception as error: msg = f"{error.__class__.__name__}: {error}" print(msg) datum = {'model': self.modelname, 'mutation': str(mutation_name), 'complex_ddG': msg } data.append(datum) return data # ====== movement # this code is experimental def movement(self, original: pyrosetta.Pose, resi: int, chain: str, distance: int, trials: int = 50, temperature: int = 1.0, replicate_number: int = 10): """ This method adapted from a notebook of mine, but not from an official source, is not well written. It should be a filter and score combo. It returns the largest bb_rmsd of the pdb residue resi following backrub. """ n = self.get_neighbour_vector(pose=original, resi=resi, chain=chain, distance=distance, own_chain_only=False) # resi if chain is None: # pose numbering. target_res = resi else: target_res = original.pdb_info().pdb2pose(chain=chain, res=resi) # prep rv = pyrosetta.rosetta.core.select.residue_selector.ResidueVector(n) backrub = pyrosetta.rosetta.protocols.backrub.BackrubMover() backrub.set_pivot_residues(rv) # https://www.rosettacommons.org/docs/latest/scripting_documentation/RosettaScripts/Movers/movers_pages/GenericMonteCarloMover monégasque = pyrosetta.rosetta.protocols.monte_carlo.GenericMonteCarloMover(maxtrials=trials, max_accepted_trials=trials, # gen.max_accepted_trials() = 0 task_scaling=5, # gen.task_scaling() mover=backrub, temperature=temperature, sample_type='low', drift=True) monégasque.set_scorefxn(self.scorefxn) # monégasque.add_filter(filters , False , 0.005 , 'low' , True ) # define the first 4 atoms (N C CA O) am = pyrosetta.rosetta.utility.vector1_unsigned_long(4) for i in range(1, 5): am[i] = i # find most deviant best_r = 0 for i in range(replicate_number): variant = original.clone() monégasque.apply(variant) if monégasque.accept_counter() > 0: variant = monégasque.last_accepted_pose() # pretty sure redundant # bb_rmsd is all residues: pyrosetta.rosetta.core.scoring.bb_rmsd(pose, ori) r = pyrosetta.rosetta.core.scoring.residue_rmsd_nosuper(variant.residue(target_res), original.residue(target_res), am) if r > best_r: best_r = r return best_r
PHP
UTF-8
1,009
3.90625
4
[]
no_license
<?php require_once('page.inc.php'); class Math { // Constantes de classes : // ----------------------- const pi = 3.14159; // Méthode statique : // ------------------ static function carre($valeur) { return $valeur * $valeur; } } echo "Math::pi = " . Math::pi . "\n"; echo "</br>"; echo "Carré de 8 = " . Math::carre(8) . "\n"; /* Conversion de classe en chaîne : -------------------------------- */ class Affichable { public $testUn; public $testDeux; public function __toString() { return (var_export($this , TRUE)); } } echo "<br>Afficher une classe :<br>"; $p = new Affichable(); echo $p; echo "</br>"; /* API d'introspection : */ $classe = new ReflectionClass("Page"); echo "<pre>"; echo $classe; echo "</pre>"; echo "<br><br>"; class A { } class B extends A { } // Vérification du Type de classe : $b = new B(); if($b instanceof B) { echo "<br>ok !<br/>"; } if($b instanceof A) { echo "ok !<br/>"; }
Java
UTF-8
748
3.59375
4
[]
no_license
/** * Author : Zhaolong Zhong * Date : 2015 12:10:46 AM * Problem: * Remove all elements from a linked list of integers that have value val. */ package list; import linkedlist.ListNode; public class RemoveElements { public ListNode removeElements(ListNode head, int val) { if (head == null) return null; while (head.val == val) { head = head.next; if (head == null) return null; } ListNode pre = head; ListNode cur = head.next; while (cur != null) { if (cur.val == val) { cur = cur.next; pre.next = null; } else { pre.next = cur; pre = cur; cur = cur.next; } } return head; } }
JavaScript
UTF-8
1,666
4.28125
4
[]
no_license
// 2 - Pari e Dispari // L'utente sceglie pari o dispari e inserisce un numero da 1 a 5. // Generiamo un numero random (sempre da 1 a 5) per il computer (usando una funzione). // Sommiamo i due numeri // Stabiliamo se la somma dei due numeri è pari o dispari (usando una funzione) // Dichiariamo chi ha vinto. var primaScelta = 1; var sceltaUtente; do { if (primaScelta == 1) { sceltaUtente = prompt('pari o dispari ?').toLowerCase(); primaScelta++; } else { sceltaUtente = prompt('Ho detto pari o dispari ?!').toLowerCase(); } } while (sceltaUtente != 'pari' && sceltaUtente !='dispari'); console.log('Utente ha scelto: ' + sceltaUtente); function numeroRandom (min, max) { num = Math.floor(Math.random() * (max - min + 1) + min ); return num; } var numeroPc = numeroRandom(1, 5); console.log('numero del PC: ' + numeroPc); var numeroUtente = 0; var primaVolta = 1; while (numeroUtente < 1 || numeroUtente > 5) { if (primaVolta == 1) { numeroUtente = parseInt(prompt('inserisci un numero tra 1 e 5')); primaVolta++; } else { numeroUtente = parseInt(prompt('ho detto un numero tra 1 e 5 !')); } } console.log('numero Utente: ' + numeroUtente); var somma = numeroPc + numeroUtente; console.log('la somma e: ' + somma); function verificaPari (num) { return num % 2 == 0; } if (sceltaUtente == 'pari' && verificaPari(somma)) { alert('hai vinto'); console.log('hai vinto'); } else if (sceltaUtente == 'dispari' && verificaPari(somma) == false) { alert('hai vinto'); console.log('hai vinto'); } else { alert('hai perso'); console.log('hai perso'); }
Python
UTF-8
931
3.34375
3
[]
no_license
# Time Complexity : O(N) # Space Complexity : O(1) # Did this code successfully run on Leetcode : Yes # Any problem you faced while coding this : Couldn't figure out a one pass solution :( # Your code here along with comments explaining your approach class Solution: def sortColors(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ r = 0 w = 0 b = 0 for i in range(len(nums)): if nums[i] == 0: r +=1 if nums[i] == 1: w +=1 if nums[i] == 2: b +=1 i =0 while i < r: nums[i] = 0 i = i+1 while i < r+w: nums[i] = 1 i = i+1 while i < r+w+b: nums[i] = 2 i = i+1
Markdown
UTF-8
16,605
2.953125
3
[]
no_license
## 一、概念 幂等性, 通俗的说就是一个接口, 多次发起同一个请求, 必须保证操作只能执行一次 比如: - 订单接口, 不能多次创建订单 - 支付接口, 重复支付同一笔订单只能扣一次钱 - 支付宝回调接口, 可能会多次回调, 必须处理重复回调 - 普通表单提交接口, 因为网络超时等原因多次点击提交, 只能成功一次 等等 ## 二、常见解决方案 - 唯一索引 -- 防止新增脏数据 - token机制 -- 防止页面重复提交 - 悲观锁 -- 获取数据的时候加锁(锁表或锁行) - 乐观锁 -- 基于版本号version实现, 在更新数据那一刻校验数据 - 分布式锁 -- redis(jedis、redisson)或zookeeper实现 - 状态机 -- 状态变更, 更新数据时判断状态 ## 三、本文实现 本文采用第2种方式实现, 即通过redis + token机制实现接口幂等性校验 ## 四、实现思路 为需要保证幂等性的每一次请求创建一个唯一标识token, 先获取token, 并将此token存入redis, 请求接口时, 将此token放到header或者作为请求参数请求接口, 后端接口判断redis中是否存在此token: - 如果存在, 正常处理业务逻辑, 并从redis中删除此token, 那么, 如果是重复请求, 由于token已被删除, 则不能通过校验, 返回请勿重复操作提示 - 如果不存在, 说明参数不合法或者是重复请求, 返回提示即可 ## 五、项目简介 - springboot - redis - @ApiIdempotent注解 + 拦截器对请求进行拦截 - @ControllerAdvice全局异常处理 - 压测工具: jmeter **说明:** 本文重点介绍幂等性核心实现, 关于springboot如何集成redis、ServerResponse、ResponseCode等细枝末节不在本文讨论范围之内, 有兴趣的小伙伴可以查看我的Github项目: > https://github.com/wangzaiplus/springboot/tree/wxw ## 六、代码实现 **pom** ``` <!-- Redis-Jedis --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency> <!--lombok 本文用到@Slf4j注解, 也可不引用, 自定义log即可--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.10</version> </dependency> ``` **JedisUtil** ``` package com.wangzaiplus.test.util; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; @Component @Slf4j public class JedisUtil { @Autowired private JedisPool jedisPool; private Jedis getJedis() { return jedisPool.getResource(); } /** * 设值 * * @param key * @param value * @return */ public String set(String key, String value) { Jedis jedis = null; try { jedis = getJedis(); return jedis.set(key, value); } catch (Exception e) { log.error("set key:{} value:{} error", key, value, e); return null; } finally { close(jedis); } } /** * 设值 * * @param key * @param value * @param expireTime 过期时间, 单位: s * @return */ public String set(String key, String value, int expireTime) { Jedis jedis = null; try { jedis = getJedis(); return jedis.setex(key, expireTime, value); } catch (Exception e) { log.error("set key:{} value:{} expireTime:{} error", key, value, expireTime, e); return null; } finally { close(jedis); } } /** * 取值 * * @param key * @return */ public String get(String key) { Jedis jedis = null; try { jedis = getJedis(); return jedis.get(key); } catch (Exception e) { log.error("get key:{} error", key, e); return null; } finally { close(jedis); } } /** * 删除key * * @param key * @return */ public Long del(String key) { Jedis jedis = null; try { jedis = getJedis(); return jedis.del(key.getBytes()); } catch (Exception e) { log.error("del key:{} error", key, e); return null; } finally { close(jedis); } } /** * 判断key是否存在 * * @param key * @return */ public Boolean exists(String key) { Jedis jedis = null; try { jedis = getJedis(); return jedis.exists(key.getBytes()); } catch (Exception e) { log.error("exists key:{} error", key, e); return null; } finally { close(jedis); } } /** * 设值key过期时间 * * @param key * @param expireTime 过期时间, 单位: s * @return */ public Long expire(String key, int expireTime) { Jedis jedis = null; try { jedis = getJedis(); return jedis.expire(key.getBytes(), expireTime); } catch (Exception e) { log.error("expire key:{} error", key, e); return null; } finally { close(jedis); } } /** * 获取剩余时间 * * @param key * @return */ public Long ttl(String key) { Jedis jedis = null; try { jedis = getJedis(); return jedis.ttl(key); } catch (Exception e) { log.error("ttl key:{} error", key, e); return null; } finally { close(jedis); } } private void close(Jedis jedis) { if (null != jedis) { jedis.close(); } } } ``` **自定义注解@ApiIdempotent** ``` package com.wangzaiplus.test.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 在需要保证 接口幂等性 的Controller的方法上使用此注解 */ @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface ApiIdempotent { } ``` **ApiIdempotentInterceptor拦截器** ``` package com.wangzaiplus.test.interceptor; import com.wangzaiplus.test.annotation.ApiIdempotent; import com.wangzaiplus.test.service.TokenService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.lang.reflect.Method; /** * 接口幂等性拦截器 */ public class ApiIdempotentInterceptor implements HandlerInterceptor { @Autowired private TokenService tokenService; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { if (!(handler instanceof HandlerMethod)) { return true; } HandlerMethod handlerMethod = (HandlerMethod) handler; Method method = handlerMethod.getMethod(); ApiIdempotent methodAnnotation = method.getAnnotation(ApiIdempotent.class); if (methodAnnotation != null) { check(request);// 幂等性校验, 校验通过则放行, 校验失败则抛出异常, 并通过统一异常处理返回友好提示 } return true; } private void check(HttpServletRequest request) { tokenService.checkToken(request); } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } } ``` **TokenServiceImpl** ``` package com.wangzaiplus.test.service.impl; import com.wangzaiplus.test.common.Constant; import com.wangzaiplus.test.common.ResponseCode; import com.wangzaiplus.test.common.ServerResponse; import com.wangzaiplus.test.exception.ServiceException; import com.wangzaiplus.test.service.TokenService; import com.wangzaiplus.test.util.JedisUtil; import com.wangzaiplus.test.util.RandomUtil; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.text.StrBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletRequest; @Service public class TokenServiceImpl implements TokenService { private static final String TOKEN_NAME = "token"; @Autowired private JedisUtil jedisUtil; @Override public ServerResponse createToken() { String str = RandomUtil.UUID32(); StrBuilder token = new StrBuilder(); token.append(Constant.Redis.TOKEN_PREFIX).append(str); jedisUtil.set(token.toString(), token.toString(), Constant.Redis.EXPIRE_TIME_MINUTE); return ServerResponse.success(token.toString()); } @Override public void checkToken(HttpServletRequest request) { String token = request.getHeader(TOKEN_NAME); if (StringUtils.isBlank(token)) {// header中不存在token token = request.getParameter(TOKEN_NAME); if (StringUtils.isBlank(token)) {// parameter中也不存在token throw new ServiceException(ResponseCode.ILLEGAL_ARGUMENT.getMsg()); } } if (!jedisUtil.exists(token)) { throw new ServiceException(ResponseCode.REPETITIVE_OPERATION.getMsg()); } Long del = jedisUtil.del(token); if (del <= 0) { throw new ServiceException(ResponseCode.REPETITIVE_OPERATION.getMsg()); } } } ``` **TestApplication** ``` package com.wangzaiplus.test; import com.wangzaiplus.test.interceptor.ApiIdempotentInterceptor; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @SpringBootApplication @MapperScan("com.wangzaiplus.test.mapper") public class TestApplication extends WebMvcConfigurerAdapter { public static void main(String[] args) { SpringApplication.run(TestApplication.class, args); } /** * 跨域 * @return */ @Bean public CorsFilter corsFilter() { final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource(); final CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.setAllowCredentials(true); corsConfiguration.addAllowedOrigin("*"); corsConfiguration.addAllowedHeader("*"); corsConfiguration.addAllowedMethod("*"); urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration); return new CorsFilter(urlBasedCorsConfigurationSource); } @Override public void addInterceptors(InterceptorRegistry registry) { // 接口幂等性拦截器 registry.addInterceptor(apiIdempotentInterceptor()); super.addInterceptors(registry); } @Bean public ApiIdempotentInterceptor apiIdempotentInterceptor() { return new ApiIdempotentInterceptor(); } } ``` OK, 目前为止, 校验代码准备就绪, 接下来测试验证 ## 七、测试验证 **1、获取token的控制器TokenController** ``` package com.wangzaiplus.test.controller; import com.wangzaiplus.test.common.ServerResponse; import com.wangzaiplus.test.service.TokenService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/token") public class TokenController { @Autowired private TokenService tokenService; @GetMapping public ServerResponse token() { return tokenService.createToken(); } } ``` **2、TestController, 注意@ApiIdempotent注解, 在需要幂等性校验的方法上声明此注解即可, 不需要校验的无影响** ``` package com.wangzaiplus.test.controller; import com.wangzaiplus.test.annotation.ApiIdempotent; import com.wangzaiplus.test.common.ServerResponse; import com.wangzaiplus.test.service.TestService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/test") @Slf4j public class TestController { @Autowired private TestService testService; @ApiIdempotent @PostMapping("testIdempotence") public ServerResponse testIdempotence() { return testService.testIdempotence(); } } ``` **3、获取token** ![img](https://mmbiz.qpic.cn/mmbiz_png/JfTPiahTHJhpm7YscQV1zId4HZyrewTTGM8jK6tDjwuyuzGhJxAtcGPbeWp3AU0r6h8R5uDJQ3qFqVibeXicPBMVA/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1) 查看redis ![img](https://mmbiz.qpic.cn/mmbiz_png/JfTPiahTHJhpm7YscQV1zId4HZyrewTTGVXoiaVjTnoocHNgNMNEibHnuSN9wHhGV54czUpedRmSNcic1HJnsyrcibA/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1) **4、测试接口安全性: 利用jmeter测试工具模拟50个并发请求, 将上一步获取到的token作为参数** ![img](https://mmbiz.qpic.cn/mmbiz_png/JfTPiahTHJhpm7YscQV1zId4HZyrewTTGH2fHAejfoVRoNsoUoV4XyEUHLgrsdiarWM0fH1zTM46tRXJhmseQgew/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1) ![img](https://mmbiz.qpic.cn/mmbiz_png/JfTPiahTHJhpm7YscQV1zId4HZyrewTTGEwcFtBqktexAvl6qFzibyp9W8XzYQD8icm3myH6JtwXtLGpBAiaic3FWtA/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1) **5、header或参数均不传token, 或者token值为空, 或者token值乱填, 均无法通过校验, 如token值为"abcd"** ![img](https://mmbiz.qpic.cn/mmbiz_png/JfTPiahTHJhpm7YscQV1zId4HZyrewTTGXLwOCA9X6KDwjibaGVicbovCkia1fRmOnolRrIaq3RRzAI8zVIsGBFGfw/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1) ## 八、注意点(非常重要) ![img](https://mmbiz.qpic.cn/mmbiz_png/JfTPiahTHJhpm7YscQV1zId4HZyrewTTGvibjesdw5AUs9cONrq2Vme9zuDuUfpVhZ18H9ddx8jMayHenVLwK9Yg/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1) 上图中, 不能单纯的直接删除token而不校验是否删除成功, 会出现并发安全性问题, 因为, 有可能多个线程同时走到第46行, 此时token还未被删除, 所以继续往下执行, 如果不校验jedisUtil.del(token)的删除结果而直接放行, 那么还是会出现重复提交问题, 即使实际上只有一次真正的删除操作, 下面重现一下 稍微修改一下代码: ![img](https://mmbiz.qpic.cn/mmbiz_png/JfTPiahTHJhpm7YscQV1zId4HZyrewTTG8FYPMoNdANrBH2bAJymN4Q9xTRwnicMH364GGoyoJ5s3lm7nan0tY7w/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1) 再次请求 ![img](https://mmbiz.qpic.cn/mmbiz_png/JfTPiahTHJhpm7YscQV1zId4HZyrewTTGqppdIMnHuQPuJ76K9SIObJo1ficCibd3THoxZicSacvntDAZ6h0xl6dmQ/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1) 再看看控制台 ![img](https://mmbiz.qpic.cn/mmbiz_png/JfTPiahTHJhpm7YscQV1zId4HZyrewTTGnibZMOdl5G9aFo0qmFf7ibk2y7IdXoMYRFGjcticj00bnuxHRa5Cyic1yw/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1) 虽然只有一个真正删除掉token, 但由于没有对删除结果进行校验, 所以还是有并发问题, 因此, 必须校验 ## 九、总结 其实思路很简单, 就是每次请求保证唯一性, 从而保证幂等性, 通过拦截器+注解, 就不用每次请求都写重复代码, 其实也可以利用spring aop实现, 无所谓。
Java
UTF-8
944
3.421875
3
[]
no_license
package com.aca; public class Time { public static void main(String[] args) { int hour = 23; int minute = 02; int second = 0; int secondsInADay = 24 * 60 *60; System.out.println("total seconds in a day: " + secondsInADay); // number of seconds since midnight //convert hours to seconds int totalSecondsHour = hour * 60 * 60; //convert minutes to seconds int totalSecondsMinute = minute * 60; float totalSecondsSinceMidnight = totalSecondsHour + totalSecondsMinute + second; System.out.println("total seconds since midnight: " + totalSecondsSinceMidnight); float remainingSeconds = secondsInADay - totalSecondsSinceMidnight; System.out.println("Seconds remaining: " +remainingSeconds ); //percentage of the day that has passed float percent = (totalSecondsSinceMidnight / secondsInADay) * 100; System.out.println("Percent of Day that has passed: " + percent); } }
Java
UTF-8
1,285
1.875
2
[]
no_license
package com.sjtu.adminanddealer.controller; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; /** * ImageController的单元测试类. * * @author Chuyuxuan */ @Ignore @RunWith(SpringRunner.class) @ActiveProfiles("test") @WebMvcTest(controllers = {ImageController.class}) @AutoConfigureMockMvc public class ImageControllerTest { @Autowired private MockMvc mockMvc; @Autowired private ImageController imageController; @MockBean private StringRedisTemplate redisTemplate; @Test public void testDI() throws Exception { Assert.assertNotNull(imageController); } // TODO:获取图片的逻辑不太好写单元测试,一般可以通过PostMan手动测试 }
Python
UTF-8
2,654
3.265625
3
[ "Python-2.0" ]
permissive
# -*- coding: utf-8 -*- """ Module qui permet de gerer l'encodage de certains arguments. Comme par exemple, l'encodage en base64 pour palier au probleme de caracteres speciaux non geres par les urls. """ from excalibur.exceptions import ArgumentError, DecodeAlgorithmNotFoundError import base64 class DecodeArguments(object): """ Classe contenant les differents algorithmes de decodage. Pour implementer un nouvel algorithme, une methode suivant la regle de nommage suivante decode_nomalgo doit recevoir la valeur en argument. Et retourner la valeur decodee. """ def __init__(self, f): self.f = f def __get__(self, instance, owner): self.cls = owner self.obj = instance return self.__call__ def __call__(self, *k, **kw): """ Pour chacun des arguments passes, regarde s'il doit etre decode. Et si c'est le cas, appelle la methode correspondante. """ self.ressources = k[1] self.ressource = k[0].ressource self.method_name = k[0].method self.arguments = k[0].arguments if self.ressource not in self.ressources.keys(): raise ArgumentError("ressource not found") ressource = self.ressources[self.ressource] # the check is optionnal, it occurs only if there is an entry # "arguments try: if "arguments" in ressource[self.method_name].keys(): arguments = ressource[self.method_name]["arguments"] if arguments: for argument_name in self.arguments: if "encoding" in arguments[argument_name]: algo = arguments[argument_name]["encoding"] method = getattr(self, "decode_" + algo) self.arguments[argument_name] = method( self.arguments[argument_name]) except KeyError: raise ArgumentError('Wrong ressource configuration: key not found for method %s' % self.method_name) except AttributeError: raise DecodeAlgorithmNotFoundError(algo) return self.f(self.obj, *k, **kw) def decode_base64(self, value): """ Implemente le decodage base64. """ # base64 decoding returns bytestrings decoded_value = base64.b64decode(value).decode("utf-8") return decoded_value def decode_base64url(self, value): """ safeb64 """ decoded_value = base64.urlsafe_b64decode(value.encode('utf-8'))\ .decode("utf-8") return decoded_value
JavaScript
UTF-8
3,501
2.734375
3
[]
no_license
/** * Avenue FB 登入相關方法集成 * * @param {string} appId [開發者的 appId] * @param {string} appVerifyUrl * [ * fb 個人資料完成後導向開發者 app 的 url, * 這邊會透過自動產生 form 的方式 已POST 傳送兩個參數 jAuthResponse 以及 jInformation, * 即驗證回傳物件以及個人資訊回傳物件的 JSON 字串 * ] * * @depend {jQuery, fos.routing.js} */ var AvenueFacebookHandler = function (appId, appVerifyUrl) { this.appId = appId; this.url = appVerifyUrl; this.init(); }; /** * 初始化 FB 物件 */ AvenueFacebookHandler.prototype.init = function () { var self = this; /** * 宣告fb 非同步初始化事件 */ // window.fbAsyncInit = function() { // FB.init({ // appId: self.appId, // cookie: true, // enable cookies to allow the server to access // // the session // xfbml: true, // parse social plugins on this page // version: 'v2.2' // use version 2.1 // }); // }; // Load the SDK asynchronously // (function(d, s, id) { // var js, fjs = d.getElementsByTagName(s)[0]; // if (d.getElementById(id)) return; // js = d.createElement(s); js.id = id; // js.src = "//connect.facebook.net/zh_TW/sdk.js"; // fjs.parentNode.insertBefore(js, fjs); // }(document, 'script', 'facebook-jssdk')); return this; }; /** * 透過FB物件登入avenue * * 1. FB.login 會先和 FB 進行第一步驗證 * 2. 通過後,執行驗證成功的CallBack, 該Callback 會取得使用者的個人資訊 * 3. 取得個人資訊成功後,將資料放入隱藏的表單裡提交 */ AvenueFacebookHandler.prototype.login = function () { var self = this; return FB.login(function(authResponse) { if ('connected' === authResponse.status) { self.loginSuccessCallback(authResponse); } else if ('not_authorized' === authResponse.status) { alert('開發者請登入應用程式喔!'); } else { alert('請登入臉書喔!'); } }, {scope: 'public_profile,email'}); }; /** * 驗證確定成功登入的 callBack * * @param {object} authResponse */ AvenueFacebookHandler.prototype.loginSuccessCallback = function (authResponse) { var self = this; return FB.api('/me', function(information) { self.redirecToAvenueViaAutosubmitForm(authResponse, information); }); }; /** * 透過自動提交一個隱藏表單導向 avenue後台完成登入 | 註冊 * * @param {object} authResponse * @param {object} information */ AvenueFacebookHandler.prototype.redirecToAvenueViaAutosubmitForm = function (authResponse, information) { var $form = $('<form action="' + this.url + '" name="avenueFbLogin" method="POST"></form>'); var jAuthResponse = JSON.stringify(authResponse); var jInformation = JSON.stringify(information); $form .append('<input type="hidden" name="jAuthResponse" />') .append('<input type="hidden" name="jInformation" />') ; $form.find('input[name="jAuthResponse"]').val(jAuthResponse); $form.find('input[name="jInformation"]').val(jInformation); return $form.submit(); }; /** * FB 的登出方法(應該是用不太到) */ AvenueFacebookHandler.prototype.facebookLogout = function () { FB.logout(function () { window.location.reload(); }); return this; };
C#
UTF-8
1,288
2.625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ComponentModel; namespace RailwayCL { public class ShopUtils { private static ShopUtils shopUtils; private string cbValue = "Id"; private string cbDisplay = "Name"; private string cbNonSelected = "ВЫБЕРИТЕ "; private string className = "Shop"; private ShopUtils() { } public static ShopUtils GetInstance() { // для исключения возможности создания двух объектов // при многопоточном приложении if (shopUtils == null) { lock (typeof(ShopUtils)) { if (shopUtils == null) shopUtils = new ShopUtils(); } } return shopUtils; } public string CbValue { get { return cbValue; } } public string CbDisplay { get { return cbDisplay; } } public string CbNonSelected { get { return cbNonSelected; } } public string ClassName { get { return className; } set { className = value; } } } }
C++
SHIFT_JIS
2,274
2.734375
3
[]
no_license
#pragma once //gpwb_[ #include"GameL\SceneObjManager.h" #include"math.h" //gpl[Xy[X using namespace GameL; #define HERO_FRONT (0)// #define HERO_BACK (1)//w #define HERO_RIGHT (2)//E #define HERO_LEFT (3)// #define HERO_XSPEED (5)//l̑xX #define HERO_YSPEED (5)//l̑xY //IuWFNg : l class CObjHero : public CObj { public: CObjHero(float x,float y); ~CObjHero() {}; void Init(); //CjVCY void Action(); //ANV void Draw(); //h[ Point pos;//ʒu Vector vec;//ړxNg Vector acc;//x float GetX() { return pos.x; } float GetY() { return pos.y; } float GetVX() { return vec.x; } float GetVY() { return vec.y; } void SetX(float x) { pos.x = x; } void SetY(float y) { pos.y = y; } void SetVX(float vx) { vec.x = vx; } void SetVY(float vy) { vec.y = vy; } void SetUp(bool b) { m_hit_up = b; } void SetDown(bool b) { m_hit_down = b; } void SetLeft(bool b) { m_hit_left = b; } void SetRight(bool b) { m_hit_right = b; } bool GetUp() { return m_hit_up; } bool GetDown() { return m_hit_down; } bool GetLeft() { return m_hit_left; } bool GetRight() { return m_hit_right; } int GetBT() { return m_block_type; } void SetBT(int t) { m_block_type = t; } int GetSwordAngle() { return m_direc; }//̊px private: float m_x; //l@xړpϐ float m_y; //l@yړpϐ float m_vx; //ړxNg float m_vy; //ړxNg int m_direc; //ľ //ʃAj[V int m_ani_time1; //Aj[Vt[Ԋu int m_ani_frame1; //`t[ //wʃAj[V int m_ani_time2; //Aj[Vt[Ԋu int m_ani_frame2; //`t[ //EAj[V int m_ani_time3; //Aj[Vt[Ԋu int m_ani_frame3; //`t[ //Aj[V int m_ani_time4; //Aj[Vt[Ԋu int m_ani_frame4; //`t[ bool m_hit_up; bool m_hit_down; bool m_hit_left; bool m_hit_right; int m_block_type; };
Java
UTF-8
415
3.328125
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package stringrev; class Stringrev{ public static void main(String args[]){ String str[] = "He is the one".split(" "); String finalStr=""; for(int i = str.length-1; i>= 0 ;i--){ finalStr += str[i]+" "; } System.out.println(finalStr); } }
C
UTF-8
528
3.6875
4
[]
no_license
#include <stdio.h> #include <stdlib.h> int buscaBinaria(int a[], int x, int lenght); int main(void){ int x = 31; int a[] = {1,3,4,5,8,9,17,18,31}; printf("%d", buscaBinaria(a, x,9)); return 0; }; int buscaBinaria(int a[], int x,int lenght){ int inicio = 0; int final = lenght; int meio = (inicio+final)/2; while(inicio < final){ if(x == a[meio]) return meio; else{ if(x > a[meio]) inicio = meio; else final = meio; } meio = (inicio+final)/2; } }
Markdown
UTF-8
230
2.765625
3
[]
no_license
# awsstuff A small set of programs to upload a bunch of files on your computer into an s3 bucket. The files are stored in the bucket in the exact same way they are stored in your system (depending on the initial path you give).
JavaScript
UTF-8
2,968
2.515625
3
[]
no_license
$().ready(function() { // 在键盘按下并释放及提交后验证提交表单 $("#signinForm").validate({ rules: { username: { required: true, minlength: 3, maxlength:16, remote:{ type: "get", url: "/checkname", data: { name: function() { return $("#username").val(); } }, dataType: "html", dataFilter: function(data, type) { if (data == "true") return true; else return false; } } }, password1: { required: true, minlength: 6, maxlength: 16 }, password2: { required: true, minlength: 6, maxlength:16, equalTo: "#password1" }, email: { required: true, email: true, remote:{ type: "get", url: "/checkemail", data: { email: function() { return $("#email").val(); } }, dataType: "html", dataFilter: function(data, type) { if (data == "true") return true; else return false; } } }, phone:{ required:true, minlength: 11, maxlength:11 } }, messages: { username: { required: "请输入用户名", minlength: "用户名必需由两个字母组成", remote:"此用户名已存在" }, password1: { required: "请输入密码", minlength: "密码长度不能小于 6 个字母" }, password2: { required: "请输入密码", minlength: "密码长度不能小于 6 个字母", maxlength:"密码长度不能超过16个字符", equalTo: "两次密码输入不一致" }, email: { required:"请输入你的邮箱", email:"请输入一个正确的邮箱", remote:"此邮箱已存在", }, phone:{ required:"请输入你的电话号码", minlength: "电话号码为11位", maxlength:"电话号码为11位", } } }) });
Java
UTF-8
385
1.828125
2
[]
no_license
package mw56_sb55.game.api; import common.message.IChatMessage; import provided.datapacket.ADataPacket; import provided.datapacket.ADataPacketAlgoCmd; public interface IGameOver extends IChatMessage { /** * Show game over. */ public void ShowGameOver(); /** * Get the command * @return The command. */ public ADataPacketAlgoCmd<ADataPacket, ?, Void> getCmd(); }
Python
UTF-8
16,943
2.9375
3
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- import numpy as np import scipy.sparse as sp import random def to_dense(X): '''Convert X to dense matrix if necessary.''' if isinstance(X, sp.csr_matrix): return X.todense() else: return X def project_L1(v, l=1., eps=.01): '''Perfoms eps-accurate projection of v to L1 ball with radius l. Does not preserve the L2 norm. See: D. Sculley: "Web-Scale K-Means Clustering", Proceedings of the 19th international conference on World Wide Web, (2010) ''' L1 = np.linalg.norm(v, ord=1) if L1 <= l * (1. + eps): return v upper = np.linalg.norm(v, ord=np.inf) lower = 0. theta = 0. current = L1 while (current > l * (1. + eps)) or (current < l): theta = .5 * (upper + lower) current = np.maximum( 0., np.add(np.fabs(v), -theta)).sum() if current <= l: upper = theta else: lower = theta return np.multiply(np.sign(v), np.maximum(0., np.add(np.fabs(v), -theta))) def to_sparse(X, project=False, inplace=True, l=1., eps=.01): '''Convert X to sparse matrix if necessary. On request perfoms eps-accurate projection to L1 ball with radius l. If inplace=True, this will overwrite X in-place. ''' if isinstance(X, sp.csr_matrix): if inplace is False: X = X.copy() if project is True: n_rows, _ = X.get_shape() for row_idx in range(n_rows): # project on L1 ball X.data[X.indptr[row_idx]:X.indptr[row_idx + 1]] = project_L1( v=X.data[X.indptr[row_idx]:X.indptr[row_idx + 1]], l=l, eps=eps) # length-normalize X.data[X.indptr[row_idx]:X.indptr[row_idx + 1]] /= np.linalg.norm( X.data[X.indptr[row_idx]:X.indptr[row_idx + 1]]) # make sparse representation more efficient # (inplace operation) X.eliminate_zeros() return X else: if inplace is False: X = np.array(X) if project is True: n_rows, _ = X.shape for row_idx in range(n_rows): # project on L1 ball X[row_idx] = project_L1( v=X[row_idx], l=l, eps=eps) # length-normalize X[row_idx] /= np.linalg.norm( X[row_idx]) return sp.csr_matrix(X) def cosine_distances(X, Y): '''Return a cosine distance matrix. Computes the cosine distance matrix between each pair of vectors in the rows of X and Y. These vectors must have unit length. ''' # compute cosine similarities # (we use *, because np.dot is not aware of sparse) if isinstance(X, sp.csr_matrix) or isinstance(Y, sp.csr_matrix): dist = X * Y.T if isinstance(dist, sp.csr_matrix): dist = to_dense(dist) else: dist = np.dot(X, Y.T) # convert into cosine distances dist *= -1. dist += 1. # make sure that all entries are non-negative np.maximum(dist, 0., out=dist) return dist class SphericalMiniBatchKMeans: def __init__(self, n_clusters=3, n_init=3, max_iter=100, batch_size=100, max_no_improvement=10, reassignment_ratio=.01, project_l=1., project_eps=.01): '''Set instance parameters.''' self.n_clusters = n_clusters self.max_iter = max_iter self.n_init = n_init self.batch_size = batch_size self.max_no_improvement = max_no_improvement self.reassignment_ratio = reassignment_ratio self.project_l = project_l self.project_eps = project_eps self.inertia_ = None self.centers_ = None self.counts_ = None def fit(self, n_samples, get_batch): '''Compute the cluster centers by chunking the data into mini-batches. Adapted from https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/k_means_.py. TODO: figure out if we need to cache any distances or if having a single distances array is beneficial from a performance/memory utilization point of view. ''' n_batches = np.int64( np.ceil(np.float64(n_samples) / self.batch_size)) n_init = self.n_init init_batch_size = min( 3 * self.batch_size, n_samples) # sample validation batch for initial clustering init_validation_batch = get_batch( batch_size=init_batch_size) # look repeatedly for the best possible initial clustering for init_idx in xrange(n_init): # set initial counts to zero init_counts = np.zeros( self.n_clusters, dtype=np.int32) # sample initial batch init_batch = get_batch(batch_size=init_batch_size) # come up with initial centers (CSR format) init_centers = self._init(batch=init_batch) nearest_center, _ = self._labels_inertia( batch=init_validation_batch, centers=init_centers, compute_labels=True) # refine centers and get their counts dense_init_centers = to_dense(init_centers) self._update( batch=init_validation_batch, nearest_center=nearest_center, counts=init_counts, dense_centers=dense_init_centers) init_centers = to_sparse( dense_init_centers, project=True, inplace=True, l=self.project_l, eps=self.project_eps) # get the inertia of the refined centers _, inertia = self._labels_inertia( batch=init_validation_batch, centers=init_centers, compute_labels=False) # identify the best initial guess if (self.inertia_ is None) or (inertia < self.inertia_): self.centers_ = init_centers self.counts_ = init_counts self.inertia_ = inertia # context to be used by the _convergence() routine convergence_context = {} # convert cluster centers to dense format dense_centers = to_dense(self.centers_) # optimize the clustering iteratively until convergence # or maximum number of iterations is reached n_iter = np.int64(self.max_iter * n_batches) for iter_idx in xrange(n_iter): # sample a mini-batch by picking randomly from data set mini_batch = get_batch(self.batch_size) # randomly reassign? if (((iter_idx + 1) % (10 + self.counts_.min()) == 0)) and (self.reassignment_ratio > 0.): self._reassign( batch=mini_batch, counts=self.counts_, dense_centers=dense_centers, reassignment_ratio=self.reassignment_ratio) # convert cluster centers to sparse format # and perfom an eps-accurate projection to an L1 ball # to reduce the number of non-zero components self.centers_ = to_sparse( dense_centers, project=True, inplace=True, l=self.project_l, eps=self.project_eps) # find nearest cluster centers for data in mini-batch, # i.e. find concept vectors closest in cosine similarities nearest_center, self.inertia_ = self._labels_inertia( batch=mini_batch, centers=self.centers_, compute_labels=True) # test convergence if (self._convergence(n_samples, context=convergence_context, batch_inertia=self.inertia_)): break # incremental update of the cluster centers, i.e. the concept # vectors. dense_centers = to_dense(init_centers) self._update(batch=mini_batch, nearest_center=nearest_center, counts=self.counts_, dense_centers=dense_centers) self.n_iter_ = iter_idx + 1 return self def _init(self, batch): '''Selects initial centers in a smart way to speed up convergence. see: Arthur, D. and Vassilvitskii, S., "k-means++: the advantages of careful seeding", ACM-SIAM symposium on Discrete algorithms (2007) Adapted from https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/k_means_.py. ''' n_samples = batch.shape[0] n_centers = self.n_clusters n_features = batch.shape[1] # set the number of local seeding trials n_local_trials = 2 + np.int64(np.log(n_centers)) # pick first center randomly centers = np.empty((n_centers,), dtype=np.int32) centers[0] = random.randint(0, n_samples-1) # initialize the list of closest distances closest_dist = cosine_distances(batch[centers[0]], batch).getA1() # calculate the sum of the distances current_dist_sum = closest_dist.sum() # estimate the remaining n_centers-1 centers for c in xrange(1, n_centers): # sample center candidates with a probability proportional to the # cosine distance to the closest existing center (such that centers # least similar to the existing centers are more likely to be # drawn) candidate_ids = np.searchsorted( closest_dist.cumsum(), [random.random() * current_dist_sum for _ in range(n_local_trials)]) # compute distances to center candidates candidate_dist = cosine_distances(batch[candidate_ids], batch) # decide which candidate is the best best_candidate = None best_dist = None best_dist_sum = None for trial in xrange(n_local_trials): # element-wise comparison new_dist = np.minimum(closest_dist, candidate_dist[trial].getA1()) new_dist_sum = new_dist.sum() # identify the best local trial if (best_candidate is None) or (new_dist_sum < best_dist_sum): best_candidate = candidate_ids[trial] best_dist = new_dist best_dist_sum = new_dist_sum # assign center to best local trial centers[c] = best_candidate # update the list of closest distances closest_dist = best_dist # update the current distance sum current_dist_sum = best_dist_sum return to_sparse(X=batch[centers], project=True, inplace=True, l=self.project_l, eps=self.project_eps) def _reassign(self, batch, counts, dense_centers, reassignment_ratio=None): '''Reassign centers that have very low counts. Adapted from https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/k_means_.py. ''' n_samples, _ = batch.get_shape() if reassignment_ratio is None: reassignment_ratio = self.reassignment_ratio to_reassign = np.float64(counts) < reassignment_ratio * np.float64(counts.max()) n_reassigns = to_reassign.sum() # pick at most 0.5 * n_samples new centers max_reassigns = np.int64(.5 * np.float64(n_samples)) if n_reassigns > max_reassigns: to_reassign[np.argsort(counts)[max_reassigns:]] = False n_reassigns = to_reassign.sum() if n_reassigns: # pick new centers amongst observations with uniform probability new_centers = np.random.choice(n_samples, n_reassigns) dense_centers[to_reassign] = batch[new_centers].todense() # a dirty hack from scikit-learn that resets the counts somewhat counts[to_reassign] = np.min(counts[~to_reassign]) def _update(self, batch, nearest_center, counts, dense_centers): '''Update cluster centers. Adapted from https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/k_means_.py. ''' n_centers = self.n_clusters batch_data = batch.data batch_indices = batch.indices batch_indptr = batch.indptr for center_idx in xrange(n_centers): # find records in mini-batch assigned to this center center_mask = nearest_center == center_idx count = center_mask.sum() if count > 0: # the new center will be a convex sum of # (old count / new count) * center # and (1 - old count / new count) * mean, # where mean is the average of all samples that # are closest to the center # multiply by the old count dense_centers[center_idx] *= counts[center_idx] # add (new count - old count) * mean for sample_idx, nearest in enumerate(center_mask): if nearest: # element-wise addition of the samples for col_idx in xrange(batch_indptr[sample_idx], batch_indptr[sample_idx + 1]): dense_centers[center_idx, batch_indices[col_idx]] += batch_data[col_idx] # update count counts[center_idx] += count # divide by the new count dense_centers[center_idx] /= counts[center_idx] # project center onto the unit sphere such that it mimicks a # concept vector dense_centers[center_idx] /= np.linalg.norm( dense_centers[center_idx], ord=2) def _convergence(self, n_samples, context, batch_inertia=None): '''Early stopping logic. Adapted from https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/k_means_.py. ''' if batch_inertia is None: batch_inertia = self.inertia_ batch_inertia /= self.batch_size # use an exponentially weighted average (ewa) of the inertia to monitor # the convergence ewa_inertia = context.get('ewa_inertia') if ewa_inertia is None: ewa_inertia = batch_inertia else: alpha = np.float64(self.batch_size) * 2. / ( np.float64(n_samples) + 1.) alpha = 1. if alpha > 1. else alpha ewa_inertia = ewa_inertia * (1. - alpha) + batch_inertia * alpha # early stopping heuristic due to lack of improvement on smoothed # inertia ewa_inertia_min = context.get('ewa_inertia_min') no_improvement = context.get('no_improvement', 0) if ewa_inertia_min is None or ewa_inertia < ewa_inertia_min: no_improvement = 0 ewa_inertia_min = ewa_inertia else: no_improvement += 1 if self.max_no_improvement <= no_improvement: return True # update the convergence context to maintain state across successive # calls: context['ewa_inertia'] = ewa_inertia context['ewa_inertia_min'] = ewa_inertia_min context['no_improvement'] = no_improvement return False def _labels_inertia(self, batch, centers=None, compute_labels=False): if centers is None: centers = self.centers_ dist = cosine_distances(centers, batch) if compute_labels is True: labels = dist.argmin(axis=0).getA1() inertia = dist[labels, np.arange(dist.shape[1])].sum() else: labels = None inertia = dist.min(axis=0).sum() return labels, inertia def predict(self, batch): '''Predict labels. TODO: check if model is fitted. ''' batch_labels, batch_inertia = self._labels_inertia( batch=batch, compute_labels=True) return batch_labels, batch_inertia
Java
UTF-8
1,010
2.546875
3
[]
no_license
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import student.TestCase; /** * @author lihui * @version 1.0 */ public class HashTest extends TestCase { /** * set up test cases */ public void setUp() { // Nothing needed } /** * Read contents of a file into a string * * @param path * File name * @return the string * @throws IOException */ static String readFile(String path) throws IOException { byte[] encoded = Files.readAllBytes(Paths.get(path)); return new String(encoded); } /** * @throws Exception */ public void testAdd() throws Exception { String[] args = new String[3]; args[0] = "32"; args[1] = "10"; args[2] = "src/testAdd.txt"; MemMan.main(args); assertFuzzyEquals( readFile("src/addOutput.txt"), systemOut().getHistory()); } }
Java
UTF-8
1,374
2.359375
2
[]
no_license
package softagi.mansour.firebase.models; public class userModel { private String name; private String email; private String mobile; private String address; private String imageUrl; private String Uid; public userModel(String name, String email, String mobile, String address, String imageUrl, String uid) { this.name = name; this.email = email; this.mobile = mobile; this.address = address; this.imageUrl = imageUrl; Uid = uid; } public userModel() { } public String getUid() { return Uid; } public void setUid(String uid) { Uid = uid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } }
C++
UTF-8
470
2.75
3
[]
no_license
#ifndef CPPHAT_MATH_H_ #define CPPHAT_MATH_H_ class Point { public: int X, Y; Point(int _x = 0, int _y = 0); Point operator+(const Point& op); Point& operator+=(const Point& op); Point operator-(const Point& op); Point& operator-=(const Point& op); bool operator<(const Point& op); bool operator<=(const Point& op); bool operator>(const Point& op); bool operator>=(const Point& op); int to1D(int width); static Point from1D(int d, int width); }; #endif
Ruby
UTF-8
1,370
2.90625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
require 'config_volumizer/version' require 'config_volumizer/parser' require 'config_volumizer/generator' module ConfigVolumizer class << self # Parses keys within the {source} hash matching {base_name} # returning a hash with all the matched data under a string key matching the {base_name} # # @see ConfigVolumizer::Parser.parse # # @param [Hash] source # @param [Hash] mapping # @return [Hash] def parse(source, mapping) Parser.parse(source, mapping) end # Fetches the data described by the mapping from the source # works similar to #parse, but has a default value mechanism # and skips the root key # # @param [Hash] source # @param [String] mapping_key # @param [Object] mapping_info # @param [Object] default - default value if key not found # @param [proc] block - default value proc (is passed key as parameter) # @return [Object] def fetch(source, mapping_key, mapping_info, default=nil, &block) value = Parser.parse(source, mapping_key => mapping_info) value.fetch(mapping_key.to_s, *[default].compact, &block) end # Generates a flattened config out of a data hash # # @see ConfigVolumizer::Generator.generate # # @param [Hash] data # @return [Hash] def generate(data) Generator.generate(data) end end end
Python
UTF-8
1,917
2.859375
3
[]
no_license
import string import random as rd import numpy as np import pandas as pd import sys from fastText import train_supervised data = pd.read_csv('spam.csv',encoding='ISO-8859-1'); stopwords = [ x.replace('\n', '') for x in open('stopwords.txt').readlines() ] valdata = data.values n_data = [] for x in valdata: value = x[1] ## Eliminar stopwords #for stop in stopwords: #value = value.replace(' '+stop+' ', ' ') n_data.append([ x[0], value ]) n_data = pd.DataFrame(n_data) count_train=4000 train_data = n_data.iloc[0:count_train,] test_data = n_data.iloc[count_train:len(data),] cot_file = 'data.train' test_file = 'data.test' def add_label(filename, label, text): with open(filename, 'a') as fm: fm.write('__label__'+label + ' ' + text + '\n') fm.flush() fm.close() def apply_filter(td, filename): with open(filename, 'w') as sp: sp.write('') #in content ds = {} for f in td.values: target = f[0] text = f[1] if target not in ds: ds[target] = [] ds[target].append(text) #append spam for value in ds['spam']: add_label(filename ,'spam', value) #append ham for value in ds['ham']: add_label(filename ,'ham', value) apply_filter(train_data, cot_file) apply_filter(test_data, test_file) predict_ok = 0 predict_fail = 0 #Creamos el modelo model = train_supervised(input=cot_file, epoch=50, wordNgrams=5, verbose=2, minCount=1, loss="hs") ##Testear el archivo test sin categoria for d in test_data.values: pred_label, estimation = model.predict(d[1]) predicted = pred_label[0].replace('__label__', '') real = d[0] if str(real) == str(predicted): predict_ok+=1 else: predict_fail+=1 print('\nResults:') ln = len(test_data) print('Predicted True', predict_ok/ln) print('Predicted False',predict_fail/ln) print('\n') nex, precision, recall = model.test(test_file) print('N Examples', nex) print('Precision', precision) print('Recall', recall) print('\n')
Java
UTF-8
576
2.65625
3
[]
no_license
package com.revature.services; import java.util.List; import com.revature.daos.UserDAO; import com.revature.daos.UserDAOImpl; import com.revature.models.User; public class LoginService { UserService userservice = new UserService(); UserDAO userDAO = new UserDAOImpl(); public User login(String eMail, String password) { List<User> users = userDAO.getAll(); for (int i = 0; i < users.size();i++) { if (users.get(i).getEMail().equals(eMail)) { if( users.get(i).getPass().equals(password)) { return users.get(i); } } } return null; } }
Shell
UTF-8
1,313
3.953125
4
[]
no_license
#!/bin/bash # Renames the bundled 'app' to whatever you want. if [ -z $1 ]; then echo 'Need to specify new app name!' exit fi #Note that $0 contains the full path of the script being executed. script_path=`dirname $0` cd ${script_path} #Now go through each of the spots where we had to hardcode app and replace it with #our new name. We rename the directories last. #-i means inplace editing. Need to specify an extension that it is saved in. So ''. #settings.py. NOTE: We hardcode lines here. This is bad, but oh well. sed -i '' -e '107s|app|'$1'|' settings.py sed -i '' -e 's|app.backends|'$1'.backends|' settings.py sed -i '' -e 's|app.helpers|'$1'.helpers|' settings.py sed -i '' -e 's|# app|# '$1'|' settings.py #urls.py sed -i '' -e 's|app.urls|'$1'.urls|g' urls.py sed -i '' -e 's|app.views|'$1'.views|g' urls.py #app/urls.py sed -i '' -e 's|app.views|'$1'.views|g' app/urls.py #app/views.py sed -i '' -e 's|app/home|'$1'/home|g' app/views.py #app/templates/app/home.html. Replace only first line. sed -i '' -e '1s|app|'$1'|' app/templates/app/home.html #Now for the app/templates/django_rpx_plus/*.html files sed -i '' -e '1s|app|'$1'|' app/templates/app/*.html #Now rename our directories #app/templates/app/ mv app/templates/app app/templates/$1 #app/ mv app $1 echo 'All done!'
Python
UTF-8
4,349
2.609375
3
[]
no_license
import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets from torchvision.transforms import transforms from tensorboardX import SummaryWriter from torchvision.utils import save_image from tqdm import tqdm from model import VAE writer = SummaryWriter() def loss_function(recon_x, x, mu, logvar): BCE = F.binary_cross_entropy(recon_x.view(-1, 96*96), x.view(-1, 96*96), reduction='sum') KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp()) return BCE + KLD def train(epoch_num, model, train_loader, optimizer, args): model.train() losses = [] for batch_idx, (images, _) in tqdm(enumerate(train_loader), total=len(train_loader)): images = images.to(args.device) optimizer.zero_grad() recon_batch, mu, logvar = model(images) loss = loss_function(recon_batch, images, mu, logvar) loss.backward() optimizer.step() losses.append(loss.item()) if batch_idx % args.log_interval == 0: print('Train Epoch: {} [{}/{}]\tLoss: {:.6f}'.format( epoch_num, batch_idx, len(train_loader), loss.item())) writer.add_scalar('Avg Loss', sum(losses) / float(len(losses))) def test(epoch, model, loader, args): model.eval() test_loss = 0 with torch.no_grad(): for i, (data, _) in enumerate(loader): data = data.to(args.device) recon_batch, mu, logvar = model(data) test_loss += loss_function(recon_batch, data, mu, logvar).item() if i == 0: n = min(data.size(0), 8) comparison = torch.cat([data[:n], recon_batch.view(args.batch_size, 3, 96, 96)[:n]]) save_image(comparison.cpu(), 'results/reconstruction_' + str(epoch) + '.png', nrow=n) break test_loss /= len(loader.dataset) print('====> Test set loss: {:.4f}'.format(test_loss)) def run(args): train_loader = torch.utils.data.DataLoader( datasets.ImageFolder(args.data, transform=transforms.ToTensor()), batch_size=args.batch_size, shuffle=True, num_workers=8) test_loader = torch.utils.data.DataLoader( datasets.ImageFolder(args.data_val, transform=transforms.ToTensor()), batch_size=args.batch_size, shuffle=False, num_workers=8) model = nn.DataParallel(VAE()) model = model.to(args.device) if args.checkpoint is not None: model.load_state_dict(torch.load(args.checkpoint)) optimizer = optim.Adam(model.parameters(), lr=args.lr) for epoch in range(1, args.epochs + 1): train(epoch, model, train_loader, optimizer, args) model_file = 'models/model_' + str(epoch) + '.pth' torch.save(model.state_dict(), model_file) print('Saved model to ' + model_file) test(epoch, model, test_loader, args) writer.close() if __name__ == "__main__": parser = argparse.ArgumentParser(description="Variational Autoencoder") parser.add_argument('--data', type=str, required=True, help="folder where data is located") parser.add_argument('--data-val', type=str, required=True, help='folder where validation data is located') parser.add_argument('--checkpoint', type=str, default=None, help='path to model checkpoint') parser.add_argument('--batch-size', type=int, default=64, metavar='N', help='input batch size for training (default: 64)') parser.add_argument('--epochs', type=int, default=10, metavar='N', help='number of epochs to train (default: 10)') parser.add_argument('--lr', type=float, default=1e-3, metavar='LR', help='learning rate (default: 1e-3)') parser.add_argument('--log-interval', type=int, default=10, metavar='N', help='how many batches to wait before logging training status') parser.add_argument('--no-cuda', action="store_true", help='run on cpu') args = parser.parse_args() args.device = torch.device('cuda' if torch.cuda.is_available() and not args.no_cuda else 'cpu') print('Running with these options:', args) run(args)