language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
1,394
2.296875
2
[]
no_license
package com.tecsup.gestion.dao; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import com.tecsup.gestion.exception.DAOException; import com.tecsup.gestion.exception.EmptyResultException; import com.tecsup.gestion.mapper.DepartmentsMapper; import com.tecsup.gestion.model.Departments; @Repository public class DepartmentsDAOImpl implements DepartmentsDAO { private static final Logger logger = LoggerFactory.getLogger(DepartmentsDAOImpl.class); @Autowired private JdbcTemplate jdbcTemplate; @Override public Departments findDepartments(int department_id) throws DAOException, EmptyResultException { String query = "SELECT department_id, name, description, city, department_id " + " FROM departments WHERE department_id = ?"; Object[] params = new Object[] { department_id }; try { Departments depa = (Departments) jdbcTemplate.queryForObject(query, params, new DepartmentsMapper()); // return depa; //return null; } catch (EmptyResultDataAccessException e) { throw new EmptyResultException(); } catch (Exception e) { logger.info("Error: " + e.getMessage()); throw new DAOException(e.getMessage()); } } }
TypeScript
UTF-8
982
2.5625
3
[]
no_license
import { StateObjectType, StoreObjectType } from '@samsite/store/types'; import { TravelLocalityStateType } from '@samsite/store/handlers/travel/types'; import { getAllTravelLocalitiesSelector } from '@samsite/selectors/travel/localities'; export const getAllTravelLocalitiesGroupedByCountryCodeSelector = ( state: StoreObjectType<TravelLocalityStateType>, ): StateObjectType<TravelLocalityStateType[]> => { const allLocalities = getAllTravelLocalitiesSelector(state); return allLocalities && Object.keys(allLocalities).length && Object.values(allLocalities).reduce( ( acc: StateObjectType<TravelLocalityStateType[]>, locality: TravelLocalityStateType, ): StateObjectType<TravelLocalityStateType[]> => { if (!(locality.countryCode in acc)) { acc[locality.countryCode] = []; } acc[locality.countryCode].push(locality); return acc; }, {}, ); };
Python
UTF-8
159
3.8125
4
[]
no_license
rev=0 num=int(input("Enter a number:")) while(num>0): dig=num%10 rev=rev*10+dig num=num//10 print("the reverse of number is {0}".format(rev))
Java
UTF-8
520
1.875
2
[]
no_license
package com.snaplogic.snaps.systempropertytest; import com.snaplogic.account.api.AccountType; import com.snaplogic.account.api.capabilities.AccountCategory; import com.snaplogic.snap.api.capabilities.General; import com.snaplogic.snap.api.capabilities.Version; /** * Created by Syed on 31/3/17. */ @General(title = "Dynamic Account") @Version(snap = 1) @AccountCategory(type = AccountType.CUSTOM) public class DynamicAccount extends CommonAccount { public DynamicAccount() { super.p1Exp = true; } }
Java
UTF-8
951
2.5
2
[ "Apache-2.0" ]
permissive
package org.openintents.cmfilemanager.compatibility; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; public class BitmapDrawable_Compatible { private static boolean use_SDK_1_6 = true; /** * Replaces "new BitmapDrawable(context.getResources(), bitmap)" available only in SDK 1.6 and higher. * * @param resources * @param bitmap * @return */ public static BitmapDrawable getNewBitmapDrawable(Resources resources, Bitmap bitmap) { BitmapDrawable b = null; if (use_SDK_1_6) { try { // SDK 1.6 compatible version b = BitmapDrawable_SDK_1_6.getNewBitmapDrawable(resources, bitmap); } catch (VerifyError e) { // SDK 1.5 compatible version: use_SDK_1_6 = false; b = new BitmapDrawable(bitmap); } } else { // SDK 1.5 compatible version: b = new BitmapDrawable(bitmap); } return b; } }
JavaScript
UTF-8
2,485
2.65625
3
[]
no_license
$(function () { //获取验证码功能 $(".btn_vcode").on("click", function () { //1. 只要点击了,先禁用按钮 var tel = $("#tel").val() console.log(tel) if(!tel){ mui.toast("请输入手机号") return false } var $this = $(this); $this.prop("disabled", true).addClass("disabled") var count = 5; var timer = setInterval(function () { count--; $this.text(count+"s"); //当时间为0 if(count === 0){ clearInterval(timer); //让按钮能点 $this.prop("disabled", false).removeClass("disabled").text("重新发送"); } }, 1000); //2. 发送ajax请求 $.ajax({ type:"POST", url:"http://47.100.3.125/api/verificationCodes", data:{ phone:tel }, success:function(res){ console.log(res) localStorage.setItem("key",res.data.key) console.log(typeof(res.data.key)) }, error:function(res){ if(res.status == 422){ mui.toast("手机号已注册") } } }); }); //注册功能 $(".regster").on("click", function (e) { e.preventDefault(); var username = $("[name='username']").val(); var password = $("[name='password']").val(); var repassword = $("[name='repassword']").val(); var mobile = $("[name='mobile']").val(); var vCode = $("[name='vCode']").val(); if(!mobile){ mui.toast("请输入手机号"); return false; } if(password.length<6){ mui.toast("密码长度至少为6位"); return false; } if(!password){ mui.toast("请输入密码"); return false; } if(repassword != password){ mui.toast("两次输入的密码不一致"); return false; } if(!/^1[34578]\d{9}$/.test(mobile)){ mui.toast("手机号码格式不对"); return false; } if(!vCode){ mui.toast("请输入手机验证码"); return false; } var key = localStorage.getItem("key") console.log(key) $.ajax({ type:"POST", url:"http://47.100.3.125/api/users", data:{ verification_key:key, verification_code:vCode, password:password }, success:function(res){ console.log(res) if(res.status_code == 200){ mui.toast("注册成功") // location.href = "login.html" } } }); }); });
Shell
UTF-8
568
3.34375
3
[]
no_license
#!/usr/bin/env bash # Break on error set -e # Get import dir SCRIPT_DIR="$(dirname $(realpath "${BASH_SOURCE[0]}"))" # Source shared files source "${SCRIPT_DIR}/.environment" source "${SCRIPT_DIR}/.functions" # Log start console_log "$0: Starting..." # rsnapshot console_log "Running rsnapshot..." sudo rsnapshot -c "${SCRIPT_DIR}/.rsnapshot.conf" upgrade # Create snapshot file console_log "Unmounting external FS..." sudo umount ${ARCH_UPDATE_EXTERNAL_MNT} # Run the update console_log "Pacman update..." yay -Syu $* # Log finish console_log "$0: Finished."
JavaScript
UTF-8
987
2.78125
3
[]
no_license
import React, { useCallback, useEffect, useState } from 'react'; import '../02-useEffect/effects.css'; import { ShowIncrement } from './ShowIncrement'; export const CallbackHook = () => { const [counter, setCounter] = useState(10); // const increment = () => { // setCounter(counter+1); // } /* regresará una version memorizada de esa funcion para mandarla como argumento, si la dependecia no ha cambiado */ const increment = useCallback((num) => { setCounter(c => c+num); /* se coloca de esta manera para eliminar la dependencia*/ }, [setCounter]); /* counter no porque siempre se volverá a ejecutar esa funcion bc tiene la misma dependencia */ useEffect(() => { /* ??? */ }, [increment]) return ( <div> <h1>UseCallback Hook: {counter}</h1> <hr /> <ShowIncrement increment={increment}/> {/* se ocupa a fuerza el react memo */} </div> ) }
C++
UTF-8
1,739
2.96875
3
[]
no_license
#pragma once #include <map> #include "Commands.h" #include "CommandsEnvironment.h" class CommandsVisitorBase { public: //virtual void onVisit(const Command& command) = 0; virtual void onVisit(const SequentialCommand& ) = 0; virtual void onVisit(const EmptyCommand&) = 0; virtual void onVisit(const CallCommand& call_command) = 0; virtual void onVisit(const DeclareProcedureCommand& call_command) = 0; virtual void onVisit(const TurtleCommand& turtle_command) = 0; virtual void onVisit(const IfCommand& if_command) = 0; virtual void onVisit(const RepeatCommand& repeat_command) = 0; virtual void onVisit(const AssignCommand& assign_command) = 0; }; class CommandsVisitor : public CommandsVisitorBase { private: CommandsEnvironment environment; void throwExecutionError(const std::string& message, const Command& command) const; public: explicit CommandsVisitor(const CommandsEnvironment& environment) : environment(environment) { } explicit CommandsVisitor(std::shared_ptr<TurtleState> turtleState) : environment(CommandsEnvironment(turtleState)) { } CommandsEnvironment get_environment() const { return environment; } // Inherited via VisitorBase void onVisit(const EmptyCommand&) override; void onVisit(const SequentialCommand& ) override; void onVisit(const CallCommand& call_command) override; void onVisit(const DeclareProcedureCommand& call_command) override; void onVisit(const TurtleCommand& turtle_command) override; void onVisit(const IfCommand& if_command) override; void onVisit(const RepeatCommand& repeat_command) override; void onVisit(const AssignCommand& assign_command) override; static CommandsVisitor createNestedVisitor(const CommandsEnvironment& nestedEnvironment); };
Swift
UTF-8
2,244
2.890625
3
[]
no_license
// // ShopService.swift // shishaLog // // Created by 宮本一成 on 2020/07/15. // Copyright © 2020 ISSEY MIYAMOTO. All rights reserved. // import Firebase struct ShopCredentials { let shopName: String let shopAddress: String let shopImage: UIImage } struct ShopService { static let shared = ShopService() // shop情報の登録を行う func registerShop(credentials: ShopCredentials, completion: @escaping(Error?, DatabaseReference) -> Void){ guard let imageData = credentials.shopImage.jpegData(compressionQuality: 0.3) else { return } let filename = NSUUID().uuidString let storageRef = STORAGE_SHOP_IMAGE.child(filename) storageRef.putData(imageData, metadata: nil) { (meta, error) in storageRef.downloadURL { (url, error) in if let error = error { print("DEBUG: error is \(error.localizedDescription)") } guard let shopImageUrl = url?.absoluteString else { return } let values = [ "shopName": credentials.shopName, "shopAddress": credentials.shopAddress, "shopImageUrl": shopImageUrl, ] as [String: Any] REF_SHOPS.childByAutoId().updateChildValues(values, withCompletionBlock: completion) } } } func fetchAllShops(completion: @escaping(([Shop]) -> Void)){ var shops = [Shop]() REF_SHOPS.observe(.childAdded) { (snapshot) in guard let dictionary = snapshot.value as? [String: Any] else { return } let shop = Shop(shopID: snapshot.key, dictionary: dictionary) shops.append(shop) completion(shops) } } // 一件だけ取得 func fetchSomeShop(shopID: String, completion: @escaping(Shop) -> Void){ REF_SHOPS.child(shopID).observeSingleEvent(of: .value) { (snapshot) in guard let dictionary = snapshot.value as? [String: Any] else { return } let shop = Shop(shopID: shopID, dictionary: dictionary) completion(shop) } } }
JavaScript
UTF-8
487
3.34375
3
[]
no_license
//method overloading class Maths{ add=()=>{ console.log("no arg method") } add=(no1)=>{ console.log("one arg method") } add=(no1,no2)=>{ console.log("two arg method") } } var math=new Maths() math.add(10) // will execute only recently implemented method //method overriding class Parent{ phone=()=>{ console.log("have nokia 5310") } } class Child extends Parent{ phone=()=>{ console.log("have iphone12") } } var ch=new Child() ch.phone()
TypeScript
UTF-8
645
2.71875
3
[]
no_license
/** * news model */ export class News { /** * news model * @param created date * @param description description * @param link link too article * @param title title * @param url url * @param enclosures img info */ constructor ( public created: number, public description: string, public link: string, public title: string, public url: string, public enclosures: [Enclosures]) {} } /** * enclosure model */ export class Enclosures { /** * length */ length: String; /** * img type */ type: String; /** * img url */ url: String; }
Java
UTF-8
2,562
2.5
2
[ "MIT" ]
permissive
package domain; import java.io.Serializable; public class Food implements Serializable{ private int code,hit=0; private String name, maker, material, image; private double supportpereat, calory, carbo, protein, fat, sugar, natrium, chole, fattyacid, transfat; private String allergy; public Food() { super(); } public Food(int code, String name, String maker, String material, String image) { super(); this.code = code; this.name = name; this.maker = maker; this.material = material; this.image = image; hit = 0; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMaker() { return maker; } public void setMaker(String maker) { this.maker = maker; } public String getMaterial() { return material; } public void setMaterial(String material) { this.material = material; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public double getSupportpereat() { return supportpereat; } public void setSupportpereat(double supportpereat) { this.supportpereat = supportpereat; } public double getCalory() { return calory; } public void setCalory(double calory) { this.calory = calory; } public double getCarbo() { return carbo; } public void setCarbo(double carbo) { this.carbo = carbo; } public double getProtein() { return protein; } public void setProtein(double protein) { this.protein = protein; } public double getFat() { return fat; } public void setFat(double fat) { this.fat = fat; } public double getSugar() { return sugar; } public void setSugar(double sugar) { this.sugar = sugar; } public double getNatrium() { return natrium; } public void setNatrium(double natrium) { this.natrium = natrium; } public double getChole() { return chole; } public void setChole(double chole) { this.chole = chole; } public double getFattyacid() { return fattyacid; } public void setFattyacid(double fattyacid) { this.fattyacid = fattyacid; } public double getTransfat() { return transfat; } public void setTransfat(double transfat) { this.transfat = transfat; } public String getAllergy() { return allergy; } public void setAllergy(String allergy) { this.allergy = allergy; } public int getHit() { return hit; } public void setHit(int hit) { this.hit = hit; } }
C#
UTF-8
3,241
3.15625
3
[]
no_license
using System; using System.Collections.Generic; using System.Data.SqlClient; using Users.BusinessLogic; namespace Users.Data { public class UserRepository : IUserRepository { private readonly SqlConnection _connection; public UserRepository(SqlConnection connection) { _connection = connection; } public List<User> GetAll() { var list = new List<User>(); var query = $"select * from users"; var command = new SqlCommand { CommandText = query, Connection = _connection }; var reader = command.ExecuteReader(); while (reader.Read()) { var userId = (int)reader["id"]; var userName = reader["username"] as string; var email = reader["email"] as string; var description = reader["description"] as string; var city = reader["city"] as string; var street = reader["street"] as string; list.Add(new User { Id = userId, Email = email, Description = description, Username = userName, Street = street, City = city }); } return list; } public IList<User> GetAll() { string sqlString = "SELECT * FROM USERS"; SqlCommand sqlCommand = new SqlCommand(sqlString, sqlConnection); sqlConnection.Open(); SqlDataReader reader = sqlCommand.ExecuteReader(); // Create list to store users IList<User> users = new List<User>(); while (reader.Read()) { users.Add(new User { Id = (int)reader["ID"], UserName = reader["USERNAME"] as string, Email = reader["EMAIL"] as string, Description = reader["DESCRIPTION"] as string, City = reader["CITY"] as string, Street = reader["STREET"] as string }); } sqlConnection.Close(); return users; } public User GetById(int id) { User user = new User(); string sqlString = "SELECT * FROM USERS WHERE ID = @id"; SqlCommand sqlCommand = new SqlCommand(sqlString, sqlConnection); sqlCommand.Parameters.Add(new SqlParameter { ParameterName = "id", Value = id }); sqlConnection.Open(); SqlDataReader reader = sqlCommand.ExecuteReader(); while (reader.Read()) { user.Id = (int)reader["ID"]; user.UserName = reader["USERNAME"] as string; user.Email = reader["EMAIL"] as string; user.Description = reader["DESCRIPTION"] as string; user.City = reader["CITY"] as string; user.Street = reader["STREET"] as string; } sqlConnection.Close(); return user; } } }
Java
UTF-8
2,588
2.578125
3
[]
no_license
package com.aaron.springweb.dao; import org.apache.ibatis.jdbc.SQL; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * Created by Administrator on 2016/9/29. */ public class TestMybatis { @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testSql() { String sql = selectPersonSql(); sql = selectPersonLike("11","aaron","qiu"); System.out.println(sql); } private String selectPersonSql() { return new SQL() {{ SELECT("P.ID, P.USERNAME, P.PASSWORD, P.FULL_NAME"); SELECT("P.LAST_NAME, P.CREATED_ON, P.UPDATED_ON"); FROM("PERSON P"); FROM("ACCOUNT A"); INNER_JOIN("DEPARTMENT D on D.ID = P.DEPARTMENT_ID"); INNER_JOIN("COMPANY C on D.COMPANY_ID = C.ID"); WHERE("P.ID = A.ID"); WHERE("P.FIRST_NAME like ?"); OR(); WHERE("P.LAST_NAME like ?"); GROUP_BY("P.ID"); HAVING("P.LAST_NAME like ?"); OR(); HAVING("P.FIRST_NAME like ?"); ORDER_BY("P.ID"); ORDER_BY("P.FULL_NAME"); }}.toString(); } // With conditionals (note the final parameters, required for the anonymous inner class to access them) public String selectPersonLike(final String id, final String firstName, final String lastName) { return new SQL() {{ SELECT("P.ID, P.USERNAME, P.PASSWORD, P.FIRST_NAME, P.LAST_NAME"); FROM("PERSON P"); if (id != null) { WHERE("P.ID like #{id}"); } if (firstName != null) { WHERE("P.FIRST_NAME like #{firstName}"); } if (lastName != null) { WHERE("P.LAST_NAME like #{lastName}"); } ORDER_BY("P.LAST_NAME"); }}.toString(); } public String deletePersonSql() { return new SQL() {{ DELETE_FROM("PERSON"); WHERE("ID = #{id}"); }}.toString(); } public String insertPersonSql() { return new SQL() {{ INSERT_INTO("PERSON"); VALUES("ID, FIRST_NAME", "#{id}, #{firstName}"); VALUES("LAST_NAME", "#{lastName}"); }}.toString(); } public String updatePersonSql() { return new SQL() {{ UPDATE("PERSON"); SET("FIRST_NAME = #{firstName}"); WHERE("ID = #{id}"); }}.toString(); } }
Java
UTF-8
4,096
2.34375
2
[]
no_license
package io.simondev.demoinflearnrestapi.configs; import io.simondev.demoinflearnrestapi.accounts.AccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.security.servlet.PathRequest; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore; @Configuration // @EnableWebSecurity 애노테이션을 설정하고, WebSecurityConfigurerAdapter를 상속받는 순간 // Spring Boot가 제공해주는 default Spring Security 설정은 더 이상 적용이 되지 않는다. // 즉, 여기에 적용하는 설정만 적용된다. @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired AccountService accountService; // 스프링 시큐리티의 UserDetailsService @Autowired PasswordEncoder passwordEncoder; // OAuth 토큰을 저장하는 곳인데, 빈으로 등록한다. @Bean public TokenStore tokenStore() { return new InMemoryTokenStore(); } // AuthenticationManager를 빈으로 노출시켜준다. // 그러면 다른 AuthorizationServer나 ResourceServer가 참조할 수 있게 된다. @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } // AuthenticationManager를 어떻게 만들지 재정의 @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(accountService) // UserDetailsService 설정 .passwordEncoder(passwordEncoder); // PasswordEncoder 설정 } // 필터를 적용할지 말지 걸러낸다. (스프링 시큐리티에 들어오지도 않는다) // static이나 문서 같은 경우에는 서버에서 조금이라도 덜 일하게 하려면, // WebSecurity를 적용하여 배재시키는게 더 좋은 방법이다. @Override public void configure(WebSecurity web) throws Exception { web.ignoring().mvcMatchers("/docs/index.html"); web.ignoring().requestMatchers(PathRequest.toStaticResources().atCommonLocations()); // 정적 리소스 } // @Override // protected void configure(HttpSecurity http) throws Exception { // // 스프링 시큐리티로 들어온 다음, 특정 파일들을 anonymous로 허용한다. // // 죽, 아무나 접근할 수 있는 요청을 만드는 것이다. //// http.authorizeRequests() //// .mvcMatchers("/docs/index.html").anonymous() //// .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).anonymous(); // // http // .anonymous() // 익명 사용자를 허용한다. // .and() // .formLogin() // 폼 인증을 사용한다. // .and() // .authorizeRequests() // //.mvcMatchers(HttpMethod.GET, "/api/**").anonymous() // 내가 허용할 메서드를 설정 // .mvcMatchers(HttpMethod.GET, "/api/**").authenticated() // 테스트를 위해 인증으로 설정 // .anyRequest().authenticated(); // 나머지는 인증이 필요로 하다. // } }
C++
UTF-8
2,662
2.546875
3
[]
no_license
#pragma once #include "SUtils.h" #include "SDxBasic.h" class SArcBall { private: D3DXMATRIXA16 m_mRotation; // Matrix for arc ball's orientation D3DXMATRIXA16 m_mTranslation; // Matrix for arc ball's position D3DXMATRIXA16 m_mTranslationDelta; // Matrix for arc ball's position POINT m_Offset; // window offset, or upper-left corner of window UINT m_nWidth; // arc ball's window width UINT m_nHeight; // arc ball's window height D3DXVECTOR2 m_vCenter; // center of arc ball float m_fRadius; // arc ball's radius in screen coords float m_fRadiusTranslation; // arc ball's radius for translating the target D3DXQUATERNION m_qDown; // Quaternion before button down D3DXQUATERNION m_qNow; // Composite quaternion for current drag bool m_bDrag; // Whether user is dragging arc ball POINT m_ptLastMouse; // position of last mouse point D3DXVECTOR3 m_vDownPt; // stating point of rotation arc D3DXVECTOR3 m_vCurrentPt; // current point of rotation arc public: D3DXVECTOR3 ScreenToVector(float fScreenPtX, float fScreenPtY); static D3DXQUATERNION WINAPI QuatFromBallPoints(const D3DXVECTOR3 &vForm, const D3DXVECTOR3 &vTo); public: // Functions to change behavior void Reset(); void SetWindow(int nWidth, int nHeight, float fRadius = 0.9f); void SetOffset(int nX, int nY); // Call these from client and use GetRotationMatrix() to read new rotation matrix void OnBegin(int nX, int nY); // start the rotation(pass current mouse position) void OnMove(int nX, int nY); // continue the rotation void OnEnd(); // end the rotation // Or call this to automatically handle left, middle right buttons //LRESULT HandleMessages(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); // Functions to get/set state const D3DXMATRIX* GetRotationMatrix() { return D3DXMatrixRotationQuaternion(&m_mRotation, &m_qNow); } PROPERTY_G(GetTranslationMatrix) D3DXMATRIX& _mTranslation; const D3DXMATRIX& GetTranslationMatrix()const { return m_mTranslation; } PROPERTY_G(GetTranslationDeltaMatrix) D3DXMATRIX& _mTranslationDelta; const D3DXMATRIX& GetTranslationDeltaMatrix()const { return m_mTranslationDelta; } PROPERTY_G(isBeingDragged) bool _bDrag; bool isBeingDragged() const { return m_bDrag; } PROPERTY_S(SetTranslationRadius) float& _fRadiusTranslation; void SetTranslationRadius(float fRadiusTranslation) { m_fRadiusTranslation = fRadiusTranslation; } PROPERTY(GetQuatNow, SetQuatNow) D3DXQUATERNION _qNow; D3DXQUATERNION GetQuatNow() const { return m_qNow; } void SetQuatNow(D3DXQUATERNION q) { m_qNow = q; } public: SArcBall(); ~SArcBall(); };
C++
UTF-8
1,141
3.234375
3
[]
no_license
/* 链接:https://www.nowcoder.com/questionTerminal/f72adfe389b84da7a4986bde2a886ec3 来源:牛客网 求字典序在s1和s2之间的,长度在len1到len2的字符串的个数,结果mod 1000007。 输入描述: 每组数据包涵s1(长度小于100),s2(长度小于100),len1(小于100000),len2(大于len1,小于100000) 输出描述: 输出答案。 示例1 输入 ab ce 1 2 输出 56 */ #include <iostream> #include <string> #include <math.h> #include <vector> using namespace std; int main() { string s1, s2; int len1 = 0, len2 = 0; while(cin >> s1 >> s2 >> len1 >> len2) { vector<int> v; if(s1.size() < len2) s1.append(len2 - s1.size(), 'a'); if(s2.size() < len2) s2.append(len2 - s2.size(), 'z' + 1); for(int i = 0; i < len2; ++i) v.push_back(s2[i] - s1[i]); int res = 0; for(int i = len1; i <= len2; ++i) { for(int j = 0; j < i; ++j) res += v[j] * pow(26, i - j - 1); } cout << (res - 1) % 1000007 << endl; } return 0; }
PHP
UTF-8
2,339
2.796875
3
[ "MIT" ]
permissive
<?php namespace App\DwhControl\Common\Traits; use App\DwhControl\Common\Enum\HealthIndicatorStatusEnum; use App\DwhControl\Common\Models\HealthIndicator; use Illuminate\Database\Eloquent\Relations\MorphMany; trait HasHealthIndicatorTrait { /** * @return MorphMany */ public function health_indicators(): MorphMany { return $this->morphMany(HealthIndicator::class, 'belongsToModel'); } /** * @param int $type_id * @param string $name * @return HealthIndicator|null */ public function health_indicator(int $type_id, string $name): ?HealthIndicator { /** @var HealthIndicator|null $indicator */ $indicator = $this->health_indicators()->where('health_indicator_type_id', $type_id)->where('name', $name)->first(); return $indicator; } /** * @param int $type_id * @param string $name * @param HealthIndicatorStatusEnum $status * @param string $status_text * @param float|null $value * @return HealthIndicator */ public function setHealthIndicator(int $type_id, string $name, HealthIndicatorStatusEnum $status, string $status_text = '', float $value = null): HealthIndicator { if (is_null($indicator = $this->health_indicator($type_id, $name))) { $indicator = $this->health_indicators()->create([ 'health_indicator_type_id' => $type_id, 'name' => $name, 'status' => $status, 'status_text' => $status_text, 'value' => $value ]); } else { $indicator->update([ 'status' => $status, 'status_text' => $status_text, 'value' => $value ]); } $this->updateOverallHealth(); return $indicator; } /** * @return $this */ public function updateOverallHealth(): self { $order = HealthIndicatorStatusEnum::orderedByCriticality(); $worst = HealthIndicatorStatusEnum::HEALTH_OK(); $this->health_indicators->each(function (HealthIndicator $indicator) use ($order, &$worst) { if (array_search($indicator->status, $order) > $worst) $worst = $indicator->status; }); $this->health = $worst; return $this; } }
C#
UTF-8
1,253
3.3125
3
[]
no_license
using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Linq; namespace remove_all_marked_elements_of_list { [TestClass] public class TestFixture { [TestMethod] public void Test1() { int[] integerList = new int[] { 1, 1, 2, 3, 1, 2, 3, 4 }; int[] valuesList = new int[] { 1, 3 }; int[] expectedList = new int[] { 2, 2, 4 }; Assert.IsTrue(Kata.Remove(integerList, valuesList).SequenceEqual(expectedList)); } [TestMethod] public void Test2() { int[] integerList = new int[] { 1, 1, 2, 3, 1, 2, 3, 4, 4, 3, 5, 6, 7, 2, 8 }; int[] valuesList = new int[] { 1, 3, 4, 2 }; int[] expectedList = new int[] { 5, 6, 7, 8 }; Assert.IsTrue(Kata.Remove(integerList, valuesList).SequenceEqual(expectedList)); } [TestMethod] public void Test3() { int[] integerList = new int[] { 8, 2, 7, 2, 3, 4, 6, 5, 4, 4, 1, 2, 3 }; int[] valuesList = new int[] { 2, 4, 3 }; int[] expectedList = new int[] { 8, 7, 6, 5, 1 }; Assert.IsTrue(Kata.Remove(integerList, valuesList).SequenceEqual(expectedList)); } } }
Shell
UTF-8
1,519
3.5625
4
[ "CC0-1.0" ]
permissive
#!/bin/bash #Autora: Helena Moreda Boza #Fichero: arpad.sh #Versión:09-04-2015 #Resumen: script que comprueba cada 5 minutos si la mac de nuestro router ha cambiado y nos avisa mediante una ventana emergente en el caso de un posible caso de ataque Man in the Middle. #Exportamos la pantalla para que puedan visualizarse las alertas pantalla=":0" usuario_conectado=`w | grep init | grep $pantalla | awk {'print $1'}` export XAUTHORITY=/home/$usuario_conectado/.Xauthority #Obtengo la ip del router donde: # -n Muestra la tabla de enrutamiento en formato numérico [dirección IP] # tr -s quita los espacios # cut corta la segunda columna iprouter=`sudo route -n|grep UG |tr -s " "|cut -d " " -f2` #Obtengo la mac del router macrouter=`sudo arp -n|grep -w $iprouter|tr -s " "|cut -d " " -f3` #En el caso de que el fichero que contiene la mac no exista lo creamos if [ ! -f /etc/mac_router.txt ]; then sudo touch /etc/mac_router.txt sudo echo $macrouter > /etc/mac_router.txt fi #Metemos en una variable la mac actual del router comprobar=`sudo arp -n|grep -w $iprouter|tr -s " "|cut -d " " -f3` #Metemos en una variable el contenido del fichero que contiene la mac mac=`sudo cat /etc/mac_router.txt` #En el caso de que no coincidan se enviará una alerta mediante ventana emergente if [ "$mac" != "$comprobar" ] then DISPLAY=:0 zenity --warning --text="La mac del router ha cambiado, es posible que esté siendo víctima de un ataque Man in the middle. Su anterior mac era $mac y ahora es $comprobar" fi
JavaScript
UTF-8
1,143
2.796875
3
[]
no_license
import { expect } from 'chai'; import Trip from '../src/Trip.js' import TripRepo from '../src/TripRepo.js'; import sampleTripData from '../src/data/sampleTripData.js'; import destinationData from '../src/data/sampleDestinationData.js' describe('Trip', () => { let sampleTrip; beforeEach(() => { sampleTrip = new Trip(sampleTripData['trips'][0]); }) it('Should be a function', () => { expect(Trip).to.be.a('function'); }) it('Should have a trip id', () => { expect(sampleTrip.id).to.eql(1); }) it('Should have a userID of who took the trip', () => { expect(sampleTrip.userID).to.equal(44); }) it('Should have a destinationID', () => { expect(sampleTrip.destinationID).to.eql(49); }) it('Should have a number of travelers', () => { expect(sampleTrip.travelers).to.eql(1); }) it('Should have a duration', () => { expect(sampleTrip.duration).to.eql(8); }) it('Should have a method that calculates the cost of one trip', () => { const costForRomeTrip = sampleTrip.calculateCostForOneTrip(4, 17, 22, destinationData) expect(costForRomeTrip).to.eql(9592) }) });
C++
SHIFT_JIS
2,001
2.953125
3
[]
no_license
#pragma once #include "TDNLIB.h" //=============================================== // At@xbge[u //=============================================== static const char EP_AlphabetTable[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '-', '*', '/', '!', '?', '#', '$', ' ', '\0' // I[R[h(O͂̍ۂ͂uO͏IvƂ) }; /********************************************/ // OAt@xbg`p(ɃvC[̖O) /********************************************/ class AlphabetRenderer { public: //=============================================== // RXgN^ //=============================================== AlphabetRenderer() :m_pAlphabet(new tdn2DObj("DATA/UI/Other/alphabet.png")) { // }bvRei for (int i = 0; i < _countof(EP_AlphabetTable); i++) { m_id[EP_AlphabetTable[i]] = i; } } //=============================================== // `(c̃At@xbg`) //=============================================== void Render(int x, int y, char c) { int ID = m_id[c]; int srcX, srcY; // ItO(END) if (c == '\0') { srcX = 7, srcY = 7; // ԉE } // else if (c == ' ') { srcX = 6, srcY = 7; // ԉE1 } // ȊO̕ʂ̕ else { srcX = ID % 8, srcY = ID / 8; } m_pAlphabet->Render(x, y, 64, 64, srcX * 64, srcY * 64, 64, 64); } int GetAlphabetID(char c){ return m_id[c]; } private: //=============================================== // oϐ //=============================================== std::unique_ptr<tdn2DObj> m_pAlphabet; // At@xbg̉摜 std::map<char, int> m_id; // };
JavaScript
UTF-8
1,196
2.71875
3
[]
no_license
function searchBooks() { document.querySelector('.dataSearch').addEventListener('click', function () { let formSearch = document.forms['searchBook']; let inputValue = formSearch.inputData.value; new Promise(function (reject) { let xhr = new XMLHttpRequest(); xhr.open('GET', `https://api.itbook.store/1.0/search/${inputValue}`); xhr.send(); xhr.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { let parseData = JSON.parse(this.responseText); document.querySelector('.data').innerHTML = parseData; } else { reject(Error(document.querySelector('.data').innerHTML = xhr.responseText)); } }; promise.then(data => { if (data.length > 0) { document.querySelector('.data').innerHTML = 'books found' } else { document.querySelector('.data').innerText = 'no data' } formSearch.reset(); }) }); }, )}
Java
UTF-8
3,523
2.109375
2
[]
no_license
package com.gianghoang; import com.gianghoang.core.Employee; import com.gianghoang.core.Person; import com.gianghoang.core.Student; import com.gianghoang.db.EmployeeDAO; import com.gianghoang.db.PersonDAO; import com.gianghoang.db.StudentDAO; import com.gianghoang.resources.*; import io.dropwizard.Application; import io.dropwizard.db.DataSourceFactory; import io.dropwizard.hibernate.HibernateBundle; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration("com.gianghoang") @ComponentScan("com.gianghoang") public class HelloDropwizardApplication extends Application<HelloDropwizardConfiguration> { private static final Logger LOGGER = LoggerFactory.getLogger(HelloDropwizardApplication.class); public static void main(final String[] args) throws Exception { // AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(HelloDropwizardApplication.class); new HelloDropwizardApplication().run("server", "config.yml"); } private final HibernateBundle<HelloDropwizardConfiguration> hibernateBundle = new HibernateBundle<HelloDropwizardConfiguration>( Employee.class, Student.class, Person.class ) { @Override public DataSourceFactory getDataSourceFactory( HelloDropwizardConfiguration configuration ) { return configuration.getDataSourceFactory(); } }; @Override public String getName() { return "HelloDropwizard"; } @Override public void initialize(final Bootstrap<HelloDropwizardConfiguration> bootstrap) { // TODO: application initialization bootstrap.addBundle(hibernateBundle); } @Override public void run(final HelloDropwizardConfiguration configuration, final Environment environment) { // TODO: implement application final EmployeeDAO employeeDAO = new EmployeeDAO(hibernateBundle.getSessionFactory()); environment.jersey().register(new EmployeesResource(employeeDAO)); final StudentDAO studentDAO = new StudentDAO(hibernateBundle.getSessionFactory()); environment.jersey().register(new StudentResource(studentDAO)); final PersonDAO personDAO = new PersonDAO(hibernateBundle.getSessionFactory()); environment.jersey().register(new PersonResource(personDAO)); final HelloWorldResource resource = new HelloWorldResource(); final CpuResource cpuResource = new CpuResource(); final NetioResource netioResource = new NetioResource(); final HelloResource helloResource = new HelloResource(); final StringResource stringResource = new StringResource(); final RsaResource rsaResource = new RsaResource(); final TimeResource timeResource = new TimeResource(); environment.jersey().register(cpuResource); environment.jersey().register(resource); environment.jersey().register(netioResource); environment.jersey().register(helloResource); environment.jersey().register(stringResource); environment.jersey().register(rsaResource); environment.jersey().register(timeResource); environment.jersey().register(timeResource); } }
JavaScript
UTF-8
1,052
2.625
3
[]
no_license
import React, { useState, useEffect } from "react"; import axios from "axios"; import Weather from "./Weather"; const CountryDetail = ({ result }) => { const [weatherData, setWeatherData] = useState([]); useEffect(() => { axios .get( `https://api.openweathermap.org/data/2.5/weather?q=${result.capital}&appid=${process.env.REACT_APP_OPEN_WEATHER_API_KEY}&units=metric` ) .then((response) => setWeatherData(response.data)); }, [result.capital]); return ( <div> <h2>{result.name}</h2> <p> Capital: {result.capital} <br /> Population: {result.population} </p> <h3>Languages</h3> <ul> {result.languages.map((lang) => ( <li key={lang.iso639_1}>{lang.name}</li> ))} </ul> <img src={result.flag} alt={result.name} style={{ width: "150px" }} /> {weatherData && <Weather data={weatherData} />} </div> ); }; export default CountryDetail;
Shell
UTF-8
281
2.90625
3
[]
no_license
#!/bin/bash ### BEGIN INIT INFO # Provides: jdk-8 ### END INIT INFO source /etc/os-release case $ID in debian|ubuntu|devuan) apt-get update apt install openjdk-8-jdk -y ;; centos|fedora|rhel) yum install java-1.8.0-openjdk -y ;; *) exit 1 ;; esac
Java
UTF-8
427
2.03125
2
[]
no_license
package com.example.smartcomplaint.dao; import java.util.ArrayList; /** * Created by Rakshith on 10/13/2015. */ public class ComplaintInfoList { public ArrayList<ComplaintInfo> getComplaints() { return complaints; } public void setComplaints(ArrayList<ComplaintInfo> complaints) { this.complaints = complaints; } ArrayList<ComplaintInfo> complaints=new ArrayList<ComplaintInfo>(); }
C#
UTF-8
230
3
3
[]
no_license
using System; class A { static void Main() { string s = "using System;class A{{static void Main(){{string s={0}{1}{0};char q='{0}';Console.Write(s,q,s);}}}}"; char q = '"'; Console.Write(s, q, s); } }
TypeScript
UTF-8
1,645
2.515625
3
[]
no_license
import { Specification } from '../specification/specification'; import { ParamBuilder } from "../../query/param/param-builder"; import { HttpParams } from '@angular/common/http'; export class PreparedQuery { limit: number; offest: number; specification: Specification; ordersBy: Map<String, String>; toHttpParams(): HttpParams { return ParamBuilder.getInstance() .addParam("limit", this.limit) .addParam("offest", this.offest) .addJsonParam("specification", this.specification) .addJsonParam("ordersBy", this.ordersBy) .toHttpParams(); } } export class PreparedQueryBuilder { public static getInstance(): PreparedQueryBuilder { return new PreparedQueryBuilder(); } private toBuild: PreparedQuery = new PreparedQuery(); constructor() { this.toBuild = new PreparedQuery(); } public limit(limit: number): PreparedQueryBuilder { this.toBuild.limit = limit; return this; } public offest(offest: number): PreparedQueryBuilder { this.toBuild.offest = offest; return this; } public specification(specification: Specification): PreparedQueryBuilder { this.toBuild.specification = specification; return this; } public orderby(column: string, order: string): PreparedQueryBuilder { if (this.toBuild.ordersBy == null) { this.toBuild.ordersBy = new Map(); } this.toBuild.ordersBy.set(column, order); return this; } public build(): PreparedQuery { return this.toBuild; } }
JavaScript
UTF-8
645
2.578125
3
[]
no_license
var GildedRose = function () { console.log("OMGHAI!"); var items = []; items.push(new Item("+5 Dexterity Vest", 10, 20)); items.push(new Item("Aged Brie", 2, 0)); items.push(new Item("Elixir of the Mongoose", 5, 7)); items.push(new Item("Sulfuras, Hand of Ragnaros", 0, 80)); items.push(new Item("Backstage passes to a TAFKAL80ETC concert", 15, 20)); items.push(new Item("Conjured Mana Cake", 3, 6)); GildedRose.updateQuality(items); }; GildedRose.updateQuality = function (items) { for (var i = 0; i < items.length; i++) { var item = items[i]; item.decreaseSellIn(); item.updateQuality(); } return items; };
C#
UTF-8
2,719
2.953125
3
[]
no_license
using Caliburn.Micro; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Wpf_MVVM.Models; //ShellViewModel is Interface and This Acts Like The Backend Code where we write The Logic. // I am doing this while watching the Tutorials of Iamtimcory on WPF tutorials. // In fact, All the three Folders Represent The user Interface. {Models Views and ViewModels} namespace Wpf_MVVM.ViewModels { public class ShellViewModel :Conductor<object> { public ShellViewModel() { People.Add(new PersonModel { FirstName = "James" , LastName = "Bond"}); People.Add(new PersonModel { FirstName = "Eddie", LastName = "Heisenberg" }); People.Add(new PersonModel { FirstName = "Lionel", LastName = "Messi" }); People.Add(new PersonModel { FirstName = "Cristiano", LastName = "Ronaldo" }); } private string _firstName = ""; public string FirstName { get { return _firstName; } set { _firstName = value; NotifyOfPropertyChange(() => FirstName); NotifyOfPropertyChange(() => FullName); } } private string _lastName; public string LastName { get { return _lastName; } set { _lastName = value; NotifyOfPropertyChange(() => LastName); NotifyOfPropertyChange(() => FullName); } } public string FullName { get { return $"{FirstName} {LastName}"; } } private BindableCollection<PersonModel> _people= new BindableCollection<PersonModel>(); public BindableCollection<PersonModel> People { get { return _people; } set { _people = value; } } private String _selectedPerson; public String SelectedPerson { get { return _selectedPerson; } set { _selectedPerson = value; NotifyOfPropertyChange(() => SelectedPerson); } } public bool CanClearText() => !string.IsNullOrWhiteSpace(FirstName) || !string.IsNullOrWhiteSpace(LastName); //{ // throw new NotImplementedException(); //} public void ClearText(string firstName, string lastName) { FirstName = ""; LastName = ""; } public void LoadPageOne() { ActivateItem(new FirstChildViewModel()); } public void LoadPageTwo() { ActivateItem(new SecondChildViewModel()); } } }
PHP
UTF-8
3,268
2.59375
3
[]
no_license
<?php require_once __DIR__.'../services/ServiceInvoice.php'; $service = new InvoiceService; if ($service->isDataValid()) { $customerId = $_POST['customerId']; $invoiceDate = $_POST['invoiceDate']; $billingAddress = $_POST['billingAddress']; $billingCity = $_POST['billingCity']; $billingState = $_POST['billingState']; $billingCountry = $_POST['billingCountry']; $billingPostalCode = $_POST['billingPostalCode']; $total = $_POST['total']; $service->InsertInvoice($customerId, $invoiceDate, $billingAddress, $billingCity, $billingState, $billingCountry, $billingPostalCode, $total); } else { echo 'Not insertaed'; } ?> <?php require 'header.php'; ?> <div class="container"> <div class="card mt-5"> <div class="card-header"> <h2>Create An Invoice</h2> </div> <div class="card-boby"> <?php if(!empty($message)): ?> <div class="alert alert-sucess"> <?=$message; ?> </div> <?php endif; ?> <form method="POST"> <div class="form-group"> <label for="customerId">Customer ID</label> <input type="text" name="customerId" id="customerId" class="form-control"> </div> <div class="form-group"> <label for="invoiceDate">Invoice Date</label> <input type="date_format" name="invoiceDate" id="invoiceDate" class="form-control"> </div> <div class="form-group"> <label for="billingAddress">Billing Address</label> <input type="text" name="billingAddress" id="billingAddress" class="form-control"> </div> <div class="form-group"> <label for="billingCity">Billing City</label> <input type="text" name="billingCity" id="billingCity" class="form-control"> </div> <div class="form-group"> <label for="billingState">Billing State</label> <input type="text" name="billingState" id="billingState" class="form-control"> </div> <div class="form-group"> <label for="billingCountry">Billing Country</label> <input type="text" name="billingCountry" id="billingCountry" class="form-control"> </div> <div class="form-group"> <label for="billingPostalCode">Billing Postal Code</label> <input type="text" name="billingPostalCode" id="billingPostalCode" class="form-control"> </div> <div class="form-group"> <label for="total">Total</label> <input type="text" name="total" id="total" class="form-control"> </div> <div class="form-group"> <button type="submit" class="btn btn-info">Create An Invoice</button> </div> </form> </div> </div> </div> <?php require 'footer.php'; ?>
Python
UTF-8
1,258
4.46875
4
[]
no_license
# [조건문] # if people = 5 apple = 4 # 비교연산자 # print(people == apple) # false # print(people >= apple) # false # print(people <= apple) # true # if(true): # 이부분이 실행됩니다. # if(false): # 이부분은 실행되지 않아요. # if people == apple: # print('딱 맞다.') # if people > apple: # print('사과가 부족해') # if people < apple: # print('사과가 충분해') # 라이브러리 호출하고 안에있는 함수를 쓰는 방법 from datetime import datetime hour = datetime.now().hour # elif : 위가 아니면 그다음 if문. # else : 위가 아니면... 마지막 # if hour < 12: # print('am') # elif hour == 12: # print('noon') # else: # print('pm') # and와 or의 사용법 # a = 1 # b = 1 # c = 1 # if a == 1 and b == 1 and c == 1: # 교집합 # print('공동 1위: a, b, c') # a = 1 # b = 2 # c = 3 # if a == 1 or b == 1 or c == 1: # 합집합 # print('1등이 1명이상 있습니다.') # a = 1 # if a != 1: # a가 1이 아닐 때 # print('실행하세요.') a = 1 b = 1 c = 2 # if a != 1 or b != 1 or c != 1: # print('실행하세요.') # c때매 실행됨 if a != 1 and b != 1 and c != 1: print('실행하세요.') # a, b때매 실행안됨
Python
UTF-8
4,642
2.9375
3
[]
no_license
from tkinter import * from tkinter import messagebox, Frame from tkinter import ttk import DataBaser # Criar janela jan = Tk() jan.title('Painel de Acesso') jan.geometry('300x600') # o tamanho da janela jan.configure(background='white') # Configura a cor da janela jan.resizable(width=False, height=False) # impede que o tamanho da janela seja alterado jan.attributes('-alpha', 0.9) # deixando um pouco transparente jan.iconbitmap(default='icons/Logoicon.ico') # Adiciona o logo icon no canto superior esquerdo # Carregar imagem logo = PhotoImage(file='icons/jam.png') # imagem (100x100) # Criar os widgets da janela separando em dois, direita e esquerda # separada por uma barra branca UpFrame: Frame = Frame(jan, width=300, height=200, bg='GREEN', relief='raise') UpFrame.pack(side=TOP) LowFrame = Frame(jan, width=300, height=395, bg='MIDNIGHTBLUE', relief='raise') LowFrame.pack(side=RIGHT) # bg é a cor de fundo LogoLabel = Label(UpFrame, image=logo, bg='GREEN') # Exibi um texto ou imagem LogoLabel.place(x=100, y=50) # posicionando a imagem # fg é a cor do texto UserLabel = Label(LowFrame, text='Usuário:', font=('Century Gothic', 12), bg='MIDNIGHTBLUE', fg='White') UserLabel.place(x=5, y=150) UserEntry = ttk.Entry(LowFrame, width=30) UserEntry.place(x=100, y=152) PassLabel = Label(LowFrame, text='Senha:', font=('Century Gothic', 12), bg='MIDNIGHTBLUE', fg='White') PassLabel.place(x=5, y=185) PassEntry = ttk.Entry(LowFrame, width=30, show='*') # width = tmanho máximo do texto, show = mostra * no lugar digitado PassEntry.place(x=100, y=187) login_label = Label(LowFrame, text='Faça seu Login', font=('Century Gothic', 16), bg='MIDNIGHTBLUE', fg='yellow') login_label.place(x=5, y=15) def login(): user = UserEntry.get() senha = PassEntry.get() DataBaser.cursor.execute(""" SELECT * FROM Users WHERE (Usuário = ? and Senha = ?) """, (user, senha)) print('Selecionado') verifylogin = DataBaser.cursor.fetchone() try: if user in verifylogin and senha in verifylogin: messagebox.showinfo(title='Login Info', message='Login Efetuado com Sucesso.') except: messagebox.showerror(title='Login info', message='Acesso Negado') def register(): # Removendo widgets de login loginbuttom.place(x=5000) cadbuttom.place(x=5000) # Inserindo Widgets de cadastro nomelabel = Label(LowFrame, text='Nome:', font=('Century Gothic', 12), bg='MIDNIGHTBLUE', fg='White') nomelabel.place(x=5, y=80) nomeentry = ttk.Entry(LowFrame, width=30) nomeentry.place(x=100, y=82) emaillabel = Label(LowFrame, text='Email:', font=('Century Gothic', 12), bg='MIDNIGHTBLUE', fg='White') emaillabel.place(x=5, y=115) emailentry = ttk.Entry(LowFrame, width=30) emailentry.place(x=100, y=117) def registerbd(): nome = nomeentry.get() usuario = UserEntry.get() email = emailentry.get() senha = PassEntry.get() if nome == '' or usuario == '' or email == '' or senha == '': messagebox.showerror(title='ERRO Ao Registrar', message='Preencha Todos Os Campos Corretamente!') else: DataBaser.cursor.execute(""" INSERT INTO Users(Nome, Email, Usuário, Senha) VALUES(?, ?, ?, ?) """, (nome, email, usuario, senha)) DataBaser.conexao.commit() messagebox.showinfo(title='Registro da Informação', message='Registrado com Sucesso') def voltar(): # Removendo width de registro cadlabel.place_forget() nomelabel.place_forget() nomeentry.place_forget() emaillabel.place_forget() emailentry.place_forget() voltar.place(x=2000) registrar.place(x=2000) # Inserindo width de button loginlabel = Label(LowFrame, text='Faça seu Login', font=('Century Gothic', 16), bg='MIDNIGHTBLUE', fg='yellow') loginlabel.place(x=5, y=15) loginbuttom.place(x=120, y=225) cadbuttom.place(x=10, y=355) cadlabel = Label(LowFrame, text='Faça seu Cadastro', font=('Century Gothic', 16), bg='MIDNIGHTBLUE', fg='yellow') cadlabel.place(x=5, y=15) voltar = ttk.Button(LowFrame, text='Voltar', width=10, command=voltar) voltar.place(x=10, y=355) registrar = ttk.Button(LowFrame, text='Registrar', width=14, command=registerbd) registrar.place(x=110, y=225) # Botões loginbuttom = ttk.Button(LowFrame, text='Login', width=10, command=login) loginbuttom.place(x=120, y=225) cadbuttom = ttk.Button(LowFrame, text='Cadastre-se', width=14, command=register) cadbuttom.place(x=10, y=355) jan.mainloop()
JavaScript
UTF-8
2,577
3.359375
3
[ "MIT" ]
permissive
module.exports = class { constructor( items ) { this.items = items; this.reset(); this.totalItems = this.items.length; } // ------------------------------------ API // Go to the next item next( loopOnOverShoot=false ) { this.incramentItemIndex(1, loopOnOverShoot); } prev( loopOnOverShoot=false ) { this.incramentItemIndex(-1, loopOnOverShoot); } isAtLastItem(){ if (this.currentItemIndex === (this.totalItems-1)) return true; return false; } get currentItem() { return this.items[ this.currentItemIndex ]; } get firstItem() { return this.items[ 0 ]; } get lastItem() { return this.items[ this.items.length-1 ]; } incramentItemIndex( incrament, loopOnOverShoot) { if (loopOnOverShoot == null) { loopOnOverShoot = false; } let newIndex = this.currentItemIndex + incrament; // Make sure the new index falls within the range of items if (newIndex > (this.totalItems - 1)) newIndex = loopOnOverShoot ? 0 : this.totalItems - 1; // if new index is greater than the last item, show last item. else if (newIndex < 0) newIndex = loopOnOverShoot ? this.totalItems - 1 : 0; // if the index is less than 0, show first item. // Make sure new item is different than old item, return if (this.currentItemIndex !== newIndex) { this.currentItemIndex = newIndex; return true; } return false; } changeItemByIndex( newIndex ) { const plusOrMinus = newIndex > this.currentItemIndex ? 1 : -1; const incramentDifference = Math.abs( this.currentItemIndex - newIndex ) * plusOrMinus; this.incramentItemIndex( incramentDifference ); } activateItemByParam(param, val) { this.currentItemIndex = this.getIndexByParam(param, val); } getIndexByParam(param, val) { for (let i = 0; i < this.items.length; i++) { const item = this.items[i]; if (item[param] === val) { return i; } } return null; } getItemByParam(param, val) { // Add in some checking to make sure it works return this.items[ this.getIndexByParam(param, val) ]; } reset() { this.currentItemIndex = 0; } addItem(item, index) { if ((index == null)) { index = this.items.length; } else { index; } this.items.splice(index, 0, item); this.totalItems++; } removeItembyParam(param, val) { this.removeItemByIndex(this.getIndexByParam(param, val)); } removeItemByIndex(index){ if ((index == null)) { return; } this.items.splice(index, 1); this.totalItems--; } }
Java
UTF-8
655
2.59375
3
[ "MIT" ]
permissive
package org.rfc8452.aead; public class ByteOperations { static void inPlaceUpdate(byte[] b, final int n) { b[0] = (byte) n; b[1] = (byte) (n >> 8); b[2] = (byte) (n >> 16); b[3] = (byte) (n >> 24); } static void inPlaceUpdate(byte[] b, final long n, final int offset) { b[offset] = (byte) n; b[1 + offset] = (byte) (n >> 8); b[2 + offset] = (byte) (n >> 16); b[3 + offset] = (byte) (n >> 24); b[4 + offset] = (byte) (n >> 32); b[5 + offset] = (byte) (n >> 40); b[6 + offset] = (byte) (n >> 48); b[7 + offset] = (byte) (n >> 56); } }
PHP
UTF-8
5,152
2.71875
3
[ "LicenseRef-scancode-free-unknown", "MIT" ]
permissive
<?php namespace App\Game\Kingdoms\Builders; use App\Flare\Models\GameUnit; use App\Flare\Models\KingdomLog; class KingdomAttackedBuilder { /** * @var KingdomLog $log */ private $log; /** * Sets the log. * * @param KingdomLog $log * @return KingdomAttackedBuilder */ public function setLog(KingdomLog $log): KingdomAttackedBuilder { $this->log = $log; return $this; } public function fetchBuildingDamageReport(): array { $oldDefenderBuildings = $this->log->old_defender['buildings']; $newDefenderBuildings = $this->log->new_defender['buildings']; $buildingChanges = []; foreach ($newDefenderBuildings as $index => $building) { $oldDurability = $oldDefenderBuildings[$index]['current_durability']; $newDurability = $building['current_durability']; $buildingName = $building['name']; if (($newDurability === 0 && $oldDurability !== 0) && ($newDurability !== $oldDurability)) { $buildingChanges[$buildingName] = [ 'has_fallen' => true, 'old_durability' => $oldDurability, 'new_durability' => $newDurability, 'durability_lost' => 1, 'decreases_morale' => $this->decreasesMorale($building), 'affects_morale' => $this->affectsMorale($building), 'decrease_morale_amount' => $building['game_building']['decrease_morale_amount'], 'increase_morale_amount' => $building['game_building']['increase_morale_amount'], ]; } else if (($newDurability !== 0 && $oldDurability !== 0) && ($newDurability !== $oldDurability)) { $percentage = 1 - ($newDurability / $oldDurability); $buildingChanges[$buildingName] = [ 'has_fallen' => false, 'old_durability' => $oldDurability, 'new_durability' => $newDurability, 'durability_lost' => $percentage, 'decreases_morale' => false, 'affects_morale' => $this->affectsMorale($building), 'decrease_morale_amount' => $building['game_building']['decrease_morale_amount'], 'increase_morale_amount' => $building['game_building']['increase_morale_amount'], ]; } } return $buildingChanges; } public function fetchUnitKillReport(): array { $oldUnits = $this->log->units_sent; $unitsSurvived = $this->log->units_survived; $unitLosses = []; if (is_null($oldUnits)) { return $unitLosses; } foreach ($oldUnits as $index => $unit) { $amountLeft = $unitsSurvived[$index]['amount']; if ($amountLeft > 0) { if ($amountLeft === $unit['amount']) { $amountLeft = 0.0; } else { $amountLeft = number_format($amountLeft / $unit['amount'], 2); } } else { $amountLeft = 1.0; } $unitLosses[GameUnit::find($unit['unit_id'])->name] = [ 'amount_killed' => $amountLeft, ]; } return $unitLosses; } public function fetchUnitDamageReport(): array { $oldDefenderUnits = $this->log->old_defender['units']; $newDefenderUnits = $this->log->new_defender['units']; $unitChanges = []; foreach ($oldDefenderUnits as $index => $unitInfo) { $oldAmount = $unitInfo['amount']; $newAmount = $newDefenderUnits[$index]['amount']; $unitName = GameUnit::find($unitInfo['game_unit_id'])->name; if (($newAmount === 0 && $oldAmount !== 0) && $newAmount !== $oldAmount) { $unitChanges[$unitName] = [ 'lost_all' => true, 'old_amount' => $oldAmount, 'new_amount' => $newAmount, 'lost' => 1, ]; } else if (($newAmount !== 0 && $oldAmount !== 0) && $newAmount !== $oldAmount) { $percentage = 1 - ($newAmount / $oldAmount); $unitChanges[$unitName] = [ 'lost_all' => $percentage <= 0.0, 'old_amount' => $oldAmount, 'new_amount' => $newAmount, 'lost' => number_format($percentage, 2), ]; } } return $unitChanges; } protected function decreasesMorale(array $building): bool { return $building['current_durability'] === 0 && $building['game_building']['decrease_morale_amount'] > 0; } protected function affectsMorale(array $building): bool { return $building['game_building']['decrease_morale_amount'] > 0 && $building['game_building']['increase_morale_amount'] > 0; } }
PHP
UTF-8
350
2.578125
3
[ "MIT" ]
permissive
<?php session_start(); //Start a session session_unset(); //Take all the session variable when you login and take all the userid/name are delete from the session variables session_destroy(); //Destroy the session we're running from the current website header("Location: ../index.php"); //Take person back from the front page
C#
UTF-8
5,709
2.6875
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace kevinlucasraimondinogueira3017102087 { public partial class Form1 : Form { public Form1() { InitializeComponent(); inicializar(); } public void inicializar() { carregarCombox(); rb_Operario.Checked = true; rb_Gerente.Checked = false; tb_salarioBruto.Text = ""; tb_salarioBrutoCalculado.Text = ""; tb_imposto.Text = ""; tb_salarioLiquido.Text = ""; } private void carregarCombox() { List<Item> list = new List<Item>(); list.Add(new Item { Nome = "Matutino", Valor = "1" }); list.Add(new Item { Nome = "Vespertino", Valor = "2" }); list.Add(new Item { Nome = "Noturno", Valor = "3" }); list.Sort(delegate (Item a, Item b) { return a.Nome.CompareTo(b.Nome); }); comboBox1.DataSource = list; comboBox1.DisplayMember = "Nome"; comboBox1.ValueMember = "Valor"; comboBox1.SelectedIndex = 0; } private void button2_Click(object sender, EventArgs e) { inicializar(); } private void button1_Click(object sender, EventArgs e) { Application.Exit(); } private void tb_salarioBruto_KeyPress(object sender, KeyPressEventArgs e) { if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.')) { e.Handled = true; } if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1)) { e.Handled = true; } } private void bt_calcular_Click(object sender, EventArgs e) { if (!tb_salarioBruto.Text.Equals("")) { Double salarioBruto = Convert.ToDouble(tb_salarioBruto.Text); String valueComboBox = (String)comboBox1.SelectedValue; Double salarioBrutoCalculado = 0.0; Double porcentagemBeneficio = 0.0; Double alicota = 0.0; Double imposto = 0.0; Double salarioLiquido = 0.0; Double parcelaDedutivel = 0.0; if (rb_Operario.Checked.Equals(true)) { if (valueComboBox.Equals("1") || valueComboBox.Equals("2")) { porcentagemBeneficio = 0.5; } else { porcentagemBeneficio = 0.7; } } else { if (rb_Gerente.Checked.Equals(true)) { if (valueComboBox.Equals("1") || valueComboBox.Equals("2")) { porcentagemBeneficio = 1.0; } else { porcentagemBeneficio = 1.5; } } } salarioBrutoCalculado = ((salarioBruto * porcentagemBeneficio) / 100) + salarioBruto; tb_salarioBrutoCalculado.Text = formatarMoeda(salarioBrutoCalculado); if (salarioBrutoCalculado < 1499.15) { imposto = 0.0; } else { if (salarioBrutoCalculado > 1499.16 && salarioBrutoCalculado <= 22460.75) { alicota = 7.5 / 100; parcelaDedutivel = 112.43; } else { if (salarioBrutoCalculado > 2246.76 && salarioBrutoCalculado <= 2995.75) { alicota = 15.0 / 100; parcelaDedutivel = 280.94; } else { if (salarioBrutoCalculado > 2995.71 && salarioBrutoCalculado <= 3743.19) { alicota = 22.5 / 100; parcelaDedutivel = 505.62; } else { if (salarioBrutoCalculado > 3743.19) { alicota = 27.5 / 100; parcelaDedutivel = 692.78; } } } } imposto = (salarioBruto * alicota) - parcelaDedutivel; } salarioLiquido = salarioBrutoCalculado - imposto; tb_salarioLiquido.Text = formatarMoeda(salarioLiquido); tb_imposto.Text = formatarMoeda(imposto); } } String formatarMoeda(Double value) { return String.Format("{0:C}", Convert.ToInt32(value)); } private double Truncar(double valor) { valor *= 100; valor = Math.Truncate(valor); valor /= 100; return valor; } } }
C++
UTF-8
343
2.515625
3
[]
no_license
#ifndef ENDURANCE_H #define ENDURANCE_H #include "character/characteristics/skill/skill.h" class Endurance : public Skill { public: Endurance(bool trndFlag = false); ~Endurance(); void addBonus(const Bonus * const bonus); void subBonus(const Bonus * const bonus); const char * toString() const; }; #endif // ENDURANCE_H
PHP
UTF-8
1,923
2.546875
3
[]
no_license
<?php /** * List View Loop * This file sets up the structure for the list loop * * Override this template in your own theme by creating a file at [your-theme]/tribe-events/list/loop.php * * @package TribeEventsCalendar * @since 3.0 * @author Modern Tribe Inc. * */ if ( !defined('ABSPATH') ) { die('-1'); } ?> <?php global $more; $more = false; ?> <div class="tribe-events-loop hfeed vcalendar"> <table class="events-table" width="100%" cellpadding="0" cellspacing="0"> <?php $prev_event_date = ""; ?> <?php while ( have_posts() ) : the_post(); ?> <?php do_action( 'tribe_events_inside_before_loop' ); ?> <!-- Month / Year Headers --> <?php //tribe_events_list_the_date_headers(); ?> <!-- Event --> <!-- <div id="post-<?php the_ID() ?>" class="<?php tribe_events_event_classes() ?>"> --> <?php global $post; $event = $post; if ( tribe_event_is_multiday( $event ) ) { // multi-date event if ( tribe_event_is_all_day( $event ) ) { $current_event_date = tribe_get_start_date( $event, true, "F j" ) ; } else { $current_event_date = tribe_get_start_date( $event, false, "F j" ) ; } } elseif ( tribe_event_is_all_day( $event ) ) { // all day event $current_event_date = tribe_get_start_date( $event, true, "F j" ) ; } else { // single day event $current_event_date = tribe_get_start_date( $event, false, "F j" ) ; } if ( $prev_event_date == "" ) $prev_event_date = $current_event_date; if( $prev_event_date == $current_event_date ){ $class = ""; } else{ $class = "last-event"; $prev_event_date = $current_event_date; } ?> <tr class="<?php echo $class?>" > <?php tribe_get_template_part( 'list/single', 'event' ) ?> </tr> <!-- </div> --><!-- .hentry .vevent --> <?php do_action( 'tribe_events_inside_after_loop' ); ?> <?php endwhile; ?> </table> </div><!-- .tribe-events-loop -->
Java
UTF-8
5,512
2.09375
2
[]
no_license
package com.example.listacontactos; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.FrameLayout; import android.widget.GridView; import android.widget.ImageButton; import android.widget.ListView; import android.widget.Spinner; import com.example.listacontactos.adapter.AdapterGrid; import com.example.listacontactos.adapter.AdapterList; import com.example.listacontactos.db.Contactos; import com.example.listacontactos.utils.Constants; import com.example.listacontactos.utils.Utils; import java.util.ArrayList; public class ActivityListaContactos extends AppCompatActivity { FrameLayout frameGrid, frameList; GridView gridView; ListView lista; ImageButton imgButton; Toolbar toolbarMain; Spinner spinnerFiltros; ArrayAdapter<String> adapterSpinner; String listaSpinner[] = {"Lista", "Celdas"}; ArrayList<String> nombre, telefono, urlImagen, iddatabase; Integer imagenes[]; Contactos contactos; int positionActual; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_lista_contactos); frameList = (FrameLayout) findViewById(R.id.frame_lista); frameGrid = (FrameLayout) findViewById(R.id.frame_grid); gridView = (GridView)findViewById(R.id.lgridcontactos); lista =(ListView)findViewById(R.id.listacontactos); imgButton = (ImageButton)findViewById(R.id.imgbutton_addcontact); toolbarMain =(Toolbar)findViewById(R.id.toolbar_main); spinnerFiltros = (Spinner)findViewById(R.id.spfiltros); setSupportActionBar(toolbarMain); contactos = new Contactos(ActivityListaContactos.this); cargarMisPreferencias(); crearSpinner(); cargarDatos(); gridView.setAdapter( new AdapterGrid(ActivityListaContactos.this, nombre, telefono, urlImagen)); lista.setAdapter( new AdapterList(ActivityListaContactos.this, nombre, telefono, imagenes, iddatabase)); imgButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ActivityListaContactos.this, Activity_NuevoContacto.class); startActivity(intent); finish(); } }); } public ActivityListaContactos(){ } public void crearSpinner() { adapterSpinner = new ArrayAdapter<String>(ActivityListaContactos.this, android.R.layout.simple_list_item_1, listaSpinner); spinnerFiltros.setAdapter(adapterSpinner); spinnerFiltros.setSelection(positionActual); spinnerFiltros.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if(position ==0) { frameListaVisible(); } else if(position == 1) { frameGridVisible(); } guardarMisPreferencias(position); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } public void frameListaVisible(){ frameList.setVisibility(View.VISIBLE); frameList.setEnabled(true); frameGrid.setVisibility(View.GONE); frameGrid.setEnabled(false); } public void frameGridVisible(){ frameList.setVisibility(View.GONE); frameList.setEnabled(false); frameGrid.setVisibility(View.VISIBLE); frameGrid.setEnabled(true); } public void cargarDatos(){ try{ nombre.clear(); telefono.clear(); urlImagen.clear(); iddatabase.clear(); } catch (Exception e) { Log.e("error", "error al limpiar" + e); } nombre = new ArrayList<String>(); telefono = new ArrayList<String>(); urlImagen = new ArrayList<String>(); iddatabase = new ArrayList<String>(); try { contactos.abrir(); nombre = contactos.SelectNombres(); telefono = contactos.SelectTelefonos(); urlImagen = contactos.SelectTelefonos(); iddatabase = contactos.SelectidDB(); contactos.cerrar(); } catch (Exception e) { e.printStackTrace(); } int i =0; imagenes = new Integer[nombre.size()]; while(i<nombre.size()){ imagenes[i] = R.drawable.img_1; i++; } } public void cargarMisPreferencias(){ Utils utils = new Utils(); utils.cargarPreferencias(ActivityListaContactos.this); if(Constants.tipofiltro.equals("0")) { frameListaVisible(); } else if(Constants.tipofiltro.equals("1")){ frameGridVisible(); } positionActual = Integer.parseInt(Constants.tipofiltro); } public void guardarMisPreferencias(int position){ Utils utils = new Utils(); utils.guardarPreferencias(ActivityListaContactos.this, String.valueOf(position)); } }
Java
UTF-8
1,918
2.296875
2
[]
no_license
package fr.jeanlouispiera.metier; import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.repository.query.Param; import fr.jeanlouispiera.entities.Site; import fr.jeanlouispiera.entities.SiteCotation; import fr.jeanlouispiera.entities.SiteMassif; import fr.jeanlouispiera.entities.SiteNiveauDePratique; import fr.jeanlouispiera.entities.SiteOrientation; import fr.jeanlouispiera.entities.SiteRegion; import fr.jeanlouispiera.entities.SiteTag; import fr.jeanlouispiera.entities.SiteTypeRoche; public interface ISiteMetier { //1 CRUD SITE //1-1 CREATE SITE Site createSite(String nomSite, int altitude, int nbVoies, int hauteurMin, int hauteurMax, int longueurTotaleVoies, SiteNiveauDePratique siteNiveauDePratique, SiteCotation siteCotation, SiteMassif siteMassif, SiteOrientation siteOrientation, SiteRegion siteRegion, SiteTypeRoche siteTypeRoche, SiteTag siteTag); Site addSite(Site site); //1-2 READ SITE Site readSite (long numSite); //1-3 UPDATE DE SON ESPACE PERSONNEL ******** [PAR L'UTILISATEUR MEMBRE OU VISITEUR] Site updateSite(Site site); //1-4 DELETE DE SON ESPACE PERSONNEL ******* [PAR L'UTILISATEUR MEMBRE OU VISITEUR] void deleteSite (Long numSite); //2-1 AFFICHER TOUS LES SITES public List<Site> displayAllSites(); public Page<Site> findAll(Pageable pageable); public Page<Site> searchAllByNomSite(String nomSite, Pageable pageable); public Page<Site> searchByNomSiteAndSiteMassif(String nomSite, @Param("massif") String massif, Pageable pageable); public Page<Site> searchByNomSiteAndSiteMassifAndSiteCotation(String nomSite, @Param("massif") String massif, @Param("cotation") String cotation,Pageable pageable); }
C#
UTF-8
5,171
2.640625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MySql.Data.MySqlClient; using System.Windows.Forms; using System.Data; using System.IO; using System.Drawing; namespace Sixi { class DBconnect { MySqlConnection cnn; public DBconnect() { string connectionString = null; connectionString = "server=localhost;database=school;uid=Josh;pwd=0721466024jm."; cnn = new MySqlConnection(connectionString); cnn.Open(); } public void LoadComboBox(String SQL, ComboBox cbo) { cbo.Items.Clear(); MySqlCommand cmd = new MySqlCommand(SQL, cnn); MySqlDataReader read = cmd.ExecuteReader(); while (read.Read()) { cbo.Items.Add(read.GetString(0)); } read.Close(); cnn.Close(); } public void LoadTextBox(string Sql, TextBox text) { AutoCompleteStringCollection collection = new AutoCompleteStringCollection(); MySqlCommand cmd = new MySqlCommand(Sql, cnn); MySqlDataReader read = cmd.ExecuteReader(); while (read.Read()) { collection.Add(read.GetString(0)); } text.AutoCompleteCustomSource = collection; text.AutoCompleteMode = AutoCompleteMode.SuggestAppend; text.AutoCompleteSource = AutoCompleteSource.CustomSource; read.Close(); cnn.Close(); } //Close connectioN //Insert statement public void Insert(string query) { //create command and assign the query and connection from the constructor MySqlCommand cmd = new MySqlCommand(query, cnn); //Execute command cmd.ExecuteNonQuery(); cnn.Close(); } //Update statement public void Update(string query) { //create command and assign the query and connection from the constructor MySqlCommand cmd = new MySqlCommand(query, cnn); //Execute command cmd.ExecuteNonQuery(); cnn.Close(); } //Delete statement public void Delete(string query) { //create command and assign the query and connection from the constructor MySqlCommand cmd = new MySqlCommand(query, cnn); //Execute command cmd.ExecuteNonQuery(); cnn.Close(); } //Select statement public void Select(string query, DataGridView dgv) { //Create Command //Create a data reader and Execute the command DataTable tbl = new DataTable(); MySqlDataAdapter adp = new MySqlDataAdapter(query, cnn); adp.Fill(tbl); dgv.DataSource = tbl; cnn.Close(); } //Count statement //public int Count() //{ //} //Backup public void Backup() { } //Restore public void Restore() { } public bool Register(string query) { MySqlCommand cmd = new MySqlCommand(query, cnn); //Execute command cmd.ExecuteNonQuery(); cnn.Close(); return true; } public bool hasRegistered(string query) { MySqlCommand cmd = new MySqlCommand(query, cnn); MySqlDataReader reader = cmd.ExecuteReader(); if (reader.Read()) { reader.Close(); cnn.Close(); return true; } else { reader.Close(); cnn.Close(); return false; } } public void LoadImage(string query, PictureBox picture) { MySqlCommand cmd = new MySqlCommand(query, cnn); MySqlDataReader read = cmd.ExecuteReader(); while (read.Read()) { string path = Application.StartupPath + @"\Images\" + read.GetString(0); if (File.Exists(path)) { picture.Tag = path; picture.Image = Image.FromFile(path); } else { picture.Tag = read.GetString(0); picture.Image = null; } } read.Close(); cnn.Close(); } public bool IsLogin(string query) { //create command and assign the query and connection from the constructor MySqlCommand cmd = new MySqlCommand(query, cnn); MySqlDataReader reader = cmd.ExecuteReader(); if (reader.Read()) { reader.Close(); cnn.Close(); return true; } else { reader.Close(); cnn.Close(); return false; } } } }
Markdown
UTF-8
1,686
2.71875
3
[]
no_license
### 订单查询 酒店入住 日历选择功能 https://sunguangqing.github.io/calendar/calendar.html ### My97DatePicker日期控件地址:http://www.my97.net/demo/index.htm >下载calendar文件夹放到根目录中,将WdatePicker.js文件引用到页面中即可 <br /><script src="calendar/WdatePicker.js"></script> #### `HTML结构:` #### >订单查询日历控件使用 >可选择的时间不能超过当前的时间,后面选择框的时间不能小于前面选定的时间并且不能大于当前的时间 ```HTML <div class="date-btn"> <input id="start-time" onclick="WdatePicker({maxDate:'%y-%M-%d'})" /> ~ <input onclick="WdatePicker({minDate:'#F{$dp.$D(\'start-time\',{d:0});}',maxDate:'%y-%M-%d'})" /> </div> ``` #### >酒店入驻日历控件使用 >可选的时间不能小于当前的时间,后面选择框的时间不能小于当前的时间加一天并且不能大于商家设定的时间 ```HTML <div class="date-btn"> <input type="text" class="Wdate" id="start-time-hotel" onclick="WdatePicker({skin:'whyGreen', minDate:'%y-%M-%d', maxDate:'2050-12-12'})"/> ~ <input type="text" class="Wdate" onclick="WdatePicker({skin:'whyGreen', minDate: '#F{$dp.$D(\\\'start-time-hotel\\\',{d:1});}'})"/> <span class="wdate-icon"></span> </div> ``` #### `CSS代码:` ```CSS .date-btn{ width: 255px; height: 30px; line-height: 30px; border: 1px solid #d9d9d9; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; padding: 0 18px; } .date-btn input{ position: relative; top: -2px; width: 100px; height: 28px; border: 0; text-align: center; color: #777; } ```
Python
UTF-8
1,113
3.609375
4
[ "Unlicense" ]
permissive
import unittest def is_subseq(a, b): i = 0 for ch in b: if ch == a[i]: i += 1 if i == len(a): return True return False class Solution: def findLUSlength(self, strs): """ :type strs: List[str] :rtype: int """ strs.sort(key=len, reverse=True) for i, a in enumerate(strs): for j, b in enumerate(strs): if i == j: continue if len(b) < len(a): return len(a) if is_subseq(a, b): break else: return len(a) return -1 class Test(unittest.TestCase): def test(self): self._test(['aba', 'cdc'], 3) self._test(['abcd', 'abc'], 4) self._test(['abc', 'dbc'], 3) self._test(['abc', 'abc'], -1) self._test(['aba', 'cdc', 'eae'], 3) def _test(self, strs, expected): actual = Solution().findLUSlength(strs) self.assertEqual(expected, actual) if __name__ == '__main__': unittest.main()
C++
UTF-8
2,478
3.375
3
[]
no_license
// // main.cpp // HPEA2 // // Created by Hasan Qureshi on 2/5/20. // Copyright © 2020 Hasan Qureshi. All rights reserved. // #include <iostream> #include <cmath> #include <algorithm> #include <iomanip> using namespace std; void deposit(double& bal); void withdraw(double& bal); void status(double& bal); void menu(){ cout<<"What would you like to do today?"<<endl; cout<<"Select 1 to deposit funds"<<endl; cout<<"Select 2 to withdraw funds"<<endl; cout<<"Select 3 to check your balence"<<endl; cout<<"Select 4 to exit"<<endl; }; int main(int argc, const char * argv[]) { int choice=3; double balance=0.00; cout<<"Welcome to your bank ATM"<<endl; cout<<"What would you like to do today?"<<endl; cout<<"Select 1 to deposit funds"<<endl; cout<<"Select 2 to withdraw funds"<<endl; cout<<"Select 3 to check your balence"<<endl; cout<<"Select 4 to exit"<<endl; //cin>>choice; while (cin){ switch (choice) { case 1: deposit(balance); break; case 2: withdraw(balance); break; case 3: status(balance); break; case 4: cout <<"Your final balence is $"<< fixed <<setprecision(2)<< balance << ". Thank you for banking with us. We appreciate your business."<<endl; exit(0); break; default: cout<<"Invalid choice please choose again"<<endl; } cin>>choice; //deposit(balance); } cout<<endl; cout <<"Hello customer, your current balance is $"<<fixed <<setprecision(2)<< balance << endl; return 0; } void deposit(double& bal){ double dep; cout<<"How much would you like to deposit? "<<endl; cin>>dep; if(dep>0){ bal+=dep; } else{ cout<<"Cannot deposit a nonnegative sum."<<endl; } cout<<endl; cout<<"Your new balance is: $"<<fixed <<setprecision(2)<<bal<<endl;; cout<<"What would you like to do next?"<<endl; cout<<endl; menu(); } void withdraw(double& bal){ double wit; cout<<"How much would you like to withdraw? "<<endl; cin>>wit; if (wit>bal){ cout<<"Insefficent funds"<<endl; } else{ bal-=wit; } cout<<endl; cout<<"Your new balance is: $"<<fixed <<setprecision(2)<<bal<<endl; cout<<"What would you like to do next?"<<endl; cout<<endl; menu(); } void status(double& bal){ cout<<"Your balance is: $"<<fixed <<setprecision(2)<<bal<<endl; cout<<endl; }
JavaScript
UTF-8
795
2.640625
3
[]
no_license
// Import node module for mongo ORM const mongoose = require("mongoose"); // define database for books const Schema = mongoose.Schema; // schema makes non-relational db(Mongo) like a relational db(MySQL) // Each schema key is a db field and its datatype that will be validated. // Also some fields are required when creating a document and one field is defined as unique. const bookSchema = new Schema({ title: { type: String, required: true }, subtitle: { type: String }, authors: { type: [String], required: true }, link: { type: String, required: true }, description: { type: String, required: true }, image: { type: String, required: true }, googleId: { type: String, required: true, unique: true } }); const Book = mongoose.model("Book", bookSchema); module.exports = Book;
C++
UTF-8
1,450
2.71875
3
[]
no_license
#include "Human.h" #include <ctime> #include <random> #include <glm/gtx/rotate_vector.hpp> #include <Engine/ResourceManager.h> Human::Human() { } Human::~Human() { } void Human::init(float speed, glm::vec2 pos){ static std::mt19937 randomEngine(time(nullptr)); static std::uniform_real_distribution<float> ranDir(-1.0f, 1.0f); static std::uniform_int_distribution<int> ranInt(1, 40); m_health = 20; m_color = Engine::ColorRGBA8(255, 255, 255, 255); m_speed = speed; m_position = pos; m_textureID = Engine::ResourceManager::getTexture("Textures/human.png").id; //Generate random start frame m_frames = ranInt(randomEngine); //Get random direction m_direction = glm::vec2(ranDir(randomEngine), ranDir(randomEngine)); //make sure direction isn't zero if (m_direction.length() == 0) m_direction = glm::vec2(1.0f, 0.0f); m_direction = glm::normalize(m_direction); } void Human::update(const std::vector<std::string>& levelData, std::vector<Human*>& humans, std::vector<Zombie*>& zombies, float deltaTime){ static std::mt19937 randomEngine(time(nullptr)); static std::uniform_real_distribution<float> randRotate(-40.0f, 40.0f); m_position += m_direction * m_speed * deltaTime; if (m_frames == 60) { m_direction = glm::rotate(m_direction, randRotate(randomEngine)); m_frames = 0; }else { m_frames++; } if (collideWithLevel(levelData)) { m_direction = glm::rotate(m_direction, randRotate(randomEngine)); } }
C#
UTF-8
42,435
2.703125
3
[ "MIT" ]
permissive
using System; using Xunit; namespace Freestylecoding.Math.CSharp.Tests { // NOTE: The sanity tests are here to do low level tests of a few parts // This lets me isolate those tests so I can use those parts in the rest of the tests // // In other words: // IF ANY OF THE SANITY TESTS FAIL, DON'T TRUST ANY OTHER TEST! [Trait( "Type", "Sanity" )] public class IntegerSanity { [Fact] public void LeftShift() => Assert.Equal( new Integer( new[] { 4u, 0x8000_0000u, 0u }, true ), new Integer( new[] { 9u }, true ) << 63 ); [Fact] public void RightShift() => Assert.Equal( new Integer( new[] { 9u }, true ), new Integer( new[] { 4u, 0x8000_0000u, 0u }, true ) >> 63 ); [Fact] public void GreaterThanTrue() => Assert.True( new Integer( new[] { 0xBADu, 0xDEADBEEFu } ) > new Integer( new[] { 0xDEADBEEFu, 0xBADu }, true ) ); [Fact] public void GreaterThanFalseByLessThan() => Assert.False( new Integer( new[] { 0xBADu, 0xDEADBEEFu }, true ) > new Integer( new[] { 0xDEADBEEFu, 0xBADu } ) ); [Fact] public void GreaterThanFalseByEquals() => Assert.False( new Integer( new[] { 0xBADu, 0xDEADBEEFu }, true ) > new Integer( new[] { 0xBADu, 0xDEADBEEFu }, true ) ); [Fact] public void Addition() => Assert.Equal( new Integer( new[] { 0xFFFF_FFFFu, 0xFFFF_FFFFu } ), new Integer( new[] { 1u, 0u, 0u } ) + new Integer( new[] { 1u }, true ) ); [Fact] public void Subtraction() => Assert.Equal( new Integer( new[] { 2u, 0u, 0u } ), new Integer( new[] { 1u, 1u } ) - new Integer( new[] { 1u, uint.MaxValue - 1u, uint.MaxValue }, true ) ); [Fact] public void Multiplication() => Assert.Equal( new Integer( new[] { 0x75CD9046u, 0x541D5980u }, true ), new Integer( new[] { 0xFEDCBA98u }, true ) * new Integer( new[] { 0x76543210u } ) ); [Fact] public void DivisionModulo() => Assert.Equal( new Tuple<Integer,Integer>( new Integer( new[] { 0xFEDCBA98u } ), new Integer( new[] { 0x12345678u }, true) ), Integer.op_DividePercent( new Integer(new[] { 0x75CD9046u, 0x6651AFF8u }, true), new Integer(new[] { 0x76543210u }, true) ) ); [Fact] public void ToStringTest() => Assert.Equal( "-1234567890123456789", new Integer( new[] { 0x112210F4u, 0x7DE98115u }, true ).ToString() ); [Fact] public void Parse() => Assert.Equal( new Integer( new[] { 0x112210F4u, 0x7DE98115u }, true ), Integer.Parse( "-1234567890123456789" ) ); } public class IntegerAnd { [Theory] [InlineData( "0", "0", "0" )] [InlineData( "1", "0", "0" )] [InlineData( "0", "1", "0" )] [InlineData( "1", "1", "1" )] [InlineData( "-1", "1", "1" )] [InlineData( "1", "-1", "1" )] [InlineData( "-1", "-1", "-1" )] public void Sanity( string l, string r, string x ) => Assert.Equal( Integer.Parse( x ), Integer.Parse( l ) & Integer.Parse( r ) ); [Fact] public void BiggerLeft() => Assert.Equal( Integer.Unit, new Integer( new[] { 0xFu, 0x00000101u } ) & new Integer( new[] { 0x00010001u } ) ); [Fact] public void BiggerRight() => Assert.Equal( Integer.Unit, new Integer( new[] { 0x00010001u } ) & new Integer( new[] { 0xFu, 0x00000101u } ) ); } public class IntegerOr { [Theory] [InlineData( "0", "0", "0" )] [InlineData( "1", "0", "1" )] [InlineData( "0", "1", "1" )] [InlineData( "1", "1", "1" )] [InlineData( "-1", "1", "-1" )] [InlineData( "1", "-1", "-1" )] [InlineData( "-1", "-1", "-1" )] public void Sanity( string l, string r, string x ) => Assert.Equal( Integer.Parse( x ), Integer.Parse( l ) | Integer.Parse( r ) ); [Fact] public void BiggerLeft() => Assert.Equal( new Integer( new[] { 0xFu, 0x10101u } ), new Integer( new[] { 0xFu, 0x00000101u } ) | new Integer( new[] { 0x00010001u } ) ); [Fact] public void BiggerRight() => Assert.Equal( new Integer( new[] { 0xFu, 0x10101u } ), new Integer( new[] { 0x00010001u } ) | new Integer( new[] { 0xFu, 0x00000101u } ) ); } public class IntegerXor { [Theory] [InlineData( "0", "0", "0" )] [InlineData( "1", "0", "1" )] [InlineData( "0", "1", "1" )] [InlineData( "1", "1", "0" )] [InlineData( "-1", "0", "-1" )] [InlineData( "0", "-1", "-1" )] [InlineData( "-1", "-1", "0" )] [InlineData( "-1", "1", "0" )] [InlineData( "1", "-1", "0" )] [InlineData( "1", "2", "3" )] [InlineData( "-1", "2", "-3" )] [InlineData( "1", "-2", "-3" )] [InlineData( "-1", "-2", "3" )] public void Sanity( string l, string r, string x ) => Assert.Equal( Integer.Parse( x ), Integer.Parse( l ) ^ Integer.Parse( r ) ); [Fact] public void BiggerLeft() => Assert.Equal( new Integer( new[] { 0xFu, 0x10100u } ), new Integer( new[] { 0xFu, 0x00000101u } ) ^ new Integer( new[] { 0x00010001u } ) ); [Fact] public void BiggerRight() => Assert.Equal( new Integer( new[] { 0xFu, 0x10100u } ), new Integer( new[] { 0x00010001u } ) ^ new Integer( new[] { 0xFu, 0x00000101u } ) ); } //public class IntegerBitwiseNot { // // NOTE: These are not going through Parse because it would be // // more difficult to casually tell what is going on. // [Theory] // [InlineData( 0xFFFFFFFEu, 1u )] // [InlineData( 1u, 0xFFFFFFFEu )] // public void Sanity( uint r, uint x ) => // Assert.Equal( new Integer( new[] { x }, true ), ~ new Integer( new[] { r }, false) ); // [Fact] // public void Bigger() => // Assert.Equal( new Integer( new[] { 0xF0123456u, 0x789ABCDEu }, true ), ~ new Integer( new[] { 0x0FEDCBA9u, 0x87654321u }, false ) ); // [Theory] // [InlineData( true, false )] // [InlineData( false, true )] // let Sign expected initial = // Assert.Equal( new Integer(new[] { 0xF0123456u, 0x789ABCDEu }, expected), ~~~ new Integer(new[] { 0x0FEDCBA9u, 0x87654321u }, initial) ); //} public class IntegerLeftShift { [Theory] [InlineData( "1", 1, "2" )] [InlineData( "-1", 1, "-2" )] public void Sanity( string l, int r, string s ) => Assert.Equal( Integer.Parse( s ), Integer.Parse( l ) << r ); [Fact] public void Multiple() => Assert.Equal( new Integer( new[] { 0x3Cu } ), new Integer( new[] { 0xFu } ) << 2 ); [Fact] public void Overflow() => Assert.Equal( new Integer( new[] { 1u, 0xFFFFFFFEu } ), new Integer( new[] { 0xFFFFFFFFu } ) << 1 ); [Fact] public void MultipleOverflow() => Assert.Equal( new Integer( new[] { 0x5u, 0xFFFFFFF8u } ), new Integer( new[] { 0xBFFFFFFFu } ) << 3 ); [Fact] public void OverOneUInt() => Assert.Equal( new Integer( new[] { 8u, 0u, 0u } ), Integer.Unit << 67 ); [Fact] public void OverflowNegative() => Assert.Equal( new Integer( new[] { 1u, 0xFFFFFFFEu }, true ), new Integer( new[] { 0xFFFFFFFFu }, true ) << 1 ); [Fact] public void MultipleOverflowNegative() => Assert.Equal( new Integer( new[] { 0x5u, 0xFFFFFFF8u }, true ), new Integer( new[] { 0xBFFFFFFFu }, true ) << 3 ); [Fact] public void OverOneUIntNegative() => Assert.Equal( new Integer( new[] { 8u, 0u, 0u }, true ), new Integer( Natural.Unit, true ) << 67 ); } public class IntegerRightShift { [Theory] [InlineData( "1", 1, "0" )] [InlineData( "15", 2, "3" )] [InlineData( "60", 2, "15" )] [InlineData( "60", 1, "30" )] [InlineData( "-1", 1, "0" )] [InlineData( "-2", 1, "-1" )] [InlineData( "-15", 2, "-3" )] [InlineData( "-60", 2, "-15" )] [InlineData( "-60", 1, "-30" )] public void Sanity( string l, int r, string s ) => Assert.Equal( Integer.Parse( s ), Integer.Parse( l ) >> r ); [Fact] public void Underflow() => Assert.Equal( new Integer( new[] { 0x7FFFFFFFu } ), new Integer( new[] { 0xFFFFFFFFu } ) >> 1 ); [Fact] public void MultipleUnderflow() => Assert.Equal( new Integer( new[] { 0x1u, 0x5FFFFFFFu } ), new Integer( new[] { 0xAu, 0xFFFFFFFFu } ) >> 3 ); [Fact] public void OverOneUInt() => Assert.Equal( Integer.Unit, new Integer( new[] { 0x10u, 0u, 0u } ) >> 68 ); [Fact] public void ReduceToZero() => Assert.Equal( Integer.Zero, new Integer( new[] { 0x10u, 0u, 0u } ) >> 99 ); [Fact] public void UnderflowNegative() => Assert.Equal( new Integer( new[] { 0x7FFFFFFFu }, true ), new Integer( new[] { 0xFFFFFFFFu }, true ) >> 1 ); [Fact] public void MultipleUnderflowNegative() => Assert.Equal( new Integer( new[] { 0x1u, 0x5FFFFFFFu }, true ), new Integer( new[] { 0xAu, 0xFFFFFFFFu }, true ) >> 3 ); [Fact] public void OverOneUIntNegative() => Assert.Equal( new Integer( Natural.Unit, true ), new Integer( new[] { 0x10u, 0u, 0u }, true ) >> 68 ); [Fact] public void RetainsNegative() => Assert.Equal( new Integer( new[] { 1u }, true ), new Integer( new[] { 2u }, true ) >> 1 ); [Fact] public void NegativeReduceToZero() => Assert.Equal( Integer.Zero, new Integer( new[] { 0x10u, 0u, 0u }, true ) >> 99 ); } public class IntegerEquality { [Theory] [InlineData( "0", "0", true )] [InlineData( "0", "1", false )] [InlineData( "1", "0", false )] [InlineData( "1", "1", true )] [InlineData( "0", "-1", false )] [InlineData( "-1", "0", false )] [InlineData( "-1", "1", false )] [InlineData( "1", "-1", false )] [InlineData( "-1", "-1", true )] public void Sanity( string l, string r, bool x ) => Assert.Equal( x, Integer.Parse( l ) == Integer.Parse( r ) ); [Fact] public void BiggerLeft() => Assert.False( new Integer( new[] { 0xBADu, 0xDEADBEEFu } ) == new Integer( new[] { 0xDEADBEEFu } ) ); [Fact] public void BiggerRight() => Assert.False( new Integer( new[] { 0xDEADBEEFu } ) == new Integer( new[] { 0xBADu, 0xDEADBEEFu } ) ); } public class IntegerGreaterThan { [Theory] [InlineData( "0", "1", false )] [InlineData( "1", "0", true )] [InlineData( "0", "-1", true )] [InlineData( "-1", "0", false )] [InlineData( "1", "1", false )] [InlineData( "-1", "1", false )] [InlineData( "1", "-1", true )] [InlineData( "-1", "-1", false )] public void Sanity( string l, string r, bool x ) => Assert.Equal( x, Integer.Parse( l ) > Integer.Parse( r ) ); [Fact] public void BiggerLeft() => Assert.True( new Integer( new[] { 0xBADu, 0xDEADBEEFu } ) > new Integer( new[] { 0xDEADBEEFu } ) ); [Fact] public void BiggerRight() => Assert.False( new Integer( new[] { 0xDEADBEEFu } ) > new Integer( new[] { 0xBADu, 0xDEADBEEFu } ) ); [Fact] public void CascadeGreaterThan() => Assert.True( new Integer( new[] { 1u, 1u } ) > new Integer( new[] { 1u, 0u } ) ); [Fact] public void CascadeEqual() => Assert.False( new Integer( new[] { 1u, 0u } ) > new Integer( new[] { 1u, 0u } ) ); [Fact] public void CascadeLessThan() => Assert.False( new Integer( new[] { 1u, 0u } ) > new Integer( new[] { 1u, 1u } ) ); [Fact] public void BiggerLeftNegative() => Assert.False( new Integer( new[] { 0xBADu, 0xDEADBEEFu }, true ) > new Integer( new[] { 0xDEADBEEFu }, true ) ); [Fact] public void BiggerRightNegative() => Assert.True( new Integer( new[] { 0xDEADBEEFu }, true ) > new Integer( new[] { 0xBADu, 0xDEADBEEFu }, true ) ); [Fact] public void CascadeGreaterThanNegative() => Assert.False( new Integer( new[] { 1u, 1u }, true ) > new Integer( new[] { 1u, 0u }, true ) ); [Fact] public void CascadeEqualNegative() => Assert.False( new Integer( new[] { 1u, 0u }, true ) > new Integer( new[] { 1u, 0u }, true ) ); [Fact] public void CascadeLessThanNegative() => Assert.True( new Integer( new[] { 1u, 0u }, true ) > new Integer( new[] { 1u, 1u }, true ) ); [Fact] public void BiggerLeftMixedNegativeLeft() => Assert.False( new Integer( new[] { 0xBADu, 0xDEADBEEFu }, true ) > new Integer( new[] { 0xDEADBEEFu }, false ) ); [Fact] public void BiggerRightMixedNegativeLeft() => Assert.False( new Integer( new[] { 0xDEADBEEFu }, true ) > new Integer( new[] { 0xBADu, 0xDEADBEEFu }, false ) ); [Fact] public void CascadeGreaterThanMixedNegativeLeft() => Assert.False( new Integer( new[] { 1u, 1u }, true ) > new Integer( new[] { 1u, 0u }, false ) ); [Fact] public void CascadeEqualMixedNegativeLeft() => Assert.False( new Integer( new[] { 1u, 0u }, true ) > new Integer( new[] { 1u, 0u }, false ) ); [Fact] public void CascadeLessThanMixedNegativeLeft() => Assert.False( new Integer( new[] { 1u, 0u }, true ) > new Integer( new[] { 1u, 1u }, false ) ); [Fact] public void BiggerLeftMixedNegativeRight() => Assert.True( new Integer( new[] { 0xBADu, 0xDEADBEEFu }, false ) > new Integer( new[] { 0xDEADBEEFu }, true ) ); [Fact] public void BiggerRightMixedNegativeRight() => Assert.True( new Integer( new[] { 0xDEADBEEFu }, false ) > new Integer( new[] { 0xBADu, 0xDEADBEEFu }, true ) ); [Fact] public void CascadeGreaterThanMixedNegativeRight() => Assert.True( new Integer( new[] { 1u, 1u }, false ) > new Integer( new[] { 1u, 0u }, true ) ); [Fact] public void CascadeEqualMixedNegativeRight() => Assert.True( new Integer( new[] { 1u, 0u }, false ) > new Integer( new[] { 1u, 0u }, true ) ); [Fact] public void CascadeLessThanMixedNegativeRight() => Assert.True( new Integer( new[] { 1u, 0u }, false ) > new Integer( new[] { 1u, 1u }, true ) ); } public class IntegerLessThan { [Theory] [InlineData( "0", "1", true )] [InlineData( "1", "0", false )] [InlineData( "0", "-1", false )] [InlineData( "-1", "0", true )] [InlineData( "1", "1", false )] [InlineData( "-1", "1", true )] [InlineData( "1", "-1", false )] [InlineData( "-1", "-1", false )] public void Sanity( string l, string r, bool x ) => Assert.Equal( x, Integer.Parse( l ) < Integer.Parse( r ) ); [Fact] public void BiggerLeft() => Assert.False( new Integer( new[] { 0xBADu, 0xDEADBEEFu } ) < new Integer( new[] { 0xDEADBEEFu } ) ); [Fact] public void BiggerRight() => Assert.True( new Integer( new[] { 0xDEADBEEFu } ) < new Integer( new[] { 0xBADu, 0xDEADBEEFu } ) ); [Fact] public void CascadeGreaterThan() => Assert.False( new Integer( new[] { 1u, 1u } ) < new Integer( new[] { 1u, 0u } ) ); [Fact] public void CascadeEqual() => Assert.False( new Integer( new[] { 1u, 0u } ) < new Integer( new[] { 1u, 0u } ) ); [Fact] public void CascadeLessThan() => Assert.True( new Integer( new[] { 1u, 0u } ) < new Integer( new[] { 1u, 1u } ) ); [Fact] public void BiggerLeftNegative() => Assert.True( new Integer( new[] { 0xBADu, 0xDEADBEEFu }, true ) < new Integer( new[] { 0xDEADBEEFu }, true ) ); [Fact] public void BiggerRightNegative() => Assert.False( new Integer( new[] { 0xDEADBEEFu }, true ) < new Integer( new[] { 0xBADu, 0xDEADBEEFu }, true ) ); [Fact] public void CascadeGreaterThanNegative() => Assert.True( new Integer( new[] { 1u, 1u }, true ) < new Integer( new[] { 1u, 0u }, true ) ); [Fact] public void CascadeEqualNegative() => Assert.False( new Integer( new[] { 1u, 0u }, true ) < new Integer( new[] { 1u, 0u }, true ) ); [Fact] public void CascadeLessThanNegative() => Assert.False( new Integer( new[] { 1u, 0u }, true ) < new Integer( new[] { 1u, 1u }, true ) ); [Fact] public void BiggerLeftMixedNegativeLeft() => Assert.True( new Integer( new[] { 0xBADu, 0xDEADBEEFu }, true ) < new Integer( new[] { 0xDEADBEEFu }, false ) ); [Fact] public void BiggerRightMixedNegativeLeft() => Assert.True( new Integer( new[] { 0xDEADBEEFu }, true ) < new Integer( new[] { 0xBADu, 0xDEADBEEFu }, false ) ); [Fact] public void CascadeGreaterThanMixedNegativeLeft() => Assert.True( new Integer( new[] { 1u, 1u }, true ) < new Integer( new[] { 1u, 0u }, false ) ); [Fact] public void CascadeEqualMixedNegativeLeft() => Assert.True( new Integer( new[] { 1u, 0u }, true ) < new Integer( new[] { 1u, 0u }, false ) ); [Fact] public void CascadeLessThanMixedNegativeLeft() => Assert.True( new Integer( new[] { 1u, 0u }, true ) < new Integer( new[] { 1u, 1u }, false ) ); [Fact] public void BiggerLeftMixedNegativeRight() => Assert.False( new Integer( new[] { 0xBADu, 0xDEADBEEFu }, false ) < new Integer( new[] { 0xDEADBEEFu }, true ) ); [Fact] public void BiggerRightMixedNegativeRight() => Assert.False( new Integer( new[] { 0xDEADBEEFu }, false ) < new Integer( new[] { 0xBADu, 0xDEADBEEFu }, true ) ); [Fact] public void CascadeGreaterThanMixedNegativeRight() => Assert.False( new Integer( new[] { 1u, 1u }, false ) < new Integer( new[] { 1u, 0u }, true ) ); [Fact] public void CascadeEqualMixedNegativeRight() => Assert.False( new Integer( new[] { 1u, 0u }, false ) < new Integer( new[] { 1u, 0u }, true ) ); [Fact] public void CascadeLessThanMixedNegativeRight() => Assert.False( new Integer( new[] { 1u, 0u }, false ) < new Integer( new[] { 1u, 1u }, true ) ); } public class IntegerGreaterThanOrEqual { [Theory] [InlineData( "0", "1", false )] [InlineData( "1", "0", true )] [InlineData( "0", "-1", true )] [InlineData( "-1", "0", false )] [InlineData( "1", "1", true )] [InlineData( "-1", "1", false )] [InlineData( "1", "-1", true )] [InlineData( "-1", "-1", true )] public void Sanity( string l, string r, bool x ) => Assert.Equal( x, Integer.Parse( l ) >= Integer.Parse( r ) ); [Fact] public void BiggerLeft() => Assert.True( new Integer( new[] { 0xBADu, 0xDEADBEEFu } ) >= new Integer( new[] { 0xDEADBEEFu } ) ); [Fact] public void BiggerRight() => Assert.False( new Integer( new[] { 0xDEADBEEFu } ) >= new Integer( new[] { 0xBADu, 0xDEADBEEFu } ) ); [Fact] public void CascadeGreaterThan() => Assert.True( new Integer( new[] { 1u, 1u } ) >= new Integer( new[] { 1u, 0u } ) ); [Fact] public void CascadeEqual() => Assert.True( new Integer( new[] { 1u, 0u } ) >= new Integer( new[] { 1u, 0u } ) ); [Fact] public void CascadeLessThan() => Assert.False( new Integer( new[] { 1u, 0u } ) >= new Integer( new[] { 1u, 1u } ) ); [Fact] public void BiggerLeftNegative() => Assert.False( new Integer( new[] { 0xBADu, 0xDEADBEEFu }, true ) >= new Integer( new[] { 0xDEADBEEFu }, true ) ); [Fact] public void BiggerRightNegative() => Assert.True( new Integer( new[] { 0xDEADBEEFu }, true ) >= new Integer( new[] { 0xBADu, 0xDEADBEEFu }, true ) ); [Fact] public void CascadeGreaterThanNegative() => Assert.False( new Integer( new[] { 1u, 1u }, true ) >= new Integer( new[] { 1u, 0u }, true ) ); [Fact] public void CascadeEqualNegative() => Assert.True( new Integer( new[] { 1u, 0u }, true ) >= new Integer( new[] { 1u, 0u }, true ) ); [Fact] public void CascadeLessThanNegative() => Assert.True( new Integer( new[] { 1u, 0u }, true ) >= new Integer( new[] { 1u, 1u }, true ) ); [Fact] public void BiggerLeftMixedNegativeLeft() => Assert.False( new Integer( new[] { 0xBADu, 0xDEADBEEFu }, true ) >= new Integer( new[] { 0xDEADBEEFu }, false ) ); [Fact] public void BiggerRightMixedNegativeLeft() => Assert.False( new Integer( new[] { 0xDEADBEEFu }, true ) >= new Integer( new[] { 0xBADu, 0xDEADBEEFu }, false ) ); [Fact] public void CascadeGreaterThanMixedNegativeLeft() => Assert.False( new Integer( new[] { 1u, 1u }, true ) >= new Integer( new[] { 1u, 0u }, false ) ); [Fact] public void CascadeEqualMixedNegativeLeft() => Assert.False( new Integer( new[] { 1u, 0u }, true ) >= new Integer( new[] { 1u, 0u }, false ) ); [Fact] public void CascadeLessThanMixedNegativeLeft() => Assert.False( new Integer( new[] { 1u, 0u }, true ) >= new Integer( new[] { 1u, 1u }, false ) ); [Fact] public void BiggerLeftMixedNegativeRight() => Assert.True( new Integer( new[] { 0xBADu, 0xDEADBEEFu }, false ) >= new Integer( new[] { 0xDEADBEEFu }, true ) ); [Fact] public void BiggerRightMixedNegativeRight() => Assert.True( new Integer( new[] { 0xDEADBEEFu }, false ) >= new Integer( new[] { 0xBADu, 0xDEADBEEFu }, true ) ); [Fact] public void CascadeGreaterThanMixedNegativeRight() => Assert.True( new Integer( new[] { 1u, 1u }, false ) >= new Integer( new[] { 1u, 0u }, true ) ); [Fact] public void CascadeEqualMixedNegativeRight() => Assert.True( new Integer( new[] { 1u, 0u }, false ) >= new Integer( new[] { 1u, 0u }, true ) ); [Fact] public void CascadeLessThanMixedNegativeRight() => Assert.True( new Integer( new[] { 1u, 0u }, false ) >= new Integer( new[] { 1u, 1u }, true ) ); } public class IntegerLessThanOrEqual { [Theory] [InlineData( "0", "1", true )] [InlineData( "1", "0", false )] [InlineData( "0", "-1", false )] [InlineData( "-1", "0", true )] [InlineData( "1", "1", true )] [InlineData( "-1", "1", true )] [InlineData( "1", "-1", false )] [InlineData( "-1", "-1", true )] public void Sanity( string l, string r, bool x ) => Assert.Equal( x, Integer.Parse( l ) <= Integer.Parse( r ) ); [Fact] public void BiggerLeft() => Assert.False( new Integer( new[] { 0xBADu, 0xDEADBEEFu } ) <= new Integer( new[] { 0xDEADBEEFu } ) ); [Fact] public void BiggerRight() => Assert.True( new Integer( new[] { 0xDEADBEEFu } ) <= new Integer( new[] { 0xBADu, 0xDEADBEEFu } ) ); [Fact] public void CascadeGreaterThan() => Assert.False( new Integer( new[] { 1u, 1u } ) <= new Integer( new[] { 1u, 0u } ) ); [Fact] public void CascadeEqual() => Assert.True( new Integer( new[] { 1u, 0u } ) <= new Integer( new[] { 1u, 0u } ) ); [Fact] public void CascadeLessThan() => Assert.True( new Integer( new[] { 1u, 0u } ) <= new Integer( new[] { 1u, 1u } ) ); [Fact] public void BiggerLeftNegative() => Assert.True( new Integer( new[] { 0xBADu, 0xDEADBEEFu }, true ) <= new Integer( new[] { 0xDEADBEEFu }, true ) ); [Fact] public void BiggerRightNegative() => Assert.False( new Integer( new[] { 0xDEADBEEFu }, true ) <= new Integer( new[] { 0xBADu, 0xDEADBEEFu }, true ) ); [Fact] public void CascadeGreaterThanNegative() => Assert.True( new Integer( new[] { 1u, 1u }, true ) <= new Integer( new[] { 1u, 0u }, true ) ); [Fact] public void CascadeEqualNegative() => Assert.True( new Integer( new[] { 1u, 0u }, true ) <= new Integer( new[] { 1u, 0u }, true ) ); [Fact] public void CascadeLessThanNegative() => Assert.False( new Integer( new[] { 1u, 0u }, true ) <= new Integer( new[] { 1u, 1u }, true ) ); [Fact] public void BiggerLeftMixedNegativeLeft() => Assert.True( new Integer( new[] { 0xBADu, 0xDEADBEEFu }, true ) <= new Integer( new[] { 0xDEADBEEFu }, false ) ); [Fact] public void BiggerRightMixedNegativeLeft() => Assert.True( new Integer( new[] { 0xDEADBEEFu }, true ) <= new Integer( new[] { 0xBADu, 0xDEADBEEFu }, false ) ); [Fact] public void CascadeGreaterThanMixedNegativeLeft() => Assert.True( new Integer( new[] { 1u, 1u }, true ) <= new Integer( new[] { 1u, 0u }, false ) ); [Fact] public void CascadeEqualMixedNegativeLeft() => Assert.True( new Integer( new[] { 1u, 0u }, true ) <= new Integer( new[] { 1u, 0u }, false ) ); [Fact] public void CascadeLessThanMixedNegativeLeft() => Assert.True( new Integer( new[] { 1u, 0u }, true ) <= new Integer( new[] { 1u, 1u }, false ) ); [Fact] public void BiggerLeftMixedNegativeRight() => Assert.False( new Integer( new[] { 0xBADu, 0xDEADBEEFu }, false ) <= new Integer( new[] { 0xDEADBEEFu }, true ) ); [Fact] public void BiggerRightMixedNegativeRight() => Assert.False( new Integer( new[] { 0xDEADBEEFu }, false ) <= new Integer( new[] { 0xBADu, 0xDEADBEEFu }, true ) ); [Fact] public void CascadeGreaterThanMixedNegativeRight() => Assert.False( new Integer( new[] { 1u, 1u }, false ) <= new Integer( new[] { 1u, 0u }, true ) ); [Fact] public void CascadeEqualMixedNegativeRight() => Assert.False( new Integer( new[] { 1u, 0u }, false ) <= new Integer( new[] { 1u, 0u }, true ) ); [Fact] public void CascadeLessThanMixedNegativeRight() => Assert.False( new Integer( new[] { 1u, 0u }, false ) <= new Integer( new[] { 1u, 1u }, true ) ); } public class IntegerInequality { [Theory] [InlineData( "0", "0", false )] [InlineData( "0", "1", true )] [InlineData( "1", "0", true )] [InlineData( "1", "1", false )] [InlineData( "0", "-1", true )] [InlineData( "-1", "0", true )] [InlineData( "-1", "1", true )] [InlineData( "1", "-1", true )] [InlineData( "-1", "-1", false )] public void Sanity( string l, string r, bool x ) => Assert.Equal( x, Integer.Parse( l ) != Integer.Parse( r ) ); [Fact] public void BiggerLeft() => Assert.True( new Integer( new[] { 0xBADu, 0xDEADBEEFu } ) != new Integer( new[] { 0xDEADBEEFu } ) ); [Fact] public void BiggerRight() => Assert.True( new Integer( new[] { 0xDEADBEEFu } ) != new Integer( new[] { 0xBADu, 0xDEADBEEFu } ) ); } public class IntegerAddition { [Theory] [InlineData( "1", "1", "2" )] // Sanity [InlineData( "-1", "1", "0" )] // Sanity [InlineData( "1", "-1", "0" )] // Sanity [InlineData( "-1", "-1", "-2" )] // Sanity [InlineData( "1", "0", "1" )] // Sanity [InlineData( "-1", "0", "-1" )] // Sanity [InlineData( "0", "1", "1" )] // Sanity [InlineData( "0", "-1", "-1" )] // Sanity [InlineData( "1", "5", "6" )] // l < r [InlineData( "-1", "5", "4" )] // l < r [InlineData( "1", "-5", "-4" )] // l < r [InlineData( "-1", "-5", "-6" )] // l < r [InlineData( "9", "2", "11" )] // l > r [InlineData( "-9", "2", "-7" )] // l > r [InlineData( "9", "-2", "7" )] // l > r [InlineData( "-9", "-2", "-11" )] // l > r public void Sanity( string l, string r, string s ) => Assert.Equal( Integer.Parse( s ), Integer.Parse( l ) + Integer.Parse( r ) ); [Fact] public void Overflow() => Assert.Equal( new Integer( new[] { 1u, 2u } ), new Integer( new[] { uint.MaxValue } ) + new Integer( new[] { 3u } ) ); [Fact] public void LeftBiggerNoOverflow() => Assert.Equal( new Integer( new[] { 0xFu, 0xFF0Fu } ), new Integer( new[] { 0xFu, 0xFu } ) + new Integer( new[] { 0xFF00u } ) ); [Fact] public void RightBiggerNoOverflow() => Assert.Equal( new Integer( new[] { 0xFu, 0xFF0Fu } ), new Integer( new[] { 0xFF00u } ) + new Integer( new[] { 0xFu, 0xFu } ) ); [Fact] public void CascadingOverflow() => Assert.Equal( new Integer( new[] { 1u, 0u, 0u } ), new Integer( new[] { 1u } ) + new Integer( new[] { uint.MaxValue, uint.MaxValue } ) ); [Fact] public void OverflowCausedOverflow() => Assert.Equal( new Integer( new[] { 2u, 0u, 0u } ), new Integer( new[] { 1u, 1u } ) + new Integer( new[] { 1u, uint.MaxValue - 1u, uint.MaxValue } ) ); [Fact] public void OverflowNegative() => Assert.Equal( new Integer( new[] { 1u, 2u }, true ), new Integer( new[] { uint.MaxValue }, true ) + new Integer( new[] { 3u }, true ) ); [Fact] public void LeftBiggerNoOverflowNegative() => Assert.Equal( new Integer( new[] { 0xFu, 0xFF0Fu }, true ), new Integer( new[] { 0xFu, 0xFu }, true ) + new Integer( new[] { 0xFF00u }, true ) ); [Fact] public void RightBiggerNoOverflowNegative() => Assert.Equal( new Integer( new[] { 0xFu, 0xFF0Fu }, true ), new Integer( new[] { 0xFF00u }, true ) + new Integer( new[] { 0xFu, 0xFu }, true ) ); [Fact] public void CascadingOverflowNegative() => Assert.Equal( new Integer( new[] { 1u, 0u, 0u }, true ), new Integer( new[] { 1u }, true ) + new Integer( new[] { uint.MaxValue, uint.MaxValue }, true ) ); [Fact] public void OverflowCausedOverflowNegative() => Assert.Equal( new Integer( new[] { 2u, 0u, 0u }, true ), new Integer( new[] { 1u, 1u }, true ) + new Integer( new[] { 1u, uint.MaxValue - 1u, uint.MaxValue }, true ) ); } public class IntegerSubtraction { [Theory] [InlineData( "1", "1", "0" )] // Sanity [InlineData( "-1", "1", "-2" )] // Sanity [InlineData( "1", "-1", "2" )] // Sanity [InlineData( "-1", "-1", "0" )] // Sanity [InlineData( "1", "0", "1" )] // Sanity [InlineData( "-1", "0", "-1" )] // Sanity [InlineData( "0", "1", "-1" )] // Sanity [InlineData( "0", "-1", "1" )] // Sanity [InlineData( "9", "2", "7" )] // l > r [InlineData( "-9", "2", "-11" )] // l > r [InlineData( "9", "-2", "11" )] // l > r [InlineData( "-9", "-2", "-7" )] // l > r [InlineData( "1", "5", "-4" )] // l < r [InlineData( "-1", "5", "-6" )] // l < r [InlineData( "1", "-5", "6" )] // l < r [InlineData( "-1", "-5", "4" )] // l < r public void Sanity( string l, string r, string s ) => Assert.Equal( Integer.Parse( s ), Integer.Parse( l ) - Integer.Parse( r ) ); [Fact] public void MultiItemNoUnderflow() => Assert.Equal( new Integer( new[] { 2u, 2u } ), new Integer( new[] { 3u, 4u } ) - new Integer( new[] { 1u, 2u } ) ); [Fact] public void MultiItemNegativeNoUnderflow() => Assert.Equal( new Integer( new[] { 2u, 2u }, true ), new Integer( new[] { 3u, 4u }, true ) - new Integer( new[] { 1u, 2u }, true ) ); [Fact] public void MultiItemMixedLeftNoUnderflow() => Assert.Equal( new Integer( new[] { 4u, 6u }, true ), new Integer( new[] { 3u, 4u }, true ) - new Integer( new[] { 1u, 2u } ) ); [Fact] public void MultiItemMixedRightNoUnderflow() => Assert.Equal( new Integer( new[] { 4u, 6u } ), new Integer( new[] { 3u, 4u } ) - new Integer( new[] { 1u, 2u }, true ) ); [Fact] public void MultiItemUnderflow() => Assert.Equal( new Integer( new[] { 0x2u, 0xFFFFFFFFu } ), new Integer( new[] { 4u, 2u } ) - new Integer( new[] { 1u, 3u } ) ); [Fact] public void MultiItemCascadingUnderflow() => Assert.Equal( new Integer( new[] { 0xFFFFFFFFu, 0xFFFFFFFFu } ), new Integer( new[] { 1u, 0u, 0u } ) - new Integer( new[] { 1u } ) ); [Fact] public void MultiItemNegativeOverflow() => Assert.Equal( new Integer( new[] { 4u, 2u }, true ), new Integer( new[] { 0x2u, 0xFFFFFFFFu }, true ) - new Integer( new[] { 1u, 3u } ) ); [Fact] public void MultiItemCascadingNegativeOverflow() => Assert.Equal( new Integer( new[] { 1u, 0u, 0u }, true ), new Integer( new[] { 0xFFFFFFFFu, 0xFFFFFFFFu }, true ) - new Integer( new[] { 1u } ) ); } public class IntegerMultiply { [Theory] [InlineData( "1", "1", "1" )] // Sanity [InlineData( "-1", "1", "-1" )] // Sanity [InlineData( "1", "-1", "-1" )] // Sanity [InlineData( "-1", "-1", "1" )] // Sanity [InlineData( "1", "0", "0" )] // Sanity [InlineData( "-1", "0", "0" )] // Sanity [InlineData( "0", "1", "0" )] // Sanity [InlineData( "0", "-1", "0" )] // Sanity [InlineData( "6", "7", "42" )] // multiple bits [InlineData( "-6", "7", "-42" )] // multiple bits [InlineData( "6", "-7", "-42" )] // multiple bits [InlineData( "-6", "-7", "42" )] // multiple bits public void Sanity( string l, string r, string p ) => Assert.Equal( Integer.Parse( p ), Integer.Parse( l ) * Integer.Parse( r ) ); [Fact] public void Big() => Assert.Equal( new Integer( new[] { 0x75CD9046u, 0x541D5980u } ), new Integer( new[] { 0xFEDCBA98u } ) * new Integer( new[] { 0x76543210u } ) ); [Fact] public void BigMixedLeft() => Assert.Equal( new Integer( new[] { 0x75CD9046u, 0x541D5980u }, true ), new Integer( new[] { 0xFEDCBA98u }, true ) * new Integer( new[] { 0x76543210u } ) ); [Fact] public void BigMixedRight() => Assert.Equal( new Integer( new[] { 0x75CD9046u, 0x541D5980u }, true ), new Integer( new[] { 0xFEDCBA98u } ) * new Integer( new[] { 0x76543210u }, true ) ); [Fact] public void BigNegative() => Assert.Equal( new Integer( new[] { 0x75CD9046u, 0x541D5980u } ), new Integer( new[] { 0xFEDCBA98u }, true ) * new Integer( new[] { 0x76543210u }, true ) ); } public class IntegerDivision { [Theory] [InlineData( "1", "1", "1" )] // Sanity [InlineData( "-1", "1", "-1" )] // Sanity [InlineData( "1", "-1", "-1" )] // Sanity [InlineData( "-1", "-1", "1" )] // Sanity [InlineData( "0", "1", "0" )] // Sanity [InlineData( "0", "-1", "0" )] // Sanity [InlineData( "44", "7", "6" )] // multiple bits [InlineData( "-44", "7", "-6" )] // multiple bits [InlineData( "44", "-7", "-6" )] // multiple bits [InlineData( "-44", "-7", "6" )] // multiple bits [InlineData( "52", "5", "10" )] // rev [InlineData( "-52", "5", "-10" )] // rev [InlineData( "52", "-5", "-10" )] // rev [InlineData( "-52", "-5", "10" )] // rev [InlineData( "52", "10", "5" )] // rev [InlineData( "-52", "10", "-5" )] // rev [InlineData( "52", "-10", "-5" )] // rev [InlineData( "-52", "-10", "5" )] // rev public void Sanity( string dividend, string divisor, string quotient ) => Assert.Equal( Integer.Parse( quotient ), Integer.Parse( dividend ) / Integer.Parse( divisor ) ); [Fact] public void Zero() => Assert.Equal( new Integer( new[] { 0u } ), new Integer( new[] { 5u } ) / new Integer( new[] { 10u } ) ); [Fact] public void DivideByZero() => Assert.Throws<DivideByZeroException>( () => Integer.Unit / Integer.Zero ); [Fact] public void Big() => Assert.Equal( new Integer( new[] { 0xFEDCBA98u } ), new Integer( new[] { 0x75CD9046u, 0x6651AFF8u } ) / new Integer( new[] { 0x76543210u } ) ); [Fact] public void BigMixedLeft() => Assert.Equal( new Integer( new[] { 0xFEDCBA98u }, true ), new Integer( new[] { 0x75CD9046u, 0x6651AFF8u }, true ) / new Integer( new[] { 0x76543210u } ) ); [Fact] public void BigMixedRight() => Assert.Equal( new Integer( new[] { 0xFEDCBA98u }, true ), new Integer( new[] { 0x75CD9046u, 0x6651AFF8u } ) / new Integer( new[] { 0x76543210u }, true ) ); [Fact] public void BigNegative() => Assert.Equal( new Integer( new[] { 0xFEDCBA98u } ), new Integer( new[] { 0x75CD9046u, 0x6651AFF8u }, true ) / new Integer( new[] { 0x76543210u }, true ) ); } public class IntegerModulo { [Theory] [InlineData( "1", "1", "0" )] // Sanity [InlineData( "-1", "1", "0" )] // Sanity [InlineData( "1", "-1", "0" )] // Sanity [InlineData( "-1", "-1", "0" )] // Sanity [InlineData( "0", "1", "0" )] // Sanity [InlineData( "0", "-1", "0" )] // Sanity [InlineData( "44", "7", "2" )] // multiple bits [InlineData( "-44", "7", "-2" )] // multiple bits [InlineData( "44", "-7", "2" )] // multiple bits [InlineData( "-44", "-7", "-2" )] // multiple bits [InlineData( "52", "5", "2" )] // rev [InlineData( "-52", "5", "-2" )] // rev [InlineData( "52", "-5", "2" )] // rev [InlineData( "-52", "-5", "-2" )] // rev [InlineData( "52", "10", "2" )] // rev [InlineData( "-52", "10", "-2" )] // rev [InlineData( "52", "-10", "2" )] // rev [InlineData( "-52", "-10", "-2" )] // rev public void Sanity( string dividend, string divisor, string remainder ) => Assert.Equal( Integer.Parse( remainder ), Integer.Parse( dividend ) % Integer.Parse( divisor ) ); [Fact] public void Zero() => Assert.Equal( new Integer( new[] { 0u } ), new Integer( new[] { 20u } ) % new Integer( new[] { 10u } ) ); [Fact] public void DivideByZero() => Assert.Throws<DivideByZeroException>( () => Integer.Unit % Integer.Zero ); [Fact] public void Big() => Assert.Equal( new Integer( new[] { 0x12345678u } ), new Integer( new[] { 0x75CD9046u, 0x6651AFF8u } ) % new Integer( new[] { 0x76543210u } ) ); [Fact] public void BigMixedLeft() => Assert.Equal( new Integer( new[] { 0x12345678u }, true ), new Integer( new[] { 0x75CD9046u, 0x6651AFF8u }, true ) % new Integer( new[] { 0x76543210u } ) ); [Fact] public void BigMixedRight() => Assert.Equal( new Integer( new[] { 0x12345678u } ), new Integer( new[] { 0x75CD9046u, 0x6651AFF8u } ) % new Integer( new[] { 0x76543210u }, true ) ); [Fact] public void BigNegative() => Assert.Equal( new Integer( new[] { 0x12345678u }, true ), new Integer( new[] { 0x75CD9046u, 0x6651AFF8u }, true ) % new Integer( new[] { 0x76543210u }, true ) ); } public class IntegerDivisionModulo { [Theory] [InlineData( "1", "1", "1", "0" )] // Sanity [InlineData( "-1", "1", "-1", "0" )] // Sanity [InlineData( "1", "-1", "-1", "0" )] // Sanity [InlineData( "-1", "-1", "1", "0" )] // Sanity [InlineData( "0", "1", "0", "0" )] // Sanity [InlineData( "0", "-1", "0", "0" )] // Sanity [InlineData( "44", "7", "6", "2" )] // multiple bits [InlineData( "-44", "7", "-6", "-2" )] // multiple bits [InlineData( "44", "-7", "-6", "2" )] // multiple bits [InlineData( "-44", "-7", "6", "-2" )] // multiple bits [InlineData( "52", "5", "10", "2" )] // rev [InlineData( "-52", "5", "-10", "-2" )] // rev [InlineData( "52", "-5", "-10", "2" )] // rev [InlineData( "-52", "-5", "10", "-2" )] // rev [InlineData( "52", "10", "5", "2" )] // rev [InlineData( "-52", "10", "-5", "-2" )] // rev [InlineData( "52", "-10", "-5", "2" )] // rev [InlineData( "-52", "-10", "5", "-2" )] // rev public void Sanity( string dividend, string divisor, string quotient, string remainder ) => Assert.Equal( new Tuple<Integer,Integer>( Integer.Parse( quotient ), Integer.Parse( remainder ) ), Integer.op_DividePercent( Integer.Parse( dividend ), Integer.Parse( divisor ) ) ); [Fact] public void DivideByZero() => Assert.Throws<DivideByZeroException>( () => Integer.op_DividePercent( Integer.Unit, Integer.Zero ) ); [Fact] public void Big() => Assert.Equal( new Tuple<Integer,Integer>( new Integer( new[] { 0xFEDCBA98u } ), new Integer( new[] { 0x12345678u } ) ), Integer.op_DividePercent( new Integer( new[] { 0x75CD9046u, 0x6651AFF8u } ), new Integer( new[] { 0x76543210u } ) ) ); [Fact] public void BigMixedLeft() => Assert.Equal( new Tuple<Integer,Integer>( new Integer( new[] { 0xFEDCBA98u }, true ), new Integer( new[] { 0x12345678u }, true ) ), Integer.op_DividePercent( new Integer( new[] { 0x75CD9046u, 0x6651AFF8u }, true ), new Integer( new[] { 0x76543210u } ) ) ); [Fact] public void BigMixedRight() => Assert.Equal( new Tuple<Integer,Integer>( new Integer( new[] { 0xFEDCBA98u }, true ), new Integer( new[] { 0x12345678u } ) ), Integer.op_DividePercent( new Integer( new[] { 0x75CD9046u, 0x6651AFF8u } ), new Integer( new[] { 0x76543210u }, true ) ) ); [Fact] public void BigNegative() => Assert.Equal( new Tuple<Integer,Integer>( new Integer( new[] { 0xFEDCBA98u } ), new Integer( new[] { 0x12345678u }, true ) ), Integer.op_DividePercent( new Integer( new[] { 0x75CD9046u, 0x6651AFF8u }, true ), new Integer( new[] { 0x76543210u }, true ) ) ); } public class IntegerNegation { [Theory] [InlineData( "1", "-1" )] // Sanity [InlineData( "-1", "1" )] // Sanity [InlineData( "0", "0" )] // Sanity public void Sanity( string a, string e ) => Assert.Equal( Integer.Parse( e ), -Integer.Parse( a ) ); [Fact] public void Big() => Assert.Equal( new Integer( new[] { 0xFEDCBA9u, 0x76543210u }, true ), -new Integer( new[] { 0xFEDCBA9u, 0x76543210u } ) ); [Fact] public void BigNegative() => Assert.Equal( new Integer( new[] { 0xFEDCBA9u, 0x76543210u } ), -new Integer( new[] { 0xFEDCBA9u, 0x76543210u }, true ) ); } public class IntegerEquals { [Theory] [InlineData( "1", "1", true )] // Sanity [InlineData( "1", "-1", false )] // Sanity [InlineData( "-1", "1", false )] // Sanity [InlineData( "-1", "-1", true )] // Sanity public void Sanity( string l, string r, bool e ) => Assert.Equal( e, Integer.Parse( l ).Equals( Integer.Parse( r ) ) ); [Fact] public void NaturalEquals() => Assert.True( Integer.Unit.Equals( Natural.Unit ) ); [Fact] public void NaturalNotEquals() => Assert.False( Integer.Unit.Equals( Natural.Zero ) ); [Fact] public void NaturalSignNotEquals() => Assert.False( ( -Integer.Unit ).Equals( Natural.Unit ) ); } public class IntegerToString { [Theory] [InlineData( 0u, false, "0" )] // Sanity [InlineData( 1u, false, "1" )] // Sanity [InlineData( 123u, false, "123" )] // multiple bits [InlineData( 45678u, false, "45678" )] // rev [InlineData( 1u, true, "-1" )] // Sanity [InlineData( 123u, true, "-123" )] // multiple bits [InlineData( 45678u, true, "-45678" )] // rev public void Sanity( uint data, bool negative, string expected ) => Assert.Equal( expected, new Integer( new[] { data }, negative ).ToString() ); [Fact] public void Bigger() => Assert.Equal( "1234567890123456789", new Integer( new[] { 0x112210F4u, 0x7DE98115u } ).ToString() ); [Fact] public void BiggerNegative() => Assert.Equal( "-1234567890123456789", new Integer( new[] { 0x112210F4u, 0x7DE98115u }, true ).ToString() ); } public class IntegerParse { [Theory] [InlineData( "0", 0u, false )] // Sanity [InlineData( "1", 1u, false )] // Sanity [InlineData( "123", 123u, false )] // multiple bits [InlineData( "45678", 45678u, false )] // rev [InlineData( "-0", 0u, false )] // Sanity [InlineData( "-1", 1u, true )] // Sanity [InlineData( "-123", 123u, true )] // multiple bits [InlineData( "-45678", 45678u, true )] // rev public void Sanity( string str, uint data, bool negative ) => Assert.Equal( new Integer( new[] { data }, negative ), Integer.Parse( str ) ); [Fact] public void Bigger() => Assert.Equal( new Integer( new[] { 0x112210F4u, 0x7DE98115u } ), Integer.Parse( "1234567890123456789" ) ); [Fact] public void BiggerNegative() => Assert.Equal( new Integer( new[] { 0x112210F4u, 0x7DE98115u }, true ), Integer.Parse( "-1234567890123456789" ) ); } }
TypeScript
UTF-8
2,730
2.546875
3
[ "MIT" ]
permissive
import { slackAPI } from './slackAPI'; import {Channel} from './channelAPI'; import config from './config'; import { MessageAttachment } from '@slack/web-api/dist/methods'; const shuffle = require('shuffle-array'); const noticeTempl:[MessageAttachment] = [{ "fallback": `Please, help me to keep our Slack workspace clean by renaming this channel to comply with our naming convention <${config.url.namingConventionUrl}>.`, "color": "#36a64f", "pretext": "I need your help !", "title": "This Channel name doest not comply with our Slack Naming Convention (click here to consult).", "title_link": `${config.url.namingConventionUrl}`, "text": `Please, help us to keep Slack a friendly place.\nRename the name of this channel to comply with our Slack Naming Convention.\nNeed help, contact <#${config.admin.channelId}>.`, "footer": "SlackPrettify" }] const supNoticeTempl:[MessageAttachment] = [{ "fallback": "Keep our Slack clean", "color": "#36a64f", "pretext": "Following channels where notified", "fields": [], "footer": "SlackPrettify" }] class NotifyAPI { constructor() { } private async notifyChannel (ch:Channel) { let res:any; console.log("Notify sent to channel "+ch.name); if (process.env.NODE_ENV.indexOf('dev') > -1) { res = await slackAPI.client.chat.postMessage({channel: config.sup.channelId, text:"", attachments: noticeTempl}) } else { res = await slackAPI.client.chat.postMessage({channel: ch.id, text:"", attachments: noticeTempl}) } console.log('Message sent: ', res.ts); } private async notifySup(lst:MessageAttachment["fields"], total:number) { let msg=supNoticeTempl; msg[0].fields = lst; msg[0].title = `${lst.length} channels notified / ${total} channels to fix`; console.log(`Report sent to sup ${lst.length} to fix/${total}`); const res = await slackAPI.client.chat.postMessage({channel: config.sup.channelId, text:"", attachments: supNoticeTempl}) console.log('Message sent: ', res.ts); } public async notifyChannels(channels:Channel[]) { let shuffledChannels:Channel[]; let ChannelsSumUp: MessageAttachment["fields"] = []; shuffledChannels = shuffle(channels); for (var i = 0, len = Math.min(shuffledChannels.length,config.samplesMax); i < len; i++) { await this.notifyChannel(shuffledChannels[i]) ChannelsSumUp.push({title: `${shuffledChannels[i].id}`, value:'To fix', short:true}); }; await this.notifySup(ChannelsSumUp, shuffledChannels.length); } }; const notifyAPI = new NotifyAPI(); export { notifyAPI };
Markdown
UTF-8
729
2.671875
3
[]
no_license
# avatar-generator A simple Vue project that generates random (but reproducible) avatars. A project to learn how SVG and paths work while using some of my artistic talent :). Check online: https://avatar-generator.netlify.app Screenshot: ![Screen shot](/avatarg.png?raw=true "Avatar Generator") Video of usage: ![Screen recording](/avatarg1.gif?raw=true "Avatar Generator") ## Project setup ``` npm install ``` ### Compiles and hot-reloads for development ``` npm run serve ``` ### Compiles and minifies for production ``` npm run build ``` ### Run your tests ``` npm run test ``` ### Lints and fixes files ``` npm run lint ``` ### Customize configuration See [Configuration Reference](https://cli.vuejs.org/config/).
Java
UTF-8
497
2.265625
2
[]
no_license
package ru.job4j.array.ru.job4j.array; import static org.junit.Assert.assertThat; import static org.hamcrest.Matchers.is; import junit.framework.TestCase; public class SkipNegativeTest extends TestCase { public void testSkip() { int[][] in = { {1, -2}, {1, 2} }; int[][] expect = { {1, 0}, {1, 2} }; int[][] result = SkipNegative.skip(in); assertThat(result, is(expect)); } }
PHP
UTF-8
4,614
3.046875
3
[]
no_license
<?php namespace wishlist\controllers; use Slim\Http\Request; use Slim\Http\Response; use wishlist\models\Utilisateur; /** * Class ControleurConnexion * @package wishlist\controllers */ class ControleurConnexion { private $c; /** * Constructeur de la classe ControleurConnexion * @param \Slim\Container $c */ public function __construct(\Slim\Container $c) { $this->c = $c; } /** * Methode qui appelle le render 0 de VueCompte pour afficher * la page de connexion * @param Request $rq * @param Response $rs * @param array $args * @return Response */ public function getConnexion(Request $rq, Response $rs, array $args): Response { session_start(); $htmlvars = [ 'basepath' => $rq->getUri()->getBasePath() ]; //ouvre la page html 0 $vue = new \wishlist\views\VueCompte([], $this->c); $html = $vue->render($htmlvars, 0); $rs->getBody()->write($html); return $rs; } /** * Methode qui permet de connecter un utilisateur * @param Request $rq * @param Response $rs * @param array $args * @return Response */ public function connexion(Request $rq, Response $rs, array $args): Response { $htmlvars = [ 'basepath' => $rq->getUri()->getBasePath() ]; //recuperation des données $post = $rq->getParsedBody(); $identifiant = filter_var($post['identifiant'], FILTER_SANITIZE_STRING) ; $mdp = filter_var($post['mdp'], FILTER_SANITIZE_STRING); $user = Utilisateur::where('Identifiant', '=', $identifiant) ->first(); //la session devrait etre dans le if, mais on ne sait pas pourquoi la function retourne faux. session_start(); $_SESSION['profile'] = $user['idUser']; if (password_verify($mdp, $user['MotDePasse'])) { // session_start(); // $_SESSION['profile'] = $user['idUser']; } //redirection vers la racine $url_racine = $this->c->router->pathFor('racine'); return $rs->withRedirect($url_racine); } /** * Methode qui permet de creer un compte * @param Request $rq * @param Response $rs * @param array $args * @return Response */ public function creationCompte(Request $rq, Response $rs, array $args): Response { session_start(); $htmlvars = [ 'basepath' => $rq->getUri()->getBasePath() ]; $vue = new \wishlist\views\VueCompte([], $this->c); $html = $vue->render($htmlvars, 3); $rs->getBody()->write($html); return $rs; } /** * Methode qui enregistre dans la base de données le compte créer * @param Request $rq * @param Response $rs * @param array $args * @return Response */ public function creationComptePost(Request $rq, Response $rs, array $args): Response { session_start(); $htmlvars = [ 'basepath' => $rq->getUri()->getBasePath() ]; //recuperation des données $post = $rq->getParsedBody(); $identifiant = filter_var($post['identifiant'], FILTER_SANITIZE_STRING) ; $mdp = filter_var($post['mdp'], FILTER_SANITIZE_STRING) ; //hashage du mdp $hash=password_hash($mdp, PASSWORD_DEFAULT); //enregistrement des données $user = new Utilisateur(); $user->Identifiant = $identifiant; $user->MotDePasse = $hash; $user->save(); //fin de redirection $vue = new \wishlist\views\VueCompte([], $this->c); $html = $vue->render($htmlvars, 0); $rs->getBody()->write($html); return $rs; } /** * Methode qui permet de deconnecter un compte * @param Request $rq * @param Response $rs * @param array $args * @return Response */ public function deconnexion(Request $rq, Response $rs, array $args): Response { session_start(); $htmlvars = [ 'basepath' => $rq->getUri()->getBasePath() ]; // ferme la session session_destroy(); $vue = new \wishlist\views\VueParticipant([], $this->c); $html = $vue->render($htmlvars,0); $rs->getBody()->write($html); return $rs; } }
C++
UTF-8
2,213
2.6875
3
[]
no_license
/*========================================================================== * * Copyright (C) 1999, 2000 Microsoft Corporation. All Rights Reserved. * * File: wavformat.h * Content: * This module contains the CWaveFormat class which is used to work with * WAVEFORMATEX structures. * * History: * Date By Reason * ==== == ====== * 07/06/00 rodtoll Created * ***************************************************************************/ #ifndef __WAVFORMAT_H #define __WAVFORMAT_H ///////////////////////////////////////////////////////////////////// // // CWaveFormat // // Used to store and manipulate WAVEFORMATEX structures. // class CWaveFormat { public: CWaveFormat(): m_pwfxFormat(NULL), m_fOwned(FALSE) {}; ~CWaveFormat() { Cleanup(); }; // Initialize with full parameters HRESULT Initialize( WORD wFormatTag, DWORD nSamplesPerSec, WORD nChannels, WORD wBitsPerSample, WORD nBlockAlign, DWORD nAvgBytesPerSec, WORD cbSize, void *pvExtra ); // Initialize and copy the specified format HRESULT InitializeCPY( LPWAVEFORMATEX pwfxFormat, void *pvExtra ); // Build a standard PCM format HRESULT InitializePCM( WORD wHZ, BOOL fStereo, BYTE bBitsPerSample ); // Create a WAVEFORMAT that is of size dwSize HRESULT InitializeMEM( DWORD dwSize ); // Initialize but unowned HRESULT InitializeUSE( WAVEFORMATEX *pwfxFormat ); // Initialize from registry HRESULT InitializeREG( HKEY hKeyRoot, const WCHAR *wszPath ); // Set this object equal to the parameter HRESULT SetEqual( CWaveFormat *pwfxFormat ); // Are these two types equal? BOOL IsEqual( CWaveFormat *pwfxFormat ); // Return a pointer to the format inline WAVEFORMATEX *GetFormat() { return m_pwfxFormat; }; inline WAVEFORMATEX *Disconnect() { m_fOwned = FALSE; return GetFormat(); }; // Is this an eight bit waveformat? inline BOOL IsEightBit() const { return (m_pwfxFormat->wBitsPerSample==8); }; // Write the contained value to the registry HRESULT WriteREG( HKEY hKeyRoot, const WCHAR *wszPath ); protected: void Cleanup(); WAVEFORMATEX *m_pwfxFormat; BOOL m_fOwned; }; #endif
Python
UTF-8
9,682
2.59375
3
[ "BSD-2-Clause" ]
permissive
from twisted.internet.defer import inlineCallbacks from twisted.internet.task import Clock from vumi.components.window_manager import WindowManager, WindowException from vumi.tests.helpers import VumiTestCase, PersistenceHelper class TestWindowManager(VumiTestCase): @inlineCallbacks def setUp(self): self.persistence_helper = self.add_helper(PersistenceHelper()) redis = yield self.persistence_helper.get_redis_manager() self.window_id = 'window_id' # Patch the clock so we can control time self.clock = Clock() self.patch(WindowManager, 'get_clock', lambda _: self.clock) self.wm = WindowManager(redis, window_size=10, flight_lifetime=10) self.add_cleanup(self.wm.stop) yield self.wm.create_window(self.window_id) self.redis = self.wm.redis @inlineCallbacks def test_windows(self): windows = yield self.wm.get_windows() self.assertTrue(self.window_id in windows) def test_strict_window_recreation(self): return self.assertFailure( self.wm.create_window(self.window_id, strict=True), WindowException) @inlineCallbacks def test_window_recreation(self): orig_clock_time = self.clock.seconds() clock_time = yield self.wm.create_window(self.window_id) self.assertEqual(clock_time, orig_clock_time) @inlineCallbacks def test_window_removal(self): yield self.wm.add(self.window_id, 1) yield self.assertFailure(self.wm.remove_window(self.window_id), WindowException) key = yield self.wm.get_next_key(self.window_id) item = yield self.wm.get_data(self.window_id, key) self.assertEqual(item, 1) self.assertEqual((yield self.wm.remove_window(self.window_id)), None) @inlineCallbacks def test_adding_to_window(self): for i in range(10): yield self.wm.add(self.window_id, i) window_key = self.wm.window_key(self.window_id) window_members = yield self.redis.llen(window_key) self.assertEqual(window_members, 10) @inlineCallbacks def test_fetching_from_window(self): for i in range(12): yield self.wm.add(self.window_id, i) flight_keys = [] for i in range(10): flight_key = yield self.wm.get_next_key(self.window_id) self.assertTrue(flight_key) flight_keys.append(flight_key) out_of_window_flight = yield self.wm.get_next_key(self.window_id) self.assertEqual(out_of_window_flight, None) # We should get data out in the order we put it in for i, flight_key in enumerate(flight_keys): data = yield self.wm.get_data(self.window_id, flight_key) self.assertEqual(data, i) # Removing one should allow for space for the next to fill up yield self.wm.remove_key(self.window_id, flight_keys[0]) next_flight_key = yield self.wm.get_next_key(self.window_id) self.assertTrue(next_flight_key) @inlineCallbacks def test_set_and_external_id(self): yield self.wm.set_external_id(self.window_id, "flight_key", "external_id") self.assertEqual( (yield self.wm.get_external_id(self.window_id, "flight_key")), "external_id") self.assertEqual( (yield self.wm.get_internal_id(self.window_id, "external_id")), "flight_key") @inlineCallbacks def test_remove_key_removes_external_and_internal_id(self): yield self.wm.set_external_id(self.window_id, "flight_key", "external_id") yield self.wm.remove_key(self.window_id, "flight_key") self.assertEqual( (yield self.wm.get_external_id(self.window_id, "flight_key")), None) self.assertEqual( (yield self.wm.get_internal_id(self.window_id, "external_id")), None) @inlineCallbacks def assert_count_waiting(self, window_id, amount): self.assertEqual((yield self.wm.count_waiting(window_id)), amount) @inlineCallbacks def assert_expired_keys(self, window_id, amount): # Stuff has taken too long and so we should get 10 expired keys expired_keys = yield self.wm.get_expired_flight_keys(window_id) self.assertEqual(len(expired_keys), amount) @inlineCallbacks def assert_in_flight(self, window_id, amount): self.assertEqual((yield self.wm.count_in_flight(window_id)), amount) @inlineCallbacks def slide_window(self, limit=10): for i in range(limit): yield self.wm.get_next_key(self.window_id) @inlineCallbacks def test_expiry_of_acks(self): def mock_clock_time(self): return self._clocktime self.patch(WindowManager, 'get_clocktime', mock_clock_time) self.wm._clocktime = 0 for i in range(30): yield self.wm.add(self.window_id, i) # We're manually setting the clock instead of using clock.advance() # so we can wait for the deferreds to finish before continuing to the # next clear_expired_flight_keys run since LoopingCall() will only fire # again if the previous run has completed. yield self.slide_window() self.wm._clocktime = 10 yield self.wm.clear_expired_flight_keys() self.assert_expired_keys(self.window_id, 10) yield self.slide_window() self.wm._clocktime = 20 yield self.wm.clear_expired_flight_keys() self.assert_expired_keys(self.window_id, 20) yield self.slide_window() self.wm._clocktime = 30 yield self.wm.clear_expired_flight_keys() self.assert_expired_keys(self.window_id, 30) self.assert_in_flight(self.window_id, 0) self.assert_count_waiting(self.window_id, 0) @inlineCallbacks def test_monitor_windows(self): yield self.wm.remove_window(self.window_id) window_ids = ['window_id_1', 'window_id_2'] for window_id in window_ids: yield self.wm.create_window(window_id) for i in range(20): yield self.wm.add(window_id, i) key_callbacks = {} def callback(window_id, key): key_callbacks.setdefault(window_id, []).append(key) cleanup_callbacks = [] def cleanup_callback(window_id): cleanup_callbacks.append(window_id) yield self.wm._monitor_windows(callback, False) self.assertEqual(set(key_callbacks.keys()), set(window_ids)) self.assertEqual(len(key_callbacks.values()[0]), 10) self.assertEqual(len(key_callbacks.values()[1]), 10) yield self.wm._monitor_windows(callback, False) # Nothing should've changed since we haven't removed anything. self.assertEqual(len(key_callbacks.values()[0]), 10) self.assertEqual(len(key_callbacks.values()[1]), 10) for window_id, keys in key_callbacks.items(): for key in keys: yield self.wm.remove_key(window_id, key) yield self.wm._monitor_windows(callback, False) # Everything should've been processed now self.assertEqual(len(key_callbacks.values()[0]), 20) self.assertEqual(len(key_callbacks.values()[1]), 20) # Now run again but cleanup the empty windows self.assertEqual(set((yield self.wm.get_windows())), set(window_ids)) for window_id, keys in key_callbacks.items(): for key in keys: yield self.wm.remove_key(window_id, key) yield self.wm._monitor_windows(callback, True, cleanup_callback) self.assertEqual(len(key_callbacks.values()[0]), 20) self.assertEqual(len(key_callbacks.values()[1]), 20) self.assertEqual((yield self.wm.get_windows()), []) self.assertEqual(set(cleanup_callbacks), set(window_ids)) class TestConcurrentWindowManager(VumiTestCase): @inlineCallbacks def setUp(self): self.persistence_helper = self.add_helper(PersistenceHelper()) redis = yield self.persistence_helper.get_redis_manager() self.window_id = 'window_id' # Patch the count_waiting so we can fake the race condition self.clock = Clock() self.patch(WindowManager, 'count_waiting', lambda _, window_id: 100) self.wm = WindowManager(redis, window_size=10, flight_lifetime=10) self.add_cleanup(self.wm.stop) yield self.wm.create_window(self.window_id) self.redis = self.wm.redis @inlineCallbacks def test_race_condition(self): """ A race condition can occur when multiple window managers try and access the same window at the same time. A LoopingCall loops over the available windows, for those windows it tries to get a next key. It does that by checking how many are waiting to be sent out and adding however many it can still carry to its own flight. Since there are concurrent workers, between the time of checking how many are available and how much room it has available, a different window manager may have already beaten it to it. If this happens Redis' `rpoplpush` method will return None since there are no more available keys for the given window. """ yield self.wm.add(self.window_id, 1) yield self.wm.add(self.window_id, 2) yield self.wm._monitor_windows(lambda *a: True, True) self.assertEqual((yield self.wm.get_next_key(self.window_id)), None)
JavaScript
UTF-8
1,879
2.984375
3
[]
no_license
function logout (){ /* When the function is activated by onclick event the name and password are deleted from localStorage */ localStorage.removeItem("username"); localStorage.removeItem("password"); /*Login page redirection*/ window.location.assign("../JB_admin.html"); } function check_admin(){ /* if someone attempts to hit the page without authentication will be automatically redirected e.g domainname/templates/admin_page*/ var user = {admin:"Jonas-Brothers", password:"JohnLennon1964"}; var admin=localStorage.getItem("username"); var password=localStorage.getItem("password"); if(user.admin==admin && user.password==password){ /* If the condition is true the admin will be welcome */ document.getElementById("admin").innerHTML="Welcome: "+admin; /* If we are logged localStorage will update automatically */ load_db("../files/news.js","obj"); load_db("../files/pictures.js","pictures"); load_db("../files/videos.js","videos"); load_db("../files/events.js","events"); }else{ /* else will be redirected to login page */ window.location.assign("../JB_admin.html"); } } check_admin(); function load_db(location,lS_key) { /* 'location' - is path location of server storage files and 'lS_key' - represent localStorage key XMLHttpRequest is used to send and recive data from server To send data si used Post method and Get to recive data*/ var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { /*readyState==4 means request finished and response is ready status == 200 means this is the standard response for successful HTTP requests*/ if (this.readyState == 4 && this.status == 200) { /* Data is stored in local storage */ localStorage.setItem(lS_key,JSON.parse(this.responseText)); } }; xhttp.open("GET", location, true); xhttp.send(); }
C++
UTF-8
3,223
2.859375
3
[ "MIT" ]
permissive
#include <math.h> #include <fstream> #include <string.h> #include "Parameterization.h" #include "GlobalMacros.h" using namespace std; BoxProjection::BoxProjection(double radius) : Parameterization(radius) { name = "BoxProjection"; Jmax = 20; Kmax = 20; Lmax = 1; Gmax = 6; x_lb = -radius + 0.00001e0; x_ub = radius - 0.00001e0; y_lb = -radius + 0.00001e0; y_ub = radius - 0.00001e0; z_lb = -radius + 0.00001e0; z_ub = radius - 0.00001e0; dx = (x_ub - x_lb) / (double)(Jmax - 1); dy = (y_ub - y_lb) / (double)(Jmax - 1); dz = (z_ub - z_lb) / (double)(Jmax - 1); } double BoxProjection::coordinateX(int J, int K, int L, int G) { switch (G) { case 0: // Lower z x = x_lb + (double)J * dx; y = y_lb + (double)K * dy; z = z_lb; break; case 1: // Lower y x = x_ub - (double)J * dx; y = y_lb; z = z_lb + (double)K * dz; break; case 2: // Lower x x = x_lb; y = y_lb + (double)J * dy; z = z_lb + (double)K * dz; break; case 3: // Upper z x = x_ub - (double)J * dx; y = y_lb + (double)K * dy; z = z_ub; break; case 4: // Upper y x = x_lb + (double)J * dx; y = y_ub; z = z_lb + (double)K * dz; break; case 5: // Upper x x = x_ub; y = y_ub - (double)J * dy; z = z_lb + (double)K * dz; break; } return x * projection(x, y, z); } double BoxProjection::coordinateY(int J, int K, int L, int G) { switch (G) { case 0: // Lower z x = x_lb + (double)J * dx; y = y_lb + (double)K * dy; z = z_lb; break; case 1: // Lower y x = x_ub - (double)J * dx; y = y_lb; z = z_lb + (double)K * dz; break; case 2: // Lower x x = x_lb; y = y_lb + (double)J * dy; z = z_lb + (double)K * dz; break; case 3: // Upper z x = x_ub - (double)J * dx; y = y_lb + (double)K * dy; z = z_ub; break; case 4: // Upper y x = x_lb + (double)J * dx; y = y_ub; z = z_lb + (double)K * dz; break; case 5: // Upper x x = x_ub; y = y_ub - (double)J * dy; z = z_lb + (double)K * dz; break; } return y * projection(x, y, z); } double BoxProjection::coordinateZ(int J, int K, int L, int G) { switch (G) { case 0: // Lower z x = x_lb + (double)J * dx; y = y_lb + (double)K * dy; z = z_lb; break; case 1: // Lower y x = x_ub - (double)J * dx; y = y_lb; z = z_lb + (double)K * dz; break; case 2: // Lower x x = x_lb; y = y_lb + (double)J * dy; z = z_lb + (double)K * dz; break; case 3: // Upper z x = x_ub - (double)J * dx; y = y_lb + (double)K * dy; z = z_ub; break; case 4: // Upper y x = x_lb + (double)J * dx; y = y_ub; z = z_lb + (double)K * dz; break; case 5: // Upper x x = x_ub; y = y_ub - (double)J * dy; z = z_lb + (double)K * dz; break; } return z * projection(x, y, z); } double BoxProjection::projection(double x, double y, double z) { return radius / sqrt(x * x + y * y + z * z); }
PHP
UTF-8
1,112
2.546875
3
[ "MIT" ]
permissive
<?php namespace App\Traits; use App\Models\SystemSetting; use App\Models\MemberCard; use Carbon\Carbon; trait MemberCardTrait { public function calculateDueDate() { $due = SystemSetting::where('field', 'member_card_due')->first()['value']; return Carbon::now()->addMonths($due); } public function cardPrefix() { $prefix = SystemSetting::where('field', 'member_card_prefix')->first()['value']; return $prefix; } public function cardPostfix() { $postfix = SystemSetting::where('field', 'member_card_postfix')->first()['value']; return $postfix; } public function incrementCardNumber() { $card_length = SystemSetting::where('field', 'member_card_length')->first()['value']; $latest_no = MemberCard::orderBy('card_no', 'DESC')->first()['card_no']; if(count($latest_no) <= 0){ $card_latest_no = sprintf('%0' . $card_length . 'd', 1); }else{ $card_latest_no = sprintf('%0' . $card_length . 'd', $latest_no + 1); } return $card_latest_no; } }
Python
UTF-8
2,360
2.765625
3
[]
no_license
#!/usr/bin/env python # coding: utf-8 # In[1]: get_ipython().run_line_magic('matplotlib', 'inline') import matplotlib.pyplot as plt import re import urllib.request import numpy as np from datetime import datetime, timedelta # In[2]: def find_nearest_cell(array,value): idx = (np.abs(array-value)).argmin() return idx # In[3]: latarray = np.linspace(-89.875,89.875,720) lonarray = np.linspace(0.125,359.875,1440) huancayo = (-12.06513, 360-75.20486) # In[4]: celllatindex = find_nearest_cell(latarray,huancayo[0]) celllonindex = find_nearest_cell(lonarray,huancayo[1]) print(celllatindex,celllonindex) # In[5]: zerodate = datetime(1850,1,1) zerodate.isoformat(' ') # In[6]: begindate = zerodate + timedelta(days=56978.5) begindate.isoformat(' ') # In[7]: enddate = zerodate + timedelta(days=89850.5) enddate.isoformat(' ') # In[8]: intervals = [[0,4999],[5000,9999],[10000,14999],[15000,19999],[20000,24999],[25000,29999],[30000,34674]] pptlist = [] daylist = [] # In[9]: for interval in intervals: fp = urllib.request.urlopen("https://dataserver.nccs.nasa.gov/thredds/dodsC/bypass/NEX-GDDP/bcsd/rcp45/r1i1p1/pr/CSIRO-Mk3-6-0.ncml.ascii?pr["+str(interval[0])+":1:"+str(interval[1])+"]["+str(celllatindex)+":1:"+str(celllatindex)+"]["+str(celllonindex)+":1:"+str(celllonindex)+"]") mybytes = fp.read() mystr = mybytes.decode("utf8") fp.close() lines = mystr.split('\n') breakers = [] breakerTexts = ['pr[time','pr.pr','pr.time'] for line in lines: for text in breakerTexts: if text in line: breakers.append(lines.index(line)) dayline = lines[breakers[0]] dayline = re.sub('\[|\]',' ',dayline) days = int(dayline.split()[4]) print("Procesing interval %s of %d days" % (str(interval), days)) for item in range(breakers[1]+1, breakers[1]+days+1): ppt = float(lines[item].split(',')[1])*86400 pptlist.append(ppt) for day in lines[breakers[2]+1].split(','): daylist.append(zerodate + timedelta(days=float(day))) # In[10]: plt.plot(daylist,pptlist) plt.gcf().autofmt_xdate() plt.ylabel('Global Precipitation (mm/day)') plt.show() # In[ ]:
Ruby
UTF-8
193
3.453125
3
[]
no_license
x = "hi there" my_hash = {x: "some value"} my_hash2 = {x => "some value"} # The difference b/w the 2... # my_hash uses a symbol, x, as the key # my_hash2 uses the string 'hi there' as the key
C++
UTF-8
629
3.375
3
[]
no_license
#include<iostream> #include<vector> #include<iterator> using namespace std; int main() { vector<int> vec; vector<int>::iterator i; for(int j=0;j<10;j++) { vec.push_back(j); } for(i=vec.begin();i!=vec.end();++i) { cout<<*i<<endl; } } /* //stl_cpp_2.cpp #include <vector> #include <iostream> int main(void) { std::vector<double> a; std::vector<double>::const_iterator i; a.push_back(1); a.push_back(2); a.push_back(3); a.push_back(4); a.push_back(5); for(i=a.begin(); i!=a.end(); ++i){ std::cout<<(*i)<<std::endl; } return 0; } */
Python
UTF-8
669
3.75
4
[]
no_license
class Student: def __init__(self, firstname, lastname): self.fistname = firstname self.lastname = lastname def getName(self): fullname = self.fistname + " " + self.lastname return fullname def printName(self): print(self.getName()) class Mediateknikstudent(Student): def getGrettingString(self): grettingString = "He" return grettingString def printGrettingString(self): print(self.getGrettingString()) studentOne = Student("Adam", "Jonsson") studentOne.printName() studentTwo = Mediateknikstudent("Madam", "Nossnoj") studentTwo.printName() studentTwo.printGrettingString()
C++
UTF-8
1,088
3.578125
4
[]
no_license
#include <iostream> #include <iomanip> #include "invmenu.h" using namespace std; void invMenu() { //Info Storage int selection; //Output cout << setw(40) << "Serendipity Booksellers" << endl; cout << setw(37) << "Inventory Database" << endl; cout << endl; cout << "1. Look-Up a Book" << endl; cout << "2. Add a Book" << endl; cout << "3. Edit a Book's Record" << endl; cout << "4. Delete a Book" << endl; cout << "5. Return to Main Menu" << endl; cout << endl; cout << "Enter your choice: "; cin >> selection; switch (selection) { case 1: lookUpBook(); break; case 2: addBook(); break; case 3: editBook(); break; case 4: deleteBook(); break; default: cout << "Please try again and enter a number in the range 1-4." << endl; } } void lookUpBook() { cout << "You selected Look Up Book." << endl; } void addBook() { cout << "You selected Add Book" << endl; } void editBook() { cout << "You selcted Edit Book" << endl; } void deleteBook() { cout << "You selected Delete Book" << endl; }
Java
UTF-8
1,836
1.820313
2
[]
no_license
package spring.testing.server.configuration; import java.util.ArrayList; import java.util.List; import javax.sql.DataSource; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.jdbc.core.JdbcTemplate; import spring.testing.server.bills.LineItem; import spring.testing.server.compliance.logging.Registrar; import spring.testing.server.compliance.logging.TrafficRegistrar; import spring.testing.server.exchange.CheeseExchange; import spring.testing.server.exchange.Exchange; import spring.testing.server.exchange.RateParser; import spring.testing.server.gateway.ExchangeStatus; import spring.testing.server.persistence.jdbc.RateRepository; import spring.testing.server.rules.CalculationRule; import spring.testing.server.rules.CompositeLineItemRule; @Configuration public class AppConfiguration { @Bean public RateRepository rateRepository() { return new RateRepository(); } @Bean public CompositeLineItemRule compositeLineItemRule() { List<CalculationRule> rules = new ArrayList<>(); CalculationRule factorRule = new CalculationRule() { public float getMultiplier(LineItem t) { return 1.1f; } }; rules.add(factorRule); return new CompositeLineItemRule(rules); }; @Bean public RateParser rateParser() { return new RateParser(); } @Bean public Exchange exchange() { return new CheeseExchange(rateRepository()); } @Bean public ExchangeStatus statusMonitor() { return new ExchangeStatus(); } @Bean public Registrar trafficLogger( ) { return new TrafficRegistrar(); } }
TypeScript
UTF-8
841
2.5625
3
[]
no_license
import React from 'react' import { Elements, HTMLSerializer } from 'prismic-reactjs' import { HTMLSerializerElementMap } from './types' function serializeElements(map: HTMLSerializerElementMap): HTMLSerializer<React.ReactNode> { return function (type, element, content, children, key): React.ReactNode { const node = map[type as Elements] if (node) { const [component, props] = node let propagator = props || {} if (typeof props === 'function') { propagator = props(element) } const propsWithKey = { ...propagator, key } // <img /> elements don't have children if (type === Elements.image) { return React.createElement(component, propsWithKey) } return React.createElement(component, propsWithKey, children) } } } export default serializeElements
C++
UTF-8
576
3.015625
3
[]
no_license
#include "../IOLib.hpp" class Solution { public: Solution(vector<int> nums) { numbers = nums; } int pick(int target) { int res = 0, count = 0; for(int i = 0; i < numbers.size(); i++){ if(numbers[i] == target){ count++; if(rand() % count == 0) res = i; } } return res; } private: vector<int> numbers; }; /** * Your Solution object will be instantiated and called as such: * Solution obj = new Solution(nums); * int param_1 = obj.pick(target); */
Java
UTF-8
293
1.90625
2
[]
no_license
package com.omarmohamed.myvideogallery.ui.player; /** * Created by omarmohamed on 26/08/2016. */ public interface PlayerListener { void onBufferingStart(); void onBufferingComplete(); void onSetDuration(long durationMs); void onUpdateProgress(float percentComplete); }
Markdown
UTF-8
12,626
2.53125
3
[]
no_license
--- title: 'Migrating a PostgreSQL DB to a new machine without doing a dump &#038; restore' author: Evan Hoffman excerpt: rsync over NFS can be so fast. layout: post permalink: /2011/07/11/migrating-a-postgresql-db-to-a-new-machine-without-doing-a-dump-restore/ dsq_thread_id: - 2949520998 categories: - Uncategorized tags: - compellent - database - dba - devops - dl360 - dump - howto - hp - linkedin - linux - migration - msa - msa70 - nfs - postgres - postgresql - restore - rsync - work --- Long ago, before I stepped into my role as de facto DBA in my current job, dump &#038; restore of our Postgres database (dumping the entire DB to a text file, formatting the data disk, and restoring the data) was a pretty regular event. This was needed because we didn&#8217;t regularly vacuum the DB, which in turn was due to vacuums taking forever (which in the end ended up being due to crappy underlying hardware). We started doing monthly global vacuums (they took so long that monthly was about all we could handle) and we discovered we no longer needed to do dump &#038; restores. When we finally upgraded to Postgres 8.2, which introduced autovacuum, things got even better, since we didn&#8217;t have to manage vacuuming via cron jobs. <!--more--> In the years between then and now our Postgres DB has ballooned to such a size that a D&#038;R isn&#8217;t something we could feasibly do in a scheduled maintenance window. The last time I did one was when we bade farewell to the decrepit database in September, 2007. At that point our database consumed 730 GB on disk. Looking through my email archives, we began the dump at 6:30 PM on a Friday night and it completed at 3:48 AM Saturday. The restore started around 9 AM and ran until around 1 PM (I assume it went so much faster than the dump due to the new DB being significantly better hardware-wise). Building indices took until 9:27 PM Saturday. We then ran a global &#8220;ANALYZE&#8221; to generate DB stats; the analyze ran from 10 PM until 1 AM Sunday. We then had most of Sunday to process the backlog of data that accumulated since Friday afternoon when we took the database offline. So, with a 730 GB DB, the entire procedure took 9 hours (dump) + 4 hours (restore) + 8 hours (index rebuild) + 3 hours (analyze), so about 24 hours. However, as I said, in the years since then our database has grown as we house more and more data, currently at about 1220 GB. It might have been possible to do the migration via dump &#038; restore in the scheduled window, but I wasn&#8217;t looking forward to it. Instead, I decided to try a different option: copying the data files directly from the old server to the new one. If this worked it would eliminate almost all the overhead and the move would be complete in however long it took to copy the data from one host to the other. ### Reasons We had a couple reasons for doing this upgrade. Performance wasn&#8217;t really one of them though; we were pretty confident that the performance of the DB was as good as we were likely to get with platter disks, and our SAN doesn&#8217;t currently have SSDs. The old DB has dual Xeon 5160 2-core CPUs @3.0ghz, 32 GB memory, and a RAID 5 OS volume. The database resided on an <a href="http://h10010.www1.hp.com/wwpc/us/en/sm/WF05a/12169-304616-3930445-3930445-3930445-3355734.html" onclick="_gaq.push(['_trackEvent', 'outbound-article', 'http://h10010.www1.hp.com/wwpc/us/en/sm/WF05a/12169-304616-3930445-3930445-3930445-3355734.html', 'HP MSA70']);" >HP MSA70</a>, with 24x 10krpm 146 GB SAS drives (+1 hot spare) in RAID 10 for a 1.6 TB logical volume. At the time I debated RAID 6 vs RAID 10 but in the end I opted for the performance of RAID 10 vs the capacity of RAID 6 and it worked out well. But one of the reasons we decided to upgrade was that the drives in the DB were starting to die and the warranty had expired on them, and each disk cost about $300 to replace. That was a pretty big liability and I expected the disks to begin dying more frequently. Another reason for upgrading was the benefits of having the data on the SAN, especially snapshotting. We&#8217;d been doing daily backups for a while but doing a dump of the DB while it&#8217;s in use makes it take forever, causing degraded performance while it&#8217;s running. Snapshot isn&#8217;t a perfect solution, but at least it&#8217;s an option. Another reason for wanting to move the DB to the SAN was for DR purposes; if we setup SAN-SAN replication to another site, with the DB on the SAN, we get that backed up for free. And probably the biggest reason, we were up to 1.25 TB used out of 1.6, over 80% full. We&#8217;d probably be good for another few months, but for me 80% is pretty full. ### Prerequisites In order for this to work, the version of Postgres on both machines has to be of the same minor version. In my case, the source DB (server A) was running 8.2.5 (the newest at the time the box was built), so I built 8.2.18 (<a href="http://yum.pgrpms.org/srpms/8.2/redhat/rhel-5Client-i386/postgresql-8.2.18-1PGDG.rhel5.src.rpm" onclick="_gaq.push(['_trackEvent', 'outbound-article', 'http://yum.pgrpms.org/srpms/8.2/redhat/rhel-5Client-i386/postgresql-8.2.18-1PGDG.rhel5.src.rpm', 'source RPM']);" >source RPM</a>) on the target (server B). Server B is pretty beefy: <a href="http://h10010.www1.hp.com/wwpc/us/en/sm/WF05a/15351-15351-3328412-241644-241475-4091408.html" onclick="_gaq.push(['_trackEvent', 'outbound-article', 'http://h10010.www1.hp.com/wwpc/us/en/sm/WF05a/15351-15351-3328412-241644-241475-4091408.html', 'HP DL360 G7']);" >HP DL360 G7</a> with dual <a href="http://ark.intel.com/Product.aspx?id=47921" onclick="_gaq.push(['_trackEvent', 'outbound-article', 'http://ark.intel.com/Product.aspx?id=47921', 'Xeon X5660 6-core CPUs']);" >Xeon X5660 6-core CPUs</a> @2.8 GHz, 96 GB PC3-10600 ECC mem, QLogic QLE-4062 iSCSI HBA connected to a 4TB volume on our Compellent SAN (tier 1, RAID 10 across 32x 15krpm FC disks). Both machines of course need to be of the same architecture, in my case x86_64. It might work across Intel/AMD, but I&#8217;m not sure about that; fortunately I didn&#8217;t have to worry about that. ### Moving the data When we did dump &#038; restores, we dumped directly to a commonly-mounted NAS, which worked well, since we wouldn&#8217;t start the restore until the dump was complete, and we didn&#8217;t want to consume disk on the target with a gigantic dump file (in addition to spinning the disks with reading the dumpfile while attempting to write to them; the contention causes everything to go much slower). There wasn&#8217;t really any need to use a NAS as an intermediary in this case though, it would just double the amount of time needed to get the data from A to B. I created an NFS export on B: <div class="wp_syntax"> <table> <tr> <td class="line_numbers"> <pre>1 </pre> </td> <td class="code"> <pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">/</span>data<span style="color: #000000; font-weight: bold;">/</span>pgsql 10.0.0.35<span style="color: #7a0874; font-weight: bold;">&#40;</span>rw,no_root_squash<span style="color: #7a0874; font-weight: bold;">&#41;</span></pre> </td> </tr> </table> </div> And mounted it on A with these options in /etc/fstab: <div class="wp_syntax"> <table> <tr> <td class="line_numbers"> <pre>1 </pre> </td> <td class="code"> <pre class="bash" style="font-family:monospace;">10.0.0.36:<span style="color: #000000; font-weight: bold;">/</span>data<span style="color: #000000; font-weight: bold;">/</span>pgsql <span style="color: #000000; font-weight: bold;">/</span>mnt<span style="color: #000000; font-weight: bold;">/</span>gannon<span style="color: #000000; font-weight: bold;">/</span>nfs nfs rw,<span style="color: #007800;">rsize</span>=<span style="color: #000000;">32768</span>,<span style="color: #007800;">wsize</span>=<span style="color: #000000;">32768</span>,<span style="color: #007800;">nfsvers</span>=<span style="color: #000000;">3</span>,noatime,udp <span style="color: #000000;"></span> <span style="color: #000000;"></span></pre> </td> </tr> </table> </div> I tried TCP vs UDP mounts and found UDP was faster. I then copied the data over with my favorite Unix tool, rsync: <div class="wp_syntax"> <table> <tr> <td class="line_numbers"> <pre>1 </pre> </td> <td class="code"> <pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">time</span> rsync <span style="color: #660033;">-atp</span> <span style="color: #660033;">--delete</span> <span style="color: #660033;">--progress</span> <span style="color: #000000; font-weight: bold;">/</span>var<span style="color: #000000; font-weight: bold;">/</span>lib<span style="color: #000000; font-weight: bold;">/</span>pgsql<span style="color: #000000; font-weight: bold;">/</span>data <span style="color: #000000; font-weight: bold;">/</span>mnt<span style="color: #000000; font-weight: bold;">/</span>gannon<span style="color: #000000; font-weight: bold;">/</span>nfs<span style="color: #000000; font-weight: bold;">/</span> <span style="color: #000000; font-weight: bold;">&gt;</span> <span style="color: #000000; font-weight: bold;">/</span>home<span style="color: #000000; font-weight: bold;">/</span>evan<span style="color: #000000; font-weight: bold;">/</span>rsync.log</pre> </td> </tr> </table> </div> ### Dry run In January I did a dry run of the procedure. I had tried copying data over without stopping postgres on A, so as not to cause a service interruption, but it didn&#8217;t work; data was changing too rapidly. By the time the rsync completed, the files it had copied over earliest had already been modified again. I ended up scheduling some downtime for a weekend and did the copy. With the above NFS settings I was able to transfer data at around 50 MB/s over our gigabit switches, the whole thing took 3-4 hours. When it came up, everything seemed to be fine. I was pretty happy, because 3-4 hours is a whole lot better than 24+. ### Day of Reckoning I finally did the real migration this past weekend. I started it at 8 PM and (after an rsync snafu) completed it around 4 AM. The snafu was caused by my use of the &#8220;`--delay-updates`&#8221; flag, which I later learned copies modified files to a `/.~tmp~/` directory, and when all of them are copied, moves them into place in an attempt to make it a more &#8220;atomic&#8221; operation. I didn&#8217;t realize this was what was happening, and I got a little freaked out when I saw the disk usage for the target growing 100 GB larger than the source. I cancelled the rsync and ran it again, stupidly dropping the &#8211;delay-updates flag, which with the &#8211;delete flag caused it to delete all the stuff in .~tmp~ that it had already copied over. It deleted like 300 GB of stuff before I freaked out and cancelled it again. I cursed myself a few times, then manually moved the contents of .~tmp~ up to the parent to salvage what had already been transferred, and ran the rsync once again to move the remaining data. So it probably would have been done much sooner had I not cancelled it and then deleted a bunch of my progress. You may notice that the rsync flags above don&#8217;t include `-z`. With huge binary files being transferred over a fast LAN I don&#8217;t think there&#8217;s much reason to use -z, in fact when I added -z the throughput plummeted. After copying the data, I moved the virtual IP of the DB to the new machine, moved the cron jobs over, started postgres on B and everything worked. I finished all of my cleanup around 6 AM Saturday, though like I said, I would have been done much sooner had I not deleted a bunch of my progress. Even still, this is a lot better than the dump &#038; restore scenario, and has the added benefit of being reversible. I&#8217;m planning to upgrade postgres on A to 8.2.18 and leave it as a standby server; if a problem arises with B, the data can be moved back relatively quickly. ### Conclusion Well, I don&#8217;t have any great insight to put here, but so far this has worked out. My next DB project is upgrading from 8.2 to either 8.4 or the 9.x series, but that&#8217;s going to require a lot more planning since client drivers will likely need to be updated, and I&#8217;m not sure if queries might need to be altered. The end (I hope).
C++
UTF-8
6,278
3.203125
3
[]
no_license
//Dan Siegel //Project 4 //Implementation File for Catalog Class #include <iostream> #include <fstream> #include <cstring> #include "catalog.h" #include "book.h" using namespace std; Catalog::Catalog(){ //constructor numberOfBooks = 0; ifstream libraryBooks("library.txt"); if(libraryBooks){ //if file opens correctly, read in contents. libraryBooks >> numberOfBooks; booklist = new Book[numberOfBooks]; char *tempTitle = new char[250]; char *tempAuthor = new char[250]; for (int i = 0; i < numberOfBooks; i++){ libraryBooks >> tempID; libraryBooks.clear(); libraryBooks.ignore(100, '\n'); libraryBooks.getline(tempTitle, 250, '\n'); libraryBooks.getline(tempAuthor, 250, '\n'); libraryBooks.clear(); libraryBooks >> tempCopies >> tempCheckOuts >> tempHolds; (booklist+i)->assignBook(tempID, tempTitle, tempAuthor, tempCopies, tempCheckOuts, tempHolds); } delete tempTitle; delete tempAuthor; } else { cout << "No library.txt" << endl; } libraryBooks.close(); } Catalog::~Catalog(){ delete [] booklist; } const void Catalog::printAllBooks(){ cout << "%%%%%% Book Catalog %%%%%%" << endl; for (int i = 0; i < numberOfBooks; i++){ (booklist+i)->printBook(); } } void Catalog::writeFile(){ ofstream newLibrary("library.txt"); newLibrary << numberOfBooks << '\n'; for (int i=0; i < numberOfBooks; i++){ char *tmpt = new char[250]; (booklist+i)->returnTitle(tmpt); char *tmpa = new char[250]; (booklist+i)->returnAuthor(tmpa); newLibrary << (booklist+i)->returnID() << '\n' << tmpt << '\n' << tmpa << '\n' << (booklist+i)->returnCopies() << '\n' << (booklist+i)->returnCheckOuts() << '\n' << (booklist+i)->returnHolds() << '\n'; delete tmpt; delete tmpa; } cout << "*** Catalog Written Out ***" << endl; newLibrary.close(); } const void Catalog::searchByAuthor(){ cin.clear(); cin.ignore(); found = false; char *tempAuthor = new char[250]; cout << "Name of Author" << endl; cin.getline(tempAuthor, 250, '\n'); for (int i = 0; i < numberOfBooks; i++){ char *temp = new char[250]; (booklist+i)->returnAuthor(temp); if (strcmp(tempAuthor, temp) == 0){ (booklist+i)->printBook(); found = true; } delete temp, tempAuthor; } if (found == false){ cout << "Author Not Found" << endl; } } const void Catalog::searchByTitle(){ cin.clear(); cin.ignore(); bool found = false; char *tempTitle = new char[250]; cout << "Name of Book" << endl; cin.getline(tempTitle, 250, '\n'); for (int i = 0; i < numberOfBooks; i++){ char *temp = new char[250]; (booklist+i)->returnTitle(temp); if (strcmp(tempTitle, temp) == 0){ (booklist+i)->printBook(); found = true; break; } delete temp, tempTitle; } if (found == false){ cout << "Title Not Found" << endl; } } void Catalog::updateBook(){ cout << "Enter id of Book or -1 to display all books: " << endl; int *actionToBook = new int[3]; int *numberFound = new int[1]; found = false; cin >> actionToBook[0]; if (actionToBook[0] == -1){ printAllBooks(); cout << "Enter id of Book" << endl; cin >> actionToBook[0]; } if (actionToBook[0] > 0) { for (int i = 0; i < numberOfBooks; i++){ if (actionToBook[0] == (booklist+i)->returnID()){ found = true; numberFound[0] = i; break; } } } if (found == true){ updateFoundBook(numberFound[0]); } else { cout << "Book Not Found" << endl; } delete actionToBook; delete numberFound; } void Catalog::checkOutBook(int bookToCheckOut, int action){ if (action == 1 || action == 0){ (booklist+bookToCheckOut)->changeCheckouts(action); cout << "Book check Out action done" << endl; } else if (action == 2){ (booklist+bookToCheckOut)->changeCheckouts(0); } } void Catalog::holdBook(int bookToHold, int action){ if (action == 1 || action == 0){ (booklist+bookToHold)->changeHolds(action); cout << "Hold Action Done" << endl; } } void Catalog::updateFoundBook(int bookToUpdate){ cout << "What would you like to do?\n 1-Checkout Book\n 2-Return Book\n 3-Hold Book\n 4-Remove Hold" << endl; int actionToBook; cin >> actionToBook; switch (actionToBook) { case 1: if ((booklist+bookToUpdate)->returnCopies() > (booklist+bookToUpdate)->returnCheckOuts()){ checkOutBook(bookToUpdate, 1); } else { cout << "All copies checked out, do you want to place on hold?" << endl; cout << "Enter 1 to add a new hold, enter 2 to skip" << endl; cin >> actionToBook; holdBook(bookToUpdate, actionToBook); } break; case 2: if ((booklist+bookToUpdate)->returnCheckOuts() >= 1){ checkOutBook(bookToUpdate, 0); } else { cout << "Double check that you still have the book checked out" << endl; } break; case 3: if ((booklist+bookToUpdate)->returnCopies() > (booklist+bookToUpdate)->returnCheckOuts() && (booklist+bookToUpdate)->returnHolds() >= 5){ cout << "Copies available Do you Want to Checkout Instead? 1 to checkout any other number to hold" << endl; cin >> actionToBook; if (actionToBook == 1){ checkOutBook(bookToUpdate, 1); } else { holdBook(bookToUpdate, 1); } } else if ((booklist+bookToUpdate)->returnHolds() >= 5){ cout << "Maximum holds reached, check back in soon" << endl; } else { holdBook(bookToUpdate, 1); } break; case 4: if ((booklist+bookToUpdate)->returnHolds() >= 1){ holdBook(bookToUpdate, 0); } else { cout << "No holds to remove" << endl; } break; default: cout << "Invalid selection" << endl; cin.clear(); cin.ignore(100, '\n'); break; } } void Catalog::activity(int uActivity){ switch(uActivity){ case 1: printAllBooks(); break; case 2: searchByTitle(); break; case 3: searchByAuthor(); break; case 4: updateBook(); break; case 5: writeFile(); cout << "Deleting Booklist, Goodbye" << endl; break; default: cin.clear(); cin.ignore(); cout << "invalid selection" << endl; break; } } void Catalog::menu(){ cout << "\n*********" << "Main Menu" << "*********" << endl; cout << "1 - Print Catalog\n" << "2 - Search by Title\n" << "3 - Search By Author\n" << "4 - Do Action\n" << "5 - Quit\n " << endl; }
PHP
UTF-8
872
2.875
3
[]
no_license
<?php namespace Mrchimp\Chimpcom\Commands; use Chimpcom; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * Candyman! * @action candyman */ class Candyman extends Command { /** * Configure the command * * @return void */ protected function configure() { $this->setName('candyman'); $this->setDescription('Test command for action system.'); $this->setHelp('Type "candyman" once, then optionally type it again.'); } /** * Run the command * * @param InputInterface $input * @param OutputInterface $output * @return int */ protected function execute(InputInterface $input, OutputInterface $output) { $output->setAction('candyman'); $output->write('candyman'); return 0; } }
Java
UTF-8
2,936
1.914063
2
[ "Apache-2.0" ]
permissive
package dev.gradleplugins.internal.plugins; import dev.gradleplugins.GradlePluginDevelopmentCompatibilityExtension; import dev.gradleplugins.GradlePluginDevelopmentTestSuite; import dev.gradleplugins.internal.GradlePluginDevelopmentDependencyExtensionInternal; import dev.gradleplugins.internal.GradlePluginDevelopmentTestSuiteInternal; import lombok.val; import org.gradle.api.Plugin; import org.gradle.api.Project; import org.gradle.api.plugins.ExtensionAware; import org.gradle.api.tasks.SourceSet; import org.gradle.api.tasks.SourceSetContainer; import org.gradle.plugin.devel.GradlePluginDevelopmentExtension; import java.util.HashSet; public abstract class GradlePluginDevelopmentUnitTestingPlugin implements Plugin<Project> { private static final String TEST_NAME = "test"; @Override public void apply(Project project) { project.getPluginManager().apply(GradlePluginDevelopmentTestingBasePlugin.class); project.getPluginManager().withPlugin("dev.gradleplugins.java-gradle-plugin", appliedPlugin -> createUnitTestSuite(project)); project.getPluginManager().withPlugin("dev.gradleplugins.groovy-gradle-plugin", appliedPlugin -> createUnitTestSuite(project)); } private void createUnitTestSuite(Project project) { val sourceSets = project.getExtensions().getByType(SourceSetContainer.class); val sourceSet = sourceSets.maybeCreate(TEST_NAME); val testSuite = project.getObjects().newInstance(GradlePluginDevelopmentTestSuiteInternal.class, TEST_NAME, sourceSet); testSuite.getTestedSourceSet().convention(project.provider(() -> sourceSets.getByName("main"))); testSuite.getTestedGradlePlugin().set((GradlePluginDevelopmentCompatibilityExtension) ((ExtensionAware)project.getExtensions().getByType(GradlePluginDevelopmentExtension.class)).getExtensions().getByName("compatibility")); testSuite.getTestedGradlePlugin().disallowChanges(); // Configure test for GradlePluginDevelopmentExtension (ensure it is not included) val gradlePlugin = project.getExtensions().getByType(GradlePluginDevelopmentExtension.class); val testSourceSets = new HashSet<SourceSet>(); testSourceSets.addAll(gradlePlugin.getTestSourceSets()); testSourceSets.remove(sourceSet); gradlePlugin.testSourceSets(testSourceSets.toArray(new SourceSet[0])); // Automatically add Gradle API as a dependency. We assume unit tests are accomplish via ProjectBuilder val dependencies = GradlePluginDevelopmentDependencyExtensionInternal.of(project.getDependencies()); dependencies.add(testSuite.getSourceSet().getImplementationConfigurationName(), testSuite.getTestedGradlePlugin().get().getMinimumGradleVersion().map(dependencies::gradleApi)); project.getComponents().add(testSuite); project.getExtensions().add(GradlePluginDevelopmentTestSuite.class, TEST_NAME, testSuite); } }
Java
UTF-8
1,306
1.84375
2
[]
no_license
/** * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package com.liferay.faces.alloy.util; /** * @author Neil Griffin */ public class StringConstants { public static final String ATTRIBUTE_CLASS = "class"; public static final String ATTRIBUTE_ID = "id"; public static final String ATTRIBUTE_CSS_CLASS = "cssClass"; public static final String ATTRIBUTE_STYLE_CLASS = "styleClass"; public static final String BOOLEAN_TRUE = "true"; public static final String BOOLEAN_FALSE = "false"; public static final String CHAR_BLANK = ""; public static final String CHAR_COMMA = ","; public static final String CHAR_SPACE = " "; public static final String ELEMENT_DIV = "div"; public static final String ELEMENT_UL = "ul"; public static final String ELEMENT_LI = "li"; }
Java
UTF-8
225
2.203125
2
[ "MIT" ]
permissive
package cz.litvaluk.fit.adp.game.state; import cz.litvaluk.fit.adp.game.model.gameobjects.cannon.Cannon; public interface ShootingMode { String getName(); void shoot(Cannon cannon); ShootingMode nextMode(); }
C#
UTF-8
3,801
2.921875
3
[ "Apache-2.0" ]
permissive
using System.Collections.Generic; using UnityEngine; using UnityEditor; namespace KEditorExtensions { /// <summary> /// Handle GUI color changes like EditorGUILayout's Horizontal and Vertical scopes! /// </summary> public static class ColorScope { //internal stack of prior colors to fall back to private static Stack<System.Tuple<Color, Color, Color>> OldColorStack = new Stack<System.Tuple<Color, Color, Color>>(); /// <summary> /// Begin a new color region. /// </summary> /// <param name="color">GUI.color value for the region.</param> /// <param name="contentColor">GUI.contentColor value for the region.</param> /// <param name="backgroundColor">GUI.backgroundColor value for the region.</param> public static void Begin(Color color, Color contentColor, Color backgroundColor) { OldColorStack.Push(new System.Tuple<Color, Color, Color>(GUI.color, GUI.contentColor, GUI.backgroundColor)); SetGUIColor(color, contentColor, backgroundColor); } /// <summary> /// Begin a new color region. /// </summary> /// <param name="color">GUI.color value for the region.</param> public static void Begin(Color color) { Begin(color, GUI.contentColor, GUI.backgroundColor); } /// <summary> /// Begin a new color region. This overload adjusts only alpha values (between 0 and 1). /// </summary> /// <param name="colorAlpha">GUI.color alpha value for the region.</param> /// <param name="contentColor">GUI.contentColor alpha value for the region.</param> /// <param name="backgroundColor">GUI.backgroundColor alpha value for the region.</param> public static void Begin(float colorAlpha, float contentColorAlpha, float backgroundColorAlpha) { Begin( AdjustAlpha(GUI.color, colorAlpha), AdjustAlpha(GUI.contentColor, contentColorAlpha), AdjustAlpha(GUI.backgroundColor, backgroundColorAlpha) ); } /// <summary> /// Begin a new color region. This overload adjusts only the alpha value (between 0 and 1). /// </summary> /// <param name="colorAlpha">GUI.color alpha value for the region.</param> /// <param name="combineWithExistingAlpha">If true, new alpha value will be relative to the current alpha value.</param> public static void Begin(float colorAlpha, bool combineWithExistingAlpha = true) { float multiplier = combineWithExistingAlpha ? GUI.color.a : 1; Begin(colorAlpha * multiplier, GUI.contentColor.a, GUI.backgroundColor.a); } /// <summary> /// End the current color region. /// </summary> public static void End() { if (OldColorStack.Count == 0) { Debug.LogWarning("You are popping more color regions than you are pushing! Check that you are using Begin() and End() the same number of times."); return; } var oldColor = OldColorStack.Pop(); SetGUIColor(oldColor.Item1, oldColor.Item2, oldColor.Item3); } //actual method for setting the gui colors private static void SetGUIColor(Color color, Color contentColor, Color backgroundColor) { GUI.color = color; GUI.contentColor = contentColor; GUI.backgroundColor = backgroundColor; } //quick function to get a color with adjusted alpha value private static Color AdjustAlpha(Color color, float alpha) { return new Color(color.r, color.g, color.b, alpha); } } }
C#
UTF-8
4,342
2.625
3
[ "MIT" ]
permissive
namespace Chr.Avro.Representation { using System.Text.Json; using Chr.Avro.Abstract; /// <summary> /// Implements a <see cref="JsonSchemaWriter" /> case that matches <see cref="BytesSchema" />s /// or <see cref="FixedSchema" />s with <see cref="DecimalLogicalType" />. /// </summary> public class JsonDecimalSchemaWriterCase : DecimalSchemaWriterCase, IJsonSchemaWriterCase { /// <summary> /// Writes a <see cref="BytesSchema" /> or <see cref="FixedSchema" /> with a /// <see cref="DecimalLogicalType" />. /// </summary> /// <inheritdoc /> public virtual JsonSchemaWriterCaseResult Write(Schema schema, Utf8JsonWriter json, bool canonical, JsonSchemaWriterContext context) { if (schema.LogicalType is DecimalLogicalType decimalLogicalType) { if (schema is FixedSchema fixedSchema) { if (context.Names.TryGetValue(fixedSchema.FullName, out var existing)) { if (!schema.Equals(existing)) { throw new InvalidSchemaException($"A conflicting schema with the name {fixedSchema.FullName} has already been written."); } json.WriteStringValue(fixedSchema.FullName); } else { context.Names.Add(fixedSchema.FullName, fixedSchema); json.WriteStartObject(); json.WriteString(JsonAttributeToken.Name, fixedSchema.FullName); if (!canonical) { if (fixedSchema.Aliases.Count > 0) { json.WritePropertyName(JsonAttributeToken.Aliases); json.WriteStartArray(); foreach (var alias in fixedSchema.Aliases) { json.WriteStringValue(alias); } json.WriteEndArray(); } } json.WriteString(JsonAttributeToken.Type, JsonSchemaToken.Fixed); if (!canonical) { json.WriteString(JsonAttributeToken.LogicalType, JsonSchemaToken.Decimal); json.WriteNumber(JsonAttributeToken.Precision, decimalLogicalType.Precision); json.WriteNumber(JsonAttributeToken.Scale, decimalLogicalType.Scale); } json.WriteNumber(JsonAttributeToken.Size, fixedSchema.Size); json.WriteEndObject(); } } else if (schema is BytesSchema) { if (canonical) { json.WriteStringValue(JsonSchemaToken.Bytes); } else { json.WriteStartObject(); json.WriteString(JsonAttributeToken.Type, JsonSchemaToken.Bytes); json.WriteString(JsonAttributeToken.LogicalType, JsonSchemaToken.Decimal); json.WriteNumber(JsonAttributeToken.Precision, decimalLogicalType.Precision); json.WriteNumber(JsonAttributeToken.Scale, decimalLogicalType.Scale); json.WriteEndObject(); } } else { throw new UnsupportedSchemaException(schema, $"A {nameof(DecimalLogicalType)} can only be written for a {nameof(BytesSchema)} or {nameof(FixedSchema)}."); } return new JsonSchemaWriterCaseResult(); } else { return JsonSchemaWriterCaseResult.FromException(new UnsupportedSchemaException(schema, $"{nameof(JsonDecimalSchemaWriterCase)} can only be applied to {nameof(BytesSchema)}s or {nameof(FloatSchema)}s with {nameof(DecimalLogicalType)}.")); } } } }
C++
UTF-8
22,793
2.921875
3
[]
no_license
#include "matrix4x4.h" #include <cstring> // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/ namespace fmormath { const Matrix4x4 Matrix4x4::ZERO( 0, 0, 0, 0 , 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0 ); const Matrix4x4 Matrix4x4::IDENTITY( 1.f, 0, 0, 0 , 0, 1.f, 0, 0 , 0, 0, 1.f, 0, 0, 0, 0, 1.f ); //static inline Real Minor( const Matrix4x4& matrix, uint r0, uint r1, uint r2, uint c0, uint c1, uint c2 ) //{ // Real result; // result = matrix[r0][c0]*matrix[r1][c1]*matrix[r2][c2] + matrix[r0][c1]*matrix[r1][c2]*matrix[r2][c0] + matrix[r0][c2]*matrix[r1][c0]*matrix[r2][c1]; // result -= matrix[r0][c0]*matrix[r1][c2]*matrix[r2][c1] + matrix[r0][c1]*matrix[r1][c0]*matrix[r2][c2] + matrix[r0][c2]*matrix[r1][c1]*matrix[r2][c0]; // return result; //} static inline Real Minor( const Matrix4x4& matrix, uint r0, uint r1, uint r2, uint c0, uint c1, uint c2 ) { Real result; result = matrix[r0][c0] * ( matrix[r1][c1]*matrix[r2][c2] - matrix[r2][c1]*matrix[r1][c2] ); result -= matrix[r0][c1] * ( matrix[r1][c0]*matrix[r2][c2] - matrix[r2][c0]*matrix[r1][c2] ); result += matrix[r0][c2] * ( matrix[r1][c0]*matrix[r2][c1] - matrix[r2][c0]*matrix[r1][c1] ); return result; } Matrix4x4::Matrix4x4(Real r00, Real r01, Real r02, Real r03, Real r10, Real r11, Real r12, Real r13, Real r20, Real r21, Real r22, Real r23, Real r30, Real r31, Real r32, Real r33 ) { m_Reals[0][0] = r00; m_Reals[0][1] = r01; m_Reals[0][2] = r02; m_Reals[0][3] = r03; m_Reals[1][0] = r10; m_Reals[1][1] = r11; m_Reals[1][2] = r12; m_Reals[1][3] = r13; m_Reals[2][0] = r20; m_Reals[2][1] = r21; m_Reals[2][2] = r22; m_Reals[2][3] = r23; m_Reals[3][0] = r30; m_Reals[3][1] = r31; m_Reals[3][2] = r32; m_Reals[3][3] = r33; } void Matrix4x4::set(Real r00, Real r01, Real r02, Real r03, Real r10, Real r11, Real r12, Real r13, Real r20, Real r21, Real r22, Real r23, Real r30, Real r31, Real r32, Real r33 ) { m_Reals[0][0] = r00; m_Reals[0][1] = r01; m_Reals[0][2] = r02; m_Reals[0][3] = r03; m_Reals[1][0] = r10; m_Reals[1][1] = r11; m_Reals[1][2] = r12; m_Reals[1][3] = r13; m_Reals[2][0] = r20; m_Reals[2][1] = r21; m_Reals[2][2] = r22; m_Reals[2][3] = r23; m_Reals[3][0] = r30; m_Reals[3][1] = r31; m_Reals[3][2] = r32; m_Reals[3][3] = r33; } bool Matrix4x4::operator ==( const Matrix4x4& other ) const { if( m_Reals[0][0] != other.m_Reals[0][0] ) return false; if( m_Reals[0][1] != other.m_Reals[0][1] ) return false; if( m_Reals[0][2] != other.m_Reals[0][2] ) return false; if( m_Reals[0][3] != other.m_Reals[0][3] ) return false; if( m_Reals[1][0] != other.m_Reals[1][0] ) return false; if( m_Reals[1][1] != other.m_Reals[1][1] ) return false; if( m_Reals[1][2] != other.m_Reals[1][2] ) return false; if( m_Reals[1][3] != other.m_Reals[1][3] ) return false; if( m_Reals[2][0] != other.m_Reals[2][0] ) return false; if( m_Reals[2][1] != other.m_Reals[2][1] ) return false; if( m_Reals[2][2] != other.m_Reals[2][2] ) return false; if( m_Reals[2][3] != other.m_Reals[2][3] ) return false; if( m_Reals[3][0] != other.m_Reals[3][0] ) return false; if( m_Reals[3][1] != other.m_Reals[3][1] ) return false; if( m_Reals[3][2] != other.m_Reals[3][2] ) return false; if( m_Reals[3][3] != other.m_Reals[3][3] ) return false; return true; } bool Matrix4x4::operator !=(const Matrix4x4 &other) const { if( m_Reals[0][0] != other.m_Reals[0][0] ) return true; if( m_Reals[0][1] != other.m_Reals[0][1] ) return true; if( m_Reals[0][2] != other.m_Reals[0][2] ) return true; if( m_Reals[0][3] != other.m_Reals[0][3] ) return true; if( m_Reals[1][0] != other.m_Reals[1][0] ) return true; if( m_Reals[1][1] != other.m_Reals[1][1] ) return true; if( m_Reals[1][2] != other.m_Reals[1][2] ) return true; if( m_Reals[1][3] != other.m_Reals[1][3] ) return true; if( m_Reals[2][0] != other.m_Reals[2][0] ) return true; if( m_Reals[2][1] != other.m_Reals[2][1] ) return true; if( m_Reals[2][2] != other.m_Reals[2][2] ) return true; if( m_Reals[2][3] != other.m_Reals[2][3] ) return true; if( m_Reals[3][0] != other.m_Reals[3][0] ) return true; if( m_Reals[3][1] != other.m_Reals[3][1] ) return true; if( m_Reals[3][2] != other.m_Reals[3][2] ) return true; if( m_Reals[3][3] != other.m_Reals[3][3] ) return true; return false; } void Matrix4x4::operator *=(Real f) { m_Reals[0][0] *= f; m_Reals[0][1] *= f; m_Reals[0][2] *= f; m_Reals[0][3] *= f; m_Reals[1][0] *= f; m_Reals[1][1] *= f; m_Reals[1][2] *= f; m_Reals[1][3] *= f; m_Reals[2][0] *= f; m_Reals[2][1] *= f; m_Reals[2][2] *= f; m_Reals[2][3] *= f; m_Reals[3][0] *= f; m_Reals[3][1] *= f; m_Reals[3][2] *= f; m_Reals[3][3] *= f; } void Matrix4x4::operator *=(const Matrix4x4 &other) { Matrix4x4 result; result.m_Reals[0][0] = m_Reals[0][0]*other.m_Reals[0][0] + m_Reals[0][1]*other.m_Reals[1][0] + m_Reals[0][2]*other.m_Reals[2][0] + m_Reals[0][3]*other.m_Reals[3][0]; result.m_Reals[1][0] = m_Reals[1][0]*other.m_Reals[0][0] + m_Reals[1][1]*other.m_Reals[1][0] + m_Reals[1][2]*other.m_Reals[2][0] + m_Reals[1][3]*other.m_Reals[3][0]; result.m_Reals[2][0] = m_Reals[2][0]*other.m_Reals[0][0] + m_Reals[2][1]*other.m_Reals[1][0] + m_Reals[2][2]*other.m_Reals[2][0] + m_Reals[2][3]*other.m_Reals[3][0]; result.m_Reals[3][0] = m_Reals[3][0]*other.m_Reals[0][0] + m_Reals[3][1]*other.m_Reals[1][0] + m_Reals[3][2]*other.m_Reals[2][0] + m_Reals[3][3]*other.m_Reals[3][0]; result.m_Reals[0][1] = m_Reals[0][0]*other.m_Reals[0][1] + m_Reals[0][1]*other.m_Reals[1][1] + m_Reals[0][2]*other.m_Reals[2][1] + m_Reals[0][3]*other.m_Reals[3][1]; result.m_Reals[1][1] = m_Reals[1][0]*other.m_Reals[0][1] + m_Reals[1][1]*other.m_Reals[1][1] + m_Reals[1][2]*other.m_Reals[2][1] + m_Reals[1][3]*other.m_Reals[3][1]; result.m_Reals[2][1] = m_Reals[2][0]*other.m_Reals[0][1] + m_Reals[2][1]*other.m_Reals[1][1] + m_Reals[2][2]*other.m_Reals[2][1] + m_Reals[2][3]*other.m_Reals[3][1]; result.m_Reals[3][1] = m_Reals[3][0]*other.m_Reals[0][1] + m_Reals[3][1]*other.m_Reals[1][1] + m_Reals[3][2]*other.m_Reals[2][1] + m_Reals[3][3]*other.m_Reals[3][1]; result.m_Reals[0][2] = m_Reals[0][0]*other.m_Reals[0][2] + m_Reals[0][1]*other.m_Reals[1][2] + m_Reals[0][2]*other.m_Reals[2][2] + m_Reals[0][3]*other.m_Reals[3][2]; result.m_Reals[1][2] = m_Reals[1][0]*other.m_Reals[0][2] + m_Reals[1][1]*other.m_Reals[1][2] + m_Reals[1][2]*other.m_Reals[2][2] + m_Reals[1][3]*other.m_Reals[3][2]; result.m_Reals[2][2] = m_Reals[2][0]*other.m_Reals[0][2] + m_Reals[2][1]*other.m_Reals[1][2] + m_Reals[2][2]*other.m_Reals[2][2] + m_Reals[2][3]*other.m_Reals[3][2]; result.m_Reals[3][2] = m_Reals[3][0]*other.m_Reals[0][2] + m_Reals[3][1]*other.m_Reals[1][2] + m_Reals[3][2]*other.m_Reals[2][2] + m_Reals[3][3]*other.m_Reals[3][2]; result.m_Reals[0][3] = m_Reals[0][0]*other.m_Reals[0][3] + m_Reals[0][1]*other.m_Reals[1][3] + m_Reals[0][2]*other.m_Reals[2][3] + m_Reals[0][3]*other.m_Reals[3][3]; result.m_Reals[1][3] = m_Reals[1][0]*other.m_Reals[0][3] + m_Reals[1][1]*other.m_Reals[1][3] + m_Reals[1][2]*other.m_Reals[2][3] + m_Reals[1][3]*other.m_Reals[3][3]; result.m_Reals[2][3] = m_Reals[2][0]*other.m_Reals[0][3] + m_Reals[2][1]*other.m_Reals[1][3] + m_Reals[2][2]*other.m_Reals[2][3] + m_Reals[2][3]*other.m_Reals[3][3]; result.m_Reals[3][3] = m_Reals[3][0]*other.m_Reals[0][3] + m_Reals[3][1]*other.m_Reals[1][3] + m_Reals[3][2]*other.m_Reals[2][3] + m_Reals[3][3]*other.m_Reals[3][3]; *this = result; } void Matrix4x4::operator +=( const Matrix4x4& other ) { m_Reals[0][0] += other.m_Reals[0][0]; m_Reals[0][1] += other.m_Reals[0][1]; m_Reals[0][2] += other.m_Reals[0][2]; m_Reals[0][3] += other.m_Reals[0][3]; m_Reals[1][0] += other.m_Reals[1][0]; m_Reals[1][1] += other.m_Reals[1][1]; m_Reals[1][2] += other.m_Reals[1][2]; m_Reals[1][3] += other.m_Reals[1][3]; m_Reals[2][0] += other.m_Reals[2][0]; m_Reals[2][1] += other.m_Reals[2][1]; m_Reals[2][2] += other.m_Reals[2][2]; m_Reals[2][3] += other.m_Reals[2][3]; m_Reals[3][0] += other.m_Reals[3][0]; m_Reals[3][1] += other.m_Reals[3][1]; m_Reals[3][2] += other.m_Reals[3][2]; m_Reals[3][3] += other.m_Reals[3][3]; } void Matrix4x4::operator -=( const Matrix4x4& other) { m_Reals[0][0] -= other.m_Reals[0][0]; m_Reals[0][1] -= other.m_Reals[0][1]; m_Reals[0][2] -= other.m_Reals[0][2]; m_Reals[0][3] -= other.m_Reals[0][3]; m_Reals[1][0] -= other.m_Reals[1][0]; m_Reals[1][1] -= other.m_Reals[1][1]; m_Reals[1][2] -= other.m_Reals[1][2]; m_Reals[1][3] -= other.m_Reals[1][3]; m_Reals[2][0] -= other.m_Reals[2][0]; m_Reals[2][1] -= other.m_Reals[2][1]; m_Reals[2][2] -= other.m_Reals[2][2]; m_Reals[2][3] -= other.m_Reals[2][3]; m_Reals[3][0] -= other.m_Reals[3][0]; m_Reals[3][1] -= other.m_Reals[3][1]; m_Reals[3][2] -= other.m_Reals[3][2]; m_Reals[3][3] -= other.m_Reals[3][3]; } Matrix4x4 Matrix4x4::operator *(Real r) const { Matrix4x4 result; result[0][0] = m_Reals[0][0] * r; result[0][1] = m_Reals[0][1] * r; result[0][2] = m_Reals[0][2] * r; result[0][3] = m_Reals[0][3] * r; result[1][0] = m_Reals[1][0] * r; result[1][1] = m_Reals[1][1] * r; result[2][2] = m_Reals[1][2] * r; result[3][3] = m_Reals[1][3] * r; result[2][0] = m_Reals[2][0] * r; result[2][1] = m_Reals[2][1] * r; result[2][2] = m_Reals[2][2] * r; result[1][3] = m_Reals[2][3] * r; result[3][0] = m_Reals[3][0] * r; result[3][1] = m_Reals[3][1] * r; result[3][2] = m_Reals[3][2] * r; result[3][3] = m_Reals[3][3] * r; return result; } Vector2f Matrix4x4::operator *(const Vector2f& v2 ) const { Vector2f result; result.x = m_Reals[0][0] * v2.x + m_Reals[0][1] * v2.y + m_Reals[0][3]; result.y = m_Reals[1][0] * v2.x + m_Reals[1][1] * v2.y + m_Reals[1][3]; return result; } Vector3f Matrix4x4::operator *(const Vector3f& v3 ) const { Vector3f result; result.x = m_Reals[0][0] * v3.x + m_Reals[0][1] * v3.y + m_Reals[0][2] * v3.z + m_Reals[0][3]; result.y = m_Reals[1][0] * v3.x + m_Reals[1][1] * v3.y + m_Reals[1][2] * v3.z + m_Reals[1][3]; result.z = m_Reals[2][0] * v3.x + m_Reals[2][1] * v3.y + m_Reals[2][2] * v3.z + m_Reals[2][3]; return result; } Vector4f Matrix4x4::operator *(const Vector4f& v4 ) const { Vector4f result; result.x = m_Reals[0][0] * v4.x + m_Reals[0][1] * v4.y + m_Reals[0][2] * v4.z + m_Reals[0][3] * v4.w; result.y = m_Reals[1][0] * v4.x + m_Reals[1][1] * v4.y + m_Reals[1][2] * v4.z + m_Reals[1][3] * v4.w; result.z = m_Reals[2][0] * v4.x + m_Reals[2][1] * v4.y + m_Reals[2][2] * v4.z + m_Reals[2][3] * v4.w; result.w = m_Reals[3][0] * v4.x + m_Reals[3][1] * v4.y + m_Reals[3][2] * v4.z + m_Reals[3][3] * v4.w; return result; } Matrix4x4 Matrix4x4::operator *( const Matrix4x4& other ) const { Matrix4x4 result; result.m_Reals[0][0] = m_Reals[0][0]*other.m_Reals[0][0] + m_Reals[0][1]*other.m_Reals[1][0] + m_Reals[0][2]*other.m_Reals[2][0] + m_Reals[0][3]*other.m_Reals[3][0]; result.m_Reals[1][0] = m_Reals[1][0]*other.m_Reals[0][0] + m_Reals[1][1]*other.m_Reals[1][0] + m_Reals[1][2]*other.m_Reals[2][0] + m_Reals[1][3]*other.m_Reals[3][0]; result.m_Reals[2][0] = m_Reals[2][0]*other.m_Reals[0][0] + m_Reals[2][1]*other.m_Reals[1][0] + m_Reals[2][2]*other.m_Reals[2][0] + m_Reals[2][3]*other.m_Reals[3][0]; result.m_Reals[3][0] = m_Reals[3][0]*other.m_Reals[0][0] + m_Reals[3][1]*other.m_Reals[1][0] + m_Reals[3][2]*other.m_Reals[2][0] + m_Reals[3][3]*other.m_Reals[3][0]; result.m_Reals[0][1] = m_Reals[0][0]*other.m_Reals[0][1] + m_Reals[0][1]*other.m_Reals[1][1] + m_Reals[0][2]*other.m_Reals[2][1] + m_Reals[0][3]*other.m_Reals[3][1]; result.m_Reals[1][1] = m_Reals[1][0]*other.m_Reals[0][1] + m_Reals[1][1]*other.m_Reals[1][1] + m_Reals[1][2]*other.m_Reals[2][1] + m_Reals[1][3]*other.m_Reals[3][1]; result.m_Reals[2][1] = m_Reals[2][0]*other.m_Reals[0][1] + m_Reals[2][1]*other.m_Reals[1][1] + m_Reals[2][2]*other.m_Reals[2][1] + m_Reals[2][3]*other.m_Reals[3][1]; result.m_Reals[3][1] = m_Reals[3][0]*other.m_Reals[0][1] + m_Reals[3][1]*other.m_Reals[1][1] + m_Reals[3][2]*other.m_Reals[2][1] + m_Reals[3][3]*other.m_Reals[3][1]; result.m_Reals[0][2] = m_Reals[0][0]*other.m_Reals[0][2] + m_Reals[0][1]*other.m_Reals[1][2] + m_Reals[0][2]*other.m_Reals[2][2] + m_Reals[0][3]*other.m_Reals[3][2]; result.m_Reals[1][2] = m_Reals[1][0]*other.m_Reals[0][2] + m_Reals[1][1]*other.m_Reals[1][2] + m_Reals[1][2]*other.m_Reals[2][2] + m_Reals[1][3]*other.m_Reals[3][2]; result.m_Reals[2][2] = m_Reals[2][0]*other.m_Reals[0][2] + m_Reals[2][1]*other.m_Reals[1][2] + m_Reals[2][2]*other.m_Reals[2][2] + m_Reals[2][3]*other.m_Reals[3][2]; result.m_Reals[3][2] = m_Reals[3][0]*other.m_Reals[0][2] + m_Reals[3][1]*other.m_Reals[1][2] + m_Reals[3][2]*other.m_Reals[2][2] + m_Reals[3][3]*other.m_Reals[3][2]; result.m_Reals[0][3] = m_Reals[0][0]*other.m_Reals[0][3] + m_Reals[0][1]*other.m_Reals[1][3] + m_Reals[0][2]*other.m_Reals[2][3] + m_Reals[0][3]*other.m_Reals[3][3]; result.m_Reals[1][3] = m_Reals[1][0]*other.m_Reals[0][3] + m_Reals[1][1]*other.m_Reals[1][3] + m_Reals[1][2]*other.m_Reals[2][3] + m_Reals[1][3]*other.m_Reals[3][3]; result.m_Reals[2][3] = m_Reals[2][0]*other.m_Reals[0][3] + m_Reals[2][1]*other.m_Reals[1][3] + m_Reals[2][2]*other.m_Reals[2][3] + m_Reals[2][3]*other.m_Reals[3][3]; result.m_Reals[3][3] = m_Reals[3][0]*other.m_Reals[0][3] + m_Reals[3][1]*other.m_Reals[1][3] + m_Reals[3][2]*other.m_Reals[2][3] + m_Reals[3][3]*other.m_Reals[3][3]; return result; } Matrix4x4 Matrix4x4::operator +(const Matrix4x4& other ) const { Matrix4x4 result; result[0][0] = m_Reals[0][0] + other.m_Reals[0][0]; result[0][1] = m_Reals[0][1] + other.m_Reals[0][1]; result[0][2] = m_Reals[0][2] + other.m_Reals[0][2]; result[0][3] = m_Reals[0][3] + other.m_Reals[0][3]; result[1][0] = m_Reals[1][0] + other.m_Reals[1][0]; result[1][1] = m_Reals[1][1] + other.m_Reals[1][1]; result[2][2] = m_Reals[1][2] + other.m_Reals[1][2]; result[3][3] = m_Reals[1][3] + other.m_Reals[1][3]; result[2][0] = m_Reals[2][0] + other.m_Reals[2][0]; result[2][1] = m_Reals[2][1] + other.m_Reals[2][1]; result[2][2] = m_Reals[2][2] + other.m_Reals[2][2]; result[1][3] = m_Reals[2][3] + other.m_Reals[2][3]; result[3][0] = m_Reals[3][0] + other.m_Reals[3][0]; result[3][1] = m_Reals[3][1] + other.m_Reals[3][1]; result[3][2] = m_Reals[3][2] + other.m_Reals[3][2]; result[3][3] = m_Reals[3][3] + other.m_Reals[3][3]; return result; } Matrix4x4 Matrix4x4::operator -(const Matrix4x4& other ) const { Matrix4x4 result; result[0][0] = m_Reals[0][0] - other.m_Reals[0][0]; result[0][1] = m_Reals[0][1] - other.m_Reals[0][1]; result[0][2] = m_Reals[0][2] - other.m_Reals[0][2]; result[0][3] = m_Reals[0][3] - other.m_Reals[0][3]; result[1][0] = m_Reals[1][0] - other.m_Reals[1][0]; result[1][1] = m_Reals[1][1] - other.m_Reals[1][1]; result[2][2] = m_Reals[1][2] - other.m_Reals[1][2]; result[3][3] = m_Reals[1][3] - other.m_Reals[1][3]; result[2][0] = m_Reals[2][0] - other.m_Reals[2][0]; result[2][1] = m_Reals[2][1] - other.m_Reals[2][1]; result[2][2] = m_Reals[2][2] - other.m_Reals[2][2]; result[1][3] = m_Reals[2][3] - other.m_Reals[2][3]; result[3][0] = m_Reals[3][0] - other.m_Reals[3][0]; result[3][1] = m_Reals[3][1] - other.m_Reals[3][1]; result[3][2] = m_Reals[3][2] - other.m_Reals[3][2]; result[3][3] = m_Reals[3][3] - other.m_Reals[3][3]; return result; } void Matrix4x4::setTranslation( const Vector3f& v ) { m_Reals[0][3] = v.x; m_Reals[1][3] = v.y; m_Reals[2][3] = v.z; } void Matrix4x4::setScale( const Vector3f& v ) { m_Reals[0][0] = v.x; m_Reals[1][1] = v.y; m_Reals[2][2] = v.z; } Vector3f Matrix4x4::getTranslation() const { return Vector3f( m_Reals[0][3], m_Reals[1][3], m_Reals[2][3] ); } Vector3f Matrix4x4::getScale() const { Vector3f scale; scale.x = m_Reals[0][0]; scale.y = m_Reals[1][1]; scale.z = m_Reals[2][2]; return scale; } Real Matrix4x4::determinant() const { Real det = 0; det += m_Reals[0][0] * Minor( *this, 1,2,3, 1,2,3 ); det -= m_Reals[0][1] * Minor( *this, 1,2,3, 0,2,3 ); det += m_Reals[0][2] * Minor( *this, 1,2,3, 0,1,3 ); det -= m_Reals[0][3] * Minor( *this, 1,2,3, 0,1,2 ); return det; } Matrix4x4 Matrix4x4::inverse() const { Matrix4x4 result; // Calcul des facteurs result.m_Reals[0][0] = Minor( *this, 1,2,3, 1,2,3 ); result.m_Reals[0][1] = -Minor( *this, 1,2,3, 0,2,3 ); result.m_Reals[0][2] = Minor( *this, 1,2,3, 0,1,3 ); result.m_Reals[0][3] = -Minor( *this, 1,2,3, 0,1,2 ); result.m_Reals[1][0] = -Minor( *this, 0,2,3, 1,2,3 ); result.m_Reals[1][1] = Minor( *this, 0,2,3, 0,2,3 ); result.m_Reals[1][2] = -Minor( *this, 0,2,3, 0,1,3 ); result.m_Reals[1][3] = Minor( *this, 0,2,3, 0,1,2 ); result.m_Reals[2][0] = Minor( *this, 0,1,3, 1,2,3 ); result.m_Reals[2][1] = -Minor( *this, 0,1,3, 0,2,3 ); result.m_Reals[2][2] = Minor( *this, 0,1,3, 0,1,3 ); result.m_Reals[2][3] = -Minor( *this, 0,1,3, 0,1,2 ); result.m_Reals[3][0] = -Minor( *this, 0,1,2, 1,2,3 ); result.m_Reals[3][1] = Minor( *this, 0,1,2, 0,2,3 ); result.m_Reals[3][2] = -Minor( *this, 0,1,2, 0,1,3 ); result.m_Reals[3][3] = Minor( *this, 0,1,2, 0,1,2 ); // Calcul du déterminant Real det = determinant(); if( det == 0.f ) { return Matrix4x4::ZERO; } Real invDet = 1.f / det; // Multiplier 1/det result *= invDet; // Transpose result = result.tranpose(); return result; } Matrix4x4 Matrix4x4::tranpose() const { Matrix4x4 result; result.m_Reals[0][0] = m_Reals[0][0]; result.m_Reals[1][0] = m_Reals[0][1]; result.m_Reals[2][0] = m_Reals[0][2]; result.m_Reals[3][0] = m_Reals[0][3]; result.m_Reals[0][1] = m_Reals[1][0]; result.m_Reals[1][1] = m_Reals[1][1]; result.m_Reals[2][1] = m_Reals[1][2]; result.m_Reals[3][1] = m_Reals[1][3]; result.m_Reals[0][2] = m_Reals[2][0]; result.m_Reals[1][2] = m_Reals[2][1]; result.m_Reals[2][2] = m_Reals[2][2]; result.m_Reals[3][2] = m_Reals[2][3]; result.m_Reals[0][3] = m_Reals[3][0]; result.m_Reals[1][3] = m_Reals[3][1]; result.m_Reals[2][3] = m_Reals[3][2]; result.m_Reals[3][3] = m_Reals[3][3]; return result; } Matrix4x4 Matrix4x4::inverseTranspose() const { return inverse().tranpose(); } Matrix4x4& Matrix4x4::makeRotationMatrix( const Quaternion& q ) { m_Reals[0][0] = 1.f - 2.f*q.y*q.y -2.f*q.z*q.z; m_Reals[0][1] = 2.f* q.x*q.y - 2.f*q.z*q.w; m_Reals[0][2] = 2.f*q.x*q.z + 2.f*q.y*q.w; m_Reals[0][3] = 0; m_Reals[1][0] = 2.f*q.x*q.y + 2.f*q.z*q.w; m_Reals[1][1] = 1 - 2.f*q.x*q.x - 2.f*q.z*q.z; m_Reals[1][2] = 2.f*q.y*q.z - 2.f*q.x*q.w; m_Reals[1][3] = 0; m_Reals[2][0] = 2.f*q.x*q.z - 2.f*q.y*q.w; m_Reals[2][1] = 2.f*q.y*q.z + 2.f*q.x*q.w; m_Reals[2][2] = 1 - 2.f*q.x*q.x -2.f*q.y*q.y; m_Reals[2][3] = 0; m_Reals[3][0] = 0; m_Reals[3][1] = 0; m_Reals[3][2] = 0; m_Reals[3][3] = 1; return *this; } Matrix4x4& Matrix4x4::makeScaleMatrix( const Vector3f& scale ) { m_Reals[0][0] = scale.x; m_Reals[0][1] = 0; m_Reals[0][2] = 0; m_Reals[0][3] = 0; m_Reals[1][0] = 0; m_Reals[1][1] = scale.y; m_Reals[1][2] = 0; m_Reals[1][3] = 0; m_Reals[2][0] = 0; m_Reals[2][1] = 0; m_Reals[2][2] = scale.z; m_Reals[2][3] = 0; m_Reals[3][0] = 0; m_Reals[3][1] = 0; m_Reals[3][2] = 0; m_Reals[3][3] = 1; return *this; } Matrix4x4& Matrix4x4::makeTranslationMatrix(const Vector3f& translation ) { m_Reals[0][0] = 1; m_Reals[0][1] = 0; m_Reals[0][2] = 0; m_Reals[0][3] = translation.x; m_Reals[1][0] = 0; m_Reals[1][1] = 1; m_Reals[1][2] = 0; m_Reals[1][3] = translation.y; m_Reals[2][0] = 0; m_Reals[2][1] = 0; m_Reals[2][2] = 1; m_Reals[2][3] = translation.z; m_Reals[3][0] = 0; m_Reals[3][1] = 0; m_Reals[3][2] = 0; m_Reals[3][3] = 1; return *this; } Matrix4x4& Matrix4x4::makeProjOrthoMatrix( uint width, uint height, uint deep ) { Real rigth = Real(width) * Real(0.5); Real left = -rigth; Real top = Real(height) * Real(0.5); Real bottom = -top; Real far = deep + 1.f; Real near = 1.f; return makeProjOrthoMatrix( left, rigth, bottom, top, near, far ); } Matrix4x4& Matrix4x4::makeProjOrthoMatrix(Real left, Real right, Real bottom, Real top, Real near, Real far) { m_Reals[0][0] = 2.f / ( right - left); m_Reals[0][1] = 0; m_Reals[0][2] = 0; m_Reals[0][3] = -1.f * ( (right + left) / ( right-left) ); m_Reals[1][0] = 0; m_Reals[1][1] = 2.f / ( top - bottom ); m_Reals[1][2] = 0; m_Reals[1][3] = -1.f * ( (top + bottom) / (top - bottom) ); m_Reals[2][0] = 0; m_Reals[2][1] = 0; m_Reals[2][2] = -2.f / (far -near); m_Reals[2][3] = -1.f * (far+near) / (far-near); m_Reals[3][0] = 0; m_Reals[3][1] = 0; m_Reals[3][2] = 0; m_Reals[3][3] = 1; return *this; } Matrix4x4 &Matrix4x4::makeProj2DMatrix(Real width, Real height) { m_Reals[0][0] = 2.f / width; m_Reals[0][1] = 0; m_Reals[0][2] = 0; m_Reals[0][3] = -1; m_Reals[1][0] = 0; m_Reals[1][1] = -2.f / height; m_Reals[1][2] = 0; m_Reals[1][3] = 1; m_Reals[2][0] = 0; m_Reals[2][1] = 0; m_Reals[2][2] = -2.f / 100.f; m_Reals[2][3] = -1.f *(102.f) / (100.f); m_Reals[3][0] = 0; m_Reals[3][1] = 0; m_Reals[3][2] = 0; m_Reals[3][3] = 1; return *this; } void Matrix4x4::translate( const Vector3f& v ) { m_Reals[0][3] += v.x; m_Reals[1][3] += v.y; m_Reals[2][3] += v.z; } void Matrix4x4::rotate( const Quaternion& quaternion ) { Matrix4x4 R; R.makeRotationMatrix( quaternion ); *this = R * *this; } }
PHP
UTF-8
2,648
2.609375
3
[ "MIT" ]
permissive
<?php session_start(); include 'header.php'; include 'Classes.php'; ?> <body> <?php /** * User: OMAR BARA * Date: 01/01/2018 * Time: 12:54 PM */ include "functions.php"; if (!empty($_SESSION)) { if (isset($_GET['qty']) && !empty($_GET['qty']) && ($_GET['qty'] > 0) AND isset($_GET['aldd']) && !empty($_GET['aldd']) ) { $qty = 0; $qty = $_GET['qty']; $allData = $_GET['aldd']; ///error if ($qty < $allData[5]) { //create invoice $price = $allData[1]; //$color = $allData[0]; //chek if there is a Sale or not $sale = $allData[2]; $name = $allData[3]; $imagePath = $allData[4]; $amount = $allData[5]; if ($sale == 'sale') { $price = 0.3 * $price; } else $sale = 0; $id = $allData[6]; $filePath = $allData[7]; $allData[8] = $qty; $counter = $_SESSION["counter"]; echo '<br><p>You have: ' . ++$counter . " Items In your Cart</p><br>"; $_SESSION['invoice'][$_SESSION["counter"]] = $allData; $order = new order(); $order->invoice_display($_SESSION['invoice']); $_SESSION["counter"]++; echo '<div class="row"><div class="col-6"> <a href="address.php" class="btn btn-primary btn-block " role="button" ><h4>Approve invoice order</h4></a></div></div><br>' . '&nbsp;' . '<br>'; } else { echo '<div class="container"><div class="well text-center"><p style="color:red"><strong> There is : '. $allData[5] .' left in stock </strong></p></div></div><div class="row"> <div class="col-6">ss</div>'; } }else if (!empty($_SESSION['invoice'])) { invoice_display($_SESSION['invoice']); echo '<p style="text-align:center;font-size: 150%;">Approve invoice order <a href="address.php" style="border: 3px solid cadetblue;background: darkslategrey">Continue</a></p>'; } else echo '<div class="container"><div class="well text-center"><p style="color:red"><strong> Empty Cart</strong></p></div></div>'; // Error Warning session expired } else { echo '<div class="container"><div class="well text-center"><p style="color:red"><strong> "Warning" Your Session is over </strong></p></div></div><div class="row"> <div class="col-6">ss</div>'; echo '</div> <div class="alert alert-danger text-center"> <strong>Error!</strong> Your setion is expired plesse return to <a href="index.php">Here</a> . </div></div>'; } ?> </body> <?php include 'footer.php';?>
Java
UTF-8
283
1.695313
2
[]
no_license
package warehouseapp.warehouse.repository; import org.springframework.data.jpa.repository.JpaRepository; import warehouseapp.warehouse.entity.Currency; import warehouseapp.warehouse.entity.Supplier; public interface SupplierRepository extends JpaRepository<Supplier, Integer> { }
Java
UTF-8
2,221
2.359375
2
[]
no_license
package com.example.restapimongodb.services; import com.example.restapimongodb.models.UserModel; import com.example.restapimongodb.models.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Optional; @Service public class UserService implements UserDetailsService { @Autowired private UserRepository repository; @Autowired private BCryptPasswordEncoder encoder; public List<UserModel> getUser(){ return repository.findAll(); } public Optional<UserModel> getUserById(String id) throws Exception{ Optional<UserModel> user = repository.findById(id); if(!user.isPresent()){ throw new Exception("User " + id + " not found"); } return user; } public Optional<UserModel> getUserByUsername(String username) { Optional<UserModel> findName = repository.findByUsername(username); return findName; } public UserModel createUser(UserModel user){ String encodedPw = encoder.encode(user.getPasword()); user.setPasword(encodedPw); UserModel createUser = repository.insert(user); return createUser; } @Override public UserDetails loadUserByUsername(String user) throws UsernameNotFoundException { Optional<UserModel> findUser =repository.findByUsername(user); if(!findUser.isPresent()){ throw new UsernameNotFoundException("Username not found"); } String userName = findUser.get().getUsername(); String pw = findUser.get().getPasword(); return new User(userName, pw, new ArrayList<>()); } }
Java
UTF-8
2,738
2.21875
2
[]
no_license
package com.example.disasterrelief; import android.content.Intent; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity implements View.OnClickListener{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button one = findViewById(R.id.foodBtn); one.setOnClickListener(this); Button two = findViewById(R.id.clothBtn); two.setOnClickListener(this); Button three = findViewById(R.id.moneyBtn); three.setOnClickListener(this); Button four = findViewById(R.id.toiletriesBtn); four.setOnClickListener(this); Button five = findViewById(R.id.miscBtn); five.setOnClickListener(this); Button six = findViewById(R.id.organizeEventBtn); six.setOnClickListener(this); Button seven = findViewById((R.id.organizeEventBtn)); seven.setOnClickListener(this); } @Override public void onClick(View v){ switch (v.getId()) { case R.id.foodBtn: openActivityFood(); break; case R.id.clothBtn: openActivityClothing(); break; case R.id.moneyBtn: openActivityMoney(); break; case R.id.toiletriesBtn: openActivityToiletries(); break; case R.id.miscBtn: openActivityMisc(); break; case R.id.organizeEventBtn: openActivityNewEvent(); break; default: break; } } public void openActivityClothing() { Intent intent = new Intent(this, ActivityClothing.class); startActivity(intent); } public void openActivityFood() { Intent intent = new Intent(this, foodActivity.class); startActivity(intent); } public void openActivityMoney() { Intent intent = new Intent(this, ActivityMoney.class); startActivity(intent); } public void openActivityToiletries() { Intent intent = new Intent(this, ActivityToiletries.class); startActivity(intent); } public void openActivityMisc() { Intent intent = new Intent(this, ActivityMisc.class); startActivity(intent); } public void openActivityNewEvent() { Intent intent = new Intent (this, createEvent.class); startActivity(intent); } }
Python
UTF-8
1,037
2.734375
3
[]
no_license
import sys sys.stdin = open("11_input.txt") T = 10 for case in range(1, T+1): long, start = map(int, input().split()) from_to = list(map(int, input().split())) call_list = [] for i in range(len(from_to)//2): k = [from_to[i*2]] k.append(from_to[(i*2) + 1]) call_list.append(k) maps = [[ 0 for x in range(101)] for y in range(101)] for call in call_list: x = call[1] y = call[0] maps[y][x] = 1 visited = [0 for x in range(101)] queue = [] queue.append(start) visited[start] = 1 while queue: k = queue.pop(0) for call in range(1, 101): if maps[k][call] == 1: if visited[call] == 0: visited[call] = visited[k] + 1 queue.append(call) result = 0 for i in range(1, 101): if visited[i] == max(visited): mem = i if mem > result: result = mem print(result)
C++
UTF-8
2,694
3.390625
3
[]
no_license
class CTimeKeeper { public: CTimeKeeper(); void init(); void every_10_milliseconds_interrupt(); void every_100_milliseconds_interrupt(); void every_second_interrupt(); void callback_later(func_ptr function, word milliseconds); private: struct callback_info { byte ticks_left: 7; byte is_slow_ticks: 1; func_ptr function; } callbacks[TIME_KEEPER_CALLBACKS_SIZE]; void update_timeouts(bool is_slow_tick); }; CTimeKeeper::CTimeKeeper() { memset(callbacks, 0, sizeof(callbacks)); } void CTimeKeeper::every_10_milliseconds_interrupt() { update_timeouts(false); } /** * We generate events every second and every half second. * To aleviate the need for listeners to toggle state, * we color our events as EVEN and ODD. */ void CTimeKeeper::every_100_milliseconds_interrupt() { } void CTimeKeeper::every_second_interrupt() { update_timeouts(true); } void CTimeKeeper::update_timeouts(bool is_slow_tick) { for (byte i = 0; i < TIME_KEEPER_CALLBACKS_SIZE; i++) { // if zero, no need to diminish if (callbacks[i].ticks_left == 0) continue; // do we care about slow or fast ticks? if (callbacks[i].is_slow_ticks != (byte)is_slow_tick) continue; // diminish, see if done callbacks[i].ticks_left -= 1; if (callbacks[i].ticks_left == 0) { // it's important to do this last, // and not touch the ticks afterwards, // as the function may reset itself. (callbacks[i].function)(); } } } void CTimeKeeper::callback_later(func_ptr function, word milliseconds) { // find the first non used slot // or the slot that points to the same function. // it's important for a function to be able to prolong its timeout. byte slot = 255; for (byte i = 0; i < TIME_KEEPER_CALLBACKS_SIZE; i++) { if ((callbacks[i].function == function) || (callbacks[i].ticks_left == 0)) { slot = i; break; } } if (slot == 255) { // we don't have enough slots to add it! FATAL(5); } callbacks[slot].function = function; if (milliseconds > 1270) { // maximum for WORD is 65K -> 65 seconds. // this allows 1 to 127 seconds. callbacks[slot].ticks_left = (milliseconds / 1000); callbacks[slot].is_slow_ticks = 1; } else { if (milliseconds < 10) milliseconds = 10; // this allows 10 milliseconds to 1.27 seconds. callbacks[slot].ticks_left = (milliseconds / 10); callbacks[slot].is_slow_ticks = 0; } }
Shell
UTF-8
1,836
3.375
3
[]
no_license
#!/bin/bash source /home/oracle/.bash_profile function qywx_inform() { curl "${qywx_webhook}" \ -H 'Content-Type: application/json' \ -d " { \"msgtype\": \"text\", \"text\": { \"content\": \"${inform_content}\" } }" } if [ -z "$1" ]; then echo "oracle system用户密码不能为空!!!" exit 1 fi TIMESTAMP=`date +%Y%m%d` deletime=`date -d "7 days ago" +%Y%m%d` file=/boss/bak/oracle username=system system_pwd="$1" sid=orcl # 配置企业微信机器人地址 qywx_webhook='' expdp_dir=$file/$TIMESTAMP mkdir -p $expdp_dir chown -R oracle.oinstall ${file} # exp默认不会导出空表,使用expdp的好处是可以导出空表 cat << EOF > /boss/shell/oracle_backup_full_db.sql create or replace directory expdp_dir as '${expdp_dir}'; grant all on directory expdp_dir to public; exit; EOF cat << EOF > /boss/shell/oracle_language_temp.sql select userenv('language') from dual; exit; EOF su - oracle << EOF export NLS_LANG=`sqlplus ${username}/${system_pwd}@${sid} @/boss/shell/oracle_language_temp.sql|grep USERENV -A 2|tail -n 1` sqlplus ${username}/${system_pwd}@${sid} @/boss/shell/oracle_backup_full_db.sql expdp ${username}/${system_pwd}@${sid} DIRECTORY=expdp_dir DUMPFILE=exp_full_database_${TIMESTAMP}.dmp LOGFILE=exp_full_database_${TIMESTAMP}.log FULL=y cd $expdp_dir zip -r exp_full_database_${TIMESTAMP}.zip exp_full_database_${TIMESTAMP}.dmp rm -rf exp_full_database_${TIMESTAMP}.dmp rm -rf $file/$deletime EOF backup_file_size=`du -sh $expdp_dir|awk '{print $1}'` if [ ! -z "${qywx_webhook}" ]; then inform_content="`ifconfig|grep 'inet '|grep -v '127.0.0.1'|head -1|awk '{print $2}'` Oracle数据库备份完成! 大小$backup_file_size" qywx_inform fi # 远程备份数据库 # scp -r $file/$TIMESTAMP root@192.168.0.4:/data/backup/jydba
C++
GB18030
788
3.671875
4
[]
no_license
#include <iostream> using namespace std; class student { public: student(); void print() const; static int getCount(); private: static int count; int studentNo; }; ///********************************************************** int student::count=0; ///ⶨ徲̬Ա ///********************************************************** student::student() { count++; studentNo=count; } void student::print()const { cout<<"student="<<studentNo<<"count="<<count<<endl; } int student::getCount() { return count; } int main() { student st1; st1.print(); cout<<"***************"<<endl; student st2; st1.print(); st2.print(); cout<<"******************\n"; cout<<"student's number is "<<student::getCount()<<endl; }
Ruby
UTF-8
649
3.546875
4
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
class Author attr_accessor :name @@post_count = 0 def initialize(name) @name = name @posts = [] end def self.post_count=(song_count) @@post_count=song_count end def posts #getter method to return @posts @posts end def add_post(post_string) post_string.author = self #says that the author instance is called on by the instance method posts and setting it equal to an instance of Author with self end def add_post_by_title(post_title) new_post_title = Post.new(post_title) new_post_title.author = self end def self.post_count @@post_count end end # end of class Author
Java
UTF-8
1,401
1.734375
2
[]
no_license
package com.base.frame.generator.order.entity; import com.baomidou.mybatisplus.annotation.TableName; import java.time.LocalDateTime; import com.baomidou.mybatisplus.annotation.TableField; import java.io.Serializable; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; /** * <p> * * </p> * * @author G * @since 2020-03-25 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @TableName("Order_InterfaceLogInfo") @ApiModel(value="InterfaceLogInfo对象", description="") public class InterfaceLogInfo implements Serializable { private static final long serialVersionUID = 1L; private String url; private String params; private String data; @TableField("resultCode") private String resultCode; @TableField("errorInfo") private String errorInfo; private String name; @TableField("createTime") private LocalDateTime createTime; @TableField("traceId") private String traceId; @TableField("useMillisecond") private Long useMillisecond; private String header; @TableField("orderID") private Long orderID; @TableField("orderDetailID") private Long orderDetailID; }
Markdown
UTF-8
1,031
3.78125
4
[]
no_license
--- description: 'https://leetcode.com/problems/perfect-squares/' --- # 279. Perfect Squares ## Problem Given a positive integer n, find the least number of perfect square numbers \(for example, `1, 4, 9, 16, ...`\) which sum to n. **Example 1:** ```text Input: n = 12 Output: 3 Explanation: 12 = 4 + 4 + 4. ``` **Example 2:** ```text Input: n = 13 Output: 2 Explanation: 13 = 4 + 9. ``` ## Solution ```cpp class Solution { public: int numSquares(int n){ static vector<int> dp{0}; static int sqrt = 1; while (dp.size() - 1 < n) { int i = dp.size(); if (i == sqrt * sqrt) { dp.emplace_back(1); ++sqrt; continue; } int min_count = INT_MAX; for (int j = 1; j * j < i; ++j) { if (min_count > dp[i - j * j] + dp[j * j]) min_count = dp[i - j * j] + dp[j * j]; } dp.emplace_back(min_count); } return dp[n]; } }; ``` * \#dp * \#math * \#important
Python
UTF-8
878
2.546875
3
[]
no_license
import numpy as np import cv2 cap = cv2.VideoCapture(0) face_cascade = cv2.CascadeClassifier(r"hafta3/opencv/haarcascade_frontalface_default.xml") eye_cascade = cv2.CascadeClassifier(r"hafta3/opencv/haarcascade_eye.xml") while True: ret,frame = cap.read() gray =cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) yuzler = face_cascade.detectMultiScale(gray,1.3,5) for (x,y,w,h) in yuzler: cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2) roi_gray = gray[y:y+h,x:x+w] roi_color = frame[y:y+h,x:x+w] eyes = eye_cascade.detectMultiScale(roi_gray,1.2) for (ex,ey,ew,eh) in eyes: cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,0,255),2) # blur = cv2.GaussianBlur(roi_color,(10,10),0) cv2.imshow('kamera1',frame) if cv2.waitKey(1) & 0xFF == ord("q"): break cap.release() cv2.destroyAllWindows()
Java
UTF-8
850
3.609375
4
[]
no_license
import java.io.File; import java.util.Scanner; public class Main { public static void main(String[] args) { if(args.length > 0){ File f = new File(args[0]); Buscador b = new Buscador(); b.buscar(f, args[1]); }else{ System.out.println("Archivo donde se busca, cadena a buscar."); } } } class Buscador{ public void buscar(File f,String str){ int cont = 0; String actual = ""; try(Scanner sc = new Scanner(f)){ while(sc.hasNextLine()){ actual = sc.nextLine(); cont++; if(actual.contains(str)){ System.out.println(cont+".- "+actual+"."); } } }catch(Exception e){ System.err.println(e.getMessage()); } } }
Java
UTF-8
2,851
2.890625
3
[]
no_license
package symtable; import java.util.HashMap; import java.util.LinkedList; import java.util.Set; import minijava.node.AVarDecl; import minijava.node.PType; import minijava.node.PVarDecl; import minijava.node.TId; import Tree.*; import Arch.*; import java.util.*; /** * A VarTable records name and type information about a <i>collection</i> * of variables. An exception is thrown if we try to add a duplicate name. * @author Brad Richards */ public class VarTable { HashMap<String, VarInfo> table = new HashMap<String, VarInfo>(); /** * Constructor populates table from an initial list of VarDecls. * @param vars A list of PVarDecl nodes from our AST. */ public VarTable(LinkedList<PVarDecl> vars) throws VarClashException { for(PVarDecl var : vars) { try { put(((AVarDecl)var).getId(), ((AVarDecl) var).getType());} catch(VarClashException e){ throw e;}} } /** Allow the option of adding individual entries as well. */ public void put(TId id, PType type) throws VarClashException { String name = id.toString().replaceAll("\\s",""); if (table.containsKey(name)) { String msg = "VarClassException: "+name + " redeclared on line "+id.getLine(); throw new VarClashException(msg); // There was a clash } else table.put(name, new VarInfo(type)); // No clash; add new binding } /** Lookup and return the type of a variable */ public PType get(String name) { PType val = null; //TODO Fill in the guts of this method. if (table.containsKey(name)) val = table.get(name).getType(); return val; } /** Lookup and return a variable's VarInfo record */ public VarInfo getInfo(String name) { return table.get(name); } /** Return all var names in the table */ public Set<String> getVarNames() { return table.keySet(); } /** Returns the number of entries in the table */ public int size() { return table.size(); } /** Print out the entire contents of the table */ public void dump() { //TODO Fill in the guts of this method. String s; ArrayList<String> it = new ArrayList<String>(table.keySet()); while(!it.isEmpty()){ s=it.remove(0); System.out.println(" "+s+" : "+table.get(s).toString()); } System.out.println(); } public void dumpIRT() { //TODO Fill in the guts of this method -- but not until the IRT checkpoint String s; ArrayList<String> it = new ArrayList<String>(table.keySet()); while(!it.isEmpty()){ s=it.remove(0); System.out.println(" "+s+" : "+table.get(s).toString()); Print.prExp(new MEM(new BINOP(0, new REG(new Reg("base")), table.get(s).getAccess().getTree())), 4); System.out.println(); System.out.println(); } } }
C#
UTF-8
1,892
2.859375
3
[]
no_license
using System; using System.IO; using Niob.SimpleHtml; namespace Niob.SimpleErrors { public static class ErrorExtensions { public static void SendError(this HttpResponse response, ushort code) { if (response == null) throw new ArgumentNullException("response"); switch (code) { case 400: response.SendError(code, "Bad Request", "The request could not be understood due to malformed syntax."); break; case 404: response.SendError(code, "Not Found", "The requested resource could not be found."); break; case 405: response.SendError(code, "Method Not Allowed", "A request was made of a resource using a request method not supported by that resource."); break; case 408: response.SendError(code, "Request Timeout", "The server timed out waiting for your request."); break; case 500: response.SendError(code, "Internal Server Error", "The server has a boo-boo."); break; } } public static void SendError(this HttpResponse response, ushort statusCode, string statusText, string desc) { if (response == null) throw new ArgumentNullException("response"); response.StatusCode = statusCode; response.StatusText = statusText; response.ContentStream = new MemoryStream(); response.StartHtml("Error!"); response.AppendHtml("<h1>{0} ({1})</h1>", statusText, statusCode); response.AppendHtml("<p>{0}</p>", desc); response.EndHtml(); response.Send(); } } }
Markdown
UTF-8
1,955
3.1875
3
[ "MIT" ]
permissive
# Jester [Jokes dataset](http://eigentaste.berkeley.edu/dataset/) consists of several datasets which contain joke ratings in real values ranging from -10.00 to +10.00. Texts of jokes are available too. ## Stats ### Dataset 1 - 73,421 users - 100 jokes - collected between April 1999 - May 2003 ### Dataset 3 - 54,905 users - 150 jokes( 50 not in Dataset 1) - collected from November 2006 - Mar 2015 - 22 jokes have few ratings as they were removed as of May 2009 deemed to be out of date (eg, Bill Clinton jokes;) their ids are: {1, 2, 3, 4, 5, 6, 9, 10, 11, 12, 14, 20, 27, 31, 43, 51, 52, 61, 73, 80, 100, 116}. - As of May 2009, the jokes {7, 8, 13, 15, 16, 17, 18, 19} are the "gauge set" (as discussed in the Eigentaste paper) and the jokes {1, 2, 3, 4, 5, 6, 9, 10, 11, 12, 14, 20, 27, 31, 43, 51, 52, 61, 73, 80, 100, 116} were removed (i.e. they are never displayed or rated). ### Dataset 4 - 7699 users - 158 jokes - 22 of the jokes don't have ratings, their ids are: {1, 2, 3, 4, 5, 6, 9, 10, 11, 12, 14, 20, 27, 31, 43, 51, 52, 61, 73, 80, 100, 116}. - The jokes {1, 2, 3, 4, 5, 6, 9, 10, 11, 12, 14, 20, 27, 31, 43, 51, 52, 61, 73, 80, 100, 116} have been removed (i.e. they are never displayed or rated). ## Extra parameters - `dataset=1` one of 1, 3, 4 to choose corresponding version. ## Structure Dataset 1 consists of 3 matrices as provided, they are not merged together. Ratings are in a form of matrix with columns representing jokes. In original data 99 meant "no rating" it is replaced to `NaN` here. ```text data 1 2 3 ... 0 -7.82 8.79 -9.66 ... 1 4.08 -0.29 6.36 ... 2 NaN NaN NaN ... ... ... ... ... ... ``` Joke texts are available as `Pandas.Series` ```text jokes 1 A man visits the doctor. The doctor says "I ha... 2 This couple had an excellent relationship goin... 3 Q. What's 200 feet long and has 4 teeth? A. ... ```
C#
UTF-8
3,030
2.671875
3
[]
no_license
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Renci.SshNet; namespace ReleaseFileBackupTool { class SftpFileBackup { public string RemoteHost { set; get; } public int RemotePort { set; get; } public string RemoteUser { set; get; } public string RemoteBasePath { set; get; } public string SshPrivateKeyPath { set; get; } public string SshPassword { set; get; } public string ReleasePath { set; get; } public string BackupPath { set; get; } public List<string> MessageList { private set; get; } /// <summary> /// コンストラクタ /// </summary> public SftpFileBackup() { this.MessageList = new List<string>(); } /// <summary> /// バックアップ実行 /// </summary> public void execute() { var authMethod = new PrivateKeyAuthenticationMethod(this.RemoteUser, new PrivateKeyFile(this.SshPrivateKeyPath, this.SshPassword)); var connectionInfo = new ConnectionInfo(this.RemoteHost, this.RemotePort, this.RemoteUser, authMethod); using (var client = new SftpClient(connectionInfo)) { // リリースファイル一覧を探索 string[] files = Directory.GetFiles(this.ReleasePath, "*", SearchOption.AllDirectories); foreach (var file in files) { // 絶対パスを相対パスへ変換 Uri basePath = new Uri(this.ReleasePath); Uri relativePath = basePath.MakeRelativeUri(new Uri(file)); string remoteFile = relativePath.ToString(); // バックアップ先ファイル名を決定 string backupFilePath = this.BackupPath + relativePath; // ディレクトリが存在しない場合は作成 string directoryPath = Path.GetDirectoryName(backupFilePath); if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } // ダウンロード client.Connect(); client.ChangeDirectory(this.RemoteBasePath); if (client.Exists(remoteFile)) { using (var fs = File.OpenWrite(backupFilePath)) { client.DownloadFile(remoteFile, fs); } this.MessageList.Add("Success : " + relativePath); } else { this.MessageList.Add("FileNotFound : " + relativePath); } client.Disconnect(); } } } } }
PHP
UTF-8
466
2.515625
3
[]
no_license
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Buildings extends Model { protected $table = 'buildings'; protected $fillable = [ 'name', 'abbrev', 'description', 'conference_id' ]; public function rooms() { return $this->hasMany('App\Models\Rooms', 'building_id'); } public function conference(){ return $this->belongsTo('App\Models\Conference', 'conference_id'); } }
Go
UTF-8
1,207
2.953125
3
[ "MIT" ]
permissive
package wamp import ( "math/rand" "sync" "time" ) const maxID int64 = 1 << 53 func init() { rand.Seed(time.Now().UnixNano()) } // NewID generates a random WAMP ID. func GlobalID() ID { return ID(rand.Int63n(maxID)) //nolint:gosec } // IDGen is generator for WAMP request IDs. Create with new(IDGen). // // WAMP request IDs are sequential per WAMP session, starting at 1 and wrapping // around at 2**53 (both value are inclusive [1, 2**53]). // // The reason to choose the specific upper bound is that 2^53 is the largest // integer such that this integer and all (positive) smaller integers can be // represented exactly in IEEE-754 doubles. Some languages (e.g. JavaScript) // use doubles as their sole number type. // // See https://github.com/wamp-proto/wamp-proto/blob/master/spec/basic.md#ids type IDGen struct { next int64 } // Next returns next ID. func (g *IDGen) Next() ID { g.next++ if g.next > maxID { g.next = 1 } return ID(g.next) } // SyncIDGen is a concurrent-safe IDGen. Create with new(SyncIDGen). type SyncIDGen struct { IDGen lock sync.Mutex } // Next returns next ID. func (g *SyncIDGen) Next() ID { g.lock.Lock() defer g.lock.Unlock() return g.IDGen.Next() }
JavaScript
UTF-8
747
2.78125
3
[ "MIT" ]
permissive
window.global.active = 0; window.global.blocks = 2; var reRender = function(type) { var reviews = $('#reviews > .content > .reviews').children(); if(type == 'left' && window.global.active > 0) { window.global.active -= 1; } if(type == 'right' && window.global.active < reviews.length-1) { window.global.active += 1; } for (var i = 0; i < reviews.length; i++) { var review = reviews[i]; $(review).css({display: 'display'}); } for (var i = 0; i < window.global.active; i++) { var review = reviews[i]; $(review).css({display: 'none'}); } } $('#reviews > .content > .left.item').click(function() { reRender("left") }); $('#reviews > .content > .right.item').click(function() { reRender("right") });
JavaScript
UTF-8
21,261
2.5625
3
[]
no_license
let TAG_SPAN_CIRCLE_START = '<span class="ui red circular'; let TAG_SPAN_START = '<span'; let TAG_SPAN_CLOSE = '</span>'; let P_START = '<p>'; let P_END = '</p>'; count = (inputString, searachString) => { inputString += ''; //searachString += ''; if (searachString.length <= 0) { return 0; } var subStr = searachString.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); return (inputString.match(new RegExp(searachString, 'gi')) || []).length; }; cleanAllSpans = (html) => { // console.log('in cleanAllSpans'); return cleanSpan(cleanSpanCircular(html)); }; cleanSpan = (html) => { // removes all span tag entries //console.log('in cleanSpan'); while (-1 < html.indexOf(TAG_SPAN_START)) { html = cleanSpanSingle(html); } return html; }; cleanSpanSingle = (html) => { // removes one single span, keeps data //console.log('in cleanSpanSingle') let start = 0, end = 0, _html = ''; start = html.indexOf(TAG_SPAN_START); if (start > -1) { //console.log('cleanSpan Start'); _html = html.substring(0,start); html = html.substring(start); //console.log(_html); //console.log(html); } end = html.indexOf(">"); if (end > -1) { //console.log('cleanSpan End'); html = html.substring(end + 1); // add length of </span> //console.log(html); html = _html + html; //console.log('cleanSpanCircular Leftofer') //console.log(html); } start = html.indexOf(TAG_SPAN_CLOSE); if (start > -1) { //console.log('cleanSpan TAG_SPAN_CLOSE'); _html = html.substring(0,start); html = _html + html.substring(start + TAG_SPAN_CLOSE.length); //console.log(_html); //console.log(html); } return html; }; cleanSpanCircular = (html) => { // removes all circular span and it's data //console.log('in cleanSpanCircular'); while (-1 < html.indexOf(TAG_SPAN_CIRCLE_START)) { html = cleanSpanCircularSingle(html); } return html; }; cleanSpanCircularSingle = (html) => { // removes single circular span and it's data //console.log('in cleanSpanCircularSingle') //console.log(html); let start = 0, end = 0, _html = ''; start = html.indexOf(TAG_SPAN_CIRCLE_START); //console.log('start: ' + start); if (start > -1) { //console.log('cleanSpanCircular Start ' + start); _html = html.substring(0,start); html = html.substring(start); //console.log(_html); //console.log(html); } end = html.indexOf(TAG_SPAN_CLOSE); //console.log(end); if (end > -1) { //console.log('cleanSpanCircular End ' + end); html = html.substring(end + TAG_SPAN_CLOSE.length); if (html.substring(0,1) == ' '){ html.substring(1); // VERIFY for two spaces } // add length of </span> + one space ' ' //console.log(html); html = _html + html; //console.log('cleanSpanCircular Leftofer') //console.log(html); } return html; }; function getSelectionCharOffsetsWithin() { var start = 0, end = 0, text='', circleSpansTextLength = 0, circularOnly = false; var sel, range, priorRange, spanRange, doRangeOffsetSpan = false; var snippet, page, loop; sel = window.getSelection(); let tag, pageHTML, pageOriginal, snippetOuterHTML, sinppetIndex =0, cnt; let rangeOffset = 0, offsetStart = 0, offsetEnd = 0, snippetText = '', description = '', computedDesc=''; let elm, elm1, elmStart, elmEnd, elmList=[], noOrphanTag = true, results = [], result; //console.log(window.getSelection()) if (typeof window.getSelection() != "undefined" ) { try { range = window.getSelection().getRangeAt(0); //console.log(range); elmStart = range.startContainer; elmEnd = range.endContainer; //console.log(elmStart); //console.log(elmEnd); elmList.push(elmStart); if(!elmStart.isSameNode(elmEnd)) { elm = elmStart.nextSibling; while((elm != null) && !(elm.isSameNode(elmEnd) || elm.isSameNode(elmStart))) { console.log(elm); if (elm.hasChildNodes) { elm1 = elm.childNodes[0]; //console.log(elm1); if (elm1) { if (elm1.isEqualNode(elmEnd)) { console.log('operlaping span') break; } } } elmList.push(elm); elm = elm.nextSibling; } elmList.push(elmEnd); } //console.log(elmList); //console.log('elmList.length ' + elmList.length) // compute total circle span length (circleSpansTextLength) in seleted elmList, that needs to be // subtracted for start offset, has issue subtracting length for last element if (elmList.length > 1) { for (var idx = 0; idx < (elmList.length - 1); idx++) { elm = elmList[idx]; if (elm.hasChildNodes) { doRangeOffsetSpan = true; elm1 = elm.childNodes[1]; console.log(elm1); if (elm1 != null) { if(elm1.outerHTML.startsWith(TAG_SPAN_CIRCLE_START)){ circleSpansTextLength = circleSpansTextaLength + elm1.innerText.length; console.log('circleSpansTextLength ' + circleSpansTextLength); } } } } } let totalSnippet = ''; // used for snippet text for compined list if (elmList.length > 1) { for (var idx = 0; idx < elmList.length; idx++) { elm = elmList[idx]; totalSnippet = totalSnippet + elm.nodeValue; } } // always returns closest common parent on overlaping tags tag = range.commonAncestorContainer.parentNode.outerHTML; //console.log('range.commonAncestorContainer.parentNode.outerHTML'); //console.log(tag); // test to make sure not just circluar annotion selected if (tag.startsWith(TAG_SPAN_CIRCLE_START)) { // reject and warn user as invalid selction in case of true circularOnly = true; } snippet = range.startContainer.parentElement; tag = snippet.outerHTML; if (tag.startsWith(TAG_SPAN_START)) { if (!tag.startsWith(TAG_SPAN_CIRCLE_START)) { doRangeOffsetSpan = true; } } //console.log('snippet'); //console.log(snippet); //console.log(tag); if (tag.startsWith('<div')) { page = snippet; //noOrphanTag = false; } else { // need different alternate to stop on body or html tag while (!(tag.startsWith('<p') || tag.startsWith('<P')|| tag.startsWith('<body') || tag.startsWith('<BODY'))) { snippet = snippet.parentElement; //console.log(tag); tag = snippet.outerHTML; } page = snippet.parentElement; tag = page.outerHTML; //console.log('page'); //console.log(page); //console.log(tag); while (!(tag.startsWith('<div') || tag.startsWith('<DIV')|| tag.startsWith('<body') || tag.startsWith('<BODY'))) { page = page.parentElement; //console.log(page); tag = page.outerHTML; } } //console.log(range.startContainer); //console.log(snippet); //pageOriginal = page.outerHTML; pageOriginal = page.innerHTML; pageHTML = cleanAllSpans(pageOriginal); snippetOuterHTML = cleanAllSpans(snippet.innerHTML); priorRange = range.cloneRange(); priorRange.selectNodeContents(page); priorRange.setEnd(range.startContainer, range.startOffset); start = priorRange.toString().length + 3; end = start + range.toString().length; text = range.toString(); rangeOffset = range.startOffset; //console.log('rangeOffset: ' + rangeOffset); cnt = 0; if (doRangeOffsetSpan) { var dup = snippet.cloneNode(); spanRange = document.createRange(); spanRange.selectNodeContents(snippet); spanRange.setEnd(range.startContainer, range.startOffset); rangeOffset = spanRange.toString().length; //console.log('spanRange.toString()'); //console.log(spanRange.toString()); //console.log('rangeOffset In span: ' + rangeOffset); } // console.log('pageHTML: '); // console.log(pageHTML); // console.log('snippetOuterHTML: '); // console.log(snippetOuterHTML); // console.log('priorRange toString: ' + priorRange.toString().length); // console.log(priorRange.toString()); if(noOrphanTag){ sinppetIndex = count(priorRange.toString(), snippetOuterHTML); // check repeats offsetStart = pageHTML.indexOf(snippetOuterHTML); // snippet tag start snippetText = snippetOuterHTML; } else { // need more testing snippetText = elmStart.nodeValue; sinppetIndex = count(priorRange.toString(), snippetText) offsetStart = pageHTML.indexOf(snippetText); snippetOuterHTML = snippetText; } //console.log('sinppetIndex ' + sinppetIndex); cnt = 0; //console.log('idx: ' + cnt + ', offsetStart ' + offsetStart); while (cnt < sinppetIndex) { cnt++; if (-1 < pageHTML.indexOf(snippetOuterHTML, offsetStart)) { offsetStart = pageHTML.indexOf(snippetOuterHTML, (offsetStart + 1)); //console.log('idx: ' + cnt + ', offsetStart ' + offsetStart); } } description = range.toString(); offsetStart = offsetStart + rangeOffset; offsetEnd = offsetStart + description.length - circleSpansTextLength; // if(!noOrphanTag){ // offsetStart = start; // offsetEnd = end; // } computedDesc = pageHTML.substring(offsetStart, offsetEnd); //console.log(offsetStart + ' ' + offsetEnd); var _end = computedDesc.indexOf(P_END); var _shift = 0; var _idx = 0, _tx='', _tx1=''; let _st = offsetStart, _en = offsetEnd; //console.log(computedDesc); while (-1 != _end) { // TODO: change to while //console.log('P_END'); _en = _st + _end; result = { offsetStart: _st, offsetEnd: _en, snippetText: totalSnippet, description: description // may need to replace with computedDesc } results.push(result); _tx1 = pageHTML.substring(offsetEnd, (offsetEnd + P_END.length)); offsetEnd = offsetEnd + P_END.length; _tx = computedDesc.substring(0,_end); computedDesc = _tx + computedDesc.substring(_end + P_END.length) + _tx1; //console.log(computedDesc); _end = computedDesc.indexOf(P_START, _end); if (-1 != _end) { _st = offsetStart + _end + P_START.length; _tx1 = pageHTML.substring(offsetEnd, (offsetEnd + P_START.length)); offsetEnd = offsetEnd + P_START.length; _tx = computedDesc.substring(0,_end); computedDesc = _tx + computedDesc.substring(_end + P_START.length) + _tx1; _en = _st + _end; //console.log(computedDesc); _end = computedDesc.indexOf(P_END); //TODO: back to while loop } _idx++; if (idx > 3) { //break; } } if (results.length > 0) { result = { offsetStart: _st, offsetEnd: _en, snippetText: totalSnippet, description: description // may need to replace with computedDesc } results.push(result); } if (description == computedDesc) { //console.log('description == computedDesc ' + description) } else { // TODO: Uma, enable in case of error //console.log('description <> computedDesc "' + description + '" "' + computedDesc + '"'); } //var documentFragment = cloneRange.extractContents(); //console.log('documentFragment: '); //console.log(documentFragment); //console.log('*************************************************'); } catch (error) { //DOM Exception console.log(error); } } if (results.length == 0) { result = { offsetStart: offsetStart, offsetEnd: offsetEnd, snippetText: snippetText, description: computedDesc // may need to replace with computedDesc } results.push(result); } return { pageHTML: pageHTML, results: results, computedDesc: computedDesc, start: start, end: end, text: text, circularOnly: circularOnly }; } function printSelection() { var sel = getSelectionCharOffsetsWithin(); var pval = document.getElementById("result"); var _txt = ''; //console.log('selection: '); //console.log(sel); if (sel.circularOnly) { _txt = "Selected Cirular only, invalid text"; } else if (sel.text.length > 0) { _txt = "Start: " + sel.start + ", End: " + sel.end + ", Text: '" + sel.text + "', length: " + sel.text.length; } else { _txt = "No selection found."; } pval.innerText = "Selected Text: " + _txt; } function clearSelection() { var pval = document.getElementById("result"); pval.innerText = "Selected Text:" ; } function formatedRules(text) { if (text) { // remove rule prefix var _text = text.replace(/rule-/g, ''); // replace ' ' with ',' _text = _text.replace(/\s+/g, ', '); //console.log(_text); return _text; } else { return ''; } } function resetToolbar() { $(".icon-bar > a.selected").removeClass("selected"); } function toggleRule(obj) { obj.classList.toggle("selected"); //filp css style 'selected' $("#selectedText").removeClass(); var style = getCurrentRules(); if (style.length > 0) { $("#selectedText").addClass(style); document.getElementById("selectedRules").innerText = formatedRules(style); } } let ruleCount = 0; let currentrules = []; function getRuleId() { ruleCount++; var ruleid = "00000" + ruleCount; ruleid = 'rule' + ruleid.substring(ruleid.length - 5); //console.log(ruleid); return ruleid; } function getCurrentRules() { var style= ''; var list = $(".icon-bar > a.selected"); if(list.length > 0){ list.map((index, elm) => { style = style + elm.id + ' '; }); } return style.trim(); } function applyRules() { var selObj = window.getSelection(); if(!(selObj && selObj.toString().trim().length > 0)) { return; } var rule = {active: true, norepeat: true}; var style = getCurrentRules(); //console.log(sel); if(style.length > 0){ var _htm0 = document.getElementById("previewDiv").innerHTML; rule.id = getRuleId(); rule.rules = formatedRules(style) rule.text = selObj.toString(); var sel = getSelectionCharOffsetsWithin(); rule.start = sel.start;//may be limit to start and end? rule.end = sel.end; currentrules.push(rule); //store in global variable for later use console.log(currentrules); var _htm = _htm0.substring(0, sel.start); // _htm = _htm + '<span id="' + rule.id + '" class="'+ style + '">' + _htm0.substring(sel.start, sel.end) + '</span>' _htm = _htm + ruleToHtml(noolSrc, rule); _htm = _htm + _htm0.substring(sel.end); document.getElementById("previewDiv").innerHTML = _htm; // update rule history table var _history = ''; var aid; if(currentrules.length > 0) { // may be convert text link to icons _history = '<div style="width: 100%;">' _history = _history + '<span style="float:right;">'; _history = _history + '<a href="#" onClick="displayRules()">Display Rules</a> | ' _history = _history + '<a href="#" onClick="showAllRules()">Show All</a> | ' _history = _history + '<a href="#" onClick="hideAllRules()">Hide All</a> | ' _history = _history + '<a href="#" onClick="removeAllRules()">Delete All</a></span></div>' _history = _history + '<table id="history"><thead><tr><th>Rules</th><th>Selected Text</th>'; _history = _history + '<th>Actions</th></tr></thead><tbody>'; currentrules.map((elm, index) => { aid = 'showhide_' + elm.id; // console.log(aid); _history = _history + '<tr><td>' + elm.rules + '</td><td>'; _history = _history + elm.text + '</td><td>'; _history = _history + '<a id="' + aid + '" href="#" onClick="showHideRule('; _history = _history + elm.id +')">Hide</a> | <a href="#" onClick='; _history = _history +'"removeRule(' + elm.id +')">Remove</td></tr>'; }); _history = _history + '</tbody></table>'; } // //console.log(_history); document.getElementById("ruleDocument").innerHTML = _history; // reset toolbar resetToolbar(); $("#rules-def, #icons-v, #create-rule").addClass('display-none'); //var _html = $("#htmlSrc").html(); //_html = ruleHtmlInsertAll(_html, currentrules); document.getElementById("previewDiv").innerHTML = _html; document.getElementById("selectedText").innerHTML = ""; document.getElementById("selectedRules").innerHTML = ""; $("#selectedRules").removeClass(); } } function getHistorySpanId(text) { if (!text) return ''; if(typeof text === 'object'){ //var lst = text.classList; //console.log(lst); // use this to read class names return text.id; } return text; } function showHideRule(id) { console.log('showHideRule'); var _id = getHistorySpanId(id); console.log(_id); var elm = document.getElementById('showhide_' + _id); console.log(elm); if (elm) { if (elm.innerText === 'Show'){ elm.innerText = 'Hide'; $('#'+ obj.id).removeClass('display-none'); } else { elm.innerText = 'Show'; $('#'+ obj.id).addClass('display-none'); } } } function removeRule(id) { console.log('removeRule'); var _id = getHistorySpanId(id); console.log(_id); } function editRule(id) { //not used now console.log('editRule'); var _id = getHistorySpanId(id); console.log(_id); } function hideAllRules() { console.log('hideAllRules'); if(currentrules.length > 0) { currentrules.map((obj) =>{ var elm = document.getElementById('showhide_' + obj.id); $('#'+ obj.id).removeClass('display-none'); //console.log(elm); // set active flag to false if (elm) { elm.innerText = 'Show'; } }); } } function showAllRules() { console.log('showAllRules'); if(currentrules.length > 0) { currentrules.map((obj) =>{ var elm = document.getElementById('showhide_' + obj.id); //console.log(elm); // set active flag to true if (elm) { elm.innerText = 'Hide'; } }); } } function removeAllRules() { console.log('removeAllRule'); if(currentrules.length > 0) { // find span by id and remove them // empty rules array object currentrules.map((obj) =>{ var elm = document.getElementById('showhide_' + obj.id); //console.log(elm); }); } } function displayRules() { // mehod to display 'rules' as formated json data console.log('DisplayRules'); } function formatSpan(id, styles, text) { var _str = '<span id="'+ id + '" class="' + ruleFormat(id, styles) + '">' + text + '</span>'; return _str; } function ruleFormat(id, rule) { if(!rule) return rule; rule = rule.replace(/\s/g, ''); // remve any spaces if (rule.indexOf(',') > -1) { let styles = rule.split(','); rule = id; styles.map(function(elm){ rule = rule + ' rule-' + elm; }); } else { rule = id + ' rule-' + rule; } return rule; } function getId(id) { return id + ' '; } let startShift; function ruleHtmlInsertAll(html, rules) { startShift = 0; var _html = html; rules.map(function(elm){ _html = ruleHtmlInsertOne(_html, elm, startShift) }); return _html; } function ruleHtmlInsertOne(html, rule, startShift) { var st = rule.start + startShift; var ed = rule.end + startShift; //console.log('ruleHtmlInsertOne');console.log(rule);console.log(startShift); //console.log(st); var _html = html.substring(0, st); var _html1 = ruleToHtml(noolSrc, rule); startShift = startShift + (_html1.length - rule.text.length); //console.log(startShift);console.log(startShift + rule.end); //console.log(html.substring(ed)); _html = _html + _html1 + html.substring(ed); return _html; } var noolSrc, flow, Selection; function ruleToHtml(noolSrc, rule){ console.log(rule); var m = new Selection(rule); var session = flow.getSession(m); session.match(function(err){ if(err){ console.error(err); } else{ session.dispose(); } }); // if (session) // session.dispose(); console.log(m.html); return m.html; }
C
UTF-8
273
3.40625
3
[]
no_license
#include "holberton.h" #include <stdio.h> /** * main - print program name * @argc: number of arguments * @argv: arguments (string) * * Return: 0 on Success */ int main(int argc, char **argv) { if (argc) { argc--; printf("%s\n", argv[argc]); } return (0); }