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
JavaScript
UTF-8
1,987
2.921875
3
[]
no_license
import { useState } from "react"; import FormInput from "./formInput.js" const ExpenseForm = (props) => { const [formValue, setFormValue] = useState({ description: "", price: 0, date: null, }) const [description, setDescription] = useState(""); //description là 1 biến còn setDescription là 1 function làm thay đổi giá trị biến kia const [price, setPrice] = useState(""); //useState ở trên là tương ứng biến kia là 1 string, còn ở đây là 1 number const [date, setDate] = useState(""); const [formVisible, setFormVisible] = useState(false); const toggleFormVisible = () => { setFormVisible(prev => !prev) } const handleSubmit = (event) => { event.preventDefault(); props.onSubmit({ description: description, price: price, date: new Date(date), }); }; const handleDescriptionChange = (event) => { setDescription(event.target.value); }; const handlePriceChange = (event) => { setPrice(event.target.value); } const handleDateChange = (event) => { setDate(event.target.value); } const handleCancel = () => { setPrice(""); setDate(""); setDescription(""); toggleFormVisible(); } return ( <div> {formVisible ? (<form onSubmit={handleSubmit}> <FormInput label="Description" type="text" placeholder="Enter description ..." onChange={handleDescriptionChange}/> <FormInput label="Price" type="number" placeholder="Enter price ..." value={price} onChange={handlePriceChange}/> <FormInput label="Date" type="date" placeholder="Enter date ..." value={date} onChange={handleDateChange}/> <div> <button type="submit" onSubmit={handleSubmit}>Add</button> <button type="button" onClick={handleCancel}>Cancel</button> </div> </form> ) : ( <button type="button" onClick={toggleFormVisible}>Add Expense</button> )} </div> ); }; export default ExpenseForm;
PHP
UTF-8
1,077
2.921875
3
[ "MIT" ]
permissive
<?php namespace App\Api\Controller; use App\Api\Formatter\UnitFormatter; use App\Game\ManagerInterface; use Symfony\Component\HttpFoundation\Response; class GameController { /** * @var ManagerInterface */ private $manager; /** * GameController constructor. * @param ManagerInterface $manager */ public function __construct(ManagerInterface $manager) { $this->manager = $manager; } public function getUnits($gameId, UnitFormatter $unitFormatter): Response { $game = $this->manager->getGame($gameId); if(!$game) { return new Response("Game not found", 404); } $units = $this->manager->getUnits($game); return new Response($unitFormatter->format($units)); } public function getUnit($unitId, UnitFormatter $unitFormatter): Response { $unit = $this->manager->getUnit($unitId); if(!$unit) { return new Response("Unit not found", 404); } return new Response($unitFormatter->formatOne($unit)); } }
Python
UTF-8
243
3.640625
4
[]
no_license
def busca(sequencia, item_procurado): for i in range(len(sequencia)): if sequencia[i] == item_procurado: return True sequencia = ['leo','joao','geracy'] if busca(sequencia,'leo') == True: print("Encontrado")
Python
UTF-8
158
2.78125
3
[]
no_license
"""Draw square""" from turtle import * def task_2(): for _ in range(4): forward(90) left(90) if __name__ == '__main__': task_2()
Python
UTF-8
788
2.71875
3
[]
no_license
import json from soup_helpers import get_soup_for_url def fetch_name_for_id(id): url = 'https://www.elitegsp.com/posts/?id={}'.format(id) soup = get_soup_for_url(url) title = soup.find(id='posts_title') if title: character_name = title.text.split("'")[0] return character_name name_to_id = {} id_to_name = {} main_soup = get_soup_for_url('https://www.elitegsp.com/posts/') for option in main_soup.find(id='posts_dropbox').find_all('option'): if option.text == 'All Posts': continue id = option['value'].split('=')[1] name = fetch_name_for_id(id) name_to_id[name] = id id_to_name[id] = name with open('mappings/name_to_id.json', 'w') as f: f.write(json.dumps(name_to_id)) with open('mappings/id_to_name.json', 'w') as f: f.write(json.dumps(id_to_name))
Java
UTF-8
822
2.46875
2
[]
no_license
package edu.uga.cs.evote.logic.impl; import java.util.List; import edu.uga.cs.evote.EVException; import edu.uga.cs.evote.entity.Voter; import edu.uga.cs.evote.object.ObjectLayer; public class DeleteVoterAccountCtrl{ private ObjectLayer objectLayer = null; private String userName = null; public DeleteVoterAccountCtrl(ObjectLayer objectLayer){ this.objectLayer = objectLayer; } public void delete(String userName) throws EVException{ Voter voterModel = objectLayer.createVoter(); voterModel.setUserName(userName); List <Voter> voters = objectLayer.findVoter(voterModel); if(!voters.isEmpty()){ Voter vote = voters.get(0); objectLayer.deleteVoter(vote); } else{ throw new EVException("Could not delete User"); } } }
Markdown
UTF-8
89
2.671875
3
[]
no_license
# Basic-Portfolio Week 1 Homework Assignment whereupon I create my own portfolio website
Markdown
UTF-8
922
3.203125
3
[]
no_license
# Navigation - [Navigation](#navigation) - [Links](#links) - [Solution 1 贪心,模拟入栈和出栈操作](#solution-1-%e8%b4%aa%e5%bf%83%e6%a8%a1%e6%8b%9f%e5%85%a5%e6%a0%88%e5%92%8c%e5%87%ba%e6%a0%88%e6%93%8d%e4%bd%9c) # Links 1. https://leetcode-cn.com/problems/zhan-de-ya-ru-dan-chu-xu-lie-lcof/ # Solution 1 贪心,模拟入栈和出栈操作 1. 设置一个辅助栈stack,然后不断从pushed中push元素进去。 2. 假如stack的栈顶元素等于popped序列中下一个要pop的值,则立刻将该值pop出来。 ``` 时间复杂度:O(N) 空间复杂度:O(N) ``` ```python class Solution: def validateStackSequences(self, pushed, popped): stack = [] count = 0 for x in pushed: stack.append(x) while stack and stack[-1] == popped[count]: stack.pop() count += 1 return not stack ```
C#
UTF-8
4,464
3
3
[]
no_license
using System; using System.Globalization; namespace HSMSDriver { internal class Str2SecsItem { internal static byte[] GetBinary(string data) { string[] strArray = data.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); byte[] buffer = new byte[strArray.Length]; for (int i = 0; i < strArray.Length; i++) { buffer[i] = byte.Parse(strArray[i], NumberStyles.HexNumber); } return buffer; } internal static bool[] GetBoolean(string data) { string[] strArray = data.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); bool[] flagArray = new bool[strArray.Length]; for (int i = 0; i < strArray.Length; i++) { if (strArray[i] == "T" || strArray[i] == "True") { flagArray[i] = true; } else { if (strArray[i] != "F" && strArray[i] != "False") { throw new Exception("Not Support translate " + strArray[i] + " to boolean"); } flagArray[i] = false; } } return flagArray; } internal static float[] GetF4(string data) { string[] strArray = data.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); float[] numArray = new float[strArray.Length]; for (int i = 0; i < strArray.Length; i++) { numArray[i] = float.Parse(strArray[i]); } return numArray; } internal static double[] GetF8(string data) { string[] strArray = data.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); double[] numArray = new double[strArray.Length]; for (int i = 0; i < strArray.Length; i++) { numArray[i] = double.Parse(strArray[i]); } return numArray; } internal static sbyte[] GetI1(string data) { string[] strArray = data.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); sbyte[] numArray = new sbyte[strArray.Length]; for (int i = 0; i < strArray.Length; i++) { numArray[i] = sbyte.Parse(strArray[i]); } return numArray; } internal static short[] GetI2(string data) { string[] strArray = data.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); short[] numArray = new short[strArray.Length]; for (int i = 0; i < strArray.Length; i++) { numArray[i] = short.Parse(strArray[i]); } return numArray; } internal static int[] GetI4(string data) { string[] strArray = data.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); int[] numArray = new int[strArray.Length]; for (int i = 0; i < strArray.Length; i++) { numArray[i] = int.Parse(strArray[i]); } return numArray; } internal static long[] GetI8(string data) { string[] strArray = data.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); long[] numArray = new long[strArray.Length]; for (int i = 0; i < strArray.Length; i++) { numArray[i] = long.Parse(strArray[i]); } return numArray; } internal static byte[] GetU1(string data) { string[] strArray = data.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); byte[] buffer = new byte[strArray.Length]; for (int i = 0; i < strArray.Length; i++) { buffer[i] = byte.Parse(strArray[i]); } return buffer; } internal static ushort[] GetU2(string data) { string[] strArray = data.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); ushort[] numArray = new ushort[strArray.Length]; for (int i = 0; i < strArray.Length; i++) { numArray[i] = ushort.Parse(strArray[i]); } return numArray; } internal static uint[] GetU4(string data) { string[] strArray = data.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); uint[] numArray = new uint[strArray.Length]; for (int i = 0; i < strArray.Length; i++) { numArray[i] = uint.Parse(strArray[i]); } return numArray; } internal static ulong[] GetU8(string data) { string[] strArray = data.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); ulong[] numArray = new ulong[strArray.Length]; for (int i = 0; i < strArray.Length; i++) { numArray[i] = ulong.Parse(strArray[i]); } return numArray; } } }
Java
UTF-8
118
1.882813
2
[]
no_license
package uni.dao; import uni.model.Payment; public interface PaymentDAO { void addPayment(Payment p); }
Java
UTF-8
209
1.804688
2
[]
no_license
package Entities; import java.util.ArrayList; import java.util.List; public class SupProcessActivity { public int SupProcessID; public List<Activity> ActivitiesDBList = new ArrayList<Activity>(); }
Markdown
UTF-8
2,702
3.3125
3
[]
no_license
# 06.橋接模式 Bridge ## 講解 ### 橋接模式 橋接模式,是讓兩個"介面"接再一起,實現已組合代替繼承的作法 例子:手機品牌與手機軟體 這兩個是分開的項目,若是用繼承方式,會變成過多的類別,所以用組合方式實現 ```puml @startuml scale 1.5 skinparam classAttributeIconSize 0 abstract class 手機軟體{ } abstract class 通訊錄{ } abstract class 遊戲{ } 手機軟體 <|-- 通訊錄 手機軟體 <|-- 遊戲 遊戲 <|-- A品牌遊戲 遊戲 <|-- B品牌遊戲 遊戲 <|-- C品牌遊戲 通訊錄 <|-- A品牌通訊錄 通訊錄 <|-- B品牌通訊錄 通訊錄 <|-- C品牌通訊錄 note as N1 若是以繼承實現功能,一旦多個角色(這邊以多品牌舉例) 就會變成每個功能都要多寫很多Class end note @enduml ``` ```puml @startuml skinparam classAttributeIconSize 0 scale 1.5 abstract class 手機軟體{ public abstract void Run()==>軟體運行; } abstract class 手機品牌{ protected HandsetSoft soft; public void SetHandsetSoft(HandsetSoft soft)==>設定軟體 public abstract void Run()==>品牌運行; } 手機品牌 *-right- 手機軟體 手機軟體 <|-- 通訊錄 手機軟體 <|-- 遊戲 手機軟體 <|-- MP3 手機品牌 <|-- A品牌 手機品牌 <|-- B品牌 手機品牌 <|-- C品牌 note as N1 利用組合代替繼承 這樣品牌與軟件分成兩個類別分別開發 並且即使新增也只需要新增對應的類別 但有個問題 如果放在一般軟體沒問題,但在遊戲中 時常會突然改遊戲機制,這時就出現麻煩 因為就必須更動"手機品牌(角色)"或是"手機軟件(武器系統)"這些父類 那旗下所有子類就必須更動到,所以必須注意 同時因為兩類解耦,所以必須注意,"手機品牌(角色)"跟"手機軟件(武器系統)"之間無法溝通 例: "手機軟件(武器系統)"無法拿到"手機品牌(角色)"上的狀態,反之亦然 end note @enduml ``` ### 書中案例 在書中橋接模式是用在角色跟武器系統上,將兩個系統分開來 創建角色時就能為角色換上不同武器 ```puml @startuml scale 1.5 skinparam classAttributeIconSize 0 abstract class ICharacter{ protector IWeapon void Attack() } abstract class IWeapon{ Fire() } ICharacter *-right- IWeapon ICharacter <|-- ISoldier ICharacter <|-- IEnemy IWeapon <|-- WeaponGun IWeapon <|-- WeaponRifile IWeapon <|-- WeaponRocket @enduml ``` ### 總結下 透過橋接模式,能將角色和武器數據分割 武器所要執行的"粒子","判定","模型" 都可以和角色數據分開,不用為了新增角色,而增加許多繼承類 這樣透過**組合**方式代替**繼承**
Java
UTF-8
1,658
2.9375
3
[]
no_license
package advanced; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.Properties; import java.util.Scanner; public class Demo2 { public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException, SQLException { Properties properties=new Properties(); properties.load(new FileInputStream("D:/swetha/advancedjava/Db.properties")); Class.forName(properties.getProperty("driver")); Connection con=DriverManager.getConnection(properties.getProperty("url"),properties); System.out.println(con); System.out.println(properties.getProperty("driver")); System.out.println(properties.getProperty("url")+properties); PreparedStatement pst=con.prepareStatement("select * from student where id=?"); Scanner s=new Scanner(System.in); while(true) { System.out.println("enter id index"); int id=s.nextInt(); pst.setInt(1, id); ResultSet rs=pst.executeQuery(); while(rs.next()) { System.out.println(rs.getString(2)); System.out.println(rs.getInt(3)); System.out.println(rs.getInt(4)); System.out.println(rs.getInt(5)); System.out.println(rs.getInt(6)); } System.out.println("enetr 1 to cnt"); int i=s.nextInt(); if(i==1){ } else{ break; } } } }
TypeScript
UTF-8
1,844
2.734375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
import Matter from './matter'; import {PhysicsType} from './Physics'; import {GameObject} from '@eva/eva.js'; declare interface BodyOptions { chamfer?: number; // 斜切角 angle?: number; // 旋转角 isStatic?: boolean; density?: number; // 密度; restitution?: number; // 回弹系数 velocity?: number; // 速率 speed?: number; // 速度 motion?: number; // 势能 mass?: number; } export interface RectangleParams { x: number; y: number; width: number; height: number; options: BodyOptions; } export interface Verctor { x: number; y: number; } export default class BodiesFactory { private Bodies: any; constructor() { this.Bodies = Matter.Bodies; } public create(component) { let body = null; const {gameObject, bodyParams} = component; const coordinate = this.getCoordinate(gameObject); const x = bodyParams.position ? bodyParams.position.x : coordinate.x; const y = bodyParams.position ? bodyParams.position.y : coordinate.y; switch (bodyParams.type) { case PhysicsType.RECTANGLE: { const width = gameObject.transform.size.width * gameObject.transform.scale.x; const height = gameObject.transform.size.height * gameObject.transform.scale.y; body = this.Bodies.rectangle(x, y, width, height,bodyParams.bodyOptions); break; } case PhysicsType.CIRCLE: { body = this.Bodies.circle(x, y, bodyParams.radius, bodyParams.bodyOptions); } } return body; } private getCoordinate(gameObject: GameObject): Verctor { const x = gameObject.transform.position.x + gameObject.transform.anchor.x * gameObject.parent.transform.size.width; const y = gameObject.transform.position.y + gameObject.transform.anchor.y * gameObject.parent.transform.size.height; return { x, y, }; } }
Java
UTF-8
2,994
2.03125
2
[]
no_license
package com.yaytech.MesProject.config; import com.zaxxer.hikari.HikariDataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; import java.util.HashMap; @Configuration @PropertySource({"classpath:db.properties"}) @EnableJpaRepositories( basePackages = "com.yaytech.MesProject.repo.mssql", entityManagerFactoryRef = "mssqlEntityManager", transactionManagerRef = "mssqlTransactionManager") public class MsSqlConfig { @Autowired Environment env; @Bean @Primary @ConfigurationProperties(prefix="spring.datasource-mssql") public DataSourceProperties mssqlDataSourceProperties(){ return new DataSourceProperties(); } @Bean(name = "mssqlDataSource") @Primary public DataSource mssqlDataSource(@Qualifier("mssqlDataSourceProperties") DataSourceProperties mssqlDataSourceProperties) { return mssqlDataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build(); } // productEntityManager bean @Bean(name = "mssqlEntityManager") @Primary public LocalContainerEntityManagerFactoryBean mssqlEntityManager(EntityManagerFactoryBuilder postgresEntityManagerFactoryBuilder, @Qualifier("mssqlDataSource") DataSource mssqlDataSource) { HashMap<String, Object> hibernateProperties = new HashMap<>(); hibernateProperties.put("hibernate.hbm2ddl.auto", "none"); return postgresEntityManagerFactoryBuilder .dataSource(mssqlDataSource) .packages("com.yaytech.MesProject.model.mssql") .persistenceUnit("mssqlDataSource") .properties(hibernateProperties) .build(); } // productTransactionManager bean @Bean @Primary public PlatformTransactionManager mssqlTransactionManager(@Qualifier("mssqlEntityManager") EntityManagerFactory mssqlEntityManager) { return new JpaTransactionManager(mssqlEntityManager); } }
Markdown
UTF-8
1,133
2.796875
3
[]
no_license
--- title: "Paper notes: Type-based memory allocator hardening notes" layout: post tags: - paper notes - isolated heap - memory allocator hardening - type-safety --- Internet Explorer's new `g_hIsolatedHeap` mitigation is like a poor man's type-safe memory reuse implementation. "Poor man's" since instead of real type-safety, it specifies categories of "dangerous" objects that are placed on the isolated heap. An example full implementation of type-safe memory reuse is <a href="/public/3f7f268d4896869a6634f76403e5954b.pdf">Cling</a>, a heap manager that restricts memory reuse to same-type objects. Of course <a href="http://robert.ocallahan.org/2010/10/mitigating-dangling-pointer-bugs-using_15.html">Firefox's frame poisoning</a> (since 2010) also implements some type-safe memory reuse ideas. Btw, the above frame poisoning blog post does not refer to Cling, but a <a href="/public/a8f45baeab77e1bf41d30dce444523b3.pdf">much earlier paper</a> on type-safe memory reuse. Relevant Twitter link: <a href="https://twitter.com/_argp/statuses/498798680863145984">https://twitter.com/_argp/statuses/498798680863145984</a>
C++
GB18030
369
3.296875
3
[]
no_license
#include <iostream> #include<string.h> #pragma warning(disable:4996) using namespace std; class student { private: char name[20]; int age; public: student(const char n[], int a) { strcpy(name, n); age = a; } void show() { cout << "ѧΪ" << name << "ǣ" << age << endl; } }; int main() { student AA("", 20); AA.show(); }
Ruby
UTF-8
1,793
3.390625
3
[]
no_license
require_relative 'deck' require_relative 'player' require_relative 'dealer' require_relative 'interface' class Game include Interface INITIAL_BALANCE = 100 RATE = 10 attr_accessor :bets attr_reader :deck, :player, :dealer def initialize @deck = Deck.new @player = Player.new(ask_the_name) @dealer = Dealer.new @bets = 0 set_initial_balance end def set_initial_balance player.bank = INITIAL_BALANCE dealer.bank = INITIAL_BALANCE end def place_the_bet self.bets += RATE * 2 player.bank -= RATE dealer.bank -= RATE end def over? (player.cards_values.size == 3) || (dealer.cards_values.size == 3) end def draw? (player.points == dealer.points) || (player.points > 21 && dealer.points > 21) end def winner return dealer if player.points > 21 return player if dealer.points > 21 player.points > dealer.points ? player : dealer end def share_money if draw? dealer.bank += 10 player.bank += 10 else winner.bank += 20 end end def deal_2_cards 2.times do player.deal(deck.card) dealer.deal(deck.card) end display(:cards) puts_player_points end def play_to_end dealer.hidden_cards = dealer.true_cards until over? case step when 'Hit' then player.deal(deck.card) when "Show cards" then break end dealer.points < 17 ? dealer.deal(deck.card) : next end puts_result_tables end def start deal_2_cards place_the_bet play_to_end puts_winner share_money puts_banks end def reset @deck = Deck.new @bets = 0 player.cards = '' player.cards_values = [] dealer.cards = '' dealer.cards_values = [] dealer.hidden_cards = 'X X' end end
C
UTF-8
10,205
2.796875
3
[ "MIT" ]
permissive
#include "pass.h" int _pass_log_dom = -1; Clipboard_Set_Func clipboard_set = NULL; Output_Func output = NULL; /*============================================================================* * Logging Callbacks * *============================================================================*/ static void _stdout(const char *format, ...) { va_list args; va_start(args, format); vfprintf(stdout, format, args); va_end(args); fflush(stdout); } /*============================================================================* * Init/Shutdown * *============================================================================*/ static Eina_Bool _init(const char *file) { int chk; /* Set logger */ output = _stdout; chk = eina_init(); EINA_SAFETY_ON_TRUE_GOTO(chk <= 0, eina_err); chk = eet_init(); EINA_SAFETY_ON_TRUE_GOTO(chk <= 0, eet_err); _pass_log_dom = eina_log_domain_register("pass", EINA_COLOR_RED); EINA_SAFETY_ON_TRUE_GOTO(_pass_log_dom < 0, log_err); chk = clipboard_init(); EINA_SAFETY_ON_FALSE_GOTO(chk, clipboard_err); chk = file_init(file); EINA_SAFETY_ON_FALSE_GOTO(chk, file_err); chk = tty_init(); EINA_SAFETY_ON_FALSE_GOTO(chk, tty_err); return EINA_TRUE; tty_err: file_shutdown(); file_err: clipboard_shutdown(); clipboard_err: eina_log_domain_unregister(_pass_log_dom); log_err: eet_shutdown(); eet_err: eina_shutdown(); eina_err: return EINA_FALSE; } static void _shutdown(void) { tty_shutdown(); file_shutdown(); clipboard_shutdown(); eina_log_domain_unregister(_pass_log_dom); _pass_log_dom = -1; eet_shutdown(); eina_shutdown(); output = NULL; } /*============================================================================* * Password Generation * *============================================================================*/ static int _password_gen(unsigned char len) { /* Ascii characters to use */ const int start = 32, stop = 125; const int nope[] = { 96, // ` (grave accent) 0 // SENTINEL }; char *buf; int i; int *ptr; Eina_Bool chk; buf = alloca(len + 1); for (i = 0; i < len; i++) { again: /* Char in the allowed range */ buf[i] = rand() % (stop - start) + start; /* Reject nope characters */ ptr = (int *)nope; while (*ptr != 0) { if (buf[i] == *ptr) goto again; ptr++; } } buf[len] = 0; chk = clipboard_set(buf, len); memset(buf, 0, len); return (!chk); // 0 is chk was true } /*============================================================================* * Getopt * *============================================================================*/ static const Ecore_Getopt _options = { "pass", "%prog [options] (at least one)", "1.2", "2013-2016 © Jean Guyomarc'h", "MIT", "A command-line password manager", EINA_TRUE, { ECORE_GETOPT_STORE_STR('f', "file", "Provide the path of the file to be used"), ECORE_GETOPT_STORE_TRUE('l', "list", "Display the list of stored data"), ECORE_GETOPT_STORE_STR('a', "add", "Add a new string to the encrypted database"), ECORE_GETOPT_STORE_STR('d', "delete", "Deletes the entry for the given key"), ECORE_GETOPT_STORE_STR('x', "extract", "Extracts the entry for the given key"), ECORE_GETOPT_STORE_DEF_SHORT('g', "generate", "Generates a random password in your clipboard", 32), ECORE_GETOPT_STORE_STR('r', "replace", "Replace by the provided key"), // FIXME ECORE_GETOPT_STORE_STR('R', "rename", "Rename the provided key"), ECORE_GETOPT_HELP ('h', "help"), ECORE_GETOPT_VERSION('V', "version"), ECORE_GETOPT_SENTINEL } }; static inline void _help_show(void) { ecore_getopt_help(stderr, &_options); } /*============================================================================* * Helpers * *============================================================================*/ static int _pass_add(const char *key, Eina_Bool strict) { EINA_SAFETY_ON_NULL_RETURN_VAL(key, 2); char *password = NULL, *cipher = NULL; int status, password_len, cipher_len; if (strict && file_entry_exists(key)) { ERR("Entry \"%s\" already exists", key); return 2; } output("Write the data you want to store: "); password = tty_string_silent_get(&password_len); output("Write a cipher key to encrypt the data: "); cipher = tty_string_silent_get(&cipher_len); if (EINA_UNLIKELY(!password) || EINA_UNLIKELY(!cipher)) { status = 2; goto end; } status = file_add(key, password, cipher); end: if (password) { memset(password, 0, password_len); munlock(password, password_len + 1); password_len = 0; free(password); } if (cipher) { memset(cipher, 0, cipher_len); munlock(cipher, cipher_len + 1); cipher_len = 0; free(cipher); } return status; } static int _pass_del(const char *key) { EINA_SAFETY_ON_NULL_RETURN_VAL(key, 2); char *str; int status; if (!file_entry_exists(key)) { ERR("Entry \"%s\" does not exist", key); return 1; } again: output("Are you sure to delete \"%s\". It cannot be recovered! [y/N] ", key); str = tty_string_get(NULL, EINA_FALSE); if (str == NULL) status = 1; else { if ((!strncasecmp(str, "y", 1)) || (!strncasecmp(str, "yes", 3))) status = file_del(key); else if ((str[0] == 0) || /* User pressed [ENTER] */ (!strncasecmp(str, "n", 1)) || (!strncasecmp(str, "no", 2))) status = 0; else { ERR("Please answer yes/y or no/n."); goto again; } } free(str); return status; } static int _pass_extract(const char *key) { EINA_SAFETY_ON_NULL_RETURN_VAL(key, 2); char *data, *cipher; int cipher_len, data_len; Eina_Bool chk; if (!file_entry_exists(key)) { ERR("Entry \"%s\" does not exist", key); return 1; } output("Write your decipher key: "); cipher = tty_string_silent_get(&cipher_len); EINA_SAFETY_ON_NULL_RETURN_VAL(cipher, 2); data = file_get(key, cipher, &data_len); if (data == NULL) { ZERO_MUNLOCK(cipher, cipher_len); FREE(cipher); cipher_len = 0; return 2; } chk = clipboard_set(data, data_len); memset(data, 0, data_len); if (!chk) CRI("Failed to set data to clipboard"); ZERO_MUNLOCK(cipher, cipher_len); ZERO_MUNLOCK(data, data_len); FREE(cipher); FREE(data); cipher_len = 0; return chk ? 0 : -1; } static EINA_UNUSED int // FIXME << Remove EINA_UNUSED _pass_rename(const char *old_key, const char *new_key) { EINA_SAFETY_ON_NULL_RETURN_VAL(new_key, 2); EINA_SAFETY_ON_NULL_RETURN_VAL(old_key, 2); if (!file_entry_exists(old_key)) { ERR("Entry \"%s\" does not exist", old_key); return 1; } if (file_entry_exists(new_key)) { ERR("Entry \"%s\" already exists", new_key); return 1; } return file_replace(old_key, new_key); } /*============================================================================* * Main * *============================================================================*/ int main(int argc, char **argv) { Eina_Bool quit_opt = EINA_FALSE; Eina_Bool list_opt = EINA_FALSE; short gen_opt = 0; char *add_opt = NULL; char *del_opt = NULL; char *get_opt = NULL; char *file_name = NULL; char *replace_opt = NULL; // FIXME char *rename_opt = NULL; int args; int status = EXIT_FAILURE; Ecore_Getopt_Value values[] = { ECORE_GETOPT_VALUE_STR(file_name), ECORE_GETOPT_VALUE_BOOL(list_opt), ECORE_GETOPT_VALUE_STR(add_opt), ECORE_GETOPT_VALUE_STR(del_opt), ECORE_GETOPT_VALUE_STR(get_opt), ECORE_GETOPT_VALUE_SHORT(gen_opt), ECORE_GETOPT_VALUE_STR(replace_opt), //FIXME ECORE_GETOPT_VALUE_STR(rename_opt), ECORE_GETOPT_VALUE_BOOL(quit_opt), ECORE_GETOPT_VALUE_BOOL(quit_opt), ECORE_GETOPT_VALUE_NONE }; args = ecore_getopt_parse(&_options, values, argc, argv); if (args != argc) { _help_show(); return EXIT_FAILURE; } else if (args < 0) return EXIT_FAILURE; if (quit_opt) return EXIT_SUCCESS; if (EINA_UNLIKELY(!_init(file_name))) return EXIT_FAILURE; /* List all entries */ if (list_opt) { status = file_list(); goto end; } /* Add an entry */ if (add_opt) { status = _pass_add(add_opt, EINA_TRUE); goto end; } /* Delete an entry */ if (del_opt) { status = _pass_del(del_opt); goto end; } /* Get the content of an entry */ if (get_opt) { status = _pass_extract(get_opt); goto end; } // FIXME /* Rename an entry */ // FIXME if (rename_opt) // FIXME { // FIXME if (!replace_opt) // FIXME { // FIXME ERR("This options must be used in pair with --replace"); // FIXME goto end; // FIXME } // FIXME status = _pass_rename(rename_opt, replace_opt); // FIXME goto end; // FIXME } /* Replace the content of an entry */ if (replace_opt) { status = _pass_add(replace_opt, EINA_FALSE); goto end; } /* Generate the password */ if (gen_opt > 0) { if (gen_opt > 64) gen_opt = 64; status = _password_gen(gen_opt); goto end; } end: _shutdown(); return status; }
TypeScript
UTF-8
824
2.859375
3
[]
no_license
import moment = require("moment-timezone") import { IBusinessDayConstraint } from "." import { RangeConstraint } from "./RangeConstraint" export class BetweenDates extends RangeConstraint implements IBusinessDayConstraint { static readonly FORMAT = "YYYY-MM-DD" constructor(minDate: string, maxDate: string) { const minMoment = moment.utc(minDate, BetweenDates.FORMAT) const maxMoment = moment.utc(maxDate, BetweenDates.FORMAT) super(minMoment.startOf("day").unix(), maxMoment.endOf("day").unix()) } isBusinessDay(): boolean { return true } maxMax(): number { return Number.MAX_SAFE_INTEGER } minMin(): number { return Number.MIN_SAFE_INTEGER } relevantValueOf(time: moment.Moment): number { return time.unix() } }
Go
UTF-8
18,995
2.6875
3
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
package lr import ( "bytes" "fmt" "io" "os" "sort" "text/scanner" "github.com/emirpasic/gods/lists/arraylist" "github.com/emirpasic/gods/sets/treeset" "github.com/emirpasic/gods/utils" "github.com/npillmayer/gotype/syntax/lr/iteratable" "github.com/npillmayer/gotype/syntax/lr/sparse" ) // TODO: Improve documentation... // https://stackoverflow.com/questions/12968048/what-is-the-closure-of-a-left-recursive-lr0-item-with-epsilon-transitions // = optimization // https://www.cs.bgu.ac.il/~comp151/wiki.files/ps6.html#sec-2-7-3 // Actions for parser action tables. const ( ShiftAction = -1 AcceptAction = -2 ) // === Closure and Goto-Set Operations ======================================= // Refer to "Crafting A Compiler" by Charles N. Fisher & Richard J. LeBlanc, Jr. // Section 6.2.1 LR(0) Parsing // Compute the closure of an Earley item. func (ga *LRAnalysis) closure(i Item, A *Symbol) *iteratable.Set { S := newItemSet() S.Add(i) return ga.closureSet(S) } // Compute the closure of an Earley item. // https://www.cs.bgu.ac.il/~comp151/wiki.files/ps6.html#sec-2-7-3 func (ga *LRAnalysis) closureSet(S *iteratable.Set) *iteratable.Set { C := S.Copy() // add start items to closure C.IterateOnce() for C.Next() { item := asItem(C.Item()) A := item.PeekSymbol() // get symbol A after dot if A != nil && !A.IsTerminal() { // A is non-terminal R := ga.g.FindNonTermRules(A, true) if New := R.Difference(C); !New.Empty() { C.Union(New) } } } return C } func (ga *LRAnalysis) gotoSet(closure *iteratable.Set, A *Symbol) (*iteratable.Set, *Symbol) { // for every item in closure C // if item in C: N -> ... *A ... // advance N -> ... A * ... gotoset := newItemSet() for _, x := range closure.Values() { i := asItem(x) if i.PeekSymbol() == A { ii := i.Advance() T().Debugf("goto(%s) -%s-> %s", i, A, ii) gotoset.Add(ii) } } //gotoset.Dump() return gotoset, A } func (ga *LRAnalysis) gotoSetClosure(i *iteratable.Set, A *Symbol) (*iteratable.Set, *Symbol) { gotoset, _ := ga.gotoSet(i, A) //T().Infof("gotoset = %v", gotoset) gclosure := ga.closureSet(gotoset) //T().Infof("gclosure = %v", gclosure) T().Debugf("goto(%s) --%s--> %s", itemSetString(i), A, itemSetString(gclosure)) return gclosure, A } // === CFSM Construction ===================================================== // CFSMState is a state within the CFSM for a grammar. type CFSMState struct { ID int // serial ID of this state items *iteratable.Set // configuration items within this state Accept bool // is this an accepting state? } // CFSM edge between 2 states, directed and with a terminal type cfsmEdge struct { from *CFSMState to *CFSMState label *Symbol } // Dump is a debugging helper func (s *CFSMState) Dump() { T().Debugf("--- state %03d -----------", s.ID) Dump(s.items) T().Debugf("-------------------------") } func (s *CFSMState) isErrorState() bool { return s.items.Size() == 0 } // Create a state from an item set func state(id int, iset *iteratable.Set) *CFSMState { s := &CFSMState{ID: id} if iset == nil { s.items = newItemSet() } else { s.items = iset } return s } func (s *CFSMState) allItems() []interface{} { vals := s.items.Values() return vals } func (s *CFSMState) String() string { return fmt.Sprintf("(state %d | [%d])", s.ID, s.items.Size()) } func (s *CFSMState) containsCompletedStartRule() bool { for _, x := range s.items.Values() { i := asItem(x) if i.rule.Serial == 0 && i.PeekSymbol() == nil { return true } } return false } // Create an edge func edge(from, to *CFSMState, label *Symbol) *cfsmEdge { return &cfsmEdge{ from: from, to: to, label: label, } } // We need this for the set of states. It sorts states by serial ID. func stateComparator(s1, s2 interface{}) int { c1 := s1.(*CFSMState) c2 := s2.(*CFSMState) return utils.IntComparator(c1.ID, c2.ID) } // Add a state to the CFSM. Checks first if state is present. func (c *CFSM) addState(iset *iteratable.Set) *CFSMState { s := c.findStateByItems(iset) if s == nil { s = state(c.cfsmIds, iset) c.cfsmIds++ } c.states.Add(s) return s } // Find a CFSM state by the contained item set. func (c *CFSM) findStateByItems(iset *iteratable.Set) *CFSMState { it := c.states.Iterator() for it.Next() { s := it.Value().(*CFSMState) if s.items.Equals(iset) { return s } } return nil } func (c *CFSM) addEdge(s0, s1 *CFSMState, sym *Symbol) *cfsmEdge { e := edge(s0, s1, sym) c.edges.Add(e) return e } func (c *CFSM) allEdges(s *CFSMState) []*cfsmEdge { it := c.edges.Iterator() r := make([]*cfsmEdge, 0, 2) for it.Next() { e := it.Value().(*cfsmEdge) if e.from == s { r = append(r, e) } } return r } // CFSM is the characteristic finite state machine for a LR grammar, i.e. the // LR(0) state diagram. Will be constructed by a TableGenerator. // Clients normally do not use it directly. Nevertheless, there are some methods // defined on it, e.g, for debugging purposes, or even to // compute your own tables from it. type CFSM struct { g *Grammar // this CFSM is for Grammar g states *treeset.Set // all the states edges *arraylist.List // all the edges between states S0 *CFSMState // start state cfsmIds int // serial IDs for CFSM states } // create an empty (initial) CFSM automata. func emptyCFSM(g *Grammar) *CFSM { c := &CFSM{g: g} c.states = treeset.NewWith(stateComparator) c.edges = arraylist.New() return c } // TableGenerator is a generator object to construct LR parser tables. // Clients usually create a Grammar G, then a LRAnalysis-object for G, // and then a table generator. TableGenerator.CreateTables() constructs // the CFSM and parser tables for an LR-parser recognizing grammar G. type TableGenerator struct { g *Grammar ga *LRAnalysis dfa *CFSM gototable *sparse.IntMatrix actiontable *sparse.IntMatrix HasConflicts bool } // NewTableGenerator creates a new TableGenerator for a (previously analysed) grammar. func NewTableGenerator(ga *LRAnalysis) *TableGenerator { lrgen := &TableGenerator{} lrgen.g = ga.Grammar() lrgen.ga = ga return lrgen } // CFSM returns the characteristic finite state machine (CFSM) for a grammar. // Usually clients call lrgen.CreateTables() beforehand, but it is possible // to call lrgen.CFSM() directly. The CFSM will be created, if it has not // been constructed previously. func (lrgen *TableGenerator) CFSM() *CFSM { if lrgen.dfa == nil { lrgen.dfa = lrgen.buildCFSM() } return lrgen.dfa } // GotoTable returns the GOTO table for LR-parsing a grammar. The tables have to be // built by calling CreateTables() previously (or a separate call to // BuildGotoTable(...).) func (lrgen *TableGenerator) GotoTable() *sparse.IntMatrix { if lrgen.gototable == nil { T().P("lr", "gen").Errorf("tables not yet initialized") } return lrgen.gototable } // ActionTable returns the ACTION table for LR-parsing a grammar. The tables have to be // built by calling CreateTables() previously (or a separate call to // BuildSLR1ActionTable(...).) func (lrgen *TableGenerator) ActionTable() *sparse.IntMatrix { if lrgen.actiontable == nil { T().P("lr", "gen").Errorf("tables not yet initialized") } return lrgen.actiontable } // CreateTables creates the necessary data structures for an SLR parser. func (lrgen *TableGenerator) CreateTables() { lrgen.dfa = lrgen.buildCFSM() lrgen.gototable = lrgen.BuildGotoTable() lrgen.actiontable, lrgen.HasConflicts = lrgen.BuildSLR1ActionTable() } // AcceptingStates returns all states of the CFSM which represent an accept action. // Clients have to call CreateTables() first. func (lrgen *TableGenerator) AcceptingStates() []int { if lrgen.dfa == nil { T().Errorf("tables not yet generated; call CreateTables() first") return nil } acc := make([]int, 0, 3) for _, x := range lrgen.dfa.states.Values() { state := x.(*CFSMState) if state.Accept { //acc = append(acc, state.ID) it := lrgen.dfa.edges.Iterator() for it.Next() { e := it.Value().(*cfsmEdge) if e.to.ID == state.ID { acc = append(acc, e.from.ID) } } } } unique(acc) return acc } // Construct the characteristic finite state machine CFSM for a grammar. func (lrgen *TableGenerator) buildCFSM() *CFSM { T().Debugf("=== build CFSM ==================================================") G := lrgen.g cfsm := emptyCFSM(G) closure0 := lrgen.ga.closure(StartItem(G.rules[0])) item, sym := StartItem(G.rules[0]) T().Debugf("Start item=%v/%v", item, sym) T().Debugf("----------") Dump(closure0) T().Debugf("----------") cfsm.S0 = cfsm.addState(closure0) cfsm.S0.Dump() S := treeset.NewWith(stateComparator) S.Add(cfsm.S0) for S.Size() > 0 { s := S.Values()[0].(*CFSMState) S.Remove(s) G.EachSymbol(func(A *Symbol) interface{} { T().Debugf("checking goto-set for symbol = %v", A) gotoset, _ := lrgen.ga.gotoSetClosure(s.items, A) snew := cfsm.findStateByItems(gotoset) if snew == nil { snew = cfsm.addState(gotoset) if !snew.isErrorState() { S.Add(snew) if snew.containsCompletedStartRule() { snew.Accept = true } } } if !snew.isErrorState() { cfsm.addEdge(s, snew, A) } snew.Dump() return nil }) T().Debugf("-----------------------------------------------------------------") } return cfsm } // CFSM2GraphViz exports a CFSM to the Graphviz Dot format, given a filename. func (c *CFSM) CFSM2GraphViz(filename string) { f, err := os.Create(filename) if err != nil { panic(fmt.Sprintf("file open error: %v", err.Error())) } defer f.Close() f.WriteString(`digraph { graph [splines=true, fontname=Helvetica, fontsize=10]; node [shape=Mrecord, style=filled, fontname=Helvetica, fontsize=10]; edge [fontname=Helvetica, fontsize=10]; `) for _, x := range c.states.Values() { s := x.(*CFSMState) f.WriteString(fmt.Sprintf("s%03d [fillcolor=%s label=\"{%03d | %s}\"]\n", s.ID, nodecolor(s), s.ID, forGraphviz(s.items))) } it := c.edges.Iterator() for it.Next() { x := it.Value() edge := x.(*cfsmEdge) f.WriteString(fmt.Sprintf("s%03d -> s%03d [label=\"%s\"]\n", edge.from.ID, edge.to.ID, edge.label)) } f.WriteString("}\n") } func nodecolor(state *CFSMState) string { if state.Accept { return "lightgray" } return "white" } // =========================================================================== // BuildGotoTable builds the GOTO table. This is normally not called directly, but rather // via CreateTables(). func (lrgen *TableGenerator) BuildGotoTable() *sparse.IntMatrix { statescnt := lrgen.dfa.states.Size() maxtok := 0 lrgen.g.EachSymbol(func(A *Symbol) interface{} { if A.Token() > maxtok { // find maximum token value maxtok = A.Token() } return nil }) T().Infof("GOTO table of size %d x %d", statescnt, maxtok) gototable := sparse.NewIntMatrix(statescnt, maxtok, sparse.DefaultNullValue) states := lrgen.dfa.states.Iterator() for states.Next() { state := states.Value().(*CFSMState) edges := lrgen.dfa.allEdges(state) for _, e := range edges { //T().Debugf("edge %s --%v--> %v", state, e.label, e.to) //T().Debugf("GOTO (%d , %d ) = %d", state.ID, symvalue(e.label), e.to.ID) gototable.Set(state.ID, e.label.Value, int32(e.to.ID)) } } return gototable } // GotoTableAsHTML exports a GOTO-table in HTML-format. func GotoTableAsHTML(lrgen *TableGenerator, w io.Writer) { if lrgen.gototable == nil { T().Errorf("GOTO table not yet created, cannot export to HTML") return } parserTableAsHTML(lrgen, "GOTO", lrgen.gototable, w) } // ActionTableAsHTML exports the SLR(1) ACTION-table in HTML-format. func ActionTableAsHTML(lrgen *TableGenerator, w io.Writer) { if lrgen.actiontable == nil { T().Errorf("ACTION table not yet created, cannot export to HTML") return } parserTableAsHTML(lrgen, "ACTION", lrgen.actiontable, w) } func parserTableAsHTML(lrgen *TableGenerator, tname string, table *sparse.IntMatrix, w io.Writer) { var symvec = make([]*Symbol, len(lrgen.g.terminals)+len(lrgen.g.nonterminals)) io.WriteString(w, "<html><body>\n") io.WriteString(w, "<img src=\"cfsm.png\"/><p>") io.WriteString(w, fmt.Sprintf("%s table of size = %d<p>", tname, table.ValueCount())) io.WriteString(w, "<table border=1 cellspacing=0 cellpadding=5>\n") io.WriteString(w, "<tr bgcolor=#cccccc><td></td>\n") j := 0 lrgen.g.EachSymbol(func(A *Symbol) interface{} { io.WriteString(w, fmt.Sprintf("<td>%s</td>", A)) symvec[j] = A j++ return nil }) io.WriteString(w, "</tr>\n") states := lrgen.dfa.states.Iterator() var td string // table cell for states.Next() { state := states.Value().(*CFSMState) io.WriteString(w, fmt.Sprintf("<tr><td>state %d</td>\n", state.ID)) for _, A := range symvec { v1, v2 := table.Values(state.ID, A.Value) if v1 == table.NullValue() { td = "&nbsp;" } else if v2 == table.NullValue() { td = fmt.Sprintf("%d", v1) } else { td = fmt.Sprintf("%d/%d", v1, v2) } io.WriteString(w, "<td>") io.WriteString(w, td) io.WriteString(w, "</td>\n") } io.WriteString(w, "</tr>\n") } io.WriteString(w, "</table></body></html>\n") } // =========================================================================== // BuildLR0ActionTable contructs the LR(0) Action table. This method is not called by // CreateTables(), as we normally use an SLR(1) parser and therefore an action table with // lookahead included. This method is provided as an add-on. func (lrgen *TableGenerator) BuildLR0ActionTable() (*sparse.IntMatrix, bool) { statescnt := lrgen.dfa.states.Size() T().Infof("ACTION.0 table of size %d x 1", statescnt) actions := sparse.NewIntMatrix(statescnt, 1, sparse.DefaultNullValue) return lrgen.buildActionTable(actions, false) } // BuildSLR1ActionTable constructs the SLR(1) Action table. This method is normally not called // by clients, but rather via CreateTables(). It builds an action table including // lookahead (using the FOLLOW-set created by the grammar analyzer). func (lrgen *TableGenerator) BuildSLR1ActionTable() (*sparse.IntMatrix, bool) { statescnt := lrgen.dfa.states.Size() maxtok := 0 lrgen.g.EachSymbol(func(A *Symbol) interface{} { if A.Token() > maxtok { // find maximum token value maxtok = A.Token() } return nil }) T().Infof("ACTION.1 table of size %d x %d", statescnt, maxtok) actions := sparse.NewIntMatrix(statescnt, maxtok, sparse.DefaultNullValue) return lrgen.buildActionTable(actions, true) } // For building an ACTION table we iterate over all the states of the CFSM. // An inner loop iterates over alle the Earley items within a CFSM-state. // If an item has a non-terminal immediately after the dot, we produce a shift // entry. If an item's dot is behind the complete (non-epsilon) RHS of a rule, // then // - for the LR(0) case: we produce a reduce-entry for the rule // - for the SLR case: we produce a reduce-entry for for the rule for each // terminal from FOLLOW(LHS). // // The table is returned as a sparse matrix, where every entry may consist of up // to 2 entries, thus allowing for shift/reduce- or reduce/reduce-conflicts. // // Shift entries are represented as -1. Reduce entries are encoded as the // ordinal no. of the grammar rule to reduce. 0 means reducing the start rule, // i.e., accept. func (lrgen *TableGenerator) buildActionTable(actions *sparse.IntMatrix, slr1 bool) ( *sparse.IntMatrix, bool) { // hasConflicts := false states := lrgen.dfa.states.Iterator() for states.Next() { state := states.Value().(*CFSMState) T().Debugf("--- state %d --------------------------------", state.ID) for _, v := range state.items.Values() { T().Debugf("item in s%d = %v", state.ID, v) i := asItem(v) A := i.PeekSymbol() prefix := i.Prefix() T().Debugf("symbol at dot = %v, prefix = %v", A, prefix) if A != nil && A.IsTerminal() { // create a shift entry P := pT(state, A) T().Debugf(" creating action entry --%v--> %d", A, P) if slr1 { if a1 := actions.Value(state.ID, A.Token()); a1 != actions.NullValue() { T().Debugf(" %s is 2nd action", valstring(int32(P), actions)) if a1 == ShiftAction { T().Debugf(" relax, double shift") } else { hasConflicts = true actions.Add(state.ID, A.Token(), int32(P)) } } else { actions.Add(state.ID, A.Token(), int32(P)) } T().Debugf(actionEntry(state.ID, A.Token(), actions)) } else { actions.Add(state.ID, 1, int32(P)) } } if A == nil { // we are at the end of a rule rule, inx := lrgen.g.matchesRHS(i.rule.LHS, prefix) // find the rule if inx >= 0 { // found => create a reduce entry if slr1 { lookaheads := lrgen.ga.Follow(rule.LHS) T().Debugf(" Follow(%v) = %v", rule.LHS, lookaheads) laslice := lookaheads.AppendTo(nil) //for _, la := range lookaheads { for _, la := range laslice { a1, a2 := actions.Values(state.ID, la) if a1 != actions.NullValue() || a2 != actions.NullValue() { T().Debugf(" %s is 2nd action", valstring(int32(inx), actions)) hasConflicts = true } actions.Add(state.ID, la, int32(inx)) // reduce rule[inx] T().Debugf(" creating reduce_%d action entry @ %v for %v", inx, la, rule) T().Debugf(actionEntry(state.ID, la, actions)) } } else { T().Debugf(" creating reduce_%d action entry for %v", inx, rule) actions.Add(state.ID, 1, int32(inx)) // reduce rule[inx] } } } } } return actions, hasConflicts } func pT(state *CFSMState, terminal *Symbol) int { if terminal.Token() == scanner.EOF { return AcceptAction } return ShiftAction } // ---------------------------------------------------------------------- func unique(in []int) []int { // from slice tricks sort.Ints(in) j := 0 for i := 1; i < len(in); i++ { if in[j] == in[i] { continue } j++ // in[i], in[j] = in[j], in[i] // preserve the original data in[j] = in[i] // only set what is required } result := in[:j+1] return result } func actionEntry(stateID int, la int, aT *sparse.IntMatrix) string { a1, a2 := aT.Values(stateID, la) return fmt.Sprintf("Action(%s,%s)", valstring(a1, aT), valstring(a2, aT)) } // valstring is a short helper to stringify an action table entry. func valstring(v int32, m *sparse.IntMatrix) string { if v == m.NullValue() { return "<none>" } else if v == AcceptAction { return "<accept>" } else if v == ShiftAction { return "<shift>" } return fmt.Sprintf("<reduce %d>", v) } func itemSetString(S *iteratable.Set) string { var b bytes.Buffer b.WriteString("{") S.IterateOnce() first := true for S.Next() { item := S.Item().(Item) if first { b.WriteString(" ") first = false } else { b.WriteString(", ") } b.WriteString(item.String()) } b.WriteString(" }") return b.String() }
C
UTF-8
3,124
2.5625
3
[ "BSD-3-Clause-LBNL" ]
permissive
/** * A struct storing the configuration of the indexing procedure. */ typedef struct { int parallelism; /** < parallelism of metadata index */ // index_anchor_t *_idx_anchor; /** < an internal instance of root index_anchor */ int rank; /** < rank of the current MPI process */ int size; /** < number of all MPI processes */ int current_file_count; /** < The number of files current process have gone through */ int topk; /** < The number of first few files that will be scanned */ int is_build_from_scratch; /** < Indicating if we are building the index from scratch */ int is_mdb_enabled; /** < Indicating if mdb function is enabled (1=enabled; 0=disabled). Usually, this should be set to 1. */ int is_aof_enabled; /** < Indicating if aof function is enabled (1=enabled; 0=disabled). Enabling this may slightly slow down the indexing performance, but enhancing the fault-tolerance. */ char *dataset_path; /** <path to the dataset directory */ char *index_dir_path; /** <path to the index file directory */ } indexing_config_t; /** * Initializing metadata index with specified parallelism parameter. * * @param parallelism Specified parallelism parameter. * @param rank The rank of the current process. If MPI is disabled, it should be 0. * @param size The number of all MPI processes. If MPI is disabled, it should be 1. * @param topk The number of first few files that needs to be scanned for indexing. * @param enable_mdb Whether mdb functionality should be enabled. 1: enable. 0: disable. * @param enable_aof Whether aof functionality should be enabled. 1: enable. 0: disable. * @param dataset_path path to the dataset directory. * @param index_dir_path path to the index file directory * @return An instance of indexing_config_t struct. */ indexing_config_t *init_indexing_config(int parallelism, int rank, int size, int topk, int enable_mdb, int enable_aof, char *dataset_path, char *index_dir_path); /** * Scan a collection of data and build the metadata index from scratch. * * @param param an instance of indexing_config_t. * @return 0 success, 1 error raised. */ int indexing_data_collection(indexing_config_t *param); // int save_index_change_to_aof(char *dir_path); /** * Recover the in-memory index from the mdb files. * * @param param an instance of indexing_config_t. * @return 0 success, 1 error raised. */ int recovering_index(indexing_config_t *param); // int recovering_index_from_aof(char *aof_dir_path);
Markdown
UTF-8
1,254
3.3125
3
[]
no_license
# Utilizando estilos Globais Diferente do estilo escopado para o componente, o Estilo Global como o próprio nome diz, faz referência a todo o projeto. Podendo ser utilizado dentro de qualquer componente do REACT. Dentro da pasta _**src**_, crie uma pasta _**styles**_.Nesta pasta crie o arquivo _**global.js**_ e adicione o seguinte conteúdo: ```js import { createGlobalStyle } from 'styled-components'; export default createGlobalStyle` *{ margin:0; padding:0; outline:0; box-sizing: border-box; } html,body, #root{ min-height: 100%; } body{ background: #7159c1; -webkit-font-smoothing: antialiased !important; } body, input, button{ color: #222; font-size: 14px; font-family: Arial, Helvetica, sans-serif; } button { cursor: pointer; } `; ``` Temos então o arquivo de estilo global criado, entretanto ele ainda não foi importado em nenhum lugar. como ele é o estilo global, vamos importa-lo dentro de nosso _**App.js**_, que fica da seguinte forma: ```js import React from 'react'; import Routes from './routes'; import GlobalStyle from './styles/global'; function App() { return ( <> <Routes /> <GlobalStyle /> </> ); } export default App; ```
C#
UTF-8
1,314
2.828125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using MongoDB.Driver; using MOKJU_API.Models; using Microsoft.Extensions.Configuration; namespace MOKJU_API.Services { public class ShopService { private readonly IMongoCollection<Shop> _shop; public ShopService(IConfiguration config) { var client = new MongoClient(config.GetConnectionString("BookstoreDb")); var database = client.GetDatabase("Database"); _shop = database.GetCollection<Shop>("Shop"); } public List<Shop> Get() { return _shop.Find(shop => true).ToList(); } public Shop Get(string id) { return _shop.Find<Shop>(shop => shop.Id == id).FirstOrDefault(); } public Shop Create(Shop shop) { _shop.InsertOne(shop); return shop; } public void Update(string id, Shop shopIn) { _shop.ReplaceOne(shop => shop.Id == id, shopIn); } public void Remove(Shop shopIn) { _shop.DeleteOne(shop => shop.Id == shopIn.Id); } public void Remove(string id) { _shop.DeleteOne(shop => shop.Id == id); } } }
SQL
UTF-8
768
2.703125
3
[]
no_license
--liquibase formatted sql --changeset converter:baseline dbms:mysql,mariadb runOnChange:true ALTER TABLE ArtistInstance ADD FOREIGN KEY (ArtistId) REFERENCES Artist(ArtistId); ALTER TABLE GenreAssign ADD FOREIGN KEY (GenreId) REFERENCES Genre(GenreId); ALTER TABLE GenreAssign ADD FOREIGN KEY (ArtistInstanceId) REFERENCES ArtistInstance(ArtistInstanceId); ALTER TABLE RecordLabelAssign ADD FOREIGN KEY (RecordLabelId) REFERENCES RecordLabel(RecordLabelId); ALTER TABLE RecordLabelAssign ADD FOREIGN KEY (ArtistInstanceId) REFERENCES ArtistInstance(ArtistInstanceId); ALTER TABLE TypeOfArtistAssign ADD FOREIGN KEY (TypeOfArtistId) REFERENCES TypeOfArtist(TypeOfArtistId); ALTER TABLE TypeOfArtistAssign ADD FOREIGN KEY (ArtistId) REFERENCES Artist(ArtistId);
TypeScript
UTF-8
3,190
2.8125
3
[]
no_license
/* eslint-disable @typescript-eslint/camelcase */ import { Definition } from '../../shared/models/define/define-models'; import { DefineService } from './define.service'; const testArray: Definition[] = [ { definition: 'one', permalink: 'https://urbandictionary.com/whatever', thumbs_up: 12, author: 'jr', word: 'test', defid: 1, written_on: 'whatever', // ISO Date example: 'test', thumbs_down: 14, current_vote: 'test', sound_urls: ['test'], }, { definition: 'two', permalink: 'https://urbandictionary.com/whatever', thumbs_up: 12, author: 'jr', word: 'test', defid: 1, written_on: 'whatever', // ISO Date example: 'test', thumbs_down: 14, current_vote: 'test', sound_urls: ['test'], }, { definition: 'three', permalink: 'https://urbandictionary.com/whatever', thumbs_up: 12, author: 'jr', word: 'test', defid: 1, written_on: 'whatever', // ISO Date example: 'test', thumbs_down: 14, current_vote: 'test', sound_urls: ['test'], }, { definition: 'four', permalink: 'https://urbandictionary.com/whatever', thumbs_up: 12, author: 'jr', word: 'test', defid: 1, written_on: 'whatever', // ISO Date example: 'test', thumbs_down: 14, current_vote: 'test', sound_urls: ['test'], }, { definition: 'five', permalink: 'https://urbandictionary.com/whatever', thumbs_up: 12, author: 'jr', word: 'test', defid: 1, written_on: 'whatever', // ISO Date example: 'five', thumbs_down: 14, current_vote: 'test', sound_urls: ['test'], }, ]; describe('define-utils', () => { let defineService: DefineService; beforeEach(() => { defineService = DefineService.getInstance(); }); describe('capitalizeFirstLetter()', () => { it('should capitalize all first letters of a given string', () => { expect(defineService.capitalizeFirstLetter('test string')).toBe('Test String'); }); it('should capitalize only the first letter of the first word when all = false', () => { expect(defineService.capitalizeFirstLetter('test string', false)).toBe('Test string'); }); }); describe('define()', () => { it('should return a promise when attempting to define', () => { expect(defineService.define('test')).toBeDefined(); // Firm this up }); }); describe('formatDefs()', () => { it('should return an array of 3 length when no maxDefs parameter is provided', () => { expect(defineService.formatDefs(testArray, 'test').length).toBe(3); }); it('should return an array of 4 length when a maxDefs parameter of 4 is provided', () => { expect(defineService.formatDefs(testArray, 'test', 4).length).toBe(4); }); it('should return testArray.length if maxDefs parameter is larger than testArray.length', () => { expect(defineService.formatDefs(testArray, 'test', 10).length).toBe(5); }); it(`should return [{ "Sorry, no definitions found" }] if defArr === 0`, () => { expect(defineService.formatDefs([], 'test')[0].text).toBe('Sorry, no definitions found.'); }); }); });
Python
UTF-8
2,988
2.53125
3
[ "Apache-2.0" ]
permissive
import torch import torch.nn as nn import torch.distributions as dist import torch.nn.functional as F import numpy as np import math def loss_function(recon_x,x,mu,logstd,rec_log_std=0,sum_samplewise=True): """ recon_x : reconstructed sample x : sample mu: mean of sample logstd: log of std deviation rec_log_std: reconstruction log standard deviation Gives the loss function for CeVAE network""" rec_std = math.exp(rec_log_std) rec_var = rec_std**2 x_dist = dist.Normal(recon_x,rec_std) log_p_x_z = x_dist.log_prob(x) if sum_samplewise: log_p_x_z = torch.sum(log_p_x_z, dim=(1, 2, 3)) z_prior = dist.Normal(0, 1.) z_post = dist.Normal(mu, torch.exp(logstd)) kl_div = dist.kl_divergence(z_post, z_prior) if sum_samplewise: kl_div = torch.sum(kl_div, dim=(1, 2, 3)) if sum_samplewise: loss = torch.mean(kl_div - log_p_x_z) else: loss = torch.mean(torch.sum(kl_div, dim=(1, 2, 3)) - torch.sum(log_p_x_z, dim=(1, 2, 3))) return loss, kl_div, -log_p_x_z # def kl_loss_fn(recon_x,x,mu,logstd,rec_log_std=0,sum_samplewise=True): # """ # recon_x : reconstructed sample # x : sample # mu: mean of sample # logstd: log of std deviation # rec_log_std: reconstruction log standard deviation # Gives the loss function for CeVAE network""" # rec_std = math.exp(rec_log_std) # rec_var = rec_std**2 # x_dist = dist.Normal(recon_x,rec_std) # log_p_x_z = x_dist.log_prob(x) # if sum_samplewise: # log_p_x_z = torch.sum(log_p_x_z, dim=(1, 2, 3)) # z_prior = dist.Normal(0, 1.) # z_post = dist.Normal(mu, torch.exp(logstd)) # kl_div = dist.kl_divergence(z_post, z_prior) # if sum_samplewise: # kl_div = torch.sum(kl_div, dim=(1, 2, 3)) # if sum_samplewise: # loss = torch.mean(kl_div - log_p_x_z) # else: # loss = torch.mean(torch.sum(kl_div, dim=(1, 2, 3)) - torch.sum(log_p_x_z, dim=(1, 2, 3))) # return loss, kl_div, -log_p_x_z def kl_loss_fn(recon_x,x,mu,logstd,rec_log_std=0,sum_samplewise=True): BCE = F.mse_loss(recon_x, x) KLD = -0.5 * torch.sum(1 + logstd - mu.pow(2) - logstd.exp()) # loss = nn.KLDivLoss() # losses = loss(mu,logstd**2) loss = BCE*KLD return loss, BCE, KLD def kl_loss_fn_train(recon_x,x,mu,logstd,rec_log_std=0,sum_samplewise=True): BCE = F.mse_loss(recon_x, x) KLD = -0.5 * torch.sum(1 + logstd - mu.pow(2) - logstd.exp()) # loss = nn.KLDivLoss() # losses = loss(mu,logstd**2) loss = BCE*KLD return loss def rec_loss_ce(recon_x, x): """ The function checks the l2 loss for reconstruction of image in Context Encoder """ loss_fn = nn.MSELoss() loss = loss_fn(x,recon_x) return loss def rec_loss_fn (recon_x,x): """ The function checks the reconstruction loss of image in VAE """ loss_fn = nn.MSELoss() loss = loss_fn(x,recon_x) return loss
Java
UTF-8
264
2.296875
2
[]
no_license
public class RmvFdLCh { public static void main(String[] args) { String str="maybe"; String s=""; //for(int i=0;i<str.length();i++){ s=str.substring(1,str.length()-1); System.out.println(s); } }
Java
UTF-8
732
2.4375
2
[]
no_license
package com.kgc.xml; import org.aspectj.lang.ProceedingJoinPoint; public class Handler { //切面 公共的代码 增强类 public void login(){ System.out.println("验证登录通过!!!"); } public void afterReturn(){ System.out.println("后置增强"); } //ProceedingJoinPoint执行连接点 public void around(ProceedingJoinPoint p) throws Throwable { System.out.println("环绕增强前"); p.proceed(); //调用目标方法 切点 //int i=1/0; System.out.println("环绕增强后"); } public void excep(){ System.out.println("异常增强"); } public void end(){ System.out.println("最后增强"); } }
Markdown
UTF-8
8,153
2.546875
3
[]
no_license
--- description: "Simple Way to Prepare Quick Beef short ribs" title: "Simple Way to Prepare Quick Beef short ribs" slug: 2182-simple-way-to-prepare-quick-beef-short-ribs date: 2021-01-16T04:25:04.631Z image: https://img-global.cpcdn.com/recipes/00d709441d6b005e/751x532cq70/beef-short-ribs-recipe-main-photo.jpg thumbnail: https://img-global.cpcdn.com/recipes/00d709441d6b005e/751x532cq70/beef-short-ribs-recipe-main-photo.jpg cover: https://img-global.cpcdn.com/recipes/00d709441d6b005e/751x532cq70/beef-short-ribs-recipe-main-photo.jpg author: Bobby Hines ratingvalue: 4 reviewcount: 36361 recipeingredient: - "3 splashes red wine vinegar" - "3 cups red wine" - "1/4 cup brown sugar" - "1 can tomato paste" - "8 carrots" - "1 medium onion" - "3 garlic cloves" - "3 tomatoes" - "1 roasted bell pepper" - " Beef short ribs" - "8 radishes" - "6 rosemary twigs" - " Pured yucca" - "3 lbs yucca root" - "Half stick of butter" - "1/4 cup Greek yogurt" recipeinstructions: - "In one pot cook down red wine, red wine vinegar, tomato paste, and brown sugar" - "Sauté 2 carrots, the garlic, bell pepper, tomatoes, and onion with a splash of gazebo room Greek dressing." - "Combine the sautéed vegetables with the red wine sauce. Cook down until vegetables fall apart. Purée the mixture" - "Brown the beef short ribs and lay in oven safe pan. Add the rest of the uncooked vegetables into the pan. Cover with the rest of the rosemary." - "Pour the thick sauce over everything in the pan and put in oven at 350 until the meat is tender." - "Peel yucca root, dice it, and boil it." - "Drain the yucca and purée it. Add the butter and yogurt and combine thoroughly." - "Serve beef short ribs over the puréed yucca" categories: - Recipe tags: - beef - short - ribs katakunci: beef short ribs nutrition: 233 calories recipecuisine: American preptime: "PT30M" cooktime: "PT53M" recipeyield: "4" recipecategory: Dessert --- ![Beef short ribs](https://img-global.cpcdn.com/recipes/00d709441d6b005e/751x532cq70/beef-short-ribs-recipe-main-photo.jpg) Hello everybody, it is John, welcome to my recipe page. Today, I will show you a way to prepare a distinctive dish, beef short ribs. It is one of my favorites food recipes. For mine, I'm gonna make it a little bit unique. This will be really delicious. Short ribs are the quintessential caveman cut, straight out of Fred Flinstone&#39;s larder, with their hunks of rich meat on the bone, looking primal and carnivore-ready. They&#39;re a rich winter meal, too, easy and. In this recipe for slow cooker short ribs, the braising liquid is simple, but flavorful. The basis is a combination of sautéed onion and garlic. Beef short ribs is one of the most favored of current trending foods on earth. It's enjoyed by millions every day. It is simple, it's fast, it tastes delicious. They are nice and they look wonderful. Beef short ribs is something which I have loved my entire life. To get started with this particular recipe, we have to prepare a few components. You can have beef short ribs using 16 ingredients and 8 steps. Here is how you cook that. <!--inarticleads1--> ##### The ingredients needed to make Beef short ribs: 1. Get 3 splashes red wine vinegar 1. Get 3 cups red wine 1. Take 1/4 cup brown sugar 1. Take 1 can tomato paste 1. Make ready 8 carrots 1. Prepare 1 medium onion 1. Prepare 3 garlic cloves 1. Take 3 tomatoes 1. Prepare 1 roasted bell pepper 1. Prepare Beef short ribs 1. Take 8 radishes 1. Get 6 rosemary twigs 1. Get Puréed yucca 1. Get 3 lbs yucca root 1. Make ready Half stick of butter 1. Prepare 1/4 cup Greek yogurt This are delicious beef short ribs cooked in a sweet hot sauce. Beef Short ribs cooked low and slow transform into tender, sweet, savoury and delicious meat. With only a couple of ingredients, you will be blown away with the amount of flavour that these ribs have. These barbecue beef short ribs make an easy complete meal in one pot. <!--inarticleads2--> ##### Instructions to make Beef short ribs: 1. In one pot cook down red wine, red wine vinegar, tomato paste, and brown sugar 1. Sauté 2 carrots, the garlic, bell pepper, tomatoes, and onion with a splash of gazebo room Greek dressing. 1. Combine the sautéed vegetables with the red wine sauce. Cook down until vegetables fall apart. Purée the mixture 1. Brown the beef short ribs and lay in oven safe pan. Add the rest of the uncooked vegetables into the pan. Cover with the rest of the rosemary. 1. Pour the thick sauce over everything in the pan and put in oven at 350 until the meat is tender. 1. Peel yucca root, dice it, and boil it. 1. Drain the yucca and purée it. Add the butter and yogurt and combine thoroughly. 1. Serve beef short ribs over the puréed yucca With only a couple of ingredients, you will be blown away with the amount of flavour that these ribs have. These barbecue beef short ribs make an easy complete meal in one pot. The slow-cooked short ribs are cooked with potatoes and vegetables, along with a flavorful barbecue sauce mixture. Beef short ribs, braised in red wine and veal stock with onion, celery, and carrots. These braised beef short ribs are easy to make, so do not be intimidated by the overall time! Foods That Can Make You Happy A lot of us think that comfort foods are bad for us and that we need to stay away from them. Sometimes, if your comfort food is essentially candy or other junk foods, this can be true. Other times, though, comfort foods can be altogether nourishing and it's good for you to consume them. There are some foods that basically can boost your moods when you consume them. When you feel a little down and need an emotional pick-me-up, test out a few of these. Eggs, believe it or not, are great for helping you fight depression. Just see to it that you do not toss the egg yolk. The egg yolk is the most important part of the egg in terms of helping raise your mood. Eggs, the egg yolk particularly, are stuffed full of B vitamins. B vitamins can be fantastic for lifting up your mood. This is because they help improve the function of your neural transmitters, the parts of your brain that control your mood. Eat an egg and feel better! Make a trail mix out of seeds and/or nuts. Peanuts, cashews, sunflower seeds, almonds, pumpkin seeds, etc are all terrific for helping to boost your mood. This is possible as these foods are high in magnesium which raises your production of serotonin. Serotonin is a feel-good substance that directs the brain how to feel at any given point in time. The more serotonin you have, the more pleasant you will feel. Not only that, nuts, particularly, are a fantastic protein food source. Cold water fish are great if you would like to feel happier. Salmon, herring, tuna, mackerel, trout, etc, they're all high in omega-3 fatty acids and DHA. Omega-3 fatty acids and DHA are two things that promote the quality and the function of your brain's grey matter. It's the truth: consuming tuna fish sandwiches can really help you fight your depression. It's not hard to overcome your bad mood when you consume grains. Barley, quinoa, millet, teff, etc are all excellent for helping you be in a happier state of mind. They fill you up better and that can help improve your moods too. Feeling hungry can be awful! The reason these grains can improve your mood is that they are easy for your stomach to digest. These foods are easier to digest than others which helps jumpstart a rise in your sugar levels which in turn brings up your mood to a happier place. Green tea is fantastic for moods. You just knew it had to be included in this article, right? Green tea is high in a specific amino acid called L-theanine. Studies have found that this particular amino acid can actually stimulate brain waves. This helps raise your mental sharpness while having a relaxing effect on the rest of your body. You knew that green tea helps you feel better. Now you are aware that green tea helps you to elevate your moods as well! Now you can see that junk food isn't necessarily what you should eat when you are wanting to help your moods get better. Try a couple of of these tips instead.
Shell
UTF-8
3,622
2.6875
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
#!/bin/sh # # (c) 2019 Copyright, Real-Time Innovations, Inc. All rights reserved. # # RTI grants Licensee a license to use, modify, compile, and create derivative # works of the Software. Licensee has the right to distribute object form # only for use with RTI products. The Software is provided "as is", with no # warranty of any type, including any warranty for fitness for any purpose. # RTI is under no obligation to maintain or support the Software. RTI shall # not be liable for any incidental or consequential damages arising out of the # use or inability to use the software. # ############################################################################### ############################################################################### RTI_PLUGINS_CLONE_DIR=rtiroutingservice-plugins RTI_PLUGINS_URL=https://github.com/rticommunity/rtiroutingservice-plugins.git RTI_PLUGINS_BRANCH=master # RSHELPER_CLONE_DIR=rtiroutingservice-plugin-helper # RSHELPER_URL=https://bitbucket.rti.com/scm/~asorbini/rtiroutingservice-plugin-helper.git # RSHELPER_BRANCH=release # RTI_MQTT_CLONE_DIR=rtiroutingservice-adapter-mqtt # RTI_MQTT_URL=https://bitbucket.rti.com/scm/~asorbini/rtiroutingservice-adapter-mqtt.git # RTI_MQTT_BRANCH=release # RTI_MQTT_DEPS=" # RSHELPER # " # RTI_TSFM_CLONE_DIR=rtiroutingservice-transform # RTI_TSFM_URL=https://bitbucket.rti.com/scm/~asorbini/rtiroutingservice-transform.git # RTI_TSFM_BRANCH=release # RTI_TSFM_DEPS=" # RSHELPER # " # RTI_TSFM_FIELD_CLONE_DIR=rtiroutingservice-transform-field # RTI_TSFM_FIELD_URL=https://bitbucket.rti.com/scm/~asorbini/rtiroutingservice-transform-field.git # RTI_TSFM_FIELD_BRANCH=release # RTI_TSFM_FIELD_DEPS=" # RSHELPER # RTI_TSFM # " # RTI_TSFM_JSON_CLONE_DIR=rtiroutingservice-transform-json # RTI_TSFM_JSON_URL=https://bitbucket.rti.com/scm/~asorbini/rtiroutingservice-transform-json.git # RTI_TSFM_JSON_BRANCH=release # RTI_TSFM_JSON_DEPS=" # RSHELPER # RTI_TSFM # " # RTI_PRCS_FWD_CLONE_DIR=rtiroutingservice-process-fwd # RTI_PRCS_FWD_URL=https://bitbucket.rti.com/scm/~asorbini/rtiroutingservice-process-fwd.git # RTI_PRCS_FWD_BRANCH=release # RTI_PRCS_FWD_DEPS=" # RSHELPER # " # RTI_MQTTSHAPES_CLONE_DIR=rtiroutingservice-example-mqtt-shapes # RTI_MQTTSHAPES_URL=https://bitbucket.rti.com/scm/~asorbini/rtiroutingservice-example-mqtt-shapes.git # RTI_MQTTSHAPES_BRANCH=release # RTI_MQTTSHAPES_DEPS=" # RSHELPER # RTI_MQTT # RTI_TSFM # RTI_TSFM_FIELD # RTI_TSFM_JSON # RTI_PRCS_FWD # " # RTI_PLUGINS_ALL=" # RTI_PLUGINS # RTI_MQTT # RTI_TSFM # RTI_TSFM_FIELD # RTI_TSFM_JSON # RTI_PRCS_FWD # RTI_MQTTSHAPES # " RTI_PLUGINS_ALL=" RTI_PLUGINS " ############################################################################### ############################################################################### SH_DIR=$(cd "$(dirname "${0}")" && pwd) TEST_HELPERS="${SH_DIR}/test_helpers.sh" . ${TEST_HELPERS} ############################################################################### TEST_TARGETS="${TEST_TARGETS:-${RTI_PLUGINS_ALL}}" TEST_MAKE_TGT_BUILD=${TEST_MAKE_TGT_BUILD:-} TEST_MAKE_TGT_CLEAN=${TEST_MAKE_TGT_CLEAN:-clean-all} TEST_CMAKE_BUILD_DIR="${TEST_CMAKE_BUILD_DIR:-build}" TEST_CMAKE_INSTALL_DIR="${TEST_CMAKE_INSTALL_DIR:-install}" TEST_CMAKE_GENERATOR="${TEST_CMAKE_GENERATOR:-Unix Makefiles}" TEST_CMAKE_SKIP_INSTALL="${TEST_CMAKE_SKIP_INSTALL:-}" TEST_CMAKE_BUILD_TYPE="${TEST_BUILD_TYPE:-Release}" TEST_ROOT="${TEST_ROOT:-$(pwd)/.test-tmp}" TEST_LOG="${TEST_LOG:-${TEST_ROOT}/test-$(date +%Y%m%d-%H%M%S).log}" ############################################################################### test_init
Java
UTF-8
380
2.53125
3
[]
no_license
import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.NoSuchElementException; import java.io.FileNotFoundException; public abstract class Plan{ private String name; protected Plan(String name){ this.name=name; } public String getName(){return name;} public abstract double getCost(PhoneUsage usage); }
JavaScript
UTF-8
1,351
2.796875
3
[]
no_license
//1-require express validator const {body, validationResult} = require('express-validator') const registerValidators = () => [ body('firstName', "The first name is required").notEmpty(), body('lastName', "The last name is required").notEmpty(), body('email', "Invalid email").isEmail(), body('password', "The password must contain from 6 to 12 characters, at least one Upper case, at least one lower case.").isLength({ min: 6, max: 12 }).matches( /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z]/, ), ] const loginValidators = () => [ body('email', "Invalid email").isEmail(), body('password', "The password must contain from 6 to 12 characters, at least one Upper case, at least one lower case.").isLength({ min: 6, max: 12 }).matches( /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z]/, ), ] const commentValidators = () => [ body('commenter', "Specify a user name").notEmpty(), body('commentBody', "The comment is required").notEmpty(), ] const validator = (req, res, next) => { const errors = validationResult(req) if (!errors.isEmpty()) { return res.status(400).send({ errors: errors.array().map(el => ({msg: el.msg})) }) } next() } module.exports = {registerValidators, loginValidators, commentValidators,validator}
C++
UTF-8
1,484
3.265625
3
[ "MIT" ]
permissive
#include <vector> using std::vector; using std::max; using std::min; class Solution { public: int maximalRectangle(vector<vector<char>>& matrix) { int ret = 0, row = matrix.size(); if (row == 0) return ret; int column = matrix[0].size(); vector<int> left(column, 0), right(column, column), height(column, 0); for (auto v : matrix) { for (int i = 0; i < column; ++i) { if (v[i] == '1') height[i]++; else height[i] = 0; } int curr_left = 0; for (int i = 0; i < column; ++i) { if (v[i] == '1') left[i] = max(left[i], curr_left); else { left[i] = 0; curr_left = i + 1; } } int curr_right = column; for (int i = column - 1; i >= 0; --i) { if (v[i] == '1') right[i] = min(right[i], curr_right); else { right[i] = column; curr_right = i; } } for (int i = 0; i < column; ++i) { ret = max(ret, (right[i] - left[i]) * height[i]); } } return ret; } };
Shell
UTF-8
248
3.0625
3
[]
no_license
#!/bin/bash # How to use variables a=123 HELLO=$a echo HELLO # HELLO echo "HELLO" # HELLO echo $HELLO # 123 echo ${HELLO} # 123 echo '$HELLO' # $HELLO echo HELLO="A B CDE" echo $HELLO # A B CDE echo "$HELLO" # A B CDE
Markdown
UTF-8
5,060
3.9375
4
[]
no_license
# prop 装饰器 Props是在元素上公开的自定义属性/属性,开发人员可以为其提供值。子组件不应该知道或引用父组件,因此应该使用道具将数据从父组件传递到子组件。组件需要使用@Prop()decorator显式声明它们希望接收的道具。道具可以是数字、字符串、布尔值,甚至是对象或数组。默认情况下,当设置了用@Prop()装饰器装饰的成员时,该组件将有效地重新呈现 ``` import { Prop } from '@stencil/core'; ... export class TodoList { @Prop() color: string; @Prop() favoriteNumber: number; @Prop() isSelected: boolean; @Prop() myHttpService: MyHttpService; } ``` 在TodoList类中,通过this操作符访问Props。 ``` logColor() { console.log(this.color) } ``` 外部,Prop设置在元素上。 ``` <todo-list color="blue" favorite-number="24" is-selected="true"></todo-list> ``` JSX中 使用驼峰 ``` <todo-list color="blue" favoriteNumber={24} isSelected="true"></todo-list> ``` 也可以使用JS访问 ``` const todoListElement = document.querySelector('todo-list'); console.log(todoListElement.myHttpService); // MyHttpService console.log(todoListElement.color); // blue ``` ##### Prop options Prop(opts?:PropOptions)decorator接受一个可选参数来指定某些选项,例如可变性、DOM属性的名称,或者属性的值是否应该反映到DOM中。 ``` export interface PropOptions { attribute?: string; mutable?: boolean; reflect?: boolean; ``` ##### Prop mutability 可变性 重要的是要知道,在默认情况下,Prop在组件逻辑中是不可变的。一旦用户设置了一个值,组件就不能在内部更新它。 但是,可以通过将属性声明为可变的方式,从组件内部显式地允许对其进行变异,如下例所示: ``` import { Prop } from '@stencil/core'; ... export class NameElement { @Prop({ mutable: true }) name: string = 'Stencil'; componentDidLoad() { this.name = 'Stencil 0.7.0'; } } ``` ##### Attribute Name 属性名 属性和组件属性是强连接的,但不一定相同。虽然属性是一个HTML概念,但属性是面向对象编程中固有的JS概念。 在Prop中,应用于属性的@Prop()装饰器将指示模具编译器也侦听DOM属性中的更改。 通常属性的名称与属性的名称相同,但情况并非总是如此。以以下组件为例: ``` import { Component, Prop } from '@stencil/core'; @Component({ tag: 'my-cmp' }) class Component { @Prop() value: string; @Prop() isValid: boolean; @Prop() controller: MyController; } ``` 此组件有3个属性,但编译器将只创建2个属性:value和isValid。 ``` <my-cmp value="Hello" is-valid></my-cmp> ``` 注意,控制器类型不是一个原语,因为DOM属性只能是字符串,所以有一个名为“controller”的相关DOM属性是没有意义的。 同时,isValid属性遵循camelCase命名,但属性不区分大小写,因此默认情况下属性名称将有效。 幸运的是,可以使用@Prop()decorator的attribute选项更改此“默认”行为: ``` import { Component, Prop } from '@stencil/core'; @Component({ tag: 'my-cmp' }) class Component { @Prop() value: string; @Prop({ attribute: 'valid' }) isValid: boolean; @Prop({ attribute: 'controller' }) controller: MyController; } ``` 通过使用此选项,我们可以明确哪些属性具有关联的DOM属性及其名称。 ##### Reflect Properties Values to Attributes 将属性值反映到属性 在某些情况下,保持props与属性同步可能很有用。在这种情况下,您可以将@Prop()decorator中的reflect选项设置为true,因为它默认为false ``` @Prop({ reflect: true }) ``` 当“prop”设置为“reflect”时,意味着它们的值将在DOM中呈现为HTML属性: 以以下组件为例: ``` @Component({ tag: 'my-cmp' }) class Cmp { @Prop({ reflect: true }) message = 'Hello'; @Prop({ reflect: false }) value = 'The meaning of life...'; @Prop({ reflect: true }) number = 42; } ``` demo ``` <my-cmp message="Hello" number="42"></my-cmp> ``` 请注意,设置为“反射”(true)的属性将呈现为属性,而未设置为“反射”的属性则不会。 虽然没有设置为“反射”的属性(如“值”)没有呈现为属性,但这并不意味着它不存在——值属性仍然包含生命的意义。。 ``` const cmp = document.querySelector('my-cmp'); console.log(cmp.value); // it prints 'The meaning of life...' ``` ##### Prop default values and validation prop默认值及校验 使用 @Watch() 来校验prop: ``` import { Prop, Watch } from '@stencil/core'; ... export class TodoList { @Prop() name: string = 'Stencil'; @Watch('name') validateName(newValue: string, oldValue: string) { const isBlank = typeof newValue == null; const has2chars = typeof newValue === 'string' && newValue.length >= 2; if (isBlank) { throw new Error('name: required') }; if (!has2chars) { throw new Error('name: has2chars') }; } } ```
Markdown
UTF-8
1,027
2.96875
3
[]
no_license
# Project Overview This is a web application to demonstrate accessibility, service workers and responsive design and is part of the [Udacity front end web developer nanodegree course][1]. ## Running the application 1. Ensure you have [node and npm][2] installed, and execute the below command to install [live-server][3]: `npm install -g live-server` 2. Clone this project and navigate to the root of the project directory and execute this command: `live-server` 3. You will get a message like this from the command: ``` >live-server Serving "C:\Data\Web Development\mws-restaurant-stage-1" at http://127.0.0.1:8080 Ready for changes ``` 4. The path and URL would be different based on how you chose to install and run live-server, and where you cloned your project to. Use the URL provided in the message to access the website from a web browser. [1]: https://eu.udacity.com/course/front-end-web-developer-nanodegree--nd001 [2]: https://nodejs.org/en/download/ [3]: https://www.npmjs.com/package/live-server
C
UTF-8
12,743
2.75
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <errno.h> #include <llvm-c/Core.h> #include <llvm-c/TargetMachine.h> #include <llvm-c/Analysis.h> fn read_file(path: *const char) -> *char: var file = fopen(path, "rb") if !file: printf("unable to open '%s': %s\n", path, strerror(errno)) return NULL fseek(file, 0, SEEK_END) var size = ftell(file) fseek(file, 0, SEEK_SET) var text = (char*)malloc(size + 1) assert(text) assert(fread(text, size, 1, file) == 1) text[size] = 0 fclose(file) return text struct string_intern { index: *int; index_len: int; index_cap: int; big_string: *char; big_string_len: int; big_string_cap: int; }; fn intern_string(s: *const char, n: int, intern: *struct string_intern) -> int: for var i = 0; i < intern.index_len; i++: var j = intern.index[i] var t = &intern.big_string[j] if strlen(t) != n: continue if memcmp(t, s, n) != 0: continue return j var j = intern.big_string_len if j + n + 1 > intern.big_string_cap: intern.big_string_cap += 4096 intern.big_string = realloc(intern.big_string, intern.big_string_cap) memcpy(&intern.big_string[j], s, n) intern.big_string[j + n] = 0 intern.big_string_len = j + n + 1 if intern.index_len >= intern.index_cap: intern.index_cap += 32 intern.index = realloc(intern.index, intern.index_cap * sizeof(int)) intern.index[intern.index_len] = j intern.index_len += 1 return j fn get_string(j: int, intern: *struct string_intern) -> *const char: return &intern.big_string[j] enum token { token_fn, token_var, token_import, token_i8, token_i32, token_num_keywords, token_integer_literal, token_string_literal, token_identifier, token_lparen, token_rparen, token_lbrace, token_rbrace, token_lbracket, token_rbracket, token_colon, token_comma, token_semicolon, token_equals, token_star, token_plus, token_minus, token_arrow, token_dot, token_ellipsis, token_space, token_eol, token_eof, token_error, }; fn token2string(t: enum token) -> *const char: switch t: case token_fn: return "fn" case token_var: return "var" case token_import: return "import" case token_i8: return "i8" case token_i32: return "i32" case token_integer_literal: return "integer literal" case token_string_literal: return "string literal" case token_identifier: return "identifier" case token_lparen: return "(" case token_rparen: return ")" case token_lbrace: return "{" case token_rbrace: return "}" case token_lbracket: return "[" case token_rbracket: return "]" case token_colon: return ":" case token_comma: return "," case token_semicolon: return ";" case token_equals: return "=" case token_star: return "*" case token_plus: return "+" case token_minus: return "-" case token_arrow: return "->" case token_dot: return "." case token_ellipsis: return "..." case token_space: return "' '" case token_eol: return "'\n'" case token_eof: return "'\\0'" default: return "undefined" fn char2token(c: char) -> enum token: switch c: case 'a'...'z': case 'A'...'Z': case '_': return token_identifier case '0'...'9': return token_integer_literal case '"': return token_string_literal case '(': return token_lparen case ')': return token_rparen case '{': return token_lbrace case '}': return token_rbrace case '[': return token_lbracket case ']': return token_rbracket case ':': return token_colon case ',': return token_comma case ';': return token_semicolon case '=': return token_equals case '*': return token_star case '+': return token_plus case '-': return token_minus case '.': return token_dot case ' ': return token_space case '\n': return token_eol case '\0': return token_eof default: return token_error enum type_kind { type_void, type_i8, type_i32, }; struct type { kind: enum type_kind; }; struct param { name: int; type: *struct type; }; struct function_type { return_type: *struct type; params: *struct param; num_params: int; }; struct function { name: int; type: struct function_type; }; struct translation_unit { strings: struct string_intern; functions: *struct function; keywords: [token_num_keywords]int; }; struct parser { path: *const char; text: *const char; unit: *struct translation_unit; token: enum token; line_no: int; start: int; end: int; string: int; indent: int; prev_indent: int; }; var RED = "\x1b[0;31m"; var NORMAL = "\x1b[0m"; fn print_parse_error(p: *struct parser, msg: *const char) -> void: var line_start = p.start for ; line_start != 0 && p.text[line_start - 1] != '\n'; line_start -= 1: continue var line_end = p.end for ; p.text[line_end] != '\0' && p.text[line_end] != '\n'; line_end += 1: continue var line_offset = p.start - line_start printf("%s:%d:%d: %serror:%s %s\n", p.path, p.line_no, line_offset, RED, NORMAL, msg) printf(" %4d | %.*s\n", p.line_no, line_end - line_start, &p.text[line_start]) printf(" | "); for var i = line_start; i < p.start; i++: if p.text[i] == '\t': printf("\t") continue printf(" ") printf("%s", RED) for var i = p.start; i < p.end; i++: printf("^") printf("%s\n", NORMAL) fn bump_identifier(p: *struct parser) -> enum token: while 1: switch p.text[p.end]: case 'a'...'z': case 'A'...'Z': case '0'...'9': case '_': p.end += 1 continue break var s = &p.text[p.start] var n = p.end - p.start p.string = intern_string(s, n, &p.unit.strings) for var i = 0; i < token_num_keywords; i++: if p.unit.keywords[i] == p.string: return i return token_identifier fn bump_integer_literal(p: *struct parser) -> void: while 1: switch p.text[p.end]: case '0'...'9': p.end += 1 continue break var s = &p.text[p.start] var n = p.end - p.start p.string = intern_string(s, n, &p.unit.strings) fn bump_string_literal(p: *struct parser) -> void: p.end += 1 var s: [256]char var n = 0 while 1: var c = p.text[p.end] if c == '\0': print_parse_error(p, "unterminated string literal") exit(1) if c == '"': p.end += 1 break if c == '\\': p.end += 1 var d = p.text[p.end] switch d: case '\0': print_parse_error(p, "unterminated string literal") exit(1) case '"': c = '"' break case 'n': c = '\n' break case 't': c = '\t' break case 'r': c = '\r' break case '0': c = '\0' break default: print_parse_error(p, "invalid escape sequence"); exit(1) s[n] = c n += 1 p.end += 1 p.string = intern_string(s, n, &p.unit.strings) fn bump(p: *struct parser) -> void: while 1: p.start = p.end if p.indent == -1: while p.text[p.end] == ' ': p.end += 1 p.indent = (p.end - p.start) / 4 if p.prev_indent < p.indent: p.prev_indent += 1 p.token = token_lbrace break if p.indent < p.prev_indent: p.prev_indent -= 1 p.token = token_rbrace break p.start = p.end p.string = 0 var prev = p.token var next = char2token(p.text[p.end]) switch next: case token_identifier: next = bump_identifier(p) break case token_integer_literal: bump_integer_literal(p) break case token_string_literal: bump_string_literal(p) break case token_lparen: case token_rparen: case token_lbrace: case token_rbrace: case token_lbracket: case token_rbracket: case token_colon: case token_comma: case token_semicolon: case token_equals: case token_star: case token_plus: case token_eof: p.end += 1 break case token_space: p.end += 1 continue case token_minus: if p.text[p.end + 1] == '>': next = token_arrow p.end += 2 break p.end += 1 break case token_dot: if p.text[p.end + 1] == '.' && p.text[p.end + 2] == '.': next = token_ellipsis p.end += 3 break p.end += 1 break case token_eol: p.indent = -1 while p.text[p.end] == '\n': p.line_no += 1 p.end += 1 switch prev: case token_rparen: case token_i32: case token_identifier: case token_integer_literal: next = token_semicolon break default: continue break default: p.end += 1 print_parse_error(p, "unexpected character") exit(1) p.token = next break fn parse(p: *struct parser, t: enum token) -> void: if p.token == t: bump(p) return var msg: [64]char var x = token2string(t) var y = token2string(p.token) sprintf(msg, "expected %s, got %s", x, y) print_parse_error(p, msg) exit(1) fn parse_type(p: *struct parser) -> *struct type: return NULL fn parse_function_type(p: *struct parser) -> struct function_type: var f = (struct function_type){} parse(p, token_lparen) parse(p, token_rparen) parse(p, token_arrow) f.return_type = parse_type(p) return f fn parse_function(p: *struct parser) -> void: parse(p, token_fn) var name = p.string parse(p, token_identifier) var type = parse_function_type(p) return fn parse_file(path: *const char, text: *const char, unit: *struct translation_unit) -> void: var p = (struct parser){} p.path = path p.text = text p.unit = unit p.token = token_eof p.line_no = 1 bump(&p) while p.token != token_eof: parse_function(&p) fn main(argc: int, argv: **char) -> int: for var i = 1; i < argc; i++: if strcmp(argv[i], "-h") == 0: printf("usage: pdc [-h] file...\n") return 0 var unit = (struct translation_unit){} for var i = 0; i < token_num_keywords; i++: var s = token2string(i) unit.keywords[i] = intern_string(s, strlen(s), &unit.strings) for var i = 1; i < argc; i++: var path = argv[i] var text = read_file(path) if !text: return 1 parse_file(path, text, &unit) free(text) return 0
C#
UTF-8
3,223
2.640625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Novacode; namespace PSWord { using System.Drawing; using System.Management.Automation; [Cmdlet(VerbsCommon.New, "WordFormatting")] class NewWordFormatting : PSCmdlet { [Parameter] public CapsStyle CapsStyle { get; set; } [Parameter] public SwitchParameter Bold { get; set; } [Parameter] public SwitchParameter Italic { get; set; } [Parameter] public FontFamily FontFamily { get; set; } [Parameter] public KnownColor FontColor { get; set; } [Parameter] public SwitchParameter Hidden { get; set; } [Parameter] public Highlight Highlight { get; set; } [Parameter] public Misc Misc { get; set; } [Parameter(Mandatory = true)] public int? Size { get; set; } [Parameter] public double Spacing { get; set; } [Parameter] public StrikeThrough StrikeThrough { get; set; } [Parameter] public UnderlineStyle UnderlineStyle { get; set; } [Parameter] public KnownColor UnderlineColor { get; set; } private Formatting formatting { get; set; } protected override void BeginProcessing() { this.formatting = new Formatting { Size = this.Size }; } protected override void ProcessRecord() { this.formatting.CapsStyle = this.CapsStyle; if (this.Bold.IsPresent) { this.formatting.Bold = true; } if (this.Italic.IsPresent) { this.formatting.Italic = true; } this.formatting.FontFamily = this.FontFamily; this.formatting.FontColor = Color.FromKnownColor(this.FontColor); if (this.Hidden.IsPresent) { this.formatting.Hidden = true; } if (!string.IsNullOrEmpty(this.Highlight.ToString())) { this.formatting.Highlight = this.Highlight; } if (!String.IsNullOrEmpty(this.Misc.ToString())) { this.formatting.Misc = this.Misc; } if (!String.IsNullOrEmpty(this.Spacing.ToString())) { this.formatting.Spacing = this.Spacing; } if (!String.IsNullOrEmpty(this.StrikeThrough.ToString())) { this.formatting.StrikeThrough = this.StrikeThrough; } if (!String.IsNullOrEmpty(this.UnderlineStyle.ToString())) { this.formatting.UnderlineStyle = this.UnderlineStyle; } if (!String.IsNullOrEmpty(this.UnderlineColor.ToString())) { this.formatting.UnderlineColor = Color.FromKnownColor(this.UnderlineColor); } this.WriteObject(this.formatting); } } }
Python
UTF-8
8,090
2.515625
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- ################################################################################ # # Copyright (c) 2017 SenseDeal AI, Inc. All Rights Reserved # ################################################################################ """ Author: Tony Qin (tony@sensedeal.ai) Date:2017/8/1 """ import os import sqlite3 import logging import subprocess from datetime import datetime, date from urllib.parse import urlparse from safe_sqlite import SafeSqlite def get_storage_key_from_url(url): url_obj = urlparse(url) domain = url_obj.hostname key = '' for i in reversed(domain.split('.')): if i != 'www': if key == '': key = i else: key = key + '.' + i return (key + url_obj.path).replace('/', '__') class LinkBaseNotSafe(object): """ Crawler data caching per relative URL and domain. Non-thread-safe implementation """ def __init__(self, crawler_name='Crawler', db_name='linkbase.db', db_dir='.'): self.crawler_name = crawler_name self.db_name = db_name self.db_dir = db_dir if not os.path.exists(self.db_dir): try: os.mkdir(self.db_dir) except OSError as e: logging.warning("%s mkdir %s failed: %s, use current dir by default", self.crawler_name, self.db_dir, e) self.conn = sqlite3.connect(os.sep.join([db_dir, db_name])) c = self.conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS sites (key text not null, url text not null, content text, in_time timestamp, crawled_time timestamp, weight real, unique(key, url))''') self.conn.commit() self.cursor = self.conn.cursor() def set(self, url): """ store the content for a given domain and relative url """ try: self.cursor.execute( "INSERT INTO sites(key, url, in_time, crawled_time, weight) VALUES (?,?,?,?,?)", (get_storage_key_from_url(url), url, datetime.now(), datetime.now(), 0)) self.conn.commit() except Exception as err: logging.warning('insert database fail, %s', err) def get(self, key): """ return the content for a given domain and relative url """ self.cursor.execute("SELECT url FROM sites WHERE key=?", (key,)) row = self.cursor.fetchone() if row: return row[0] def get_urls(self, domain): """ return all the URLS within a domain """ self.cursor.execute("SELECT url FROM sites WHERE domain=?", (domain,)) return [row[0] for row in self.cursor.fetchall()] class LinkBase(object): """ Crawler data caching per relative URL and domain. Thread-safe implementation """ def __init__(self, crawler_name='Crawler', db_name='linkbase.db', db_dir='.'): self.crawler_name = crawler_name self.db_name = db_name self.db_dir = db_dir if not os.path.exists(self.db_dir): try: os.mkdir(self.db_dir) except OSError as e: logging.warning("%s mkdir %s failed: %s, use current dir by default", self.crawler_name, self.db_dir, e) self.safe_sqlite = SafeSqlite(os.sep.join([db_dir, db_name])) self.safe_sqlite.execute('''CREATE TABLE IF NOT EXISTS sites (key text not null, url text not null, content text, in_time timestamp, crawled_time timestamp, weight real, unique(key, url))''') def __del__(self): self.safe_sqlite.close() def set(self, url): """ store the content for a given domain and relative url """ try: self.safe_sqlite.execute( "INSERT INTO sites(key, url, in_time, crawled_time, weight) VALUES (?,?,?,?,?)", (get_storage_key_from_url(url), url, datetime.now(), datetime.now(), 0)) except Exception as err: logging.warning('insert database fail, %s', err) def get(self, key): """ return the content for a given domain and relative url """ row = self.safe_sqlite.execute("SELECT url FROM sites WHERE key=?", (key,)) if row: return row[0] def get_urls(self, domain): """ return all the URLS within a domain """ self.cursor.execute("SELECT url FROM sites WHERE domain=?", (domain,)) return [row[0] for row in self.cursor.fetchall()] class PageBase(object): """ Crawler webpage caching per URL and domain """ def __init__(self, crawler_name='Crawler', db_name='pagebase.db', db_dir='.'): self.crawler_name = crawler_name self.db_name = db_name self.db_dir = db_dir if not os.path.exists(self.db_dir): try: os.mkdir(self.db_dir) except OSError as e: logging.warning("%s mkdir %s failed: %s, use current dir by default", self.crawler_name, self.db_dir, e) def save_to_disk(self, url, html, path=None): if path == None: path = self.db_dir # out_file_name = os.sep.join([path, url.replace('://', '_').replace('/', '_')]) out_file_name = os.sep.join([path, get_storage_key_from_url(url)]) logging.info('%s, saving %s,to: %s', self.crawler_name, url, out_file_name) try: with open(out_file_name, 'w') as f: f.write(html) except Exception as e: logging.error("save html: %s ,to file error %s ", html, e) def save_to_global(self, url, html): """ save to global distributed storage """ return class PdfBase(object): """ Crawler webpage caching per URL and domain """ def __init__(self, crawler_name='Crawler', db_name='pdfbase.db', db_dir='.'): self.crawler_name = crawler_name self.db_name = db_name self.db_dir = db_dir if not os.path.exists(self.db_dir): try: os.mkdir(self.db_dir) except OSError as e: logging.warning("%s mkdir %s failed: %s, use current dir by default", self.crawler_name, self.db_dir, e) def save_to_disk(self, url, path=None): if path == None: path = self.db_dir out_file_name = os.sep.join([path, get_storage_key_from_url(url)]) logging.info('%s, saving %s,to: %s', self.crawler_name, url, out_file_name) try: cmd = 'wget %s -O %s' %(url, out_file_name) print (cmd) out_bytes = subprocess.check_output(cmd, shell=True) except subprocess.CalledProcessError as e: logging.error("save pdf: %s ,to file error %s ", url, e) print (out_bytes.decode('utf-8')) def save_to_global(self, url, pdf): """ save to global distributed storage """ return class Storage(object): """ the level for storage interface, including links and webpage """ def __init__(self, crawler_name='Crawler', conf=None): self.conf = conf self.crawler_name = crawler_name self.linkbase = LinkBase(crawler_name, conf.linkbase_db_name, conf.linkbase_db_dir) self.pagebase = PageBase(crawler_name, conf.pagebase_db_name, conf.pagebase_db_dir) self.pdfbase = PdfBase(crawler_name, conf.pdfbase_db_name, conf.pdfbase_db_dir) if __name__ == '__main__': url = 'http://www.neeq.com.cn/uploads/1/file/public/201707/20170731184707_wf92rrp3uj.pdf' # pdfbase = PdfBase('1', '2', './test_out') # pdfbase.save_to_disk(url) linkbase = LinkBase() linkbase.set(url) print (linkbase.get((get_storage_key_from_url(url))))
Swift
UTF-8
749
2.9375
3
[ "MIT" ]
permissive
import Foundation struct BasketAddResponse: Decodable, Equatable { let message: String } enum BasketAddError: Error, Equatable { case notInStock, noProductWithProductId, unknown case authorizedError(AuthorizedServiceError) } typealias BasketAddResult = Result<Void, BasketAddError> typealias BasketAddCompletion = (BasketAddResult) -> () struct BasketGetResponse: Decodable, Equatable { let id: Int let productId: Int } typealias BasketGetResult = Result<[BasketGetResponse], AuthorizedServiceError> typealias BasketGetCompletion = (BasketGetResult) -> () protocol BasketServiceInterface { func add(productId: Int, completion:@escaping BasketAddCompletion) func getBasket(completion: @escaping BasketGetCompletion) }
C#
UTF-8
4,559
3.078125
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MazeGenerator : MonoBehaviour { // display private variables in inspector (materials for the maze) [SerializeField] private Material mazeFloor; [SerializeField] private Material mazeWall; [SerializeField] private GameObject mazeStart; [SerializeField] private GameObject mazeEnd; private MazeData dataGenerator; private MazeMesh meshGenerator; // mazeData is a 2D array, 0 or 1, to represent open(floor) or blocked(wall) public int[,] mazeData { get; private set; // Maze data can't be modified from outside this class } // properties to store sizes and positions public float hallWidth { get; private set; } public float hallHeight { get; private set; } public int startRow { get; private set; } public int startCol { get; private set; } public int endRow { get; private set; } public int endCol { get; private set; } private void Awake() { // instantiate it in a new variable in Awake dataGenerator = new MazeData(); meshGenerator = new MazeMesh(); } public void DisplayMaze() { // creates a new game objects which will build the maze GameObject mazeObject = new GameObject(); mazeObject.transform.position = Vector3.zero; // names the object and gives it a tag mazeObject.name = "Procedural Maze"; mazeObject.tag = "Generated"; // adds a mesh filter to the game object. MeshFilter meshFilter = mazeObject.AddComponent<MeshFilter>(); meshFilter.mesh = meshGenerator.Data(mazeData); // adds a mesh collider to the game object. MeshCollider meshCollider = mazeObject.AddComponent<MeshCollider>(); meshCollider.sharedMesh = meshFilter.mesh; // adds a mesh renderer to the game object. MeshRenderer meshRenderer = mazeObject.AddComponent<MeshRenderer>(); // assigns the array of materials with the floor and wall material meshRenderer.materials = new Material[2] { mazeFloor, mazeWall }; } public void GenerateNewMaze (int sizeRows, int sizeCols) { // checks to see if the rows/columns are divisible by 2, if (sizeRows % 2 == 0 && sizeCols % 2 == 0) { // because the generated maze will be surrounded by walls Debug.LogError("Odd Numbers work better for maze size"); } DestroyMaze(); // assigns the mazeData array with the dimensions array mazeData = dataGenerator.Dimensions(sizeRows, sizeCols); FindStartPosition(); FindFinishPosition(); hallWidth = meshGenerator.width; hallHeight = meshGenerator.height; // Places the start flag at the start of the maze. Instantiate(mazeStart, new Vector3(startCol * hallWidth, 0.0f, startRow * hallWidth), Quaternion.identity); // Places the finish flag at the end of the maze. Instantiate(mazeEnd, new Vector3(endCol * hallWidth, 0.0f, endRow * hallWidth), Quaternion.identity); DisplayMaze(); } // deletes an existing maze public void DestroyMaze() { // finds all objects with the "Generated" tag GameObject[] maze = GameObject.FindGameObjectsWithTag("Generated"); // destroys all the "Generated" objects foreach (GameObject mazeObject in maze) { Destroy(mazeObject); } Destroy(GameObject.FindGameObjectWithTag("End")); } private void FindStartPosition() { // creates an array that stores the array in mazeData int[,] maze = mazeData; // finds the maximum row and column values int rowMax = maze.GetUpperBound(0); int colMax = maze.GetUpperBound(1); // starts at (0,0), iterates through until it finds a space. for (int i = 0; i <= rowMax; i++) { for (int j = 0; j <= colMax; j++) { // checks that there is no wall if (maze[i, j] == 0) { // stores coords as the maze start position. startRow = i; startCol = j; return; } } } } private void FindFinishPosition() { // creates an array that stores the array in mazeData int[,] maze = mazeData; // finds the maximum row and column values int rowMax = maze.GetUpperBound(0); int colMax = maze.GetUpperBound(1); // starts with the max values, iterates in reverse until it finds a space. for (int i = rowMax; i >= 0; i--) { for (int j = colMax; j >= 0; j--) { if (maze[i, j] == 0) { // stores coords as the maze end position. endRow = i; endCol = j; return; } } } } }
JavaScript
UTF-8
3,147
2.59375
3
[]
no_license
$(document).ready(function() { let jpgBtn = new Btn("jpg"); let pngBtn = new Btn("png"); jpgBtn.disable(); pngBtn.disable(); $('#file-btn').on('change', function(e) { const file = e.target.files[0] if (file.length === 0) { alert('出错了, 文件不能为空') return } let reader = new FileReader(); reader.readAsArrayBuffer(file); reader.onload = function(e) { let typedarray = new Uint8Array(e.target.result); PDFJS.getDocument(typedarray).then(function(pdf) { if (pdf) { $('#main_btn').text(file.name).css('font-size', '13px'); jpgBtn.clickable(function() { conversion('jpg', pdf) }); pngBtn.clickable(function() { conversion('png', pdf) }); } }); }; }) function conversion(type, pdf) { let container = document.getElementById('container'), pdfDoc = pdf, scale = 1, numPages = pdfDoc.numPages; jpgBtn.ongoing(); pngBtn.ongoing(); let readQueue = []; for (let i = 0; i < numPages; i++) { readQueue.push(pdfDoc.getPage(i + 1)); } Promise.all(readQueue).then((arr) => { let renderQueue = arr.map((item, idx) => { let canvas = document.createElement('canvas'); let ctx = canvas.getContext('2d'); let viewport = item.getViewport(scale) container.append(canvas); canvas.id = idx; canvas.height = viewport.height; canvas.width = viewport.width; return item.render({ canvasContext: ctx, viewport }).promise; }) console.log('renderQueue', renderQueue) let allPagesNum = renderQueue.length let finishPagesNum = 0 renderQueue.forEach(item => { item.then(res => { finishPagesNum += 1 $('#main_btn').text(parseInt(finishPagesNum * 100 / allPagesNum) + '%').css({ 'font-size': '20px', 'padding': '0 4px' }) finishPagesNum >= allPagesNum && download(type) }).catch(err => { finishPagesNum += 1 $('#main_btn').text(parseInt(finishPagesNum * 100 / allPagesNum) + '%').css({ 'font-size': '20px', 'padding': '0 4px' }) finishPagesNum >= allPagesNum && download(type) }) }) }) } }); function download(type) { let typeStr = type == png ? "image/png" : 'image/jpg' console.log(type, typeStr) let zip = new JSZip(); let images = zip.folder("images"); $('#container canvas').each(function(idx) { images.file("pic-"+idx+"." + type, base64toBlob($(this)[0].toDataURL(typeStr, 0.6)), { base64: true }); }) zip.generateAsync({ type: "blob" }).then(function(content) { saveAs(content, "pdftoimages.zip"); }); } function base64toBlob(dataurl){ var arr = dataurl.split(','); var mime = arr[0].match(/:(.*?);/)[1]; var bstr = atob(arr[1]); var n = bstr.length; var u8arr = new Uint8Array(n); while(n--){ u8arr[n] = bstr.charCodeAt(n); } return new Blob([u8arr], {type:mime}); }
Markdown
UTF-8
3,076
3.125
3
[]
no_license
> 在CTF各大类别的题型中,都会有爆破的需求,那么如何优雅的爆破一个32位整数呢?这里分享一个多线程爆破32位整数的一个方法。 --- # 1.脚本与使用须知 - 正常情况下,修改check函数就可以使用。 - thread_num为线程数,默认为cpu核心数,建议不修改,线程远超cpu核心数,多线程反而会变慢。一定要为2的整数次幂。 - print_threshold 为输出枚举中间状态的阈值,凡是遍历到能整除该数的 都将打印出信息,相当于给爆破过程一些反馈。 - bit_num 数字的比特位,默认为32位整数。 - check函数是校验num的正确性的,此处一定要修改。 - 脚本运行结束后,结果会在enumeration_result.txt中,也可以在控制台搜索reult。 - 这种类型的脚本一般不做面向对象封装。 ```python from threading import Thread from multiprocessing import cpu_count import os import math # 线程数 一定要为2的整数次幂 thread_num = cpu_count() # 输出枚举中间状态的阈值 凡是遍历到能整除该数的 都将打印出信息 print_threshold = 2 ** 19 # 数字的比特位 bit_num = 32 # 此处需要重写 校验num是否为所需要的 该处校验的复杂度不能太高 def checkNum(num): return True def enumeration(num, pid): # 输出线程启动信息 print("[Process%d]: start from %d" % (pid, num)) # 单个线程的枚举 while num < 2**(bit_num - math.log2(thread_num) - 1)*(pid + 1): # 校验num if checkNum(num): print("[Process%d]: The result is num = %d" % (pid, num)) f = open('enumeration_result.txt', 'w') # 将答案写入文件 f.write("[Process%d]: The result is num = %d" % (pid, num)) f.close() # 退出所有线程 os._exit(0) num+=1 # 输出中间时段的信息 if num % print_threshold == 0: print('[Process%d]: now is %d' % (pid, num)) # 输出线程退出信息 print('[Process%d]: exited!' % pid) for i in range(0, thread_num): t = Thread(target=enumeration, args=(i * (2 ** (bit_num - math.log2(thread_num) - 1)), i)) t.start() ``` # 2.脚本实现细节 ## 2.1 脚本整体思路 每个线程其实主要是在爆一个高位,例如采用8个线程,那么实际上第1个线程,爆破的是`0*2^28---1*2^28`,第二个线程,爆破的是`1*2^28---2*2^28`,依此类推。 ## 2.2 线程数选择 线程数最好等于cpu核心数,低了或者高了都会影响效率。 ## 2.3 爆破过程反馈 如果爆破的时候控制台一点反馈都没有,就不知道现在的速度如何,进度如何。如果反馈太多,那么眼花缭乱的找不到有用信息。所以专门设置了一个反馈阈值,每到一个指定数字节点会输出一段信息。 ## 2.4 结果反馈 只要有一个进程找到了需要的数,立刻退出所有的线程。将结果打印,并存储到文件(方便查看结果) --- >**<font size=5>ATFWUS 2021-08-19**
C
UTF-8
1,619
3.59375
4
[]
no_license
#include "complex.h" #include <math.h> #include <stdio.h> //Implementation of complex_t functions void print_greeting(){ printf("hello\n"); } complex_t c_zero(){ return c_make(0.0, 0.0); } complex_t c_make(double r, double i){ complex_t result; result.r = sqrt(r*r + i*i); result.theta = atan2(i , r); return result; } complex_t c_add(complex_t z1, complex_t z2){ complex_t result; double i; double r; r = real(z1) + real(z2); i = imag(z1) + imag(z2); result = c_make(r, i); return result; } complex_t c_sub(complex_t z1, complex_t z2){ complex_t result; double i; double r; r = real(z1) - real(z2); i = imag(z1) - imag(z2); result = c_make(r, i); return result; } complex_t c_mul(complex_t z1, complex_t z2){ complex_t result; result.r = z1.r * z2.r; result.theta = z1.theta + z2.theta; return result; } complex_t c_div(complex_t z1, complex_t z2){ complex_t result; result.r = z1.r / z2.r; result.theta = z1.theta - z2.theta; return result; } complex_t c_pow(complex_t z1, double p){ complex_t result; result.r = pow(z1.r, p); result.theta = z1.theta * p; return result; } void c_print(complex_t z){ printf("%g+%gi", real(z), imag(z)); } void c2a(complex_t z, char str[]){ sprintf(str, "%g + %gi", real(z), imag(z)); } double real(complex_t z){ return z.r * cos(z.theta); } double imag(complex_t z){ return z.r * sin(z.theta); }
JavaScript
UTF-8
424
3.15625
3
[]
no_license
function staircase(n){ for(var i=0;i<n;i++){ for(var q=0;q<=i;q++){ process.stdout.write("#") } console.log('\n') } } function pyramid(n){ for(var i=0;i<=n;i++){ for(var k=i;k<n;k++){ process.stdout.write(" ") } for(var j=0;j<(2*i-1);j++){ process.stdout.write("#") } console.log('\n') } } pyramid(4)
Markdown
UTF-8
911
2.609375
3
[]
no_license
# MEMORY CORRUPTION EXPLOITS This repository contains exploits written while going through [opensecuritytraining's] course on [Introduction_To_Software_Exploits]. The course instructor introduces the memory corruption vulnerabilities and concepts in step-by-step manner. An awesome course that adding a lot to knowledge. The vulnerable binaries can be found [here]. Exploits - * [exploit_basic_vuln.py] * [exploit_mystery.py] * [exploit_seh_overflow.py] * [exploit_seh_harden.py] <br> A very big thanks to Corey Kallenberg @CoreyKal [opensecuritytraining's]: http://www.opensecuritytraining.info/ [Introduction_To_Software_Exploits]: http://www.opensecuritytraining.info/Exploits2.html [here]: ./exploits2classmaterial [exploit_basic_vuln.py]: ./exploit_basic_vuln.py [exploit_mystery.py]: ./exploit_mystery.py [exploit_seh_overflow.py]: ./exploit_seh_overflow.py [exploit_seh_harden.py]: ./exploit_seh_harden.py
Markdown
UTF-8
3,483
2.96875
3
[]
no_license
title=Jakarta EE application multi module gradle template date=2019-08-08 type=post tags=jakartaee, gradle status=published ~~~~~~ In this post i will share simple and useful **gradle** template to organize multi module Jakarta EE application. We will implement typical one which consists from REST controller (**module1**) and some main logic (**module2**). Big picture of our application architecture is: ![EE multi module application](/img/2019-08-ee-multimodule-template-arch.png) So, lets do initialization of project with next gradle template: `settings.gradle:` ```java rootProject.name = 'ee-application-multi-module-gradle-template' include 'module1' include 'module2:module2-api', 'module2:module2-core' ``` `root build.gradle:` ```java defaultTasks 'clean', 'build' subprojects { ext.libraryVersions = [ javaee : '8.0', ] defaultTasks 'clean', 'build' repositories { jcenter() } } ``` Above, we described initial application structure, where **module1** is flat sub project for our controller and **module2** is our main logic which consists from `API` and `Core` sub projects. As controller will use main logic API and we decided to separate application to modules (that means no big enterprise archive) - our sub projects should be simple enough: `module1 build.gradle:` ```java apply plugin: 'war' dependencies { compile project(':module2:module2-api') providedCompile "javax:javaee-api:${libraryVersions.javaee}" } ``` `module2:module2-api:` ```java apply plugin: 'java' dependencies { } ``` `module2:module2-core:` ```java apply plugin: 'war' dependencies { compile project(':module2:module2-api') providedCompile "javax:javaee-api:${libraryVersions.javaee}" } ``` Actually, that's it! Now we can implement our controller like: ```java @Path("/") @Stateless @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public class TestEndpoint { @EJB(lookup = TestService.TEST_SERVICE_JNDI) TestService testService; @GET @Path("/test") public Response test() { SomethingDto something = testService.doSomething(); return Response.ok().entity(something.getMessage()).build(); } ``` In turn, main logic `API` contents from `Interface` and `DTO`: `TestService.java:` ```java public interface TestService { String TEST_SERVICE_NAME = "test-service"; String TEST_SERVICE_JNDI ="java:global/module2-core/" + TEST_SERVICE_NAME; SomethingDto doSomething(); } ``` `SomethingDto.java:` ```java public class SomethingDto implements Serializable{ ... } ``` In the end, main logic `Core` contents from the logic that implements API: `TestServiceImpl.java` ```java @Remote(TestService.class) @Stateless(name = TestService.TEST_SERVICE_NAME) public class TestServiceImpl implements TestService { @PersistenceContext EntityManager entityManager; @Override public SomethingDto doSomething() { TestEntity entity = entityManager.find(TestEntity.class, Long.MAX_VALUE); return new SomethingDto("Hello Jakarta EE world!"); } } ``` Described Jakarta EE application architecture allows us enjoy all power of EE with absolutely transparent inter module interactions and, the same time, stay close to micro service design - as we have no limits with using one container for all modules. Source code of this demo available on [GitHub](https://github.com/kostenkoserg/ee-application-multi-module-gradle-template)
Ruby
UTF-8
5,895
2.90625
3
[]
no_license
require 'java' require 'yaml' OTTO_VERSION = "0.6.0" # distance between fields at minimum zoom, # and between animals or trees at maximum zoom. STEP_X = 25 STEP_Y = 12 ROBOT = java.awt.Robot.new class Field attr_reader :plots def initialize(x, y, rows, columns, color="none") @plots = generate_plot_list(x, y, rows, columns) @chicken_color = color end def generate_plot_list(x, y, rows, columns) # x and y denote the upper left corner of a rectangle # start_* is the left end of the current row start_x = x start_y = y plots = Array.new row = 1 while row <= rows ix = start_x iy = start_y column = 1 while column <= columns plots << [ix, iy] ix += STEP_X iy -= STEP_Y column += 1 end # next column start_x += STEP_X start_y += STEP_Y row += 1 end # next row plots end # method end # class def caps_lock? tk = java.awt.Toolkit.getDefaultToolkit tk.getLockingKeyState(java.awt.event.KeyEvent::VK_CAPS_LOCK) end def pause? while caps_lock? make_noise("pause-extended") sleep 15 end end def sleep_for(secs, sound=false) make_noise(sound) sleep secs pause? end def make_noise(sound_key) return unless Settings["play-sounds"] # don't bother alien purple chicken sound_spec = Settings[sound_key] return if !sound_spec if sound_spec =~ /^say / # Macintosh only. TODO: enforce system sound_spec else sound_file = java.io.File.new("sounds/#{sound_spec}") sound_url = sound_file.toURI().toURL() #TODO: check for existance: sound_url.openConnection.getInputStream.close # raises exception if file not found. play() just ignores java.applet.Applet.newAudioClip(sound_url).play end end def click_at(plot) pause? ROBOT.mouseMove(plot[0],plot[1]) ROBOT.delay(100 + rand(20)) return if Settings["no-clicking"] ROBOT.mousePress(java.awt.event.InputEvent::BUTTON1_MASK) ROBOT.delay(50 + rand(10)) ROBOT.mouseRelease(java.awt.event.InputEvent::BUTTON1_MASK) ROBOT.delay(@click_delay + rand(100)) end def load_coop(pen) last_premium = pen.plots.last remove_primer = Settings["remove-primer-chicken"] pen.plots.each do | premium | if remove_primer && premium == last_premium # move off of coop to ?unselect it # coop menu doesn't activate if cursor left there after adding. ROBOT.mouseMove premium[0],premium[1] ROBOT.delay(100) remove_chicken( @remove_button[remove_primer], [last_premium[0] + STEP_X, last_premium[1] - STEP_Y], :primer ) end add_chicken(premium) end if Settings["collect-eggs-after-load"] sleep_for @after_coop_loaded, "coop-loaded" # move off coop to ?unselect it ROBOT.mouseMove @coop[0],@coop[1]-205 ROBOT.delay 100 click_at @coop click_at [@coop[0]+16,@coop[1]+10] # collect eggs end end def add_chicken(chicken) click_at chicken click_at [chicken[0]+16, chicken[1]+10] # chicken/move ROBOT.mouseMove(@coop[0],@coop[1]) click_at @coop end def remove_chicken(remove_button, landing, primer=false) click_at @coop if primer click_at [@coop[0]+16,@coop[1]+32] # Look Inside when Collect Eggs active else click_at [@coop[0]+16, @coop[1]+10] # Look Inside end ROBOT.delay(@after_look_inside + rand(25)) # wait for look inside click_at remove_button ROBOT.delay(100 + rand(25)) # a little extra for the remove click_at [landing[0]-11, landing[1]+27] # deposit the chick end def unload_coop(pen) colors = Settings["premium-colors"] removes = [] colors.each do |color, count| count.times {removes << @remove_button[color]} end pen.plots.each_with_index do |landing, index| remove_chicken(removes[index], landing) end end begin cmd = ARGV[0] if !%w{load_coop unload_coop load_unload}.include?(cmd) puts "FarmerOtto version #{OTTO_VERSION}" puts "usage:" puts " otto load_coop" puts " otto unload_coop" puts " otto load_unload" exit 2 end if !File.exists?("farm.yaml") puts "The farm definition file 'farm.yaml' cannot be found." exit 8 end Settings = YAML::load_file("farm.yaml") if !Settings["settings-customized"] puts "Please describe your farm in the file 'farm.yaml'," puts "then change 'settings-customized' to true (in farm.yaml)." exit 4 end @coop = Settings["coop"] # delays used elsewhere @click_delay = Settings["ms-after-click"] || 600 @after_look_inside = Settings["ms-after-look-inside"] || 350 @after_coop_loaded = Settings["secs-after-coop-loaded"] || 5 # delays used in main() startup_delay = Settings["secs-before-beginning"] || 10 between_load_unload = Settings["secs-between-load-unload"] || 10 after_unload = Settings["secs-after-unload"] || 15 rw = Settings["remove-white-chicken-button"] @remove_button = { "white", rw, "brown", [rw[0]+292, rw[1]], "black", [rw[0], rw[1]+190], "golden", [rw[0]+292, rw[1]+190] } premium_pen = Field.new(*Settings["premium-pen"]) sleep_for startup_delay, "startup-sound" if cmd == "load_coop" load_coop(premium_pen) elsif cmd == "unload_coop" unload_coop(premium_pen) elsif cmd == "load_unload" passes = ARGV[1] || 1 passes = passes.to_i last_pass = passes - 1 passes.times do |pass| load_coop(premium_pen) sleep_for between_load_unload, "collect-eggs" unload_coop(premium_pen) unless pass == last_pass sleep_for after_unload, "check-unload-progress" end end else # cmd is also validated at start puts "unknown command: #{cmd}" if cmd end make_noise("shutdown-sound") sleep 3 # allow time for shutdown sound rescue SystemExit => e # exit via guard clauses at start of program -- ok end
Java
UTF-8
349
3.28125
3
[]
no_license
package generics; import java.util.Iterator; import java.util.Vector; public class IteratorEx { public static void main(String[] args) { Vector<Integer> v = new Vector<Integer>(); v.add(5); v.add(15); v.add(52); v.add(512); Iterator<Integer> it = v.iterator(); while(it.hasNext()) { System.out.println(it.next()); } } }
Java
UTF-8
1,088
2.171875
2
[]
no_license
package ru.dmrval.kafkaconsumer.topologyConfig; import org.apache.kafka.streams.KeyValue; import org.apache.kafka.streams.kstream.Transformer; import org.apache.kafka.streams.kstream.TransformerSupplier; import org.apache.kafka.streams.processor.ProcessorContext; import ru.dmrval.kafkaconsumer.model.Address; import ru.dmrval.kafkaconsumer.model.BankAccount; import ru.dmrval.kafkaconsumer.model.BankAccountInfo; public class BankAccountTransformerSupplier implements TransformerSupplier<String, BankAccount, KeyValue<String, BankAccountInfo>> { @Override public Transformer<String, BankAccount, KeyValue<String, BankAccountInfo>> get() { return new Transformer<String, BankAccount, KeyValue<String, BankAccountInfo>>() { @Override public void init(ProcessorContext processorContext) {} @Override public KeyValue<String, BankAccountInfo> transform(String s, BankAccount bankAccount) { return KeyValue.pair(s, new BankAccountInfo(bankAccount, new Address("A", "A", "A"))); } @Override public void close() {} }; } }
C++
UTF-8
20,855
2.71875
3
[]
no_license
#include "MyGLImageViewer.h" MyGLImageViewer::MyGLImageViewer() { auxDepthBuffer = (float*) malloc(640 * 480 * sizeof(float)); depthBuffer = (unsigned char*) malloc(640 * 480 * 3 * sizeof(unsigned char)); } MyGLImageViewer::~MyGLImageViewer() { delete [] auxDepthBuffer; delete [] depthBuffer; } void MyGLImageViewer::load1DTexture(unsigned char* data, GLuint *texVBO, int index, int width) { glBindTexture(GL_TEXTURE_1D, texVBO[index]); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA, width, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); } void MyGLImageViewer::load2DTexture(unsigned char *data, GLuint *texVBO, int index, int width, int height) { glBindTexture(GL_TEXTURE_2D, texVBO[index]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); } void MyGLImageViewer::load2DNoiseTexture(GLuint *texVBO, int index, int width, int height) { unsigned char *noise = (unsigned char*)malloc(width * height * sizeof(unsigned char)); srand((unsigned)time(NULL)); for(int pixel = 0; pixel < (width * height); pixel++) { noise[pixel] = 255.f * rand()/(float)RAND_MAX; //noise[pixel] = rand() % 128; //printf("%f\n", noise[pixel]); //system("pause"); } glBindTexture(GL_TEXTURE_2D, texVBO[index]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE8, width, height, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, noise); delete [] noise; } void MyGLImageViewer::load2DTextureDepthComponent(unsigned char *data, GLuint *texVBO, int index, int width, int height) { glBindTexture(GL_TEXTURE_2D, texVBO[index]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, width, height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, data); } void MyGLImageViewer::load2DDepthBufferTexture(GLuint *texVBO, int index, int x, int y, int width, int height) { //glReadPixels(x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, depthBuffer); glReadPixels(x, y, width, height, GL_DEPTH_COMPONENT, GL_FLOAT, auxDepthBuffer); /* int xp, yp, inversePixel; for(int pixel = 0; pixel < (640 * 480); pixel++) { xp = pixel % 640; yp = pixel / 640; inversePixel = (480 - yp) * 640 + xp; auxDepthBuffer[inversePixel] = (auxDepthBuffer[inversePixel] - 0.999) * 1000; if(auxDepthBuffer[inversePixel] != 0 && auxDepthBuffer[inversePixel] != 1) printf("%f\n", auxDepthBuffer[inversePixel]); //depthBuffer[pixel * 3 + 0] = 255 - auxDepthBuffer[inversePixel] * 255; //depthBuffer[pixel * 3 + 1] = 255 - auxDepthBuffer[inversePixel] * 255; //depthBuffer[pixel * 3 + 2] = 255 - auxDepthBuffer[inversePixel] * 255; } */ /* glBindTexture(GL_TEXTURE_2D, texVBO[index]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, depthBuffer); */ glBindTexture(GL_TEXTURE_2D, texVBO[index]); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, auxDepthBuffer); } void MyGLImageViewer::load3DTextureFromTIFFile(unsigned char *data, GLuint *texVBO, int index, int imageWidth, int imageHeight, int numberOfSlices, GLint filter) { glBindTexture(GL_TEXTURE_3D, texVBO[index]); //glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, filter); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, filter); glTexImage3D(GL_TEXTURE_3D, 0, GL_RGBA, imageWidth, imageHeight, numberOfSlices, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); } void MyGLImageViewer::loadDepthComponentTexture(float *data, GLuint *texVBO, int index, int windowWidth, int windowHeight) { glBindTexture(GL_TEXTURE_2D, texVBO[index]); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, windowWidth, windowHeight, 0, GL_DEPTH_COMPONENT, GL_FLOAT, data); } void MyGLImageViewer::loadRGBTexture(const unsigned char *data, GLuint *texVBO, int index, int windowWidth, int windowHeight) { glBindTexture(GL_TEXTURE_2D, texVBO[index]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, windowWidth, windowHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, data); } void MyGLImageViewer::draw1DTexture(GLuint *texVBO, int index, GLuint shaderProg, int windowWidth, int windowHeight, int textureID) { //glUseProgram(shaderProg); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D( 0, windowWidth/2, windowHeight/2, 0 ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); GLuint texLoc = glGetUniformLocation(shaderProg, "transferFunction"); glUniform1i(texLoc, textureID); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_1D, texVBO[index]); glBegin(GL_QUADS); glTexCoord2f(0.0f, 0.0f); glVertex2f(0.0f, 0.0f); glTexCoord2f(1.0f, 0.0f); glVertex2f(windowWidth/2, 0.0f); glTexCoord2f(1.0f, 1.0f); glVertex2f(windowWidth/2, windowHeight/2); glTexCoord2f(0.0f, 1.0f); glVertex2f(0.0f, windowHeight/2); glEnd(); //glUseProgram(0); } void MyGLImageViewer::draw2DTexture(GLuint *texVBO, int index, GLuint shaderProg, int windowWidth, int windowHeight, int textureID) { glUseProgram(shaderProg); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D( 0, windowWidth/2, windowHeight/2, 0 ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); GLuint texLoc = glGetUniformLocation(shaderProg, "image"); glUniform1i(texLoc, 0); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texVBO[index]); glBegin(GL_QUADS); glTexCoord2f(0.0f, 0.0f); glVertex2f(0.0f, 0.0f); glTexCoord2f(1.0f, 0.0f); glVertex2f(windowWidth/2, 0.0f); glTexCoord2f(1.0f, 1.0f); glVertex2f(windowWidth/2, windowHeight/2); glTexCoord2f(0.0f, 1.0f); glVertex2f(0.0f, windowHeight/2); glEnd(); glUseProgram(0); } void MyGLImageViewer::draw3DTexture(GLuint *texVBO, float *rot, float *trans, GLuint shaderProg, int windowWidth, int windowHeight, VRParams params) { glUseProgram(shaderProg); GLuint texLoc = glGetUniformLocation(shaderProg, "volume"); glUniform1i(texLoc, 7); glActiveTexture(GL_TEXTURE7); glEnable(GL_TEXTURE_3D); glBindTexture(GL_TEXTURE_3D, texVBO[params.volumeTextureIndex]); glActiveTexture(GL_TEXTURE7); glMatrixMode(GL_TEXTURE); glLoadIdentity(); texLoc = glGetUniformLocation(shaderProg, "minMaxOctree"); glUniform1i(texLoc, 2); glActiveTexture(GL_TEXTURE2); glEnable(GL_TEXTURE_3D); glBindTexture(GL_TEXTURE_3D, texVBO[params.minMaxOctreeTextureIndex]); if(params.stepSize >= 0) { GLuint texLoc = glGetUniformLocation(shaderProg, "stepSize"); glUniform1f(texLoc, params.stepSize); texLoc = glGetUniformLocation(shaderProg, "earlyRayTerminationThreshold"); glUniform1f(texLoc, params.earlyRayTerminationThreshold); texLoc = glGetUniformLocation(shaderProg, "camera"); glUniform3f(texLoc, 0, 0, 3); texLoc = glGetUniformLocation(shaderProg, "kt"); glUniform1f(texLoc, params.kt); texLoc = glGetUniformLocation(shaderProg, "ks"); glUniform1f(texLoc, params.ks); if(params.stochasticJithering) { texLoc = glGetUniformLocation(shaderProg, "stochasticJithering"); glUniform1i(texLoc, 1); } else { texLoc = glGetUniformLocation(shaderProg, "stochasticJithering"); glUniform1i(texLoc, 0); } if(params.triCubicInterpolation) { texLoc = glGetUniformLocation(shaderProg, "triCubicInterpolation"); glUniform1i(texLoc, 1); } else { texLoc = glGetUniformLocation(shaderProg, "triCubicInterpolation"); glUniform1i(texLoc, 0); } if(params.MIP) { texLoc = glGetUniformLocation(shaderProg, "MIP"); glUniform1i(texLoc, 1); } else { texLoc = glGetUniformLocation(shaderProg, "MIP"); glUniform1i(texLoc, 0); } if(params.gradientByForwardDifferences) { texLoc = glGetUniformLocation(shaderProg, "forwardDifference"); glUniform1i(texLoc, 1); } else { texLoc = glGetUniformLocation(shaderProg, "forwardDifference"); glUniform1i(texLoc, 0); } if(params.FCVisualization) { texLoc = glGetUniformLocation(shaderProg, "FCVisualization"); glUniform1i(texLoc, 1); } else { texLoc = glGetUniformLocation(shaderProg, "FCVisualization"); glUniform1i(texLoc, 0); } texLoc = glGetUniformLocation(shaderProg, "clippingPlane"); glUniform1i(texLoc, (int)params.clippingPlane); texLoc = glGetUniformLocation(shaderProg, "inverseClipping"); glUniform1i(texLoc, (int)params.inverseClipping); texLoc = glGetUniformLocation(shaderProg, "clippingOcclusion"); glUniform1i(texLoc, (int)params.clippingOcclusion); texLoc = glGetUniformLocation(shaderProg, "clippingPlaneLeftX"); glUniform1f(texLoc, params.clippingPlaneLeftX); texLoc = glGetUniformLocation(shaderProg, "clippingPlaneRightX"); glUniform1f(texLoc, params.clippingPlaneRightX); texLoc = glGetUniformLocation(shaderProg, "clippingPlaneUpY"); glUniform1f(texLoc, params.clippingPlaneUpY); texLoc = glGetUniformLocation(shaderProg, "clippingPlaneDownY"); glUniform1f(texLoc, params.clippingPlaneDownY); texLoc = glGetUniformLocation(shaderProg, "clippingPlaneFrontZ"); glUniform1f(texLoc, params.clippingPlaneFrontZ); texLoc = glGetUniformLocation(shaderProg, "clippingPlaneBackZ"); glUniform1f(texLoc, params.clippingPlaneBackZ); texLoc = glGetUniformLocation(shaderProg, "isosurfaceThreshold"); glUniform1f(texLoc, params.isoSurfaceThreshold); texLoc = glGetUniformLocation(shaderProg, "windowWidth"); glUniform1i(texLoc, windowWidth); texLoc = glGetUniformLocation(shaderProg, "windowHeight"); glUniform1i(texLoc, windowHeight); } drawQuads(1.0f/params.scaleWidth, 1.0f/params.scaleHeight, 1.0f/params.scaleDepth); texLoc = glGetUniformLocation(shaderProg, "transferFunction"); glUniform1i(texLoc, 1); glActiveTexture(GL_TEXTURE1); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, texVBO[params.transferFunctionTextureIndex]); texLoc = glGetUniformLocation(shaderProg, "noise"); glUniform1i(texLoc, 3); glActiveTexture(GL_TEXTURE3); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, texVBO[params.noiseTextureIndex]); texLoc = glGetUniformLocation(shaderProg, "backFrameBuffer"); glUniform1i(texLoc, 5); glActiveTexture(GL_TEXTURE5); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, texVBO[params.backQuadTextureIndex]); texLoc = glGetUniformLocation(shaderProg, "frontFrameBuffer"); glUniform1i(texLoc, 6); glActiveTexture(GL_TEXTURE6); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, texVBO[params.frontQuadTextureIndex]); if(params.FCVisualization) { texLoc = glGetUniformLocation(shaderProg, "positionBuffer"); glUniform1i(texLoc, 8); glActiveTexture(GL_TEXTURE8); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, texVBO[params.positionTextureIndex]); texLoc = glGetUniformLocation(shaderProg, "normalBuffer"); glUniform1i(texLoc, 9); glActiveTexture(GL_TEXTURE9); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, texVBO[params.normalTextureIndex]); } glUseProgram(0); glActiveTexture(GL_TEXTURE1); glDisable(GL_TEXTURE_2D); glActiveTexture(GL_TEXTURE2); glDisable(GL_TEXTURE_3D); glActiveTexture(GL_TEXTURE3); glDisable(GL_TEXTURE_2D); glActiveTexture(GL_TEXTURE5); glDisable(GL_TEXTURE_2D); glActiveTexture(GL_TEXTURE6); glDisable(GL_TEXTURE_2D); glActiveTexture(GL_TEXTURE7); glDisable(GL_TEXTURE_3D); if(params.FCVisualization) { glActiveTexture(GL_TEXTURE8); glDisable(GL_TEXTURE_2D); glActiveTexture(GL_TEXTURE9); glDisable(GL_TEXTURE_2D); } } void MyGLImageViewer::drawFCVisualization(GLuint *texVBO, GLuint shaderProg, int windowWidth, int windowHeight, VRParams params) { glUseProgram(shaderProg); drawQuads(1.0f/params.scaleWidth, 1.0f/params.scaleHeight, 1.0f/params.scaleDepth); GLuint texLoc = glGetUniformLocation(shaderProg, "position"); glUniform1i(texLoc, 8); glActiveTexture(GL_TEXTURE8); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, texVBO[params.positionTextureIndex]); texLoc = glGetUniformLocation(shaderProg, "normal"); glUniform1i(texLoc, 9); glActiveTexture(GL_TEXTURE9); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, texVBO[params.normalTextureIndex]); texLoc = glGetUniformLocation(shaderProg, "curvature"); glUniform1i(texLoc, 10); glActiveTexture(GL_TEXTURE10); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, texVBO[params.curvatureTextureIndex]); texLoc = glGetUniformLocation(shaderProg, "focusLayer"); glUniform1i(texLoc, 11); glActiveTexture(GL_TEXTURE11); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, texVBO[params.focusTextureIndex]); texLoc = glGetUniformLocation(shaderProg, "contextLayer"); glUniform1i(texLoc, 12); glActiveTexture(GL_TEXTURE12); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, texVBO[params.contextTextureIndex]); texLoc = glGetUniformLocation(shaderProg, "focusPoint"); glUniform2f(texLoc, params.focusPoint[0], params.focusPoint[1]); texLoc = glGetUniformLocation(shaderProg, "focusRadius"); glUniform1f(texLoc, params.focusRadius); texLoc = glGetUniformLocation(shaderProg, "windowWidth"); glUniform1i(texLoc, windowWidth); texLoc = glGetUniformLocation(shaderProg, "windowHeight"); glUniform1i(texLoc, windowHeight); glUseProgram(0); glActiveTexture(GL_TEXTURE8); glDisable(GL_TEXTURE_2D); glActiveTexture(GL_TEXTURE9); glDisable(GL_TEXTURE_2D); glActiveTexture(GL_TEXTURE10); glDisable(GL_TEXTURE_2D); glActiveTexture(GL_TEXTURE11); glDisable(GL_TEXTURE_2D); glActiveTexture(GL_TEXTURE12); glDisable(GL_TEXTURE_2D); } void MyGLImageViewer::setShadowTextureMatrix() { static double modelView[16]; static double projection[16]; // This is matrix transform every coordinate x,y,z // x = x* 0.5 + 0.5 // y = y* 0.5 + 0.5 // z = z* 0.5 + 0.5 // Moving from unit cube [-1,1] to [0,1] const GLdouble bias[16] = { 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0}; // Grab modelview and transformation matrices glGetDoublev(GL_MODELVIEW_MATRIX, modelView); glGetDoublev(GL_PROJECTION_MATRIX, projection); glMatrixMode(GL_TEXTURE); glActiveTexture(GL_TEXTURE6); glLoadIdentity(); glLoadMatrixd(bias); // concatating all matrice into one. glMultMatrixd (projection); glMultMatrixd (modelView); // Go back to normal matrix mode glMatrixMode(GL_MODELVIEW); } void MyGLImageViewer::readDepthBufferTexture(GLuint *texVBO, int index, int x, int y, int width, int height) { //Read the depth buffer into the shadow map texture glBindTexture(GL_TEXTURE_2D, texVBO[index]); glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, x, y, width, height); } void MyGLImageViewer::loadFrameBufferTexture(GLuint *texVBO, int index, int x, int y, int width, int height) { glReadPixels(x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, depthBuffer); glBindTexture(GL_TEXTURE_2D, texVBO[index]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, depthBuffer); } void MyGLImageViewer::drawShadowMapTexture(GLuint shaderProg, GLuint *texVBO, int index) { glUseProgram(shaderProg); GLuint texLoc = glGetUniformLocation(shaderProg, "ShadowMap"); glUniform1i(texLoc, 0); glActiveTexture(GL_TEXTURE3); glBindTexture(GL_TEXTURE_2D, texVBO[index]); } void MyGLImageViewer::drawQuads(float x, float y, float z, GLenum target) { bool color = true; glBegin(GL_QUADS); //front if(color) glColor3f(0, 1, 1); glMultiTexCoord3f(target, 0.0f, 1.0f, 1.0f); glVertex3f(-x, y, z); //0 if(color) glColor3f(0, 0, 1); glMultiTexCoord3f(target, 0.0f, 0.0f, 1.0f); glVertex3f(-x, -y, z); //1 if(color) glColor3f(1, 0, 1); glMultiTexCoord3f(target, 1.0f, 0.0f, 1.0f); glVertex3f(x, -y, z); //2 if(color) glColor3f(1, 1, 1); glMultiTexCoord3f(target, 1.0f, 1.0f, 1.0f); glVertex3f(x, y, z); //3 //left if(color) glColor3f(0, 1, 0); glMultiTexCoord3f(target, 0.0f, 1.0f, 0.0f); glVertex3f(-x, y, -z); //4 if(color) glColor3f(0, 0, 0); glMultiTexCoord3f(target, 0.0f, 0.0f, 0.0f); glVertex3f(-x, -y, -z); //5 if(color) glColor3f(0, 0, 1); glMultiTexCoord3f(target, 0.0f, 0.0f, 1.0f); glVertex3f(-x, -y, z); //1 if(color) glColor3f(0, 1, 1); glMultiTexCoord3f(target, 0.0f, 1.0f, 1.0f); glVertex3f(-x, y, z); //0 //back if(color) glColor3f(1, 1, 0); glMultiTexCoord3f(target, 1.0f, 1.0f, 0.0f); glVertex3f(x, y, -z); //7 if(color) glColor3f(1, 0, 0); glMultiTexCoord3f(target, 1.0f, 0.0f, 0.0f); glVertex3f(x, -y, -z); //6 if(color) glColor3f(0, 0, 0); glMultiTexCoord3f(target, 0.0f, 0.0f, 0.0f); glVertex3f(-x, -y, -z); //5 if(color) glColor3f(0, 1, 0); glMultiTexCoord3f(target, 0.0f, 1.0f, 0.0f); glVertex3f(-x, y, -z); //4 //right if(color) glColor3f(1, 1, 1); glMultiTexCoord3f(target, 1.0f, 1.0f, 1.0f); glVertex3f(x, y, z); //3 if(color) glColor3f(1, 0, 1); glMultiTexCoord3f(target, 1.0f, 0.0f, 1.0f); glVertex3f(x, -y, z); //2 if(color) glColor3f(1, 0, 0); glMultiTexCoord3f(target, 1.0f, 0.0f, 0.0f); glVertex3f(x, -y, -z); //6 if(color) glColor3f(1, 1, 0); glMultiTexCoord3f(target, 1.0f, 1.0f, 0.0f); glVertex3f(x, y, -z); //7 //top if(color) glColor3f(0, 1, 0); glMultiTexCoord3f(target, 0.0f, 1.0f, 0.0f); glVertex3f(-x, y, -z); //4 if(color) glColor3f(0, 1, 1); glMultiTexCoord3f(target, 0.0f, 1.0f, 1.0f); glVertex3f(-x, y, z); //0 if(color) glColor3f(1, 1, 1); glMultiTexCoord3f(target, 1.0f, 1.0f, 1.0f); glVertex3f(x, y, z); //3 if(color) glColor3f(1, 1, 0); glMultiTexCoord3f(target, 1.0f, 1.0f, 0.0f); glVertex3f(x, y, -z); //7 //bottom if(color) glColor3f(1, 0, 0); glMultiTexCoord3f(target, 1.0f, 0.0f, 0.0f); glVertex3f(x, -y, -z); //6 if(color) glColor3f(1, 0, 1); glMultiTexCoord3f(target, 1.0f, 0.0f, 1.0f); glVertex3f(x, -y, z); //2 if(color) glColor3f(0, 0, 1); glMultiTexCoord3f(target, 0.0f, 0.0f, 1.0f); glVertex3f(-x, -y, z); //1 if(color) glColor3f(0, 0, 0); glMultiTexCoord3f(target, 0.0f, 0.0f, 0.0f); glVertex3f(-x, -y, -z); //5 glEnd(); }
PHP
UTF-8
2,423
3.4375
3
[]
no_license
<?php /** * Created by PhpStorm. * User: susucool(527237808@qq.com) * Date: 2018/9/6 * Time: 15:27 */ // 可变标识符 $i = 3; $k = 'i'; echo $$k.'<br>'; function func(){ echo 'hello<br>'; } // 可变函数 $i = 'func'; $i(); // 可变类 可变属性 class CLS { public $k = 'variable value<br>'; } $i = 'CLS'; $j = 'k'; $l = new $i(); echo $l->$j; // 可变方法 class CLS2 { public function k(){ echo 'variable function<br>'; } } $i = 'k'; $j = new CLS2(); $j->$i(); $user='susucool'; $sql="select * from user as u where u.name='$user'"; echo $sql."<br>"; // php中,单引号和双音号都可以定义一段字符串,但区别是双引号会默认在解析中进行处理。而单引号不会。 $str = <<<TYPEOTHER fdasfdsafdasfad//////213123"#123123"32143213123<br>2112<br> TYPEOTHER; echo $str; // php 的 heredoc,大量插入html字符时候使用 $str=0; if(!isset($str)){ echo 'empty<br>'; } else { echo 'no<br>'; }//no if(empty($str)){ echo 'empty<br>'; } else { echo 'no<br>'; }//empty if( $str===null ){ echo 'empty<br>'; } else { echo 'no<br>'; }//no if( $str==null ){ echo 'empty<br>'; } else{ echo 'no<br>'; }//empty function closureCreator(){ $x = 1; return function($fun = null) use ( $x ){ echo "$x<br>"; $fun and $fun(); echo "<br>"; }; } $test = closureCreator(); $test(); $test(function(){ echo "closure test one"; }); $test(function(){ echo "closure test two"; }); $x = 'hello world'; $test(function() use($x) { echo "<br />".$x; }); $point = [1,2,3,4,5,6]; echo current($point)."<br>"; echo pos($point)."<br>"; // current/pos 返回当前被内部指针指向的数组单元的值,并不移动指针。 echo key($point)."<br>"; // key 返回数组中当前单元的键名,并不移动指针 echo next($point)."<br>"; // next 将数组中的内部指针向前移动一位,并返回移动后当前单元的值。先移动,再取值。 echo prev($point)."<br>"; // prev 将数组的内部指针倒回一位,并返回移动后当前单元的值先移动,再取值。 echo end($point)."<br>"; // end 将数组的内部指针指向最后一个单元,并返回最后一个单元的值 echo current($point)."<br>"; echo reset($point)."<br>"; // reset 将数组的内部指针指向第一个单元,并返回第一个数组单元的值 echo current($point)."<br>";
Go
UTF-8
577
2.734375
3
[]
no_license
package main import ( "flag" "fmt" "github.com/goplog/run" "log" "os" "strings" ) func main() { var cfg string fs := flag.NewFlagSet("goplog", flag.ExitOnError) fs.Usage = func() { fmt.Println(Help()) os.Exit(0) } fs.StringVar(&cfg, "c", "cfg.confg", "configuration file") fs.Parse(os.Args[1:]) f, err := os.Open(cfg) if err != nil { log.Fatalln(err) } defer f.Close() run.Run(cfg, false) } func Help() string { helpText := ` Usage: goplog [options] Options: -c configusration file default:cfg.conf ` return strings.TrimSpace(helpText) }
C#
UTF-8
1,448
3.09375
3
[]
no_license
using System; using System.IO; using Sokoban.Core; namespace Sokoban.ToyApp { class Program { public static void Main(string[] args) { if (args.Length != 1) { Console.WriteLine("Usage: ToyApp <puzzle_file>"); return; } var puzzleFilePath = args[0]; Puzzle puzzle; using (var reader = File.OpenText(puzzleFilePath)) { puzzle = Puzzle.ParseFrom(reader); } Console.Clear(); puzzle.PrintTo(Console.Out); var currentState = puzzle.InitialState; while (! currentState.IsWinning) { Console.CursorTop -= currentState.Field.Height; Console.CursorLeft = 0; currentState.PrintTo(Console.Out); Move? move = null; while (move == null) { var key = Console.ReadKey(true); switch (key.Key) { case ConsoleKey.UpArrow: case ConsoleKey.K: move = Move.Up; break; case ConsoleKey.DownArrow: case ConsoleKey.J: move = Move.Down; break; case ConsoleKey.LeftArrow: case ConsoleKey.H: move = Move.Left; break; case ConsoleKey.RightArrow: case ConsoleKey.L: move = Move.Right; break; case ConsoleKey.Escape: case ConsoleKey.Q: return; } if (move != null && !currentState.ValidateMove(move.Value)) { move = null; } } currentState = currentState.ApplyMove(move.Value); } Console.WriteLine("The Winner Is You"); return; } } }
Java
UTF-8
1,371
2.03125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package mx.edu.um.dii.labinterfaces.diasetproject.service.impl; import java.util.List; import mx.edu.um.dii.labinterfaces.diasetproject.dao.AreaDao; import mx.edu.um.dii.labinterfaces.diasetproject.model.Area; import mx.edu.um.dii.labinterfaces.diasetproject.service.AreaService; import mx.edu.um.dii.labinterfaces.diasetproject.service.BaseService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * * @author laboratoriointerface */ @Service public class AreaServiceImpl extends BaseService implements AreaService{ @Autowired private AreaDao areaDao; @Override public List<Area> getAll() { return areaDao.getAll(); } @Override public Area get(Long id) { return areaDao.get(id); } @Override public Area get(String code) { return areaDao.getByCode(code); } @Override public Area save(Area area) { return areaDao.save(area); } @Override public Area update(Area area) { return areaDao.update(area); } @Override public String delete(Long id) { return areaDao.delete(id); } }
Python
UTF-8
2,637
3.9375
4
[]
no_license
# flows are used to describe the dependencies between tasks # if tasks are like functions, we can think of a flow as a script that combines them # when you build a flow in Prefect, you're defining a computational graph that can be executed in the future # the pattern is always the same: step 1 is to build a flow, step 2 is to run() the flow from tasks import say_hello, add from prefect import Flow, Parameter ## Flow 1, to demonstrate Prefect's functional API # the easiest way to build a flow is with Prefect's functional API # we create a flow as a context manager and call tasks on each other # Prefect builds up a computational graph that represents the workflow # note: no tasks are actually executed at this time with Flow('My first flow!') as flow: first_result = add(1, y=2) second_result = add(x=first_result, y=100) # once the flow has been created, we can execute it by calling flow.run() # we can examine the state of the run, and the state and result of each task state = flow.run() assert state.is_successful() first_task_state = state.result[first_result] assert first_task_state.is_successful() assert first_task_state.result == 3 second_task_state = state.result[second_result] assert second_task_state.is_successful() assert second_task_state.result == 103 # the run() method handles scheduling, retries, data serialisation etc # note: in production execution of flow.run() would probably be handled by a management API ## Flow 2, to demonstrate the concept of parameters # Prefect provides a special task called a Parameter # Parameters enable us to provide information to a flow at runtime with Flow('Say hi!') as flow: n = Parameter('name') say_hello(n) flow.run(name='Ed') ## Flow 3, to demonstrate Prefect's imperative API # the functional API makes it easy to define workflows in a script-like style # the imperative API enables us to build flows in a more programmatic or explicit way flow = Flow('My imperative flow!') # define some new tasks name = Parameter('name') second_add = add.copy() # add our tasks to the flow flow.add_task(add) flow.add_task(second_add) flow.add_task(say_hello) # create non-data dependencies so that `say_hello` waits for `second_add` to finish say_hello.set_upstream(second_add, flow=flow) # create data bindings add.bind(x=1, y=2, flow=flow) second_add.bind(x=add, y=100, flow=flow) say_hello.bind(person=name, flow=flow) flow.run(name='Chris') # note: with the functional API, the upstream_tasks keyword arg can be used to define state-dependencies # note: you can switch between the functional API and the imperative API at any time
C#
UTF-8
1,829
3.21875
3
[]
no_license
using ExceptionCore; using ExceptionCore.Bussiness; using ExceptionCore.Critical; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ExceptionHandler { class Program { static void Main(string[] args) { int option; do { try { Console.WriteLine("====Menu===="); Console.WriteLine("[1] Hacer algo"); Console.WriteLine("[2] Hacer algo mas"); Console.WriteLine("[0] Salir"); if (!int.TryParse(Console.ReadLine(), out option)) { throw new InvalidInputException(2); } if (option == 1) { int i = 0; int j = 0; int y = i / j; Console.WriteLine("Una accion"); } else if (option == 2) { var list = new List<int>(); var x = list[10]; } } catch (Exception exception) { AbstractException catched; if (exception is AbstractException) { catched = exception as AbstractException; } else { catched = new CriticalException(exception); } catched.LogException(); option = -1; } } while (option != 0); } } }
Python
UTF-8
4,140
2.640625
3
[ "MIT" ]
permissive
"""test_example .. codeauthor:: John Lane <john.lane93@gmail.com> """ from flask import url_for from eve import Eve import pytest from mockerena.format import generate_xml_template @pytest.mark.file_format def test_generate_xml_template_flat(): """Generate xml template should accept flat structure :raises: AssertionError """ res = generate_xml_template({'bar': "{{ r['bar'] }}", 'baz': "{{ r['baz'] }}"}, 'foo') assert res == "<foo>{% for r in records %}<bar>{{ r['bar'] }}</bar><baz>{{ r['baz'] }}</baz>{% endfor %}</foo>" @pytest.mark.file_format def test_generate_xml_template_nested(): """Generate xml template should accept nested structure :raises: AssertionError """ res = generate_xml_template({'b': "{{ r['b'] }}", 'c': {'d': "{{ r['c.d'] }}"}}, 'a') assert res == "<a>{% for r in records %}<b>{{ r['b'] }}</b><c><d>{{ r['c.d'] }}</d></c>{% endfor %}</a>" @pytest.mark.file_format def test_generate_xml_template_empty_root(): """Generate xml template should not render empty root nodes :raises: AssertionError """ res = generate_xml_template({'foo': {'bar': "{{ r['bar'] }}"}, 'baz': "{{ r['baz'] }}"}, '') assert res == "{% for r in records %}<baz>{{ r['baz'] }}</baz><foo><bar>{{ r['bar'] }}</bar></foo>{% endfor %}" @pytest.mark.file_format def test_generate_xml_template_no_columns(): """Generate xml template should not render if columns is empty :raises: AssertionError """ res = generate_xml_template({}, '') assert res == '' @pytest.mark.file_format def test_generate_xml_data(client: Eve, sample_schema: dict): """Test to xml can be generated :param Eve client: Mockerena app instance :param dict sample_schema: Sample schema data :raises: AssertionError """ sample_schema["num_rows"] = 1 sample_schema["file_format"] = "xml" sample_schema["root_node"] = "custom" res = client.post(url_for('custom_schema'), json=sample_schema, headers={'Content-Type': "application/json"}) assert res.status_code == 200 assert res.get_data().decode('utf-8') == '<custom><foo>this</foo><bar>that</bar></custom>' @pytest.mark.file_format def test_generate_xml_with_default_root(client: Eve, sample_schema: dict): """Test to xml can be generated without specifying a root :param Eve client: Mockerena app instance :param dict sample_schema: Sample schema data :raises: AssertionError """ sample_schema["num_rows"] = 1 sample_schema["file_format"] = "xml" res = client.post(url_for('custom_schema'), json=sample_schema, headers={'Content-Type': "application/json"}) assert res.status_code == 200 assert res.get_data().decode('utf-8') == '<root><foo>this</foo><bar>that</bar></root>' @pytest.mark.file_format def test_generate_xml_with_nested(client: Eve, sample_schema: dict): """Test to xml can be generated with nested values :param Eve client: Mockerena app instance :param dict sample_schema: Sample schema data :raises: AssertionError """ sample_schema["num_rows"] = 1 sample_schema["file_format"] = "xml" sample_schema["is_nested"] = True sample_schema["columns"][0]["name"] = "foo.bar" sample_schema["columns"][1]["name"] = "foo.baz" res = client.post(url_for('custom_schema'), json=sample_schema, headers={'Content-Type': "application/json"}) assert res.status_code == 200 assert res.get_data().decode('utf-8') == '<root><foo><bar>this</bar><baz>that</baz></foo></root>' @pytest.mark.file_format def test_generate_xml_with_empty_root(client: Eve, sample_schema: dict): """Test to xml can be generated with an empty root :param Eve client: Mockerena app instance :param dict sample_schema: Sample schema data :raises: AssertionError """ sample_schema["num_rows"] = 1 sample_schema["file_format"] = "xml" sample_schema["root_node"] = "" res = client.post(url_for('custom_schema'), json=sample_schema, headers={'Content-Type': "application/json"}) assert res.status_code == 200 assert res.get_data().decode('utf-8') == '<foo>this</foo><bar>that</bar>'
Swift
UTF-8
4,768
2.875
3
[ "MIT" ]
permissive
// // AdmitadTrackingType.swift // AdmitadSDK // // Created by Dmitry Cherednikov on 28.09.17. // Copyright © 2017 tachos. All rights reserved. // import Foundation /** Represents type of an event and also contains additional information depending on the exact type. - *installed*: Installed event. - *confirmedPurchase*: Confirmed Purchase event type. Parametrized with tracked order. - *paidOrder*: Paid Order event type. Pararmetrized with tracked order. - *registration*: Registration event type. Parametrized with tracked order. - *loyalty*: Loyalty event type. Parametrized with number of app's launches. - *returned*: Returned event type. Parametrized with number of days since last launch. */ public enum AdmitadEventType { case installed(channel: String?) case confirmedPurchase(order: AdmitadOrder, channel: String?) case paidOrder(order: AdmitadOrder, channel: String?) case registration(userId: String, channel: String?) case loyalty(userId: String, loyalty: Int, channel: String?) case returned(userId: String, dayReturned: Int, channel: String?) case deviceinfo } // MARK: - utility internal extension AdmitadEventType { internal init?(url: URL) { guard let trackingString = url[AdmitadParameter.tracking.rawValue] else { return nil } guard let trackingType = AdmitadTrackingType(rawValue: trackingString) else { return nil } switch trackingType { case .installed: self.init(installedUrl: url) case .confirmedPurchase: self.init(confirmedPurchaseUrl: url) case .paidOrder: self.init(paidOrderUrl: url) case .registration: self.init(registrationUrl: url) case .loyalty: self.init(loyaltyUrl: url) case .returned: self.init(returnedUrl: url) case .deviceinfo: self.init(deviceinfoUrl: url) } } internal func toString() -> String { switch self { case .installed: return toString(.installed) case .confirmedPurchase: return toString(.confirmedPurchase) case .paidOrder: return toString(.paidOrder) case .registration: return toString(.registration) case .loyalty: return toString(.loyalty) case .returned: return toString(.returned) case .deviceinfo: return toString(.deviceinfo) } } private func toString(_ trackingType: AdmitadTrackingType) -> String { return trackingType.rawValue } } private extension AdmitadEventType { init(installedUrl url: URL) { let channel = url[AdmitadParameter.channel.rawValue] ?? AdmitadTracker.ADM_MOBILE_CHANNEL self = .installed(channel: channel) } init(deviceinfoUrl url: URL) { self = .deviceinfo } init?(confirmedPurchaseUrl url: URL) { guard let order = AdmitadOrder(url: url) else { return nil } let channel = url[AdmitadParameter.channel.rawValue] ?? AdmitadTracker.ADM_MOBILE_CHANNEL self = .confirmedPurchase(order: order, channel: channel) } init?(paidOrderUrl url: URL) { guard let order = AdmitadOrder(url: url) else { return nil } let channel = url[AdmitadParameter.channel.rawValue] ?? AdmitadTracker.ADM_MOBILE_CHANNEL self = .paidOrder(order: order, channel: channel) } init?(registrationUrl url: URL) { guard let userId = url[AdmitadParameter.oid.rawValue] else { return nil } let channel = url[AdmitadParameter.channel.rawValue] ?? AdmitadTracker.ADM_MOBILE_CHANNEL self = .registration(userId: userId, channel: channel) } init?(loyaltyUrl url: URL) { let userId = url[AdmitadParameter.oid.rawValue] ?? "" guard let loyaltyString = url[AdmitadParameter.loyalty.rawValue] else { return nil } guard let loyalty = Int(loyaltyString) else { return nil } let channel = url[AdmitadParameter.channel.rawValue] ?? AdmitadTracker.ADM_MOBILE_CHANNEL self = .loyalty(userId: userId, loyalty: loyalty, channel: channel) } init?(returnedUrl url: URL) { let userId = url[AdmitadParameter.oid.rawValue] ?? "" guard let dayString = url[AdmitadParameter.day.rawValue] else { return nil } guard let day = Int(dayString) else { return nil } let channel = url[AdmitadParameter.channel.rawValue] ?? AdmitadTracker.ADM_MOBILE_CHANNEL self = .returned(userId: userId, dayReturned: day, channel: channel) } }
Java
UTF-8
5,411
2.828125
3
[]
no_license
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class Rename { public static void main(String[] args) { String cm = args[0]; List<File> a = Arrays.asList(new File(args[1]).listFiles()); switch (cm) { case "pr": prefix(a, args[2]); break; case "pt": postfix(a, args[2]); break; case "lc": lowerCase(a); break; case "lt": leftTrim(a, Integer.parseInt(args[2])); break; case "fl": fixLength(a, Integer.parseInt(args[2])); break; case "rt": rightTrim(a, Integer.parseInt(args[2])); break; case "et": changeExtension(a, "." + args[2], "." + args[3]); break; case "rc": removeCharacter(a, (args.length > 2) ? args[2] : ""); break; case "sf": sortFile(a, (args.length > 2) ? args[2] : ""); break; case "z": compress(a); break; case "mc": mangaChapter(a); break; default: System.out.println("Invalid command"); break; } } public static void prefix(List<File> a, String prefix) { a.forEach(f -> f.renameTo(new File(f.getParentFile(), prefix + f.getName().toLowerCase()))); } public static void postfix(List<File> a, String postfix) { a.stream().forEach(f -> { String fullName = f.getName(); int idx = fullName.lastIndexOf("."); String name = fullName.substring(0, idx); String ext = fullName.substring(idx); String nn = name + postfix + ext; //System.out.println(nn); f.renameTo(new File(f.getParentFile(), nn)); }); } public static void lowerCase(List<File> a) { a.forEach(f -> f.renameTo(new File(f.getParentFile(), f.getName().toLowerCase()))); } public static void leftTrim(List<File> a, int num) { a.forEach(f -> f.renameTo(new File(f.getParentFile(), f.getName().substring(num)))); } public static void fixLength(List<File> a, int num) { a.forEach(f -> f.renameTo(new File(f.getParentFile(), f.getName().substring(0, num)))); } public static void rightTrim(List<File> a, int num) { a.stream().filter(f -> f.isFile()).forEach(f -> { String fullName = f.getName(); int idx = fullName.lastIndexOf("."); String name = fullName.substring(0, idx - num); String ext = fullName.substring(idx); String nn = name + ext; f.renameTo(new File(f.getParentFile(), nn)); }); a.stream().filter(f -> f.isDirectory()).forEach(f -> { String on = f.getName(); String nn = on.substring(0, on.length() - num); f.renameTo(new File(f.getParentFile(), nn)); }); } public static void changeExtension(List<File> a, String oe, String ne) { a.stream().filter(f -> f.isFile()).forEach(f -> { String fullName = f.getName(); int idx = fullName.lastIndexOf("."); String name = fullName.substring(0, idx); String ext = fullName.substring(idx); if (ext.toLowerCase().equals(oe)) { f.renameTo(new File(f.getParentFile(), name + ne)); } }); } public static void removeCharacter(List<File> a, String other) { a.forEach(f -> { String nn = f.getName().replace("_", " ").replace(":", " - "); if (!other.isEmpty()) { nn = nn.replace(other, ""); } f.renameTo(new File(f.getParentFile(), nn)); }); } public static void sortFile(List<File> a, String prefix) { a.sort((o1, o2) -> { return o1.getName().compareTo(o2.getName()); }); int i = 0; for (File f : a) { String on = f.getName(); String ext = on.substring(on.lastIndexOf(".")).toLowerCase(); String nn = prefix + String.valueOf(1001 + i).substring(1) + ext; System.out.println(on + " -> " + nn); f.renameTo(new File(f.getParentFile(), nn)); i += 1; } } public static void mangaChapter(List<File> a) { a.forEach(f -> { if (f.isDirectory()) { String on = f.getName(); int i = on.lastIndexOf(' '); String prefix = (i >= 0 ? on.substring(i + 1, on.length()) : on) + "-"; sortFile(Arrays.asList(f.listFiles()), prefix); // Chuyen cac file ra ngoai Arrays.asList(f.listFiles()).forEach(e -> { e.renameTo(new File(f.getParentFile(), e.getName())); }); } }); } public static void compress(List<File> a) { a.sort((o1, o2) -> { return o1.getName().compareTo(o2.getName()); }); a.stream().filter(f -> f.isDirectory()).forEach(f -> { compress(f, new File(f.getParentFile(), f.getName() + ".zip")); }); } public static void compress(File folder, File archive) { System.out.println("Zipping " + folder.getName()); try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(archive))) { List<File> files = Arrays.asList(folder.listFiles()); files.sort((o1, o2) -> { return o1.getName().compareTo(o2.getName()); }); for (File f : files) { System.out.print(f.getName() + "\r"); addZipEntry(f, zos); } System.out.println("\nDone"); } catch (IOException ex) { ex.printStackTrace(); } } private static void addZipEntry(File file, ZipOutputStream zos) throws IOException { ZipEntry ze = new ZipEntry(file.getName()); zos.putNextEntry(ze); FileInputStream fis = new FileInputStream(file); byte[] buffer = new byte[1024]; int count; while ((count = fis.read(buffer)) > 0) { zos.write(buffer, 0, count); } fis.close(); zos.closeEntry(); } }
Java
UTF-8
2,518
2.6875
3
[ "MIT" ]
permissive
package test.udp; import com.alibaba.fastjson.JSONObject; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class UdpTest { public static void main(String[] args) { // ipAddressIsable(); udpGB(); } public static void ipAddressIsable(){ try { boolean status = InetAddress.getByName("171.18.193.114").isReachable(1000); System.out.println("IP 地址是否可通信:" + status); }catch (Exception e){ System.out.println(e.getMessage()); } } public static void udpGB() { try { // 创建广播 InetAddress broadcastAddress = InetAddress.getByName("172.18.199.255"); DatagramSocket socket = new DatagramSocket(); socket.setSoTimeout(1000); // 1秒时间应该足够了 JSONObject broadMsg = new JSONObject(); broadMsg.put("AllSearch", 1); broadMsg.put("LocalWebPort", 8080); broadMsg.put("WebServerSend", true); broadMsg.put("Platform", 1); broadMsg.put("timeStamp", System.currentTimeMillis()); // 发送数据 String sendData = broadMsg.toJSONString(); DatagramPacket sendPacket = new DatagramPacket(sendData.getBytes(), sendData.getBytes().length, broadcastAddress, 50727); socket.send(sendPacket); // 接收数据 byte[] buffer = new byte[4096]; DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length); int count = 0; while (true) { try { socket.receive(receivePacket); String message = new String(receivePacket.getData()).trim(); System.out.println("广播获取消息包:" + message); count++; Thread.sleep(1000); } catch (Exception e) { System.out.println("搜索不到设备了"); System.out.println("总共搜索设备数:" + count + "个"); break; } } // 回复数据 String replyData = "ok"; DatagramPacket reply = new DatagramPacket(replyData.getBytes(), replyData.getBytes().length, receivePacket.getAddress(), receivePacket.getPort()); socket.send(reply); } catch (Exception e) { e.printStackTrace(); } } }
Python
UTF-8
1,945
2.59375
3
[]
no_license
from datetime import date from geopy import Nominatim import datetime import wolframalpha def get_details(lat,lon): coord=[] coord.append(lat) coord.append(lon) geolocator=Nominatim(user_agent="test/1") #print('{coord[0]},{coord[1]}') coord1="{},{}".format(lat,lon) location =geolocator.reverse(coord1) s=location.address final=s.split(",") #print(final) locatity=final[0] city=final[2] pincode=final[-2] state=final[-3] country=final[-1] query1="temperature of {}".format(city) query2="Humidity of {}".format(city) client = wolframalpha.Client('AGVT22-AE67Q6APHU') print("\033[93m MONITORING ...\033[00m") try: res = client.query(query1) res2=client.query(query2) results = next(res.results).text results2 = next(res2.results).text print("=============\033[92m WELCOME TO GEOSIGHT \033[00m=================") print('\033[96m Latitute : {}\033[00m '.format(lat)) print('\033[96m Longitute : {}\033[00m '.format(lon)) print('\033[96m Locality : {}\033[00m '.format(locatity)) print('\033[96m City : {}\033[00m '.format(city)) print('\033[96m State : {}\033[00m '.format(state)) print('\033[96m Country : {}\033[00m '.format(country)) print('\033[96m Temperature : {}\033[00m '.format(results)) print('\033[96m Humidity : {}\033[00m '.format(results2)) print("======================================") except: print("=============\033[92m WELCOME TO GEOSIGHT \033[00m=================") print('\033[96m Latitute : {}\033[00m '.format(lat)) print('\033[96m Longitute : {}\033[00m '.format(lon)) print('\033[96m Locality : {}\033[00m '.format(locatity)) print('\033[96m City : {}\033[00m '.format(city)) print('\033[96m State : {}\033[00m '.format(state)) print('\033[96m Country : {}\033[00m '.format(country)) print('\033[91m Temperature : Sorry ! Not Reognized\033[00m') print('\033[91m Humidity: Sorry ! Not Reognized\033[00m') print("======================================")
Markdown
UTF-8
20,381
2.765625
3
[]
no_license
--- layout: git title: Denoising with Generative Models published: true description: Semester Project - EPFL github: 'https://github.com/Billotais/Denoising-with-Generative-Models' --- Semester Project by [Loïs Bilat](mailto:lois@bilat.xyz) at VITA Lab - EPFL - Fall 2019 Supervised by [Alexandre Alahi](mailto:alexandre.alahi@epfl.ch) and [Brian Sifringer](mailto:brian.sifringer@epfl.ch). # Notes about read papers Here you can find some short summaries of the papers studied for this project, as well as a few useful links. Those should not be considered as part of the report, but more as some help and additional ressources if needed. ## Conditional GAN [https://machinelearningmastery.com/how-to-develop-a-conditional-generative-adversarial-network-from-scratch/](https://machinelearningmastery.com/how-to-develop-a-conditional-generative-adversarial-network-from-scratch/) [pix2pix](https://arxiv.org/pdf/1611.07004.pdf) ## Pytorch Big tutorial [here](https://pytorch.org/tutorials/beginner/deep_learning_60min_blitz.html). U-net in paytorch [here](https://github.com/milesial/Pytorch-UNet). Seems really easy to creates sub-modules in a seperate file, and then call them from the main entwork. So it will be quite easy to create a class for the downsampling block and the class for the upsampling block, and then put them one after the other. Similarly, for the discriminator, they repeat a block 7 times, so we can create it and reuse it. Note : to add skip connections, we just need to keep the variable representing the ouput of the downsampling block, and give it to the upsampling block as, for instace, a class argument. We can then just "add" it. ex : ``` out16 = self.in_tr(x) out32 = self.down(16, 32, out16) out64 = self.down(32, 64, out32) out128 = self.down(64, 128, out64) out = self.up(128, 64, out128) out = self.up(64, 32, out64) out = self.up(32, 16, out32) out = self.out_tr(out) ``` [https://github.com/eriklindernoren/PyTorch-GAN](https://github.com/eriklindernoren/PyTorch-GAN) : Collection of code file to implement a GAN in pytorch. ## Audio specific torchaudio seems to be able to do resampling, and can handle waveform audio. Can do many other transformations. Probably good to use this if we do super resolution, so we can generate our intput data. Tuto [here](https://pytorch.org/tutorials/beginner/audio_preprocessing_tutorial.html) Doesn't work with anaconda Could also try to use [Librosa](https://stackoverflow.com/questions/30619740/python-downsampling-wav-audio-file) that can open files downsampled directly. ## Paper Will probably follow [this paper](https://bilat.xyz/vita/Adversarial.pdf) (MUGAN), but it is "under review" so there isn't any names. How will this work ? Need to check how to train the external network Input : fixed size audio sample from the data, going through low pass filter. They don't seem to give the input size, but they use 8 layers => 2^8 as the input size maybe ? Downsampling : 4 filters, 1 of each size. Then is goes through PRelU (Parametric relu) : $f(x) = alpha * x for x < 0, f(x) = x for x >= 0$ And then it goes throught the Superpixel block (similar to a pooling block) which reduces the dimension by 2 and double the number of filters (alternate values, even goes in one output, odd goes in the other output). This seems straight forward. Upsampling block : Once again we have the same 4 filters. I'm not sure how we are supposed to upsample if we have convolutional filters again. Then a dropout, the same PRelU, a subpixel block which this times interleaves two "samples" to make one larger. And then we stack with the input of the corresponding downsampling block. ## Noise Reduction Techniques and Algorithms For Speech Signal Processing (Algo_Speech.pdf) Different types of noise : - Background noise - Echo - Acoustic / audio feedback (Mic capture loudspeaker sound and send it back) - Amplifier noise - Quantization noise when transformning analog to digital (round values), neglectable at sampling higher than 8kHz/16bit - Loss of quality due to compression Linear filterning (Time domain) : Simple convolutation Spectral filtering (Frequency domain) : DFT and back ANC needs a recording of the noise to compare it to the audio Adaptive Line Enhancer (ALE) doesn't need it. Smoothing : noise is often random and fast change, so smoothing can help again white and blue (high freq) noise. [Link](http://bilat.xyz/vita/Algo_Speech.pdf) ## A Review of Adaptive Line Enhancers for Noise Cancellation (ALE.pdf) Doesn't need recording of noise. Adaptive self-tuning filter that can spearate periodic and stochastic component. Detect low-level sin-waves in noise [Link](http://bilat.xyz/vita/ALE.pdf) ## A review: Audio noise reduction and various techniques (Techniques.pdf) Some filters : Butterworth filter, Chebyshev filter, Elliptical filter [Link](http://bilat.xyz/vita/Techniques.pdf) ## Employing phase information for audio denoising (Phase.pdf) [Link](http://bilat.xyz/vita/Phase.pdf) ## Audio Denoising by Time-Frequency Block Thresholding (Block_Threshold.pdf) [Link](http://bilat.xyz/vita/Block_Threshold.pdf) ## Speech Denoising with Deep Feature Losses (Speech_DL.pdf) Fully convolutional network, work on the raw waveform. For the loss, use the internal activation of another network trainned for domestic audio tagging, and environnement detection (classification network). It's a little bit like a GAN. Most approaches today are done on the spectrogram domain, this one not. Prevents some artefacts due do IFT. Methods that are in the time domain often use regression loss between input and output wave. Here, the loss is the dissimilarity between hidden activations of input and ouput waves. Inspired from computer vision (-> Perceptual_Losses.pdf) Details of The main network are given in papers, section II-A-a.Different layers in the classification/feature/loss network correspond to different time scales. The classification network is inspired by VGG architecture from CV, details in paper II-B-a. II-B-b explain how to transoorm activations / weights to a loss. Train the feature loss network using multiple classification tasks (scene classification, audio tagging). Train the speech denoising using the [1] database. They used the clean speeches and some noise samples and created the training data by combining them together, then they are downsampled. Experimental setup : compared with Wiener filterning pipeline, SEGAN, and the WaveNet based one used as a baseline. Used different score metrics (overall (OVL), the signal (SIG), and the background (BAK) scores)). It was better than all the baselines. Also evaluated with human testers, also better than the others. Now this is for speech, and it might not work as well for general sound/music [Link](http://bilat.xyz/vita/Speech_DL.pdf) ## Recurrent Neural Networks for Noise Reduction in Robust ASR (RNN.pdf) SPLICE algorithm is a model that can reduce noise by finding a joint distribution between clean and noisy data, ref to article in the paper's reference, but could not find it online for free. We could simply engineer a filter, but it's hard, and not perfect . Basic idea : We can use L1 norm as the loss function. This type of network is known as denoising autoencoder (DAE). Since input has variable length, we train on a small moving window More advanced : Deep recurrent denoising audtoencoder, we add conection "between the windows" $\implies$ Input is [0 1 2] [1 2 3] [2 3 0], we give each one one to a NN with e.g. 3 hidden layer, with layer 2 recursively connected, and it gives [1] [2] [3] as the output. Uses Aurora2 corpus, with noisy variants synthetically generated [Link](http://bilat.xyz/vita/RNN.pdf) ## Investigating RNN-based speech enhancement methods for noise-robust Text-to-Speech (RNN_Speech_Enhancement.pdf) Shows the two alternative approaches (time vs frequency) on a graph [Link](http://bilat.xyz/vita/RNN_Speech_Enhancement.pdf) ## Audio Denoising with Deep Network Priors (DN_Priors.pdf) Combines time and frequency domain, unsuppervised, you try to fit the noisy audio and since we only partialy fit the output of the network helps to find the clean audio. Link to github repo with some data and the code [github](https://github.com/mosheman5/DNP). Usually we first create a mask that tells us what frequency are noise, then we use an algo that removes those frequencies. Here the assumption is that it is hard by definition to fit noise, so the NN will only fit the clean part of the input. Technique already used in CV. Diff : in CV, the output is already the cleaned image, not here, so they create a spectral mask from the ouput to then denoise the audiio. Better than other unsupervised methods, almost as good the the supervised ones. => Probably not usefull for GANs. [Link](http://bilat.xyz/vita/DN_Priors.pdf) ## Spectral and Cepstral Audio Noise Reduction Techniques in Speech Emotion Recognition (Spectral_Cepstral.pdf) They will compare their method to methods of "Spectral substraction", where you remove the noise spectrum from the audio spectrum. Need to look in more details at "Spectral domain", "Power Spectral"; "log-sepstral", "cepstral domain", ... One again no NN are used here, this is mostly some signal processing, so I don't think it will be very usefull. They also talk about "accurancy measures", e.g. "Itakura distance", "Toeplotz autocorrelation matrix", "euclidian distance between two mel-frequency cepstral vectors". Probably more informations about signal processing techniques in the references. [Link](http://bilat.xyz/vita/Spectral_Cepstral.pdf) ## Raw Waveform-based Speech Enhancement by Fully Convolutional Networks (RawWave_CNN.pdf) Convolutional, waveform to waveform. Mentions like most "Wiener filtering", "spectral substraction", "non-negative matrix factorisation". Also mentions "Deep denoising autoencoder" from (RNN.pdf), also see (DDAE.pdf) that they are citing. Explain that most models use the magnitude spectrogram (-> log-power spcetra), which will leave the phase noisy (as it used the phase from the noisy signal to reconstruct the output signal). Also mentions that it is important to use the phase information to reconstruct the signal afterwards. Apparently DL based models that use the raw form often get better results. Fully connected is not very good since it won't keep local informaton (think high frequencies). They use A "Fully convolutional network FCN" and not a CNN, see (FCN.pdf). A FCN also mean a lot less paramters. Convolutional is considered better since we need adjacent information to make sense of frequencies in the time domain. Fully connected layers cause problems (can't moel high and low frequencies together), so that's why we don't have one at the end in a FCN (FCN = CNN without fully-connected layers). For the experiment, as some of the others papers, they took clean data and corrupted it with some noise (e.g. Babble, Car, Jackhammer, pink, street, white gaussian, ...) They also mention at the end the difference between the "shift step" for the input in the case of a DNN, but it's not very clear what they did with the FCN. They say the took 512 samples from the input wave, but does it seems really low if we use e.g. 44kHz sampling for our music. [Link](http://bilat.xyz/vita/RawWave_CNN.pdf) ## Speech Enhancement Based on Deep Denoising Autoencoder (DDAE.pdf) They meantion a DAE where they only trained using clean speech : Clean as in and out, then when we give a noisy signal it tries to express it on the "clean subspace/basis function", they try to model "what makes a clean speech", need to look into that. This time, they use dirty-clean pairs, so they want to know "what is the statistical difference between noisy and clean. Once again, they create their dataset by adding some noise artificially. They mention (RNN.pdf), which uses a recurrent network, this won't be the case here. The architecture looks like a classical DNN. They stack "neural autoencoders" together, and each AE seems to be layer - non-linear - layer. They also use regularization. For training, they first pretrain each AE individually which adequate parameters, then put them together and train again. Measurement are specific to speech, they use "noise reduction", "speech distortion" and "perceptual evalutation for speech qualty - PESQ" / not clear what this is. For the features they use "Mel frequency power spectrum (MFP)" on 16ms intervals Their results are mostly better than traditional methods. [Link](http://bilat.xyz/vita/DDAE.pdf) ## SEGAN: Speech Enhancement Generative Adversarial Network (Speech_GAN.pdf) As some other papers, mention that most use spectral form, but here they use the raw waveform. Explains GAN : The generator which creates some data by learning the real data distribution and trying to approximate it, and the discriminator, usually a binary classifier, that tries to tell us if our sample is a real one or one generated by the generator. The goal for the generator is to fool the discriminator. To train : D back-props a batch of real examples classified as "true", and then a batch of fake example (generated by G) and mark them as "false". Then we fix D's parameters, and G does the backpropagation with the false example to try to make D missclassify. They then give more mathematical details and techniques (e.g. LSGAN). They use a fully convolutional network (FCN), with a encoder-decoeer layout, were the signal is "compressed", concateneted with the latent representation (?) and then decoded. They also use skip connections so we don't lose some details about the structure (we have speech in and out some we have some similarities). e.g. they transmit phase and alignment information. They then use some information from the D network to create their loss. Their dataset is the usual one we saw previously [1], and they use both artificial and natural noise to create their tran/test set. THey use a sliding window of the raw data (downsampled a little bit), and they also used a minor high freqency filter. All the code is on [github](https://github.com/santi-pdp/segan). Results are positive and are mostly done by people's opinions. [Link](http://bilat.xyz/vita/Speech_GAN.pdf) ## A Wavenet for Speech Denoising (WaveNet.pdf) They first present the WaveNet network, which was used to synthesize natural sounding speech. Their model is similair to WaveNet, but the convolution is "symetrically centerd" since we know both future and passed data unlinke for speech generation. They also have a different loss function, the output is not a probability but the clean data directly, [Link](http://bilat.xyz/vita/WaveNet.pdf) ## Audio Super-Resolution using Neural Nets (SuperRes_NN.pdf) Paper + webpage + github on super resolution with deep networks [https://kuleshov.github.io/audio-super-res/#](https://kuleshov.github.io/audio-super-res/#) Supervized model on low/high quality pairs, deep convolutional network, doesn't need specialized audio processing techniques. Explain that processing raw audio is usefull but computationally intensive. Model is fully feed-forward and inspired from image super-resolution. They consider the sample rate as the resolution we want to improve. it will work on raw audio and (bonus) is one of the rare paper that also tried to work with non-speech audio. Architecture : successive downsampling and upsampling blocks, each doing a convolution + batch norm + ReLU. Called "Bottleneck architecture", similar to the "autoencoders from previous papers. Also have some skip connectionn between "similar layers". This seems very similar to SEGAN. They also use something called "Subpixel shuffling layer", it seems to be what is used in the upsampling block to half the number of filters while increasing the spatial dimension. Two datasets, one piano [5], one with voices [6], with noisy version automaticaly generated with Chebyshev filter. They give a few metrics (Signal to Noise ratio SNR, log-spectral distance LSD) Results are good, and the model is fast enough for real-time on their GPU, but slow to train. When they tried with a more diverse musical dataset, it wasn't sucessfull and the model was underfitting. [Link](http://bilat.xyz/vita/SuperRes_NN.pdf) ## Adversarial Audio Super-resolution with Unsuppervised Feature Losses (Adversarial.pdf) Called MU-GAN GAN are hard to train, people sometimes replace the sample-space loss with a feature loss (instead of distance between two samples in the ssample space, we use the feature maps of an auxiliary nn). Their explanations of a GAN is very similar to the one for SEGAN. They have the generator (G), the discriminator (D), and they also have the convolutional autoencoder (A) that they use to create a loss (see first paragraph above). A is unsupervised The generator is a convolutional u-net (as a few other papers), where each level works has many filter sizes, and we have skip-connections. They use "Subpixel nlocks" in the upsampling block, and the opposite, a "superpixel block" in the downsampling block. Subpixels were mentionend in the previous paper, and superpixel lets you decrease the dimensionality, a little like pooling/strided convolutions. They have good illustrations explaining this. For the loss, they use the simple L2 loss from the G network, the adversarial loss from the D network. This alone doesn't give better results that a model with no GAN, so they also use the feature loss generated by the A network. They used the [6] dataset for voices, and [5] for the piano dataset. As metrics, signal-to-noise-ratio (SNR), log-spectral distance (LSD) and mean opinion score (MOS). Good results. A being unsuppervised is on-par to the classifier based loss. [Link](http://bilat.xyz/vita/Adversarial.pdf) ## Time Series Super Resolution with Temporal Adaptive Batch Normalization (TimeSerie_Batch.pdf) [Link](http://bilat.xyz/vita/TimeSerie_Batch.pdf) They want to combine recurent and convolutional, in a new type of layer called "temporal adaptive normalization". This allows the filters to be turned on and off by long range information coming from the recurrent part. Some illustration explain the architecture in more details, but once again it looks like a u-net. Super-resolutation has some spatial invariance, which implies the CNN, but we still might some usefull information furhter away, so the recurrent part can help us with that. Need to look in more details at this layer. They also use the [5] and [6] datasets # Ideas from images ## Perceptual Losses for Real-Time Style Transfer and Super-Resolution (Perceptual_Losses.pdf) [Link](http://bilat.xyz/vita/Perceptual_Losses.pdf) ## The Unreasonable Effectiveness of Deep Features as a Perceptual Metric (Perceptual_Metric.pdf) [Link](http://bilat.xyz/vita/Perceptual_Metric.pdf) ## Fully Convolutional Networks for Semantic Segmentation (FCN.pdf) [Link](http://bilat.xyz/vita/FCN.pdf) # Datasets ## 1: Voice database with noisy and clean version [https://datashare.is.ed.ac.uk/handle/10283/1942](https://datashare.is.ed.ac.uk/handle/10283/1942) ## 2: New version of [1], also voice [https://datashare.is.ed.ac.uk/handle/10283/2791](https://datashare.is.ed.ac.uk/handle/10283/2791) ## 3: Speech database with clean and noisy [https://github.com/dingzeyuli/SpEAR-speech-database](https://github.com/dingzeyuli/SpEAR-speech-database) ## 4: Aurora2 [http://aurora.hsnr.de/aurora-2.html](http://aurora.hsnr.de/aurora-2.html) Some script that can generate noisy data ## 5: Piano dataset Beethoven [https://gist.github.com/moodoki/654877be611ef63bb32d58c428d6e7ba](https://gist.github.com/moodoki/654877be611ef63bb32d58c428d6e7ba) ~350MB, OGG format, bitrate between 96 and 112 kbps ## 6: CSTR VCTK Corpus [https://datashare.is.ed.ac.uk/handle/10283/2651](https://datashare.is.ed.ac.uk/handle/10283/2651) ## 7: Magnatagatune dataset [http://mirg.city.ac.uk/codeapps/the-magnatagatune-dataset](http://mirg.city.ac.uk/codeapps/the-magnatagatune-dataset) 200 hours of music from 188 different gernres. ## 8: Maestro Dataset [https://magenta.tensorflow.org/datasets/maestro](https://magenta.tensorflow.org/datasets/maestro) Piano recording from virtuosic piano performances, ~200 hours in total, available in midi (precisly recorded from the piano, 85MB) or in WAV (122 GB).
JavaScript
UTF-8
1,316
2.875
3
[]
no_license
/** * 一覧表示領域(1行分の表示を含む) * Created by tetsuya.matsuura on 2015/11/10. */ define([ 'backbone', '..//views/ItemView' ], function (Backbone, ItemView) { var ListView = Backbone.View.extend({ // インスタンス生成時に実行 initialize: function () { console.log("[View]ListView::initialize()"); }, render: function () { console.log("[View]ListView::render()" ); // 画面に表示している一覧をクリアする this.$el.html(""); // 表示データが存在する場合に1行ずつレンダリングする if (this.collection) { this.collection.each(function (dvd) { this.append(dvd); }, this); } return this; }, append: function (dvd) { console.log("[View]ListView::append()"); var item_view = (new ItemView({model: dvd, tagName: "tr"})).render(); var index = this.collection.indexOf(dvd); if (index === 0) { this.$el.prepend(item_view.el); } else { item_view.$el.insertAfter(this.$el.children()[index-1]); } } }); return ListView; });
SQL
UTF-8
6,840
3.15625
3
[]
no_license
CREATE TABLE IF NOT EXISTS `department` ( `id` int(50) NOT NULL AUTO_INCREMENT, `depart_code` varchar(4) collate utf8_general_ci NOT NULL, `depart_name` varchar(100) collate utf8_general_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci AUTO_INCREMENT=1 ; CREATE TABLE IF NOT EXISTS `batch` ( `id` int(50) NOT NULL AUTO_INCREMENT, `batch_code` varchar(4) collate utf8_general_ci NOT NULL, `batch_name` varchar(100) collate utf8_general_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci AUTO_INCREMENT=1 ; CREATE TABLE IF NOT EXISTS `programme` ( `id` int(50) NOT NULL AUTO_INCREMENT, `depart_code` varchar(4) collate utf8_general_ci NOT NULL, `programme_code` varchar(4) collate utf8_general_ci NOT NULL, `programme_name` varchar(100) collate utf8_general_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci AUTO_INCREMENT=1 ; CREATE TABLE IF NOT EXISTS `semester` ( `id` int(50) NOT NULL AUTO_INCREMENT, `sem_code` varchar(4) collate utf8_general_ci NOT NULL, `sem_name` varchar(100) collate utf8_general_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci AUTO_INCREMENT=1 ; CREATE TABLE IF NOT EXISTS `syllabus` ( `id` int(50) NOT NULL AUTO_INCREMENT, `course_code` varchar(10) collate utf8_general_ci NOT NULL, `course_name` varchar(100) collate utf8_general_ci NOT NULL, `credit` varchar(3) collate utf8_general_ci NOT NULL, `depart_code` varchar(4) collate utf8_general_ci NOT NULL, `programme_code` varchar(4) collate utf8_general_ci NOT NULL, `sem_code` varchar(4) collate utf8_general_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci AUTO_INCREMENT=1 ; CREATE TABLE IF NOT EXISTS `workload` ( `id` int(50) NOT NULL AUTO_INCREMENT, `faculty_code` varchar(10) collate utf8_general_ci NOT NULL, `depart_code` varchar(4) collate utf8_general_ci NOT NULL, `programme_code` varchar(4) collate utf8_general_ci NOT NULL, `sem_code` varchar(4) collate utf8_general_ci NOT NULL, `course_code` varchar(10) collate utf8_general_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci AUTO_INCREMENT=1 ; CREATE TABLE IF NOT EXISTS `co` ( `id` int(50) NOT NULL AUTO_INCREMENT, `faculty_code` varchar(10) collate utf8_general_ci NOT NULL, `depart_code` varchar(4) collate utf8_general_ci NOT NULL, `programme_code` varchar(4) collate utf8_general_ci NOT NULL, `course_code` varchar(10) collate utf8_general_ci NOT NULL, `co_range` varchar(3) collate utf8_general_ci NOT NULL, `co_outcome` varchar(200) collate utf8_general_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci AUTO_INCREMENT=1 ; CREATE TABLE IF NOT EXISTS `po` ( `id` int(50) NOT NULL AUTO_INCREMENT, `faculty_code` varchar(10) collate utf8_general_ci NOT NULL, `depart_code` varchar(4) collate utf8_general_ci NOT NULL, `programme_code` varchar(4) collate utf8_general_ci NOT NULL, `po_code` varchar(3) collate utf8_general_ci NOT NULL, `po_outcome` varchar(500) collate utf8_general_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci AUTO_INCREMENT=1 ; CREATE TABLE IF NOT EXISTS `peo` ( `id` int(50) NOT NULL AUTO_INCREMENT, `faculty_code` varchar(10) collate utf8_general_ci NOT NULL, `depart_code` varchar(4) collate utf8_general_ci NOT NULL, `programme_code` varchar(4) collate utf8_general_ci NOT NULL, `peo_code` varchar(3) collate utf8_general_ci NOT NULL, `peo_desc` varchar(500) collate utf8_general_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci AUTO_INCREMENT=1 ; /* Course Delivery Plan */ CREATE TABLE IF NOT EXISTS `cdp` ( `id` int(50) NOT NULL AUTO_INCREMENT, `faculty_code` varchar(10) collate utf8_general_ci NOT NULL, `depart_code` varchar(4) collate utf8_general_ci NOT NULL, `programme_code` varchar(4) collate utf8_general_ci NOT NULL, `semester_code` varchar(4) collate utf8_general_ci NOT NULL, `course_code` varchar(10) collate utf8_general_ci NOT NULL, `period` varchar(3) collate utf8_general_ci NOT NULL, `topic` varchar(200) collate utf8_general_ci NOT NULL, `pertaining_co` varchar(3) collate utf8_general_ci NOT NULL, `pertaining_btl` varchar(3) collate utf8_general_ci NOT NULL, `tlo` varchar(200) collate utf8_general_ci NOT NULL, `method_activity` varchar(100) collate utf8_general_ci NOT NULL, `assessment_tlo` varchar(200) collate utf8_general_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci AUTO_INCREMENT=1 ; /* QP Setting */ CREATE TABLE IF NOT EXISTS `qp_set` ( `id` int(50) NOT NULL AUTO_INCREMENT, `faculty_code` varchar(10) collate utf8_general_ci NOT NULL, `depart_code` varchar(4) collate utf8_general_ci NOT NULL, `programme_code` varchar(4) collate utf8_general_ci NOT NULL, `semester_code` varchar(4) collate utf8_general_ci NOT NULL, `course_code` varchar(10) collate utf8_general_ci NOT NULL, `assesmenttype_code` varchar(3) collate utf8_general_ci NOT NULL, `qes_no` varchar(3) collate utf8_general_ci NOT NULL, `co_code` varchar(3) collate utf8_general_ci NOT NULL, `btl_code` varchar(3) collate utf8_general_ci NOT NULL, `max_mark` varchar(3) collate utf8_general_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci AUTO_INCREMENT=1 ; /* Mark Entry */ CREATE TABLE IF NOT EXISTS `mark_entry` ( `id` int(50) NOT NULL AUTO_INCREMENT, `faculty_code` varchar(10) collate utf8_general_ci NOT NULL, `depart_code` varchar(4) collate utf8_general_ci NOT NULL, `programme_code` varchar(4) collate utf8_general_ci NOT NULL, `batch_code` varchar(4) collate utf8_general_ci NOT NULL, `semester_code` varchar(4) collate utf8_general_ci NOT NULL, `course_code` varchar(10) collate utf8_general_ci NOT NULL, `assesmenttype_code` varchar(3) collate utf8_general_ci NOT NULL, `student_code` varchar(15) collate utf8_general_ci NOT NULL, `qes_no` varchar(3) collate utf8_general_ci NOT NULL, `co_code` varchar(3) collate utf8_general_ci NOT NULL, `btl_code` varchar(3) collate utf8_general_ci NOT NULL, `max_alloted` varchar(3) collate utf8_general_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci AUTO_INCREMENT=1 ;
Java
UTF-8
136
1.585938
2
[ "Apache-2.0" ]
permissive
package org.tain.mybatis.service; import org.tain.mybatis.vo.UsrVo; public interface MainService { public UsrVo getUsr(); }
Python
UTF-8
515
2.65625
3
[]
no_license
import unittest from time import sleep from Eternal_Utils.Timer import Timer class TestTimer(unittest.TestCase): def test___enter__(self): timer = Timer() self.assertIsNotNone(timer.__enter__().start) def test___exit__(self): timer = Timer(True) timer.__enter__() sleep(0.5) timer.__exit__() self.assertEqual(0, int(timer.secs)) def test___init__(self): assert True if __name__ == '__main__': # pragma: no cover unittest.main()
Java
UTF-8
2,878
2.5625
3
[]
no_license
package com.example.spreadtrumshitaoli.threaddemo; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.View; import android.widget.Button; import static com.example.spreadtrumshitaoli.threaddemo.MainActivity.TAG; /** * Created by SPREADTRUM\shitao.li on 18-3-29. */ public class StartThread extends Activity { private Button mButtonThread; private Button mButtonRunnable; private Button mButtonHandler; private Handler mHandler; private Runnable runnable; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.start_thread); mButtonThread = (Button) findViewById(R.id.bt_thread); mButtonThread.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startThread(); } }); mButtonRunnable = (Button) findViewById(R.id.bt_runnable); mButtonRunnable.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startRunnable(); } }); mButtonHandler = (Button) findViewById(R.id.bt_handler); mButtonHandler.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startHandler(); } }); } private void startThread() { new Thread() { int i =0; @Override public void run() { // super.run(); while (i++<10) { Log.d(TAG,"Use Thread run now! "+i + "Tid: "+ Thread.currentThread().getId()); } } }.start(); } private void startRunnable() { new Thread( new Runnable() { int i = 0; @Override public void run() { while (i++<10) { Log.d(TAG,"Use Runnable run now! "+i+ "Tid: "+ Thread.currentThread().getId()); } } } ).start(); } private void startHandler() { //this is in main thread. better for handler--looper--message. mHandler = new Handler(getMainLooper()); runnable = new Runnable() { int i = 0; @Override public void run() { while (i++<10) Log.d(TAG,"Use Handler run now! "+i+ "Tid: "+ Thread.currentThread().getId()); } }; mHandler.post(runnable); } @Override protected void onDestroy() { super.onDestroy(); mHandler.removeCallbacks(runnable); } }
JavaScript
UTF-8
4,486
2.640625
3
[ "MIT" ]
permissive
'use strict'; const knex = require('../db'); const moment = require('moment'); const tableName = 'journalentries'; const entryTypes = [ 'note', // User created 'warning', // System created warning 'chore', // System created info message ]; const Journal = { createEntry: function(user_id, type, entry, time, sensor_id, chore_id) { return new Promise((resolve, reject) => { if (entryTypes.indexOf(type) === -1) { throw new Error(`Unknown type for journal entry: ${type}`); } knex(tableName).insert({user_id, type, entry, time, sensor_id, chore_id}).returning('id') .then(rows => resolve(rows[0])); }); }, getLatestEntries: function(user_id, entryCount) { return knex(tableName) .select() .where({ user_id: user_id }) .orderBy('created_at', 'desc') .limit(entryCount) .then(rows => { return Promise.resolve(rows); }); }, getRelevantEntries: function(user_id, entryCount) { // Get all unfinished chores in the past // and in the next 30 days return knex(tableName) .select() .where({ user_id, done: false, }) .andWhereNot('chore_id', null) .limit(entryCount) .then(chores => { const choreCount = chores.length; const fillCount = entryCount - choreCount; return knex(tableName) .select() .where({ user_id, }) .limit(fillCount) .then(fillEntries => { return Promise.resolve(chores.concat(fillEntries)); }); }); }, getEntriesForRange: function(user_id, rangeBegin, rangeEnd) { if (moment.isMoment(rangeBegin)) { rangeBegin = rangeBegin.toISOString(); } if (moment.isMoment(rangeEnd)) { rangeEnd = rangeEnd.toISOString(); } return knex(tableName) .select() .whereBetween('time', [rangeBegin, rangeEnd]) .where({ user_id: user_id, }) .orderBy('created_at', 'desc') .then(rows => { if (rows.length > 0) { return Promise.resolve(rows); } return Promise.resolve([]); }); }, getEntriesForSensorAndRange: function(user_id, sensor_id, rangeBegin, rangeEnd) { if (moment.isMoment(rangeBegin)) { rangeBegin = rangeBegin.toISOString(); } if (moment.isMoment(rangeEnd)) { rangeEnd = rangeEnd.toISOString(); } return knex(tableName) .select() .whereBetween('time', [rangeBegin, rangeEnd]) .where({ user_id, sensor_id }) .orderBy('created_at', 'desc') .then(rows => { if (rows.length > 0) { return Promise.resolve(rows); } return Promise.resolve([]); }); }, getEntriesForChores: function(user_id) { return knex(tableName) .select() .where({ user_id, }) .andWhereNot('chore_id', null) .then(rows => Promise.resolve(rows)); }, getPendingEntriesForChoreList: function(user_id, chores) { return knex(tableName) .select() .whereIn('chore_id', chores) .andWhere({ user_id, done: false, }) .then(rows => Promise.resolve(rows)); }, removeEntry: function(user_id, entry_id) { return knex(tableName) .where({ user_id, id: entry_id, }) .del(); }, setEntryDone: function(user_id, entry_id) { return knex(tableName) .where({ user_id, id: entry_id, }) .update({ done: true, }) .then(updatedEntries => Promise.resolve(updatedEntries)); // Return the amount of updated entries }, }; module.exports = Journal;
C++
UTF-8
1,345
3.140625
3
[]
no_license
#ifndef NODODOBLE_H #define NODODOBLE_H #include <iostream> using namespace std; template <class T> class NodoDoble{ private: T elemento; NodoDoble<T>* izq; NodoDoble<T>* der; int FE; public: NodoDoble(T elemento); NodoDoble(NodoDoble<T>* a,T elemento,NodoDoble<T>* d); void setDato(T a); void setIzq(NodoDoble<T>* a); void setDer(NodoDoble<T>* a); void setFE(int a); int getFE(); T getDato(); NodoDoble<T>* getIzq(); NodoDoble<T>* getDer(); }; template <class T> NodoDoble<T>::NodoDoble(T elemento){ this->elemento=elemento; der=izq=NULL;} template <class T> NodoDoble<T>::NodoDoble(NodoDoble<T>* a,T elemento,NodoDoble<T>* d){ this->elemento=elemento; der=d; izq=a;} template <class T> T NodoDoble<T>::getDato(){ return elemento;} template <class T> void NodoDoble<T>::setDato(T a){ elemento=a; } template <class T> NodoDoble<T>* NodoDoble<T>::getDer(){ return der;} template <class T> NodoDoble<T>* NodoDoble<T>::getIzq(){ return izq;} template <class T> void NodoDoble<T>::setDer(NodoDoble<T>* a){ der=a;} template <class T> void NodoDoble<T>::setIzq(NodoDoble<T>* a){ izq=a;} template <class T> void NodoDoble<T>::setFE(int a){ FE=a; } template <class T> int NodoDoble<T>::getFE(){ return FE; } #endif // NODODOBLE_H
Java
UTF-8
1,849
2.734375
3
[]
no_license
package lp.model.pathfinder.a_star; import lp.model.position.Apex; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import static java.lang.String.format; public class AStarNode implements Comparable<AStarNode> { @NotNull private final Integer heuristicValue; @NotNull private Integer movementCost; @Nullable private Apex parentPosition; @NotNull private final Apex nodePosition; public AStarNode(@NotNull Integer heuristicValue, @NotNull final Apex nodePosition, @Nullable Apex parentPosition) { this.heuristicValue = heuristicValue; this.parentPosition = parentPosition; this.nodePosition = nodePosition; movementCost = 0; } @NotNull public Integer getHeuristicValue() { return heuristicValue; } public void reparent(@Nullable final Apex parentPosition) { this.parentPosition = parentPosition; } @NotNull public Integer getMovementCost() { return movementCost; } public void addMovementCost(@NotNull Integer movementCost) { this.movementCost += movementCost; } @Nullable public Apex getParentPosition() { return parentPosition; } @NotNull public Apex getApexPosition() { return nodePosition; } @NotNull public Integer getOverallCost() { return movementCost + heuristicValue; } @Override public int compareTo(@NotNull AStarNode o) { return this.getOverallCost().compareTo(o.getOverallCost()); } // @Override // public int compare(AStarNode first, AStarNode second) { // // return first.getOverallCost() - second.getOverallCost(); // } @Override public String toString() { return format("AStarTile{heuristicValue=%d, movementCost=%d, parentPosition=%s, nodePosition=%s}\n", heuristicValue, movementCost, parentPosition, nodePosition); } }
Markdown
UTF-8
6,232
2.765625
3
[ "MulanPSL-2.0", "LicenseRef-scancode-mulanpsl-2.0-en", "LicenseRef-scancode-unknown-license-reference" ]
permissive
--- --- --- title: 第九百一十八夜 --- 夜幕降临,莎赫札德接着讲故事: 幸福的国王陛下,当宫仆刚抬脚进御膳房门时,舍马斯宰相走上前去对宫仆说:“孩子,老夫我想见国王一面,有要事向国王禀报。等国王吃罢午饭,心情好时,劳你代我求见国王,但愿国王允许我晋见,以便当面禀报要事。” “我一定照办!”宫仆说。宫仆端着午膳给国王送去。 沃尔德汗国王用过午饭,情绪甚好,宫仆说:“国王陛下,舍马斯宰相在门外站着求见,说有要事禀报。” 国王听后一惊,不知禀报何事,随口对宫仆说:“让他进来吧!” 舍马斯宰相听说国王让他进来,心中甚为高兴,遂迈步朝国王的后宫走去。舍马斯宰相来到国王面前,行过礼,亲吻国王的手,继之一番祝福。 沃尔德汗国王问:“相爷阁下,有什么要事禀报呀?” 舍马斯宰相说:“好久不见陛下的面了,心里十分想念陛下,现在好容易才见到了。国王陛下,臣有要事禀报啊!” “有什么事,你就说吧!” “国王陛下,安拉至仁至慈,在你年纪尚幼小时,就已经赋予你渊博知识和深奥哲理,那也是在你之前的君王所不曾得到的。后来,安拉终于把王位赐予给了陛下。国王陛下,不希望你违背他的命令,而把授予你的王权转交给其他人。安拉也不希望你用自己的财宝进行反对安拉的活动,而希望你牢牢记住安拉的嘱托,服从安拉的命令。国王陛下,这些日子以来,我觉察到你把先王及其叮嘱忘到脑后去了,因为你拒绝执行先王的遗嘱,弃绝了先王的公正,拒不感谢安拉对你的恩赐……” 舍马斯宰相未说完,沃尔德汗国王惊问:“怎么回事?原因在哪里?” “原因在于你不关心国事,不问朝政,忘记了伟大安拉已把臣民的生计大事托付给了你,而你一心贪图享受今世的荣华富贵。古谚说得对:‘世有三事,君王必牢记:一曰,国家利益;二曰,宗教利益;三曰,百姓生计。’国王陛下,依臣之见,陛下理应考虑事情后果,方能找到得救一路,千万不可沉湎于导致死亡的享乐之中。不然,难免有渔夫那种遭遇。” 沃尔德汗国王惊问:“渔夫有什么遭遇?” 舍马斯宰相开始讲《渔夫与大鱼的故事》。 相传,很久很久以前,有一位渔夫。有一天,渔夫像往常一样来到河边打鱼。渔夫刚一上桥,便看见水中游着一条大鱼,心想:“我为什么不去抓那条大鱼……我要追上去,它游到哪里,我就追到哪里,抓着这条大鱼,也就可以安享几天清福了。” 想到这里,渔夫马上脱下衣服,下到河中追那条大鱼去了。渔夫顺水流而下,费了好大力气,终于抓住了那条大鱼。此时此刻,他回头望去,发现自己已远离岸边。他紧紧抓住那条鱼,随着河水的急流漂游而下,眼见自己的身子被湍急的水流带进了大漩涡,那是落进去就难以活命的地方。这时,渔夫才大声求救:“救命啊!救命啊!” 一群护河人赶来,问道:“你怎么啦?你为什么冒这种巨大危险呢?” 渔夫说:“我是自己脱离了得救正道,自找死路,自取灭亡啊!” 众人说:“喂,落水人,你早就知道这里有漩涡,是九死一生之地,为什么抛弃得救正道,而自踏死路呢?为什么还不甩掉手里的鱼,赶快逃命呢?现在谁也救不了你啦!” 渔夫绝了生还的希望,急忙甩掉冒着生命危险抓住的那条大鱼,然而为时已晚,顷刻间被漩涡吞没,一命呜呼了。 舍马斯宰相讲完故事,对沃尔德汗国王说:“国王陛下,我为陛下讲这个故事,只是为了让陛下放弃眼前影响陛下大业的卑微的小事,着眼于你所肩负的国民生计的大任,集中精力,治国安邦,振兴大业,不让任何人看到你出丑。” 沃尔德汗国王问:“相爷阁下有何见教啊?” 舍马斯宰相说:“明天,如果陛下身体和精神都好,就请允许大臣来晋见,听听他们说说自己的处境,向他们表示一下歉意,然后答应多为他们的事情操心。” 国王说:“相爷说得对,我明天一定照你的意见办。安拉护佑。” 舍马斯宰相离开国王那里,见到群臣,将晋见国王的情况告诉了他们。第二天早晨,沃尔德汗国王走出幕帘,准许大臣晋见。国王见到大臣们,表示歉意后,答应按照他们的要求行事。众臣听后,个个欢喜,人人满意,高高兴兴地回去了。 群臣走后,沃尔德汗国王的一位爱妃走到国王面前。爱妃见国王面色灰暗,低着头不说话,便问:“陛下何故心神不安?有什么不舒服吗?” 沃尔德汗国王说:“没有不舒服。我正在考虑自己的事情。我为什么不珍视自己的王权和臣民呢?长此以往,过不了多久,我的王权就要失去了。” 爱妃说:“陛下,我看你是被你的仆役和大臣们骗了。他们纯粹是故意惹你生气,有意不愿让你享受这人生乐趣,不让你得到宽舒、清闲和自在,而是想让你忙碌一生,要你在为改善他们处境的事物中丧生,或者就像童子与盗贼之间发生的事情一样。” 国王惊问:“童子与盗贼之间发生过什么事?” 爱妃开始给国王讲《童子与盗贼的故事》。 相传,很久很久以前,有七个盗贼。一天,七个盗贼照习惯外出偷盗。他们路过一个果园,见树上结满核桃,便闯进园门。 七个盗贼刚进园门,忽见一童子出现在他们面前。盗贼们对童子说:“喂,小孩子,和我们一道进核桃林去吧!我们把你托上树去,先吃饱肚子,再给我们丢下几个核桃来,好吗?” 童子一口答应,随他们进了核桃树林。 讲到这里,眼见东方透出了黎明的曙光,莎赫札德戛然止声。
TypeScript
UTF-8
1,018
3.703125
4
[ "MIT" ]
permissive
interface People { [name: string]: string; } function range(num: number): number[] { return [...Array(num).keys()]; } function shuffle(array: any[]): void { let m = array.length; let i: number; let t: any; while (m) { i = Math.floor(Math.random() * m--); t = array[m]; array[m] = array[i]; array[i] = t; } } export function goodAssignments(indices: number[]): boolean { for (let i = 0; i < indices.length; i++) if (i === indices[i]) return false; return true; } export function getRandomAssignments(numPeople: number): number[] { let indices = range(numPeople); shuffle(indices); while (!goodAssignments(indices)) shuffle(indices); return indices; } export function assignPeople(names: string[]): People { const indices = getRandomAssignments(names.length); let people: People = {}; for (let i = 0; i < names.length; i++) people[names[i]] = names[indices[i]]; return people; }
C++
UTF-8
4,468
2.84375
3
[]
no_license
#include "obstacle.hpp" #include <iostream> using namespace std; Obstacle::Obstacle(const sf::Vector2u &windowSize) : mWindowSize(windowSize) { if (!mObsTextureMap[NINV].loadFromFile("./Assets/sprites/pipe-green.png")) { //error exit(0); } if (!mObsTextureMap[INV].loadFromFile("./Assets/sprites/pipe-green-inverted.png")) { //error exit(0); } cout << "obstacle.cpp - here" << endl; } // make new obs after the genDuration // move the obs by some moving speed. void Obstacle::updateObs(float dt, float baseHeight) { mCurrDuration += dt; // new obstacles making part. if (mIsThisInitialTime && mCurrDuration >= mInitialWaitingTime) { // now after this part, the initial obstacle is made, // so initial part = false; mIsThisInitialTime = false; mCurrDuration = 0.0f; createNewObstacle(baseHeight); } if (!mIsThisInitialTime && mCurrDuration >= mGenDuration) { mCurrDuration = 0.0f; createNewObstacle(baseHeight); } // new obstacle making part ends. // update the position of obstacles or delete if out of screen for (int i = 0; i < mObstacles.size(); i++) { if (mObstacles[i][0].sprite.getPosition().x + mObsTextureMap[NINV].getSize().x * mObstacles[i][0].sprite.getScale().x <= 0) { // case when obstacle goes out of screen after moving mObstacles.erase(mObstacles.begin() + i); } else { mObstacles[i][0].sprite.move(-mSpeed * dt, 0.0f); mObstacles[i][1].sprite.move(-mSpeed * dt, 0.0f); } } // DIFFICULTY INCREASING ZONE AS USER PLAYS MORE AND MORE TIME. // mGenDuration -= mGenDuration * 0.0007 * dt; // mSpeed += mSpeed * 5 * dt; pipeHeight -= pipeHeight * dt * dt; } Obstacle::~Obstacle() {} void Obstacle::draw(sf::RenderTarget &target, sf::RenderStates states) const { for (int i = 0; i < mObstacles.size(); i++) { target.draw(mObstacles[i][0].sprite, states); target.draw(mObstacles[i][1].sprite, states); } } void Obstacle::createNewObstacle(float baseHeight) { // 0 = non-inverted, 1 = inverted. std::vector<Obstacle::Pipe> obs(2); // range for the height of obstacle. sf::Vector2f range1(mWindowSize.y / 2.0 + 80, mWindowSize.y / 2.0 + 180); sf::Vector2f range2(mWindowSize.y / 2.0 - 80, mWindowSize.y / 2.0 - 180); std::vector<sf::Vector2f> ranges{range1, range2}; obs[0].sprite.setTexture(mObsTextureMap[NINV]); obs[1].sprite.setTexture(mObsTextureMap[INV]); obs[1].sprite.setOrigin(0, mObsTextureMap[INV].getSize().y); for (int i = 0; i < obs.size(); ++i) { obs[i].sprite.setPosition(mWindowSize.x, Random::get(ranges[i].x, ranges[i].y)); obs[i].sprite.setScale(2.0f, 1.0f); } //randomly overriding the position of one of the pipes by fixing other // just a block scope made int num = Random::get({0, 1}); if (num == 1) { // overriding the inverted pipe position to be according to the pipe height obs[1].sprite.setPosition(mWindowSize.x, obs[0].sprite.getPosition().y - pipeHeight); if (obs[1].sprite.getPosition().y > mObsTextureMap[INV].getSize().y) { // scale inverted pipe in the y direction so that the upper part is not // shown empty as the pipe is lower in position than its size obs[1].sprite.scale(1.0f, obs[1].sprite.getPosition().y / mObsTextureMap[INV].getSize().y); } } else { // overriding the non-inverted pipe position to be according to the pipe height obs[0].sprite.setPosition(mWindowSize.x, obs[1].sprite.getPosition().y + pipeHeight); if (mWindowSize.y - obs[0].sprite.getPosition().y > mObsTextureMap[NINV].getSize().y + baseHeight) { // scale inverted pipe in the y direction so that the upper part is not // shown empty as the pipe is lower in position than its size obs[0].sprite.scale(1.0f, (mWindowSize.y - obs[0].sprite.getPosition().y - baseHeight) / mObsTextureMap[NINV].getSize().y); } } // obs[0].sprite.setTextureRect(sf::IntRect(0, 0, mObsTextureMap[NINV].getSize().x, mWindowSize.y - obs[0].sprite.getPosition().y - baseHeight)); mObstacles.push_back(obs); } Obstacle::ObstacleType &Obstacle::getObstacles() { return mObstacles; }
Markdown
UTF-8
15,859
2.5625
3
[]
no_license
[![Release](https://jitpack.io/v/Jagerfield/Android-Utilities-Library.svg)](https://jitpack.io/#Jagerfield/Android-Utilities-Library) [![Downloads](https://jitpack.io/v/Jagerfield/Android-Utilities-Library.svg/month.svg)](#download) # Android Utilities Library While developing Andorid apps, I gathered the functions that I repeatedly used and kept them in a utility class. The number of these functions grew, in addition there was need to manage the “Permissions” in a clean easy way. Therefore, I created a library which currently provides the following utilities: **Permissions**, **Memory**, **Battery**, **Device Info**, **Network**, **SoftKeyboard**. * The Permissions utility can be used for SDK versions 15-25 check. * If the SDK version is < 23, then it will check for the existance of the permission in the Manifest. * The library utilities' functions will return the name of the missing permission. The images below are taken from running the app on a simulator. <img src="https://github.com/Jagerfield/Android-Utilities-Library/blob/master/msc/pictures/utilities/permissions.png" width="160"/> &#160; <img src="https://github.com/Jagerfield/Android-Utilities-Library/blob/master/msc/pictures/utilities/memory.png" width="160"/> &#160; <img src="https://github.com/Jagerfield/Android-Utilities-Library/blob/master/msc/pictures/utilities/network.png" width="160"/> &#160; <img src="https://github.com/Jagerfield/Android-Utilities-Library/blob/master/msc/pictures/utilities/device.png" width="160"/> &#160; <img src="https://github.com/Jagerfield/Android-Utilities-Library/blob/master/msc/pictures/utilities/battery.png" width="160"/> The sample app for **Android Utilities Library** is available on Google Play: <a href='https://play.google.com/store/apps/details?id=jagerfield.utilities'><img alt='Get it on Google Play' src='https://play.google.com/intl/en_us/badges/images/generic/en_badge_web_generic.png' width="193" height="75"/></a> ## Library Installation In the app build.gradle add the following: Add JitPack repository at the end of repositories ``` repositories { maven { url 'https://jitpack.io' } } ``` Add the following dependency ``` dependencies { compile ('com.github.Jagerfield:Android-Utilities-Library:v3.0') { exclude group: 'com.android.support' } } ``` ##Checking Permissions To test the Permissions utility: ``` 1. Image 1 a.In Settings->Apps->Android Utilities->App info->Permissions turn all the permission switches off. 2. Image 2-3 a.In the first tab "Permissions". b.Click on "Check Permissions" button. c.And deny all permissions. 3. Image 4 a.Click on "Get" button. b.Deny the first two permissions. c.For the last two permissions, check the boxes "Never Show Again", then deny them. 4. Image 5 a.Click on "Get" button, and accept the two permissions showing in the denied permissions section. 5. Image 5 a.Click then on the "Settings" button. 6. Image 6 a.Go to the app permissions, switch all permissions on. 7. Image 7 a.Click on "Check Permissions" button and check the final status. ``` <img src="https://github.com/Jagerfield/Android-Utilities-Library/blob/master/msc/pictures/permissions/1.png" width="160"/> &#160; <img src="https://github.com/Jagerfield/Android-Utilities-Library/blob/master/msc/pictures/permissions/2.png" width="160"/> &#160; <img src="https://github.com/Jagerfield/Android-Utilities-Library/blob/master/msc/pictures/permissions/3.png" width="160"/> &#160; <img src="https://github.com/Jagerfield/Android-Utilities-Library/blob/master/msc/pictures/permissions/4.png" width="160"/> &#160; <img src="https://github.com/Jagerfield/Android-Utilities-Library/blob/master/msc/pictures/permissions/5.png" width="160"/> &#160; <img src="https://github.com/Jagerfield/Android-Utilities-Library/blob/master/msc/pictures/permissions/6.png" width="160"/> &#160; <img src="https://github.com/Jagerfield/Android-Utilities-Library/blob/master/msc/pictures/permissions/7.png" width="160"/> ##Permissions Util PermissionsUtil contains the following functions: | Value | Function's Name | Returns | | :--------- |:-------------- | :------- | | Permissions Request Code Id | ``` getPermissionsReqCodeId() ```| int | | Request Permissions | ``` requestPermissions(String permissionsItem) ```| void | | Request Permissions | ``` requestPermissions(String[] permissionsArray) ```| void | | Is Permission Granted | ``` isPermissionGranted(String permission) ```| IGetPermissionResult | | Permission Results | ``` getPermissionResults(String permissionItem) ```| IGetPermissionResult | | Permission Results | ``` getPermissionResults(String[] permissionsArray) ```| IGetPermissionResult | IGetPermissionResult contains the following functions: | Value | Function's Name | Returns | | :--------- |:-------------- | :------- | | Is Granted | ``` isGranted() ```| boolean | | Granted Permissions List | ``` getGrantedPermissionsList() ```| ArrayList<String> | | UserDenied Permissions List | ``` getUserDeniedPermissionsList() ```| ArrayList<String> | | Never Ask Again Permissions List | ``` getNeverAskAgainPermissionsList() ```| ArrayList<String> | | List of Manifest Missing Permissions Sdk less M | ``` getMissingInManifest_ForSdkBelowM() ```| ArrayList<String> | | Requested Permission Status | ``` getRequestedPermissionStatus(String permissionName) ```| String | | Requested Permissions And StatusMap | ``` getRequestedPermissionsAndStatusMap() ```| HashMap<String, String> | ### Managing permissions - First, check the status of your app permissions. The functions (getPermissionResults) and (requestPermissions) can either take an array or a string as an argument. ``` PermissionsUtil permissionsUtil = AppUtilities.getPermissionUtil(activity); IGetPermissionResult result = permissionsUtil.getPermissionResults(PERMISSIONS_ARRAY); if (result.isGranted()) { //Add your code here } else if (!result.isGranted() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { //There are missing permissions ask for them permissionsUtil.requestPermissions(PERMISSIONS_ARRAY); } else if (!result.isGranted() && Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { //For SDK less than M, there are permissions missing in the manifest String missingPermissions = TextUtils.join(", ", result.getMissingInManifest_ForSdkBelowM()).trim(); Toast.makeText(activity, "Following permissions are missing : " + missingPermissions, Toast.LENGTH_LONG).show(); Log.e(C.TAG_LIB, "Following permissions are missing : " + missingPermissions); } ``` - The function (requestPermissions) in the previous paragraph will call the (checkSelfPermission), and the user will get to choose to accept or deny permissions. The system will then make a callback in (onRequestPermissionsResult) in the MainActivity. ``` @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { PermissionsUtil permissionsUtil = AppUtilities.getPermissionUtil(activity); if (requestCode == permissionsUtil.getPermissionsReqCodeId()) { IGetPermissionResult result = null; result = permissionsUtil.getPermissionResults(permissions); if (result == null) { return; } if (result.isGranted()) { //Add your code here } else { //Write your code here //For SDK >= M, there are permissions missing and you can get them. String deniedPermissions = TextUtils.join(", ", result.getUserDeniedPermissionsList()).trim(); String neverAskAgainPermissions = TextUtils.join(", ", result.getNeverAskAgainPermissionsList()).trim(); } } } ``` - For SDK >= M, if you want to let the library to show the user a dialog to manage missing permissions, then use this code: ``` @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { PermissionsUtil permissionsUtil = AppUtilities.getPermissionUtil(this); if (requestCode == permissionsUtil.getPermissionsReqCodeId()) { IGetPermissionResult result = null; result = permissionsUtil.getPermissionResults(permissions); if (result.isGranted()) { //Write your code here return; } PermissionsManager.getNewInstance(this, result, permissions, new PermissionsManager.PermissionsManagerCallback() { @Override public void onPermissionsGranted(IGetPermissionResult result) { /** * User accepted all requested permissions */ //Write your code here } @Override public void onPermissionsMissing(IGetPermissionResult result) { //Write your code here Toast.makeText(MainActivity.this, "User didn't accept all permissions", Toast.LENGTH_LONG).show(); } }); } } ``` ##Memory Util Accessing a utility fucntion example: ``` AppUtilities.getMemoryUtil().getTotalRAM(); ``` Available functions: | Value | Function's Name | Returns | | :------------- |:-------------| :-----| | Total RAM | ```getTotalRAM()```| long | | Available External Memory Size | ```getAvailableExternalMemorySize()``` | long | | Has External SD Card | ```isHasExternalSDCard()``` | boolean | | Available Internal Memory Size | ```getAvailableInternalMemorySize()``` | long | | Total Internal Memory Size | ```getTotalInternalMemorySize()``` | long | | Total External Memory Size | ```getTotalExternalMemorySize()``` | String | ##Battery Util Accessing a utility fucntion example: ``` AppUtilities.getBatteryUtil().isBatteryPresent(); ``` Available functions: | Value | Function Name | Returns | | :------------- |:-------------| :-----| | Is Battery Present |```isBatteryPresent()``` | boolean | | Battery Temperature | ```getBatteryTemperature()``` | float | | Battery Percent | ```getBatteryPercent()``` | int | | Is Phone Charging | ```isPhoneCharging()``` | boolean | | Battery Health | ```getBatteryHealth()``` | String | | Battery Voltage |```getBatteryVoltage()``` | int | | Charging Source | ```getChargingSource()``` | String | | Battery Technology | ```getBatteryTechnology()``` | String | ##Device Info Util Accessing a utility fucntion example: ``` AppUtilities.getDeviceUtil().getDeviceName(); ``` Available functions: | Value | Function Name | Returns | | :------------- |:-------------| :-----| | Device Name | ```getDeviceName()``` | String | | Version Name | ```getVersionName(activity)``` | String | | Serial Number| ```getSerial()``` | String | | Sdk Version | ```getSdkVersion()``` | int | | Is Running On Emulator | ```isRunningOnEmulator()``` | boolean | | Release Build Version | ```getReleaseBuildVersion()``` | String | | Package Name | ```getPackageName(activity)``` | String | | Build Version Code Name| ```getBuildVersionCodeName``` | String | | Manufacturer | ```getManufacturer()``` | String | | Model | ```getModel()``` | String | | Product | ```getProduct()``` | String | | Finger print | ```getFingerprint()``` | String | | Hardware | ```getHardware()``` | String | | RadioVer | ```getRadioVer()``` | String | | Device | ```getDevice()``` | String | | Board | ```getBoard()``` | String | | Display Version | ```getDisplayVersion()``` | String | | Build Host | ```getBuildHost()``` | String | | Build Time | ```getBuildTime()``` | long | | Build User | ```getBuildUser()``` | String | | OS Version | ```getOsVersion()``` | String | | Language | ```getLanguage()``` | String | | Screen Density | ```getScreenDensity(activity)``` | String | | Screen Height | ```getScreenHeight(activity)``` | int | | Screen Width | ```getScreenWidth(activity)``` | int | | Version Code | ```getVersionCode(activity)``` | Integer | | Activity Name | ```getActivityName(activity)``` | String | | App Name | ```getAppName(activity)``` | String | | Device Ringer Mode | ```getDeviceRingerMode(activity)``` | String | | Is Device Rooted | ```isDeviceRooted()``` | boolean | | Android Id | ```getAndroidId(activity)``` | String | | Installation Source | ```getInstallSource(activity)``` | String | | User Agent | ```getUserAgent(activity)``` | String | | GSF Id | ```getDeviceUtil().getGSFId(activity)``` | String | ##Network Util Accessing a utility fucntion example: ``` AppUtilities.getDeviceUtil().getDeviceName(); ``` Available functions: | Value | Function Name | Returns | | :------------- |:-------------| :-----| | IMEI | ```getIMEI(activity)``` | String | | IMSI | ```getIMSI(activity)``` | String | | Phone Type | ```getPhoneType(activity)``` | String | | Phone Number | ```getPhoneNumber(activity)``` | String | | Operator | ```getOperator(activity)``` | String | | SIM Serial | ```getsIMSerial(activity)``` | String | | Is SIM Locked | ```isSimNetworkLocked(activity)``` | boolean | | Is Wifi Enabled | ```isWifiEnabled(activity)``` | boolean | | Network Class | ```getNetworkClass(activity)``` | String | | Is Nfc Present | ```isNfcPresent(activity)``` | boolean | | Is Nfc Enabled | ```isNfcEnabled(activity)``` | boolean | | Internet Connection Type | ```getInternetConnectionType(activity)``` | String | | Has Internet Connection | ```hasInternetConnection(activity)``` | boolean | | Bluetooth MAC | ```getBluetoothMAC(activity)``` | String | | Wifi Mac Address | ```getWifiMacAddress(activity)``` | String | ##SoftKeyborad Util Accessing a utility fucntion example: ``` AppUtilities.setSoftKeyboard(Activity activity, boolean mode); ``` Available functions: | Value | Function Name | Returns | | :------------- |:-------------| :-----| | Set Soft Keyboard | ```setSoftKeyboard(Activity activity, boolean mode)``` | void | ## How to use? The library's utilities can be either accessed individually, examples: ``` NetworkUtil networkUtil = NetworkUtil.newInstance(activity); MemoryUtil memoryUtil = MemoryUtil.newInstance(activity); ``` Or through the "AppUtilities" class which serves as a container for for the utilities. ``` public class AppUtilities { public static void getSoftKeyboard() { SoftKeyboardUtil.newInstance(); } public static PermissionsUtil getPermissionUtil(Activity activity) { return PermissionsUtil.newInstance(activity);} public static NetworkUtil getNetworkUtil() { return NetworkUtil.newInstance(); } public static MemoryUtil getMemoryUtil() { return MemoryUtil.newInstance(); } public static DeviceUtil getDeviceUtil() { return DeviceUtil.newInstance(); } public static BatteryUtil getDBatteryUtil() { return BatteryUtil.newInstance(); } } ``` ## Privacy Policy This app sample will request the follwoing permissions below which require user approval and are used for demonstration purposes only. No data is shared or used outside this app. * WRITE_EXTERNAL_STORAGE * BODY_SENSORS * READ_PHONE_STATE * ACCESS_COARSE_LOCATION Additionaly, utilities in this library require a number of permissions. These permissions are mentioned in the Manifest file and don't need user approval: * ACCESS_NETWORK_STATE * BLUETOOTH * ACCESS_WIFI_STATE * READ_GSERVICES
Java
UTF-8
425
1.6875
2
[]
no_license
package com.dalyTools.dalyTools.DAO.Repository.taskRepo; import com.dalyTools.dalyTools.DAO.Entity.task.DayTask; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.stereotype.Repository; import javax.swing.text.html.Option; @Repository public interface DayTaskRepository extends JpaRepository<DayTask,Long> { }
JavaScript
UTF-8
194
2.828125
3
[]
no_license
let started = false; function setup() { createCanvas(700, 400); noLoop(); } function draw() { if (started) { background(256); } } function start() { started = true; loop(); }
PHP
UTF-8
4,085
2.65625
3
[]
no_license
<?php //This script for the smiley thing function smiley($text){ $text =stripcslashes(" ".$text." "); //$text= preg_replace('@((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)*)@', '<a href="$1" class="linkTe" target="_blank">$1</a>', $text); $text = preg_replace("# :D #siU","<div class='smileypng' style='background-position: -18px 0px'></div>",$text); $text = preg_replace("# :d #siU","<div class='smileypng' style='background-position: -18px 0px'></div>",$text); $text = preg_replace("# =D #siU","<div class='smileypng' style='background-position: -18px 0px'></div>",$text); $text = preg_replace("# =d #siU","<div class='smileypng' style='background-position: -18px 0px'></div>",$text); $text = preg_replace("# ;\) #siU","<div class='smileypng' style='background-position:-130px 0px'></div>",$text); $text = preg_replace("# :\) #siU","<div class='smileypng' style='background-position: 0px 0px'></div>",$text); $text = preg_replace("# :\] #siU","<div class='smileypng' style='background-position: 0px 0px'></div>",$text); $text = preg_replace("# =\) #siU","<div class='smileypng' style='background-position: 0px 0px'></div>",$text); $text = preg_replace("# :\| #siU","<div class='smileypng' style='background-position: px px'></div>",$text); $text = preg_replace("# :\( #siU","<div class='smileypng' style='background-position: -36px 0px'></div>",$text); $text = preg_replace("# :o #siU","<div class='smileypng' style='background-position: -92px 0px'></div>",$text); $text = preg_replace("# :O #siU","<div class='smileypng' style='background-position: -92px 0px'></div>",$text); $text = preg_replace("# :0 #siU","<div class='smileypng' style='background-position: -92px 0px'></div>",$text); $text = preg_replace("# :8 #siU","<div class='smileypng' style='background-position: -149px 0px'></div>",$text); $text = preg_replace("# 8-\) #siU","<div class='smileypng' style='background-position: -149px 0px'></div>",$text); $text = preg_replace("# :p #siU","<div class='smileypng' style='background-position: -111px 0px'></div>",$text); $text = preg_replace("# :P #siU","<div class='smileypng' style='background-position: -111px 0px'></div>",$text); $text = preg_replace("# :\/ #siU","<div class='smileypng' style='background-position: -55px 0px'></div>",$text); $text = preg_replace("# 3:\) #siU","<div class='smileypng' style='background-position: 0px -18px'></div>",$text); $text = preg_replace("# 3:\] #siU","<div class='smileypng' style='background-position: 0px -18px'></div>",$text); $text = preg_replace("# :'\( #siU","<div class='smileypng' style='background-position: -73px 0px'></div>",$text); $text = preg_replace("# O:\) #siU","<div class='smileypng' style='background-position: -19px -18px; width:16px;'></div>",$text); $text= preg_replace("# :3 #siU","<div class='smileypng' style='background-position:-38px -18px'></div>",$text); $text = preg_replace("# &gt;:\( #siU","<div class='smileypng' style='background-position: -55px -18px'></div>",$text); $text = preg_replace("# &lt;:o #siU","<div class='smileypng' style='background-position: -93px -18px'></div>",$text); $text = preg_replace("# o.O #siU","<div class='smileypng' style='background-position: -74px -18px'></div>",$text); $text = preg_replace("# B\| #siU","<div class='smileypng' style='background-position: -111px -18px'></div>",$text); $text = preg_replace("# &lt;3 #siU","<div class='smileypng' style='background-position: -129px -18px'></div>",$text); $text = preg_replace("# \^\_\^ #siU","<div class='smileypng' style='background-position: -148px -18px'></div>",$text); $text = preg_replace("# :\* #siU","<div class='smileypng' style='background-position: -165px -18px'></div>",$text); $text = preg_replace("# :v #siU","<div class='smileypng' style='background-position: 0px -37px'></div>",$text); return ($text); } function LinkMe($text){ $text= preg_replace('@((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)*)@', '<a href="$1" class="linkTe" target="_blank">$1</a>', $text); return $text; } ?>
C#
UTF-8
3,540
2.59375
3
[]
no_license
using EvaluationAssistt.Data.Interface; using EvaluationAssistt.Domain.Entity; using EvaluationAssistt.Infrastructure.Helpers; using System; using System.Collections.Generic; using System.Linq; using EvaluationAssistt.Domain.Dto; namespace EvaluationAssistt.Service.Services { public class GroupsService { private static IUnitOfWork _unitOfWork; private static IRepository<Groups> _groupsRepository; public GroupsService() { if (_unitOfWork == null) { _unitOfWork = UnityHelper.Container.Resolve<IUnitOfWork>(); } if (_groupsRepository == null) { _groupsRepository = _unitOfWork.Groups; } } public IQueryable<GroupsDto> GetGroupsAll() { var query = _groupsRepository.All("Locations", "Agents") .Select(x => new GroupsDto() { Id = x.Id, Name = x.Name, LocationId = x.LocationId, LocationName = x.Locations.Name, AgentId = x.AgentId, AgentName = x.Agents.FirstName + " " + x.Agents.LastName }); return query; } public GroupsDto GetGroupById(int groupId) { var group = _groupsRepository.FindById(groupId); var result = new GroupsDto() { Id = group.Id, Name = group.Name, LocationId = group.LocationId, AgentId = group.AgentId }; return result; } public IQueryable<GroupsDto> GetGroupsNameValueCollection() { var query = _groupsRepository.All() .Select(x => new GroupsDto() { Id = x.Id, Name = x.Name, AgentName = x.Agents.FirstName + " " + x.Agents.LastName }); return query; } public IQueryable<GroupsDto> GetGroupsByLocationId(int locationId, int uid) { var result = _groupsRepository.Find(x => x.LocationId == locationId) .Select(x => new GroupsDto() { Id = x.Id, Name = x.Name, AgentName = x.Agents.FirstName + " " + x.Agents.LastName }); return result; } public void InsertGroup(GroupsDto dto) { var entity = new Groups() { Name = dto.Name, LocationId = dto.LocationId, AgentId = dto.AgentId }; _groupsRepository.Insert(entity); _unitOfWork.Save(); } public void UpdateGroup(GroupsDto dto) { var entity = _groupsRepository.FindById(dto.Id); entity.Name = dto.Name; entity.LocationId = dto.LocationId; entity.AgentId = dto.AgentId; _unitOfWork.Save(); } public void DeleteGroup(int id) { var entity = _groupsRepository.FindById(id); _groupsRepository.Delete(entity, true); _unitOfWork.Save(); } } }
PHP
UTF-8
4,030
2.5625
3
[]
no_license
<!DOCTYPE html> <html lang="en" > <head> <meta charset="UTF-8"> <title>Table</title> <link rel="stylesheet" href="css/style.css"> <style> #below { height:600px; width:100%; } img { float: right; } p { margin-left: 100px; padding: 35px; height:300px; font-size:22px; } h1 { text-align: center;} h4{ margin-left:250px; } input { width:35%; } button { background-color: Black; border-radius: 12px; color: white; padding: 15px 25px; text-align: center; text-decoration: none; display: inline-block; font-size: 20px; margin: 4px 920px; cursor: pointer; } </style> </head> <body> <form method="POST" action="mailback.php"> <?php $noofdays = ""; $email =""; $bookname = ""; $firstname =""; echo '<h1>'."DETAILS".'</h1>'; $len = sizeof($_POST['id']); // Loop to store and display values of individual checked checkbox. for ($i = 0; $i < $len; $i++) { $noofdays = $_POST["id"][$i]; $email = $_POST["email"][$i]; $bookname = $_POST["bookname"][$i]; $firstname = $_POST["firstname"][$i]; } echo '<h4>' . "You are giving book name is :" .'<input type="text" name="bookname" value="' . $bookname . '">'.'</h4>'; echo '<h4>' . "You are exchanging book for:" .'<input type="text" name="noofdays" value="' . $noofdays . '">'.'</h4>'; echo '<h4>' . "You are exchanging with:" .'<input type="text" name="firstname" value="' . $firstname . '">'.'</h4>'; echo '<h4>' . "Email address of person:" .'<input type="text" name="email" value="' . $email . '">'.'</h4>'; echo '<h1>LIBRARY</h1>' . '<div id="below">' . '<div class="table-users">' . '<div class="header">Catalog</div>' . '<table cellspacing="0">' . '<tr>' . '<th>Select</th>' . '<th>Book Name</th>' . '<th>Author</th>' . '</tr>'; // put your code here include 'connection.php'; $username = $_SESSION["username2"]; //reading from existing database $sql_stmt = "SELECT BookName, Author FROM booksinfo where UserName='$username'"; //SQL select query $result = mysqli_query($dbhandle, $sql_stmt); //execute SQL statement and get the object of query if (!$result) { die("database access failed" . mysqli_errno($dbhandle)); } $no_rows = mysqli_num_rows($result); //get total rows of query object if ($no_rows) { while ($row = mysqli_fetch_array($result)) { //row wise of obj query--> array echo '<tr><td>' . '<div class="radio">' . '<input type="radio" name ="id" value="' . $row['BookName'] . '">' . '</div>' . '</td>' . '<td> ' . $row['BookName'] . '</td>' . '<td> ' . $row['Author'] . '</td>' . '</tr>'; } } echo '</table>' . '</div>'; ?> <button type="submit" style="width:auto;">CONFIRM</button> </form> </body> </html>
Markdown
UTF-8
4,727
2.796875
3
[]
no_license
# 华为2019软件精英挑战赛--初赛33名 ### <a href = "https://codecraft.huawei.com/Generaldetail">赛题介绍</a> ### 队伍名称:TestNWPU ### 队员:高轶群,曹悦 ./src/CodeCraft-2019.py 是调度代码 ./data/ 存放着数据 运行方式:python3 CodeCraft-2019.py ../data/1-map-exam-1/car.txt ../data/1-map-exam-1/road.txt ../data/1-map-exam-1/cross.txt ../data/1-map-exam-1/answer.txt 上传的这一版代码最终分数是3400。 ### <a href = "https://github.com/yue1272933238/2019-HuaWeiCompetition"> 还有一个我队友写的版本,注释更多,整体思路都是一致的,只是数据结构略有不同</a> ### 整体思路 ### 1.车辆路径选择问题 我们首先考虑所有车辆走最短的路径,然后动态的调整车辆的出发时间来降低整体的调度时间,但是在实际实验中发现车辆走最短路径存在着死锁产生概率高和道路拥挤程度不均衡的问题,所以我们在路径选择方面做了车辆的实时调度,具体思路是当车辆在一个路口决定下一次行驶的方向的时候,会计算选择不同道路的剩余距离和该道路的拥挤程度,拥挤程度(road_full)用当前道路上的车辆数目除以道路理论能容纳的最大车辆数目来衡量,0代表道路上没有任何车,1代表道路上塞满了车,然后用road_full来惩罚距离,最终比较Dist×(1+road_full)的大小来实时选择需要的路径,Dist为选择该路口需要行驶的剩余距离。调度器集成在代码中,线上线下总调度时间结果一致。 ### 2.死锁的解除 车辆行驶的时候可能会发生死锁形成环路,我们认为死锁是因为部分道路上车辆数目过多导致的,并且速度慢的车是导致死锁的关键。如果在T时间发生死锁,就找出来发生死锁的车,然后先把发生死锁的车按照车速排序,取速度最慢的一半车辆将他们的发车时间推迟到T,对于已经上路的车(除了发生死锁的车),我们不改变他们的发车时间,对于在T时刻还没有上路的车,我们会事先计算他们可能会经过的路段,如果会经过死锁路段,我们也将这些车推迟到T时间以后发车。实验证明通过这样的手段,能很好的解除死锁。 ### 3.发车策略 对于车辆的发车,我们主要考虑到车速,车辆快的车应该具有更大的优先权,因为如果你先发速度慢的,再发速度快的车,肯定没有先发速度快的,再发速度慢的车效果好。在每一个时间片T,我们只发速度最快的车,通过这样的策略我们初赛的分数提高了100分,但是也不能无限制的发车,所以我们去限制道路上最大的车辆数目,只有小于这个数目的时候,才会从车库发车,注意到我们不用担心死锁,因为我们是可以解除死锁的,只是如果你放入更多的车,死锁的概率就会更大,就需要更多的时间去解锁。 ### 4.反思 我觉得我们最大的败笔在发车策略上,通过限制路上车的数目来控制发车是不恰当的行为,事实也证明我们过分的拟合了A榜,在数据更换时成绩出现了较大的下滑。这个比赛对我来说已经结束了,祝大家取得好成绩。 ### 代码结构解析 while(dead_lock == 1): #当发生死锁退出时,应该重新进行一轮调度 ##初始化一些数据结构 while(Still_have_cars(Path, Carport_temp, Carport) and dead_lock != 1): #当路上仍然有车的时候并且没有死锁继续调度 T = T + 1 #时间片+1 Dispatch_cars(Path, Map, Road, Distance, Cross) #把所有车辆状态初始化为0,确定车辆的转向 Look_all_driveway(Path, Road, Map) #该步骤处理道路内的车 while(Do_not_process_all_cars(Path)): #当没有处理完所有车,需要循环处理每一个路口 dead_lock = Look_all_cross(Path, Cross, Map, Road, T) #处理要过马路的车,若发生死锁返回1 if(dead_lock): print("dead lock happen at " + str(T) + ", " + str(len(have_stated_car)) + " cars have start" + str(count_car(Path))) process_dead_lock(Path, have_stated_car, possible_path, T, Carport_total) #处理死锁,并开始新一轮的调度 break if(count_car(Path) < 2000): #路上车数目小于2000,开始放车,先放速度快的车 Put_car_in_carport(Carport, Carport_temp, T, car_v_record) Look_all_carport(Carport, Path, 5000, T, Map, Distance, Road, have_stated_car, car_v_record)
C
UTF-8
13,988
2.734375
3
[ "MIT" ]
permissive
/************************************************************************** ** ** svd3 ** ** Quick singular value decomposition as described by: ** A. McAdams, A. Selle, R. Tamstorf, J. Teran and E. Sifakis, ** Computing the Singular Value Decomposition of 3x3 matrices ** with minimal branching and elementary floating point operations, ** University of Wisconsin - Madison technical report TR1690, May 2011 ** ** OPTIMIZED GPU VERSION ** Implementation by: Eric Jang ** ** 13 Apr 2014 ** **************************************************************************/ #ifndef SVD3_CUDA_H #define SVD3_CUDA_H #define _gamma 5.828427124 // FOUR_GAMMA_SQUARED = sqrt(8)+3; #define _cstar 0.923879532 // cos(pi/8) #define _sstar 0.3826834323 // sin(p/8) #define EPSILON 1e-6 #include <cuda.h> #include "math.h" // CUDA math library // CUDA's rsqrt seems to be faster than the inlined approximation? __host__ __device__ __forceinline__ float accurateSqrt(float x) { return x * rsqrt(x); } __host__ __device__ __forceinline__ void condSwap(bool c, float &X, float &Y) { // used in step 2 float Z = X; X = c ? Y : X; Y = c ? Z : Y; } __host__ __device__ __forceinline__ void condNegSwap(bool c, float &X, float &Y) { // used in step 2 and 3 float Z = -X; X = c ? Y : X; Y = c ? Z : Y; } // matrix multiplication M = A * B __host__ __device__ __forceinline__ void multAB(float a11, float a12, float a13, float a21, float a22, float a23, float a31, float a32, float a33, // float b11, float b12, float b13, float b21, float b22, float b23, float b31, float b32, float b33, // float &m11, float &m12, float &m13, float &m21, float &m22, float &m23, float &m31, float &m32, float &m33) { m11=a11*b11 + a12*b21 + a13*b31; m12=a11*b12 + a12*b22 + a13*b32; m13=a11*b13 + a12*b23 + a13*b33; m21=a21*b11 + a22*b21 + a23*b31; m22=a21*b12 + a22*b22 + a23*b32; m23=a21*b13 + a22*b23 + a23*b33; m31=a31*b11 + a32*b21 + a33*b31; m32=a31*b12 + a32*b22 + a33*b32; m33=a31*b13 + a32*b23 + a33*b33; } // matrix multiplication M = Transpose[A] * B __host__ __device__ __forceinline__ void multAtB(float a11, float a12, float a13, float a21, float a22, float a23, float a31, float a32, float a33, // float b11, float b12, float b13, float b21, float b22, float b23, float b31, float b32, float b33, // float &m11, float &m12, float &m13, float &m21, float &m22, float &m23, float &m31, float &m32, float &m33) { m11=a11*b11 + a21*b21 + a31*b31; m12=a11*b12 + a21*b22 + a31*b32; m13=a11*b13 + a21*b23 + a31*b33; m21=a12*b11 + a22*b21 + a32*b31; m22=a12*b12 + a22*b22 + a32*b32; m23=a12*b13 + a22*b23 + a32*b33; m31=a13*b11 + a23*b21 + a33*b31; m32=a13*b12 + a23*b22 + a33*b32; m33=a13*b13 + a23*b23 + a33*b33; } __host__ __device__ __forceinline__ void quatToMat3(const float * qV, float &m11, float &m12, float &m13, float &m21, float &m22, float &m23, float &m31, float &m32, float &m33 ) { float w = qV[3]; float x = qV[0]; float y = qV[1]; float z = qV[2]; float qxx = x*x; float qyy = y*y; float qzz = z*z; float qxz = x*z; float qxy = x*y; float qyz = y*z; float qwx = w*x; float qwy = w*y; float qwz = w*z; m11=1 - 2*(qyy + qzz); m12=2*(qxy - qwz); m13=2*(qxz + qwy); m21=2*(qxy + qwz); m22=1 - 2*(qxx + qzz); m23=2*(qyz - qwx); m31=2*(qxz - qwy); m32=2*(qyz + qwx); m33=1 - 2*(qxx + qyy); } __host__ __device__ __forceinline__ void approximateGivensQuaternion(float a11, float a12, float a22, float &ch, float &sh) { /* * Given givens angle computed by approximateGivensAngles, * compute the corresponding rotation quaternion. */ ch = 2*(a11-a22); sh = a12; bool b = _gamma*sh*sh < ch*ch; float w = rsqrt(ch*ch+sh*sh); ch=b?w*ch:_cstar; sh=b?w*sh:_sstar; } __host__ __device__ __forceinline__ void jacobiConjugation( const int x, const int y, const int z, float &s11, float &s21, float &s22, float &s31, float &s32, float &s33, float * qV) { float ch,sh; approximateGivensQuaternion(s11,s21,s22,ch,sh); float scale = ch*ch+sh*sh; float a = (ch*ch-sh*sh)/scale; float b = (2*sh*ch)/scale; // make temp copy of S float _s11 = s11; float _s21 = s21; float _s22 = s22; float _s31 = s31; float _s32 = s32; float _s33 = s33; // perform conjugation S = Q'*S*Q // Q already implicitly solved from a, b s11 =a*(a*_s11 + b*_s21) + b*(a*_s21 + b*_s22); s21 =a*(-b*_s11 + a*_s21) + b*(-b*_s21 + a*_s22); s22=-b*(-b*_s11 + a*_s21) + a*(-b*_s21 + a*_s22); s31 =a*_s31 + b*_s32; s32=-b*_s31 + a*_s32; s33=_s33; // update cumulative rotation qV float tmp[3]; tmp[0]=qV[0]*sh; tmp[1]=qV[1]*sh; tmp[2]=qV[2]*sh; sh *= qV[3]; qV[0] *= ch; qV[1] *= ch; qV[2] *= ch; qV[3] *= ch; // (x,y,z) corresponds to ((0,1,2),(1,2,0),(2,0,1)) // for (p,q) = ((0,1),(1,2),(0,2)) qV[z] += sh; qV[3] -= tmp[z]; // w qV[x] += tmp[y]; qV[y] -= tmp[x]; // re-arrange matrix for next iteration _s11 = s22; _s21 = s32; _s22 = s33; _s31 = s21; _s32 = s31; _s33 = s11; s11 = _s11; s21 = _s21; s22 = _s22; s31 = _s31; s32 = _s32; s33 = _s33; } __host__ __device__ __forceinline__ float dist2(float x, float y, float z) { return x*x+y*y+z*z; } // finds transformation that diagonalizes a symmetric matrix __host__ __device__ __forceinline__ void jacobiEigenanlysis( // symmetric matrix float &s11, float &s21, float &s22, float &s31, float &s32, float &s33, // quaternion representation of V float * qV) { qV[3]=1; qV[0]=0;qV[1]=0;qV[2]=0; // follow same indexing convention as GLM for (int i=0;i<4;i++) { // we wish to eliminate the maximum off-diagonal element // on every iteration, but cycling over all 3 possible rotations // in fixed order (p,q) = (1,2) , (2,3), (1,3) still retains // asymptotic convergence jacobiConjugation(0,1,2,s11,s21,s22,s31,s32,s33,qV); // p,q = 0,1 jacobiConjugation(1,2,0,s11,s21,s22,s31,s32,s33,qV); // p,q = 1,2 jacobiConjugation(2,0,1,s11,s21,s22,s31,s32,s33,qV); // p,q = 0,2 } } __host__ __device__ __forceinline__ void sortSingularValues(// matrix that we want to decompose float &b11, float &b12, float &b13, float &b21, float &b22, float &b23, float &b31, float &b32, float &b33, // sort V simultaneously float &v11, float &v12, float &v13, float &v21, float &v22, float &v23, float &v31, float &v32, float &v33) { float rho1 = dist2(b11,b21,b31); float rho2 = dist2(b12,b22,b32); float rho3 = dist2(b13,b23,b33); bool c; c = rho1 < rho2; condNegSwap(c,b11,b12); condNegSwap(c,v11,v12); condNegSwap(c,b21,b22); condNegSwap(c,v21,v22); condNegSwap(c,b31,b32); condNegSwap(c,v31,v32); condSwap(c,rho1,rho2); c = rho1 < rho3; condNegSwap(c,b11,b13); condNegSwap(c,v11,v13); condNegSwap(c,b21,b23); condNegSwap(c,v21,v23); condNegSwap(c,b31,b33); condNegSwap(c,v31,v33); condSwap(c,rho1,rho3); c = rho2 < rho3; condNegSwap(c,b12,b13); condNegSwap(c,v12,v13); condNegSwap(c,b22,b23); condNegSwap(c,v22,v23); condNegSwap(c,b32,b33); condNegSwap(c,v32,v33); } __host__ __device__ __forceinline__ void QRGivensQuaternion(float a1, float a2, float &ch, float &sh) { // a1 = pivot point on diagonal // a2 = lower triangular entry we want to annihilate float epsilon = EPSILON; float rho = accurateSqrt(a1*a1 + a2*a2); sh = rho > epsilon ? a2 : 0; ch = fabs(a1) + fmax(rho,epsilon); bool b = a1 < 0; condSwap(b,sh,ch); float w = rsqrt(ch*ch+sh*sh); ch *= w; sh *= w; } __host__ __device__ __forceinline__ void QRDecomposition(// matrix that we want to decompose float b11, float b12, float b13, float b21, float b22, float b23, float b31, float b32, float b33, // output Q float &q11, float &q12, float &q13, float &q21, float &q22, float &q23, float &q31, float &q32, float &q33, // output R float &r11, float &r12, float &r13, float &r21, float &r22, float &r23, float &r31, float &r32, float &r33) { float ch1,sh1,ch2,sh2,ch3,sh3; float a,b; // first givens rotation (ch,0,0,sh) QRGivensQuaternion(b11,b21,ch1,sh1); a=1-2*sh1*sh1; b=2*ch1*sh1; // apply B = Q' * B r11=a*b11+b*b21; r12=a*b12+b*b22; r13=a*b13+b*b23; r21=-b*b11+a*b21; r22=-b*b12+a*b22; r23=-b*b13+a*b23; r31=b31; r32=b32; r33=b33; // second givens rotation (ch,0,-sh,0) QRGivensQuaternion(r11,r31,ch2,sh2); a=1-2*sh2*sh2; b=2*ch2*sh2; // apply B = Q' * B; b11=a*r11+b*r31; b12=a*r12+b*r32; b13=a*r13+b*r33; b21=r21; b22=r22; b23=r23; b31=-b*r11+a*r31; b32=-b*r12+a*r32; b33=-b*r13+a*r33; // third givens rotation (ch,sh,0,0) QRGivensQuaternion(b22,b32,ch3,sh3); a=1-2*sh3*sh3; b=2*ch3*sh3; // R is now set to desired value r11=b11; r12=b12; r13=b13; r21=a*b21+b*b31; r22=a*b22+b*b32; r23=a*b23+b*b33; r31=-b*b21+a*b31; r32=-b*b22+a*b32; r33=-b*b23+a*b33; // construct the cumulative rotation Q=Q1 * Q2 * Q3 // the number of floating point operations for three quaternion multiplications // is more or less comparable to the explicit form of the joined matrix. // certainly more memory-efficient! float sh12=sh1*sh1; float sh22=sh2*sh2; float sh32=sh3*sh3; q11=(-1+2*sh12)*(-1+2*sh22); q12=4*ch2*ch3*(-1+2*sh12)*sh2*sh3+2*ch1*sh1*(-1+2*sh32); q13=4*ch1*ch3*sh1*sh3-2*ch2*(-1+2*sh12)*sh2*(-1+2*sh32); q21=2*ch1*sh1*(1-2*sh22); q22=-8*ch1*ch2*ch3*sh1*sh2*sh3+(-1+2*sh12)*(-1+2*sh32); q23=-2*ch3*sh3+4*sh1*(ch3*sh1*sh3+ch1*ch2*sh2*(-1+2*sh32)); q31=2*ch2*sh2; q32=2*ch3*(1-2*sh22)*sh3; q33=(-1+2*sh22)*(-1+2*sh32); } __host__ __device__ __forceinline__ void svd(// input A float a11, float a12, float a13, float a21, float a22, float a23, float a31, float a32, float a33, // output U float &u11, float &u12, float &u13, float &u21, float &u22, float &u23, float &u31, float &u32, float &u33, // output S float &s11, float &s12, float &s13, float &s21, float &s22, float &s23, float &s31, float &s32, float &s33, // output V float &v11, float &v12, float &v13, float &v21, float &v22, float &v23, float &v31, float &v32, float &v33) { // normal equations matrix float ATA11, ATA12, ATA13; float ATA21, ATA22, ATA23; float ATA31, ATA32, ATA33; multAtB(a11,a12,a13,a21,a22,a23,a31,a32,a33, a11,a12,a13,a21,a22,a23,a31,a32,a33, ATA11,ATA12,ATA13,ATA21,ATA22,ATA23,ATA31,ATA32,ATA33); // symmetric eigenalysis float qV[4]; jacobiEigenanlysis( ATA11,ATA21,ATA22, ATA31,ATA32,ATA33,qV); quatToMat3(qV,v11,v12,v13,v21,v22,v23,v31,v32,v33); float b11, b12, b13; float b21, b22, b23; float b31, b32, b33; multAB(a11,a12,a13,a21,a22,a23,a31,a32,a33, v11,v12,v13,v21,v22,v23,v31,v32,v33, b11, b12, b13, b21, b22, b23, b31, b32, b33); // sort singular values and find V sortSingularValues(b11, b12, b13, b21, b22, b23, b31, b32, b33, v11,v12,v13,v21,v22,v23,v31,v32,v33); // QR decomposition QRDecomposition(b11, b12, b13, b21, b22, b23, b31, b32, b33, u11, u12, u13, u21, u22, u23, u31, u32, u33, s11, s12, s13, s21, s22, s23, s31, s32, s33 ); } /// polar decomposition can be reconstructed trivially from SVD result /// A = UP __host__ __device__ __forceinline__ void pd(float a11, float a12, float a13, float a21, float a22, float a23, float a31, float a32, float a33, // output U float &u11, float &u12, float &u13, float &u21, float &u22, float &u23, float &u31, float &u32, float &u33, // output P float &p11, float &p12, float &p13, float &p21, float &p22, float &p23, float &p31, float &p32, float &p33) { float w11, w12, w13, w21, w22, w23, w31, w32, w33; float s11, s12, s13, s21, s22, s23, s31, s32, s33; float v11, v12, v13, v21, v22, v23, v31, v32, v33; svd(a11, a12, a13, a21, a22, a23, a31, a32, a33, w11, w12, w13, w21, w22, w23, w31, w32, w33, s11, s12, s13, s21, s22, s23, s31, s32, s33, v11, v12, v13, v21, v22, v23, v31, v32, v33); // P = VSV' float t11, t12, t13, t21, t22, t23, t31, t32, t33; multAB(v11, v12, v13, v21, v22, v23, v31, v32, v33, s11, s12, s13, s21, s22, s23, s31, s32, s33, t11, t12, t13, t21, t22, t23, t31, t32, t33); multAB(t11, t12, t13, t21, t22, t23, t31, t32, t33, v11, v21, v31, v12, v22, v32, v13, v23, v33, p11, p12, p13, p21, p22, p23, p31, p32, p33); // U = WV' multAB(w11, w12, w13, w21, w22, w23, w31, w32, w33, v11, v21, v31, v12, v22, v32, v13, v23, v33, u11, u12, u13, u21, u22, u23, u31, u32, u33); } #endif
Python
UTF-8
264
2.875
3
[]
no_license
import sys lst = [] for k in range(10): n = int(input()) lst.append(n) per = {} for x in lst: if x not in per: per[x] = 1 else: per[x] += 1 max_key = max(per, key=per.get) avg = int(sum(lst) / len(lst)) print(avg) print(max_key)
Java
UTF-8
4,130
2.21875
2
[]
no_license
package com.example.amit.viewpagerexample; import android.content.Context; import android.media.AudioManager; import android.media.MediaPlayer; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import java.util.ArrayList; /** * Created by AMIT on 21-03-2018. */ public class PhrasesFragment extends Fragment { MediaPlayer mediaPlayer; AudioManager audioManager; AudioManager.OnAudioFocusChangeListener onAudioFocusChangeListener=new AudioManager.OnAudioFocusChangeListener() { @Override public void onAudioFocusChange(int focusChange) { if(focusChange==AudioManager.AUDIOFOCUS_LOSS_TRANSIENT||focusChange==AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK){ mediaPlayer.pause(); mediaPlayer.seekTo(0); }else if (focusChange==AudioManager.AUDIOFOCUS_GAIN){ mediaPlayer.start(); }else if (focusChange==AudioManager.AUDIOFOCUS_LOSS){ mediaPlayer.stop(); releaseMedia(); } } }; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { ListView listView= (ListView) inflater.inflate(R.layout.word_list,container,false); final ArrayList<Word> list=new ArrayList<>(); list.add(new Word("Where are you going?","minto wuksus",R.raw.phrase_where_are_you_going)); list.add(new Word("What is your name?","tinnә oyaase'nә",R.raw.phrase_what_is_your_name)); list.add(new Word("My name is...","oyaaset...",R.raw.phrase_my_name_is)); list.add(new Word("How are you feeling?","michәksәs?",R.raw.phrase_how_are_you_feeling)); list.add(new Word("I’m feeling good.","kuchi achit",R.raw.phrase_im_feeling_good)); list.add(new Word("Are you coming?","әәnәs'aa?",R.raw.phrase_are_you_coming)); list.add(new Word("Yes, I’m coming.","hәә’ әәnәm",R.raw.phrase_yes_im_coming)); list.add(new Word("I’m coming.","әәnәm",R.raw.phrase_im_coming)); list.add(new Word("Let’s go.","yoowutis",R.raw.phrase_lets_go)); list.add(new Word("Come here.","әnni'nem",R.raw.phrase_come_here)); WordAdapter itemAdapter=new WordAdapter(getContext(),list,R.color.category_phrases); listView.setAdapter(itemAdapter); audioManager= (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE); final MediaPlayer.OnCompletionListener onCompletionListener=new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { releaseMedia(); } }; listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Word item=list.get(position); //to release previous media resource before loading current resource releaseMedia(); int response=audioManager.requestAudioFocus(onAudioFocusChangeListener,AudioManager.STREAM_MUSIC,AudioManager.AUDIOFOCUS_GAIN_TRANSIENT); if(response==AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { mediaPlayer = MediaPlayer.create(getContext(), item.getmAudioResourceId()); mediaPlayer.start(); mediaPlayer.setOnCompletionListener(onCompletionListener); } } }); return listView; } public void releaseMedia(){ if(mediaPlayer!=null) { mediaPlayer.release(); audioManager.abandonAudioFocus(onAudioFocusChangeListener); mediaPlayer = null; } } @Override public void onStop() { super.onStop(); releaseMedia(); } }
Shell
UTF-8
857
2.75
3
[]
no_license
#!/bind/bash #Code Review 01-27-17 Rance Nault, Daria Tarasova echo $1 >> Monitoring/delete.log if [ -d public/cors_demo/$1 ]; then echo $1 exists >> Monitoring/delete.log fi echo '-x '$1 > public/services/manta-sync-ignore.txt # Remove from manta and local rm -r public/cors_demo/$1 mrm -r ~~/stor/cors_demo/$1 rm -r public/cors_demo/$1.set mrm -r ~~/stor/cors_demo/$1.set rm -r public/cors_demo/$1.intermediate mrm -r ~~/stor/cors_demo/$1.intermediate # clean up the manta ignore text file echo '-x jack/ignore/ignore ' > public/services/manta-sync-ignore.txt grep -v $1 Monitoring/QC_SubList.tmp > temp && mv temp Monitoring/QC_SubList.tmp sleep 1s if [ ! -d public/cors_demo/$1 ]; then echo 'Successfully deleted' >> Monitoring/delete.log else echo 'Not successful' >> Monitoring/delete.log fi echo '------------------------' >> Monitoring/delete.log
Java
UTF-8
1,352
1.84375
2
[]
no_license
package edu.kalum.notas.core.models.entities; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; import java.io.Serializable; import java.util.Date; import java.util.List; @NoArgsConstructor @AllArgsConstructor @Data @Table(name = "detalle_actividad") @Entity public class DetalleActividad implements Serializable { @Id @Column(name = "detalle_actividad_id") private String detalleActividadId; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "seminario_id", referencedColumnName = "seminario_id") private Seminario seminario; @Column(name = "nombre_actividad") private String nombreActividad; @Column(name = "nota_actividad") private Integer notaActividad; @Column(name = "fecha_creacion") private Date fechaCreacion; @Column(name = "fecha_entrega") private Date fechaEntrega; @Column(name = "fecha_postergacion") private Date fechaPostergacion; @Column(name = "estado") private String estado; @OneToMany(mappedBy = "detalleActividad", fetch = FetchType.EAGER) @JsonIgnore @JsonIgnoreProperties({"hibernateLazyInitializer","handler"}) private List<DetalleNota> detalleNota; }
Java
UTF-8
827
2.15625
2
[]
no_license
package braxtion.io.athent.controllers; import braxtion.io.athent.models.Secret; import braxtion.io.athent.repositiory.SecretRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; @Controller public class SecretController { @Autowired SecretRepository secretRepo; @RequestMapping(name = "/createSecret", method = RequestMethod.POST) public String createSecretForm(@RequestParam("body") String body) { Secret newSecret = new Secret(); newSecret.setBody(body); secretRepo.save(newSecret); return "redirect:/"; } }
PHP
UTF-8
938
2.84375
3
[ "BSD-3-Clause" ]
permissive
<?php namespace common\helpers; use Yii; /** * Created by PhpStorm. * User: hu yang * Date: 2018/2/8 * Time: 上午10:29 */ final class RedisHelper { final static function getKey($key) { return md5($key.__CLASS__); } /** * redis 计数器 +1 * * @param $key * @param int $expire * * @return array|bool|null|string */ final static function inc($key, $expire) { $key = self::getKey($key); $count = Yii::$app->redis->executeCommand('INCR', [$key]); if ($count == 1) { Yii::$app->redis->executeCommand('EXPIRE', [$key, $expire]); } return $count; } /** * redis计数器-减少 * @param $key * @return array|bool|null|string */ public static function dec($key) { $key = self::getKey($key); return Yii::$app->redis->executeCommand('DECR', [$key]); } }
C
UTF-8
17,168
3.0625
3
[]
no_license
/*! @file Button.c @author Noel Ho Sing Nam (s.ho) @course CSD1400 @section A @brief Handles button display properties and their functions *//*__________________________________________________________________________ _*/ #include "Button.h" #include "Scene.h" #include "TestScene1.h" #include <stdio.h> #include <stdlib.h> int Button_temp_bool = 0; /*! @brief Initializes a button with default settings @return the ID of the button *//*________________________________________________________________________ _*/ int Button_Initialize_Default() { CP_Vector default_pos; default_pos.x = (float)CP_System_GetWindowWidth() / 2; default_pos.y = (float)CP_System_GetWindowHeight() / 2; CP_Vector default_text_pos; default_text_pos.x = (float)CP_System_GetWindowWidth() / 2 + 8; default_text_pos.y = (float)CP_System_GetWindowHeight() / 2 + 40; CP_Vector default_size; default_size.x = 250; default_size.y = 50; return Button_Initialize( default_pos, default_size, default_text_pos, CP_Color_Create(255, 240, 255, 255), CP_Color_Create(0, 0, 0, 255), 50.0f, "Text Not Set", 1 ); } /*! @brief Initializes a button with set data @param position - The position of the button size - The size ofthe button text_position - The position of the text button_color - The colour of the button text_color - The colour of the text text_size - The size of the text text - The text visible - Is the button visible? @return the ID of the button *//*________________________________________________________________________ _*/ int Button_Initialize(CP_Vector position, CP_Vector size, CP_Vector text_position, CP_Color button_color, CP_Color text_color, float text_size, char* text, char visible) { struct Button new_button; // Set Position new_button.Position.x = position.x; new_button.Position.y = position.y; // Set Size new_button.Size.x = (float)(strlen(text)*20) ; new_button.Size.y = size.y; // Set Text Position new_button.Text_Position.x = text_position.x; new_button.Text_Position.y = text_position.y; // Set Color new_button.Button_Color = button_color; // Set Text Color new_button.Text_Color = text_color; // Set Hover Color int r = (button_color.r + 100 > 255) ? 255 : button_color.r + 100; int g = (button_color.g + 100 > 255) ? 255 : button_color.g + 100; int b = (button_color.b + 100 > 255) ? 255 : button_color.b + 100; new_button.Hover_Color = CP_Color_Create(r, g, b, button_color.a); // Set Darken Color r = (button_color.r - 100 < 0) ? 0 : button_color.r - 100; g = (button_color.g - 100 < 0) ? 0 : button_color.g - 100; b = (button_color.b - 100 < 0) ? 0 : button_color.b - 100; new_button.Darken_Color = CP_Color_Create(r, g, b, button_color.a); // Set Text Size new_button.Text_Size = text_size; // Set Text sprintf_s(new_button.Text, 127, text); // Set Name sprintf_s(new_button.Name, 127, text); // Set Scale new_button.Scale = 1.0f; // Sets the button status as active new_button.Active = 1; // Sets the button as visible new_button.Visible = visible; // Initialize hover state new_button.Hover = 0; // Initialize darken state new_button.Darken = 0; // Initialize image to NULL new_button.Image = NULL; // Initialize special effect boolean to off new_button.Enable_SpecialEffects = 0; // Adds button to list new_button.Id = Button_List_Add(&new_button); //return new_button; return new_button.Id; } /*! @brief Moves a button's position @param id - The ID of the button displacement_x - The x-distance to translate displacement_y - The y-distance to translate @return 1 after function is complete *//*________________________________________________________________________ _*/ char Button_Translate(int id, float displacement_x, float displacement_y) { button_list[scene_id][id].Position.x += displacement_x; button_list[scene_id][id].Position.y += displacement_y; return 1; } /*! @brief Sets a button's position @param id - The ID of the button new_x - The x-position to set new_y - The y-position to set @return 1 after function is complete *//*________________________________________________________________________ _*/ char Button_Position_Set(int id, float new_x, float new_y) { button_list[scene_id][id].Position.x = new_x; button_list[scene_id][id].Position.y = new_y; return 1; } /*! @brief Sets a button's size @param id - The ID of the button new_x - The x-size to set new_y - The y-size to set @return 1 after function is complete *//*________________________________________________________________________ _*/ char Button_Size_Set(int id, float new_x, float new_y) { button_list[scene_id][id].Size.x = new_x; button_list[scene_id][id].Size.y = new_y; return 1; } /*! @brief Scales a button's size @param id - The ID of the button scale_x - The amount to scale the x-size by scale_y - The amount to scale the y-size by @return 1 after function is complete *//*________________________________________________________________________ _*/ char Button_Size_Scale(int id, float scale_x, float scale_y) { button_list[scene_id][id].Size.x *= scale_x; button_list[scene_id][id].Size.y *= scale_y; return 1; } /*! @brief Sets the Scene ID for the button class, used for accessing different functions @param id - The ID of the scene to set @return the id after compete *//*________________________________________________________________________ _*/ char Button_SceneID_Set(int id) { scene_id = id; return (char)id; } /*! @brief Moves a button's text position @param id - The ID of the button displacement_x - The x-distance to translate displacement_y - The y-distance to translate @return 1 after function is complete *//*________________________________________________________________________ _*/ char Button_Text_Translate(int id, float displacement_x, float displacement_y) { button_list[scene_id][id].Text_Position.x += displacement_x; button_list[scene_id][id].Text_Position.y += displacement_y; return 1; } /*! @brief Scales a button's text size @param id - The ID of the button scale_x - The amount to scale the x-size by scale_y - The amount to scale the y-size by @return 1 after function is complete *//*________________________________________________________________________ _*/ char Button_Text_Scale(int id, float scale) { button_list[scene_id][id].Text_Size *= scale; return 1; } /*! @brief Sets a button's text position @param id - The ID of the button new_x - The x-position to set new_y - The y-position to set @return 1 after function is complete *//*________________________________________________________________________ _*/ char Button_Text_SetPosition(int id, float new_x, float new_y) { button_list[scene_id][id].Text_Position.x = new_x; button_list[scene_id][id].Text_Position.y = new_y; return 1; } /*! @brief Sets a button's text @param id - The ID of the button new_text - The text to set @return 1 after function is complete *//*________________________________________________________________________ _*/ char Button_Text_Set(int id, char* new_text) { sprintf_s(button_list[scene_id][id].Text, 127, new_text); return 1; } /*! @brief Sets a button's colour @param id - The ID of the button r - The red value g - The green value b - The blue value a - The alpha value @return 1 after function is complete *//*________________________________________________________________________ _*/ char Button_Color_Set(int id, int r, int g, int b, int a) { CP_Color new_color = CP_Color_Create(r, g, b, a); button_list[scene_id][id].Button_Color = new_color; // Set Hover Color int nr = (r + 100 > 255) ? 255 : r + 100; int ng = (g + 100 > 255) ? 255 : g + 100; int nb = (b + 100 > 255) ? 255 : b + 100; button_list[scene_id][id].Hover_Color = CP_Color_Create(nr, ng, nb, a); // Set Darken Color nr = (r - 100 < 0) ? 0 : r - 100; ng = (g - 100 < 0) ? 0 : g - 100; nb = (b - 100 < 0) ? 0 : b - 100; button_list[scene_id][id].Darken_Color = CP_Color_Create(nr, ng, nb, a); return 1; } /*! @brief Sets a button's name (not for display) @param id - The ID of the button new_text - The name to set @return 1 after function is complete *//*________________________________________________________________________ _*/ char Button_Name_Set(int id, char* new_text) { sprintf_s(button_list[scene_id][id].Name, 127, new_text); return 1; } /*! @brief Adds a button into button class, required as the code loops through the list @param add_button - The button to add @return the id if complete, 0 if there is no more memory space *//*________________________________________________________________________ _*/ int Button_List_Add(struct Button* add_button) { for (int i = 0; i < 127; i++) { if (button_list[scene_id][i].Active == 0) { button_list[scene_id][i] = *add_button; button_list[scene_id][i].Id = i; return i; } } return 0; } /*! @brief Update function for button class *//*________________________________________________________________________ _*/ void Button_Update() { Button_Mouse_Collision_Check_All(); } /*! @brief Loops through all the buttons, checks if the mouse is touching any *//*________________________________________________________________________ _*/ void Button_Mouse_Collision_Check_All() { for (int i = 0; i < 127; i++) { if (button_list[scene_id][i].Active == 0) { return; } else if (button_list[scene_id][i].Visible) { if (Button_Mouse_Collision_Check(i)) { if (CP_Input_MouseDown(MOUSE_BUTTON_1)) { button_list[scene_id][i].Darken = 1; } else if (button_list[scene_id][i].Darken) { CP_Sound_Play(button_click); Button_Mouse_Collision_Click_ById(i); button_list[scene_id][i].Darken = 0; } } else { button_list[scene_id][i].Darken = 0; } } } } /*! @brief Checks if a mouse is hovering over a button @param id - The ID of the button @return 1 if mouse is over button, 0 if otherwise *//*________________________________________________________________________ _*/ char Button_Mouse_Collision_Check(int id) { if (!Button_temp_bool) { if (CP_Input_GetMouseWorldX() > button_list[scene_id][id].Position.x && CP_Input_GetMouseWorldX() < button_list[scene_id][id].Position.x + button_list[scene_id][id].Size.x && CP_Input_GetMouseWorldY() > button_list[scene_id][id].Position.y && CP_Input_GetMouseWorldY() < button_list[scene_id][id].Position.y + button_list[scene_id][id].Size.y) { button_list[scene_id][id].Hover = 1; return 1; } else { button_list[scene_id][id].Hover = 0; } } else { if (CP_Input_GetMouseWorldX() > button_list[scene_id][id].Position.x - button_list[scene_id][id].Size.x/2.0f && CP_Input_GetMouseWorldX() < button_list[scene_id][id].Position.x + button_list[scene_id][id].Size.x/2.0f && CP_Input_GetMouseWorldY() > button_list[scene_id][id].Position.y && CP_Input_GetMouseWorldY() < button_list[scene_id][id].Position.y + button_list[scene_id][id].Size.y) { button_list[scene_id][id].Hover = 1; return 1; } else { button_list[scene_id][id].Hover = 0; } } return 0; } /*! @brief Gets a button's ID via name @param text - The name of the button (not displayed) @return the ID of the button, -1 if it doesn't exist *//*________________________________________________________________________ _*/ int Button_GetID_By_Name(char* text) { for (int i = 0; i < 127; i++) { if (strcmp(button_list[scene_id][i].Text, text)) { return i; } } return -1; } /*! @brief Functions deciding what happens after button is clicked @param id - The ID of the button *//*________________________________________________________________________ _*/ void Button_Mouse_Collision_Click_ById(int id) { printf("Button Pressed: Scene %d, ID: %d, \"%s\"\n", Scene_GetCurrentID(), id, button_list[Scene_GetCurrentID()][id].Text); switch (Scene_GetCurrentID()) { case 0: { switch (id) { case 4: { TestScene1_BtnManager(); //go next case break; } case 5: { //Run TestScene1_BtnManager() again to close it break; } } break; } case 3: { switch (id) { case 0: // Start { Scene_ChangeScene(2); //0 - testScene 1 //Scene_ChangeScene(0); //0 - testScene 1 //2 - zac testbed break; } case 1: // Survey { /*#ifdef _WIN32 system("start https://forms.gle/wiLHNBcqdAMYVNKY9"); #elif __APPLE__ system("open https://forms.gle/wiLHNBcqdAMYVNKY9"); #elif __linux__ system("xdg-open https://forms.gle/wiLHNBcqdAMYVNKY9"); #endif*/ Scene_ChangeScene(7); break; } case 2: // Credits { Scene_ChangeScene(6); break; } case 3: // Exit { CP_Engine_Terminate(); break; } } break; } } } /*! @brief Checks for mouse collission with specific button via name @param text - The name of the button (not displayed) *//*________________________________________________________________________ _*/ void Button_Mouse_Collision_Click_ByText(char* text) { Button_Mouse_Collision_Click_ById(Button_GetID_By_Name(text)); return; } /*! @brief Renders all the buttons *//*________________________________________________________________________ _*/ void Button_Render_All() { for (int i = 0; i < 127; i++) { if (button_list[scene_id][i].Id == -1) { return; } else if (button_list[scene_id][i].Visible) { Button_Render(i); } } } /*! @brief Renders a specific button by id @param id - The ID of the button *//*________________________________________________________________________ _*/ void Button_Render(int id) { CP_Settings_TextAlignment(CP_TEXT_ALIGN_H_CENTER, CP_TEXT_ALIGN_V_MIDDLE); CP_Settings_Fill(button_list[scene_id][id].Button_Color); if (button_list[scene_id][id].Darken) { CP_Settings_Fill(button_list[scene_id][id].Darken_Color); } else if (button_list[scene_id][id].Hover) { CP_Settings_Fill(button_list[scene_id][id].Hover_Color); } if (button_list[scene_id][id].Image == NULL || button_list[scene_id][id].Enable_SpecialEffects) { CP_Graphics_DrawRect(button_list[scene_id][id].Position.x - (button_list[scene_id][id].Size.x / 2), button_list[scene_id][id].Position.y, button_list[scene_id][id].Size.x * button_list[scene_id][id].Scale, button_list[scene_id][id].Size.y * button_list[scene_id][id].Scale); } if (button_list[scene_id][id].Image != NULL) { CP_Image_Draw(button_list[scene_id][id].Image, button_list[scene_id][id].Position.x, button_list[scene_id][id].Position.y + (button_list[scene_id][id].Size.y / 2), button_list[scene_id][id].Size.x, button_list[scene_id][id].Size.y, 255 - (!!button_list[scene_id][id].Enable_SpecialEffects * 55)); } CP_Settings_Fill(button_list[scene_id][id].Text_Color); CP_Settings_TextSize(button_list[scene_id][id].Text_Size); CP_Font_DrawText(button_list[scene_id][id].Text, button_list[scene_id][id].Text_Position.x, button_list[scene_id][id].Text_Position.y); } void Button_SetTempBool(int b) { Button_temp_bool = b; } /*! @brief Sets a button's image, replace button size with image size @param id - The ID of the button img - The image to set @return 1 after function is complete *//*________________________________________________________________________ _*/ char Button_Image_Set_Override(int id, char* img) { button_list[scene_id][id].Image = CP_Image_Load(img); button_list[scene_id][id].Size.x = (float)CP_Image_GetWidth(button_list[scene_id][id].Image); button_list[scene_id][id].Size.y = (float)CP_Image_GetHeight(button_list[scene_id][id].Image); return 1; } /*! @brief Sets a button's image, size stays te same @param id - The ID of the button img - The image to set @return 1 after function is complete *//*________________________________________________________________________ _*/ char Button_Image_Set(int id, char* img) { button_list[scene_id][id].Image = CP_Image_Load(img); return 1; } /*! @brief Sets a button's special effects level @param id - The ID of the button x - The level of special effects to set *//*________________________________________________________________________ _*/ void Button_SpecialEffects_Set(int id, char x) { button_list[scene_id][id].Enable_SpecialEffects = x; return; } /*! @brief Sets a button to active @param id - The ID of the button x - Toggle for button active @return x after function is complete *//*________________________________________________________________________ _*/ char Button_Active_Set(int id, char x) { button_list[scene_id][id].Active = x; return x; } void Button_Escape() { CP_Settings_TextAlignment(CP_TEXT_ALIGN_H_LEFT, CP_TEXT_ALIGN_V_MIDDLE); } /*! @brief Initializes the button class *//*________________________________________________________________________ _*/ void Button_Class_Init() { for (int i = 0; i < 63; i++) { for (int j = 0; j < 127; j++) { button_list[i][j].Id = -1; } } button_click = CP_Sound_Load("Assets/Cowbell.wav"); }
Java
UTF-8
201
1.960938
2
[ "Apache-2.0" ]
permissive
package pro.alexzaitsev.freepager.library.view.infinite; import android.view.View; /** * * @author A.Zaitsev * */ public interface ViewFactory { View makeView(int vertical, int horizontal); }
Swift
UTF-8
943
2.734375
3
[]
no_license
// // Deposits.swift // Coke // // Created by Deepak on 21/02/17. // Copyright © 2017 IOS Development. All rights reserved. // import Foundation struct Deposit { let depositAmount : Int let productId : Int let productName : String let productQty : Int init(dictionary : [String : AnyObject]) { depositAmount = dictionary["DepositAmount"] as? Int ?? 0 productId = dictionary["ProductId"] as? Int ?? 0 productName = dictionary["ProductName"] as? String ?? "" productQty = dictionary["ProductQty"] as? Int ?? 0 } } struct Emptybottles { let bottleCount : Int let productId : Int let productName : String init(dictionary : [String : AnyObject]) { bottleCount = dictionary["BottleCount"] as? Int ?? 0 productId = dictionary["ProductId"] as? Int ?? 0 productName = dictionary["ProductName"] as? String ?? "" } }
C++
UHC
4,011
3.3125
3
[]
no_license
#include<iostream> #include<string> #include<algorithm> #include<map> #include<tuple> using namespace std; int n, k; string w[2][55]; //Է ־ ܾ . w[0] ״ , w[1]  . const int MOD = 835454957; struct State{ int len; //߰ؾ ϴ ڿ string stick; //Ƣ ڿ int dir; //, ̸ 0, ̸ 1 State(int _len, string _stick, int _dir) :len(_len), stick(_stick), dir(_dir){} bool operator<(const State& t)const{ return make_tuple(len, stick, dir) < make_tuple(t.len, t.stick, t.dir); } }; map<State, int> D; //¸ ؾ ϹǷ 迭 Ѵ. bool isPalin(const string& s){ //Ӹ ƴ Ȯ int i = 0; int j = s.size() - 1; while (i < j){ if (s[i++] != s[j--]) return false; } return true; } bool starts_with(const string& s1, const string& s2){ //s1 s2 ϴ return s2.size() <= s1.size() && s1.compare(0, s2.size(), s2) == 0; } int go(State state){ if (D.count(state) > 0){ return D[state]; } int ans = 0; if (isPalin(state.stick)){ ans++; } for (int i = 0; i < n; i++){ string s = w[state.dir][i]; if (state.len >= (int)s.size()){ // ߰ؾߵǴ ڿ s ̰ ߰ؾ Ǵ ڿ len ۴ٸ, if (starts_with(state.stick, s)){ //Ƣ ڿ stick s ϴ // ¿ Ƣ ڰ, ߰Ϸ s ̰ ans = (ans + go({ (int)state.len - (int)s.size() - 1, state.stick.substr(s.size()), state.dir })) % MOD; // ٲ ʰ ܼ ߰Ϸ Ƣ ڰ ٲ. } else if (starts_with(s, state.stick)){ //ڿ s Ƣ ڿ b ϴ ans = (ans + go({ (int)state.len - (int)s.size() - 1, s.substr(state.stick.size()), 1 - state.dir })) % MOD; // ٲ. } } } D[state] = ans; return ans; } int main(){ ios::sync_with_stdio(false); cin.tie(0); cin >> n >> k; for (int i = 0; i < n; i++){ cin >> w[0][i]; w[1][i] = w[0][i]; reverse(w[1][i].begin(), w[1][i].end()); } int ans = go({ k, "", 0 }) - 1; // ڿ ԽŰ ʱ -1 if (ans < 0) { ans = MOD - 1; } cout << ans; return 0; } //WeissBlume ڵ //#include<bits/stdc++.h> //using namespace std; //using ll = long long; //const int MOD(835454957); // //int n, m, len[55]; //char s[2][55][16]; //int d[111][22][55][2]; // //inline bool is_palindrome(const string& x) { // for (int i = 0; i + i < x.size(); i++) // if (x[i] != x[x.size() - i - 1]) // return false; // return true; //} // //int go(const int left, const int covered, const int last, const int flip) //{ // int &ret = d[left][covered][last][flip]; // if (~ret) return ret; // ret = is_palindrome(string(s[flip][last]).substr(covered)); // // for (int i = 0; i < n; i++) if (left > len[i]) { // const int minl = min(len[last] - covered, len[i]); // int matches = 0; // for (int j = 0; j < minl; j++) { // if (s[flip][last][covered + j] == s[!flip][i][j]) ++matches; // else break; // } // if (matches < minl) continue; // if (covered + matches >= len[last]) { // ret = (ret + go(left - len[i] - 1, matches, i, !flip)) % MOD; // } // else { // ret = (ret + go(left - len[i] - 1, covered + matches, last, flip)) % MOD; // } // } // // return ret; //} // //int main() //{ // scanf("%d%d", &n, &m); // for (int i = 0; i < n; i++) { // scanf("%s", s[0][i]), len[i] = strlen(s[0][i]); // for (int j = 0; j < len[i]; j++) s[1][i][len[i] - 1 - j] = s[0][i][j]; // } // // int ans = 0; // memset(d, -1, sizeof d); // for (int i = 0; i < n; i++) if (m >= len[i]) { // ans = (ans + go(m - len[i], 0, i, 0)) % MOD; // } // // printf("%d\n", ans); // return 0; //}
Java
UTF-8
632
2.609375
3
[]
no_license
package BidInfoData; import Client.ClientInfo; import java.util.Date; /** * Created by Namila on 10/6/2017. */ public class BidInfo { private ClientInfo clientInfo; private double bidValue; private Date date; public BidInfo(ClientInfo clientInfo,double bidvalue){ this.clientInfo=clientInfo; this.bidValue=bidvalue; this.date=new Date(); } public String getClientInfo() { return clientInfo.getClientname(); } public double getBidValue() { return bidValue; } public Date getDate() { return date; } }
Markdown
UTF-8
2,142
3.21875
3
[]
no_license
--- layout: post title: mimno给的机器学习建议 category: 资源帖 tags: [数据科学, 资源合集] description: mimno的机器学习建议 --- written by david mimno One of my students recently asked me for advice on learning ML. Here’s what I wrote. It’s biased toward my own experience, but should generalize. > 推荐三本书 My current favorite introduction is Kevin Murphy’s book (Machine Learning). You might also want to look at books by Chris Bishop (Pattern Recognition), Daphne Koller (Probabilistic Graphical Models), and David MacKay (Information Theory, Inference and Learning Algorithms). >基础很重要 Anything you can learn about linear algebra and probability/statistics will be useful. Strang’s Introduction to Linear Algebra, Gelman, Carlin, Stern and Rubin’s Bayesian Data Analysis, and Gelman and Hill’s Data Analysis using Regression and Multilevel/Hierarchical models are some of my favorite books. > 要反复读,从不同的角度和资料里 Don’t expect to get anything the first time. Read descriptions of the same thing from several different sources. > 要学会模型的实现,学习开源算法 There’s nothing like trying something yourself. Pick a model and implement it. Work through open source implementations and compare. Are there computational or mathematical tricks that make things work? >多读论文! Read a lot of papers. When I was a grad student, I had a 20 minute bus ride in the morning and the evening. I always tried to have an interesting paper in my bag. The bus isn’t the important part — what was useful was having about half an hour every day devoted to reading. > 深入思考和理解公式 Pick a paper you like and “live inside it” for a week. Think about it all the time. Memorize the form of each equation. Take long walks and try to figure out how each variable affects the output, and how different variables interact. Think about how you get from Eq. 6 to Eq. 7 — authors often gloss over algebraic details. Fill them in. > 坚持 Be patient and persistent. Remember von Neumann: “in mathematics you don’t understand things, you just get used to them.”
Python
UTF-8
1,499
4.375
4
[]
no_license
#!/usr/bin/python # Env: python3 # Rewrite by afei_0and1 ''' 34、罗马数字转整数 罗马数字表示: I #表示数值:1 V #表示数值:5 X #表示数值:10 L #表示数值:50 C #表示数值:100 D #表示数值:500 M #表示数值:1000 罗马数字书写规则: 一般情况下罗马数字在编写时,如果小的数字出现在大的数字的右边,则它们是相加关系。例如数值2 会写作II;当小的数字出现在大的数字左边时,它们是相减关系。例如:数值4会写作IV。对于小的数字出现 在大的数字左边的情况,只有如下几种: IV #4 IX #9 XL #40 XC #90 CD #400 CM #900 现在输入一个字符串类型的罗马数字,将其转换为整数输出,数值的输入范围大于0且小于4000。 ''' def romanNum_TransInteger(num): #罗马数字与数值建立映射关系 dic = {"I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000} res = 0 for i in range(0, len(num)): if i < len(num) - 1: j = i + 1 n1 = num[i] #取出第一个罗马数字 n2 = num[j] #取出第二个罗马数字 #进行左右大小判断 if n1 >= n2: res += dic[num[i]] else: res -= dic[num[i]] else: res += dic[num[i]] return res print(romanNum_TransInteger("IV")) ''' Output result: 4 '''
Python
UTF-8
2,255
2.90625
3
[]
no_license
import numpy as np from music21 import * def load_midi_file(path): mf = midi.MidiFile() mf.open(path, 'rb') # read in the midi file mf.read() mf.close() return mf def lowest_highest_octave(stream): # octaves = [note.pitch.octave for note in stream.flat.notes] # return min(octaves), max(octaves) lowest = 10 highest = 0 for note in stream.flat.notes: if note.isChord: octaves = [p.octave for p in note.pitches] lowest = min(octaves) if min(octaves) < lowest else lowest highest = max(octaves) if max(octaves) > highest else highest else: octave = note.pitch.octave lowest = octave if octave < lowest else lowest highest = octave if octave > highest else highest return lowest, highest def fill_note_in_array(array, offset, duration, octave, pitch): offset = int(offset * 4) height = (octave - 1) * 12 + pitch while height < 0: height += 12 while height > 71: height -= 12 for time_slice in range(offset, offset + int(duration * 4)): array[height][time_slice] = 1 def stream_to_2d_array(stream): array_width = int(stream.highestTime + 0.95) * 4 array = np.zeros([72, array_width]) for note in stream.flat.notes: if note.isChord: for pitch in note.pitches: fill_note_in_array(array, note.offset, note.duration.quarterLength, pitch.octave, pitch.pitchClass) else: fill_note_in_array(array, note.offset, note.duration.quarterLength, note.pitch.octave, note.pitch.pitchClass) return array def print_array(array): with open('output', 'w') as f: for pitch in range(array.shape[0]-1, -1, -1): f.write("".join([str(int(n)) for n in array[pitch, :]]) + '\n') def print_events(event_array): print("\n".join([str(event.offset)+" "+str(event) for event in event_array])) # filename = 'data/midi-classic-music/Satie/Gymnopedie No.1.mid' filename = 'data/midi-classic-music/Rachmaninov/srapco31.mid' # filename = 'data/midi-classic-music/Chopin/Etude No.1.mid' mf = load_midi_file(filename) stream = midi.translate.midiFileToStream(mf) array = stream_to_2d_array(stream)
Markdown
UTF-8
1,122
3.046875
3
[]
no_license
# 第1章 IPv6 IPv6 是指第 6 版因特网协议(Internet Protocol version 6),在它的名字中已经表明了它的重要性 —— 与因特网一样重要!因特网协议(Internet Protocol,简称 IP)是解决不同网络间互联需求的解决方案,并且已经成为了各种数字通信的“事实标准”。现在,大多数能够收发数字信息的设备都存在因特网协议。 IETF(Internet Engineering Task Force)组织负责对因特网协议进行标准化工作。通过标准化,可以保证不同厂商的软件具有通用性。因特网协议是一个至关重要的标准,因为现在几乎所有的东西都使用因特网协议连接到互联网中。所有的通用操作系统和网络库都支持通过因特网协议进行收发数据。换句话说,在现如今的生活中,因特网协议标准是收发数据的基础。而物联网是指将一切物件连接到因特网,需要使用 IPv6。所以我们要先介绍 IPv6。 本章主要内容: * IP 的历史 * IPv6 的作用 * IPv6 的相关概念 * IPv6 地址以及 IPv6 网络的宏观描述
C++
UTF-8
2,349
3.578125
4
[]
no_license
#include <iostream> using namespace std; class PersonaV4 { /* - MODIFICADORES DE ACCESO - +------------------------------------------------------------------+ | Modificador | Clase | SubClase | Paquete | Todos | +------------------+-----------+-----------+-----------+-----------| | public | sí | sí | sí | sí | +------------------+-----------+-----------+-----------+-----------| | private | sí | no | no | no | +------------------+-----------+-----------+-----------+-----------| | protected | sí | sí | sí | no | +------------------+-----------+-----------+-----------+-----------| */ private: string nombre; int edad; float estatura; public: string getNombre() { return this->nombre; } void setNombre(string nombre) { if (nombre.empty()) { this->nombre = "Indefinido"; cout << "Nombre vacio, verifique" << endl; } else { this->nombre = nombre; } } int getEdad() { return this->edad; } void setEdad(int edad) { if (edad < 0 || edad > 100) { this->edad = 0; cout << "No se admiten edades negativas o mayores a 100 años" << endl; } else { this->edad = edad; } } float getEstatura() { return this->estatura; } void setEstatura(float estatura) { if (estatura < 0.5f || estatura > 3.0f) { this->estatura = 0.5f; cout << "No se admiten estaturas menores a 0.5m o mayores a 3.0m" << endl; } else { this->estatura = estatura; } } string toString() { return "{nombre='" + nombre + "'" + ", edad='" + std::to_string(edad) + "'" + ", estatura='" + std::to_string(estatura) + "'" + "}"; } }; int main(int argc, char const *argv[]) { PersonaV4 persona = PersonaV4(); persona.setNombre(""); persona.setEdad(-4); persona.setEstatura(313.0f); cout << persona.toString() << endl; /* Nombre vacio, verifique No se admiten edades negativas o mayores a 100 años No se admiten estaturas menores a 0.5m o mayores a 3.0m { nombre='Indefinido', edad='0', estatura='0.5'} */ return 0; }
JavaScript
UTF-8
2,457
2.875
3
[ "MIT" ]
permissive
const http = require('http'); const net = require('net'); module.exports = (function() { function Howru(options) { this.type = options.type || 'http'; if (this.type == 'http') { this.route = options.route || '/health'; this.port = options.port || 6999; } else if (this.type == 'tcp') { this.port = options.port || 6999; } else if (this.type == 'ttl') { this.host = options.host || 'localhost'; this.port = options.port || 6999; this.path = options.path || '/'; this.interval = options.interval || 10000; } this.status = 200; this.server = null; } Howru.prototype.status = function() { return this.status; } Howru.prototype.stop = function() { if (this.type == 'http') { this.server.close(); } else if (this.type == 'tcp') { this.server.close(); } } Howru.prototype.died = function() { this.status = 500; } Howru.prototype.start = function() { if (this.type == 'http') { this.server = http.createServer((req, res) => { if (req.url == this.route) { res.writeHead(this.status, {'Content-Type': 'text/plain'}); res.end(); } }); this.server.listen(this.port); } else if (this.type == 'tcp') { this.server = net.createServer() this.server.on('connection', (sock) => { sock.on('end', () => {}); sock.on('data', (data) => { sock.write(String(this.status)); }) }); this.server.listen(this.port); } else if (this.type == 'ttl') { let req = http.request({ host: this.url, port: this.port, method: 'PUT', path: this.path }); req.write('OK'); setInterval(() => { req.write(String(this.status)); }, this.interval); req.on('error', (e) => { req.end(); console.log(`problem with request: ${e.message}`); }); } else { throw new Error('not implemented yet'); // push health status } } return Howru; }());