text
stringlengths
1
1.05M
/* * Copyright (c) Open Source Strategies, Inc. * * Opentaps is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Opentaps 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Opentaps. If not, see <http://www.gnu.org/licenses/>. */ package org.opentaps.gwt.common.server.lookup; import java.util.Arrays; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.opentaps.base.entities.PartyClassificationGroup; import org.opentaps.foundation.entity.EntityInterface; import org.opentaps.foundation.infrastructure.InfrastructureException; import org.opentaps.gwt.common.client.lookup.configuration.PartyClassificationLookupConfiguration; import org.opentaps.gwt.common.server.HttpInputProvider; import org.opentaps.gwt.common.server.InputProviderInterface; /** * The RPC service used to populate PartyClassification autocompleters widgets. */ public class PartyClassificationLookupService extends EntityLookupAndSuggestService { protected PartyClassificationLookupService(InputProviderInterface provider) { super(provider, Arrays.asList(PartyClassificationLookupConfiguration.OUT_CLASSIFICATION_ID, PartyClassificationLookupConfiguration.OUT_DESCRIPTION)); } /** * AJAX event to suggest PartyClassifications. * @param request a <code>HttpServletRequest</code> value * @param response a <code>HttpServletResponse</code> value * @return the resulting JSON response * @throws InfrastructureException if an error occurs */ public static String suggestClassifications(HttpServletRequest request, HttpServletResponse response) throws InfrastructureException { InputProviderInterface provider = new HttpInputProvider(request); JsonResponse json = new JsonResponse(response); PartyClassificationLookupService service = new PartyClassificationLookupService(provider); service.suggestClassifications(); return json.makeSuggestResponse(PartyClassificationLookupConfiguration.OUT_CLASSIFICATION_ID, service); } /** * Gets all party classifications. * @return the list of party classifications <code>GenericValue</code> */ public List<PartyClassificationGroup> suggestClassifications() { return findAll(PartyClassificationGroup.class); } @Override public String makeSuggestDisplayedText(EntityInterface partyClassification) { return partyClassification.getString(PartyClassificationLookupConfiguration.OUT_DESCRIPTION); } }
#!/usr/bin/env bash SOURCE="${BASH_SOURCE[0]}" while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink scriptroot="$( cd -P "$( dirname "$SOURCE" )" && pwd )" SOURCE="$(readlink "$SOURCE")" [[ $SOURCE != /* ]] && SOURCE="$scriptroot/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located done scriptroot="$( cd -P "$( dirname "$SOURCE" )" && pwd )" . "$scriptroot/common/tools.sh" . "$scriptroot/configure-toolset.sh" InitializeToolset . "$scriptroot/restore-toolset.sh" ReadGlobalVersion "dotnet" dotnet_sdk_version=$_ReadGlobalVersion export SDK_REPO_ROOT="$repo_root" testDotnetRoot="$artifacts_dir/bin/redist/$configuration/dotnet" testDotnetVersion=$(ls $testDotnetRoot/sdk) export DOTNET_MSBUILD_SDK_RESOLVER_SDKS_DIR="$testDotnetRoot/sdk/$testDotnetVersion/Sdks" export MicrosoftNETBuildExtensionsTargets="$artifacts_dir/bin/$configuration/Sdks/Microsoft.NET.Build.Extensions/msbuildExtensions/Microsoft/Microsoft.NET.Build.Extensions/Microsoft.NET.Build.Extensions.targets" export PATH=$testDotnetRoot:$PATH export DOTNET_ROOT=$testDotnetRoot
<gh_stars>1-10 package demo._42.event; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.event.ContextStartedEvent; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Service; /** * Created by nlabrot on 15/09/15. */ @Service public class MyEventListener { private static final Logger LOG = LoggerFactory.getLogger(MyEventListener.class); private List<AnEvent> allEvents = new ArrayList<>(); private List<AnEvent> evenEvents = new ArrayList<>(); @EventListener public void processAllEvent(AnEvent event) { allEvents.add(event); } @EventListener(condition = "#event.value % 2 == 0") public void processEvenEvent(AnEvent event) { evenEvents.add(event); } @EventListener({ContextStartedEvent.class, ContextRefreshedEvent.class}) public void handleContextStart() { LOG.info("Context Started of refreshed!!!!!!!!!!!!"); } public List<AnEvent> getAllEvents() { return allEvents; } public List<AnEvent> getEvenEvents() { return evenEvents; } }
# optimized code snippet to sort the given array arr = [5, 4, 3, 2, 1] arr.sort() print(arr) # arr is now sorted in ascending order as [1, 2, 3, 4, 5]
<reponame>toni240598/ems-angular2 import { Injectable } from '@angular/core'; import { Http } from "@angular/http"; import { Observable } from "rxjs/Observable"; import "rxjs/add/operator/map"; @Injectable() export class LoopbackService { constructor(private http:Http) { } dataSet = { location : { type:"GET", url:"/api/location_store"}, formCreate : { type:"POST", url:"/api/apps/service"}, store : { type:"GET", url:"/api/store/", params:true}, ProvinceService : {type:"POST", url:"/api/apps/location"}, ZoneService : {type:"POST", url:"/api/apps/location"}, BranchService : {type:"POST", url:"/api/apps/location"}, StoreService : {type:"POST", url:"/api/apps/location"}, 'store-dashboard' : { type:"GET", url:"/api/store/dashboard",params:true }, 'store-dashboard/chart' :{type :"GET", url : "/api/store/dashboard/chart", params:true }, 'store-alarm' : { type:"GET" , url:"/api/store/alarm" }, 'store-inventory' : { type:"GET", url:"/api/store/inventory", params:true}, 'store-detail' : { type:"GET", url:"/api/store/detail", params:true}, alarm : { type:"GET" , url:"/api/alarm" }, dashboard : { type:"GET", url:"/api/dashboard" }, inventoryService : { type:"POST", url:"/api/apps/inventory" } } getService(category, data){ let url= this.dataSet[category].url; if (this.dataSet[category].type == "GET"){ if(this.dataSet[category].params==undefined){ return this.http.get(url).map(res => res.json()); } else { url = this.setParams(category,url,data); return this.http.get(url).map(res => res.json()); } } else{ return this.http.post(url, data).map(res => res.json()); } } setParams(category,url,data){ let config = { 'store-dashboard/chart' : ["categoryChart","typeChart"], 'store-dashboard' : ["latitude","longitude"], 'store-inventory' : ["id"], 'store-detail' : ["latitude", "longitude", "id", "type"] } let metadata = config[category]; for(var i in metadata){ url += "/"; url += data[ metadata[i] ].toString(); } return url; } }
const webpack = require('webpack'); const path = require('path'); const fs = require('fs'); const cheerio = require('cheerio'); const getDllConfig = require('./config/webpack.dll'); async function checkRebuildDll(outputDir, dependencies, log) { // Generate dependencies.json or compare dependencies const dependenciesJSON = path.join(outputDir, 'dependencies.json'); if (!fs.existsSync(dependenciesJSON)){ fs.writeFileSync(dependenciesJSON, JSON.stringify({ ...dependencies, })); return true; } else { try { const currPkgString = fs.readFileSync(path.resolve(outputDir, 'dependencies.json'), 'utf-8'); if (currPkgString === JSON.stringify(dependencies)) { return false; } return true; } catch (err) { log.error('Error reading dependencies.json'); throw err; } } } async function generateDllVendorFile(outputDir, dependencies) { // Generate vendor.js let data = ''; const vendor = path.join(outputDir, 'vendor.js'); Object.keys(dependencies).forEach(dependency => { data = data.concat(`require('${dependency}');\n`); }); fs.writeFileSync(vendor, data); } async function includeDllInHTML(outputDir, defaultAppHtml, log, rebuild) { try { const htmlTemplate = path.join(outputDir, 'public', 'index.html'); const cssFile = path.join(outputDir, 'public', 'css', 'vendor.css'); // Read html content from default app index.html const htmlContent = fs.readFileSync(defaultAppHtml, 'utf-8'); const $ = cheerio.load(htmlContent); // add vendor.css if (fs.existsSync(cssFile) && !rebuild) { $('head').append('<link href="css/vendor.css" rel="stylesheet">'); } // Check if vendor.js is included inside the HTML file const hasVendor = (Array.from($('script')) || []).some(script => script.attribs.src === 'vendor.dll.js'); if (!hasVendor) { $('body').append('<script data-id="dll" src="vendor.dll.js"></script>'); } fs.writeFileSync(htmlTemplate, $.root().html()); } catch (err) { log.error('Error opening or writing to file'); } } async function buildDll({ webpackConfig, rootDir, pkg, htmlTemplate, log, }) { // Create directories to store Dll related files const outputDir = path.join(rootDir, 'node_modules', 'plugin-dll'); if (!fs.existsSync(outputDir)){ fs.mkdirSync(outputDir); } if (!fs.existsSync(path.join(outputDir, "public"))){ fs.mkdirSync(path.join(outputDir, "public")); } // Check for rebuild Dll status const rebuildDll = await checkRebuildDll(outputDir, pkg.dependencies, log); // Include vendor.js in HTML file await includeDllInHTML(outputDir, htmlTemplate, log, rebuildDll); if (rebuildDll) { await generateDllVendorFile(outputDir, pkg.dependencies); const dllConfig = getDllConfig(webpackConfig, rootDir); return new Promise((resolve, reject) => { log.info("Building Dll"); webpack(dllConfig, error => { if (error) { return reject(error); } resolve(); }); }); } log.info("No new changes from dependencies.json"); } module.exports = buildDll;
# Linux Shell > Text Processing > Tail of a Text File #1 # Introduction to the 'tail' command. # # https://www.hackerrank.com/challenges/text-processing-tail-1/problem # tail -20
Turnout.configure do |config| config.app_root = '.' config.named_maintenance_file_paths = { default: config.app_root.join('tmp', 'maintenance.yml').to_s } config.maintenance_pages_path = config.app_root.join('public').to_s config.default_maintenance_page = Turnout::MaintenancePage::HTML config.default_reason = 'You will be able to use the service from 2pm on Thursday 25&nbsp;July&nbsp;2019' config.default_allowed_paths = ['/assets'] config.default_response_code = 503 config.default_retry_after = 7200 end
#version 300 es precision mediump float; in vec2 mcLongLat;//接收从顶点着色器过来的参数 out vec4 fFragColor;//输出的片元颜色 void main() { vec3 bColor=vec3(0.678,0.231,0.129);//砖块的颜色 vec3 mColor=vec3(0.763,0.657,0.614);//水泥的颜色 vec3 color;//片元的最终颜色 //计算当前位于奇数还是偶数行 int row=int(mod((mcLongLat.y+90.0)/12.0,2.0)); //计算当前片元是否在此行区域1中的辅助变量 float ny=mod(mcLongLat.y+90.0,12.0); //每行的砖块偏移值,奇数行偏移半个砖块 float oeoffset=0.0; //当前片元是否在此行区域3中的辅助变量 float nx; if(ny>10.0) {//位于此行的区域1中 color=mColor;//采用水泥色着色 } else {//不位于此行的区域1中 if(row==1) {//若为奇数行则偏移半个砖块 oeoffset=11.0; } //计算当前片元是否在此行区域3中的辅助变量 nx=mod(mcLongLat.x+oeoffset,22.0); if(nx>20.0) {//不位于此行的区域3中 color=mColor; } else {//位于此行的区域3中 color=bColor;//采用砖块色着色 } } //将片元的最终颜色传递进渲染管线 fFragColor=vec4(color,0); }
package hudson.plugins.accurev; import java.io.Serializable; public class RefTreeExternalFile implements Serializable { private final String location; private final String status; public RefTreeExternalFile(String location, String status) { this.location = location; this.status = status; } /** * Getter for property 'location'. * * @return Value for property 'location'. */ public String getLocation() { return location; } /** * Getter for property 'status'. * * @return Value for property 'status'. */ public String getStatus() { return status; } }
./deploytemplate.py -u https://raw.githubusercontent.com/gbowerman/azure-minecraft/master/azure-marketplace/minecraft-server-ubuntu/mainTemplate.json -f parameters.json -p adminPassword,dnsNameForPublicIP -l westus2 -w
<reponame>abhija77/book_store_back /* eslint-disable prettier/prettier */ import { HttpService, Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import axios, { Axios, AxiosResponse } from 'axios'; import { Observable, timeout } from 'rxjs'; import { Connection, getConnection, Repository } from 'typeorm'; import { Book } from './book'; import { Indexation } from './indexation'; import { IndexationJaccard } from './indexationJaccard'; import BookWords from './model/book-words.model'; import BookInterface from './model/book.model'; const wordsNotAllowed = [ "de", "le", "la", "les", "du", "des", "un", "une", ".", ",", "a", "the", "an", "to", "if", "we", "on", "at", "us", "our", "of", "or", "and", "by", "this", "is", "are", "for", "in", "you", "it", "tm", "re" ] @Injectable() export class AppService { constructor(private http: HttpService, private connection: Connection, @InjectRepository(Book) private booksRepository: Repository<BookInterface>, @InjectRepository(Indexation) private indexationRepo: Repository<Indexation>, @InjectRepository(IndexationJaccard) private indexationJaccardRepo: Repository<IndexationJaccard>) { } createBook(): any { return null; } tokenize(text) { const allWords: string[] = text.replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/\r\n]/gi, " ") .split(" ") .filter(word => word != '') .map(word => word.toLowerCase()); const wordsF = allWords .filter(val => { const value = val.toLowerCase(); return !wordsNotAllowed.find(val => val == value); } ); return { size: allWords.length, words: wordsF }; } resolveText(text: string) { const words: BookWords[] = []; const list = this.tokenize(text); let wordMostPresent: BookWords = null; let wordNumber: number = list.size; list.words.forEach((value: string) => { const word: BookWords[] = words.filter((book: BookWords) => book.token.toLowerCase() === value.toLowerCase() && book.token.length == value.length); let obj = word.length > 0 ? word[0] : { token: value.toLowerCase(), occurence: 0, ratio: 0 } obj.occurence++; if (word.length == 0) { words.push(obj); } }); words.forEach((word: BookWords) => { if (wordMostPresent == null || word.occurence > wordMostPresent.occurence) { wordMostPresent = word } word.ratio = word.occurence / wordNumber; }); return words; } async createMany(url: any) { const queryRunner = this.connection.createQueryRunner(); await queryRunner.connect(); await queryRunner.startTransaction(); const res = await axios.get(url).then(value => value.data); let results = res.results; results.forEach(async element => { let book: Book = new Book() book.url_content = element.formats["text/plain; charset=utf-8"]; if (book.url_content != null && book.url_content.includes("txt")) { book.id_book = element.id try { await queryRunner.manager.save(book) await queryRunner.commitTransaction(); } catch (err) { await queryRunner.rollbackTransaction(); console.log("erreur : " + err) return err; } } }); } findAll(): Promise<BookInterface[]> { return this.booksRepository.find(); } async getTokens(url) { const res = await axios.get(url) .then(value => { console.log(value.status); return value.data; }) .catch(error => { console.log("erreur : " + error) }) let resResolved; if (res) { resResolved = this.resolveText(res); } return resResolved; } async algojaccard(v1, v2) { // /*Nombre d’éléments contenus dans les deux vecteurs (intersection)*/ // let i: number = 0; // /*Nombre d’éléments total des deux vecteurs (union)*/ // let u: number = 0; // /*On parcourt le premier vecteur d’occurrence*/ // for (const [w, c] of (Object.entries(v1) as [string, number][])) { // /*On ajoute le nombre d’occurrence du mot à l'union*/ // u = u + c; // /*Si le mot est présent dans le second vecteur on ajoute le nombre d’occurrence à l'intersection*/ // if (v2[w] != null) { // i += c + v2[w]; // } // } // /*On parcourt le second vecteur d’occurrence pour ajouter les occurrences à l'union*/ // for (const [w, c] of (Object.entries(v1) as [string, number][])) { // u += c; // } // /*On retourne l'Indice de Jaccard*/ // return i / u; // } } //InProgress async getIndexTable() { let indexTable = {}; let books = await this.findAll(); for (const book of books) { let listToken; console.log(book); try { listToken = await this.getTokens(book.url_content); } catch (e) { console.error(e); } console.log("running"); if (listToken != null && listToken != []) { listToken.forEach(tokens => { let objWord; if (indexTable[tokens.token]) { objWord = { "book": book.id_book, "occurences": tokens.occurence, "ratio": tokens.ratio }; } else { objWord = { "book": book.id_book, "occurences": tokens.occurence, "ratio": tokens.ratio }; indexTable[tokens.token] = []; } indexTable[tokens.token].push(objWord) }); } } Object.keys(indexTable).forEach(async tok => { const index = new Indexation(); index.token = tok; index.index = JSON.stringify(indexTable[tok]); await this.indexationRepo.save(index); }) console.log(indexTable); return indexTable; } async indexation() { console.log("START INDEXATION"); return await this.getIndexTable(); } async indexationJaccard() { //récupérer liste des livres let listBooks: BookInterface[] = await this.findAll(); let listIndexationJaccard = await this.indexationJaccardRepo.find(); //récupérer tokens pour chaque livre if listIndexationJaccard == []) { let books = [] for (const book of listBooks) { let tokensBook = await this.getTokens(book.url_content); books.push({ "id": book.id_book, "token": tokensBook }); } const indexationJaccard = new IndexationJaccard(); indexationJaccard.indexJaccard = JSON.stringify(books); await this.indexationJaccardRepo.save(indexationJaccard) } console.log(listIndexationJaccard); //créer table indexation jaccard //comparer 2 à 2 livre selon jaccard //stocker resultats sous forme: une ligne = nom du livre : [nom du livre=>distance,...] //stocker base de données la table d'indexation selon le modéle : une ligne = id,id_book,nom du livre,distances } async findIndexationOne(word) { return this.indexationRepo.findOne({ where: { token: word } }) } }
import sqlite3 dbname = 'userdata.db' conn = sqlite3.connect(dbname) c = conn.cursor() # Create a table for user data c.execute("""CREATE TABLE IF NOT EXISTS user (name TEXT, age INTEGER, email TEXT) """) # Add a single record record = ('John', 28, 'john@example.com') c.execute('INSERT INTO user VALUES (?,?,?)', record) # Commit changes to database conn.commit() # Retrieve and display all records c.execute('SELECT * FROM user') for user in c.fetchall(): print(user) # Close the connection to the database conn.close()
require 'thor' require 'terminal-table' require 'pathname' require 'phantomblaster/generators/script' module Phantomblaster class CLI < Thor package_name 'phantomblaster' desc 'account', 'Displays information about the account' def account title = 'Phantombuster Account' headings = ['Email', 'API Key'] rows = [[current_user.email, Phantomblaster.configuration.api_key]] table = Terminal::Table.new title: title, headings: headings, rows: rows say table end desc 'agents', 'Lists all remote agents' def agents title = 'Phantombuster Agents' headings = ['Agent Name', 'Agent ID', 'Script ID', 'Last Status'] rows = [] current_agents.each do |agent| rows << [agent['name'], agent['id'], agent['scriptId'], agent['lastEndStatus']] end table = Terminal::Table.new title: title, headings: headings, rows: rows say table end desc 'scripts', 'Lists all remote scripts' def scripts title = 'Phantombuster Scripts' headings = ['Script Name', 'Script ID', 'Script Source', 'Script Last Saved At'] rows = [] current_scripts.each do |script| rows << [script.name, script.id, script.source, script.last_saved_at] end table = Terminal::Table.new title: title, headings: headings, rows: rows say table end desc 'generate FILENAME', 'Generates an agent script' def generate(name) Phantomblaster::Generators::Script.start([name]) end desc 'upload FILENAME', 'Uploads an agent script' def upload(name) return unless yes?("Upload #{name} to Phantombuster?") res = Phantomblaster::Models::Script.upload(name) say res end desc 'download FILENAME', 'Downloads an agent script' def download(name, force = false) script = Phantomblaster::Models::Script.find_by_name(name) folder_pathname = Pathname.new(Phantomblaster.configuration.scripts_dir) file_pathname = Pathname.new(name) full_pathname = folder_pathname.join(file_pathname) unless folder_pathname.directory? return unless yes?("Directory #{folder_pathname.realdirpath} does not exist. Create it?") folder_pathname.mkpath end if !force && full_pathname.exist? return unless yes?("File #{full_pathname.realpath} already exists. Overwrite?") end full_pathname.open('w') { |f| f << script.text } say "Wrote #{full_pathname.realpath}" end desc 'pull', 'Fetches all agent scripts' def pull return unless yes?("This will pull from Phantombuster and overwrite any existing scripts. " \ "Are you sure you want to continue?") current_scripts.each do |script| download(script.name, true) end end desc 'push', 'Pushes all agent scripts' def push return unless yes?("This will push all local scripts to Phantombuster and overwrite any " \ "existing scripts. Are you sure you want to continue?") folder_pathname = Pathname.new(Phantomblaster.configuration.scripts_dir) raise 'Scripts directory does not exist' unless folder_pathname.directory? Pathname.glob("#{folder_pathname.realdirpath}/**/*.js").each do |pn| _dir, file = pn.split upload(file) end end private def current_user @current_user ||= Phantomblaster::Models::User.find end def current_agents @current_agents ||= current_user.agents end def current_scripts @current_scripts ||= Phantomblaster::Models::Script.all end end end
package leetCode;//假设有打乱顺序的一群人站成一个队列,数组 people 表示队列中一些人的属性(不一定按顺序)。 // 每个 people[i] = [hi, ki] 表示第 i个人的身高为 hi ,前面 正好 有 ki 个身高大于或等于 hi 的人。 // // 请你重新构造并返回输入数组 people 所表示的队列。返回的队列应该格式化为数组 queue ,其中 queue[j] = [hj, kj] 是队列中第 // j 个人的属性(queue[0] 是排在队列前面的人)。 // // // // // // // 示例 1: // // //输入:people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]] //输出:[[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] //解释: //编号为 0 的人身高为 5 ,没有身高更高或者相同的人排在他前面。 //编号为 1 的人身高为 7 ,没有身高更高或者相同的人排在他前面。 //编号为 2 的人身高为 5 ,有 2 个身高更高或者相同的人排在他前面,即编号为 0 和 1 的人。 //编号为 3 的人身高为 6 ,有 1 个身高更高或者相同的人排在他前面,即编号为 1 的人。 //编号为 4 的人身高为 4 ,有 4 个身高更高或者相同的人排在他前面,即编号为 0、1、2、3 的人。 //编号为 5 的人身高为 7 ,有 1 个身高更高或者相同的人排在他前面,即编号为 1 的人。 //因此 [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] 是重新构造后的队列。 // // // 示例 2: // // //输入:people = [[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]] //输出:[[4,0],[5,0],[2,2],[3,2],[1,4],[6,0]] // // // // // 提示: // // // 1 <= people.length <= 2000 // 0 <= hi <= 106 // 0 <= ki < people.length // 题目数据确保队列可以被重建 // // Related Topics 贪心 数组 排序 // 👍 948 👎 0 import java.util.Arrays; import java.util.Comparator; //leetcode submit region begin(Prohibit modification and deletion) public class L10406_ReconstructQueue { public int[][] reconstructQueue(int[][] people) { Arrays.sort(people, (people1, people2) -> { if (people1[0] != people2[0]) { return people1[0] - people2[0]; } else { return people2[1] - people1[1]; } }); int[][] result = new int[people.length][]; for (int index = 0; index < people.length; index++) { int[] indexPeople = people[index]; //前面有N个空位,加自身有 N+1个空位 int preNullCount = indexPeople[1] + 1; for (int resultIndex = 0; resultIndex < result.length; resultIndex++) { if (result[resultIndex] == null){ preNullCount--; if (preNullCount == 0){ result[resultIndex] = indexPeople; } } } } return result; } }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.u1F508 = void 0; var u1F508 = { "viewBox": "0 0 2600 2760.837", "children": [{ "name": "path", "attribs": { "d": "M1999 1779.5q-41 207.5-105.5 343.5T1776 2259q-96 0-170-153t-106-428q62-6 109.5-96t47.5-207q0-132-46.5-217.5T1494 1072q27-291 103-464.5T1776 434q52 0 116.5 134t106 343 41.5 436q0 225-41 432.5zM1593 2259h-71q-27 0-94.5-104T1302 1896l-6-1-264-334-82-23q-8 112-30.5 162t-62.5 50H711q-64 0-107.5-112.5T560 1373q0-153 43.5-265.5T711 995h154q31 0 52 46.5t33 159.5l42-10q20-4 40-7l231-289q56-198 137.5-329.5T1532 434h61q-122 73-204 328t-82 585 82 584.5 204 327.5z" }, "children": [] }] }; exports.u1F508 = u1F508;
A basic clustering algorithm can be structured as follows: 1. Select a starting point for the algorithm. 2. Calculate the distance between the starting point and each of remaining data points. 3. Select the nearest data points as the first cluster. 4. Repeat step 2 and 3 for the remaining data points by selecting the nearest data point to the group formed in the previous step. 5. Continue repeating the process until all data points have been assigned to a cluster.
#include <stdio.h> #define DEBUG_MSG(format, ...) printf("[%s:%d] " format "\n", __FILE__, __LINE__, ##__VA_ARGS__) int main() { int errorCode = 404; DEBUG_MSG("Error code: %d", errorCode); char* functionName = "exampleFunction"; DEBUG_MSG("Error occurred at function %s", functionName); return 0; }
import { NotImplementedError } from '../extensions/index.js'; /** * Given matrix, a rectangular matrix of integers, * just add up all the values that don't appear below a "0". * * @param {Array<Array>} matrix * @return {Number} * * @example * matrix = [ * [0, 1, 1, 2], * [0, 5, 0, 0], * [2, 0, 3, 3] * ] * * The result should be 9 */ export default function getMatrixElementsSum(matrix) { let result = 0; for (let line = 0; line < matrix.length; line += 1) { for (let el = 0; el < matrix[line].length; el += 1) { if (typeof matrix[line - 1] === 'undefined' || matrix[line - 1][el] !== 0) { result += matrix[line][el]; } } } return result; }
#!/bin/bash rm -f result-base cp result-base.template result-base export submissions_root="/ITSP-experiments/dataset-base" export test_dir=${submissions_root}/test export prog_name="prog" export result_file=$(pwd)/result-base export wrapper_name="wrapper-repair" export repair_src_name="repair" export ref_dir="ref" export repair_makefile="Makefile.repair" export ww_session_prefix="ww-session" export ga_session_prefix="ga-session" export ag_session_prefix="ag-session" export pr_session_prefix="pr-session" export succeed_file="succeed" export fail_file="failure" export angelix_pid_log_file="angelix_pid.log" export test_angelix_pid_log_file="test_angelix_pid.log" # prophet files export pr_revision_file="revision.log" export pr_run_conf_file="run.conf" export pr_config_file="prophet.conf" export pr_test_script="test.py" export pr_run_script="run.sh" export pr_workdir="workdir" # angelix params export tool_timeout=900 export klee_timeout=300 export klee_max_forks=400 export solver_timeout=600 export synthesis_timeout=300000 export test_timeout=10 function safe_pushd () { local target=$1 if pushd $target &> /dev/null; then return 0 else echo "[*] failed to push to $target" return 1 fi } export -f safe_pushd function safe_rm () { local flag=$1 local target=$2 if [[ $target =~ ^[a-zA-Z0-9][a-zA-Z0-9/\_\-]*$ ]]; then rm "$flag" "$target" && return 0 else echo "[Error] Did not remove $target" return 1 fi } export -f safe_rm function write_to_file () { local file=$1 local line=$2 echo -e "$line" >> $file } export -f write_to_file function create_pr_test_script () { local prob_id=$1 rm -f ${pr_test_script} && touch ${pr_test_script} cat <<EOF >> ${pr_test_script} #!/usr/bin/env python from sys import argv from os import system import getopt if __name__ == "__main__": if len(argv) < 4: print "Usage: php-tester.py <src_dir> <test_dir> <work_dir> [cases]"; exit(1); opts, args = getopt.getopt(argv[1:], "p:"); profile_dir = ""; for o, a in opts: if o == "-p": profile_dir = a; src_dir = args[0]; test_dir = args[1]; work_dir = args[2]; if profile_dir == "": cur_dir = src_dir; else: cur_dir = profile_dir; if len(args) > 3: ids = args[3:]; for i in ids: cmd = "timeout 1 " + cur_dir + "/prog < " + test_dir + "/in.${prob_id}."+ i + ".txt 1> __out"; ret = system(cmd); if (ret == 0): cmd = "diff -ZB __out " + test_dir + "/out.${prob_id}." + i + ".txt 1> /dev/null"; ret = system(cmd); if (ret == 0): print i, system("rm -rf __out"); print; EOF chmod +x ${pr_test_script} } export -f create_pr_test_script function create_revision_log () { local prob_id=$1 local prog_id=$2 local inst=$3 local basic_test_script=$4 poses=($(grep -P "^\tp" ${basic_test_script} | cut -d"|" -f1 | cut -d"<" -f2 | sed -e "s/.txt//g" | sed -e "s?test/in.${prob_id}.??g" | tr -d "\n")) negs=($(grep -P "^\tn" ${basic_test_script} | cut -d"|" -f1 | cut -d"<" -f2 | sed -e "s/.txt//g" | sed -e "s?test/in.${prob_id}.??g" | tr -d "\n")) rm -f ${pr_revision_file} &> /dev/null touch ${pr_revision_file} &> /dev/null write_to_file ${pr_revision_file} "-" write_to_file ${pr_revision_file} "-" write_to_file ${pr_revision_file} "Diff Cases: Tot ${#negs[@]}" negs_line="${negs[@]}" write_to_file ${pr_revision_file} "${negs_line}" write_to_file ${pr_revision_file} "Positive Cases: Tot ${#poses[@]}" poses_line="${poses[@]}" write_to_file ${pr_revision_file} "${poses_line}" } export -f create_revision_log function create_pr_run_conf () { local src_dir=$1 rm -f ${pr_run_conf_file} &> /dev/null touch ${pr_run_conf_file} &> /dev/null write_to_file ${pr_run_conf_file} "revision_file=${pr_revision_file}" write_to_file ${pr_run_conf_file} "src_dir=${src_dir}" write_to_file ${pr_run_conf_file} "test_dir=test" write_to_file ${pr_run_conf_file} "build_cmd=${PROPHET_TOOLS_DIR}/simple-build.py" write_to_file ${pr_run_conf_file} "test_cmd=${pr_test_script}" write_to_file ${pr_run_conf_file} "localizer=profile" write_to_file ${pr_run_conf_file} "single_case_timeout=1" } export -f create_pr_run_conf function create_pr_Makefile () { local prog_id=$1 rm -f Makefile touch Makefile write_to_file Makefile "prog: ${prog_id}.c" write_to_file Makefile "$(printf "\tgcc -std=c99 -c ${prog_id}.c -o ${prog_id}.o")" write_to_file Makefile "$(printf "\tgcc -std=c99 -o ${prog_name} ${prog_id}.o -lm")" } export -f create_pr_Makefile function create_gp_Makefile () { local prog_id=$1 rm -f Makefile touch Makefile write_to_file Makefile "all:" write_to_file Makefile "$(printf "\tgcc -std=c99 -o %s %s" "${prog_name}" "${prog_id}.c -lm")" } export -f create_gp_Makefile function create_repair_Makefile () { rm -f ${repair_makefile} touch ${repair_makefile} write_to_file ${repair_makefile} "all:" write_to_file ${repair_makefile} "$(printf "\tgcc -std=c99 -o repair repair.c -lm")" } export -f create_repair_Makefile function create_ag_Makefile() { local flags=$1 rm -f Makefile touch Makefile write_to_file Makefile "CC=gcc" write_to_file Makefile "CFLAGS=${flags}" write_to_file Makefile "" write_to_file Makefile "all:" write_to_file Makefile "$(printf "\t\$(CC) \$(CFLAGS) -c %s -o %s" "${wrapper_name}.c" "${wrapper_name}.o")" write_to_file Makefile "$(printf "\t\$(CC) \$(CFLAGS) -c %s -o %s" "${repair_src_name}.c" "${repair_src_name}.o")" write_to_file Makefile "$(printf "\t\$(CC) \$(CFLAGS) %s %s -o %s -lm" "${wrapper_name}.o" "${repair_src_name}.o" "${wrapper_name}")" write_to_file Makefile "" write_to_file Makefile "clean:" write_to_file Makefile "$(printf "\trm -f %s %s %s" "${wrapper_name}" "${wrapper_name}.o" "${repair_src_name}.o")" } export -f create_ag_Makefile function create_gp_ww_config() { local prog_id=$1 local inst=$2 local test_script=$3 local pos_test=$4 local neg_test=$5 local gp_config_file="gp-ww-${inst}.config" rm -f ${gp_config_file} &> /dev/null touch ${gp_config_file} &> /dev/null write_to_file ${gp_config_file} "$(printf "%sprogram %s.c" "--" "${prog_id}")" write_to_file ${gp_config_file} "$(printf "%scompiler gcc" "--")" write_to_file ${gp_config_file} "$(printf "%scompiler-command __COMPILER_NAME__ -o __EXE_NAME__ __SOURCE_NAME__ __COMPILER_OPTIONS__ -lm 2> /dev/null" "--")" write_to_file ${gp_config_file} "$(printf "%ssearch ww" "--")" write_to_file ${gp_config_file} "--no-rep-cache" write_to_file ${gp_config_file} "--no-test-cache" # write_to_file ${gp_config_file} "--fault-scheme uniform" write_to_file ${gp_config_file} "--add-guard" write_to_file ${gp_config_file} "$(printf "%slabel-repair" "--")" write_to_file ${gp_config_file} "$(printf "%spos-tests ${pos_test}" "--")" write_to_file ${gp_config_file} "$(printf "%sneg-tests ${neg_test}" "--")" write_to_file ${gp_config_file} "--test-script ./${test_script}" echo ${gp_config_file} } export -f create_gp_ww_config function create_gp_ga_config () { local prog_id=$1 local inst=$2 local test_script=$3 local pos_test=$4 local neg_test=$5 local gp_config_file="gp-ga-${inst}.config" rm -f ${gp_config_file} &> /dev/null touch ${gp_config_file} &> /dev/null write_to_file ${gp_config_file} "$(printf "%sprogram %s.c" "--" "${prog_id}")" write_to_file ${gp_config_file} "$(printf "%scompiler gcc" "--")" write_to_file ${gp_config_file} "$(printf "%scompiler-command __COMPILER_NAME__ -o __EXE_NAME__ __SOURCE_NAME__ __COMPILER_OPTIONS__ -lm 2> /dev/null" "--")" write_to_file ${gp_config_file} "$(printf "%stest-command __TEST_SCRIPT__ __EXE_NAME__ __TEST_NAME__ __PORT__ __SOURCE_NAME__ __FITNESS_FILE__ 2> /dev/null" "--")" write_to_file ${gp_config_file} "$(printf "%ssearch ga" "--")" write_to_file ${gp_config_file} "--no-rep-cache" write_to_file ${gp_config_file} "--no-test-cache" # write_to_file ${gp_config_file} "--fault-scheme uniform" write_to_file ${gp_config_file} "$(printf "%slabel-repair" "--")" write_to_file ${gp_config_file} "$(printf "%spos-tests ${pos_test}" "--")" write_to_file ${gp_config_file} "$(printf "%sneg-tests ${neg_test}" "--")" write_to_file ${gp_config_file} "$(printf "%sseed 560680701" "--")" write_to_file ${gp_config_file} "$(printf "%sminimization" "--")" # write_to_file ${gp_config_file} "$(printf "%sswapp 0.0" "--")" # write_to_file ${gp_config_file} "$(printf "%sappp 0.5" "--")" # write_to_file ${gp_config_file} "$(printf "%sdelp 0.5" "--")" # write_to_file ${gp_config_file} "$(printf "%scrossp 0.0" "--")" write_to_file ${gp_config_file} "$(printf "%spopsize 20" "--")" write_to_file ${gp_config_file} "$(printf "%sgenerations 10" "--")" write_to_file ${gp_config_file} "$(printf "%sallow-coverage-fail" "--")" write_to_file ${gp_config_file} "--test-script ./${test_script}" echo ${gp_config_file} } export -f create_gp_ga_config function prepare_tests() { local prob_id=$1 rm -rf test mkdir -p test cp ${test_dir}/in.${prob_id}.* test cp ${test_dir}/out.${prob_id}.* test } function is_positive_test() { local prog=$1 local in_file=$2 local out_file=$3 local result result=$(timeout 1s ${prog} < ${in_file} | diff -ZB ${out_file} -) if [[ $result == "" ]]; then echo 0 else echo 1 fi } function create_basic_test_script() { local prog_id=$1 local script=$2 local __num_of_pos=$3 local __num_of_neg=$4 rm -f ${script} touch ${script} write_to_file ${script} "#!/bin/bash" write_to_file ${script} "# \$1 = EXE" write_to_file ${script} "# \$2 = test name" write_to_file ${script} "# \$3 = port" write_to_file ${script} "# \$4 = source name" write_to_file ${script} "# \$5 = single-fitness-file name" write_to_file ${script} "# exit 0 = success" write_to_file ${script} "ulimit -t 1" write_to_file ${script} "echo \$1 \$2 \$3 \$4 \$5 >> testruns.txt" write_to_file ${script} "case \$2 in" pos_count=0 neg_count=0 local test_id for in_file in test/in.*; do local out_file=$(echo ${in_file} | sed -e "s/in/out/g") is_pos=$(is_positive_test "./${prog_name}" ${in_file} ${out_file}) if [[ ${is_pos} == 0 ]]; then pos_count=$((pos_count+1)) test_id=$(printf "p%s" ${pos_count}) else neg_count=$((neg_count+1)) test_id=$(printf "n%s" ${neg_count}) fi write_to_file ${script} "$(printf "\t%s) \$1 < %s | diff -ZB %s - &> /dev/null && exit 0 ;;" "${test_id}" "${in_file}" "${out_file}")" done write_to_file ${script} "esac" write_to_file ${script} "exit 1" chmod +x ${script} eval $__num_of_pos=${pos_count} eval $__num_of_neg=${neg_count} } function create_ag_test_script() { local basic_test_script=$1 local script=$2 rm -f ${script} touch ${script} ######################################### # collect positive and negative tests ######################################### IFS_BAK=${IFS} IFS=" " poses=($(grep -P "^\tp" ${basic_test_script})) negs=($(grep -P "^\tn" ${basic_test_script})) IFS=${IFS_BAK} write_to_file ${script} "#!/bin/bash" write_to_file ${script} "# \$1 = test name" write_to_file ${script} "# exit 0 = success" write_to_file ${script} "pid_log_file=${test_angelix_pid_log_file}" write_to_file ${script} "echo \"[${script}] pwd: \$(pwd)\"" write_to_file ${script} "# update ANGELIX_RUN (add timeout)" write_to_file ${script} "if [[ ! -z \${ANGELIX_RUN} ]]; then" write_to_file ${script} " if [[ \${ANGELIX_RUN} == \"angelix-run-test\" ]]; then" write_to_file ${script} " ANGELIX_RUN=\"timeout 2 angelix-run-test\"" write_to_file ${script} " fi" write_to_file ${script} " if [[ \${ANGELIX_RUN} == \"angelix-run-klee\" ]]; then" write_to_file ${script} " ANGELIX_RUN=\"timeout ${klee_timeout} angelix-run-klee\"" write_to_file ${script} " fi" write_to_file ${script} "fi" write_to_file ${script} "case \$1 in" for idx in $(seq 0 $((${#poses[@]} - 1))); do line=$(echo ${poses[$idx]} | sed -e "s?\$1?\${ANGELIX_RUN:-timeout 1} ./${wrapper_name}?g") line=$(echo $line | sed -e "s?test/?../../test/?g") line=$(echo $line | sed -e "s?| diff -ZB??g") line=$(echo $line | sed -e "s?- \&\&?\&\&?g") write_to_file ${script} "$(printf "\t$line")" done for idx in $(seq 0 $((${#negs[@]} - 1))); do line=$(echo ${negs[$idx]} | sed -e "s?\$1?\${ANGELIX_RUN:-timeout 1} ./${wrapper_name}?g") line=$(echo $line | sed -e "s?test/?../../test/?g") line=$(echo $line | sed -e "s?| diff -ZB??g") line=$(echo $line | sed -e "s?- \&\&?\&\&?g") write_to_file ${script} "$(printf "\t$line")" done write_to_file ${script} "esac" write_to_file ${script} "exit 1" chmod +x ${script} } export -f create_ag_test_script function create_gp_test_script () { local prog_id=$1 local basic_test_script=$2 local script=$3 rm -f ${script} touch ${script} ######################################### # collect positive and negative tests ######################################### IFS_BAK=${IFS} IFS=" " poses=($(grep -P "^\tp" ${basic_test_script})) negs=($(grep -P "^\tn" ${basic_test_script})) IFS=${IFS_BAK} write_to_file ${script} "#!/bin/bash" write_to_file ${script} "# \$1 = EXE" write_to_file ${script} "# \$2 = test name" write_to_file ${script} "# \$3 = port" write_to_file ${script} "# \$4 = source name" write_to_file ${script} "# \$5 = single-fitness-file name" write_to_file ${script} "# exit 0 = success" write_to_file ${script} "echo \$1 \$2 \$3 \$4 \$5 >> testruns.txt" write_to_file ${script} "case \$2 in" # positive tests for idx in $(seq 0 $((${#poses[@]} - 1))); do line=$(echo ${poses[$idx]}) pos_test_id=$(echo $line | cut -d")" -f1) pos_test_cmd=$(echo $line | cut -d")" -f2) write_to_file ${script} "$(printf "\t${pos_test_id}) timeout 1 ${pos_test_cmd}")" done # negative test for idx in $(seq 0 $((${#negs[@]} - 1))); do line=$(echo ${negs[$idx]}) test_id=$(echo $line | cut -d")" -f1) test_cmd=$(echo $line | cut -d")" -f2) write_to_file ${script} "$(printf "\t${test_id}) timeout 1 ${test_cmd}")" done write_to_file ${script} "esac" write_to_file ${script} "exit 1" chmod +x ${script} } export -f create_gp_test_script function create_clean_script() { local script_name="clean" rm -f ${script_name} touch ${script_name} write_to_file ${script_name} "rm -f *.cache" write_to_file ${script_name} "rm -rf *.fitness" write_to_file ${script_name} "rm -f coverage.*" write_to_file ${script_name} "rm -f repair.debug.*" write_to_file ${script_name} "rm -f repair.sanity.c" write_to_file ${script_name} "rm -f repair.c" write_to_file ${script_name} "rm -f coverage" write_to_file ${script_name} "rm -f testruns.txt" write_to_file ${script_name} "rm -rf Minimization_Files" chmod +x ${script_name} } function run_gp () { local gp_config_file=$1 local gp_log_file=$2 local __found_repair=$3 local __gp_time=$4 eval $__gp_time=0 ./clean START_TIME=$SECONDS timeout ${tool_timeout} repair ${gp_config_file} &> /dev/null ELAPSED_TIME=$(($SECONDS - $START_TIME)) eval $__gp_time=$(($SECONDS - $START_TIME)) rm -f ${gp_log_file} &> /dev/null mv repair.debug.* ${gp_log_file} &> /dev/null # check to see if we've generated a repair, pass if we do if [ -e repair.c ] then eval $__found_repair=0 else eval $__found_repair=1 fi } export -f run_gp function run_prophet () { local __found_repair=$1 local __pr_time=$2 local prophet_log=$3 eval $__pr_time=0 cat <<EOF >> ${pr_config_file} ${pr_run_conf_file} -r ${pr_workdir} -consider-all -feature-para ${PROPHET_FEATURE_PARA} -replace-ext -cond-ext EOF START_TIME=$SECONDS timeout ${tool_timeout} safe-prophet `cat ${pr_config_file}` &> ${prophet_log} eval $__pr_time=$(($SECONDS - $START_TIME)) # hack: workaround for the docker problem if [[ -e workdir/profile_localization.res && $(cat workdir/profile_localization.res | wc -l) == 0 ]]; then rm -rf workdir START_TIME=$SECONDS timeout ${tool_timeout} safe-prophet `cat ${pr_config_file}` &> ${prophet_log} eval $__pr_time=$(($SECONDS - $START_TIME)) fi # check to see if we've generated a repair, pass if we do if [ -s __fixed*.c ] then echo "[pr] found a repair" cp __fixed*.c repair.c eval $__found_repair=0 else echo "[pr] failed to find a repair" eval $__found_repair=1 fi } export -f run_prophet function run_angelix () { local __guard_ok=$1 local __tests_ok=$2 local __found_repair=$3 local __ag_time=$4 local found_gp_repair=$5 local ag_test_script=$6 local ag_config_file=$7 local gp_repair_dir=$8 local angelix_log=$9 eval $__guard_ok=1 eval $__tests_ok=1 eval $__found_repair=1 eval $__ag_time=0 if [[ ${found_gp_repair} == 0 ]]; then # collect lines lines=($(grep -n "if (1 != 0)\|if (1 == 0)" ${gp_repair_dir}/${repair_src_name}.c | cut -d':' -f1)) if [[ -z $lines ]]; then eval $__guard_ok=1 && return else eval $__guard_ok=0 fi else eval $__guard_ok=0 fi # collect positive and negative tests pos_tests=($(grep -P "^\tp" ${ag_test_script} | cut -d$'\t' -f2 | cut -d')' -f1)) neg_tests=($(grep -P "^\tn" ${ag_test_script} | cut -d$'\t' -f2 | cut -d')' -f1)) if [[ -z ${pos_tests} ]]; then eval $__tests_ok=1 # && return else eval $__tests_ok=0 fi # prepare configuration file rm -f ${ag_config_file} touch ${ag_config_file} cat <<EOF >> ${ag_config_file} ${gp_repair_dir} ${repair_src_name}.c ${ag_test_script} ${pos_tests[@]} ${neg_tests[@]} \ --golden ref --defect if-conditions assignments loop-conditions \ --synthesis-levels alternatives integer-constants variables extended-arithmetic extended-logic extended-inequalities mixed-conditional conditional-arithmetic --use-nsynth \ --synthesis-func-params --synthesis-global-vars --synthesis-used-vars \ --init-uninit-vars \ --klee-ignore-errors --ignore-infer-errors \ --klee-max-forks ${klee_max_forks} --klee-max-depth 200 --max-angelic-paths 10 \ --klee-timeout ${klee_timeout} --synthesis-timeout ${synthesis_timeout} \ --test-timeout ${test_timeout} --timeout ${tool_timeout} --verbose EOF if ! [[ -e ${ag_config_file} ]]; then echo "[AG] ${ag_config_file} does not exist" && eval $__found_repair=1 && return fi rm -f *.patch rm -f ${angelix_log} local angelix_timeout=$((tool_timeout+10)) ulimit -n 4000 # increase the maximum number of open file descriptors START_TIME=$SECONDS timeout ${angelix_timeout} angelix `cat ${ag_config_file}` &> ${angelix_log} & pid=$! echo $pid > ${angelix_pid_log_file} wait $pid eval $__ag_time=$(($SECONDS - $START_TIME)) grep -q "No negative test exists" ${angelix_log} && echo "[AG] No negative test exists" && eval $__found_repair=1 && return # check to see if we've generated a repair, pass if we do if [ -s *.patch ] then eval $__found_repair=0 else eval $__found_repair=1 fi } export -f run_angelix function create_extract_source_awk() { local awk_file=$1 rm -f ${awk_file} cat <<EOF >> ${awk_file} BEGIN { skip=1 } /WRAPPER CODE BEGINS/ || /DUMMY CODE BEGINS/ { skip=0; } skip==1 { if (\$0 !~ /__dummy_var/ && \$0 !~ /\/\* missing proto \*\//) { sub("^main_internal", "main", \$0); gsub("sprintf \(out_buffer \+ strlen \(out_buffer\),", "printf (", \$0); print } } /WRAPPER CODE ENDS/ || /DUMMY CODE ENDS/ { skip=1; } END {} EOF } export -f create_extract_source_awk function create_extract_include_awk() { local awk_file=$1 rm -f ${awk_file} cat <<EOF >> ${awk_file} BEGIN {} /#include</ { print } END {} EOF } export -f create_extract_include_awk function create_remove_conflict_decl_awk() { local awk_file=$1 rm -f ${awk_file} cat <<EOF >> ${awk_file} BEGIN {} !/\/\* missing proto \*\// && !/^extern/ { print } END {} EOF } export -f create_remove_conflict_decl_awk function create_remove_dummy_var_awk () { local awk_file=$1 rm -f ${awk_file} cat <<EOF >> ${awk_file} BEGIN {} !/__dummy_var/ { print } END {} EOF } export -f create_remove_dummy_var_awk function create_add_p1_awk () { local awk_file=$1 rm -f ${awk_file} cat <<EOF >> ${awk_file} BEGIN {} /^case \\\$2 in/ { print print " p1) exit 0 ;;" } !/^case \\\$2 in/ { print } END {} EOF } export -f create_add_p1_awk function create_wrapper_file() { local org_file=$1 if [[ ! ( -f ${org_file} ) ]]; then echo "${org_file} does not exist" return fi rm -f ${wrapper_name}.c touch ${wrapper_name}.c cat <<EOF >> ${wrapper_name}.c #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <ctype.h> #ifndef ANGELIX_OUTPUT #define ANGELIX_OUTPUT(type, expr, id) expr #endif FILE *out_file; char out_buffer[1000]; int main_internal (void); char *trim_trail_ws(char *str) { char *end; end = str + strlen(str) - 1; while(end > str && isspace(*end)) end--; *(end+1) = 0; return str; } int compare_strings(char a[], char b[]) { int c = 0; while (a[c] == b[c]) { if (a[c] == '\0' || b[c] == '\0') break; c++; } if ((a[c] == '\0') && (b[c] == '\0')) { return 0; } else { return -1; } } int main(int argc, char *argv[]) { int max = 100; char buf1[max]; char buf2[max]; FILE *file; char *cur; printf("[wrapper] test-repair started\n"); main_internal(); printf("\n[wrapper] repair_main done\n"); fflush(stdout); out_file = fopen("./out", "w"); if (out_file == NULL) { printf("failed to open out\n"); fflush(stdout); exit(-1); } fprintf(out_file, "%s", out_buffer); fclose(out_file); /* diff */ file = fopen("./out", "r"); cur = buf1; while (fgets(cur, max, file) != NULL) { cur = buf1 + strlen(buf1); } fclose(file); file = fopen(argv[1], "r"); cur = buf2; while (fgets(cur, max, file) != NULL) { cur = buf2 + strlen(buf2); } fclose(file); trim_trail_ws(buf1); trim_trail_ws(buf2); if (compare_strings(buf1, buf2) == 0) { printf("%d\n", ANGELIX_OUTPUT(int, 0, "result")); printf("Pass\n"); fflush(stdout); return 0; } else { printf("%d\n", ANGELIX_OUTPUT(int, 1, "result")); printf("Fails\n"); fflush(stdout); return 1; } } EOF rm -f ${repair_src_name}.c touch ${repair_src_name}.c cat <<EOF >> ${repair_src_name}.c // WRAPPER CODE BEGINS #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #ifndef ANGELIX_OUTPUT #define ANGELIX_OUTPUT(type, expr, id) expr #endif char out_buffer[1000]; // WRAPPER CODE ENDS EOF cat ${org_file} >> ${repair_src_name}.c indent_option="--line-length1000" indent ${indent_option} ${repair_src_name}.c sed -i.bak -E "s/^[ \t]+//g" ${repair_src_name}.c sed -i.bak -e "s/^main (void)/main_internal (void)/g" ${repair_src_name}.c sed -i.bak -e "s/^main ()/main_internal ()/g" ${repair_src_name}.c sed -i.bak -e "s/^printf (/sprintf (out_buffer + strlen(out_buffer), /g" ${repair_src_name}.c local adjust_src_awk_file="adjust-src.awk" local new_src_file="new_src.c" create_remove_conflict_decl_awk ${adjust_src_awk_file} awk -f ${adjust_src_awk_file} ${repair_src_name}.c > ${new_src_file} mv ${new_src_file} ${repair_src_name}.c indent ${indent_option} ${repair_src_name}.c } export -f create_wrapper_file function diagnose_gp_repair_failure() { local log_file=$1 local __gp_ok=$2 local __fail_reason=$3 grep -q "sanity check failed" ${log_file} && eval $__gp_ok=1 && \ eval $__fail_reason="'sanity check failed.'" && return grep -q "unexpected coverage result" ${log_file} && eval $__gp_ok=1 && \ eval $__fail_reason="'unexpected coverage result'" && return eval $__fail_reason="'no gp rep'" && eval $__gp_ok=0 && return } export -f diagnose_gp_repair_failure function diagnose_ag_repair_failure() { local why_fail="" local found_gp_repair=$1 local angelix_log=$2 if [[ ${found_gp_repair} == 1 ]]; then echo "no gp rep" && return fi grep -q "No non-error paths explored" ${angelix_log} \ && echo "No non-error paths explored" && return grep -q "synthesis failed" ${angelix_log} && echo "synthesis failed" && return grep -q "synthesis returned non-zero code" ${angelix_log} && echo "synthesis returned non-zero" && return grep -q "found 0 angelic paths" ${angelix_log} && echo "no angelic path" && return grep -q "PermissionError" ${angelix_log} && echo "PermissionError" && return echo "other ag error" && return } export -f diagnose_ag_repair_failure function repair_in_parallel () { local prob_id=$1 local prog_id=$2 local inst=$3 local basic_test_script=$4 local ww_test_script=$5 local num_of_pos=$6 local num_of_neg=$7 local repair_mode=$8 case ${repair_mode} in pr) local src_dir="src" if [[ ${skip_pr} != 0 ]]; then local session_dir="${pr_session_prefix}-${inst}" rm -rf ${session_dir} && mkdir -p ${session_dir} cp ${basic_test_script} ${session_dir} cp -r test ${session_dir} if safe_pushd "${session_dir}"; then rm -rf ${src_dir} && mkdir -p ${src_dir} cp ../${prog_id}.c ${src_dir} if safe_pushd "${src_dir}"; then create_pr_Makefile ${prog_id} popd &> /dev/null fi create_pr_test_script ${prob_id} create_revision_log ${prob_id} ${prog_id} ${inst} ${basic_test_script} create_pr_run_conf ${src_dir} found_pr_repair=1 log_file="prophet-${inst}.log" run_prophet found_pr_repair pr_time ${log_file} popd &> /dev/null fi if [[ $found_pr_repair == 0 ]]; then echo "[pr] repair succeeded" touch ${session_dir}/${succeed_file} return 1 else echo "[pr] repair failed" touch ${session_dir}/${fail_file} return 0 fi else echo "[pr] skips" return 0 fi ;; ww) if [[ ${skip_gp_ww} != 0 ]]; then local session_dir="${ww_session_prefix}-${inst}" rm -rf ${session_dir} mkdir -p ${session_dir} cp ${prog_id}.c ${session_dir} cp clean ${session_dir} cp ${basic_test_script} ${session_dir} cp -r test ${session_dir} if safe_pushd "${session_dir}"; then create_gp_test_script ${prog_id} ${basic_test_script} ${ww_test_script} gp_config_file=$(create_gp_ww_config \ ${prog_id} ${inst} ${ww_test_script} ${num_of_pos} ${num_of_neg}) log_file="gp-ww-${inst}.log" gp_ok=0 found_gp_repair=1 run_gp ${gp_config_file} ${log_file} found_gp_repair gp_ww_time if [[ $found_gp_repair == 1 ]]; then diagnose_gp_repair_failure ${log_file} gp_ok fail_reason touch ${fail_file} else touch ${succeed_file} fi popd &> /dev/null fi if [[ $found_gp_repair == 0 ]]; then echo "[ww] repair succeeded" return 1 else echo "[ww] repair failed" return 0 fi else echo "[ww] skips" return 0 fi ;; ga) if [[ ${skip_gp_ga} != 0 ]]; then local session_dir="${ga_session_prefix}-${inst}" rm -rf ${session_dir} mkdir -p ${session_dir} cp ${prog_id}.c ${session_dir} cp clean ${session_dir} cp ${basic_test_script} ${session_dir} cp -r test ${session_dir} if safe_pushd "${session_dir}"; then create_gp_test_script ${prog_id} ${basic_test_script} ${ww_test_script} local ga_test_script="test-ga-${inst}.sh" if [[ ${num_of_pos} == 0 ]]; then local add_p1_awk_file="add_p1.awk" create_add_p1_awk ${add_p1_awk_file} awk -f ${add_p1_awk_file} ${ww_test_script} > ${ga_test_script} chmod +x ${ga_test_script} gp_config_file=$(create_gp_ga_config \ ${prog_id} ${inst} ${ga_test_script} 1 ${num_of_neg}) else cp ${ww_test_script} ${ga_test_script} gp_config_file=$(create_gp_ga_config \ ${prog_id} ${inst} ${ga_test_script} ${num_of_pos} ${num_of_neg}) fi log_file="gp-ga-${inst}.log" gp_ok=0 found_gp_repair=1 run_gp ${gp_config_file} ${log_file} found_gp_repair gp_ga_time if [[ $found_gp_repair == 1 ]]; then diagnose_gp_repair_failure ${log_file} gp_ok fail_reason touch ${fail_file} else touch ${succeed_file} fi popd &> /dev/null fi if [[ $found_gp_repair == 0 ]]; then echo "[ga] repair succeeded" return 1 else echo "[ga] repair failed" return 0 fi else echo "[ga] skips" return 0 fi ;; ag) if [[ ${skip_ag} != 0 ]]; then local session_dir="${ag_session_prefix}-${inst}" rm -rf ${session_dir} mkdir -p ${session_dir} cp ${prog_id}.c ${session_dir} cp ${prog_id}-${inst}.c ${session_dir} cp clean ${session_dir} cp ${basic_test_script} ${session_dir} cp -r test ${session_dir} if safe_pushd "${session_dir}"; then repair_file="${prog_id}-${inst}.c" if ! [[ -e ${repair_file} ]]; then echo "${repair_file} does not exist" fi if [[ -e ${repair_file} ]]; then safe_rm "-rf" ${gp_repair_dir} && mkdir -p ${gp_repair_dir} safe_rm "-rf" ${ref_dir} && mkdir -p ${ref_dir} ag_test_script="test-angelix-${inst}.sh" create_ag_test_script ${basic_test_script} ${ag_test_script} if safe_pushd "${gp_repair_dir}"; then create_ag_Makefile "-std=c99" create_wrapper_file "../${repair_file}" popd &> /dev/null fi if safe_pushd "${ref_dir}"; then create_ag_Makefile "-std=c99" create_wrapper_file "../../../Main.c" popd &> /dev/null fi guard_ok=1 tests_ok=1 found_ag_repair=1 found_gp_repair=1 log_file="angelix-${inst}.log" run_angelix guard_ok tests_ok found_ag_repair ag_start_time \ ${found_gp_repair} ${ag_test_script} ${ag_config_file} \ ${gp_repair_dir} ${log_file} if [[ ${found_ag_repair} == 0 ]]; then touch ${succeed_file} else touch ${fail_file} fi fi popd &> /dev/null fi if [[ ${found_ag_repair} == 0 ]]; then echo "[ag] repair succeeded" return 1 else echo "[ag] repair failed" return 0 fi else echo "[ag] skips" return 0 fi ;; esac } export -f repair_in_parallel function handle () { local lab_id=$1 local prob_id=$2 local prog_id=$3 local skip_ag=$4 local skip_gp_ww=$5 local skip_gp_ga=$6 local inst=0 local num_of_pos=-1 local num_of_neg=-1 if safe_pushd "${prog_id}"; then cp ${prog_id}.c ${prog_id}.c.org popd &> /dev/null fi for trial in $(seq 0 1); do local repair_done=1 handle_instance $1 $2 $3 $4 $5 $6 $inst repair_done num_of_pos num_of_neg echo "repair done at ${inst}: ${repair_done}" if [[ $repair_done == 1 ]]; then break fi inst=$((inst+1)) done } function handle_instance () { local lab_id=$1 local prob_id=$2 local prog_id=$3 local skip_ag=$4 local skip_gp_ww=$5 local skip_gp_ga=$6 local inst=$7 local __repair_done=$8 local __num_of_pos=${9} local __num_of_neg=${10} ag_start_time=0 gp_ww_time=0 gp_ga_time=0 ag_refine_time=0 local repair_ok=1 eval ${__repair_done}=1 rm -rf /tmp/* if safe_pushd "${prog_id}"; then echo "[*] handle ${lab_id}-${prob_id}-${prog_id}-${inst}" export basic_test_script="test-${inst}.sh" export ww_test_script="test-ww-${inst}.sh" export ag_test_script="test-angelix-${inst}.sh" export ag_config_file="ag-${inst}.config" export gp_repair_dir="gp-repaired-${inst}" for trial in $(seq 0 0); do # break in the loop enables early return cp ${prog_id}.c ${prog_id}-org-${inst}.c cp ${prog_id}.c repair.sanity.c local adjust_src_awk_file="rem-dummy-var.awk" local new_src_file="new_src.c" create_remove_dummy_var_awk ${adjust_src_awk_file} awk -f ${adjust_src_awk_file} repair.sanity.c > ${new_src_file} mv ${new_src_file} repair.sanity.c adjust_src_awk_file="rem-conflic-decl.awk" create_remove_conflict_decl_awk ${adjust_src_awk_file} awk -f ${adjust_src_awk_file} repair.sanity.c > ${new_src_file} mv ${new_src_file} repair.sanity.c cp repair.sanity.c repair.sanity-${inst}.c cp repair.sanity.c ${prog_id}.c cp ${prog_id}.c ${prog_id}-${inst}.c create_gp_Makefile ${prog_id} rm -f ${prog_name} && make &> /dev/null if [[ ! -f ${prog_name} ]]; then echo "Failed to compile" gp_ok=1 found_gp_repair=1 guard_ok="" tests_ok="" found_ag_repair="" fail_reason="Failed to compile" break else create_clean_script prepare_tests ${prob_id} create_basic_test_script ${prog_id} ${basic_test_script} num_of_pos num_of_neg ###################################################### # Check if there is a negative test ###################################################### IFS_BAK=${IFS} IFS=" " negs=($(grep -P "^\tn" ${basic_test_script} | sed -e 's/^\tn[0-9]*)//g')) IFS=${IFS_BAK} if [[ ${#negs[@]} == 0 ]]; then echo "No negative test any more" repair_ok=0 break fi repair_ok=1 found_gp_repair_ww="" found_gp_repair_ga="" found_ag_repair="" found_pr_repair="" local parallel_log_file="parallel-${inst}.log" START_TIME=$SECONDS parallel --halt 2 repair_in_parallel \ ${prob_id} ${prog_id} ${inst} ${basic_test_script} ${ww_test_script} \ ${num_of_pos} ${num_of_neg} \ ::: "ww" "ga" "ag" "pr" &> ${parallel_log_file} time_parallel=$(($SECONDS - $START_TIME)) ######################### # kill orphan processes ######################### for trial in $(seq 0 1); do for log_file in $(find ./ -name ${angelix_pid_log_file}); do pid=$(cat ${log_file}) kill -9 -$pid &> /dev/null done for log_file in $(find ./ -name ${test_angelix_pid_log_file}); do if [[ ${log_file} == *"/backend/"* ]]; then for pid in $(cat ${log_file}); do pgid=$(ps -eo pid,pgid | grep -e "[[:space:]]${pid}[[:space:]]" | awk {'print $2'}) if [[ $pgid != "" ]]; then kill -9 -${pgid} fi done fi done orphan_pids=$(ps -o ppid,pid,comm,args -www -C klee | grep -e "[[:space:]]1[[:space:]]" | grep ${wrapper_name} | awk {'print $2'}) for pid in ${orphan_pids}; do if [[ $pid != "" ]]; then kill -9 $pid fi done sleep 1 done if [ -e "${ag_session_prefix}-${inst}/${succeed_file}" ]; then repair_ok=0 found_ag_repair=0 echo "[ag] repair succeeded" elif [ -e "${ww_session_prefix}-${inst}/${succeed_file}" ]; then repair_ok=0 found_gp_repair_ww=0 echo "[ww] repair succeeded" elif [ -e "${ga_session_prefix}-${inst}/${succeed_file}" ]; then repair_ok=0 found_gp_repair_ga=0 echo "[ga] repair succeeded" elif [ -e "${pr_session_prefix}-${inst}/${succeed_file}" ]; then repair_ok=0 found_pr_repair=0 echo "[pr] repair succeeded" fi [ -e "${ww_session_prefix}-${inst}/${fail_file}" ] && found_gp_repair_ww=1 [ -e "${ga_session_prefix}-${inst}/${fail_file}" ] && found_gp_repair_ga=1 [ -e "${ag_session_prefix}-${inst}/${fail_file}" ] && found_ag_repair=1 [ -e "${pr_session_prefix}-${inst}/${fail_file}" ] && found_pr_repair=1 fi done echo "repair_ok: ${repair_ok}" echo "found_gp_repair_ww: ${found_gp_repair_ww}" echo "found_gp_repair_ga: ${found_gp_repair_ga}" echo "found_ag_repair: ${found_ag_repair}" echo "found_pr_repair: ${found_pr_repair}" ########################### # prepare the next source ########################### export repaired_dir="repaired-${inst}" if [[ $repair_ok == 0 ]]; then fail_reason="" eval ${__repair_done}=0 if [[ ${#negs[@]} -gt 0 ]]; then if [[ ${found_gp_repair_ww} == 0 ]]; then cp -r ${ww_session_prefix}-${inst} ${repaired_dir} elif [[ ${found_gp_repair_ga} == 0 ]]; then cp -r ${ga_session_prefix}-${inst} ${repaired_dir} elif [[ ${found_pr_repair} == 0 ]]; then cp -r ${pr_session_prefix}-${inst} ${repaired_dir} elif [[ ${found_ag_repair} == 0 ]]; then cp -r ${ag_session_prefix}-${inst}/.angelix/validation/ ${repaired_dir} fi if safe_pushd "${repaired_dir}"; then local src_awk_file="extract-source.awk" local inc_awk_file="extract-include.awk" local new_src_file="new_src.c" create_extract_source_awk ${src_awk_file} create_extract_include_awk ${inc_awk_file} awk -f ${inc_awk_file} ../${prog_id}.c.org > ${new_src_file} awk -f ${src_awk_file} ${repair_src_name}.c >> ${new_src_file} # set the next source cp ${new_src_file} ../${prog_id}.c popd &> /dev/null fi fi fi eval ${__num_of_pos}=${num_of_pos} eval ${__num_of_neg}=${num_of_neg} simple_prog_id=$(echo ${prog_id} | sed "s/_buggy//g") write_to_file ${result_file} "${lab_id}\t${prob_id}\t${simple_prog_id}\t${inst}\t${num_of_pos}\t${num_of_neg}\t${found_gp_repair_ww}\t${found_gp_repair_ga}\t${found_ag_repair}\t${found_pr_repair}\t${repair_ok}\t${time_parallel}" popd &> /dev/null fi } ########################################################################################## export target_lab_id="Lab-5" export target_prob_id="2864" export target_prog_id="277609_buggy" export skip_ag=1 export skip_gp_ww=1 export skip_gp_ga=1 export skip_pr=1 export skip_done=0 if safe_pushd "${submissions_root}"; then Labs=$(ls -1d Lab*/) for lab_dir in ${Labs[@]}; do lab_id=${lab_dir%/} if [[ ! (-z ${target_lab_id}) && ${lab_id} != ${target_lab_id} ]]; then continue fi if safe_pushd "${lab_id}"; then for dir in */; do if [[ ! (-z ${target_prob_id}) && $dir != "${target_prob_id}/" ]]; then #echo "skip ${dir}" continue fi if safe_pushd $dir; then prob_id=${dir%/} for file in *.c; do if [[ $file != "Main.c" && $file != *_correct.c ]]; then prog_id=${file%.c} if [[ ! (-z ${target_prog_id}) && ${prog_id} != ${target_prog_id} ]]; then # echo "skip ${prog_id}" continue fi if [[ ${skip_done} == 0 ]]; then simple_prog_id=$(echo ${prog_id} | sed "s/_buggy//g") if grep "${simple_prog_id}" ${result_file} | \ grep "${prob_id}" | grep -q "${lab_id}"; then # echo "Skip ${lab_id} ${prob_id} ${prog_id}" continue fi fi # echo "${lab_id} ${prob_id} ${prog_id}" safe_rm "-rf" ${prog_id} mkdir -p ${prog_id} cp ${prog_id}.c ${prog_id} handle ${lab_id} ${prob_id} ${prog_id} \ ${skip_ag} ${skip_gp_ww} ${skip_gp_ga} fi done popd &> /dev/null fi done popd &> /dev/null fi done popd &> /dev/null fi
class User: def __init__(self, id: int): self.id = id def add_transaction(amount: float, currency: str, payment_type: str, user_id: int, storage_user: User) -> None: assert storage_user assert storage_user.id == user_id # Your implementation to store the transaction in the storage system # This could involve interacting with a database, API, or any other storage mechanism # For example: # storage_system.add_transaction(amount, currency, payment_type, user_id)
#!/bin/bash export PYTHONPATH='/home/ubuntu/git/GUDHI/cython/' for file in camel.csv lion.csv flam.csv elephant.csv gesture_a1_va3.csv Circles.csv twoMoons.csv twoCircles.csv mergeda9leftlegMAG.csv mergeda13leftlegMAG.csv mergeda14leftlegMAG.csv mergeda18leftlegMAG.csv seeds_dataset_cleansed.txt water-treatment.data_cleansed iris-cleansed.data dragon_vrip.ply.txt_2000_.txt torus.csv 4_rings.csv spiral.csv dsphere.csv swiss_roll.csv klein_bottle_pointcloud_new_900.txt inf_sign.csv crosstrainMergedSegs45dim.csv jumpingMergedSegs45dim.csv stepperMergedSegs45dim.csv walkingMergedSegs45dim.csv crosstrainMergedSegs9dim.csv jumpingMergedSegs9dim.csv stepperMergedSegs9dim.csv walkingMergedSegs9dim.csv do for points in 10 25 50 75 100 250 500 750 1000 do for edge in 1.0 do python runExperiments.py -f $file -e $edge -d 2 -k $points done done done
# usage: # sudo -E ./scripts/create_env.sh PROJDIR=`pwd` ME=`ls -ld $PROJDIR | awk 'NR==1 {print $3}'` MYGROUP=`ls -ld $PROJDIR | awk 'NR==1 {print $4}'` echo "ME:$ME MYGROUP:$MYGROUP" VENVDIR="venv" ENVNAME="image-enhancer-awsrn" # # install python 5 # echo "*** install python 3.5 ****" if hash python3.5; then echo "Python 3.5 is already installed" else apt-get update apt-get install build-essential checkinstall apt-get install libreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev # download Python 3.5 cd /usr/src wget https://www.python.org/ftp/python/3.5.9/Python-3.5.9.tgz tar xzf Python-3.5.9.tgz rm Python-3.5.9.tgz # install Python on Linux cd Python-3.5.9 sudo ./configure --enable-optimizations sudo make altinstall # check python3.5 -V which python3.5 # /usr/local/bin/python3.5 fi cd "$PROJDIR" # # create a fresh python5 env # echo "*** create a fresh python5 env ****" if [ -d "$VENVDIR" ]; then echo "'$VENVDIR' found. I remove it now" rm -rf "$VENVDIR" fi echo "creating python environment, please wait ..." mkdir -p "$VENVDIR" if [ -d "$VENVDIR" ]; then echo "folder '$VENVDIR' created" else echo "Warning: '$VENVDIR' could not be created" exit 1 fi cd "$VENVDIR" echo "create venv $ENVNAME" python3.5 -m venv "$ENVNAME" cd "$PROJDIR" echo "change owner and group to '$ME:$MYGROUP'" chown -hR $ME:$MYGROUP $VENVDIR echo "activate new python environment" . ./"$VENVDIR"/"$ENVNAME"/bin/activate PIP=`which pip` echo "$PIP" # # install requirements # echo "*** install requirements ****" $PIP install -r requirements.txt
<gh_stars>1-10 /** * Author: <NAME> <<EMAIL>> * Copyright (c) 2020 Gothel Software e.K. * Copyright (c) 2020 ZAFENA AB * * Author: <NAME> <<EMAIL>> * Copyright (c) 2016 Intel Corporation. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package tinyb.dbus; import java.util.List; import java.util.Map; import org.tinyb.BLERandomAddressType; import org.tinyb.BluetoothAddressType; import org.tinyb.BluetoothDevice; import org.tinyb.BluetoothException; import org.tinyb.BluetoothGattCharacteristic; import org.tinyb.BluetoothGattService; import org.tinyb.BluetoothManager; import org.tinyb.BluetoothNotification; import org.tinyb.BluetoothType; import org.tinyb.BluetoothUtils; import org.tinyb.GATTCharacteristicListener; import org.tinyb.HCIStatusCode; public class DBusDevice extends DBusObject implements BluetoothDevice { @Override public final long getCreationTimestamp() { return ts_creation; } @Override public final long getLastDiscoveryTimestamp() { return ts_creation; } // FIXME @Override public final long getLastUpdateTimestamp() { return ts_creation; } // FIXME @Override public native BluetoothType getBluetoothType(); @Override public native DBusDevice clone(); static BluetoothType class_type() { return BluetoothType.DEVICE; } @Override public BluetoothGattService find(final String UUID, final long timeoutMS) { final BluetoothManager manager = DBusManager.getBluetoothManager(); return (BluetoothGattService) manager.find(BluetoothType.GATT_SERVICE, null, UUID, this, timeoutMS); } @Override public BluetoothGattService find(final String UUID) { return find(UUID, 0); } /* D-Bus method calls: */ @Override public final HCIStatusCode disconnect() throws BluetoothException { return disconnectImpl() ? HCIStatusCode.SUCCESS : HCIStatusCode.UNSPECIFIED_ERROR ; } private native boolean disconnectImpl() throws BluetoothException; @Override public final HCIStatusCode connect() throws BluetoothException { return connectImpl() ? HCIStatusCode.SUCCESS : HCIStatusCode.UNSPECIFIED_ERROR ; } private native boolean connectImpl() throws BluetoothException; @Override public HCIStatusCode connect(final short interval, final short window, final short min_interval, final short max_interval, final short latency, final short timeout) { return connect(); // FIXME connection params ... } @Override public native boolean connectProfile(String arg_UUID) throws BluetoothException; @Override public native boolean disconnectProfile(String arg_UUID) throws BluetoothException; @Override public native boolean pair() throws BluetoothException; @Override public native boolean remove() throws BluetoothException; @Override public native boolean cancelPairing() throws BluetoothException; @Override public native List<BluetoothGattService> getServices(); @Override public boolean pingGATT() { return true; } // FIXME /* D-Bus property accessors: */ @Override public native String getAddress(); @Override public BluetoothAddressType getAddressType() { return BluetoothAddressType.BDADDR_LE_PUBLIC; /* FIXME */} @Override public BLERandomAddressType getBLERandomAddressType() { return BLERandomAddressType.UNDEFINED; /* FIXME */ } @Override public native String getName(); @Override public native String getAlias(); @Override public native void setAlias(String value); @Override public native int getBluetoothClass(); @Override public native short getAppearance(); @Override public native String getIcon(); @Override public native boolean getPaired(); @Override public native void enablePairedNotifications(BluetoothNotification<Boolean> callback); @Override public native void disablePairedNotifications(); @Override public native boolean getTrusted(); @Override public native void enableTrustedNotifications(BluetoothNotification<Boolean> callback); @Override public native void disableTrustedNotifications(); @Override public native void setTrusted(boolean value); @Override public native boolean getBlocked(); @Override public native void enableBlockedNotifications(BluetoothNotification<Boolean> callback); @Override public native void disableBlockedNotifications(); @Override public native void setBlocked(boolean value); @Override public native boolean getLegacyPairing(); @Override public native short getRSSI(); @Override public native void enableRSSINotifications(BluetoothNotification<Short> callback); @Override public native void disableRSSINotifications(); @Override public native boolean getConnected(); @Override public final short getConnectionHandle() { return 0; /* FIXME */ } @Override public native void enableConnectedNotifications(BluetoothNotification<Boolean> callback); @Override public native void disableConnectedNotifications(); @Override public native String[] getUUIDs(); @Override public native String getModalias(); @Override public native DBusAdapter getAdapter(); @Override public native Map<Short, byte[]> getManufacturerData(); @Override public native void enableManufacturerDataNotifications(BluetoothNotification<Map<Short, byte[]> > callback); @Override public native void disableManufacturerDataNotifications(); @Override public native Map<String, byte[]> getServiceData(); @Override public native void enableServiceDataNotifications(BluetoothNotification<Map<String, byte[]> > callback); @Override public native void disableServiceDataNotifications(); @Override public native short getTxPower (); @Override public native boolean getServicesResolved (); @Override public native void enableServicesResolvedNotifications(BluetoothNotification<Boolean> callback); @Override public native void disableServicesResolvedNotifications(); @Override public boolean addCharacteristicListener(final GATTCharacteristicListener listener) { return false; // FIXME } @Override public boolean removeCharacteristicListener(final GATTCharacteristicListener l) { return false; // FIXME } @Override public int removeAllAssociatedCharacteristicListener(final BluetoothGattCharacteristic associatedCharacteristic) { return 0; // FIXME } @Override public int removeAllCharacteristicListener() { return 0; // FIXME } private native void delete(); private DBusDevice(final long instance) { super(instance); ts_creation = BluetoothUtils.getCurrentMilliseconds(); } final long ts_creation; @Override public String toString() { return "Device[address["+getAddress()+", "+getAddressType()+"], '"+getName()+"']"; } }
/* * * Copyright © 2017 <NAME>(<NAME>)/<EMAIL>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "rpc_channel_impl.h" #include <gprpc/rpc_channel.h> #include <gprpc/rpc_client.h> #include <gprpc.pb.h> #include <gprpc/rpc_controller.h> #include <rpc_controller_imp.h> #include <cli_conn.h> #include <rpc_debug.h> #include <gprpc/closure.h> gprpc::client::rpc_channel_impl::rpc_channel_impl(gprpc::client::rpc_client &client, const std::string &address, const std::string &port) : address_(address), port_(port), client_(client), resolver_(*client.get_nios()) { } const string &gprpc::client::rpc_channel_impl::get_address() const { return address_; } const string &gprpc::client::rpc_channel_impl::get_port() const { return port_; } gprpc::client::rpc_client &gprpc::client::rpc_channel_impl::get_client() const { return client_; } tcp::resolver &gprpc::client::rpc_channel_impl::get_resolver() { return resolver_; } tcp::resolver::iterator &gprpc::client::rpc_channel_impl::get_it_ep() { r_lock lock(mutex_); return it_ep_; } //void gprpc::client::rpc_channel_impl::set_it_ep(tcp::resolver::iterator &it_ep) { void gprpc::client::rpc_channel_impl::set_it_ep_if_empty(tcp::resolver::iterator &it_ep) { w_lock lock(mutex_); if (it_ep_ == tcp::resolver::iterator()) { it_ep_ = it_ep; } } bool gprpc::client::rpc_channel_impl::set_rpc_data(gprpc::rpc_data &data, const MethodDescriptor *method, gprpc::rpc_controller *controller, const Message *request) { data.set_data_type(gprpc::rpc_data::REQUEST); data.set_svc_name(method->service()->full_name()); // data.set_method_name(method->full_name()); data.set_method_name(method->name()); data.set_call_id(client_.generate_seqid()); controller->impl_->set_call_id(data.call_id()); std::stringstream call_tag; call_tag << data.svc_name() << "." << data.method_name() << "." << data.call_id(); controller->impl_->set_call_tag(call_tag.str()); data.set_compress(controller->isCompress()); data.set_encrypt(controller->isEncrypt()); std::string pre_content, post_content; request->SerializeToString(&pre_content); controller->impl_->set_msg_type(gprpc::rpc_controller_impl::REQUEST); controller->impl_->set_process_end(gprpc::rpc_controller_impl::RPC_CLIENT); controller->impl_->process_data(pre_content, post_content); data.set_content(post_content); return true; } void gprpc::client::rpc_channel_impl::do_rpc(gprpc::rpc_data &data, gprpc::rpc_controller *controller, Message *response, Closure *done) { std::string rpc_data; data.SerializeToString(&rpc_data); size_t header_size = sizeof(gprpc::rpc_header); size_t data_size = rpc_data.size() + header_size; if (data_size > conn_buf_size_) { abort(controller, done, -1); return; } if (done) { // conn_.reset(new cli_conn(*this, *done, *controller, response)); cli_conn_ptr conn(new cli_conn(*this, *done, *controller, response)); gprpc::rpc_header& header = conn->get_header(); memcpy(header.magic, rpc_magic, RPC_MAGIC_LEN); header.data_len = (uint32_t)rpc_data.size(); conn->set_buffer(rpc_data); conn->start(); controller->impl_->set_remote_address(get_address()); } else { // i_log << "rpc call: " << svc_name << "." << method_name << ", conn: " << conn->get_tag(); single_sync_wait syncer; Closure *signaller = new_callback(&syncer, &single_sync_wait::signal_ex); // conn_.reset(new cli_conn(*this, *signaller, *controller, NULL)); cli_conn_ptr conn(new cli_conn(*this, *signaller, *controller, NULL)); gprpc::rpc_header& header = conn->get_header(); memcpy(header.magic, rpc_magic, RPC_MAGIC_LEN); header.data_len = (uint32_t)rpc_data.size(); conn->set_buffer(rpc_data); conn->start(); syncer.wait(); controller->impl_->set_remote_address(get_address()); handle_rpc_response(controller, conn->get_buffer(), conn->get_header().data_len, response); } } void gprpc::client::rpc_channel_impl::abort(gprpc::rpc_controller *controller, Closure *done, int32_t err_code, string extra_err_info) { controller->impl_->set_failed(err_code); if (!extra_err_info.empty()) { controller->impl_->set_failed(controller->impl_->error_text() + extra_err_info); } if (err_code == 0) { i_log << "Rpc call: " << controller->impl_->get_call_tag() << " done successfully: " << controller->ErrorCode() << ", " << controller->ErrorText() << extra_err_info; } else { e_log << "Rpc call: " << controller->impl_->get_call_tag() << " failed, error code: " << controller->ErrorCode() << ", " << controller->ErrorText() << extra_err_info; } if (done) { client_.get_wios()->post(boost::bind(&Closure::Run, done)); } } void gprpc::client::rpc_channel_impl::handle_rpc_response(gprpc::client::cli_conn_ptr conn) { gprpc::rpc_controller& controller = conn->get_controller(); if (!controller.Failed()) { gprpc::rpc_data data; if (!data.ParseFromArray(conn->get_buffer(), conn->get_header().data_len)) { controller.impl_->set_failed(-9); // if (!conn->is_sync_call()) { conn->get_done().Run(); // } return; } controller.impl_->set_msg_type(gprpc::rpc_controller_impl::RESPONSE); controller.impl_->set_process_end(gprpc::rpc_controller_impl::RPC_CLIENT); if (data.failed()) { controller.SetFailed(data.reason()); controller.SetErrorCode(data.error_code()); } controller.setEncrypt(data.encrypt()); controller.setCompress(data.compress()); //socket might have been closed by now due to timeout /*tcp::endpoint remote_ep = conn->socket().remote_endpoint(); controller.impl_->set_remote_address(remote_ep.address().to_string());*/ std::string out; controller.impl_->process_data(data.content(), out); if (!conn->get_response()->ParseFromString(out)) { //override the err info in rpc data controller.impl_->set_failed(-10); } } // if (!conn->is_sync_call()) { conn->get_done().Run(); // } } void gprpc::client::rpc_channel_impl::handle_rpc_response(gprpc::rpc_controller* controller, const void* buffer, int size, Message *response) { if (!controller->Failed()) { gprpc::rpc_data data; if (!data.ParseFromArray(buffer, size)) { controller->impl_->set_failed(-9); return; } controller->impl_->set_msg_type(gprpc::rpc_controller_impl::RESPONSE); controller->impl_->set_process_end(gprpc::rpc_controller_impl::RPC_CLIENT); if (data.failed()) { controller->SetFailed(data.reason()); controller->SetErrorCode(data.error_code()); } controller->setEncrypt(data.encrypt()); controller->setCompress(data.compress()); //socket might have been closed by now due to timeout /*tcp::endpoint remote_ep = conn->socket().remote_endpoint(); controller.impl_->set_remote_address(remote_ep.address().to_string());*/ std::string out; controller->impl_->process_data(data.content(), out); if (!response->ParseFromString(out)) { //override the err info in rpc data controller->impl_->set_failed(-10); } } } void gprpc::client::rpc_channel_impl::call_method(const MethodDescriptor *method, RpcController *controller, const Message *request, Message *response, Closure *done) { gprpc::rpc_data data; gprpc::rpc_controller* ctrl = dynamic_cast<gprpc::rpc_controller*>(controller); set_rpc_data(data, method, ctrl, request); do_rpc(data, ctrl, response, done); }
function mergeSort(array) { if (array.length <= 1) return array; const array1 = mergeSort(array.slice(0, array.length / 2)); const array2 = mergeSort(array.slice(array.length / 2, array.length)); return merge(array1, array2); } function merge(array1, array2) { const result = []; let i = 0; let j = 0; while (i < array1.length && j < array2.length) { if (array1[i] < array2[j]) { result.push(array1[i++]); } else { result.push(array2[j++]); } } while (i < array1.length) result.push(array1[i++]); while (j < array2.length) result.push(array2[j++]); return result; }
# bu.plugin.sh # Author: Taleeb Midi <taleebmidi@gmail.com> # Based on oh-my-zsh AWS plugin # # command 'bu [N]' Change directory up N times # # Faster Change Directory up function bu () { function usage () { cat <<-EOF Usage: bu [N] N N is the number of level to move back up to, this argument must be a positive integer. h help displays this basic help menu. EOF } # reset variables STRARGMNT="" FUNCTIONARG=$1 # Make sure the provided argument is a positive integer: if [[ ! -z "${FUNCTIONARG##*[!0-9]*}" ]]; then for i in $(seq 1 $FUNCTIONARG); do STRARGMNT+="../" done CMD="cd ${STRARGMNT}" eval $CMD else usage fi }
module.exports = [ require("./rendering-info/web.js"), require("./rendering-info/web-svg.js"), require("./stylesheet.js"), require("./script.js"), require("./option-availability.js"), require("./dynamic-enum.js"), require("./dynamic-schema.js"), require("./health.js"), require("./fixtures/data.js"), require("./notification/hideAxisLabel.js"), require("./notification/unsupportedDateFormat"), require("./notification/shouldBeBarChart.js"), require("./notification/shouldBeLineChart.js"), require("./notification/shouldBeBars.js"), require("./locales.js"), require("./data.js"), require("./migration.js") ].concat(require("./schema.js"));
# Script to install the TFODAPI on a Linux VM or a Docker container. # It carries out the installation steps described here: https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/installation.md # This script was modified from set_up__object_detection_api.sh. #this block was added to turn off interactive steps during installation (setting the timezone). export DEBIAN_FRONTEND=noninteractive ln -fs /usr/share/zoneinfo/Pacific/Honolulu /etc/localtime #change the time zone (Pacific/Honolulu) to yours. Google tzdata for more info. dpkg-reconfigure --frontend noninteractive tzdata apt-get update -y apt-get install -y git wget python3-tk pip install --upgrade pip pip install tqdm Cython contextlib2 pillow lxml jupyter matplotlib cd /lib/tf git clone https://github.com/tensorflow/models models # Dockerfile moves this script to /lib/tf/ so that TFODAPI is installed there git clone https://github.com/cocodataset/cocoapi.git cd cocoapi/PythonAPI make cp -r pycocotools /lib/tf/models/research/ cd ../.. mkdir protoc_3.3 cd protoc_3.3 wget https://github.com/google/protobuf/releases/download/v3.3.0/protoc-3.3.0-linux-x86_64.zip chmod 775 protoc-3.3.0-linux-x86_64.zip unzip protoc-3.3.0-linux-x86_64.zip cd ../models/research apt-get install -y protobuf-compiler echo *** Installed protobuf-compiler ../../protoc_3.3/bin/protoc object_detection/protos/*.proto --python_out=. export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim python object_detection/builders/model_builder_test.py echo **** PYTHONPATH used to run model_builder_test.py echo $PYTHONPATH python setup.py sdist (cd slim && python setup.py sdist) echo *********** PWD is echo $PWD echo *****
<filename>src/lib/index.ts<gh_stars>1-10 export * from "./rules/noImportZonesRule";
#!/bin/bash xclip -sel clip -o >in.in
<filename>src/main/java/br/com/zupacademy/gabrielf/casadocodigo/config/validacao/ErroHandlerValidation.java package br.com.zupacademy.gabrielf.casadocodigo.config.validacao; import org.springframework.http.HttpStatus; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; @RestControllerAdvice public class ErroHandlerValidation { @ResponseStatus(code = HttpStatus.BAD_REQUEST) @ExceptionHandler(MethodArgumentNotValidException.class) public List<ErroDeMensagemDto> handle(MethodArgumentNotValidException exception){ List<ErroDeMensagemDto> errosDto = new ArrayList<>(); List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors(); for (FieldError erro: fieldErrors) { String mensagem = erro.getDefaultMessage(); LocalDateTime now = LocalDateTime.now(); errosDto.add(new ErroDeMensagemDto(mensagem,erro.getField(),now)); } return errosDto; } }
<gh_stars>0 var fs = require('fs'), path = require('path'), _ = require('underscore'), data = [], result = {}, skipDir = [], configPath = './judoc.config.js', tpl, filenames, matchs, name, html, eachFile, fixDir, config, srcPath, distPath; // 读取目录 process.argv.forEach(function(argv, i) { if (argv === '--config') { configPath = process.argv[i + 1]; } }); // 读取config内容 try { config = require(path.join(process.cwd(), configPath)); } catch (e) { console.log('config missing'); return; } // 路径 srcPath = config.paths.input; distPath = config.paths.output; // 排除目录矫正 _.each(config.skip, function(v) {skipDir.push(path.join(srcPath, v))}); // 遍历src文件夹读取js eachFile = function(dir) { filenames = fs.readdirSync(dir); filenames.forEach(function(filename) { fixDir = path.join(dir, filename); if (~skipDir.indexOf(fixDir)) { // 如果目录等于config中的排除目录直接跳过 return; } else { if (path.extname(filename) !== '') { data.push(fs.readFileSync(fixDir, {encoding: 'utf8'})); // file dir log console.log(fixDir + '......loading'); } else if (filename !== '.DS_Store') { eachFile(fixDir); } } }) }; // 读取数据 tpl = fs.readFileSync(path.join(__dirname, 'tmp.html'), {encoding: 'utf8'}); eachFile(srcPath); // 读取注释 data.forEach(function(text) { // 循环文件 matchs = text.match(/\/\*\*[^*][\s\S]*?\*\//g); if (!matchs) { // 跳过不需要生成doc的js文件 return; } var singleResult = {items: []}, singleName; matchs.forEach(function(match, i) { // 循环文件中的注释 singleResult['items'][i-1] = {params: []}; match.replace(/@(name|grammar|param|return|example|more)\s(?:\{(.*)\})?\s*([^@]*)|\/\*\*[*\s]+([^@]+)/gi, function($0, $1, $2, $3, $4) { if ($1) { // 非描述信息 $1 = $1.toLowerCase(); $3 = $3.replace(/[\t ]*\*[\t ]?|(?:\s*\*[\s\/]*)*$/g, ''); // reg => 多行处理|去掉$3后面没用的 if (i === 0) { // js文件顶部注释信息 if ($1 === 'name') { // name直接作为data的key存储此文件的内容 singleName = $3; } else { singleResult[$1] = $3; } } else { // 非顶部注释 if ($1 === 'name' || $1 === 'grammar') { // name/grammar singleResult['items'][i-1][$1] = $3; } else { if ($1 === 'example' || $1 === 'more') { // example/more singleResult['items'][i-1][$1] = $3; } else { // param/return singleResult['items'][i-1]['params'].push([$1, $2, $3]); } } } } else { // 描述 $4 = $4.replace(/[\t ]*\*[\t ]?|(?:\s*\*[\s\/]*)*$/g, ''); // reg => 多行处理|去掉$3后面没用的 if (i === 0) { singleResult['desc'] = $4; } else { singleResult['items'][i-1]['desc'] = $4; } } }) }); if (singleName) result[singleName] = singleResult; }) // 模板渲染 html = _.template(tpl)({config: config, data: result}); // 创建生成目录 !fs.existsSync(distPath) && fs.mkdirSync(distPath); !fs.existsSync(path.join(distPath, 'images')) && fs.mkdirSync(path.join(distPath, 'images')); // 生成doc fs.writeFileSync(path.join(distPath, config.name + '.html'), html); // 生成html需要的image fs.writeFileSync(path.join(distPath, 'images/logo.png'), fs.readFileSync(path.join(__dirname, 'images/logo.png'))); fs.writeFileSync(path.join(distPath, 'images/background.png'), fs.readFileSync(path.join(__dirname, 'images/background.png'))); // success log console.log('all success!')
<filename>app/src/main/java/com/sereno/math/Quaternion.java package com.sereno.math; /** Quaternion class*/ public class Quaternion { /** The x (i) component*/ public float x; /** The y (j) component*/ public float y; /** The z (k) component*/ public float z; /** The w (real) component*/ public float w; /** Constructor, create a unit quaternion*/ public Quaternion() { this(0.0f, 0.0f, 0.0f, 1.0f); } /** Constructor, create a custom quaternion * @param _x the i component * @param _y the j component * @param _z the k component * @param _w the real component*/ public Quaternion(float _x, float _y, float _z, float _w) { x = _x; y = _y; z = _z; w = _w; } /** Constructor, create a custom quaternion based on a float array (w, i, j, k) * @param quat the float array*/ public Quaternion(float[] quat) { this(quat[1], quat[2], quat[3], quat[0]); } /** Constructor, create a quaternion from a axis angle * @param axis the 3D axis to rotate around * @param angle the angle to rotate to*/ public Quaternion(float[] axis, float angle) { w = (float)Math.cos(angle/2.0f); float s = (float)Math.sin(angle/2.0f); x = axis[0]*s; y = axis[1]*s; z = axis[2]*s; } /** Get the inverse of this quaternion * @return the inverse of this quaternion*/ public Quaternion getInverse() { return new Quaternion(-x, -y, -z, w); } /** Get the multiplication between "this" and x * @return this*x */ public Quaternion multiplyBy(Quaternion q) { return new Quaternion(w*q.x + x*q.w + y*q.z - z*q.y, //i part w*q.y - x*q.z + y*q.w + z*q.x, //j part w*q.z + x*q.y - y*q.x + z*q.w, //k part w*q.w - x*q.x - y*q.y - z*q.z); //The real part } /** Rotate a vector v via this quaternion * @param v the vector to rotate. The float array should be of size 3 (or more) * @return a new vector in a float[3] {x, y, z} array.*/ public float[] rotateVector(float[] v) { Quaternion invQ = getInverse(); Quaternion qPure = new Quaternion(v[0], v[1], v[2], 0); Quaternion res = this.multiplyBy(qPure).multiplyBy(invQ); return new float[]{res.x, res.y, res.z}; } /** Create a quaternion that point from sourcePoint to destPoint * @param sourcePoint the source 3D point * @param destPoint the source 3D point * @return the quaternion*/ public static Quaternion lookAt(float[] sourcePoint, float[] destPoint) { float[] forwardVector = Vector3.normalise(Vector3.minus(destPoint, sourcePoint)); float dot = forwardVector[2]; if (Math.abs(dot - (-1.0f)) < 0.000001f) { return new Quaternion(new float[]{0.0f, 1.0f, 0.0f}, (float)Math.PI); } if (Math.abs(dot - (1.0f)) < 0.000001f) { return new Quaternion(); } float rotAngle = (float) Math.acos(dot); float[] rotAxis = Vector3.crossProduct(new float[]{0.0f, 0.0f, 1.0f}, forwardVector); rotAxis = Vector3.normalise(rotAxis); return new Quaternion(rotAxis, rotAngle); } /** Convert this quaternion to a float array * @return a float array containing {w, x, y, z}*/ public float[] toFloatArray() { return new float[]{w, x, y, z}; } @Override public Object clone() { return new Quaternion(x, y, z, w); } }
<gh_stars>0 package org.gi.groupe5.dao; import org.gi.groupe5.manager.*; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DaoFactory { private String url = "jdbc:mysql://localhost:3306/park"; private String username = "root"; private String password = ""; DaoFactory(String url, String username, String password) { this.url = url; this.username = username; this.password = password; } DaoFactory() { } public static DaoFactory getInstance() { try { Class.forName("com.mysql.cj.jdbc.Driver"); } catch (ClassNotFoundException e) { } DaoFactory instance = new DaoFactory(); return instance; } public Connection getConnection() throws SQLException { return DriverManager.getConnection(url, username, password); } public ParkingDao getParkingDao() { return new ParkingManager(this); } public PlaceDao getPlaceDao() { return new PlaceManager(this); } public VehiculeDao getVehiculeDao() { return new VehiculeManager(this); } public UserDao getUserDao() { return new UserManager(this); } public ClientDao getClientDao() { return new ClientManager(this); } public TarifDao getTarifDao() { return new TarifManager(this); } public OccupationDao getOccupationDao() { return new OccupationManager(this); } public PaiementDao getPaimentDao() { return new PaiementManager(this); } }
<reponame>tabris233/go_study package main import ( "fmt" "os" "runtime" ) func f(x int) { fmt.Printf("f(%d)\n", x+0/x) defer fmt.Printf("defer f(%d)\n", x) f(x - 1) } func main2() { defer printStack() defer fmt.Printf("------") f(3) } func printStack() { var buf [4096]byte n := runtime.Stack(buf[:], false) os.Stdout.Write(buf[:n]) } func testPanic() (x int, err error) { defer func() { switch p := recover(); p { case nil: case 2: err = fmt.Errorf("2") default: panic(p) } }() x = 1 if x == 2 { panic(2) } else { panic(new(int)) } } func main() { fmt.Println(testPanic()) }
<reponame>mjburling/beneficiary-fhir-data package gov.cms.bfd.server.war.r4.providers.preadj; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.rest.client.api.IGenericClient; import ca.uhn.fhir.rest.param.DateParam; import ca.uhn.fhir.rest.param.ReferenceParam; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import gov.cms.bfd.server.war.ServerTestUtils; import gov.cms.bfd.server.war.utils.AssertUtils; import gov.cms.bfd.server.war.utils.RDATestUtils; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Set; import org.hl7.fhir.r4.model.Bundle; import org.hl7.fhir.r4.model.ClaimResponse; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; public class R4ClaimResponseResourceProviderIT { private static final RDATestUtils testUtils = new RDATestUtils(); private static final Set<String> IGNORE_PATTERNS = ImmutableSet.of("\"/link/[0-9]+/url\"", "\"/created\"", "\"/meta/lastUpdated\""); @BeforeAll public static void init() { testUtils.init(); testUtils.seedData(true); } @AfterAll public static void tearDown() { testUtils.truncateTables(); testUtils.destroy(); } @Test void shouldGetCorrectFissClaimResponseResourceById() { IGenericClient fhirClient = ServerTestUtils.get().createFhirClientV2(); ClaimResponse claimResult = fhirClient.read().resource(ClaimResponse.class).withId("f-123456").execute(); String expected = testUtils.expectedResponseFor("claimResponseFissRead"); String actual = FhirContext.forR4().newJsonParser().encodeResourceToString(claimResult); AssertUtils.assertJsonEquals(expected, actual, IGNORE_PATTERNS); } @Test void shouldGetCorrectMcsClaimResponseResourceById() { IGenericClient fhirClient = ServerTestUtils.get().createFhirClientV2(); ClaimResponse claimResult = fhirClient.read().resource(ClaimResponse.class).withId("m-654321").execute(); String expected = testUtils.expectedResponseFor("claimResponseMcsRead"); String actual = FhirContext.forR4().newJsonParser().encodeResourceToString(claimResult); AssertUtils.assertJsonEquals(expected, actual, IGNORE_PATTERNS); } @Test void shouldGetCorrectClaimResponseResourcesByMbiHash() { IGenericClient fhirClient = ServerTestUtils.get().createFhirClientV2(); Bundle claimResult = fhirClient .search() .forResource(ClaimResponse.class) .where( ImmutableMap.of( "mbi", Collections.singletonList(new ReferenceParam(RDATestUtils.MBI_OLD_HASH)), "service-date", Arrays.asList( new DateParam("gt1970-07-18"), new DateParam("lt1970-07-30")))) .returnBundle(Bundle.class) .execute(); // Sort entries for consistent testing results claimResult.getEntry().sort(Comparator.comparing(a -> a.getResource().getId())); String expected = testUtils.expectedResponseFor("claimResponseSearch"); String actual = FhirContext.forR4().newJsonParser().encodeResourceToString(claimResult); Set<String> ignorePatterns = new HashSet<>(IGNORE_PATTERNS); ignorePatterns.add("\"/id\""); ignorePatterns.add("\"/entry/[0-9]+/resource/created\""); AssertUtils.assertJsonEquals(expected, actual, ignorePatterns); } }
class HttpResponse: def __init__(self, status_code, status_text): self.status_code = status_code self.status_text = status_text self.headers = {} def set_header(self, name, value): self.headers[name] = value def generate_response(self): headers_str = '\n'.join([f"{name}: {value}" for name, value in self.headers.items()]) return f"HTTP/1.1 {self.status_code} {self.status_text}\n{headers_str}" # Example usage response = HttpResponse(200, 'OK') response.set_header('Content-Type', 'text/html') response.set_header('Server', 'Hasta') print(response.generate_response())
<filename>tests/test_basics.py import json import unittest import numpy as np from pybx.basics import mbx, bbx, MultiBx, jbx, stack_bxs, get_bx, BaseBx from pybx.excepts import BxViolation np.random.seed(1) params = { "annots_rand_file": './data/annots_rand.json', "annots_iou_file": './data/annots_iou.json', "annots_key_file": './data/annots_key.json', "annots_l": [[50., 70., 120., 100., 'rand1'], [150., 200., 250., 240., 'rand2']], "annots_l_single": [98, 345, 420, 462], "annots_l_single_imsz": (640, 480), "annots_a": np.random.randn(10, 4), "annots_i8": np.random.randint(1, 100, 4, dtype=np.int8), "annots_i16": np.random.randint(1, 100, 4, dtype=np.int16), "annots_i32": np.random.randint(1, 100, 4, dtype=np.int32), "annots_i64": np.random.randint(1, 100, 4, dtype=np.int64), "annots_f16": np.random.randn(4).astype(np.float16), "annots_f32": np.random.randn(4).astype(np.float32), "annots_f64": np.random.randn(4).astype(np.float64), } results = { "mbx_json": (120.0, 'rand2'), "mbx_list": (50.0, 'rand1'), "mbx_arr": -0.08959797456887511, "iou": 0.0425531914893617, "xywh": np.array([50.0, 70.0, 70.0, 30.0]), "jbx_label": ['person', 4], "yolo": [0.4046875, 0.840625, 0.503125, 0.24375] } class BasicsTestCase(unittest.TestCase): def test_mbx_json(self): with open(params["annots_rand_file"]) as f: annots = json.load(f) b = mbx(annots) r = b.coords[0][2], b.label[1] self.assertIsInstance(b, MultiBx, 'b is not MultiBx') self.assertEqual(r, results["mbx_json"]) def test_mbx_list(self): annots = params["annots_l"] b = mbx(annots) r = b.coords[0][2], b.label[1] self.assertIsInstance(b, MultiBx, 'b is not MultiBx') self.assertEqual(r, results["mbx_json"]) def test_mbx_array(self): annots = params["annots_a"] b = mbx(annots) r = b.coords.mean() self.assertIsInstance(b, MultiBx, 'b is not MultiBx') self.assertEqual(r, results["mbx_arr"]) def test_label_key_jbx(self): with open(params["annots_key_file"]) as f: annots = json.load(f) b_m = jbx(annots) self.assertEqual(b_m.label, results["jbx_label"]) def test_add_bbx(self): with open(params["annots_iou_file"]) as f: annots = json.load(f) b0 = bbx(annots[0]) b1 = bbx(annots[1]) b_r = b0 + b1 b_m = mbx([annots[0], annots[1]]) self.assertTrue((b_r.coords == b_m.coords).all()) def test_add_mbx_bbx(self): with open(params["annots_iou_file"]) as f: annots = json.load(f) b_m = mbx([annots[0], annots[1]]) b1 = bbx(annots[2]) b_r = b_m + b1 self.assertTrue((b1.coords == b_r.coords).any(), ) def test_bbx_warning(self): with open(params["annots_iou_file"]) as f: annots = json.load(f) self.assertRaises(AssertionError, bbx, coords=[annots]) def test_add_warning(self): with open(params["annots_iou_file"]) as f: annots = json.load(f) b0 = bbx(annots[0]) b1 = bbx(annots[1]) self.assertWarns(BxViolation, b0.__add__, other=b1) def test_stack_bxs(self): with open(params["annots_iou_file"]) as f: annots = json.load(f) b0 = bbx(annots[0]) b1 = bbx(annots[1]) bm = mbx(annots[:2]) bs = stack_bxs(b0, b1) self.assertTrue((bs.coords == bm.coords).all()) def test_iou(self): with open(params["annots_iou_file"]) as f: annots = json.load(f) b0 = bbx(annots[0]) b1 = bbx(annots[1]) b2 = bbx(annots[2]) # intersecting box iou = b0.iou(b1) # calculated iou iou_ = b2.area() / (b0.area() + b1.area() - b2.area()) self.assertEqual(iou, iou_) self.assertEqual(iou, results["iou"]) def test_xywh(self): with open(params["annots_rand_file"]) as f: annots = json.load(f) b = bbx(annots[0]) self.assertTrue((b.xywh() == results["xywh"]).all(), True) self.assertGreaterEqual(b.xywh()[-1], 0) self.assertGreaterEqual(b.xywh()[-2], 0) def test_yolo(self): annots = params["annots_l_single"] b = bbx(annots) w, h = params["annots_l_single_imsz"] b_yolo = b.yolo(normalize=True, w=w, h=h) self.assertTrue((b_yolo == results["yolo"]).all()) def test_get_bx(self): with open(params["annots_rand_file"]) as f: annots_json = json.load(f) annots_l_single = params["annots_l_single"] annots_l_multi = params["annots_l"] self.assertIsInstance(get_bx(annots_l_single), BaseBx) # list self.assertIsInstance(get_bx(annots_l_multi), MultiBx) # nested list self.assertIsInstance(get_bx(annots_json), MultiBx) # json self.assertIsInstance(get_bx(annots_json[0]), BaseBx) # dict self.assertIsInstance(get_bx(get_bx(annots_json)), MultiBx) # MultiBx self.assertIsInstance(get_bx(get_bx(annots_json[0])), BaseBx) # BaseBx def test_type_mbx(self): b = get_bx(params["annots_i8"]) self.assertIsInstance(b, MultiBx) b = get_bx(params["annots_i16"]) self.assertIsInstance(b, MultiBx) b = get_bx(params["annots_i32"]) self.assertIsInstance(b, MultiBx) b = get_bx(params["annots_i64"]) self.assertIsInstance(b, MultiBx) b = get_bx(params["annots_f16"]) self.assertIsInstance(b, MultiBx) b = get_bx(params["annots_f32"]) self.assertIsInstance(b, MultiBx) b = get_bx(params["annots_f64"]) self.assertIsInstance(b, MultiBx) b = get_bx(params["annots_l_single"]) self.assertIsInstance(b, BaseBx) if __name__ == '__main__': unittest.main()
import React, { Component } from 'react'; class FeedPage extends Component { render() { const posts = this.props.posts.map(post => { return ( <div key={post.id}> <b>{post.author}</b><br/> {post.text}<br/> </div> ); }); return ( <div> {posts} </div> ); } } export default FeedPage;
<reponame>kjhx-hw/app_comp4300_othello<filename>src/application/App.js<gh_stars>0 import React, { Component } from 'react'; import Game from '../components/Game/Game'; import GameOver from '../components/GameOver/GameOver'; import GameStart from '../components/GameStart/GameStart'; import './App.css'; class App extends Component { constructor(props) { super(props); this.state = { status: 'start', winner: null, whiteScore: 0, blackScore: 0 }; } render() { const gameStart = this.state.status === 'start' ? <GameStart go={this.startGame.bind(this)}/> : ''; const game = this.state.status === 'active' ? <Game end={this.endGame.bind(this)} /> : ''; const gameOver = this.state.status === 'over' ? <GameOver winner={this.state.winner} restart={this.restartGame.bind(this)} white={this.state.whiteScore} black={this.state.blackScore} /> : ''; return ( <div className="App"> {gameStart} {game} {gameOver} </div> ); } startGame() { this.setState({ status: 'active' }); } restartGame() { this.setState({ status: 'start', }); } endGame(winner, whiteScore, blackScore) { this.setState({ status: 'over', winner, whiteScore, blackScore }); } } export default App;
<reponame>natflausino/cub3D<gh_stars>1-10 #ifndef CUB3D_BONUS_H # define CUB3D_BONUS_H /****************************************************************************** ** LIBRARIES ******************************************************************************/ # include <math.h> # include <stdio.h> # include <float.h> # include <stdbool.h> # include <fcntl.h> # include "error.h" # include "../../libraries/minilibx-linux/mlx.h" # include "../../libraries/libft/includes/libft.h" # include "defines_bonus.h" # include "structs_bonus.h" /****************************************************************************** ** CUB3D ******************************************************************************/ void set_param(t_game *game); void check_file(int argc, char **argv, t_game *game); void read_file(t_game *game, char *file); void check_paths(t_game *game); /****************************************************************************** ** ERROR ******************************************************************************/ void return_free_error(int err, char **tab); void return_error(int err); void print_error_1(int err); void print_error_2(int err); /****************************************************************************** ** BITMAP ******************************************************************************/ void image_create(t_game *game); void fill_data(t_bmp *bmp, t_game *game); void image_header(t_bmp *bmp, int file); /****************************************************************************** ** EVENTS ******************************************************************************/ int release_key(int key, t_game *game); int press_key(int key, t_game *game); int close_window(t_game *game); void table_free(char **tab); /****************************************************************************** ** GET PARAM ******************************************************************************/ void get_param(t_game *game, char *line); int check_param(char *line); void get_texture(char *line, char **texture); void get_resolution(t_game *game, char *line); int check_digit(char *tab, char *set); /****************************************************************************** ** GRAPHICS ******************************************************************************/ void screen_resolution(t_game *game); void draw(t_game *game); int update(t_game *game); void image_put_pixel(t_game *game, int x, int y, int color); void draw_rect(t_game *game, int color); void draw_line(t_game *game, t_int_coord p0, t_int_coord p1); /****************************************************************************** ** PARSING COLOR ******************************************************************************/ void check_color(char **tab); int color_assemble(int red, int green, int blue); int get_color(char *line); void image_put(t_game *game, t_bmp *bmp, int file); int count_char(char *str, char c); /****************************************************************************** ** PARSING FILE ******************************************************************************/ char *full_line(t_game *game, char *line); void check_line(t_game *game, char *line, int fd); int map_col_size(int fd); void reset_path(t_game *game); int find_map(char *line); /****************************************************************************** ** PARSING MAP & PARSING MAP 2 ******************************************************************************/ void count_arg(t_game *game, int fd); void map_extract(t_game *game, char *line, int fd); void map_check(t_game *game); void map_check2(t_game *game, char **tab); void inside_map(char **tab); void is_map_closed(t_game *game, char **tab); void check_f_c(t_game *game, char *line); /****************************************************************************** ** PLAYER ******************************************************************************/ void move_player(t_game *game); void player_position(t_game *game); void player_facing(t_game *game); double normalize_angle(double angle); /****************************************************************************** ** RAYCATSTING & RAYCASTING 2 ******************************************************************************/ double dist2points(double x1, double y1, double x2, double y2); void dist2wall(t_game *game, double horz_dist, double vert_dist); void find_dist(t_game *game, int horz_hit, int vert_hit); void ray_facing(t_game *game, double ray); void raycast(t_game *game, double rayangle); void cast_all_rays(t_game *game); void check_horiz(t_game *game, int *horzhit); void horz_cast(t_game *game, int *horzhit); void check_vert(t_game *game, int *verthit); void vert_cast(t_game *game, int *verthit); /****************************************************************************** ** SPRITES ******************************************************************************/ void sprite_height(t_game *game, int *start, int *end, int *i); void draw_sprite(t_game *game, int x, int s_pos, int sp); void set_sprite(t_game *game, int i, int *s_pos); void sprite_param(t_game *game); void sprite_angle(t_game *game); void sort_sprite(t_game *game); void render_sprite(t_game *game); void sprite_visible(t_game *game, int x, int y); void find_sprite(t_game *game); void num_sprites(t_game *game); void hor_sprite_collider(t_game *game, double next_x, double next_y); void ver_sprite_collider(t_game *game, double next_x, double next_y); void damage_cure(t_game *game, int x, int y, int dist); char *type_define(int tex, int id); void load_sprite(t_game *game); void free_sprites(t_game *game); void find_sprite_2(t_game *game, int i, int j, int *k); void find_sprite_3(t_game *game, int i, int j); void find_sprite_2_aux(t_game *game, int i, int j); void find_sprite_3_aux(t_game *game, int i, int j); void find_sprite_3_aux1(t_game *game, int i, int j); void find_sprite_4(t_game *game, int i, int j); void win(t_game *game, int x, int y, int dist); void effect(t_game *game, int x, int y, int dist); void find_sprite_init(t_game *game); void find_sprite_2_init(t_game *game, int i, int j, int *k); void load_life(t_game *game); void free_life(t_game *game); void render_lifebar(t_game *game); int get_color_life(t_tex *life_tex, int life_x, int life_y); void free_item(t_game *game); void render_item(t_game *game); void load_item(t_game *game); int get_color_item(t_tex *item_tex, int item_x, int item_y); void load_weapon(t_game *game); void free_weapon(t_game *game); void render_weapon(t_game *game); int get_color_weapon(t_tex *weapon_tex, int weapon_x, int weapon_y); /****************************************************************************** ** TEXTURES ******************************************************************************/ void texture_select(t_game *game); void texture_ident(t_game *game); void free_textures(t_game *game); void free_textures2(t_game *game); void texture_load(t_game *game); void calculate_texture(t_game *game, int *x_tex, int side); /****************************************************************************** ** WALLS ******************************************************************************/ void draw_strip(t_game *game, int x, int side, int strip_height); void render_projection_walls(t_game *game, int i); int is_wall(t_game *game, int x, int y); int check_wall(t_game *game, double new_x, double new_y); void color_floor_ceiling(t_game *game, double wall_height, int i); void floor_texture(t_game *game, int i, int j, double wall_height); int special_floor(t_game *game, int color); int special_ceiling(t_game *game, int color); int special_wall(t_game *game, int color); /****************************************************************************** ** MINIMAP ******************************************************************************/ void minimap(t_game *game); void minimap_player(t_game *game); void minimap_rays(t_game *game); /****************************************************************************** ** DOOR ******************************************************************************/ int door(t_game *game, int x, int y, int dist); void hor_door_collider(t_game *game, double next_x, double next_y); void ver_door_collider(t_game *game, double next_x, double next_y); #endif
import {Queue} from 'queue-typescript' import {BasicGraphOnEdges} from '../../structs/basicGraphOnEdges' import {IEdge} from '../../structs/iedge' export function* GetConnectedComponents<TEdge extends IEdge>( graph: BasicGraphOnEdges<TEdge>, ): IterableIterator<number[]> { const enqueueed = new Array(graph.nodeCount).fill(false) const queue = new Queue<number>() for (let i = 0; i < graph.nodeCount; i++) { if (!enqueueed[i]) { const nodes = new Array<number>() Enqueue(i, queue, enqueueed) while (queue.length > 0) { const s: number = queue.dequeue() nodes.push(s) for (const neighbor of Neighbors(graph, s)) { Enqueue(neighbor, queue, enqueueed) } } yield nodes } } } function* Neighbors<TEdge extends IEdge>( graph: BasicGraphOnEdges<TEdge>, s: number, ): IterableIterator<number> { for (const e of graph.outEdges[s]) { yield e.target } for (const e of graph.inEdges[s]) { yield e.source } } function Enqueue(i: number, q: Queue<number>, enqueueed: boolean[]) { if (enqueueed[i] == false) { q.enqueue(i) enqueueed[i] = true } }
""" Create a web service that takes textual input and outputs a list of categories that the input text belongs to. """ import flask from nltk.corpus import wordnet # Create a web service app = flask.Flask(__name__) @app.route('/', methods=['POST']) def classify(): # Get the text from the request text = flask.request.json['text'] # Extract the categories from the text categories = [wordnet.synsets(word)[0].lexname for word in text.split()] # Return the categories return flask.jsonify({'categories': categories}) # Run the web service if __name__ == '__main__': app.run()
#include "duckdb/catalog/catalog_entry/sequence_catalog_entry.hpp" #include "duckdb/catalog/catalog_entry/schema_catalog_entry.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/common/serializer.hpp" #include "duckdb/parser/parsed_data/create_sequence_info.hpp" #include <algorithm> using namespace duckdb; using namespace std; SequenceCatalogEntry::SequenceCatalogEntry(Catalog *catalog, SchemaCatalogEntry *schema, CreateSequenceInfo *info) : StandardEntry(CatalogType::SEQUENCE, schema, catalog, info->name), usage_count(info->usage_count), counter(info->start_value), increment(info->increment), start_value(info->start_value), min_value(info->min_value), max_value(info->max_value), cycle(info->cycle) { this->temporary = info->temporary; } void SequenceCatalogEntry::Serialize(Serializer &serializer) { serializer.WriteString(schema->name); serializer.WriteString(name); // serializer.Write<int64_t>(counter); serializer.Write<uint64_t>(usage_count); serializer.Write<int64_t>(increment); serializer.Write<int64_t>(min_value); serializer.Write<int64_t>(max_value); serializer.Write<int64_t>(counter); serializer.Write<bool>(cycle); } unique_ptr<CreateSequenceInfo> SequenceCatalogEntry::Deserialize(Deserializer &source) { auto info = make_unique<CreateSequenceInfo>(); info->schema = source.Read<string>(); info->name = source.Read<string>(); // info->counter = source.Read<int64_t>(); info->usage_count = source.Read<uint64_t>(); info->increment = source.Read<int64_t>(); info->min_value = source.Read<int64_t>(); info->max_value = source.Read<int64_t>(); info->start_value = source.Read<int64_t>(); info->cycle = source.Read<bool>(); return info; }
import numpy as np from nba.ios.gadget_reader import is_parttype_in_file, read_snap from pygadgetreader import readsnap import nba.com as com def load_snapshot(snapname, snapformat, quantity, ptype): """ Load all the particle data of a specific dtype and the required quantity. Readers from other codes need to be implemented here. At the moment the NBA supports Gadget2/3/4 and ASCII format. Paramters: ---------- snapname: str Path and snashot name snapformat: str Format of the simulations (1) Gadget2/3, (2) ASCII, (3) Gadget4 - HDF5 quantity: str Particle propery: pos, vel, mass, pid ptype: str Particle type: dm, disk, bulge Returns: -------- q : numpy.array Particle data for the specified quantity and ptype # TODO: Return header and return available keys in ValueError. """ if snapformat == 1: q = readsnap(snapname, quantity, ptype) elif snapformat == 3: if quantity == 'pos': q = 'Coordinates' elif quantity == 'vel': q = 'Velocities' elif quantity == 'mass': q = 'Masses' elif quantity == 'pot': q = 'Potential' elif quantity == 'pid': q = 'ParticleIDs' elif quantity == 'acc': q = 'Acceleration' else: ValueError("* desired quantity is not available, try: ['pos', 'vel', 'mass', 'pot', 'pid', 'acc'] ") if ptype == "dm": ptype = 'PartType1' if ptype == "disk": ptype = 'PartType2' if ptype == "bulge": ptype = 'PartType3' q = read_snap(snapname+".hdf5", ptype, q) else : print('** Wrong snapshot format: (1) Gadget2/3, (2) ASCII, (3) Gadget4 (HDF5)') sys.exit() return np.ascontiguousarray(q) def halo_ids(pids, list_num_particles, gal_index): """ If in an snapshot there are several halos and the particle ids are arranged by halos i.e first N ids are of halo 1 second P ids are of halo 2 etc.. Then this function could be used to return properties of a halo given its ids order. Parameters ----------- pids: numpy.array array with all the DM particles ids list_num_particles: list A list with the number of particles of all the galaxies in the ids. [1500, 200, 50] would mean that the first halo have 1500 particles, the second halo 200, and the third and last halo 50 particles. gal_index: int Index of the needed halo or galaxy. Return -------- list of arrays With the properties of the desired halo """ #assert len(xyz)==len(vxyz)==len(pids), "your input parameters have different length" assert type(gal_index) == int, "your galaxy type should be an integer" assert gal_index >= 0, "Galaxy type can't be negative" sort_indexes = np.sort(pids) Ntot = len(pids) if gal_index ==0: N_cut_min = sort_indexes[0] N_cut_max = sort_indexes[int(sum(list_num_particles[:gal_index+1])-1)] elif gal_index == len(list_num_particles)-1: N_cut_min = sort_indexes[int(sum(list_num_particles[:gal_index]))] N_cut_max = sort_indexes[-1] else: N_cut_min = sort_indexes[int(sum(list_num_particles[:gal_index]))] N_cut_max = sort_indexes[int(sum(list_num_particles[:gal_index+1]))] # selecting halo ids halo_ids = np.where((pids>=N_cut_min) & (pids<=N_cut_max))[0] assert len(halo_ids) == list_num_particles[gal_index], 'Something went wrong selecting the satellite particles' return halo_ids def get_com(pos, vel, mass, method, snapname=0, snapformat=0): """ Function that computes the COM using a chosen method Parameters ---------- pos: numpy.array cartesian coordinates with shape (n,3) vel: numpy.array cartesian velocities with shape (n,3) mass: numpy.array Particle masse method: str shrinking: Using the shrinking sphere algorithm diskpot: Using the minimum of the disk Potential mean_por: Using the mean positions of the particle distribution Returns -------- pos_com: numpy.array With coordinates of the COM. vel_com: numpy.array With the velocity of the COM. """ if method == 'shrinking': pos_com, vel_com = com.shrinking_sphere(pos, vel, mass) elif method == 'diskpot': # TODO : Make this function generic to sims with multiple disks! #disk_particles = is_parttype_in_file(path+snap+".hdf5", 'PartType2') #assert disk_particles == True, "Error no disk particles found in snapshot" pos_disk = load_snapshot(snapname, snapformat, 'pos', 'disk') vel_disk = load_snapshot(snapname, snapformat, 'vel', 'disk') pot_disk = load_snapshot(snapname, snapformat, 'pot', 'disk') pos_com, vel_com = com.com_disk_potential(pos_disk, vel_disk, pot_disk) del pos_disk, vel_disk, pot_disk elif method == 'mean_pos': pos_com, vel_com = com.mean_pos(pos, vel, mass) return pos_com, vel_com def load_halo(snap, N_halo_part, q, com_frame=0, galaxy=0, snapformat=3, com_method='shrinking'): """ Returns the halo properties. Parameters: path : str Path to the simulations snap : str name of the snapshot N_halo_part : list A list with the number of particles of all the galaxies in the ids. [1500, 200, 50] would mean that the first halo have 1500 particles, the second halo 200, and the third and last halo 50 particles. q : list Particles properties: ['pos', 'vel', 'pot', 'mass'] etc.. IDs are necessay and loaded by default. com_frame : int In which halo the coordinates will be centered 0 -> halo 1, 1 -> halo 2 etc.. galaxy : int Halo particle data to return 0 -> halo 1, 1 -> halo 2 etc... snapformat: int 0 -> Gadget binnary, 2 -> ASCII, 3 -> Gadget HDF5 com_method : str Method to compute the COM 'shrinking', 'diskpot', 'mean_pos' Returns: -------- pos : numpy.array vel : numpy.array pot : numpy.array mass : numpy.array TODO: Leave vel and mass as args when computing COM. """ # Load data print("* Loading snapshot: {} ".format(snap)) # TBD: Define more of quantities, such as acceleration etc.. unify this beter with ios all_ids = load_snapshot(snap, snapformat, 'pid', 'dm') ids = halo_ids(all_ids, N_halo_part, galaxy) halo_properties = dict([ ('ids', ids)] ) for quantity in q: qall = load_snapshot(snap, snapformat, quantity, 'dm') halo_properties[quantity] = qall[ids] #if galaxy == 1: print("* Loading halo {} particle data".format(galaxy)) print("* Computing coordinates in halo {} reference frame".format(com_frame)) if com_frame == galaxy: pos_com, vel_com = get_com(halo_properties['pos'], halo_properties['vel'], halo_properties['mass'], com_method, snapname=snap, snapformat=snapformat) new_pos = com.re_center(halo_properties['pos'], pos_com) new_vel = com.re_center(halo_properties['vel'], vel_com) else: # computing reference frame coordinates ids_RF = halo_ids(all_ids, N_halo_part, com_frame) pos_RF = load_snapshot(snap, snapformat, 'pos', 'dm') vel_RF = load_snapshot(snap, snapformat, 'vel', 'dm') mass_RF = load_snapshot(snap, snapformat, 'vel', 'dm') pos_com, vel_com = get_com(pos_RF[ids_RF], vel_RF[ids_RF], mass_RF[ids_RF], com_method) new_pos = com.re_center(pos, pos_com) new_vel = vel.re_center(vel, vel_com) halo_properties['pos']=new_pos halo_properties['vel']=new_vel return halo_properties
rm -rf fused_resnet_block_inference_generator_tiramisu fused_resnet_block_generator_tiramisu.o fused_resnet_block_generator_tiramisu.o.h wrapper_nn_block_fused_resnet_inference fused_resnet_block_generator_tiramisu fused_resnet_block_mkldnn_result fused_resnet_block_mkl_result tiramisu_result.txt mkl_result.txt tf_model.pb tvm_autotuning.log rm -rf .pkl_memoize_py3 param_tuning.h
/* * dbtype_Guest.cpp */ #include <string> #include "dbtype_Guest.h" #include "dbtype_Entity.h" #include "dbtypes/dbtype_Id.h" #include "dbtype_Player.h" #include "concurrency/concurrency_ReaderLockToken.h" #include "concurrency/concurrency_WriterLockToken.h" #include "concurrency/concurrency_LockableObject.h" namespace mutgos { namespace dbtype { // ---------------------------------------------------------------------- Guest::Guest() : Player() { } // ---------------------------------------------------------------------- Guest::Guest(const Id &id) : Player(id, ENTITYTYPE_guest, 0, 0) { } // ---------------------------------------------------------------------- Guest::~Guest() { } // ---------------------------------------------------------------------- Entity *Guest::clone( const Id &id, const VersionType version, const InstanceType instance, concurrency::ReaderLockToken &token) { if (token.has_lock(*this)) { Entity *copy_ptr = new Guest( id, ENTITYTYPE_guest, version, instance); copy_fields(copy_ptr); return copy_ptr; } else { LOG(error, "dbtype", "clone", "Using the wrong lock token!"); return 0; } } // ---------------------------------------------------------------------- bool Guest::set_password( const std::string &new_password, concurrency::WriterLockToken &token) { return false; } // ---------------------------------------------------------------------- bool Guest::check_password( const std::string &password, concurrency::ReaderLockToken &token) { return false; } // ---------------------------------------------------------------------- Guest::Guest( const Id &id, const EntityType &type, const VersionType version, const InstanceType instance, const bool restoring) : Player(id, type, version, instance, restoring) { } } /* namespace dbtype */ } /* namespace mutgos */
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.u1F1EF = void 0; var u1F1EF = { "viewBox": "0 0 2600 2760.837", "children": [{ "name": "path", "attribs": { "d": "M2002 495q17 0 27.5 11t10.5 28v762q0 370-27 548.5t-138 291-262.5 166.5-327.5 54q-295 0-495.5-142.5T559 1843q0-25 7.5-35t18.5-13l359-113q4 0 11-1 29 0 41.5 37t54 84 106.5 79 134 32q125 0 182-75.5t57-293.5V534q0-17 11.5-28t28.5-11h432z" }, "children": [] }] }; exports.u1F1EF = u1F1EF;
#!/bin/bash echo "[+] Starting Meteor App!" if [ "$1" = "" ] then echo "[-] Usage: <dir>" echo "[!] Path needed for the containing project folder" exit 0 fi if [ ! -d $1 ] then echo "[!] Could not enter the dir: $1" exit 0 fi cd $1 echo "[+] Running NPM" npm install &>/dev/null echo "[+] Setting environment variables" export MONGO_URL='mongodb://<user>:<password>@localhost/<tablename>' export PORT=8888 export ROOT_URL='http://localhost/' echo "[+] Starting Node Server" forever start main.js
import Game from './Game.js'; import PasswordInputScreen from './PasswordInputScreen.js'; import KeyListener from './KeyboardListener.js'; import Scene from './Scene.js'; export default class UserInputScreen extends Scene { mainLogo; usernameInfo; glassplane; glassplane2; wrongAlert; inputUser; constructor(game) { super(game); this.mainLogo = Game.loadNewImage('./assets/img/Game-Logo-(Main).png'); this.usernameInfo = Game.loadNewImage('./assets/img/Input-Username.png'); } processInput() { if (this.keyBoard.isKeyDown(KeyListener.KEY_ENTER)) { this.inputUser = document.getElementById('input').value; this.game.getUserData().setUsername(this.inputUser); this.nextScene = true; } } update() { if (this.nextScene) { this.glassplane = document.getElementById('glasspane'); this.glassplane.style.display = 'none'; this.glassplane.style.position = 'absolute'; this.glassplane2 = document.getElementById('glasspane2'); this.glassplane2.style.display = 'block'; this.glassplane2.style.position = 'absolute'; this.wrongAlert = document.getElementById('alert'); this.wrongAlert.style.display = 'block'; this.wrongAlert.style.position = 'absolute'; return new PasswordInputScreen(this.game); } return null; } render() { this.game.ctx.clearRect(0, 0, this.game.canvas.width, this.game.canvas.height); this.game.ctx.drawImage(this.mainLogo, (this.game.canvas.width / 2) - 250, (this.game.canvas.height / 2) - 320); this.game.ctx.drawImage(this.usernameInfo, (this.game.canvas.width / 2) - 250, this.game.canvas.height * 0.7); } } //# sourceMappingURL=UserInputScreen.js.map
<reponame>kevinwaxi/eanno_gaming require("./bootstrap"); window.Vue = require("vue").default; import VueRouter from "vue-router"; import common from "./modules/common"; import router from "./routes/index"; import store from "./store/index"; import Vuesax from "vuesax"; import "vuesax/dist/vuesax.css"; Vue.use(Vuesax); Vue.mixin(common); Vue.component("app-layout", require("./components/AppLayout.vue").default); Vue.use(VueRouter); const app = new Vue({ el: "#app", router: router, store: store, });
package com.ruoyi.ceshi.controller; import java.util.List; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.ruoyi.common.annotation.Log; import com.ruoyi.common.enums.BusinessType; import com.ruoyi.ceshi.domain.User; import com.ruoyi.ceshi.service.IUserService; import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.utils.poi.ExcelUtil; import com.ruoyi.common.core.page.TableDataInfo; /** * 用户表Controller * * @author ruoyi * @date 2020-10-22 */ @Controller @RequestMapping("/user/user") public class UserController extends BaseController { private String prefix = "user/user"; @Autowired private IUserService userService; @RequiresPermissions("user:user:view") @GetMapping() public String user() { return prefix + "/user"; } /** * 查询用户表列表 */ @RequiresPermissions("user:user:list") @PostMapping("/list") @ResponseBody public TableDataInfo list(User user) { startPage(); List<User> list = userService.selectUserList(user); return getDataTable(list); } /** * 导出用户表列表 */ @RequiresPermissions("user:user:export") @Log(title = "用户表", businessType = BusinessType.EXPORT) @PostMapping("/export") @ResponseBody public AjaxResult export(User user) { List<User> list = userService.selectUserList(user); ExcelUtil<User> util = new ExcelUtil<User>(User.class); return util.exportExcel(list, "user"); } /** * 新增用户表 */ @GetMapping("/add") public String add() { return prefix + "/add"; } /** * 新增保存用户表 */ @RequiresPermissions("user:user:add") @Log(title = "用户表", businessType = BusinessType.INSERT) @PostMapping("/add") @ResponseBody public AjaxResult addSave(User user) { return toAjax(userService.insertUser(user)); } /** * 修改用户表 */ @GetMapping("/edit/{id}") public String edit(@PathVariable("id") Long id, ModelMap mmap) { User user = userService.selectUserById(id); mmap.put("user", user); return prefix + "/edit"; } /** * 修改保存用户表 */ @RequiresPermissions("user:user:edit") @Log(title = "用户表", businessType = BusinessType.UPDATE) @PostMapping("/edit") @ResponseBody public AjaxResult editSave(User user) { return toAjax(userService.updateUser(user)); } /** * 删除用户表 */ @RequiresPermissions("user:user:remove") @Log(title = "用户表", businessType = BusinessType.DELETE) @PostMapping( "/remove") @ResponseBody public AjaxResult remove(String ids) { return toAjax(userService.deleteUserByIds(ids)); } }
# Node class class Node: # Function to initialize the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize next as null # Linked List class class LinkedList: # Function to initialize the Linked # List object def __init__(self): self.head = None # Deletes the node at position n def deleteNode(self, position): # If linked list is empty if self.head == None: return # Store headnode temp = self.head # If head needs to be removed if position == 0: self.head = temp.next temp = None return # Find previous node of the node to be deleted for i in range(position-1): temp = temp.next if temp is None: break # If position is more than number of nodes if temp is None: return if temp.next is None: return # Node temp.next is the node to be deleted # store pointer to the next of node to be deleted next = temp.next.next # Unlink the node from linked list temp.next = None temp.next = next
""" Implement an algorithm to multiply a given matrix by a scalar. """ def multiply_matrix_by_scalar(matrix, scalar): """Multiply a given matrix by a scalar. Parameters: matrix (list): A list of lists containing the matrix values scalar (int/float): The scalar value to multiply the matrix by Returns: list: The new matrix after multiplying by scalar """ result = [[0 for x in range(len(matrix[0]))] for y in range(len(matrix))] for i in range(len(matrix)): for j in range(len(matrix[0])): result[i][j] = matrix[i][j] * scalar return result if __name__ == '__main__': matrix = [[1,4],[-4,5]] scalar = 5 print(multiply_matrix_by_scalar(matrix, scalar))
var mainCtrl = angular.module('mainCtrl', []); /*----------------------------item management dashboard -----------------------------*/ mainCtrl.controller('loginCtrl',function($scope, $http) { $scope.login = function() { var data = $.param({ email: $scope.email, pass: $scope.password }); $http({ method: 'POST', url: 'login', data: data, headers:{'Content-Type': 'application/x-www-form-urlencoded'} }).then(function (data, status, headers, config){ // location.reload(); }); }; /* $scope.logout =function() { $http.get('/os/api/logout') .success(function (response) { window.location.reload(); }) .error(function (error, status) { console.log(status); }); }; */ });
// Code generated by protoc-gen-go. DO NOT EDIT. // source: google/type/latlng.proto package latlng import ( fmt "fmt" math "math" proto "github.com/golang/protobuf/proto" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package // An object representing a latitude/longitude pair. This is expressed as a pair // of doubles representing degrees latitude and degrees longitude. Unless // specified otherwise, this must conform to the // <a href="http://www.unoosa.org/pdf/icg/2012/template/WGS_84.pdf">WGS84 // standard</a>. Values must be within normalized ranges. type LatLng struct { // The latitude in degrees. It must be in the range [-90.0, +90.0]. Latitude float64 `protobuf:"fixed64,1,opt,name=latitude,proto3" json:"latitude,omitempty"` // The longitude in degrees. It must be in the range [-180.0, +180.0]. Longitude float64 `protobuf:"fixed64,2,opt,name=longitude,proto3" json:"longitude,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *LatLng) Reset() { *m = LatLng{} } func (m *LatLng) String() string { return proto.CompactTextString(m) } func (*LatLng) ProtoMessage() {} func (*LatLng) Descriptor() ([]byte, []int) { return fileDescriptor_a087c9a103c281a9, []int{0} } func (m *LatLng) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_LatLng.Unmarshal(m, b) } func (m *LatLng) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_LatLng.Marshal(b, m, deterministic) } func (m *LatLng) XXX_Merge(src proto.Message) { xxx_messageInfo_LatLng.Merge(m, src) } func (m *LatLng) XXX_Size() int { return xxx_messageInfo_LatLng.Size(m) } func (m *LatLng) XXX_DiscardUnknown() { xxx_messageInfo_LatLng.DiscardUnknown(m) } var xxx_messageInfo_LatLng proto.InternalMessageInfo func (m *LatLng) GetLatitude() float64 { if m != nil { return m.Latitude } return 0 } func (m *LatLng) GetLongitude() float64 { if m != nil { return m.Longitude } return 0 } func init() { proto.RegisterType((*LatLng)(nil), "google.type.LatLng") } func init() { proto.RegisterFile("google/type/latlng.proto", fileDescriptor_a087c9a103c281a9) } var fileDescriptor_a087c9a103c281a9 = []byte{ // 168 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x48, 0xcf, 0xcf, 0x4f, 0xcf, 0x49, 0xd5, 0x2f, 0xa9, 0x2c, 0x48, 0xd5, 0xcf, 0x49, 0x2c, 0xc9, 0xc9, 0x4b, 0xd7, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x86, 0xc8, 0xe8, 0x81, 0x64, 0x94, 0x9c, 0xb8, 0xd8, 0x7c, 0x12, 0x4b, 0x7c, 0xf2, 0xd2, 0x85, 0xa4, 0xb8, 0x38, 0x72, 0x12, 0x4b, 0x32, 0x4b, 0x4a, 0x53, 0x52, 0x25, 0x18, 0x15, 0x18, 0x35, 0x18, 0x83, 0xe0, 0x7c, 0x21, 0x19, 0x2e, 0xce, 0x9c, 0xfc, 0xbc, 0x74, 0x88, 0x24, 0x13, 0x58, 0x12, 0x21, 0xe0, 0x94, 0xcc, 0xc5, 0x9f, 0x9c, 0x9f, 0xab, 0x87, 0x64, 0xac, 0x13, 0x37, 0xc4, 0xd0, 0x00, 0x90, 0x85, 0x01, 0x8c, 0x51, 0x16, 0x50, 0xb9, 0xf4, 0xfc, 0x9c, 0xc4, 0xbc, 0x74, 0xbd, 0xfc, 0xa2, 0x74, 0xfd, 0xf4, 0xd4, 0x3c, 0xb0, 0x73, 0xf4, 0x21, 0x52, 0x89, 0x05, 0x99, 0xc5, 0xc8, 0x6e, 0xb5, 0x86, 0x50, 0x3f, 0x18, 0x19, 0x17, 0x31, 0x31, 0xbb, 0x87, 0x04, 0x24, 0xb1, 0x81, 0x55, 0x1b, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0xc0, 0x7b, 0xd0, 0x8b, 0xd8, 0x00, 0x00, 0x00, }
<reponame>zonesgame/StendhalArcClient<gh_stars>1-10 /* $Id$ */ /*************************************************************************** * (C) Copyright 2003-2014 - Stendhal * *************************************************************************** *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ package games.stendhal.client.events; import games.stendhal.client.ClientSingletonRepository; import games.stendhal.client.entity.Entity; import games.stendhal.client.sound.ConfiguredSounds; import games.stendhal.client.sound.facade.AudibleArea; import games.stendhal.client.sound.facade.AudibleCircleArea; import games.stendhal.client.sound.facade.InfiniteAudibleArea; import games.stendhal.client.sound.facade.SoundFileType; import games.stendhal.client.sound.facade.SoundGroup; import games.stendhal.common.constants.SoundID; import games.stendhal.common.constants.SoundLayer; import games.stendhal.common.math.Algebra; import games.stendhal.common.math.Numeric; import marauroa.common.Logger; /** * Plays a sound. * * @author hendrik */ class SoundEvent extends Event<Entity> { /** logger instance */ private static Logger logger = Logger.getLogger(SoundEvent.class); /** * Executes the event. */ @Override public void execute() { SoundLayer layer = SoundLayer.AMBIENT_SOUND; int idx = event.getInt("layer"); if (idx < SoundLayer.values().length) { layer = SoundLayer.values()[idx]; } float volume = 1.0f; if (event.has("volume")) { volume = Numeric.intToFloat(event.getInt("volume"), 100.0f); } AudibleArea area; if (event.has("radius")) { int radius = event.getInt("radius"); area = new AudibleCircleArea(Algebra.vecf((float) entity.getX(), (float) entity.getY()), radius / 4.0f, radius); } else { area = new InfiniteAudibleArea(); } String soundName; if (event.has("sound_id")) { final SoundID id = SoundID.getById(event.get("sound_id")); soundName = ConfiguredSounds.get(id); if (soundName == null) { logger.warn("No sound configured for ID: " + id.toString()); } } else { soundName = event.get("sound"); } if (soundName != null) { SoundGroup group = ClientSingletonRepository.getSound().getGroup(layer.groupName); group.loadSound(soundName, soundName + ".ogg", SoundFileType.OGG, false); group.play(soundName, volume, 0, area, null, false, true); } } }
function simulateEmailSession(session, email) { sendAndReceiveLoop(session); if (session.hasResponseCode(221)) { return getMailBox(email); } }
THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32 nkerns_1=64 nkerns_2=96 first_drop=1 last_drop=1 opt_med=adam std=1e-1 pattern='hinge' Loss_L=10 python cnn_6layer_svhn.py relu 1 1e-3 2e-6 lcn
<reponame>w2ogroup/titan<filename>titan-cassandra/src/test/java/com/thinkaurelius/titan/graphdb/astyanax/InternalAstyanaxGraphConcurrentTest.java package com.thinkaurelius.titan.graphdb.astyanax; import com.thinkaurelius.titan.CassandraStorageSetup; import com.thinkaurelius.titan.diskstorage.cassandra.CassandraProcessStarter; import com.thinkaurelius.titan.graphdb.TitanGraphConcurrentTest; import org.junit.BeforeClass; public class InternalAstyanaxGraphConcurrentTest extends TitanGraphConcurrentTest { @BeforeClass public static void startCassandra() { CassandraProcessStarter.startCleanEmbedded(CassandraStorageSetup.cassandraYamlPath); } public InternalAstyanaxGraphConcurrentTest() { super(CassandraStorageSetup.getAstyanaxGraphConfiguration()); } }
<gh_stars>0 const heading = { fontSize: '72px', color: 'blue' } export default function InLine(){ return( <div> <h1 style={heading}>Đây là InLine</h1> <h1 className="error"> Lỗi màu xanh hôm bữa</h1> </div> ) }
#!/bin/sh echo "Starting Docker Daemon from dockerd-cmd.sh" dockerd --host=unix:///var/run/docker.sock --host=tcp://0.0.0.0:2375 --storage-driver=vfs& sleep 3; echo "Starting minikube"; minikube start echo "Sleeping forever!"; while :; do read; done
#!/bin/bash # Copyright 2020 The IREE Authors # # Licensed under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # Checks for tabs in files modified vs the specified reference commit (default # "main") set -o pipefail BASE_REF="${1:-main}" declare -a excluded_files_patterns=( "^\.gitmodules$" "/third_party/" "^third_party/" ) # Join on | excluded_files_pattern="$(IFS="|" ; echo "${excluded_files_patterns[*]?}")" readarray -t files < <(\ (git diff --name-only --diff-filter=d "${BASE_REF}" || kill $$) \ | grep -v -E "${excluded_files_pattern?}") diff="$(grep --with-filename --line-number --perl-regexp --binary-files=without-match '\t' "${files[@]}")" grep_exit="$?" if (( "${grep_exit?}" >= 2 )); then exit "${grep_exit?}" fi if (( "${grep_exit?}" == 0 )); then echo "Changed files include tabs. Please use spaces."; echo "$diff" exit 1; fi
export rv cfg_file_mkdir() { if [ -d "$1" ] ; then cfg_tty_notice "Directory $1 already exists" else mkdir -p "$1" >/dev/null 2>&1 rv=$? if [ "$rv" -eq 0 ] ; then cfg_tty_info "Directory $1 created" else cfg_tty_alert "Failed to create directory $1" exit fi fi } cfg_file_rm() { if [ -f "$1" ] || [ -d "$1" ] ; then rm -rf "$1" >/dev/null 2>&1 rv=$? if [ "$rv" -eq 0 ] ; then cfg_tty_info "$1 removed" else cfg_tty_warning "Failed to remove $1" fi else cfg_tty_notice "$1 not found, skipping removal" fi } cfg_file_put() { printf "%b" "$2" >> "$1" rv=$? if [ "$rv" -ne 0 ] ; then cfg_tty_alert "Failed to write to $1" return 1 fi return 0 } cfg_file_putn() { printf "%b\n" "$2" >> "$1" rv=$? if [ "$rv" -ne 0 ] ; then cfg_tty_alert "Failed to write to $1" return 1 fi return 0 } cfg_file_sym() { if [ -L "$1" ] ; then if [ -e "$1" ] ; then cfg_tty_notice "Symlink $1 exists, skipping" return 0 else cfg_tty_warning "Broken symlink $1 found, removing" cfg_file_rm "$1" fi fi if [ ! -f "$2" ] ; then cfg_tty_crit "Target $2 not found, symlink not created" return 1 fi ln -sf "$2" "$1" >/dev/null 2>&1 rv=$? if [ "$rv" -eq 0 ] ; then cfg_tty_info "Symlink $1 --> $2 created" else cfg_tty_alert "Failed to create symlink $1 --> $2" exit fi } cfg_file_bkp() { if [ -f "$1" ] ; then cp "$1" "$2" >/dev/null 2>&1 core_check $? "File $1 backed up to $2" if [ "$rv" -eq 0 ] ; then cfg_tty_info "Backup $1 --> $2 created" else cfg_tty_alert "Failed to create backup $1 --> $2" exit fi else cfg_tty_warning "File $1 not found, skipping backup" fi } cfg_file_bkp_safe() { if [ -f "$2" ] ; then cfg_tty_notice "Backup file $2 exists, skipping" else cfg_file_bkp "$1" "$2" fi } cfg_file_scp() { if [ -z "$CFG_LOG" ] ; then scp -r "$1" "$2" >"$CFG_LOG" 2>&1 else scp -r "$1" "$2" >/dev/null 2>&1 fi rv=$? if [ $rv -eq 0 ] ; then cfg_tty_info "Copied $1 --> $2 over SSH" else cfg_tty_alert "Failed to copy $1 --> $2 over SSH" exit 1 fi }
class SbankenAPI def self.get_accounts(access_token, source_id, nin) Rails.cache.fetch(['accounts', Sbanken.name, source_id], expires_in: 1.second) do SbankenAPI.http_get('https://api.sbanken.no/exec.bank/api/v1/Accounts', access_token, nin)['items'] end end def self.get_transactions(ext_account_id, access_token, source_id, nin) Rails.cache.fetch(['transaction', Sbanken.name, ext_account_id, source_id], expires_in: 1.second) do SbankenAPI.http_get("https://api.sbanken.no/exec.bank/api/v1/Transactions/#{ext_account_id}?startDate=#{(Time.now - 2.weeks).strftime("%Y-%m-%d")}&endDate=#{(Time.now - 1.week).strftime("%Y-%m-%d")}", access_token, nin)['items'] end end def self.get_access_token(client_id, client_secret, source_id) Rails.cache.fetch(['access_token', Sbanken.name, source_id], expires_in: 900.seconds) do url = URI.parse('https://auth.sbanken.no/identityserver/connect/token') http = Net::HTTP.new(url.host, url.port) req = Net::HTTP::Post.new(url.path, initheader = { 'Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json', }) http.use_ssl = true req.basic_auth client_id, client_secret req.body = "grant_type=client_credentials" response = http.request(req) JSON.parse(response.body)['access_token'] end end def self.http_get(url, access_token, nin) url = URI.parse(url) http = Net::HTTP.new(url.host, url.port) http.use_ssl = true path = url.path path = "#{path}?#{url.query}" if url.query response = http.get(path, { 'Content-Type' => 'application/json', 'Accept' => 'application/json', 'Authorization' => "Bearer #{access_token}", 'customerId' => nin }) JSON.parse(response.body) end end
CREATE USER 'info'@'localhost' IDENTIFIED BY 'g4sGfdTbT23'; CREATE USER 'info'@'%' IDENTIFIED BY 'g4sGfdTbT23'; CREATE DATABASE info CHARACTER SET utf8 COLLATE utf8_general_ci; GRANT ALL PRIVILEGES ON info.* TO 'info'@'localhost'; GRANT ALL PRIVILEGES ON info.* TO 'info'@'%'; CREATE USER 'info_user'@'localhost' IDENTIFIED BY 'tmuL4svR76d'; CREATE USER 'info_user'@'%' IDENTIFIED BY 'tmuL4svR76d'; GRANT DELETE ON info.* TO 'info_user'@'localhost'; GRANT DELETE ON info.* TO 'info_user'@'%'; GRANT INSERT ON info.* TO 'info_user'@'localhost'; GRANT INSERT ON info.* TO 'info_user'@'%'; GRANT SELECT ON info.* TO 'info_user'@'localhost'; GRANT SELECT ON info.* TO 'info_user'@'%'; GRANT UPDATE ON info.* TO 'info_user'@'localhost'; GRANT UPDATE ON info.* TO 'info_user'@'%';
#!/usr/bin/env bash #SBATCH -J variant_calling_batch_array_job #SBATCH -N 1 #SBATCH -n 1 #SBATCH --array=1-3 #SBATCH --mem=6G set -e ## Load the required modules module load BWA module load freebayes module load SAMtools module load VCFtools module load annovar # Extract the nth line of file_list.txt # and assign that to variable fq1. # NB file_list.txt was created with: # ls ~/dc_workshop/data/trimmed_fastq/*_R1.trim.fq.gz > file_list.txt fq1=$(awk "NR==${SLURM_ARRAY_TASK_ID}" file_list.txt) genome=~/dc_workshop/data/ref_genome/chr20.fa cd ~/dc_workshop/results # The following steps should have been done _before_ running this array job: # bwa index $genome # mkdir -p sam bam vcf vcf_annotated echo "working with file $fq1" base=$(basename $fq1 _R1.trim.fq.gz) echo "base name is $base" fq1=~/dc_workshop/data/trimmed_fastq/${base}_R1.trim.fq.gz fq2=~/dc_workshop/data/trimmed_fastq/${base}_R2.trim.fq.gz sam=~/dc_workshop/results/sam/${base}.aligned.sam bam=~/dc_workshop/results/bam/${base}.aligned.bam sorted_bam=~/dc_workshop/results/bam/${base}.aligned.sorted.bam variants=~/dc_workshop/results/vcf/${base}_chr20.vcf variants_filtered=~/dc_workshop/results/vcf/${base}_chr20_filtered annovar_input=~/dc_workshop/results/vcf_annotated/${base}_avinput annovar_db=/mnt/shared/annovar_db/humandb bwa mem $genome $fq1 $fq2 > $sam samtools view -S -b $sam > $bam samtools sort -o $sorted_bam $bam samtools index $sorted_bam echo "Running freebayes..." freebayes -f $genome $sorted_bam > $variants vcftools --vcf $variants --minQ 20 --recode --recode-INFO-all --out $variants_filtered convert2annovar.pl -format vcf4 ${variants_filtered}.recode.vcf > $annovar_input ## Need to change directory as annovar will create output in the working directory cd ~/dc_workshop/results/vcf_annotated/ table_annovar.pl $annovar_input $annovar_db -buildver hg38 -out ${base}_final -remove -protocol refGene,1000g2015aug_all,cosmic70,dbnsfp30a -operation g,f,f,f -nastring NA -csvout
#!/bin/bash sudo apt update sudo apt install -y nginx sox libsox-fmt-mp3 rws ffmpeg gstreamer1.0-plugins-good gstreamer1.0-tools sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/default.bak sudo cp etc/nginx.conf /etc/nginx/sites-available/default sudo cp etc/car.service /etc/systemd/system/ sudo cp -r etc/rpi-car-control /etc/ sudo systemctl enable nginx.service sudo systemctl restart nginx.service sudo systemctl enable car.service sudo apt install -y ansible if [ ! -f ~/.ssh/id_rsa.pub ] then ssh-keygen -q -N "" -f ~/.ssh/id_rsa fi if [ -f ~/.ssh/authorized_keys ] then mv ~/.ssh/authorized_keys ~/.ssh/authorized_keys.bak fi cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys chmod 600 ~/.ssh/authorized_keys ssh -o "StrictHostKeyChecking no" localhost echo "Added localhost to .ssh/known_hosts" 2>/dev/null ansible-playbook -i localhost, raspbian-python3.6.yml if [ -f ~/.ssh/authorized_keys.bak ] then mv ~/.ssh/authorized_keys.bak ~/.ssh/authorized_keys else rm ~/.ssh/authorized_keys fi sudo pip3.6 install --upgrade pip setuptools wheel sudo pip3.6 install rpi.gpio sudo pip3.6 install websockets sudo pip3.6 install smbus2 sudo pip3.6 install vl53l1x sudo pip3.6 install Adafruit_DHT ( # Install Rust curl https://sh.rustup.rs -sSf | sh . ~/.cargo/env # Clone the raspivid_mjpeg_server repo and build and install the server git clone https://github.com/kig/raspivid_mjpeg_server cd raspivid_mjpeg_server echo "Building raspivid_mjpeg_server. This is going to take forever (15 minutes on Raspberry Pi 3B+) so do some pushups in the meanwhile." cargo build --release cp target/release/raspivid_mjpeg_server ../bin/ ) sudo mkdir -p /opt/rpi-car-control sudo cp -r bin control html sensors video web_server run.sh /opt/rpi-car-control echo "The car is installed" echo echo "For rproxy SSH server:" echo "----------------------" echo 'export RPROXY=my.rproxy.server' echo 'ssh $RPROXY -- "sudo useradd car -s /bin/false"; sudo mkdir ~car/.ssh; sudo touch ~car/.ssh/authorized_keys; sudo chmod -R go-rwx ~car/.ssh' echo 'ssh $RPROXY -- "cat >> sudo tee ~car/.ssh/authorized_keys" < ~/.ssh/id_rsa.pub' echo 'ssh $RPROXY -- "sudo tee /etc/sshd_config" < etc/sshd_config' echo echo 'After starting the car server, you can now connect to the car at http://$RPROXY:9999/car/' echo 'For HTTPS and authentication, set up an nginx reverse proxy on $RPROXY (see etc/remote_nginx.conf)' echo echo "To start the car server" echo "-----------------------" echo "sudo systemctl start car" echo echo "Open http://raspberrypi/car/" echo exit
parallel --jobs 6 < ./results/experiment_disks/run-1/sea_cp_5n_6t_6d_1000f_617m_5i/jobs/jobs_n3.txt
<gh_stars>0 package util import ( "crypto/md5" "crypto/rand" "encoding/hex" "io" "mime/multipart" ) // 生成32位MD5 func MD532(text string) string { ctx := md5.New() ctx.Write([]byte(text)) return hex.EncodeToString(ctx.Sum(nil)) } // MD5file 生成32位MD5file func MD5file(file multipart.File) string { var returnMD5String string ctx := md5.New() if _, err := io.Copy(ctx, file); err != nil { return returnMD5String } returnMD5String = hex.EncodeToString(ctx.Sum(nil)) return hex.EncodeToString(ctx.Sum(nil)) } // GenerateUniqueID func GenerateUniqueID() string { b := make([]byte, 16) n, err := rand.Read(b) if n != len(b) || err != nil { } return hex.EncodeToString(b) }
#include "ruby.h" #include "util.h" #include "st.h" VALUE rb_cArray; static ID id_cmp; #define ARY_DEFAULT_SIZE 16 #define ARY_MAX_SIZE (LONG_MAX / sizeof(VALUE)) void rb_mem_clear(mem, size) register VALUE *mem; register long size; { while (size--) { *mem++ = Qnil; } } static inline void memfill(mem, size, val) register VALUE *mem; register long size; register VALUE val; { while (size--) { *mem++ = val; } } #define ARY_TMPLOCK FL_USER1 static inline void rb_ary_modify_check(ary) VALUE ary; { if (OBJ_FROZEN(ary)) rb_error_frozen("array"); if (FL_TEST(ary, ARY_TMPLOCK)) rb_raise(rb_eRuntimeError, "can't modify array during iteration"); if (!OBJ_TAINTED(ary) && rb_safe_level() >= 4) rb_raise(rb_eSecurityError, "Insecure: can't modify array"); } static void rb_ary_modify(ary) VALUE ary; { VALUE *ptr; rb_ary_modify_check(ary); if (FL_TEST(ary, ELTS_SHARED)) { ptr = ALLOC_N(VALUE, RARRAY(ary)->len); FL_UNSET(ary, ELTS_SHARED); RARRAY(ary)->aux.capa = RARRAY(ary)->len; MEMCPY(ptr, RARRAY(ary)->ptr, VALUE, RARRAY(ary)->len); RARRAY(ary)->ptr = ptr; } } VALUE rb_ary_freeze(ary) VALUE ary; { return rb_obj_freeze(ary); } /* * call-seq: * array.frozen? -> true or false * * Return <code>true</code> if this array is frozen (or temporarily frozen * while being sorted). */ static VALUE rb_ary_frozen_p(ary) VALUE ary; { if (OBJ_FROZEN(ary)) return Qtrue; if (FL_TEST(ary, ARY_TMPLOCK)) return Qtrue; return Qfalse; } static VALUE ary_alloc _((VALUE)); static VALUE ary_alloc(klass) VALUE klass; { NEWOBJ(ary, struct RArray); OBJSETUP(ary, klass, T_ARRAY); ary->len = 0; ary->ptr = 0; ary->aux.capa = 0; return (VALUE)ary; } static VALUE ary_new(klass, len) VALUE klass; long len; { VALUE ary = ary_alloc(klass); if (len < 0) { rb_raise(rb_eArgError, "negative array size (or size too big)"); } if (len > ARY_MAX_SIZE) { rb_raise(rb_eArgError, "array size too big"); } if (len == 0) len++; RARRAY(ary)->ptr = ALLOC_N(VALUE, len); RARRAY(ary)->aux.capa = len; return ary; } VALUE rb_ary_new2(len) long len; { return ary_new(rb_cArray, len); } VALUE rb_ary_new() { return rb_ary_new2(ARY_DEFAULT_SIZE); } #ifdef HAVE_STDARG_PROTOTYPES #include <stdarg.h> #define va_init_list(a,b) va_start(a,b) #else #include <varargs.h> #define va_init_list(a,b) va_start(a) #endif VALUE #ifdef HAVE_STDARG_PROTOTYPES rb_ary_new3(long n, ...) #else rb_ary_new3(n, va_alist) long n; va_dcl #endif { va_list ar; VALUE ary; long i; ary = rb_ary_new2(n); va_init_list(ar, n); for (i=0; i<n; i++) { RARRAY(ary)->ptr[i] = va_arg(ar, VALUE); } va_end(ar); RARRAY(ary)->len = n; return ary; } VALUE rb_ary_new4(n, elts) long n; const VALUE *elts; { VALUE ary; ary = rb_ary_new2(n); if (n > 0 && elts) { MEMCPY(RARRAY(ary)->ptr, elts, VALUE, n); } /* This assignment to len will be moved to the above "if" block in Ruby 1.9 */ RARRAY(ary)->len = n; return ary; } VALUE rb_assoc_new(car, cdr) VALUE car, cdr; { VALUE ary; ary = rb_ary_new2(2); RARRAY(ary)->ptr[0] = car; RARRAY(ary)->ptr[1] = cdr; RARRAY(ary)->len = 2; return ary; } static VALUE to_ary(ary) VALUE ary; { return rb_convert_type(ary, T_ARRAY, "Array", "to_ary"); } VALUE rb_check_array_type(ary) VALUE ary; { return rb_check_convert_type(ary, T_ARRAY, "Array", "to_ary"); } static VALUE rb_ary_replace _((VALUE, VALUE)); /* * call-seq: * Array.new(size=0, obj=nil) * Array.new(array) * Array.new(size) {|index| block } * * Returns a new array. In the first form, the new array is * empty. In the second it is created with _size_ copies of _obj_ * (that is, _size_ references to the same * _obj_). The third form creates a copy of the array * passed as a parameter (the array is generated by calling * to_ary on the parameter). In the last form, an array * of the given size is created. Each element in this array is * calculated by passing the element's index to the given block and * storing the return value. * * Array.new * Array.new(2) * Array.new(5, "A") * * # only one copy of the object is created * a = Array.new(2, Hash.new) * a[0]['cat'] = 'feline' * a * a[1]['cat'] = 'Felix' * a * * # here multiple copies are created * a = Array.new(2) { Hash.new } * a[0]['cat'] = 'feline' * a * * squares = Array.new(5) {|i| i*i} * squares * * copy = Array.new(squares) */ static VALUE rb_ary_initialize(argc, argv, ary) int argc; VALUE *argv; VALUE ary; { long len; VALUE size, val; rb_ary_modify(ary); if (rb_scan_args(argc, argv, "02", &size, &val) == 0) { RARRAY(ary)->len = 0; if (rb_block_given_p()) { rb_warning("given block not used"); } return ary; } if (argc == 1 && !FIXNUM_P(size)) { val = rb_check_array_type(size); if (!NIL_P(val)) { rb_ary_replace(ary, val); return ary; } } len = NUM2LONG(size); if (len < 0) { rb_raise(rb_eArgError, "negative array size"); } if (len > ARY_MAX_SIZE) { rb_raise(rb_eArgError, "array size too big"); } if (len > RARRAY(ary)->aux.capa) { REALLOC_N(RARRAY(ary)->ptr, VALUE, len); RARRAY(ary)->aux.capa = len; } if (rb_block_given_p()) { long i; if (argc == 2) { rb_warn("block supersedes default value argument"); } for (i=0; i<len; i++) { rb_ary_store(ary, i, rb_yield(LONG2NUM(i))); RARRAY(ary)->len = i + 1; } } else { memfill(RARRAY(ary)->ptr, len, val); RARRAY(ary)->len = len; } return ary; } /* * Returns a new array populated with the given objects. * * Array.[]( 1, 'a', /^A/ ) * Array[ 1, 'a', /^A/ ] * [ 1, 'a', /^A/ ] */ static VALUE rb_ary_s_create(argc, argv, klass) int argc; VALUE *argv; VALUE klass; { VALUE ary = ary_alloc(klass); if (argc > 0) { RARRAY(ary)->ptr = ALLOC_N(VALUE, argc); MEMCPY(RARRAY(ary)->ptr, argv, VALUE, argc); } RARRAY(ary)->len = RARRAY(ary)->aux.capa = argc; return ary; } void rb_ary_store(ary, idx, val) VALUE ary; long idx; VALUE val; { if (idx < 0) { idx += RARRAY(ary)->len; if (idx < 0) { rb_raise(rb_eIndexError, "index %ld out of array", idx - RARRAY(ary)->len); } } else if (idx >= ARY_MAX_SIZE) { rb_raise(rb_eIndexError, "index %ld too big", idx); } rb_ary_modify(ary); if (idx >= RARRAY(ary)->aux.capa) { long new_capa = RARRAY(ary)->aux.capa / 2; if (new_capa < ARY_DEFAULT_SIZE) { new_capa = ARY_DEFAULT_SIZE; } if (new_capa >= ARY_MAX_SIZE - idx) { new_capa = (ARY_MAX_SIZE - idx) / 2; } new_capa += idx; REALLOC_N(RARRAY(ary)->ptr, VALUE, new_capa); RARRAY(ary)->aux.capa = new_capa; } if (idx > RARRAY(ary)->len) { rb_mem_clear(RARRAY(ary)->ptr + RARRAY(ary)->len, idx-RARRAY(ary)->len + 1); } if (idx >= RARRAY(ary)->len) { RARRAY(ary)->len = idx + 1; } RARRAY(ary)->ptr[idx] = val; } /* * call-seq: * array << obj -> array * * Append---Pushes the given object on to the end of this array. This * expression returns the array itself, so several appends * may be chained together. * * [ 1, 2 ] << "c" << "d" << [ 3, 4 ] * #=> [ 1, 2, "c", "d", [ 3, 4 ] ] * */ VALUE rb_ary_push(ary, item) VALUE ary; VALUE item; { rb_ary_store(ary, RARRAY(ary)->len, item); return ary; } /* * call-seq: * array.push(obj, ... ) -> array * * Append---Pushes the given object(s) on to the end of this array. This * expression returns the array itself, so several appends * may be chained together. * * a = [ "a", "b", "c" ] * a.push("d", "e", "f") * #=> ["a", "b", "c", "d", "e", "f"] */ static VALUE rb_ary_push_m(argc, argv, ary) int argc; VALUE *argv; VALUE ary; { while (argc--) { rb_ary_push(ary, *argv++); } return ary; } /* * call-seq: * array.pop -> obj or nil * * Removes the last element from <i>self</i> and returns it, or * <code>nil</code> if the array is empty. * * a = [ "a", "m", "z" ] * a.pop #=> "z" * a #=> ["a", "m"] */ VALUE rb_ary_pop(ary) VALUE ary; { rb_ary_modify_check(ary); if (RARRAY(ary)->len == 0) return Qnil; if (!FL_TEST(ary, ELTS_SHARED) && RARRAY(ary)->len * 2 < RARRAY(ary)->aux.capa && RARRAY(ary)->aux.capa > ARY_DEFAULT_SIZE) { RARRAY(ary)->aux.capa = RARRAY(ary)->len * 2; REALLOC_N(RARRAY(ary)->ptr, VALUE, RARRAY(ary)->aux.capa); } return RARRAY(ary)->ptr[--RARRAY(ary)->len]; } static VALUE ary_make_shared(ary) VALUE ary; { if (!FL_TEST(ary, ELTS_SHARED)) { NEWOBJ(shared, struct RArray); OBJSETUP(shared, rb_cArray, T_ARRAY); shared->len = RARRAY(ary)->len; shared->ptr = RARRAY(ary)->ptr; shared->aux.capa = RARRAY(ary)->aux.capa; RARRAY(ary)->aux.shared = (VALUE)shared; FL_SET(ary, ELTS_SHARED); OBJ_FREEZE(shared); return (VALUE)shared; } else { return RARRAY(ary)->aux.shared; } } /* * call-seq: * array.shift -> obj or nil * * Returns the first element of <i>self</i> and removes it (shifting all * other elements down by one). Returns <code>nil</code> if the array * is empty. * * args = [ "-m", "-q", "filename" ] * args.shift #=> "-m" * args #=> ["-q", "filename"] */ VALUE rb_ary_shift(ary) VALUE ary; { VALUE top; rb_ary_modify_check(ary); if (RARRAY(ary)->len == 0) return Qnil; top = RARRAY(ary)->ptr[0]; if (RARRAY_LEN(ary) < ARY_DEFAULT_SIZE && !FL_TEST(ary, ELTS_SHARED)) { MEMMOVE(RARRAY_PTR(ary), RARRAY_PTR(ary)+1, VALUE, RARRAY_LEN(ary)-1); } else { if (!FL_TEST(ary, ELTS_SHARED)) { RARRAY(ary)->ptr[0] = Qnil; } ary_make_shared(ary); RARRAY(ary)->ptr++; /* shift ptr */ } RARRAY(ary)->len--; return top; } VALUE rb_ary_unshift(ary, item) VALUE ary, item; { rb_ary_modify(ary); if (RARRAY(ary)->len == RARRAY(ary)->aux.capa) { long capa_inc = RARRAY(ary)->aux.capa / 2; if (capa_inc < ARY_DEFAULT_SIZE) { capa_inc = ARY_DEFAULT_SIZE; } RARRAY(ary)->aux.capa += capa_inc; REALLOC_N(RARRAY(ary)->ptr, VALUE, RARRAY(ary)->aux.capa); } /* sliding items */ MEMMOVE(RARRAY(ary)->ptr + 1, RARRAY(ary)->ptr, VALUE, RARRAY(ary)->len); RARRAY(ary)->len++; RARRAY(ary)->ptr[0] = item; return ary; } /* * call-seq: * array.unshift(obj, ...) -> array * * Prepends objects to the front of <i>array</i>. * other elements up one. * * a = [ "b", "c", "d" ] * a.unshift("a") #=> ["a", "b", "c", "d"] * a.unshift(1, 2) #=> [ 1, 2, "a", "b", "c", "d"] */ static VALUE rb_ary_unshift_m(argc, argv, ary) int argc; VALUE *argv; VALUE ary; { long len = RARRAY(ary)->len; if (argc == 0) return ary; /* make rooms by setting the last item */ rb_ary_store(ary, len + argc - 1, Qnil); /* sliding items */ MEMMOVE(RARRAY(ary)->ptr + argc, RARRAY(ary)->ptr, VALUE, len); MEMCPY(RARRAY(ary)->ptr, argv, VALUE, argc); return ary; } /* faster version - use this if you don't need to treat negative offset */ static inline VALUE rb_ary_elt(ary, offset) VALUE ary; long offset; { if (RARRAY(ary)->len == 0) return Qnil; if (offset < 0 || RARRAY(ary)->len <= offset) { return Qnil; } return RARRAY(ary)->ptr[offset]; } VALUE rb_ary_entry(ary, offset) VALUE ary; long offset; { if (offset < 0) { offset += RARRAY(ary)->len; } return rb_ary_elt(ary, offset); } static VALUE rb_ary_subseq(ary, beg, len) VALUE ary; long beg, len; { VALUE klass, ary2, shared; VALUE *ptr; if (beg > RARRAY(ary)->len) return Qnil; if (beg < 0 || len < 0) return Qnil; if (RARRAY(ary)->len < len || RARRAY(ary)->len < beg + len) { len = RARRAY(ary)->len - beg; if (len < 0) len = 0; } klass = rb_obj_class(ary); if (len == 0) return ary_new(klass, 0); shared = ary_make_shared(ary); ptr = RARRAY(ary)->ptr; ary2 = ary_alloc(klass); RARRAY(ary2)->ptr = ptr + beg; RARRAY(ary2)->len = len; RARRAY(ary2)->aux.shared = shared; FL_SET(ary2, ELTS_SHARED); return ary2; } /* * call-seq: * array[index] -> obj or nil * array[start, length] -> an_array or nil * array[range] -> an_array or nil * array.slice(index) -> obj or nil * array.slice(start, length) -> an_array or nil * array.slice(range) -> an_array or nil * * Element Reference---Returns the element at _index_, * or returns a subarray starting at _start_ and * continuing for _length_ elements, or returns a subarray * specified by _range_. * Negative indices count backward from the end of the * array (-1 is the last element). Returns nil if the index * (or starting index) are out of range. * * a = [ "a", "b", "c", "d", "e" ] * a[2] + a[0] + a[1] #=> "cab" * a[6] #=> nil * a[1, 2] #=> [ "b", "c" ] * a[1..3] #=> [ "b", "c", "d" ] * a[4..7] #=> [ "e" ] * a[6..10] #=> nil * a[-3, 3] #=> [ "c", "d", "e" ] * # special cases * a[5] #=> nil * a[5, 1] #=> [] * a[5..10] #=> [] * */ VALUE rb_ary_aref(argc, argv, ary) int argc; VALUE *argv; VALUE ary; { VALUE arg; long beg, len; if (argc == 2) { if (SYMBOL_P(argv[0])) { rb_raise(rb_eTypeError, "Symbol as array index"); } beg = NUM2LONG(argv[0]); len = NUM2LONG(argv[1]); if (beg < 0) { beg += RARRAY(ary)->len; } return rb_ary_subseq(ary, beg, len); } if (argc != 1) { rb_scan_args(argc, argv, "11", 0, 0); } arg = argv[0]; /* special case - speeding up */ if (FIXNUM_P(arg)) { return rb_ary_entry(ary, FIX2LONG(arg)); } if (SYMBOL_P(arg)) { rb_raise(rb_eTypeError, "Symbol as array index"); } /* check if idx is Range */ switch (rb_range_beg_len(arg, &beg, &len, RARRAY(ary)->len, 0)) { case Qfalse: break; case Qnil: return Qnil; default: return rb_ary_subseq(ary, beg, len); } return rb_ary_entry(ary, NUM2LONG(arg)); } /* * call-seq: * array.at(index) -> obj or nil * * Returns the element at _index_. A * negative index counts from the end of _self_. Returns +nil+ * if the index is out of range. See also <code>Array#[]</code>. * (<code>Array#at</code> is slightly faster than <code>Array#[]</code>, * as it does not accept ranges and so on.) * * a = [ "a", "b", "c", "d", "e" ] * a.at(0) #=> "a" * a.at(-1) #=> "e" */ static VALUE rb_ary_at(ary, pos) VALUE ary, pos; { return rb_ary_entry(ary, NUM2LONG(pos)); } /* * call-seq: * array.first -> obj or nil * array.first(n) -> an_array * * Returns the first element, or the first +n+ elements, of the array. * If the array is empty, the first form returns <code>nil</code>, and the * second form returns an empty array. * * a = [ "q", "r", "s", "t" ] * a.first #=> "q" * a.first(1) #=> ["q"] * a.first(3) #=> ["q", "r", "s"] */ static VALUE rb_ary_first(argc, argv, ary) int argc; VALUE *argv; VALUE ary; { if (argc == 0) { if (RARRAY(ary)->len == 0) return Qnil; return RARRAY(ary)->ptr[0]; } else { VALUE nv, result; long n, i; rb_scan_args(argc, argv, "01", &nv); n = NUM2LONG(nv); if (n > RARRAY(ary)->len) n = RARRAY(ary)->len; result = rb_ary_new2(n); for (i=0; i<n; i++) { rb_ary_push(result, RARRAY(ary)->ptr[i]); } return result; } } /* * call-seq: * array.last -> obj or nil * array.last(n) -> an_array * * Returns the last element(s) of <i>self</i>. If the array is empty, * the first form returns <code>nil</code>. * * [ "w", "x", "y", "z" ].last #=> "z" */ static VALUE rb_ary_last(argc, argv, ary) int argc; VALUE *argv; VALUE ary; { if (argc == 0) { if (RARRAY(ary)->len == 0) return Qnil; return RARRAY(ary)->ptr[RARRAY(ary)->len-1]; } else { VALUE nv, result; long n, i; rb_scan_args(argc, argv, "01", &nv); n = NUM2LONG(nv); if (n > RARRAY(ary)->len) n = RARRAY(ary)->len; result = rb_ary_new2(n); for (i=RARRAY(ary)->len-n; n--; i++) { rb_ary_push(result, RARRAY(ary)->ptr[i]); } return result; } } /* * call-seq: * array.fetch(index) -> obj * array.fetch(index, default ) -> obj * array.fetch(index) {|index| block } -> obj * * Tries to return the element at position <i>index</i>. If the index * lies outside the array, the first form throws an * <code>IndexError</code> exception, the second form returns * <i>default</i>, and the third form returns the value of invoking * the block, passing in the index. Negative values of <i>index</i> * count from the end of the array. * * a = [ 11, 22, 33, 44 ] * a.fetch(1) #=> 22 * a.fetch(-1) #=> 44 * a.fetch(4, 'cat') #=> "cat" * a.fetch(4) { |i| i*i } #=> 16 */ static VALUE rb_ary_fetch(argc, argv, ary) int argc; VALUE *argv; VALUE ary; { VALUE pos, ifnone; long block_given; long idx; rb_scan_args(argc, argv, "11", &pos, &ifnone); block_given = rb_block_given_p(); if (block_given && argc == 2) { rb_warn("block supersedes default value argument"); } idx = NUM2LONG(pos); if (idx < 0) { idx += RARRAY(ary)->len; } if (idx < 0 || RARRAY(ary)->len <= idx) { if (block_given) return rb_yield(pos); if (argc == 1) { rb_raise(rb_eIndexError, "index %ld out of array", idx); } return ifnone; } return RARRAY(ary)->ptr[idx]; } /* * call-seq: * array.index(obj) -> int or nil * * Returns the index of the first object in <i>self</i> such that is * <code>==</code> to <i>obj</i>. Returns <code>nil</code> if * no match is found. * * a = [ "a", "b", "c" ] * a.index("b") #=> 1 * a.index("z") #=> nil */ static VALUE rb_ary_index(ary, val) VALUE ary; VALUE val; { long i; for (i=0; i<RARRAY(ary)->len; i++) { if (rb_equal(RARRAY(ary)->ptr[i], val)) return LONG2NUM(i); } return Qnil; } /* * call-seq: * array.rindex(obj) -> int or nil * * Returns the index of the last object in <i>array</i> * <code>==</code> to <i>obj</i>. Returns <code>nil</code> if * no match is found. * * a = [ "a", "b", "b", "b", "c" ] * a.rindex("b") #=> 3 * a.rindex("z") #=> nil */ static VALUE rb_ary_rindex(ary, val) VALUE ary; VALUE val; { long i = RARRAY(ary)->len; while (i--) { if (i > RARRAY(ary)->len) { i = RARRAY(ary)->len; continue; } if (rb_equal(RARRAY(ary)->ptr[i], val)) return LONG2NUM(i); } return Qnil; } /* * call-seq: * array.indexes( i1, i2, ... iN ) -> an_array * array.indices( i1, i2, ... iN ) -> an_array * * Deprecated; use <code>Array#values_at</code>. */ static VALUE rb_ary_indexes(argc, argv, ary) int argc; VALUE *argv; VALUE ary; { VALUE new_ary; long i; rb_warn("Array#%s is deprecated; use Array#values_at", rb_id2name(rb_frame_last_func())); new_ary = rb_ary_new2(argc); for (i=0; i<argc; i++) { rb_ary_push(new_ary, rb_ary_aref(1, argv+i, ary)); } return new_ary; } VALUE rb_ary_to_ary(obj) VALUE obj; { if (TYPE(obj) == T_ARRAY) { return obj; } if (rb_respond_to(obj, rb_intern("to_ary"))) { return rb_convert_type(obj, T_ARRAY, "Array", "to_ary"); } return rb_ary_new3(1, obj); } static void rb_ary_splice(ary, beg, len, rpl) VALUE ary; long beg, len; VALUE rpl; { long rlen; if (len < 0) rb_raise(rb_eIndexError, "negative length (%ld)", len); if (beg < 0) { beg += RARRAY(ary)->len; if (beg < 0) { beg -= RARRAY(ary)->len; rb_raise(rb_eIndexError, "index %ld out of array", beg); } } if (RARRAY(ary)->len < len || RARRAY(ary)->len < beg + len) { len = RARRAY(ary)->len - beg; } if (NIL_P(rpl)) { rlen = 0; } else { rpl = rb_ary_to_ary(rpl); rlen = RARRAY(rpl)->len; } rb_ary_modify(ary); if (beg >= RARRAY(ary)->len) { if (beg > ARY_MAX_SIZE - rlen) { rb_raise(rb_eIndexError, "index %ld too big", beg); } len = beg + rlen; if (len >= RARRAY(ary)->aux.capa) { REALLOC_N(RARRAY(ary)->ptr, VALUE, len); RARRAY(ary)->aux.capa = len; } rb_mem_clear(RARRAY(ary)->ptr + RARRAY(ary)->len, beg - RARRAY(ary)->len); if (rlen > 0) { MEMCPY(RARRAY(ary)->ptr + beg, RARRAY(rpl)->ptr, VALUE, rlen); } RARRAY(ary)->len = len; } else { long alen; if (beg + len > RARRAY(ary)->len) { len = RARRAY(ary)->len - beg; } alen = RARRAY(ary)->len + rlen - len; if (alen >= RARRAY(ary)->aux.capa) { REALLOC_N(RARRAY(ary)->ptr, VALUE, alen); RARRAY(ary)->aux.capa = alen; } if (len != rlen) { MEMMOVE(RARRAY(ary)->ptr + beg + rlen, RARRAY(ary)->ptr + beg + len, VALUE, RARRAY(ary)->len - (beg + len)); RARRAY(ary)->len = alen; } if (rlen > 0) { MEMMOVE(RARRAY(ary)->ptr + beg, RARRAY(rpl)->ptr, VALUE, rlen); } } } /* * call-seq: * array[index] = obj -> obj * array[start, length] = obj or an_array or nil -> obj or an_array or nil * array[range] = obj or an_array or nil -> obj or an_array or nil * * Element Assignment---Sets the element at _index_, * or replaces a subarray starting at _start_ and * continuing for _length_ elements, or replaces a subarray * specified by _range_. If indices are greater than * the current capacity of the array, the array grows * automatically. A negative indices will count backward * from the end of the array. Inserts elements if _length_ is * zero. If +nil+ is used in the second and third form, * deletes elements from _self_. An +IndexError+ is raised if a * negative index points past the beginning of the array. See also * <code>Array#push</code>, and <code>Array#unshift</code>. * * a = Array.new * a[4] = "4"; #=> [nil, nil, nil, nil, "4"] * a[0, 3] = [ 'a', 'b', 'c' ] #=> ["a", "b", "c", nil, "4"] * a[1..2] = [ 1, 2 ] #=> ["a", 1, 2, nil, "4"] * a[0, 2] = "?" #=> ["?", 2, nil, "4"] * a[0..2] = "A" #=> ["A", "4"] * a[-1] = "Z" #=> ["A", "Z"] * a[1..-1] = nil #=> ["A"] */ static VALUE rb_ary_aset(argc, argv, ary) int argc; VALUE *argv; VALUE ary; { long offset, beg, len; if (argc == 3) { if (SYMBOL_P(argv[0])) { rb_raise(rb_eTypeError, "Symbol as array index"); } if (SYMBOL_P(argv[1])) { rb_raise(rb_eTypeError, "Symbol as subarray length"); } rb_ary_splice(ary, NUM2LONG(argv[0]), NUM2LONG(argv[1]), argv[2]); return argv[2]; } if (argc != 2) { rb_raise(rb_eArgError, "wrong number of arguments (%d for 2)", argc); } if (FIXNUM_P(argv[0])) { offset = FIX2LONG(argv[0]); goto fixnum; } if (SYMBOL_P(argv[0])) { rb_raise(rb_eTypeError, "Symbol as array index"); } if (rb_range_beg_len(argv[0], &beg, &len, RARRAY(ary)->len, 1)) { /* check if idx is Range */ rb_ary_splice(ary, beg, len, argv[1]); return argv[1]; } offset = NUM2LONG(argv[0]); fixnum: rb_ary_store(ary, offset, argv[1]); return argv[1]; } /* * call-seq: * array.insert(index, obj...) -> array * * Inserts the given values before the element with the given index * (which may be negative). * * a = %w{ a b c d } * a.insert(2, 99) #=> ["a", "b", 99, "c", "d"] * a.insert(-2, 1, 2, 3) #=> ["a", "b", 99, "c", 1, 2, 3, "d"] */ static VALUE rb_ary_insert(argc, argv, ary) int argc; VALUE *argv; VALUE ary; { long pos; if (argc == 1) return ary; if (argc < 1) { rb_raise(rb_eArgError, "wrong number of arguments (at least 1)"); } pos = NUM2LONG(argv[0]); if (pos == -1) { pos = RARRAY(ary)->len; } if (pos < 0) { pos++; } rb_ary_splice(ary, pos, 0, rb_ary_new4(argc - 1, argv + 1)); return ary; } /* * call-seq: * array.each {|item| block } -> array * * Calls <i>block</i> once for each element in <i>self</i>, passing that * element as a parameter. * * a = [ "a", "b", "c" ] * a.each {|x| print x, " -- " } * * produces: * * a -- b -- c -- */ VALUE rb_ary_each(ary) VALUE ary; { long i; for (i=0; i<RARRAY(ary)->len; i++) { rb_yield(RARRAY(ary)->ptr[i]); } return ary; } /* * call-seq: * array.each_index {|index| block } -> array * * Same as <code>Array#each</code>, but passes the index of the element * instead of the element itself. * * a = [ "a", "b", "c" ] * a.each_index {|x| print x, " -- " } * * produces: * * 0 -- 1 -- 2 -- */ static VALUE rb_ary_each_index(ary) VALUE ary; { long i; for (i=0; i<RARRAY(ary)->len; i++) { rb_yield(LONG2NUM(i)); } return ary; } /* * call-seq: * array.reverse_each {|item| block } * * Same as <code>Array#each</code>, but traverses <i>self</i> in reverse * order. * * a = [ "a", "b", "c" ] * a.reverse_each {|x| print x, " " } * * produces: * * c b a */ static VALUE rb_ary_reverse_each(ary) VALUE ary; { long len = RARRAY(ary)->len; while (len--) { rb_yield(RARRAY(ary)->ptr[len]); if (RARRAY(ary)->len < len) { len = RARRAY(ary)->len; } } return ary; } /* * call-seq: * array.length -> int * * Returns the number of elements in <i>self</i>. May be zero. * * [ 1, 2, 3, 4, 5 ].length #=> 5 */ static VALUE rb_ary_length(ary) VALUE ary; { return LONG2NUM(RARRAY(ary)->len); } /* * call-seq: * array.empty? -> true or false * * Returns <code>true</code> if <i>self</i> array contains no elements. * * [].empty? #=> true */ static VALUE rb_ary_empty_p(ary) VALUE ary; { if (RARRAY(ary)->len == 0) return Qtrue; return Qfalse; } VALUE rb_ary_dup(ary) VALUE ary; { VALUE dup = rb_ary_new2(RARRAY(ary)->len); DUPSETUP(dup, ary); MEMCPY(RARRAY(dup)->ptr, RARRAY(ary)->ptr, VALUE, RARRAY(ary)->len); RARRAY(dup)->len = RARRAY(ary)->len; return dup; } extern VALUE rb_output_fs; static VALUE inspect_join(ary, arg) VALUE ary; VALUE *arg; { return rb_ary_join(arg[0], arg[1]); } VALUE rb_ary_join(ary, sep) VALUE ary, sep; { long len = 1, i; int taint = Qfalse; VALUE result, tmp; if (RARRAY(ary)->len == 0) return rb_str_new(0, 0); if (OBJ_TAINTED(ary) || OBJ_TAINTED(sep)) taint = Qtrue; for (i=0; i<RARRAY(ary)->len; i++) { tmp = rb_check_string_type(RARRAY(ary)->ptr[i]); len += NIL_P(tmp) ? 10 : RSTRING(tmp)->len; } if (!NIL_P(sep)) { StringValue(sep); len += RSTRING(sep)->len * (RARRAY(ary)->len - 1); } result = rb_str_buf_new(len); for (i=0; i<RARRAY(ary)->len; i++) { tmp = RARRAY(ary)->ptr[i]; switch (TYPE(tmp)) { case T_STRING: break; case T_ARRAY: if (tmp == ary || rb_inspecting_p(tmp)) { tmp = rb_str_new2("[...]"); } else { VALUE args[2]; args[0] = tmp; args[1] = sep; tmp = rb_protect_inspect(inspect_join, ary, (VALUE)args); } break; default: tmp = rb_obj_as_string(tmp); } if (i > 0 && !NIL_P(sep)) rb_str_buf_append(result, sep); rb_str_buf_append(result, tmp); if (OBJ_TAINTED(tmp)) taint = Qtrue; } if (taint) OBJ_TAINT(result); return result; } /* * call-seq: * array.join(sep=$,) -> str * * Returns a string created by converting each element of the array to * a string, separated by <i>sep</i>. * * [ "a", "b", "c" ].join #=> "abc" * [ "a", "b", "c" ].join("-") #=> "a-b-c" */ static VALUE rb_ary_join_m(argc, argv, ary) int argc; VALUE *argv; VALUE ary; { VALUE sep; rb_scan_args(argc, argv, "01", &sep); if (NIL_P(sep)) sep = rb_output_fs; return rb_ary_join(ary, sep); } /* * call-seq: * array.to_s -> string * * Returns _self_<code>.join</code>. * * [ "a", "e", "i", "o" ].to_s #=> "aeio" * */ VALUE rb_ary_to_s(ary) VALUE ary; { if (RARRAY(ary)->len == 0) return rb_str_new(0, 0); return rb_ary_join(ary, rb_output_fs); } static ID inspect_key; struct inspect_arg { VALUE (*func)(); VALUE arg1, arg2; }; static VALUE inspect_call(arg) struct inspect_arg *arg; { return (*arg->func)(arg->arg1, arg->arg2); } static VALUE get_inspect_tbl(create) int create; { VALUE inspect_tbl = rb_thread_local_aref(rb_thread_current(), inspect_key); if (NIL_P(inspect_tbl)) { if (create) { tbl_init: inspect_tbl = rb_ary_new(); rb_thread_local_aset(rb_thread_current(), inspect_key, inspect_tbl); } } else if (TYPE(inspect_tbl) != T_ARRAY) { rb_warn("invalid inspect_tbl value"); if (create) goto tbl_init; rb_thread_local_aset(rb_thread_current(), inspect_key, Qnil); return Qnil; } return inspect_tbl; } static VALUE inspect_ensure(obj) VALUE obj; { VALUE inspect_tbl; inspect_tbl = get_inspect_tbl(Qfalse); if (!NIL_P(inspect_tbl)) { rb_ary_pop(inspect_tbl); } return 0; } VALUE rb_protect_inspect(func, obj, arg) VALUE (*func)(ANYARGS); VALUE obj, arg; { struct inspect_arg iarg; VALUE inspect_tbl; VALUE id; inspect_tbl = get_inspect_tbl(Qtrue); id = rb_obj_id(obj); if (rb_ary_includes(inspect_tbl, id)) { return (*func)(obj, arg); } rb_ary_push(inspect_tbl, id); iarg.func = func; iarg.arg1 = obj; iarg.arg2 = arg; return rb_ensure(inspect_call, (VALUE)&iarg, inspect_ensure, obj); } VALUE rb_inspecting_p(obj) VALUE obj; { VALUE inspect_tbl; inspect_tbl = get_inspect_tbl(Qfalse); if (NIL_P(inspect_tbl)) return Qfalse; return rb_ary_includes(inspect_tbl, rb_obj_id(obj)); } static VALUE inspect_ary(ary) VALUE ary; { int tainted = OBJ_TAINTED(ary); long i; VALUE s, str; str = rb_str_buf_new2("["); for (i=0; i<RARRAY(ary)->len; i++) { s = rb_inspect(RARRAY(ary)->ptr[i]); if (OBJ_TAINTED(s)) tainted = Qtrue; if (i > 0) rb_str_buf_cat2(str, ", "); rb_str_buf_append(str, s); } rb_str_buf_cat2(str, "]"); if (tainted) OBJ_TAINT(str); return str; } /* * call-seq: * array.inspect -> string * * Create a printable version of <i>array</i>. */ static VALUE rb_ary_inspect(ary) VALUE ary; { if (RARRAY(ary)->len == 0) return rb_str_new2("[]"); if (rb_inspecting_p(ary)) return rb_str_new2("[...]"); return rb_protect_inspect(inspect_ary, ary, 0); } /* * call-seq: * array.to_a -> array * * Returns _self_. If called on a subclass of Array, converts * the receiver to an Array object. */ static VALUE rb_ary_to_a(ary) VALUE ary; { if (rb_obj_class(ary) != rb_cArray) { VALUE dup = rb_ary_new2(RARRAY(ary)->len); rb_ary_replace(dup, ary); return dup; } return ary; } /* * call-seq: * array.to_ary -> array * * Returns _self_. */ static VALUE rb_ary_to_ary_m(ary) VALUE ary; { return ary; } VALUE rb_ary_reverse(ary) VALUE ary; { VALUE *p1, *p2; VALUE tmp; rb_ary_modify(ary); if (RARRAY(ary)->len > 1) { p1 = RARRAY(ary)->ptr; p2 = p1 + RARRAY(ary)->len - 1; /* points last item */ while (p1 < p2) { tmp = *p1; *p1++ = *p2; *p2-- = tmp; } } return ary; } /* * call-seq: * array.reverse! -> array * * Reverses _self_ in place. * * a = [ "a", "b", "c" ] * a.reverse! #=> ["c", "b", "a"] * a #=> ["c", "b", "a"] */ static VALUE rb_ary_reverse_bang(ary) VALUE ary; { return rb_ary_reverse(ary); } /* * call-seq: * array.reverse -> an_array * * Returns a new array containing <i>self</i>'s elements in reverse order. * * [ "a", "b", "c" ].reverse #=> ["c", "b", "a"] * [ 1 ].reverse #=> [1] */ static VALUE rb_ary_reverse_m(ary) VALUE ary; { return rb_ary_reverse(rb_ary_dup(ary)); } struct ary_sort_data { VALUE ary; VALUE *ptr; long len; }; static void ary_sort_check(data) struct ary_sort_data *data; { if (RARRAY(data->ary)->ptr != data->ptr || RARRAY(data->ary)->len != data->len) { rb_raise(rb_eArgError, "array modified during sort"); } } static int sort_1(a, b, data) VALUE *a, *b; struct ary_sort_data *data; { VALUE retval = rb_yield_values(2, *a, *b); int n; n = rb_cmpint(retval, *a, *b); ary_sort_check(data); return n; } static int sort_2(ap, bp, data) VALUE *ap, *bp; struct ary_sort_data *data; { VALUE retval; VALUE a = *ap, b = *bp; int n; if (FIXNUM_P(a) && FIXNUM_P(b)) { if ((long)a > (long)b) return 1; if ((long)a < (long)b) return -1; return 0; } if (TYPE(a) == T_STRING) { if (TYPE(b) == T_STRING) return rb_str_cmp(a, b); } retval = rb_funcall(a, id_cmp, 1, b); n = rb_cmpint(retval, a, b); ary_sort_check(data); return n; } static VALUE sort_internal(ary) VALUE ary; { struct ary_sort_data data; data.ary = ary; data.ptr = RARRAY(ary)->ptr; data.len = RARRAY(ary)->len; qsort(RARRAY(ary)->ptr, RARRAY(ary)->len, sizeof(VALUE), rb_block_given_p()?sort_1:sort_2, &data); return ary; } static VALUE sort_unlock(ary) VALUE ary; { FL_UNSET(ary, ARY_TMPLOCK); return ary; } /* * call-seq: * array.sort! -> array * array.sort! {| a,b | block } -> array * * Sorts _self_. Comparisons for * the sort will be done using the <code><=></code> operator or using * an optional code block. The block implements a comparison between * <i>a</i> and <i>b</i>, returning -1, 0, or +1. See also * <code>Enumerable#sort_by</code>. * * a = [ "d", "a", "e", "c", "b" ] * a.sort #=> ["a", "b", "c", "d", "e"] * a.sort {|x,y| y <=> x } #=> ["e", "d", "c", "b", "a"] */ VALUE rb_ary_sort_bang(ary) VALUE ary; { rb_ary_modify(ary); if (RARRAY(ary)->len > 1) { FL_SET(ary, ARY_TMPLOCK); /* prohibit modification during sort */ rb_ensure(sort_internal, ary, sort_unlock, ary); } return ary; } /* * call-seq: * array.sort -> an_array * array.sort {| a,b | block } -> an_array * * Returns a new array created by sorting <i>self</i>. Comparisons for * the sort will be done using the <code><=></code> operator or using * an optional code block. The block implements a comparison between * <i>a</i> and <i>b</i>, returning -1, 0, or +1. See also * <code>Enumerable#sort_by</code>. * * a = [ "d", "a", "e", "c", "b" ] * a.sort #=> ["a", "b", "c", "d", "e"] * a.sort {|x,y| y <=> x } #=> ["e", "d", "c", "b", "a"] */ VALUE rb_ary_sort(ary) VALUE ary; { ary = rb_ary_dup(ary); rb_ary_sort_bang(ary); return ary; } /* * call-seq: * array.collect {|item| block } -> an_array * array.map {|item| block } -> an_array * * Invokes <i>block</i> once for each element of <i>self</i>. Creates a * new array containing the values returned by the block. * See also <code>Enumerable#collect</code>. * * a = [ "a", "b", "c", "d" ] * a.collect {|x| x + "!" } #=> ["a!", "b!", "c!", "d!"] * a #=> ["a", "b", "c", "d"] */ static VALUE rb_ary_collect(ary) VALUE ary; { long i; VALUE collect; if (!rb_block_given_p()) { return rb_ary_new4(RARRAY(ary)->len, RARRAY(ary)->ptr); } collect = rb_ary_new2(RARRAY(ary)->len); for (i = 0; i < RARRAY(ary)->len; i++) { rb_ary_push(collect, rb_yield(RARRAY(ary)->ptr[i])); } return collect; } /* * call-seq: * array.collect! {|item| block } -> array * array.map! {|item| block } -> array * * Invokes the block once for each element of _self_, replacing the * element with the value returned by _block_. * See also <code>Enumerable#collect</code>. * * a = [ "a", "b", "c", "d" ] * a.collect! {|x| x + "!" } * a #=> [ "a!", "b!", "c!", "d!" ] */ static VALUE rb_ary_collect_bang(ary) VALUE ary; { long i; rb_ary_modify(ary); for (i = 0; i < RARRAY(ary)->len; i++) { rb_ary_store(ary, i, rb_yield(RARRAY(ary)->ptr[i])); } return ary; } VALUE rb_values_at(obj, olen, argc, argv, func) VALUE obj; long olen; int argc; VALUE *argv; VALUE (*func) _((VALUE,long)); { VALUE result = rb_ary_new2(argc); long beg, len, i, j; for (i=0; i<argc; i++) { if (FIXNUM_P(argv[i])) { rb_ary_push(result, (*func)(obj, FIX2LONG(argv[i]))); continue; } /* check if idx is Range */ switch (rb_range_beg_len(argv[i], &beg, &len, olen, 0)) { case Qfalse: break; case Qnil: continue; default: for (j=0; j<len; j++) { rb_ary_push(result, (*func)(obj, j+beg)); } continue; } rb_ary_push(result, (*func)(obj, NUM2LONG(argv[i]))); } return result; } /* * call-seq: * array.values_at(selector,... ) -> an_array * * Returns an array containing the elements in * _self_ corresponding to the given selector(s). The selectors * may be either integer indices or ranges. * See also <code>Array#select</code>. * * a = %w{ a b c d e f } * a.values_at(1, 3, 5) * a.values_at(1, 3, 5, 7) * a.values_at(-1, -3, -5, -7) * a.values_at(1..3, 2...5) */ static VALUE rb_ary_values_at(argc, argv, ary) int argc; VALUE *argv; VALUE ary; { return rb_values_at(ary, RARRAY(ary)->len, argc, argv, rb_ary_entry); } /* * call-seq: * array.select {|item| block } -> an_array * * Invokes the block passing in successive elements from <i>array</i>, * returning an array containing those elements for which the block * returns a true value (equivalent to <code>Enumerable#select</code>). * * a = %w{ a b c d e f } * a.select {|v| v =~ /[aeiou]/} #=> ["a", "e"] */ static VALUE rb_ary_select(ary) VALUE ary; { VALUE result; long i; result = rb_ary_new2(RARRAY(ary)->len); for (i = 0; i < RARRAY(ary)->len; i++) { if (RTEST(rb_yield(RARRAY(ary)->ptr[i]))) { rb_ary_push(result, rb_ary_elt(ary, i)); } } return result; } /* * call-seq: * array.delete(obj) -> obj or nil * array.delete(obj) { block } -> obj or nil * * Deletes items from <i>self</i> that are equal to <i>obj</i>. If * the item is not found, returns <code>nil</code>. If the optional * code block is given, returns the result of <i>block</i> if the item * is not found. * * a = [ "a", "b", "b", "b", "c" ] * a.delete("b") #=> "b" * a #=> ["a", "c"] * a.delete("z") #=> nil * a.delete("z") { "not found" } #=> "not found" */ VALUE rb_ary_delete(ary, item) VALUE ary; VALUE item; { long i1, i2; for (i1 = i2 = 0; i1 < RARRAY(ary)->len; i1++) { VALUE e = RARRAY(ary)->ptr[i1]; if (rb_equal(e, item)) continue; if (i1 != i2) { rb_ary_store(ary, i2, e); } i2++; } if (RARRAY(ary)->len == i2) { if (rb_block_given_p()) { return rb_yield(item); } return Qnil; } rb_ary_modify(ary); if (RARRAY(ary)->len > i2) { RARRAY(ary)->len = i2; if (i2 * 2 < RARRAY(ary)->aux.capa && RARRAY(ary)->aux.capa > ARY_DEFAULT_SIZE) { REALLOC_N(RARRAY(ary)->ptr, VALUE, i2 * 2); RARRAY(ary)->aux.capa = i2 * 2; } } return item; } VALUE rb_ary_delete_at(ary, pos) VALUE ary; long pos; { long i, len = RARRAY(ary)->len; VALUE del; if (pos >= len) return Qnil; if (pos < 0) { pos += len; if (pos < 0) return Qnil; } rb_ary_modify(ary); del = RARRAY(ary)->ptr[pos]; for (i = pos + 1; i < len; i++, pos++) { RARRAY(ary)->ptr[pos] = RARRAY(ary)->ptr[i]; } RARRAY(ary)->len = pos; return del; } /* * call-seq: * array.delete_at(index) -> obj or nil * * Deletes the element at the specified index, returning that element, * or <code>nil</code> if the index is out of range. See also * <code>Array#slice!</code>. * * a = %w( ant bat cat dog ) * a.delete_at(2) #=> "cat" * a #=> ["ant", "bat", "dog"] * a.delete_at(99) #=> nil */ static VALUE rb_ary_delete_at_m(ary, pos) VALUE ary, pos; { return rb_ary_delete_at(ary, NUM2LONG(pos)); } /* * call-seq: * array.slice!(index) -> obj or nil * array.slice!(start, length) -> sub_array or nil * array.slice!(range) -> sub_array or nil * * Deletes the element(s) given by an index (optionally with a length) * or by a range. Returns the deleted object, subarray, or * <code>nil</code> if the index is out of range. Equivalent to: * * def slice!(*args) * result = self[*args] * self[*args] = nil * result * end * * a = [ "a", "b", "c" ] * a.slice!(1) #=> "b" * a #=> ["a", "c"] * a.slice!(-1) #=> "c" * a #=> ["a"] * a.slice!(100) #=> nil * a #=> ["a"] */ static VALUE rb_ary_slice_bang(argc, argv, ary) int argc; VALUE *argv; VALUE ary; { VALUE arg1, arg2; long pos, len; if (rb_scan_args(argc, argv, "11", &arg1, &arg2) == 2) { pos = NUM2LONG(arg1); len = NUM2LONG(arg2); delete_pos_len: if (pos < 0) { pos = RARRAY(ary)->len + pos; } arg2 = rb_ary_subseq(ary, pos, len); rb_ary_splice(ary, pos, len, Qnil); /* Qnil/rb_ary_new2(0) */ return arg2; } if (!FIXNUM_P(arg1) && rb_range_beg_len(arg1, &pos, &len, RARRAY(ary)->len, 1)) { goto delete_pos_len; } return rb_ary_delete_at(ary, NUM2LONG(arg1)); } /* * call-seq: * array.reject! {|item| block } -> array or nil * * Equivalent to <code>Array#delete_if</code>, deleting elements from * _self_ for which the block evaluates to true, but returns * <code>nil</code> if no changes were made. Also see * <code>Enumerable#reject</code>. */ static VALUE rb_ary_reject_bang(ary) VALUE ary; { long i1, i2; rb_ary_modify(ary); for (i1 = i2 = 0; i1 < RARRAY(ary)->len; i1++) { VALUE v = RARRAY(ary)->ptr[i1]; if (RTEST(rb_yield(v))) continue; if (i1 != i2) { rb_ary_store(ary, i2, v); } i2++; } if (RARRAY(ary)->len == i2) return Qnil; if (i2 < RARRAY(ary)->len) RARRAY(ary)->len = i2; return ary; } /* * call-seq: * array.reject {|item| block } -> an_array * * Returns a new array containing the items in _self_ * for which the block is not true. */ static VALUE rb_ary_reject(ary) VALUE ary; { ary = rb_ary_dup(ary); rb_ary_reject_bang(ary); return ary; } /* * call-seq: * array.delete_if {|item| block } -> array * * Deletes every element of <i>self</i> for which <i>block</i> evaluates * to <code>true</code>. * * a = [ "a", "b", "c" ] * a.delete_if {|x| x >= "b" } #=> ["a"] */ static VALUE rb_ary_delete_if(ary) VALUE ary; { rb_ary_reject_bang(ary); return ary; } /* * call-seq: * array.zip(arg, ...) -> an_array * array.zip(arg, ...) {| arr | block } -> nil * * Converts any arguments to arrays, then merges elements of * <i>self</i> with corresponding elements from each argument. This * generates a sequence of <code>self.size</code> <em>n</em>-element * arrays, where <em>n</em> is one more that the count of arguments. If * the size of any argument is less than <code>enumObj.size</code>, * <code>nil</code> values are supplied. If a block given, it is * invoked for each output array, otherwise an array of arrays is * returned. * * a = [ 4, 5, 6 ] * b = [ 7, 8, 9 ] * * [1,2,3].zip(a, b) #=> [[1, 4, 7], [2, 5, 8], [3, 6, 9]] * [1,2].zip(a,b) #=> [[1, 4, 7], [2, 5, 8]] * a.zip([1,2],[8]) #=> [[4,1,8], [5,2,nil], [6,nil,nil]] */ static VALUE rb_ary_zip(argc, argv, ary) int argc; VALUE *argv; VALUE ary; { int i, j; long len; VALUE result; for (i=0; i<argc; i++) { argv[i] = to_ary(argv[i]); } if (rb_block_given_p()) { for (i=0; i<RARRAY(ary)->len; i++) { VALUE tmp = rb_ary_new2(argc+1); rb_ary_push(tmp, rb_ary_elt(ary, i)); for (j=0; j<argc; j++) { rb_ary_push(tmp, rb_ary_elt(argv[j], i)); } rb_yield(tmp); } return Qnil; } len = RARRAY(ary)->len; result = rb_ary_new2(len); for (i=0; i<len; i++) { VALUE tmp = rb_ary_new2(argc+1); rb_ary_push(tmp, rb_ary_elt(ary, i)); for (j=0; j<argc; j++) { rb_ary_push(tmp, rb_ary_elt(argv[j], i)); } rb_ary_push(result, tmp); } return result; } /* * call-seq: * array.transpose -> an_array * * Assumes that <i>self</i> is an array of arrays and transposes the * rows and columns. * * a = [[1,2], [3,4], [5,6]] * a.transpose #=> [[1, 3, 5], [2, 4, 6]] */ static VALUE rb_ary_transpose(ary) VALUE ary; { long elen = -1, alen, i, j; VALUE tmp, result = 0; alen = RARRAY(ary)->len; if (alen == 0) return rb_ary_dup(ary); for (i=0; i<alen; i++) { tmp = to_ary(rb_ary_elt(ary, i)); if (elen < 0) { /* first element */ elen = RARRAY(tmp)->len; result = rb_ary_new2(elen); for (j=0; j<elen; j++) { rb_ary_store(result, j, rb_ary_new2(alen)); } } else if (elen != RARRAY(tmp)->len) { rb_raise(rb_eIndexError, "element size differs (%d should be %d)", RARRAY(tmp)->len, elen); } for (j=0; j<elen; j++) { rb_ary_store(rb_ary_elt(result, j), i, rb_ary_elt(tmp, j)); } } return result; } /* * call-seq: * array.replace(other_array) -> array * * Replaces the contents of <i>self</i> with the contents of * <i>other_array</i>, truncating or expanding if necessary. * * a = [ "a", "b", "c", "d", "e" ] * a.replace([ "x", "y", "z" ]) #=> ["x", "y", "z"] * a #=> ["x", "y", "z"] */ static VALUE rb_ary_replace(copy, orig) VALUE copy, orig; { VALUE shared; rb_ary_modify(copy); orig = to_ary(orig); if (copy == orig) return copy; shared = ary_make_shared(orig); if (RARRAY(copy)->ptr && !FL_TEST(copy, ELTS_SHARED)) free(RARRAY(copy)->ptr); RARRAY(copy)->ptr = RARRAY(orig)->ptr; RARRAY(copy)->len = RARRAY(orig)->len; RARRAY(copy)->aux.shared = shared; FL_SET(copy, ELTS_SHARED); return copy; } /* * call-seq: * array.clear -> array * * Removes all elements from _self_. * * a = [ "a", "b", "c", "d", "e" ] * a.clear #=> [ ] */ VALUE rb_ary_clear(ary) VALUE ary; { rb_ary_modify(ary); RARRAY(ary)->len = 0; if (ARY_DEFAULT_SIZE * 2 < RARRAY(ary)->aux.capa) { REALLOC_N(RARRAY(ary)->ptr, VALUE, ARY_DEFAULT_SIZE * 2); RARRAY(ary)->aux.capa = ARY_DEFAULT_SIZE * 2; } return ary; } /* * call-seq: * array.fill(obj) -> array * array.fill(obj, start [, length]) -> array * array.fill(obj, range ) -> array * array.fill {|index| block } -> array * array.fill(start [, length] ) {|index| block } -> array * array.fill(range) {|index| block } -> array * * The first three forms set the selected elements of <i>self</i> (which * may be the entire array) to <i>obj</i>. A <i>start</i> of * <code>nil</code> is equivalent to zero. A <i>length</i> of * <code>nil</code> is equivalent to <i>self.length</i>. The last three * forms fill the array with the value of the block. The block is * passed the absolute index of each element to be filled. * * a = [ "a", "b", "c", "d" ] * a.fill("x") #=> ["x", "x", "x", "x"] * a.fill("z", 2, 2) #=> ["x", "x", "z", "z"] * a.fill("y", 0..1) #=> ["y", "y", "z", "z"] * a.fill {|i| i*i} #=> [0, 1, 4, 9] * a.fill(-2) {|i| i*i*i} #=> [0, 1, 8, 27] */ static VALUE rb_ary_fill(argc, argv, ary) int argc; VALUE *argv; VALUE ary; { VALUE item, arg1, arg2; long beg = 0, end = 0, len = 0; VALUE *p, *pend; int block_p = Qfalse; if (rb_block_given_p()) { block_p = Qtrue; rb_scan_args(argc, argv, "02", &arg1, &arg2); argc += 1; /* hackish */ } else { rb_scan_args(argc, argv, "12", &item, &arg1, &arg2); } switch (argc) { case 1: beg = 0; len = RARRAY(ary)->len; break; case 2: if (rb_range_beg_len(arg1, &beg, &len, RARRAY(ary)->len, 1)) { break; } /* fall through */ case 3: beg = NIL_P(arg1) ? 0 : NUM2LONG(arg1); if (beg < 0) { beg = RARRAY(ary)->len + beg; if (beg < 0) beg = 0; } len = NIL_P(arg2) ? RARRAY(ary)->len - beg : NUM2LONG(arg2); break; } rb_ary_modify(ary); if (len < 0) { return ary; } if (beg >= ARY_MAX_SIZE || len > ARY_MAX_SIZE - beg) { rb_raise(rb_eArgError, "argument too big"); } end = beg + len; if (end > RARRAY(ary)->len) { if (end >= RARRAY(ary)->aux.capa) { REALLOC_N(RARRAY(ary)->ptr, VALUE, end); RARRAY(ary)->aux.capa = end; } rb_mem_clear(RARRAY(ary)->ptr + RARRAY(ary)->len, end - RARRAY(ary)->len); RARRAY(ary)->len = end; } if (block_p) { VALUE v; long i; for (i=beg; i<end; i++) { v = rb_yield(LONG2NUM(i)); if (i>=RARRAY(ary)->len) break; RARRAY(ary)->ptr[i] = v; } } else { p = RARRAY(ary)->ptr + beg; pend = p + len; while (p < pend) { *p++ = item; } } return ary; } /* * call-seq: * array + other_array -> an_array * * Concatenation---Returns a new array built by concatenating the * two arrays together to produce a third array. * * [ 1, 2, 3 ] + [ 4, 5 ] #=> [ 1, 2, 3, 4, 5 ] */ VALUE rb_ary_plus(x, y) VALUE x, y; { VALUE z; long len; y = to_ary(y); len = RARRAY(x)->len + RARRAY(y)->len; z = rb_ary_new2(len); MEMCPY(RARRAY(z)->ptr, RARRAY(x)->ptr, VALUE, RARRAY(x)->len); MEMCPY(RARRAY(z)->ptr + RARRAY(x)->len, RARRAY(y)->ptr, VALUE, RARRAY(y)->len); RARRAY(z)->len = len; return z; } /* * call-seq: * array.concat(other_array) -> array * * Appends the elements in other_array to _self_. * * [ "a", "b" ].concat( ["c", "d"] ) #=> [ "a", "b", "c", "d" ] */ VALUE rb_ary_concat(x, y) VALUE x, y; { y = to_ary(y); if (RARRAY(y)->len > 0) { rb_ary_splice(x, RARRAY(x)->len, 0, y); } return x; } /* * call-seq: * array * int -> an_array * array * str -> a_string * * Repetition---With a String argument, equivalent to * self.join(str). Otherwise, returns a new array * built by concatenating the _int_ copies of _self_. * * * [ 1, 2, 3 ] * 3 #=> [ 1, 2, 3, 1, 2, 3, 1, 2, 3 ] * [ 1, 2, 3 ] * "," #=> "1,2,3" * */ static VALUE rb_ary_times(ary, times) VALUE ary, times; { VALUE ary2, tmp; long i, len; tmp = rb_check_string_type(times); if (!NIL_P(tmp)) { return rb_ary_join(ary, tmp); } len = NUM2LONG(times); if (len == 0) return ary_new(rb_obj_class(ary), 0); if (len < 0) { rb_raise(rb_eArgError, "negative argument"); } if (ARY_MAX_SIZE/len < RARRAY(ary)->len) { rb_raise(rb_eArgError, "argument too big"); } len *= RARRAY(ary)->len; ary2 = ary_new(rb_obj_class(ary), len); RARRAY(ary2)->len = len; for (i=0; i<len; i+=RARRAY(ary)->len) { MEMCPY(RARRAY(ary2)->ptr+i, RARRAY(ary)->ptr, VALUE, RARRAY(ary)->len); } OBJ_INFECT(ary2, ary); return ary2; } /* * call-seq: * array.assoc(obj) -> an_array or nil * * Searches through an array whose elements are also arrays * comparing _obj_ with the first element of each contained array * using obj.==. * Returns the first contained array that matches (that * is, the first associated array), * or +nil+ if no match is found. * See also <code>Array#rassoc</code>. * * s1 = [ "colors", "red", "blue", "green" ] * s2 = [ "letters", "a", "b", "c" ] * s3 = "foo" * a = [ s1, s2, s3 ] * a.assoc("letters") #=> [ "letters", "a", "b", "c" ] * a.assoc("foo") #=> nil */ VALUE rb_ary_assoc(ary, key) VALUE ary, key; { long i; VALUE v; for (i = 0; i < RARRAY(ary)->len; ++i) { v = RARRAY(ary)->ptr[i]; if (TYPE(v) == T_ARRAY && RARRAY(v)->len > 0 && rb_equal(RARRAY(v)->ptr[0], key)) return v; } return Qnil; } /* * call-seq: * array.rassoc(key) -> an_array or nil * * Searches through the array whose elements are also arrays. Compares * <em>key</em> with the second element of each contained array using * <code>==</code>. Returns the first contained array that matches. See * also <code>Array#assoc</code>. * * a = [ [ 1, "one"], [2, "two"], [3, "three"], ["ii", "two"] ] * a.rassoc("two") #=> [2, "two"] * a.rassoc("four") #=> nil */ VALUE rb_ary_rassoc(ary, value) VALUE ary, value; { long i; VALUE v; for (i = 0; i < RARRAY(ary)->len; ++i) { v = RARRAY(ary)->ptr[i]; if (TYPE(v) == T_ARRAY && RARRAY(v)->len > 1 && rb_equal(RARRAY(v)->ptr[1], value)) return v; } return Qnil; } static VALUE recursive_equal(ary1, ary2) VALUE ary1, ary2; { long i; for (i=0; i<RARRAY(ary1)->len; i++) { if (!rb_equal(rb_ary_elt(ary1, i), rb_ary_elt(ary2, i))) return Qfalse; } return Qtrue; } /* * call-seq: * array == other_array -> bool * * Equality---Two arrays are equal if they contain the same number * of elements and if each element is equal to (according to * Object.==) the corresponding element in the other array. * * [ "a", "c" ] == [ "a", "c", 7 ] #=> false * [ "a", "c", 7 ] == [ "a", "c", 7 ] #=> true * [ "a", "c", 7 ] == [ "a", "d", "f" ] #=> false * */ static VALUE rb_ary_equal(ary1, ary2) VALUE ary1, ary2; { if (ary1 == ary2) return Qtrue; if (TYPE(ary2) != T_ARRAY) { if (!rb_respond_to(ary2, rb_intern("to_ary"))) { return Qfalse; } return rb_equal(ary2, ary1); } if (RARRAY(ary1)->len != RARRAY(ary2)->len) return Qfalse; if (rb_inspecting_p(ary1)) return Qfalse; return rb_protect_inspect(recursive_equal, ary1, ary2); } static VALUE recursive_eql(ary1, ary2) VALUE ary1, ary2; { long i; for (i=0; i<RARRAY(ary1)->len; i++) { if (!rb_eql(rb_ary_elt(ary1, i), rb_ary_elt(ary2, i))) return Qfalse; } return Qtrue; } /* * call-seq: * array.eql?(other) -> true or false * * Returns <code>true</code> if _array_ and _other_ are the same object, * or are both arrays with the same content. */ static VALUE rb_ary_eql(ary1, ary2) VALUE ary1, ary2; { if (ary1 == ary2) return Qtrue; if (TYPE(ary2) != T_ARRAY) return Qfalse; if (RARRAY(ary1)->len != RARRAY(ary2)->len) return Qfalse; if (rb_inspecting_p(ary1)) return Qfalse; return rb_protect_inspect(recursive_eql, ary1, ary2); } static VALUE recursive_hash _((VALUE ary)); static VALUE recursive_hash(ary) VALUE ary; { long i, h; VALUE n; h = RARRAY(ary)->len; for (i=0; i<RARRAY(ary)->len; i++) { h = (h << 1) | (h<0 ? 1 : 0); n = rb_hash(RARRAY(ary)->ptr[i]); h ^= NUM2LONG(n); } return LONG2FIX(h); } /* * call-seq: * array.hash -> fixnum * * Compute a hash-code for this array. Two arrays with the same content * will have the same hash code (and will compare using <code>eql?</code>). */ static VALUE rb_ary_hash(ary) VALUE ary; { if (rb_inspecting_p(ary)) { return LONG2FIX(0); } return rb_protect_inspect(recursive_hash, ary, 0); } /* * call-seq: * array.include?(obj) -> true or false * * Returns <code>true</code> if the given object is present in * <i>self</i> (that is, if any object <code>==</code> <i>anObject</i>), * <code>false</code> otherwise. * * a = [ "a", "b", "c" ] * a.include?("b") #=> true * a.include?("z") #=> false */ VALUE rb_ary_includes(ary, item) VALUE ary; VALUE item; { long i; for (i=0; i<RARRAY(ary)->len; i++) { if (rb_equal(RARRAY(ary)->ptr[i], item)) { return Qtrue; } } return Qfalse; } VALUE recursive_cmp(ary1, ary2) VALUE ary1, ary2; { long i, len; len = RARRAY(ary1)->len; if (len > RARRAY(ary2)->len) { len = RARRAY(ary2)->len; } for (i=0; i<len; i++) { VALUE v = rb_funcall(rb_ary_elt(ary1, i), id_cmp, 1, rb_ary_elt(ary2, i)); if (v != INT2FIX(0)) { return v; } } return Qundef; } /* * call-seq: * array <=> other_array -> -1, 0, +1 * * Comparison---Returns an integer (-1, 0, * or +1) if this array is less than, equal to, or greater than * other_array. Each object in each array is compared * (using <=>). If any value isn't * equal, then that inequality is the return value. If all the * values found are equal, then the return is based on a * comparison of the array lengths. Thus, two arrays are * ``equal'' according to <code>Array#<=></code> if and only if they have * the same length and the value of each element is equal to the * value of the corresponding element in the other array. * * [ "a", "a", "c" ] <=> [ "a", "b", "c" ] #=> -1 * [ 1, 2, 3, 4, 5, 6 ] <=> [ 1, 2 ] #=> +1 * */ VALUE rb_ary_cmp(ary1, ary2) VALUE ary1, ary2; { long len; VALUE v; ary2 = to_ary(ary2); if (ary1 == ary2) return INT2FIX(0); if (rb_inspecting_p(ary1)) return INT2FIX(0); v = rb_protect_inspect(recursive_cmp, ary1, ary2); if (v != Qundef) return v; len = RARRAY(ary1)->len - RARRAY(ary2)->len; if (len == 0) return INT2FIX(0); if (len > 0) return INT2FIX(1); return INT2FIX(-1); } static VALUE ary_make_hash(ary1, ary2) VALUE ary1, ary2; { VALUE hash = rb_hash_new(); long i; for (i=0; i<RARRAY(ary1)->len; i++) { rb_hash_aset(hash, RARRAY(ary1)->ptr[i], Qtrue); } if (ary2) { for (i=0; i<RARRAY(ary2)->len; i++) { rb_hash_aset(hash, RARRAY(ary2)->ptr[i], Qtrue); } } return hash; } /* * call-seq: * array - other_array -> an_array * * Array Difference---Returns a new array that is a copy of * the original array, removing any items that also appear in * other_array. (If you need set-like behavior, see the * library class Set.) * * [ 1, 1, 2, 2, 3, 3, 4, 5 ] - [ 1, 2, 4 ] #=> [ 3, 3, 5 ] */ static VALUE rb_ary_diff(ary1, ary2) VALUE ary1, ary2; { VALUE ary3; volatile VALUE hash; long i; hash = ary_make_hash(to_ary(ary2), 0); ary3 = rb_ary_new(); for (i=0; i<RARRAY(ary1)->len; i++) { if (st_lookup(RHASH(hash)->tbl, RARRAY(ary1)->ptr[i], 0)) continue; rb_ary_push(ary3, rb_ary_elt(ary1, i)); } return ary3; } /* * call-seq: * array & other_array * * Set Intersection---Returns a new array * containing elements common to the two arrays, with no duplicates. * * [ 1, 1, 3, 5 ] & [ 1, 2, 3 ] #=> [ 1, 3 ] */ static VALUE rb_ary_and(ary1, ary2) VALUE ary1, ary2; { VALUE hash, ary3, v, vv; long i; ary2 = to_ary(ary2); ary3 = rb_ary_new2(RARRAY(ary1)->len < RARRAY(ary2)->len ? RARRAY(ary1)->len : RARRAY(ary2)->len); hash = ary_make_hash(ary2, 0); for (i=0; i<RARRAY(ary1)->len; i++) { v = vv = rb_ary_elt(ary1, i); if (st_delete(RHASH(hash)->tbl, (st_data_t*)&vv, 0)) { rb_ary_push(ary3, v); } } return ary3; } /* * call-seq: * array | other_array -> an_array * * Set Union---Returns a new array by joining this array with * other_array, removing duplicates. * * [ "a", "b", "c" ] | [ "c", "d", "a" ] * #=> [ "a", "b", "c", "d" ] */ static VALUE rb_ary_or(ary1, ary2) VALUE ary1, ary2; { VALUE hash, ary3; VALUE v, vv; long i; ary2 = to_ary(ary2); ary3 = rb_ary_new2(RARRAY(ary1)->len+RARRAY(ary2)->len); hash = ary_make_hash(ary1, ary2); for (i=0; i<RARRAY(ary1)->len; i++) { v = vv = rb_ary_elt(ary1, i); if (st_delete(RHASH(hash)->tbl, (st_data_t*)&vv, 0)) { rb_ary_push(ary3, v); } } for (i=0; i<RARRAY(ary2)->len; i++) { v = vv = rb_ary_elt(ary2, i); if (st_delete(RHASH(hash)->tbl, (st_data_t*)&vv, 0)) { rb_ary_push(ary3, v); } } return ary3; } /* * call-seq: * array.uniq! -> array or nil * * Removes duplicate elements from _self_. * Returns <code>nil</code> if no changes are made (that is, no * duplicates are found). * * a = [ "a", "a", "b", "b", "c" ] * a.uniq! #=> ["a", "b", "c"] * b = [ "a", "b", "c" ] * b.uniq! #=> nil */ static VALUE rb_ary_uniq_bang(ary) VALUE ary; { VALUE hash, v, vv; long i, j; hash = ary_make_hash(ary, 0); if (RARRAY(ary)->len == RHASH(hash)->tbl->num_entries) { return Qnil; } for (i=j=0; i<RARRAY(ary)->len; i++) { v = vv = rb_ary_elt(ary, i); if (st_delete(RHASH(hash)->tbl, (st_data_t*)&vv, 0)) { rb_ary_store(ary, j++, v); } } RARRAY(ary)->len = j; return ary; } /* * call-seq: * array.uniq -> an_array * * Returns a new array by removing duplicate values in <i>self</i>. * * a = [ "a", "a", "b", "b", "c" ] * a.uniq #=> ["a", "b", "c"] */ static VALUE rb_ary_uniq(ary) VALUE ary; { ary = rb_ary_dup(ary); rb_ary_uniq_bang(ary); return ary; } /* * call-seq: * array.compact! -> array or nil * * Removes +nil+ elements from array. * Returns +nil+ if no changes were made. * * [ "a", nil, "b", nil, "c" ].compact! #=> [ "a", "b", "c" ] * [ "a", "b", "c" ].compact! #=> nil */ static VALUE rb_ary_compact_bang(ary) VALUE ary; { VALUE *p, *t, *end; rb_ary_modify(ary); p = t = RARRAY(ary)->ptr; end = p + RARRAY(ary)->len; while (t < end) { if (NIL_P(*t)) t++; else *p++ = *t++; } if (RARRAY(ary)->len == (p - RARRAY(ary)->ptr)) { return Qnil; } RARRAY(ary)->len = RARRAY(ary)->aux.capa = (p - RARRAY(ary)->ptr); REALLOC_N(RARRAY(ary)->ptr, VALUE, RARRAY(ary)->len); return ary; } /* * call-seq: * array.compact -> an_array * * Returns a copy of _self_ with all +nil+ elements removed. * * [ "a", nil, "b", nil, "c", nil ].compact * #=> [ "a", "b", "c" ] */ static VALUE rb_ary_compact(ary) VALUE ary; { ary = rb_ary_dup(ary); rb_ary_compact_bang(ary); return ary; } /* * call-seq: * array.nitems -> int * * Returns the number of non-<code>nil</code> elements in _self_. * May be zero. * * [ 1, nil, 3, nil, 5 ].nitems #=> 3 */ static VALUE rb_ary_nitems(ary) VALUE ary; { long n = 0; VALUE *p, *pend; p = RARRAY(ary)->ptr; pend = p + RARRAY(ary)->len; while (p < pend) { if (!NIL_P(*p)) n++; p++; } return LONG2NUM(n); } static long flatten(ary, idx, ary2, memo) VALUE ary; long idx; VALUE ary2, memo; { VALUE id; long i = idx; long n, lim = idx + RARRAY(ary2)->len; id = rb_obj_id(ary2); if (rb_ary_includes(memo, id)) { rb_raise(rb_eArgError, "tried to flatten recursive array"); } rb_ary_push(memo, id); rb_ary_splice(ary, idx, 1, ary2); while (i < lim) { VALUE tmp; tmp = rb_check_array_type(rb_ary_elt(ary, i)); if (!NIL_P(tmp)) { n = flatten(ary, i, tmp, memo); i += n; lim += n; } i++; } rb_ary_pop(memo); return lim - idx - 1; /* returns number of increased items */ } /* * call-seq: * array.flatten! -> array or nil * * Flattens _self_ in place. * Returns <code>nil</code> if no modifications were made (i.e., * <i>array</i> contains no subarrays.) * * a = [ 1, 2, [3, [4, 5] ] ] * a.flatten! #=> [1, 2, 3, 4, 5] * a.flatten! #=> nil * a #=> [1, 2, 3, 4, 5] */ static VALUE rb_ary_flatten_bang(ary) VALUE ary; { long i = 0; int mod = 0; VALUE memo = Qnil; while (i<RARRAY(ary)->len) { VALUE ary2 = RARRAY(ary)->ptr[i]; VALUE tmp; tmp = rb_check_array_type(ary2); if (!NIL_P(tmp)) { if (NIL_P(memo)) { memo = rb_ary_new(); } i += flatten(ary, i, tmp, memo); mod = 1; } i++; } if (mod == 0) return Qnil; return ary; } /* * call-seq: * array.flatten -> an_array * * Returns a new array that is a one-dimensional flattening of this * array (recursively). That is, for every element that is an array, * extract its elements into the new array. * * s = [ 1, 2, 3 ] #=> [1, 2, 3] * t = [ 4, 5, 6, [7, 8] ] #=> [4, 5, 6, [7, 8]] * a = [ s, t, 9, 10 ] #=> [[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10] * a.flatten #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10 */ static VALUE rb_ary_flatten(ary) VALUE ary; { ary = rb_ary_dup(ary); rb_ary_flatten_bang(ary); return ary; } /* Arrays are ordered, integer-indexed collections of any object. * Array indexing starts at 0, as in C or Java. A negative index is * assumed to be relative to the end of the array---that is, an index of -1 * indicates the last element of the array, -2 is the next to last * element in the array, and so on. */ void Init_Array() { rb_cArray = rb_define_class("Array", rb_cObject); rb_include_module(rb_cArray, rb_mEnumerable); rb_define_alloc_func(rb_cArray, ary_alloc); rb_define_singleton_method(rb_cArray, "[]", rb_ary_s_create, -1); rb_define_method(rb_cArray, "initialize", rb_ary_initialize, -1); rb_define_method(rb_cArray, "initialize_copy", rb_ary_replace, 1); rb_define_method(rb_cArray, "to_s", rb_ary_to_s, 0); rb_define_method(rb_cArray, "inspect", rb_ary_inspect, 0); rb_define_method(rb_cArray, "to_a", rb_ary_to_a, 0); rb_define_method(rb_cArray, "to_ary", rb_ary_to_ary_m, 0); rb_define_method(rb_cArray, "frozen?", rb_ary_frozen_p, 0); rb_define_method(rb_cArray, "==", rb_ary_equal, 1); rb_define_method(rb_cArray, "eql?", rb_ary_eql, 1); rb_define_method(rb_cArray, "hash", rb_ary_hash, 0); rb_define_method(rb_cArray, "[]", rb_ary_aref, -1); rb_define_method(rb_cArray, "[]=", rb_ary_aset, -1); rb_define_method(rb_cArray, "at", rb_ary_at, 1); rb_define_method(rb_cArray, "fetch", rb_ary_fetch, -1); rb_define_method(rb_cArray, "first", rb_ary_first, -1); rb_define_method(rb_cArray, "last", rb_ary_last, -1); rb_define_method(rb_cArray, "concat", rb_ary_concat, 1); rb_define_method(rb_cArray, "<<", rb_ary_push, 1); rb_define_method(rb_cArray, "push", rb_ary_push_m, -1); rb_define_method(rb_cArray, "pop", rb_ary_pop, 0); rb_define_method(rb_cArray, "shift", rb_ary_shift, 0); rb_define_method(rb_cArray, "unshift", rb_ary_unshift_m, -1); rb_define_method(rb_cArray, "insert", rb_ary_insert, -1); rb_define_method(rb_cArray, "each", rb_ary_each, 0); rb_define_method(rb_cArray, "each_index", rb_ary_each_index, 0); rb_define_method(rb_cArray, "reverse_each", rb_ary_reverse_each, 0); rb_define_method(rb_cArray, "length", rb_ary_length, 0); rb_define_alias(rb_cArray, "size", "length"); rb_define_method(rb_cArray, "empty?", rb_ary_empty_p, 0); rb_define_method(rb_cArray, "index", rb_ary_index, 1); rb_define_method(rb_cArray, "rindex", rb_ary_rindex, 1); rb_define_method(rb_cArray, "indexes", rb_ary_indexes, -1); rb_define_method(rb_cArray, "indices", rb_ary_indexes, -1); rb_define_method(rb_cArray, "join", rb_ary_join_m, -1); rb_define_method(rb_cArray, "reverse", rb_ary_reverse_m, 0); rb_define_method(rb_cArray, "reverse!", rb_ary_reverse_bang, 0); rb_define_method(rb_cArray, "sort", rb_ary_sort, 0); rb_define_method(rb_cArray, "sort!", rb_ary_sort_bang, 0); rb_define_method(rb_cArray, "collect", rb_ary_collect, 0); rb_define_method(rb_cArray, "collect!", rb_ary_collect_bang, 0); rb_define_method(rb_cArray, "map", rb_ary_collect, 0); rb_define_method(rb_cArray, "map!", rb_ary_collect_bang, 0); rb_define_method(rb_cArray, "select", rb_ary_select, 0); rb_define_method(rb_cArray, "values_at", rb_ary_values_at, -1); rb_define_method(rb_cArray, "delete", rb_ary_delete, 1); rb_define_method(rb_cArray, "delete_at", rb_ary_delete_at_m, 1); rb_define_method(rb_cArray, "delete_if", rb_ary_delete_if, 0); rb_define_method(rb_cArray, "reject", rb_ary_reject, 0); rb_define_method(rb_cArray, "reject!", rb_ary_reject_bang, 0); rb_define_method(rb_cArray, "zip", rb_ary_zip, -1); rb_define_method(rb_cArray, "transpose", rb_ary_transpose, 0); rb_define_method(rb_cArray, "replace", rb_ary_replace, 1); rb_define_method(rb_cArray, "clear", rb_ary_clear, 0); rb_define_method(rb_cArray, "fill", rb_ary_fill, -1); rb_define_method(rb_cArray, "include?", rb_ary_includes, 1); rb_define_method(rb_cArray, "<=>", rb_ary_cmp, 1); rb_define_method(rb_cArray, "slice", rb_ary_aref, -1); rb_define_method(rb_cArray, "slice!", rb_ary_slice_bang, -1); rb_define_method(rb_cArray, "assoc", rb_ary_assoc, 1); rb_define_method(rb_cArray, "rassoc", rb_ary_rassoc, 1); rb_define_method(rb_cArray, "+", rb_ary_plus, 1); rb_define_method(rb_cArray, "*", rb_ary_times, 1); rb_define_method(rb_cArray, "-", rb_ary_diff, 1); rb_define_method(rb_cArray, "&", rb_ary_and, 1); rb_define_method(rb_cArray, "|", rb_ary_or, 1); rb_define_method(rb_cArray, "uniq", rb_ary_uniq, 0); rb_define_method(rb_cArray, "uniq!", rb_ary_uniq_bang, 0); rb_define_method(rb_cArray, "compact", rb_ary_compact, 0); rb_define_method(rb_cArray, "compact!", rb_ary_compact_bang, 0); rb_define_method(rb_cArray, "flatten", rb_ary_flatten, 0); rb_define_method(rb_cArray, "flatten!", rb_ary_flatten_bang, 0); rb_define_method(rb_cArray, "nitems", rb_ary_nitems, 0); id_cmp = rb_intern("<=>"); inspect_key = rb_intern("__inspect_key__"); } /********************************************************************** bignum.c - $Author: wyhaines $ $Date: 2009-07-14 17:05:27 +0200 (Tue, 14 Jul 2009) $ created at: Fri Jun 10 00:48:55 JST 1994 Copyright (C) 1993-2003 <NAME> **********************************************************************/ #include "ruby.h" #include "rubysig.h" #include <math.h> #include <ctype.h> #ifdef HAVE_IEEEFP_H #include <ieeefp.h> #endif VALUE rb_cBignum; #if defined __MINGW32__ #define USHORT _USHORT #endif #define BDIGITS(x) ((BDIGIT*)RBIGNUM(x)->digits) #define BITSPERDIG (SIZEOF_BDIGITS*CHAR_BIT) #define BIGRAD ((BDIGIT_DBL)1 << BITSPERDIG) #define DIGSPERLONG ((unsigned int)(SIZEOF_LONG/SIZEOF_BDIGITS)) #if HAVE_LONG_LONG # define DIGSPERLL ((unsigned int)(SIZEOF_LONG_LONG/SIZEOF_BDIGITS)) #endif #define BIGUP(x) ((BDIGIT_DBL)(x) << BITSPERDIG) #define BIGDN(x) RSHIFT(x,BITSPERDIG) #define BIGLO(x) ((BDIGIT)((x) & (BIGRAD-1))) #define BDIGMAX ((BDIGIT)-1) #define BIGZEROP(x) (RBIGNUM(x)->len == 0 || \ (BDIGITS(x)[0] == 0 && \ (RBIGNUM(x)->len == 1 || bigzero_p(x)))) static int bigzero_p(VALUE); static int bigzero_p(x) VALUE x; { long i; for (i = 0; i < RBIGNUM(x)->len; ++i) { if (BDIGITS(x)[i]) return 0; } return 1; } static VALUE bignew_1(klass, len, sign) VALUE klass; long len; int sign; { NEWOBJ(big, struct RBignum); OBJSETUP(big, klass, T_BIGNUM); big->sign = sign?1:0; big->len = len; big->digits = ALLOC_N(BDIGIT, len); return (VALUE)big; } #define bignew(len,sign) bignew_1(rb_cBignum,len,sign) VALUE rb_big_clone(x) VALUE x; { VALUE z = bignew_1(CLASS_OF(x), RBIGNUM(x)->len, RBIGNUM(x)->sign); MEMCPY(BDIGITS(z), BDIGITS(x), BDIGIT, RBIGNUM(x)->len); return z; } /* modify a bignum by 2's complement */ static void get2comp(x) VALUE x; { long i = RBIGNUM(x)->len; BDIGIT *ds = BDIGITS(x); BDIGIT_DBL num; if (!i) return; while (i--) ds[i] = ~ds[i]; i = 0; num = 1; do { num += ds[i]; ds[i++] = BIGLO(num); num = BIGDN(num); } while (i < RBIGNUM(x)->len); if (num != 0) { REALLOC_N(RBIGNUM(x)->digits, BDIGIT, ++RBIGNUM(x)->len); ds = BDIGITS(x); ds[RBIGNUM(x)->len-1] = RBIGNUM(x)->sign ? ~0 : 1; } } void rb_big_2comp(x) /* get 2's complement */ VALUE x; { get2comp(x); } static VALUE bigtrunc(x) VALUE x; { long len = RBIGNUM(x)->len; BDIGIT *ds = BDIGITS(x); if (len == 0) return x; while (--len && !ds[len]); RBIGNUM(x)->len = ++len; return x; } static VALUE bigfixize(VALUE x) { long len = RBIGNUM(x)->len; BDIGIT *ds = BDIGITS(x); if (len*SIZEOF_BDIGITS <= sizeof(VALUE)) { long num = 0; while (len--) { num = BIGUP(num) + ds[len]; } if (num >= 0) { if (RBIGNUM(x)->sign) { if (POSFIXABLE(num)) return LONG2FIX(num); } else { if (NEGFIXABLE(-(long)num)) return LONG2FIX(-(long)num); } } } return x; } static VALUE bignorm(VALUE x) { if (!FIXNUM_P(x) && TYPE(x) == T_BIGNUM) { x = bigfixize(bigtrunc(x)); } return x; } VALUE rb_big_norm(x) VALUE x; { return bignorm(x); } VALUE rb_uint2big(n) unsigned long n; { BDIGIT_DBL num = n; long i = 0; BDIGIT *digits; VALUE big; big = bignew(DIGSPERLONG, 1); digits = BDIGITS(big); while (i < DIGSPERLONG) { digits[i++] = BIGLO(num); num = BIGDN(num); } i = DIGSPERLONG; while (--i && !digits[i]) ; RBIGNUM(big)->len = i+1; return big; } VALUE rb_int2big(n) long n; { long neg = 0; VALUE big; if (n < 0) { n = -n; neg = 1; } big = rb_uint2big(n); if (neg) { RBIGNUM(big)->sign = 0; } return big; } VALUE rb_uint2inum(n) unsigned long n; { if (POSFIXABLE(n)) return LONG2FIX(n); return rb_uint2big(n); } VALUE rb_int2inum(n) long n; { if (FIXABLE(n)) return LONG2FIX(n); return rb_int2big(n); } #ifdef HAVE_LONG_LONG void rb_quad_pack(buf, val) char *buf; VALUE val; { LONG_LONG q; val = rb_to_int(val); if (FIXNUM_P(val)) { q = FIX2LONG(val); } else { long len = RBIGNUM(val)->len; BDIGIT *ds; if (len > SIZEOF_LONG_LONG/SIZEOF_BDIGITS) rb_raise(rb_eRangeError, "bignum too big to convert into `quad int'"); ds = BDIGITS(val); q = 0; while (len--) { q = BIGUP(q); q += ds[len]; } if (!RBIGNUM(val)->sign) q = -q; } memcpy(buf, (char*)&q, SIZEOF_LONG_LONG); } VALUE rb_quad_unpack(buf, sign) const char *buf; int sign; { unsigned LONG_LONG q; long neg = 0; long i; BDIGIT *digits; VALUE big; memcpy(&q, buf, SIZEOF_LONG_LONG); if (sign) { if (FIXABLE((LONG_LONG)q)) return LONG2FIX((LONG_LONG)q); if ((LONG_LONG)q < 0) { q = -(LONG_LONG)q; neg = 1; } } else { if (POSFIXABLE(q)) return LONG2FIX(q); } i = 0; big = bignew(DIGSPERLL, 1); digits = BDIGITS(big); while (i < DIGSPERLL) { digits[i++] = BIGLO(q); q = BIGDN(q); } i = DIGSPERLL; while (i-- && !digits[i]) ; RBIGNUM(big)->len = i+1; if (neg) { RBIGNUM(big)->sign = 0; } return bignorm(big); } #else #define QUAD_SIZE 8 void rb_quad_pack(buf, val) char *buf; VALUE val; { long len; memset(buf, 0, QUAD_SIZE); val = rb_to_int(val); if (FIXNUM_P(val)) { val = rb_int2big(FIX2LONG(val)); } len = RBIGNUM(val)->len * SIZEOF_BDIGITS; if (len > QUAD_SIZE) { rb_raise(rb_eRangeError, "bignum too big to convert into `quad int'"); } memcpy(buf, (char*)BDIGITS(val), len); if (!RBIGNUM(val)->sign) { len = QUAD_SIZE; while (len--) { *buf = ~*buf; buf++; } } } #define BNEG(b) (RSHIFT(((BDIGIT*)b)[QUAD_SIZE/SIZEOF_BDIGITS-1],BITSPERDIG-1) != 0) VALUE rb_quad_unpack(buf, sign) const char *buf; int sign; { VALUE big = bignew(QUAD_SIZE/SIZEOF_BDIGITS, 1); memcpy((char*)BDIGITS(big), buf, QUAD_SIZE); if (sign && BNEG(buf)) { long len = QUAD_SIZE; char *tmp = (char*)BDIGITS(big); RBIGNUM(big)->sign = 0; while (len--) { *tmp = ~*tmp; tmp++; } } return bignorm(big); } #endif VALUE rb_cstr_to_inum(str, base, badcheck) const char *str; int base; int badcheck; { const char *s = str; char *end; char sign = 1, nondigit = 0; int c; BDIGIT_DBL num; long len, blen = 1; long i; VALUE z; BDIGIT *zds; #define conv_digit(c) \ (!ISASCII(c) ? -1 : \ isdigit(c) ? ((c) - '0') : \ islower(c) ? ((c) - 'a' + 10) : \ isupper(c) ? ((c) - 'A' + 10) : \ -1) if (!str) { if (badcheck) goto bad; return INT2FIX(0); } if (badcheck) { while (ISSPACE(*str)) str++; } else { while (ISSPACE(*str) || *str == '_') str++; } if (str[0] == '+') { str++; } else if (str[0] == '-') { str++; sign = 0; } if (str[0] == '+' || str[0] == '-') { if (badcheck) goto bad; return INT2FIX(0); } if (base <= 0) { if (str[0] == '0') { switch (str[1]) { case 'x': case 'X': base = 16; break; case 'b': case 'B': base = 2; break; case 'o': case 'O': base = 8; break; case 'd': case 'D': base = 10; break; default: base = 8; } } else if (base < -1) { base = -base; } else { base = 10; } } switch (base) { case 2: len = 1; if (str[0] == '0' && (str[1] == 'b'||str[1] == 'B')) { str += 2; } break; case 3: len = 2; break; case 8: if (str[0] == '0' && (str[1] == 'o'||str[1] == 'O')) { str += 2; } case 4: case 5: case 6: case 7: len = 3; break; case 10: if (str[0] == '0' && (str[1] == 'd'||str[1] == 'D')) { str += 2; } case 9: case 11: case 12: case 13: case 14: case 15: len = 4; break; case 16: len = 4; if (str[0] == '0' && (str[1] == 'x'||str[1] == 'X')) { str += 2; } break; default: if (base < 2 || 36 < base) { rb_raise(rb_eArgError, "illegal radix %d", base); } if (base <= 32) { len = 5; } else { len = 6; } break; } if (*str == '0') { /* squeeze preceeding 0s */ while (*++str == '0'); if (!(c = *str) || ISSPACE(c)) --str; } c = *str; c = conv_digit(c); if (c < 0 || c >= base) { if (badcheck) goto bad; return INT2FIX(0); } len *= strlen(str)*sizeof(char); if (len <= (sizeof(VALUE)*CHAR_BIT)) { unsigned long val = strtoul((char*)str, &end, base); if (*end == '_') goto bigparse; if (badcheck) { if (end == str) goto bad; /* no number */ while (*end && ISSPACE(*end)) end++; if (*end) goto bad; /* trailing garbage */ } if (POSFIXABLE(val)) { if (sign) return LONG2FIX(val); else { long result = -(long)val; return LONG2FIX(result); } } else { VALUE big = rb_uint2big(val); RBIGNUM(big)->sign = sign; return bignorm(big); } } bigparse: len = (len/BITSPERDIG)+1; if (badcheck && *str == '_') goto bad; z = bignew(len, sign); zds = BDIGITS(z); for (i=len;i--;) zds[i]=0; while ((c = *str++) != 0) { if (c == '_') { if (badcheck) { if (nondigit) goto bad; nondigit = c; } continue; } else if ((c = conv_digit(c)) < 0) { break; } if (c >= base) break; nondigit = 0; i = 0; num = c; for (;;) { while (i<blen) { num += (BDIGIT_DBL)zds[i]*base; zds[i++] = BIGLO(num); num = BIGDN(num); } if (num) { blen++; continue; } break; } } if (badcheck) { str--; if (s+1 < str && str[-1] == '_') goto bad; while (*str && ISSPACE(*str)) str++; if (*str) { bad: rb_invalid_str(s, "Integer"); } } return bignorm(z); } VALUE rb_str_to_inum(str, base, badcheck) VALUE str; int base; int badcheck; { char *s; long len; StringValue(str); if (badcheck) { s = StringValueCStr(str); } else { s = RSTRING(str)->ptr; } if (s) { len = RSTRING(str)->len; if (s[len]) { /* no sentinel somehow */ char *p = ALLOCA_N(char, len+1); MEMCPY(p, s, char, len); p[len] = '\0'; s = p; } } return rb_cstr_to_inum(s, base, badcheck); } #if HAVE_LONG_LONG VALUE rb_ull2big(n) unsigned LONG_LONG n; { BDIGIT_DBL num = n; long i = 0; BDIGIT *digits; VALUE big; big = bignew(DIGSPERLL, 1); digits = BDIGITS(big); while (i < DIGSPERLL) { digits[i++] = BIGLO(num); num = BIGDN(num); } i = DIGSPERLL; while (i-- && !digits[i]) ; RBIGNUM(big)->len = i+1; return big; } VALUE rb_ll2big(n) LONG_LONG n; { long neg = 0; VALUE big; if (n < 0) { n = -n; neg = 1; } big = rb_ull2big(n); if (neg) { RBIGNUM(big)->sign = 0; } return big; } VALUE rb_ull2inum(n) unsigned LONG_LONG n; { if (POSFIXABLE(n)) return LONG2FIX(n); return rb_ull2big(n); } VALUE rb_ll2inum(n) LONG_LONG n; { if (FIXABLE(n)) return LONG2FIX(n); return rb_ll2big(n); } #endif /* HAVE_LONG_LONG */ VALUE rb_cstr2inum(str, base) const char *str; int base; { return rb_cstr_to_inum(str, base, base==0); } VALUE rb_str2inum(str, base) VALUE str; int base; { return rb_str_to_inum(str, base, base==0); } const char ruby_digitmap[] = "0123456789abcdefghijklmnopqrstuvwxyz"; VALUE rb_big2str0(x, base, trim) VALUE x; int base; int trim; { volatile VALUE t; BDIGIT *ds; long i, j, hbase; VALUE ss; char *s; if (FIXNUM_P(x)) { return rb_fix2str(x, base); } i = RBIGNUM(x)->len; if (BIGZEROP(x)) { return rb_str_new2("0"); } if (i >= LONG_MAX/SIZEOF_BDIGITS/CHAR_BIT) { rb_raise(rb_eRangeError, "bignum too big to convert into `string'"); } j = SIZEOF_BDIGITS*CHAR_BIT*i; switch (base) { case 2: break; case 3: j = j * 53L / 84 + 1; break; case 4: case 5: case 6: case 7: j = (j + 1) / 2; break; case 8: case 9: j = (j + 2) / 3; break; case 10: case 11: case 12: case 13: case 14: case 15: j = j * 28L / 93 + 1; break; case 16: case 17: case 18: case 19: case 20: case 21: case 22: case 23: case 24: case 25: case 26: case 27: case 28: case 29: case 30: case 31: j = (j + 3) / 4; break; case 32: case 33: case 34: case 35: case 36: j = (j + 4) / 5; break; default: rb_raise(rb_eArgError, "illegal radix %d", base); break; } j++; /* space for sign */ hbase = base * base; #if SIZEOF_BDIGITS > 2 hbase *= hbase; #endif t = rb_big_clone(x); ds = BDIGITS(t); ss = rb_str_new(0, j+1); s = RSTRING(ss)->ptr; s[0] = RBIGNUM(x)->sign ? '+' : '-'; TRAP_BEG; while (i && j > 1) { long k = i; BDIGIT_DBL num = 0; while (k--) { num = BIGUP(num) + ds[k]; ds[k] = (BDIGIT)(num / hbase); num %= hbase; } if (trim && ds[i-1] == 0) i--; k = SIZEOF_BDIGITS; while (k--) { s[--j] = ruby_digitmap[num % base]; num /= base; if (!trim && j <= 1) break; if (trim && i == 0 && num == 0) break; } } if (trim) {while (s[j] == '0') j++;} i = RSTRING(ss)->len - j; if (RBIGNUM(x)->sign) { memmove(s, s+j, i); RSTRING(ss)->len = i-1; } else { memmove(s+1, s+j, i); RSTRING(ss)->len = i; } s[RSTRING(ss)->len] = '\0'; TRAP_END; return ss; } VALUE rb_big2str(VALUE x, int base) { return rb_big2str0(x, base, Qtrue); } /* * call-seq: * big.to_s(base=10) => string * * Returns a string containing the representation of <i>big</i> radix * <i>base</i> (2 through 36). * * 12345654321.to_s #=> "12345654321" * 12345654321.to_s(2) #=> "1011011111110110111011110000110001" * 12345654321.to_s(8) #=> "133766736061" * 12345654321.to_s(16) #=> "2dfdbbc31" * 78546939656932.to_s(36) #=> "rubyrules" */ static VALUE rb_big_to_s(argc, argv, x) int argc; VALUE *argv; VALUE x; { VALUE b; int base; rb_scan_args(argc, argv, "01", &b); if (argc == 0) base = 10; else base = NUM2INT(b); return rb_big2str(x, base); } static unsigned long big2ulong(x, type) VALUE x; char *type; { long len = RBIGNUM(x)->len; BDIGIT_DBL num; BDIGIT *ds; if (len > SIZEOF_LONG/SIZEOF_BDIGITS) rb_raise(rb_eRangeError, "bignum too big to convert into `%s'", type); ds = BDIGITS(x); num = 0; while (len--) { num = BIGUP(num); num += ds[len]; } return num; } unsigned long rb_big2ulong_pack(x) VALUE x; { unsigned long num = big2ulong(x, "unsigned long"); if (!RBIGNUM(x)->sign) { return -num; } return num; } unsigned long rb_big2ulong(x) VALUE x; { unsigned long num = big2ulong(x, "unsigned long"); if (!RBIGNUM(x)->sign) { if ((long)num < 0) { rb_raise(rb_eRangeError, "bignum out of range of unsigned long"); } return -num; } return num; } long rb_big2long(x) VALUE x; { unsigned long num = big2ulong(x, "long"); if ((long)num < 0 && (RBIGNUM(x)->sign || (long)num != LONG_MIN)) { rb_raise(rb_eRangeError, "bignum too big to convert into `long'"); } if (!RBIGNUM(x)->sign) return -(long)num; return num; } #if HAVE_LONG_LONG static unsigned LONG_LONG big2ull(x, type) VALUE x; char *type; { long len = RBIGNUM(x)->len; BDIGIT_DBL num; BDIGIT *ds; if (len > SIZEOF_LONG_LONG/SIZEOF_BDIGITS) rb_raise(rb_eRangeError, "bignum too big to convert into `%s'", type); ds = BDIGITS(x); num = 0; while (len--) { num = BIGUP(num); num += ds[len]; } return num; } unsigned LONG_LONG rb_big2ull(x) VALUE x; { unsigned LONG_LONG num = big2ull(x, "unsigned long long"); if (!RBIGNUM(x)->sign) return -num; return num; } LONG_LONG rb_big2ll(x) VALUE x; { unsigned LONG_LONG num = big2ull(x, "long long"); if ((LONG_LONG)num < 0 && (RBIGNUM(x)->sign || (LONG_LONG)num != LLONG_MIN)) { rb_raise(rb_eRangeError, "bignum too big to convert into `long long'"); } if (!RBIGNUM(x)->sign) return -(LONG_LONG)num; return num; } #endif /* HAVE_LONG_LONG */ static VALUE dbl2big(d) double d; { long i = 0; BDIGIT c; BDIGIT *digits; VALUE z; double u = (d < 0)?-d:d; if (isinf(d)) { rb_raise(rb_eFloatDomainError, d < 0 ? "-Infinity" : "Infinity"); } if (isnan(d)) { rb_raise(rb_eFloatDomainError, "NaN"); } while (!POSFIXABLE(u) || 0 != (long)u) { u /= (double)(BIGRAD); i++; } z = bignew(i, d>=0); digits = BDIGITS(z); while (i--) { u *= BIGRAD; c = (BDIGIT)u; u -= c; digits[i] = c; } return z; } VALUE rb_dbl2big(d) double d; { return bignorm(dbl2big(d)); } double rb_big2dbl(x) VALUE x; { double d = 0.0; long i = RBIGNUM(x)->len; BDIGIT *ds = BDIGITS(x); while (i--) { d = ds[i] + BIGRAD*d; } if (isinf(d)) { rb_warn("Bignum out of Float range"); d = HUGE_VAL; } if (!RBIGNUM(x)->sign) d = -d; return d; } /* * call-seq: * big.to_f -> float * * Converts <i>big</i> to a <code>Float</code>. If <i>big</i> doesn't * fit in a <code>Float</code>, the result is infinity. * */ static VALUE rb_big_to_f(x) VALUE x; { return rb_float_new(rb_big2dbl(x)); } /* * call-seq: * big <=> numeric => -1, 0, +1 * * Comparison---Returns -1, 0, or +1 depending on whether <i>big</i> is * less than, equal to, or greater than <i>numeric</i>. This is the * basis for the tests in <code>Comparable</code>. * */ static VALUE rb_big_cmp(x, y) VALUE x, y; { long xlen = RBIGNUM(x)->len; switch (TYPE(y)) { case T_FIXNUM: y = rb_int2big(FIX2LONG(y)); break; case T_BIGNUM: break; case T_FLOAT: { double a = RFLOAT(y)->value; if (isinf(a)) { if (a > 0.0) return INT2FIX(-1); else return INT2FIX(1); } return rb_dbl_cmp(rb_big2dbl(x), a); } default: return rb_num_coerce_cmp(x, y); } if (RBIGNUM(x)->sign > RBIGNUM(y)->sign) return INT2FIX(1); if (RBIGNUM(x)->sign < RBIGNUM(y)->sign) return INT2FIX(-1); if (xlen < RBIGNUM(y)->len) return (RBIGNUM(x)->sign) ? INT2FIX(-1) : INT2FIX(1); if (xlen > RBIGNUM(y)->len) return (RBIGNUM(x)->sign) ? INT2FIX(1) : INT2FIX(-1); while(xlen-- && (BDIGITS(x)[xlen]==BDIGITS(y)[xlen])); if (-1 == xlen) return INT2FIX(0); return (BDIGITS(x)[xlen] > BDIGITS(y)[xlen]) ? (RBIGNUM(x)->sign ? INT2FIX(1) : INT2FIX(-1)) : (RBIGNUM(x)->sign ? INT2FIX(-1) : INT2FIX(1)); } /* * call-seq: * big == obj => true or false * * Returns <code>true</code> only if <i>obj</i> has the same value * as <i>big</i>. Contrast this with <code>Bignum#eql?</code>, which * requires <i>obj</i> to be a <code>Bignum</code>. * * 68719476736 == 68719476736.0 #=> true */ static VALUE rb_big_eq(x, y) VALUE x, y; { switch (TYPE(y)) { case T_FIXNUM: y = rb_int2big(FIX2LONG(y)); break; case T_BIGNUM: break; case T_FLOAT: { volatile double a, b; a = RFLOAT(y)->value; if (isnan(a)) return Qfalse; b = rb_big2dbl(x); return (a == b)?Qtrue:Qfalse; } default: return rb_equal(y, x); } if (RBIGNUM(x)->sign != RBIGNUM(y)->sign) return Qfalse; if (RBIGNUM(x)->len != RBIGNUM(y)->len) return Qfalse; if (MEMCMP(BDIGITS(x),BDIGITS(y),BDIGIT,RBIGNUM(y)->len) != 0) return Qfalse; return Qtrue; } /* * call-seq: * big.eql?(obj) => true or false * * Returns <code>true</code> only if <i>obj</i> is a * <code>Bignum</code> with the same value as <i>big</i>. Contrast this * with <code>Bignum#==</code>, which performs type conversions. * * 68719476736.eql?(68719476736.0) #=> false */ static VALUE rb_big_eql(x, y) VALUE x, y; { if (TYPE(y) != T_BIGNUM) return Qfalse; if (RBIGNUM(x)->sign != RBIGNUM(y)->sign) return Qfalse; if (RBIGNUM(x)->len != RBIGNUM(y)->len) return Qfalse; if (MEMCMP(BDIGITS(x),BDIGITS(y),BDIGIT,RBIGNUM(y)->len) != 0) return Qfalse; return Qtrue; } /* * call-seq: * -big => other_big * * Unary minus (returns a new Bignum whose value is 0-big) */ static VALUE rb_big_uminus(x) VALUE x; { VALUE z = rb_big_clone(x); RBIGNUM(z)->sign = !RBIGNUM(x)->sign; return bignorm(z); } /* * call-seq: * ~big => integer * * Inverts the bits in big. As Bignums are conceptually infinite * length, the result acts as if it had an infinite number of one * bits to the left. In hex representations, this is displayed * as two periods to the left of the digits. * * sprintf("%X", ~0x1122334455) #=> "..FEEDDCCBBAA" */ static VALUE rb_big_neg(x) VALUE x; { VALUE z = rb_big_clone(x); long i; BDIGIT *ds; if (!RBIGNUM(x)->sign) get2comp(z); ds = BDIGITS(z); i = RBIGNUM(x)->len; if (!i) return INT2FIX(~0); while (i--) ds[i] = ~ds[i]; RBIGNUM(z)->sign = !RBIGNUM(z)->sign; if (RBIGNUM(x)->sign) get2comp(z); return bignorm(z); } static VALUE bigsub(x, y) VALUE x, y; { VALUE z = 0; BDIGIT *zds; BDIGIT_DBL_SIGNED num; long i = RBIGNUM(x)->len; /* if x is larger than y, swap */ if (RBIGNUM(x)->len < RBIGNUM(y)->len) { z = x; x = y; y = z; /* swap x y */ } else if (RBIGNUM(x)->len == RBIGNUM(y)->len) { while (i > 0) { i--; if (BDIGITS(x)[i] > BDIGITS(y)[i]) { break; } if (BDIGITS(x)[i] < BDIGITS(y)[i]) { z = x; x = y; y = z; /* swap x y */ break; } } } z = bignew(RBIGNUM(x)->len, z==0); zds = BDIGITS(z); for (i = 0, num = 0; i < RBIGNUM(y)->len; i++) { num += (BDIGIT_DBL_SIGNED)BDIGITS(x)[i] - BDIGITS(y)[i]; zds[i] = BIGLO(num); num = BIGDN(num); } while (num && i < RBIGNUM(x)->len) { num += BDIGITS(x)[i]; zds[i++] = BIGLO(num); num = BIGDN(num); } while (i < RBIGNUM(x)->len) { zds[i] = BDIGITS(x)[i]; i++; } return z; } static VALUE bigadd(x, y, sign) VALUE x, y; int sign; { VALUE z; BDIGIT_DBL num; long i, len; sign = (sign == RBIGNUM(y)->sign); if (RBIGNUM(x)->sign != sign) { if (sign) return bigsub(y, x); return bigsub(x, y); } if (RBIGNUM(x)->len > RBIGNUM(y)->len) { len = RBIGNUM(x)->len + 1; z = x; x = y; y = z; } else { len = RBIGNUM(y)->len + 1; } z = bignew(len, sign); len = RBIGNUM(x)->len; for (i = 0, num = 0; i < len; i++) { num += (BDIGIT_DBL)BDIGITS(x)[i] + BDIGITS(y)[i]; BDIGITS(z)[i] = BIGLO(num); num = BIGDN(num); } len = RBIGNUM(y)->len; while (num && i < len) { num += BDIGITS(y)[i]; BDIGITS(z)[i++] = BIGLO(num); num = BIGDN(num); } while (i < len) { BDIGITS(z)[i] = BDIGITS(y)[i]; i++; } BDIGITS(z)[i] = (BDIGIT)num; return z; } /* * call-seq: * big + other => Numeric * * Adds big and other, returning the result. */ VALUE rb_big_plus(x, y) VALUE x, y; { switch (TYPE(y)) { case T_FIXNUM: y = rb_int2big(FIX2LONG(y)); /* fall through */ case T_BIGNUM: return bignorm(bigadd(x, y, 1)); case T_FLOAT: return rb_float_new(rb_big2dbl(x) + RFLOAT(y)->value); default: return rb_num_coerce_bin(x, y); } } /* * call-seq: * big - other => Numeric * * Subtracts other from big, returning the result. */ VALUE rb_big_minus(x, y) VALUE x, y; { switch (TYPE(y)) { case T_FIXNUM: y = rb_int2big(FIX2LONG(y)); /* fall through */ case T_BIGNUM: return bignorm(bigadd(x, y, 0)); case T_FLOAT: return rb_float_new(rb_big2dbl(x) - RFLOAT(y)->value); default: return rb_num_coerce_bin(x, y); } } VALUE rb_big_mul0(x, y) VALUE x, y; { long i, j; BDIGIT_DBL n = 0; VALUE z; BDIGIT *zds; if (FIXNUM_P(x)) x = rb_int2big(FIX2LONG(x)); switch (TYPE(y)) { case T_FIXNUM: y = rb_int2big(FIX2LONG(y)); break; case T_BIGNUM: break; case T_FLOAT: return rb_float_new(rb_big2dbl(x) * RFLOAT(y)->value); default: return rb_num_coerce_bin(x, y); } j = RBIGNUM(x)->len + RBIGNUM(y)->len + 1; z = bignew(j, RBIGNUM(x)->sign==RBIGNUM(y)->sign); zds = BDIGITS(z); while (j--) zds[j] = 0; for (i = 0; i < RBIGNUM(x)->len; i++) { BDIGIT_DBL dd = BDIGITS(x)[i]; if (dd == 0) continue; n = 0; for (j = 0; j < RBIGNUM(y)->len; j++) { BDIGIT_DBL ee = n + (BDIGIT_DBL)dd * BDIGITS(y)[j]; n = zds[i + j] + ee; if (ee) zds[i + j] = BIGLO(n); n = BIGDN(n); } if (n) { zds[i + j] = n; } } return z; } /* * call-seq: * big * other => Numeric * * Multiplies big and other, returning the result. */ VALUE rb_big_mul(x, y) VALUE x, y; { return bignorm(rb_big_mul0(x, y)); } static void bigdivrem(x, y, divp, modp) VALUE x, y; VALUE *divp, *modp; { long nx = RBIGNUM(x)->len, ny = RBIGNUM(y)->len; long i, j; VALUE yy, z; BDIGIT *xds, *yds, *zds, *tds; BDIGIT_DBL t2; BDIGIT_DBL_SIGNED num; BDIGIT dd, q; if (BIGZEROP(y)) rb_num_zerodiv(); yds = BDIGITS(y); if (nx < ny || (nx == ny && BDIGITS(x)[nx - 1] < BDIGITS(y)[ny - 1])) { if (divp) *divp = rb_int2big(0); if (modp) *modp = x; return; } xds = BDIGITS(x); if (ny == 1) { dd = yds[0]; z = rb_big_clone(x); zds = BDIGITS(z); t2 = 0; i = nx; while (i--) { t2 = BIGUP(t2) + zds[i]; zds[i] = (BDIGIT)(t2 / dd); t2 %= dd; } RBIGNUM(z)->sign = RBIGNUM(x)->sign==RBIGNUM(y)->sign; if (modp) { *modp = rb_uint2big((unsigned long)t2); RBIGNUM(*modp)->sign = RBIGNUM(x)->sign; } if (divp) *divp = z; return; } z = bignew(nx==ny?nx+2:nx+1, RBIGNUM(x)->sign==RBIGNUM(y)->sign); zds = BDIGITS(z); if (nx==ny) zds[nx+1] = 0; while (!yds[ny-1]) ny--; dd = 0; q = yds[ny-1]; while ((q & (1<<(BITSPERDIG-1))) == 0) { q <<= 1; dd++; } if (dd) { yy = rb_big_clone(y); tds = BDIGITS(yy); j = 0; t2 = 0; while (j<ny) { t2 += (BDIGIT_DBL)yds[j]<<dd; tds[j++] = BIGLO(t2); t2 = BIGDN(t2); } yds = tds; j = 0; t2 = 0; while (j<nx) { t2 += (BDIGIT_DBL)xds[j]<<dd; zds[j++] = BIGLO(t2); t2 = BIGDN(t2); } zds[j] = (BDIGIT)t2; } else { zds[nx] = 0; j = nx; while (j--) zds[j] = xds[j]; } j = nx==ny?nx+1:nx; do { if (zds[j] == yds[ny-1]) q = BIGRAD-1; else q = (BDIGIT)((BIGUP(zds[j]) + zds[j-1])/yds[ny-1]); if (q) { i = 0; num = 0; t2 = 0; do { /* multiply and subtract */ BDIGIT_DBL ee; t2 += (BDIGIT_DBL)yds[i] * q; ee = num - BIGLO(t2); num = (BDIGIT_DBL)zds[j - ny + i] + ee; if (ee) zds[j - ny + i] = BIGLO(num); num = BIGDN(num); t2 = BIGDN(t2); } while (++i < ny); num += zds[j - ny + i] - t2;/* borrow from high digit; don't update */ while (num) { /* "add back" required */ i = 0; num = 0; q--; do { BDIGIT_DBL ee = num + yds[i]; num = (BDIGIT_DBL)zds[j - ny + i] + ee; if (ee) zds[j - ny + i] = BIGLO(num); num = BIGDN(num); } while (++i < ny); num--; } } zds[j] = q; } while (--j >= ny); if (divp) { /* move quotient down in z */ *divp = rb_big_clone(z); zds = BDIGITS(*divp); j = (nx==ny ? nx+2 : nx+1) - ny; for (i = 0;i < j;i++) zds[i] = zds[i+ny]; RBIGNUM(*divp)->len = i; } if (modp) { /* normalize remainder */ *modp = rb_big_clone(z); zds = BDIGITS(*modp); while (--ny && !zds[ny]); ++ny; if (dd) { t2 = 0; i = ny; while(i--) { t2 = (t2 | zds[i]) >> dd; q = zds[i]; zds[i] = BIGLO(t2); t2 = BIGUP(q); } } RBIGNUM(*modp)->len = ny; RBIGNUM(*modp)->sign = RBIGNUM(x)->sign; } } static void bigdivmod(x, y, divp, modp) VALUE x, y; VALUE *divp, *modp; { VALUE mod; bigdivrem(x, y, divp, &mod); if (RBIGNUM(x)->sign != RBIGNUM(y)->sign && !BIGZEROP(mod)) { if (divp) *divp = bigadd(*divp, rb_int2big(1), 0); if (modp) *modp = bigadd(mod, y, 1); } else { if (divp) *divp = *divp; if (modp) *modp = mod; } } /* * call-seq: * big / other => Numeric * big.div(other) => Numeric * * Divides big by other, returning the result. */ static VALUE rb_big_div(x, y) VALUE x, y; { VALUE z; switch (TYPE(y)) { case T_FIXNUM: y = rb_int2big(FIX2LONG(y)); break; case T_BIGNUM: break; case T_FLOAT: return rb_float_new(rb_big2dbl(x) / RFLOAT(y)->value); default: return rb_num_coerce_bin(x, y); } bigdivmod(x, y, &z, 0); return bignorm(z); } /* * call-seq: * big % other => Numeric * big.modulo(other) => Numeric * * Returns big modulo other. See Numeric.divmod for more * information. */ static VALUE rb_big_modulo(x, y) VALUE x, y; { VALUE z; switch (TYPE(y)) { case T_FIXNUM: y = rb_int2big(FIX2LONG(y)); break; case T_BIGNUM: break; default: return rb_num_coerce_bin(x, y); } bigdivmod(x, y, 0, &z); return bignorm(z); } /* * call-seq: * big.remainder(numeric) => number * * Returns the remainder after dividing <i>big</i> by <i>numeric</i>. * * -1234567890987654321.remainder(13731) #=> -6966 * -1234567890987654321.remainder(13731.24) #=> -9906.22531493148 */ static VALUE rb_big_remainder(x, y) VALUE x, y; { VALUE z; switch (TYPE(y)) { case T_FIXNUM: y = rb_int2big(FIX2LONG(y)); break; case T_BIGNUM: break; default: return rb_num_coerce_bin(x, y); } bigdivrem(x, y, 0, &z); return bignorm(z); } static VALUE big_lshift _((VALUE, unsigned long)); static VALUE big_rshift _((VALUE, unsigned long)); static VALUE big_shift(x, n) VALUE x; int n; { if (n < 0) return big_lshift(x, (unsigned int)n); else if (n > 0) return big_rshift(x, (unsigned int)n); return x; } /* * call-seq: * big.divmod(numeric) => array * * See <code>Numeric#divmod</code>. * */ VALUE rb_big_divmod(x, y) VALUE x, y; { VALUE div, mod; switch (TYPE(y)) { case T_FIXNUM: y = rb_int2big(FIX2LONG(y)); break; case T_BIGNUM: break; default: return rb_num_coerce_bin(x, y); } bigdivmod(x, y, &div, &mod); return rb_assoc_new(bignorm(div), bignorm(mod)); } /* * call-seq: * big.quo(numeric) -> float * * Returns the floating point result of dividing <i>big</i> by * <i>numeric</i>. * * -1234567890987654321.quo(13731) #=> -89910996357705.5 * -1234567890987654321.quo(13731.24) #=> -89909424858035.7 * */ static VALUE rb_big_quo(x, y) VALUE x, y; { double dx = rb_big2dbl(x); double dy; switch (TYPE(y)) { case T_FIXNUM: dy = (double)FIX2LONG(y); break; case T_BIGNUM: dy = rb_big2dbl(y); break; case T_FLOAT: dy = RFLOAT(y)->value; break; default: return rb_num_coerce_bin(x, y); } return rb_float_new(dx / dy); } /* * call-seq: * big ** exponent #=> numeric * * Raises _big_ to the _exponent_ power (which may be an integer, float, * or anything that will coerce to a number). The result may be * a Fixnum, Bignum, or Float * * 123456789 ** 2 #=> 15241578750190521 * 123456789 ** 1.2 #=> 5126464716.09932 * 123456789 ** -2 #=> 6.5610001194102e-17 */ VALUE rb_big_pow(x, y) VALUE x, y; { double d; long yy; if (y == INT2FIX(0)) return INT2FIX(1); switch (TYPE(y)) { case T_FLOAT: d = RFLOAT(y)->value; break; case T_BIGNUM: rb_warn("in a**b, b may be too big"); d = rb_big2dbl(y); break; case T_FIXNUM: yy = FIX2LONG(y); if (yy > 0) { VALUE z = x; const long BIGLEN_LIMIT = 1024*1024 / SIZEOF_BDIGITS; if ((RBIGNUM(x)->len > BIGLEN_LIMIT) || (RBIGNUM(x)->len > BIGLEN_LIMIT / yy)) { rb_warn("in a**b, b may be too big"); d = (double)yy; break; } for (;;) { yy -= 1; if (yy == 0) break; while (yy % 2 == 0) { yy /= 2; x = rb_big_mul0(x, x); bigtrunc(x); } z = rb_big_mul0(z, x); bigtrunc(z); } return bignorm(z); } d = (double)yy; break; default: return rb_num_coerce_bin(x, y); } return rb_float_new(pow(rb_big2dbl(x), d)); } /* * call-seq: * big & numeric => integer * * Performs bitwise +and+ between _big_ and _numeric_. */ VALUE rb_big_and(xx, yy) VALUE xx, yy; { volatile VALUE x, y, z; BDIGIT *ds1, *ds2, *zds; long i, l1, l2; char sign; x = xx; y = rb_to_int(yy); if (FIXNUM_P(y)) { y = rb_int2big(FIX2LONG(y)); } if (!RBIGNUM(y)->sign) { y = rb_big_clone(y); get2comp(y); } if (!RBIGNUM(x)->sign) { x = rb_big_clone(x); get2comp(x); } if (RBIGNUM(x)->len > RBIGNUM(y)->len) { l1 = RBIGNUM(y)->len; l2 = RBIGNUM(x)->len; ds1 = BDIGITS(y); ds2 = BDIGITS(x); sign = RBIGNUM(y)->sign; } else { l1 = RBIGNUM(x)->len; l2 = RBIGNUM(y)->len; ds1 = BDIGITS(x); ds2 = BDIGITS(y); sign = RBIGNUM(x)->sign; } z = bignew(l2, RBIGNUM(x)->sign || RBIGNUM(y)->sign); zds = BDIGITS(z); for (i=0; i<l1; i++) { zds[i] = ds1[i] & ds2[i]; } for (; i<l2; i++) { zds[i] = sign?0:ds2[i]; } if (!RBIGNUM(z)->sign) get2comp(z); return bignorm(z); } /* * call-seq: * big | numeric => integer * * Performs bitwise +or+ between _big_ and _numeric_. */ VALUE rb_big_or(xx, yy) VALUE xx, yy; { volatile VALUE x, y, z; BDIGIT *ds1, *ds2, *zds; long i, l1, l2; char sign; x = xx; y = rb_to_int(yy); if (FIXNUM_P(y)) { y = rb_int2big(FIX2LONG(y)); } if (!RBIGNUM(y)->sign) { y = rb_big_clone(y); get2comp(y); } if (!RBIGNUM(x)->sign) { x = rb_big_clone(x); get2comp(x); } if (RBIGNUM(x)->len > RBIGNUM(y)->len) { l1 = RBIGNUM(y)->len; l2 = RBIGNUM(x)->len; ds1 = BDIGITS(y); ds2 = BDIGITS(x); sign = RBIGNUM(y)->sign; } else { l1 = RBIGNUM(x)->len; l2 = RBIGNUM(y)->len; ds1 = BDIGITS(x); ds2 = BDIGITS(y); sign = RBIGNUM(x)->sign; } z = bignew(l2, RBIGNUM(x)->sign && RBIGNUM(y)->sign); zds = BDIGITS(z); for (i=0; i<l1; i++) { zds[i] = ds1[i] | ds2[i]; } for (; i<l2; i++) { zds[i] = sign?ds2[i]:(BIGRAD-1); } if (!RBIGNUM(z)->sign) get2comp(z); return bignorm(z); } /* * call-seq: * big ^ numeric => integer * * Performs bitwise +exclusive or+ between _big_ and _numeric_. */ VALUE rb_big_xor(xx, yy) VALUE xx, yy; { volatile VALUE x, y; VALUE z; BDIGIT *ds1, *ds2, *zds; long i, l1, l2; char sign; x = xx; y = rb_to_int(yy); if (FIXNUM_P(y)) { y = rb_int2big(FIX2LONG(y)); } if (!RBIGNUM(y)->sign) { y = rb_big_clone(y); get2comp(y); } if (!RBIGNUM(x)->sign) { x = rb_big_clone(x); get2comp(x); } if (RBIGNUM(x)->len > RBIGNUM(y)->len) { l1 = RBIGNUM(y)->len; l2 = RBIGNUM(x)->len; ds1 = BDIGITS(y); ds2 = BDIGITS(x); sign = RBIGNUM(y)->sign; } else { l1 = RBIGNUM(x)->len; l2 = RBIGNUM(y)->len; ds1 = BDIGITS(x); ds2 = BDIGITS(y); sign = RBIGNUM(x)->sign; } RBIGNUM(x)->sign = RBIGNUM(x)->sign?1:0; RBIGNUM(y)->sign = RBIGNUM(y)->sign?1:0; z = bignew(l2, !(RBIGNUM(x)->sign ^ RBIGNUM(y)->sign)); zds = BDIGITS(z); for (i=0; i<l1; i++) { zds[i] = ds1[i] ^ ds2[i]; } for (; i<l2; i++) { zds[i] = sign?ds2[i]:~ds2[i]; } if (!RBIGNUM(z)->sign) get2comp(z); return bignorm(z); } static VALUE check_shiftdown(VALUE y, VALUE x) { if (!RBIGNUM(x)->len) return INT2FIX(0); if (RBIGNUM(y)->len > SIZEOF_LONG / SIZEOF_BDIGITS) { return RBIGNUM(x)->sign ? INT2FIX(0) : INT2FIX(-1); } return Qnil; } /* * call-seq: * big << numeric => integer * * Shifts big left _numeric_ positions (right if _numeric_ is negative). */ VALUE rb_big_lshift(x, y) VALUE x, y; { long shift; int neg = 0; for (;;) { if (FIXNUM_P(y)) { shift = FIX2LONG(y); if (shift < 0) { neg = 1; shift = -shift; } break; } else if (TYPE(y) == T_BIGNUM) { if (!RBIGNUM(y)->sign) { VALUE t = check_shiftdown(y, x); if (!NIL_P(t)) return t; neg = 1; } shift = big2ulong(y, "long", Qtrue); break; } y = rb_to_int(y); } if (neg) return big_rshift(x, shift); return big_lshift(x, shift); } static VALUE big_lshift(x, shift) VALUE x; unsigned long shift; { BDIGIT *xds, *zds; long s1 = shift/BITSPERDIG; int s2 = shift%BITSPERDIG; VALUE z; BDIGIT_DBL num = 0; long len, i; len = RBIGNUM(x)->len; z = bignew(len+s1+1, RBIGNUM(x)->sign); zds = BDIGITS(z); for (i=0; i<s1; i++) { *zds++ = 0; } xds = BDIGITS(x); for (i=0; i<len; i++) { num = num | (BDIGIT_DBL)*xds++<<s2; *zds++ = BIGLO(num); num = BIGDN(num); } *zds = BIGLO(num); return bignorm(z); } /* * call-seq: * big >> numeric => integer * * Shifts big right _numeric_ positions (left if _numeric_ is negative). */ VALUE rb_big_rshift(x, y) VALUE x, y; { long shift; int neg = 0; for (;;) { if (FIXNUM_P(y)) { shift = FIX2LONG(y); if (shift < 0) { neg = 1; shift = -shift; } break; } else if (TYPE(y) == T_BIGNUM) { if (RBIGNUM(y)->sign) { VALUE t = check_shiftdown(y, x); if (!NIL_P(t)) return t; } else { neg = 1; } shift = big2ulong(y, "long", Qtrue); break; } y = rb_to_int(y); } if (neg) return big_lshift(x, shift); return big_rshift(x, shift); } static VALUE big_rshift(x, shift) VALUE x; unsigned long shift; { BDIGIT *xds, *zds; long s1 = shift/BITSPERDIG; int s2 = shift%BITSPERDIG; VALUE z; BDIGIT_DBL num = 0; long i, j; volatile VALUE save_x; if (s1 > RBIGNUM(x)->len) { if (RBIGNUM(x)->sign) return INT2FIX(0); else return INT2FIX(-1); } if (!RBIGNUM(x)->sign) { save_x = x = rb_big_clone(x); get2comp(x); } xds = BDIGITS(x); i = RBIGNUM(x)->len; j = i - s1; if (j == 0) { if (RBIGNUM(x)->sign) return INT2FIX(0); else return INT2FIX(-1); } z = bignew(j, RBIGNUM(x)->sign); if (!RBIGNUM(x)->sign) { num = ((BDIGIT_DBL)~0) << BITSPERDIG; } zds = BDIGITS(z); while (i--, j--) { num = (num | xds[i]) >> s2; zds[j] = BIGLO(num); num = BIGUP(xds[i]); } if (!RBIGNUM(x)->sign) { get2comp(z); } return bignorm(z); } /* * call-seq: * big[n] -> 0, 1 * * Bit Reference---Returns the <em>n</em>th bit in the (assumed) binary * representation of <i>big</i>, where <i>big</i>[0] is the least * significant bit. * * a = 9**15 * 50.downto(0) do |n| * print a[n] * end * * <em>produces:</em> * * 000101110110100000111000011110010100111100010111001 * */ static VALUE rb_big_aref(x, y) VALUE x, y; { BDIGIT *xds; BDIGIT_DBL num; unsigned long shift; long i, s1, s2; if (TYPE(y) == T_BIGNUM) { if (!RBIGNUM(y)->sign) return INT2FIX(0); if (RBIGNUM(bigtrunc(y))->len > SIZEOF_LONG/SIZEOF_BDIGITS) { out_of_range: return RBIGNUM(x)->sign ? INT2FIX(0) : INT2FIX(1); } shift = big2ulong(y, "long", Qfalse); } else { i = NUM2LONG(y); if (i < 0) return INT2FIX(0); shift = (VALUE)i; } s1 = shift/BITSPERDIG; s2 = shift%BITSPERDIG; if (s1 >= RBIGNUM(x)->len) goto out_of_range; if (!RBIGNUM(x)->sign) { xds = BDIGITS(x); i = 0; num = 1; while (num += ~xds[i], ++i <= s1) { num = BIGDN(num); } } else { num = BDIGITS(x)[s1]; } if (num & ((BDIGIT_DBL)1<<s2)) return INT2FIX(1); return INT2FIX(0); } /* * call-seq: * big.hash => fixnum * * Compute a hash based on the value of _big_. */ static VALUE rb_big_hash(x) VALUE x; { long i, len, key; BDIGIT *digits; key = 0; digits = BDIGITS(x); len = RBIGNUM(x)->len; for (i=0; i<len; i++) { key ^= *digits++; } return LONG2FIX(key); } /* * MISSING: documentation */ static VALUE rb_big_coerce(x, y) VALUE x, y; { if (FIXNUM_P(y)) { return rb_assoc_new(rb_int2big(FIX2LONG(y)), x); } else if (TYPE(y) == T_BIGNUM) { return rb_assoc_new(y, x); } else { rb_raise(rb_eTypeError, "can't coerce %s to Bignum", rb_obj_classname(y)); } /* not reached */ return Qnil; } /* * call-seq: * big.abs -> aBignum * * Returns the absolute value of <i>big</i>. * * -1234567890987654321.abs #=> 1234567890987654321 */ static VALUE rb_big_abs(x) VALUE x; { if (!RBIGNUM(x)->sign) { x = rb_big_clone(x); RBIGNUM(x)->sign = 1; } return x; } VALUE rb_big_rand(max, rand_buf) VALUE max; double *rand_buf; { VALUE v; long len = RBIGNUM(max)->len; if (BIGZEROP(max)) { return rb_float_new(rand_buf[0]); } v = bignew(len,1); len--; BDIGITS(v)[len] = BDIGITS(max)[len] * rand_buf[len]; while (len--) { BDIGITS(v)[len] = ((BDIGIT)~0) * rand_buf[len]; } return v; } /* * call-seq: * big.size -> integer * * Returns the number of bytes in the machine representation of * <i>big</i>. * * (256**10 - 1).size #=> 12 * (256**20 - 1).size #=> 20 * (256**40 - 1).size #=> 40 */ static VALUE rb_big_size(big) VALUE big; { return LONG2FIX(RBIGNUM(big)->len*SIZEOF_BDIGITS); } /* * Bignum objects hold integers outside the range of * Fixnum. Bignum objects are created * automatically when integer calculations would otherwise overflow a * Fixnum. When a calculation involving * Bignum objects returns a result that will fit in a * Fixnum, the result is automatically converted. * * For the purposes of the bitwise operations and <code>[]</code>, a * Bignum is treated as if it were an infinite-length * bitstring with 2's complement representation. * * While Fixnum values are immediate, Bignum * objects are not---assignment and parameter passing work with * references to objects, not the objects themselves. * */ void Init_Bignum() { rb_cBignum = rb_define_class("Bignum", rb_cInteger); rb_define_method(rb_cBignum, "to_s", rb_big_to_s, -1); rb_define_method(rb_cBignum, "coerce", rb_big_coerce, 1); rb_define_method(rb_cBignum, "-@", rb_big_uminus, 0); rb_define_method(rb_cBignum, "+", rb_big_plus, 1); rb_define_method(rb_cBignum, "-", rb_big_minus, 1); rb_define_method(rb_cBignum, "*", rb_big_mul, 1); rb_define_method(rb_cBignum, "/", rb_big_div, 1); rb_define_method(rb_cBignum, "%", rb_big_modulo, 1); rb_define_method(rb_cBignum, "div", rb_big_div, 1); rb_define_method(rb_cBignum, "divmod", rb_big_divmod, 1); rb_define_method(rb_cBignum, "modulo", rb_big_modulo, 1); rb_define_method(rb_cBignum, "remainder", rb_big_remainder, 1); rb_define_method(rb_cBignum, "quo", rb_big_quo, 1); rb_define_method(rb_cBignum, "**", rb_big_pow, 1); rb_define_method(rb_cBignum, "&", rb_big_and, 1); rb_define_method(rb_cBignum, "|", rb_big_or, 1); rb_define_method(rb_cBignum, "^", rb_big_xor, 1); rb_define_method(rb_cBignum, "~", rb_big_neg, 0); rb_define_method(rb_cBignum, "<<", rb_big_lshift, 1); rb_define_method(rb_cBignum, ">>", rb_big_rshift, 1); rb_define_method(rb_cBignum, "[]", rb_big_aref, 1); rb_define_method(rb_cBignum, "<=>", rb_big_cmp, 1); rb_define_method(rb_cBignum, "==", rb_big_eq, 1); rb_define_method(rb_cBignum, "eql?", rb_big_eql, 1); rb_define_method(rb_cBignum, "hash", rb_big_hash, 0); rb_define_method(rb_cBignum, "to_f", rb_big_to_f, 0); rb_define_method(rb_cBignum, "abs", rb_big_abs, 0); rb_define_method(rb_cBignum, "size", rb_big_size, 0); } /********************************************************************** class.c - $Author: shyouhei $ $Date: 2009-01-16 02:58:45 +0100 (Fri, 16 Jan 2009) $ created at: Tue Aug 10 15:05:44 JST 1993 Copyright (C) 1993-2003 <NAME> **********************************************************************/ #include "ruby.h" #include "rubysig.h" #include "node.h" #include "st.h" #include <ctype.h> extern st_table *rb_class_tbl; VALUE rb_class_boot(super) VALUE super; { NEWOBJ(klass, struct RClass); OBJSETUP(klass, rb_cClass, T_CLASS); klass->super = super; klass->iv_tbl = 0; klass->m_tbl = 0; /* safe GC */ klass->m_tbl = st_init_numtable(); OBJ_INFECT(klass, super); return (VALUE)klass; } VALUE rb_class_new(super) VALUE super; { Check_Type(super, T_CLASS); if (super == rb_cClass) { rb_raise(rb_eTypeError, "can't make subclass of Class"); } if (FL_TEST(super, FL_SINGLETON)) { rb_raise(rb_eTypeError, "can't make subclass of virtual class"); } return rb_class_boot(super); } struct clone_method_data { st_table *tbl; VALUE klass; }; static int clone_method(mid, body, data) ID mid; NODE *body; struct clone_method_data *data; { NODE *fbody = body->nd_body; if (fbody && nd_type(fbody) == NODE_SCOPE) { NODE *cref = (NODE*)fbody->nd_rval; if (cref) cref = cref->nd_next; fbody = rb_copy_node_scope(fbody, NEW_CREF(data->klass, cref)); } st_insert(data->tbl, mid, (st_data_t)NEW_METHOD(fbody, body->nd_noex)); return ST_CONTINUE; } /* :nodoc: */ VALUE rb_mod_init_copy(clone, orig) VALUE clone, orig; { rb_obj_init_copy(clone, orig); if (!FL_TEST(CLASS_OF(clone), FL_SINGLETON)) { RBASIC(clone)->klass = RBASIC(orig)->klass; RBASIC(clone)->klass = rb_singleton_class_clone(clone); } RCLASS(clone)->super = RCLASS(orig)->super; if (RCLASS(orig)->iv_tbl) { ID id; RCLASS(clone)->iv_tbl = st_copy(RCLASS(orig)->iv_tbl); id = rb_intern("__classpath__"); st_delete(RCLASS(clone)->iv_tbl, (st_data_t*)&id, 0); id = rb_intern("__classid__"); st_delete(RCLASS(clone)->iv_tbl, (st_data_t*)&id, 0); } if (RCLASS(orig)->m_tbl) { struct clone_method_data data; data.tbl = RCLASS(clone)->m_tbl = st_init_numtable(); data.klass = (VALUE)clone; st_foreach(RCLASS(orig)->m_tbl, clone_method, (st_data_t)&data); } return clone; } /* :nodoc: */ VALUE rb_class_init_copy(clone, orig) VALUE clone, orig; { if (RCLASS(clone)->super != 0) { rb_raise(rb_eTypeError, "already initialized class"); } if (FL_TEST(orig, FL_SINGLETON)) { rb_raise(rb_eTypeError, "can't copy singleton class"); } return rb_mod_init_copy(clone, orig); } VALUE rb_singleton_class_clone(obj) VALUE obj; { VALUE klass = RBASIC(obj)->klass; if (!FL_TEST(klass, FL_SINGLETON)) return klass; else { /* copy singleton(unnamed) class */ NEWOBJ(clone, struct RClass); OBJSETUP(clone, 0, RBASIC(klass)->flags); if (BUILTIN_TYPE(obj) == T_CLASS) { RBASIC(clone)->klass = (VALUE)clone; } else { RBASIC(clone)->klass = rb_singleton_class_clone(klass); } clone->super = RCLASS(klass)->super; clone->iv_tbl = 0; clone->m_tbl = 0; if (RCLASS(klass)->iv_tbl) { clone->iv_tbl = st_copy(RCLASS(klass)->iv_tbl); } { struct clone_method_data data; data.tbl = clone->m_tbl = st_init_numtable(); switch (TYPE(obj)) { case T_CLASS: case T_MODULE: data.klass = obj; break; default: data.klass = 0; break; } st_foreach(RCLASS(klass)->m_tbl, clone_method, (st_data_t)&data); } rb_singleton_class_attached(RBASIC(clone)->klass, (VALUE)clone); FL_SET(clone, FL_SINGLETON); return (VALUE)clone; } } void rb_singleton_class_attached(klass, obj) VALUE klass, obj; { if (FL_TEST(klass, FL_SINGLETON)) { if (!RCLASS(klass)->iv_tbl) { RCLASS(klass)->iv_tbl = st_init_numtable(); } st_insert(RCLASS(klass)->iv_tbl, rb_intern("__attached__"), obj); } } VALUE rb_make_metaclass(obj, super) VALUE obj, super; { VALUE klass = rb_class_boot(super); FL_SET(klass, FL_SINGLETON); RBASIC(obj)->klass = klass; rb_singleton_class_attached(klass, obj); if (BUILTIN_TYPE(obj) == T_CLASS && FL_TEST(obj, FL_SINGLETON)) { RBASIC(klass)->klass = klass; RCLASS(klass)->super = RBASIC(rb_class_real(RCLASS(obj)->super))->klass; } else { VALUE metasuper = RBASIC(rb_class_real(super))->klass; /* metaclass of a superclass may be NULL at boot time */ if (metasuper) { RBASIC(klass)->klass = metasuper; } } return klass; } VALUE rb_define_class_id(id, super) ID id; VALUE super; { VALUE klass; if (!super) super = rb_cObject; klass = rb_class_new(super); rb_make_metaclass(klass, RBASIC(super)->klass); return klass; } void rb_check_inheritable(super) VALUE super; { if (TYPE(super) != T_CLASS) { rb_raise(rb_eTypeError, "superclass must be a Class (%s given)", rb_obj_classname(super)); } if (RBASIC(super)->flags & FL_SINGLETON) { rb_raise(rb_eTypeError, "can't make subclass of virtual class"); } } VALUE rb_class_inherited(super, klass) VALUE super, klass; { if (!super) super = rb_cObject; return rb_funcall(super, rb_intern("inherited"), 1, klass); } VALUE rb_define_class(name, super) const char *name; VALUE super; { VALUE klass; ID id; id = rb_intern(name); if (rb_const_defined(rb_cObject, id)) { klass = rb_const_get(rb_cObject, id); if (TYPE(klass) != T_CLASS) { rb_raise(rb_eTypeError, "%s is not a class", name); } if (rb_class_real(RCLASS(klass)->super) != super) { rb_name_error(id, "%s is already defined", name); } return klass; } if (!super) { rb_warn("no super class for `%s', Object assumed", name); } klass = rb_define_class_id(id, super); st_add_direct(rb_class_tbl, id, klass); rb_name_class(klass, id); rb_const_set(rb_cObject, id, klass); rb_class_inherited(super, klass); return klass; } VALUE rb_define_class_under(outer, name, super) VALUE outer; const char *name; VALUE super; { VALUE klass; ID id; id = rb_intern(name); if (rb_const_defined_at(outer, id)) { klass = rb_const_get_at(outer, id); if (TYPE(klass) != T_CLASS) { rb_raise(rb_eTypeError, "%s is not a class", name); } if (rb_class_real(RCLASS(klass)->super) != super) { rb_name_error(id, "%s is already defined", name); } return klass; } if (!super) { rb_warn("no super class for `%s::%s', Object assumed", rb_class2name(outer), name); } klass = rb_define_class_id(id, super); rb_set_class_path(klass, outer, name); rb_const_set(outer, id, klass); rb_class_inherited(super, klass); return klass; } VALUE rb_module_new() { NEWOBJ(mdl, struct RClass); OBJSETUP(mdl, rb_cModule, T_MODULE); mdl->super = 0; mdl->iv_tbl = 0; mdl->m_tbl = 0; mdl->m_tbl = st_init_numtable(); return (VALUE)mdl; } VALUE rb_define_module_id(id) ID id; { VALUE mdl; mdl = rb_module_new(); rb_name_class(mdl, id); return mdl; } VALUE rb_define_module(name) const char *name; { VALUE module; ID id; id = rb_intern(name); if (rb_const_defined(rb_cObject, id)) { module = rb_const_get(rb_cObject, id); if (TYPE(module) == T_MODULE) return module; rb_raise(rb_eTypeError, "%s is not a module", rb_obj_classname(module)); } module = rb_define_module_id(id); st_add_direct(rb_class_tbl, id, module); rb_const_set(rb_cObject, id, module); return module; } VALUE rb_define_module_under(outer, name) VALUE outer; const char *name; { VALUE module; ID id; id = rb_intern(name); if (rb_const_defined_at(outer, id)) { module = rb_const_get_at(outer, id); if (TYPE(module) == T_MODULE) return module; rb_raise(rb_eTypeError, "%s::%s is not a module", rb_class2name(outer), rb_obj_classname(module)); } module = rb_define_module_id(id); rb_const_set(outer, id, module); rb_set_class_path(module, outer, name); return module; } static VALUE include_class_new(module, super) VALUE module, super; { NEWOBJ(klass, struct RClass); OBJSETUP(klass, rb_cClass, T_ICLASS); if (BUILTIN_TYPE(module) == T_ICLASS) { module = RBASIC(module)->klass; } if (!RCLASS(module)->iv_tbl) { RCLASS(module)->iv_tbl = st_init_numtable(); } klass->iv_tbl = RCLASS(module)->iv_tbl; klass->m_tbl = RCLASS(module)->m_tbl; klass->super = super; if (TYPE(module) == T_ICLASS) { RBASIC(klass)->klass = RBASIC(module)->klass; } else { RBASIC(klass)->klass = module; } OBJ_INFECT(klass, module); OBJ_INFECT(klass, super); return (VALUE)klass; } void rb_include_module(klass, module) VALUE klass, module; { VALUE p, c; int changed = 0; rb_frozen_class_p(klass); if (!OBJ_TAINTED(klass)) { rb_secure(4); } if (TYPE(module) != T_MODULE) { Check_Type(module, T_MODULE); } OBJ_INFECT(klass, module); c = klass; while (module) { int superclass_seen = Qfalse; if (RCLASS(klass)->m_tbl == RCLASS(module)->m_tbl) rb_raise(rb_eArgError, "cyclic include detected"); /* ignore if the module included already in superclasses */ for (p = RCLASS(klass)->super; p; p = RCLASS(p)->super) { switch (BUILTIN_TYPE(p)) { case T_ICLASS: if (RCLASS(p)->m_tbl == RCLASS(module)->m_tbl) { if (!superclass_seen) { c = p; /* move insertion point */ } goto skip; } break; case T_CLASS: superclass_seen = Qtrue; break; } } c = RCLASS(c)->super = include_class_new(module, RCLASS(c)->super); changed = 1; skip: module = RCLASS(module)->super; } if (changed) rb_clear_cache(); } /* * call-seq: * mod.included_modules -> array * * Returns the list of modules included in <i>mod</i>. * * module Mixin * end * * module Outer * include Mixin * end * * Mixin.included_modules #=> [] * Outer.included_modules #=> [Mixin] */ VALUE rb_mod_included_modules(mod) VALUE mod; { VALUE ary = rb_ary_new(); VALUE p; for (p = RCLASS(mod)->super; p; p = RCLASS(p)->super) { if (BUILTIN_TYPE(p) == T_ICLASS) { rb_ary_push(ary, RBASIC(p)->klass); } } return ary; } /* * call-seq: * mod.include?(module) => true or false * * Returns <code>true</code> if <i>module</i> is included in * <i>mod</i> or one of <i>mod</i>'s ancestors. * * module A * end * class B * include A * end * class C < B * end * B.include?(A) #=> true * C.include?(A) #=> true * A.include?(A) #=> false */ VALUE rb_mod_include_p(mod, mod2) VALUE mod; VALUE mod2; { VALUE p; Check_Type(mod2, T_MODULE); for (p = RCLASS(mod)->super; p; p = RCLASS(p)->super) { if (BUILTIN_TYPE(p) == T_ICLASS) { if (RBASIC(p)->klass == mod2) return Qtrue; } } return Qfalse; } /* * call-seq: * mod.ancestors -> array * * Returns a list of modules included in <i>mod</i> (including * <i>mod</i> itself). * * module Mod * include Math * include Comparable * end * * Mod.ancestors #=> [Mod, Comparable, Math] * Math.ancestors #=> [Math] */ VALUE rb_mod_ancestors(mod) VALUE mod; { VALUE p, ary = rb_ary_new(); for (p = mod; p; p = RCLASS(p)->super) { if (FL_TEST(p, FL_SINGLETON)) continue; if (BUILTIN_TYPE(p) == T_ICLASS) { rb_ary_push(ary, RBASIC(p)->klass); } else { rb_ary_push(ary, p); } } return ary; } #define VISI(x) ((x)&NOEX_MASK) #define VISI_CHECK(x,f) (VISI(x) == (f)) static int ins_methods_push(name, type, ary, visi) ID name; long type; VALUE ary; long visi; { if (type == -1) return ST_CONTINUE; switch (visi) { case NOEX_PRIVATE: case NOEX_PROTECTED: case NOEX_PUBLIC: visi = (type == visi); break; default: visi = (type != NOEX_PRIVATE); break; } if (visi) { rb_ary_push(ary, rb_str_new2(rb_id2name(name))); } return ST_CONTINUE; } static int ins_methods_i(name, type, ary) ID name; long type; VALUE ary; { return ins_methods_push(name, type, ary, -1); /* everything but private */ } static int ins_methods_prot_i(name, type, ary) ID name; long type; VALUE ary; { return ins_methods_push(name, type, ary, NOEX_PROTECTED); } static int ins_methods_priv_i(name, type, ary) ID name; long type; VALUE ary; { return ins_methods_push(name, type, ary, NOEX_PRIVATE); } static int ins_methods_pub_i(name, type, ary) ID name; long type; VALUE ary; { return ins_methods_push(name, type, ary, NOEX_PUBLIC); } static int method_entry(key, body, list) ID key; NODE *body; st_table *list; { long type; if (key == ID_ALLOCATOR) return ST_CONTINUE; if (!st_lookup(list, key, 0)) { if (!body->nd_body) type = -1; /* none */ else type = VISI(body->nd_noex); st_add_direct(list, key, type); } return ST_CONTINUE; } static VALUE class_instance_method_list(argc, argv, mod, func) int argc; VALUE *argv; VALUE mod; int (*func) _((ID, long, VALUE)); { VALUE ary; int recur; st_table *list; if (argc == 0) { recur = Qtrue; } else { VALUE r; rb_scan_args(argc, argv, "01", &r); recur = RTEST(r); } list = st_init_numtable(); for (; mod; mod = RCLASS(mod)->super) { st_foreach(RCLASS(mod)->m_tbl, method_entry, (st_data_t)list); if (BUILTIN_TYPE(mod) == T_ICLASS) continue; if (FL_TEST(mod, FL_SINGLETON)) continue; if (!recur) break; } ary = rb_ary_new(); st_foreach(list, func, ary); st_free_table(list); return ary; } /* * call-seq: * mod.instance_methods(include_super=true) => array * * Returns an array containing the names of public instance methods in * the receiver. For a module, these are the public methods; for a * class, they are the instance (not singleton) methods. With no * argument, or with an argument that is <code>false</code>, the * instance methods in <i>mod</i> are returned, otherwise the methods * in <i>mod</i> and <i>mod</i>'s superclasses are returned. * * module A * def method1() end * end * class B * def method2() end * end * class C < B * def method3() end * end * * A.instance_methods #=> ["method1"] * B.instance_methods(false) #=> ["method2"] * C.instance_methods(false) #=> ["method3"] * C.instance_methods(true).length #=> 43 */ VALUE rb_class_instance_methods(argc, argv, mod) int argc; VALUE *argv; VALUE mod; { return class_instance_method_list(argc, argv, mod, ins_methods_i); } /* * call-seq: * mod.protected_instance_methods(include_super=true) => array * * Returns a list of the protected instance methods defined in * <i>mod</i>. If the optional parameter is not <code>false</code>, the * methods of any ancestors are included. */ VALUE rb_class_protected_instance_methods(argc, argv, mod) int argc; VALUE *argv; VALUE mod; { return class_instance_method_list(argc, argv, mod, ins_methods_prot_i); } /* * call-seq: * mod.private_instance_methods(include_super=true) => array * * Returns a list of the private instance methods defined in * <i>mod</i>. If the optional parameter is not <code>false</code>, the * methods of any ancestors are included. * * module Mod * def method1() end * private :method1 * def method2() end * end * Mod.instance_methods #=> ["method2"] * Mod.private_instance_methods #=> ["method1"] */ VALUE rb_class_private_instance_methods(argc, argv, mod) int argc; VALUE *argv; VALUE mod; { return class_instance_method_list(argc, argv, mod, ins_methods_priv_i); } /* * call-seq: * mod.public_instance_methods(include_super=true) => array * * Returns a list of the public instance methods defined in <i>mod</i>. * If the optional parameter is not <code>false</code>, the methods of * any ancestors are included. */ VALUE rb_class_public_instance_methods(argc, argv, mod) int argc; VALUE *argv; VALUE mod; { return class_instance_method_list(argc, argv, mod, ins_methods_pub_i); } /* * call-seq: * obj.singleton_methods(all=true) => array * * Returns an array of the names of singleton methods for <i>obj</i>. * If the optional <i>all</i> parameter is true, the list will include * methods in modules included in <i>obj</i>. * * module Other * def three() end * end * * class Single * def Single.four() end * end * * a = Single.new * * def a.one() * end * * class << a * include Other * def two() * end * end * * Single.singleton_methods #=> ["four"] * a.singleton_methods(false) #=> ["two", "one"] * a.singleton_methods #=> ["two", "one", "three"] */ VALUE rb_obj_singleton_methods(argc, argv, obj) int argc; VALUE *argv; VALUE obj; { VALUE recur, ary, klass; st_table *list; rb_scan_args(argc, argv, "01", &recur); if (argc == 0) { recur = Qtrue; } klass = CLASS_OF(obj); list = st_init_numtable(); if (klass && FL_TEST(klass, FL_SINGLETON)) { st_foreach(RCLASS(klass)->m_tbl, method_entry, (st_data_t)list); klass = RCLASS(klass)->super; } if (RTEST(recur)) { while (klass && (FL_TEST(klass, FL_SINGLETON) || TYPE(klass) == T_ICLASS)) { st_foreach(RCLASS(klass)->m_tbl, method_entry, (st_data_t)list); klass = RCLASS(klass)->super; } } ary = rb_ary_new(); st_foreach(list, ins_methods_i, ary); st_free_table(list); return ary; } void rb_define_method_id(klass, name, func, argc) VALUE klass; ID name; VALUE (*func)(); int argc; { rb_add_method(klass, name, NEW_CFUNC(func,argc), NOEX_PUBLIC); } void rb_define_method(klass, name, func, argc) VALUE klass; const char *name; VALUE (*func)(); int argc; { ID id = rb_intern(name); int ex = NOEX_PUBLIC; rb_add_method(klass, id, NEW_CFUNC(func, argc), ex); } void rb_define_protected_method(klass, name, func, argc) VALUE klass; const char *name; VALUE (*func)(); int argc; { rb_add_method(klass, rb_intern(name), NEW_CFUNC(func, argc), NOEX_PROTECTED); } void rb_define_private_method(klass, name, func, argc) VALUE klass; const char *name; VALUE (*func)(); int argc; { rb_add_method(klass, rb_intern(name), NEW_CFUNC(func, argc), NOEX_PRIVATE); } void rb_undef_method(klass, name) VALUE klass; const char *name; { rb_add_method(klass, rb_intern(name), 0, NOEX_UNDEF); } #define SPECIAL_SINGLETON(x,c) do {\ if (obj == (x)) {\ return c;\ }\ } while (0) VALUE rb_singleton_class(obj) VALUE obj; { VALUE klass; if (FIXNUM_P(obj) || SYMBOL_P(obj)) { rb_raise(rb_eTypeError, "can't define singleton"); } if (rb_special_const_p(obj)) { SPECIAL_SINGLETON(Qnil, rb_cNilClass); SPECIAL_SINGLETON(Qfalse, rb_cFalseClass); SPECIAL_SINGLETON(Qtrue, rb_cTrueClass); rb_bug("unknown immediate %ld", obj); } DEFER_INTS; if (FL_TEST(RBASIC(obj)->klass, FL_SINGLETON) && rb_iv_get(RBASIC(obj)->klass, "__attached__") == obj) { klass = RBASIC(obj)->klass; } else { klass = rb_make_metaclass(obj, RBASIC(obj)->klass); } if (OBJ_TAINTED(obj)) { OBJ_TAINT(klass); } else { FL_UNSET(klass, FL_TAINT); } if (OBJ_FROZEN(obj)) OBJ_FREEZE(klass); ALLOW_INTS; return klass; } void rb_define_singleton_method(obj, name, func, argc) VALUE obj; const char *name; VALUE (*func)(); int argc; { rb_define_method(rb_singleton_class(obj), name, func, argc); } void rb_define_module_function(module, name, func, argc) VALUE module; const char *name; VALUE (*func)(); int argc; { rb_define_private_method(module, name, func, argc); rb_define_singleton_method(module, name, func, argc); } void rb_define_global_function(name, func, argc) const char *name; VALUE (*func)(); int argc; { rb_define_module_function(rb_mKernel, name, func, argc); } void rb_define_alias(klass, name1, name2) VALUE klass; const char *name1, *name2; { rb_alias(klass, rb_intern(name1), rb_intern(name2)); } void rb_define_attr(klass, name, read, write) VALUE klass; const char *name; int read, write; { rb_attr(klass, rb_intern(name), read, write, Qfalse); } #ifdef HAVE_STDARG_PROTOTYPES #include <stdarg.h> #define va_init_list(a,b) va_start(a,b) #else #include <varargs.h> #define va_init_list(a,b) va_start(a) #endif int #ifdef HAVE_STDARG_PROTOTYPES rb_scan_args(int argc, const VALUE *argv, const char *fmt, ...) #else rb_scan_args(argc, argv, fmt, va_alist) int argc; const VALUE *argv; const char *fmt; va_dcl #endif { int n, i = 0; const char *p = fmt; VALUE *var; va_list vargs; va_init_list(vargs, fmt); if (*p == '*') goto rest_arg; if (ISDIGIT(*p)) { n = *p - '0'; if (n > argc) rb_raise(rb_eArgError, "wrong number of arguments (%d for %d)", argc, n); for (i=0; i<n; i++) { var = va_arg(vargs, VALUE*); if (var) *var = argv[i]; } p++; } else { goto error; } if (ISDIGIT(*p)) { n = i + *p - '0'; for (; i<n; i++) { var = va_arg(vargs, VALUE*); if (argc > i) { if (var) *var = argv[i]; } else { if (var) *var = Qnil; } } p++; } if(*p == '*') { rest_arg: var = va_arg(vargs, VALUE*); if (argc > i) { if (var) *var = rb_ary_new4(argc-i, argv+i); i = argc; } else { if (var) *var = rb_ary_new(); } p++; } if (*p == '&') { var = va_arg(vargs, VALUE*); if (rb_block_given_p()) { *var = rb_block_proc(); } else { *var = Qnil; } p++; } va_end(vargs); if (*p != '\0') { goto error; } if (argc > i) { rb_raise(rb_eArgError, "wrong number of arguments (%d for %d)", argc, i); } return argc; error: rb_fatal("bad scan arg format: %s", fmt); return 0; } /********************************************************************** compar.c - $Author: shyouhei $ $Date: 2007-02-13 00:01:19 +0100 (Tue, 13 Feb 2007) $ created at: Thu Aug 26 14:39:48 JST 1993 Copyright (C) 1993-2003 <NAME> **********************************************************************/ #include "ruby.h" VALUE rb_mComparable; static ID cmp; int rb_cmpint(val, a, b) VALUE val, a, b; { if (NIL_P(val)) { rb_cmperr(a, b); } if (FIXNUM_P(val)) return FIX2INT(val); if (TYPE(val) == T_BIGNUM) { if (RBIGNUM(val)->sign) return 1; return -1; } if (RTEST(rb_funcall(val, '>', 1, INT2FIX(0)))) return 1; if (RTEST(rb_funcall(val, '<', 1, INT2FIX(0)))) return -1; return 0; } void rb_cmperr(x, y) VALUE x, y; { const char *classname; if (SPECIAL_CONST_P(y)) { y = rb_inspect(y); classname = StringValuePtr(y); } else { classname = rb_obj_classname(y); } rb_raise(rb_eArgError, "comparison of %s with %s failed", rb_obj_classname(x), classname); } #define cmperr() (rb_cmperr(x, y), Qnil) static VALUE cmp_eq(a) VALUE *a; { VALUE c = rb_funcall(a[0], cmp, 1, a[1]); if (NIL_P(c)) return Qnil; if (rb_cmpint(c, a[0], a[1]) == 0) return Qtrue; return Qfalse; } static VALUE cmp_failed() { return Qnil; } /* * call-seq: * obj == other => true or false * * Compares two objects based on the receiver's <code><=></code> * method, returning true if it returns 0. Also returns true if * _obj_ and _other_ are the same object. */ static VALUE cmp_equal(x, y) VALUE x, y; { VALUE a[2]; if (x == y) return Qtrue; a[0] = x; a[1] = y; return rb_rescue(cmp_eq, (VALUE)a, cmp_failed, 0); } /* * call-seq: * obj > other => true or false * * Compares two objects based on the receiver's <code><=></code> * method, returning true if it returns 1. */ static VALUE cmp_gt(x, y) VALUE x, y; { VALUE c = rb_funcall(x, cmp, 1, y); if (NIL_P(c)) return cmperr(); if (rb_cmpint(c, x, y) > 0) return Qtrue; return Qfalse; } /* * call-seq: * obj >= other => true or false * * Compares two objects based on the receiver's <code><=></code> * method, returning true if it returns 0 or 1. */ static VALUE cmp_ge(x, y) VALUE x, y; { VALUE c = rb_funcall(x, cmp, 1, y); if (NIL_P(c)) return cmperr(); if (rb_cmpint(c, x, y) >= 0) return Qtrue; return Qfalse; } /* * call-seq: * obj < other => true or false * * Compares two objects based on the receiver's <code><=></code> * method, returning true if it returns -1. */ static VALUE cmp_lt(x, y) VALUE x, y; { VALUE c = rb_funcall(x, cmp, 1, y); if (NIL_P(c)) return cmperr(); if (rb_cmpint(c, x, y) < 0) return Qtrue; return Qfalse; } /* * call-seq: * obj <= other => true or false * * Compares two objects based on the receiver's <code><=></code> * method, returning true if it returns -1 or 0. */ static VALUE cmp_le(x, y) VALUE x, y; { VALUE c = rb_funcall(x, cmp, 1, y); if (NIL_P(c)) return cmperr(); if (rb_cmpint(c, x, y) <= 0) return Qtrue; return Qfalse; } /* * call-seq: * obj.between?(min, max) => true or false * * Returns <code>false</code> if <i>obj</i> <code><=></code> * <i>min</i> is less than zero or if <i>anObject</i> <code><=></code> * <i>max</i> is greater than zero, <code>true</code> otherwise. * * 3.between?(1, 5) #=> true * 6.between?(1, 5) #=> false * 'cat'.between?('ant', 'dog') #=> true * 'gnu'.between?('ant', 'dog') #=> false * */ static VALUE cmp_between(x, min, max) VALUE x, min, max; { if (RTEST(cmp_lt(x, min))) return Qfalse; if (RTEST(cmp_gt(x, max))) return Qfalse; return Qtrue; } /* * The <code>Comparable</code> mixin is used by classes whose objects * may be ordered. The class must define the <code><=></code> operator, * which compares the receiver against another object, returning -1, 0, * or +1 depending on whether the receiver is less than, equal to, or * greater than the other object. <code>Comparable</code> uses * <code><=></code> to implement the conventional comparison operators * (<code><</code>, <code><=</code>, <code>==</code>, <code>>=</code>, * and <code>></code>) and the method <code>between?</code>. * * class SizeMatters * include Comparable * attr :str * def <=>(anOther) * str.size <=> anOther.str.size * end * def initialize(str) * @str = str * end * def inspect * @str * end * end * * s1 = SizeMatters.new("Z") * s2 = SizeMatters.new("YY") * s3 = SizeMatters.new("XXX") * s4 = SizeMatters.new("WWWW") * s5 = SizeMatters.new("VVVVV") * * s1 < s2 #=> true * s4.between?(s1, s3) #=> false * s4.between?(s3, s5) #=> true * [ s3, s2, s5, s4, s1 ].sort #=> [Z, YY, XXX, WWWW, VVVVV] * */ void Init_Comparable() { rb_mComparable = rb_define_module("Comparable"); rb_define_method(rb_mComparable, "==", cmp_equal, 1); rb_define_method(rb_mComparable, ">", cmp_gt, 1); rb_define_method(rb_mComparable, ">=", cmp_ge, 1); rb_define_method(rb_mComparable, "<", cmp_lt, 1); rb_define_method(rb_mComparable, "<=", cmp_le, 1); rb_define_method(rb_mComparable, "between?", cmp_between, 2); cmp = rb_intern("<=>"); } /********************************************************************** dir.c - $Author: shyouhei $ $Date: 2009-02-04 06:26:31 +0100 (Wed, 04 Feb 2009) $ created at: Wed Jan 5 09:51:01 JST 1994 Copyright (C) 1993-2003 <NAME> Copyright (C) 2000 Network Applied Communication Laboratory, Inc. Copyright (C) 2000 Information-technology Promotion Agency, Japan **********************************************************************/ #include "ruby.h" #include <sys/types.h> #include <sys/stat.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #if defined HAVE_DIRENT_H && !defined _WIN32 # include <dirent.h> # define NAMLEN(dirent) strlen((dirent)->d_name) #elif defined HAVE_DIRECT_H && !defined _WIN32 # include <direct.h> # define NAMLEN(dirent) strlen((dirent)->d_name) #else # define dirent direct # if !defined __NeXT__ # define NAMLEN(dirent) (dirent)->d_namlen # else # /* On some versions of NextStep, d_namlen is always zero, so avoid it. */ # define NAMLEN(dirent) strlen((dirent)->d_name) # endif # if HAVE_SYS_NDIR_H # include <sys/ndir.h> # endif # if HAVE_SYS_DIR_H # include <sys/dir.h> # endif # if HAVE_NDIR_H # include <ndir.h> # endif # ifdef _WIN32 # include "win32/dir.h" # endif #endif #include <errno.h> #ifndef HAVE_STDLIB_H char *getenv(); #endif #ifndef HAVE_STRING_H char *strchr _((char*,char)); #endif #include <ctype.h> #include "util.h" #if !defined HAVE_LSTAT && !defined lstat #define lstat stat #endif #ifndef CASEFOLD_FILESYSTEM # if defined DOSISH || defined __VMS # define CASEFOLD_FILESYSTEM 1 # else # define CASEFOLD_FILESYSTEM 0 # endif #endif #define FNM_NOESCAPE 0x01 #define FNM_PATHNAME 0x02 #define FNM_DOTMATCH 0x04 #define FNM_CASEFOLD 0x08 #if CASEFOLD_FILESYSTEM #define FNM_SYSCASE FNM_CASEFOLD #else #define FNM_SYSCASE 0 #endif #define FNM_NOMATCH 1 #define FNM_ERROR 2 #define downcase(c) (nocase && ISUPPER(c) ? tolower(c) : (c)) #define compare(c1, c2) (((unsigned char)(c1)) - ((unsigned char)(c2))) /* caution: in case *p == '\0' Next(p) == p + 1 in single byte environment Next(p) == p in multi byte environment */ #if defined(CharNext) # define Next(p) CharNext(p) #elif defined(DJGPP) # define Next(p) ((p) + mblen(p, RUBY_MBCHAR_MAXSIZE)) #elif defined(__EMX__) # define Next(p) ((p) + emx_mblen(p)) static inline int emx_mblen(const char *p) { int n = mblen(p, RUBY_MBCHAR_MAXSIZE); return (n < 0) ? 1 : n; } #endif #ifndef Next /* single byte environment */ # define Next(p) ((p) + 1) # define Inc(p) (++(p)) # define Compare(p1, p2) (compare(downcase(*(p1)), downcase(*(p2)))) #else /* multi byte environment */ # define Inc(p) ((p) = Next(p)) # define Compare(p1, p2) (CompareImpl(p1, p2, nocase)) static int CompareImpl(const char *p1, const char *p2, int nocase) { const int len1 = Next(p1) - p1; const int len2 = Next(p2) - p2; #ifdef _WIN32 char buf1[10], buf2[10]; /* large enough? */ #endif if (len1 < 0 || len2 < 0) { rb_fatal("CompareImpl: negative len"); } if (len1 == 0) return len2; if (len2 == 0) return -len1; #ifdef _WIN32 if (nocase && rb_w32_iswinnt()) { if (len1 > 1) { if (len1 >= sizeof(buf1)) { rb_fatal("CompareImpl: too large len"); } memcpy(buf1, p1, len1); buf1[len1] = '\0'; CharLower(buf1); p1 = buf1; /* trick */ } if (len2 > 1) { if (len2 >= sizeof(buf2)) { rb_fatal("CompareImpl: too large len"); } memcpy(buf2, p2, len2); buf2[len2] = '\0'; CharLower(buf2); p2 = buf2; /* trick */ } } #endif if (len1 == 1) if (len2 == 1) return compare(downcase(*p1), downcase(*p2)); else { const int ret = compare(downcase(*p1), *p2); return ret ? ret : -1; } else if (len2 == 1) { const int ret = compare(*p1, downcase(*p2)); return ret ? ret : 1; } else { const int ret = memcmp(p1, p2, len1 < len2 ? len1 : len2); return ret ? ret : len1 - len2; } } #endif /* environment */ static char * bracket(p, s, flags) const char *p; /* pattern (next to '[') */ const char *s; /* string */ int flags; { const int nocase = flags & FNM_CASEFOLD; const int escape = !(flags & FNM_NOESCAPE); int ok = 0, not = 0; if (*p == '!' || *p == '^') { not = 1; p++; } while (*p != ']') { const char *t1 = p; if (escape && *t1 == '\\') t1++; if (!*t1) return NULL; p = Next(t1); if (p[0] == '-' && p[1] != ']') { const char *t2 = p + 1; if (escape && *t2 == '\\') t2++; if (!*t2) return NULL; p = Next(t2); if (!ok && Compare(t1, s) <= 0 && Compare(s, t2) <= 0) ok = 1; } else if (!ok && Compare(t1, s) == 0) ok = 1; } return ok == not ? NULL : (char *)p + 1; } /* If FNM_PATHNAME is set, only path element will be matched. (upto '/' or '\0') Otherwise, entire string will be matched. End marker itself won't be compared. And if function succeeds, *pcur reaches end marker. */ #define UNESCAPE(p) (escape && *(p) == '\\' ? (p) + 1 : (p)) #define ISEND(p) (!*(p) || (pathname && *(p) == '/')) #define RETURN(val) return *pcur = p, *scur = s, (val); static int fnmatch_helper(pcur, scur, flags) const char **pcur; /* pattern */ const char **scur; /* string */ int flags; { const int period = !(flags & FNM_DOTMATCH); const int pathname = flags & FNM_PATHNAME; const int escape = !(flags & FNM_NOESCAPE); const int nocase = flags & FNM_CASEFOLD; const char *ptmp = 0; const char *stmp = 0; const char *p = *pcur; const char *s = *scur; if (period && *s == '.' && *UNESCAPE(p) != '.') /* leading period */ RETURN(FNM_NOMATCH); while (1) { switch (*p) { case '*': do { p++; } while (*p == '*'); if (ISEND(UNESCAPE(p))) { p = UNESCAPE(p); RETURN(0); } if (ISEND(s)) RETURN(FNM_NOMATCH); ptmp = p; stmp = s; continue; case '?': if (ISEND(s)) RETURN(FNM_NOMATCH); p++; Inc(s); continue; case '[': { const char *t; if (ISEND(s)) RETURN(FNM_NOMATCH); if (t = bracket(p + 1, s, flags)) { p = t; Inc(s); continue; } goto failed; } } /* ordinary */ p = UNESCAPE(p); if (ISEND(s)) RETURN(ISEND(p) ? 0 : FNM_NOMATCH); if (ISEND(p)) goto failed; if (Compare(p, s) != 0) goto failed; Inc(p); Inc(s); continue; failed: /* try next '*' position */ if (ptmp && stmp) { p = ptmp; Inc(stmp); /* !ISEND(*stmp) */ s = stmp; continue; } RETURN(FNM_NOMATCH); } } static int fnmatch(p, s, flags) const char *p; /* pattern */ const char *s; /* string */ int flags; { const int period = !(flags & FNM_DOTMATCH); const int pathname = flags & FNM_PATHNAME; const char *ptmp = 0; const char *stmp = 0; if (pathname) { while (1) { if (p[0] == '*' && p[1] == '*' && p[2] == '/') { do { p += 3; } while (p[0] == '*' && p[1] == '*' && p[2] == '/'); ptmp = p; stmp = s; } if (fnmatch_helper(&p, &s, flags) == 0) { while (*s && *s != '/') Inc(s); if (*p && *s) { p++; s++; continue; } if (!*p && !*s) return 0; } /* failed : try next recursion */ if (ptmp && stmp && !(period && *stmp == '.')) { while (*stmp && *stmp != '/') Inc(stmp); if (*stmp) { p = ptmp; stmp++; s = stmp; continue; } } return FNM_NOMATCH; } } else return fnmatch_helper(&p, &s, flags); } VALUE rb_cDir; struct dir_data { DIR *dir; char *path; }; static void free_dir(dir) struct dir_data *dir; { if (dir) { if (dir->dir) closedir(dir->dir); if (dir->path) free(dir->path); } free(dir); } static VALUE dir_close _((VALUE)); static VALUE dir_s_alloc _((VALUE)); static VALUE dir_s_alloc(klass) VALUE klass; { struct dir_data *dirp; VALUE obj = Data_Make_Struct(klass, struct dir_data, 0, free_dir, dirp); dirp->dir = NULL; dirp->path = NULL; return obj; } /* * call-seq: * Dir.new( string ) -> aDir * * Returns a new directory object for the named directory. */ static VALUE dir_initialize(dir, dirname) VALUE dir, dirname; { struct dir_data *dp; SafeStringValue(dirname); Data_Get_Struct(dir, struct dir_data, dp); if (dp->dir) closedir(dp->dir); if (dp->path) free(dp->path); dp->dir = NULL; dp->path = NULL; dp->dir = opendir(RSTRING(dirname)->ptr); if (dp->dir == NULL) { if (errno == EMFILE || errno == ENFILE) { rb_gc(); dp->dir = opendir(RSTRING(dirname)->ptr); } if (dp->dir == NULL) { rb_sys_fail(RSTRING(dirname)->ptr); } } dp->path = strdup(RSTRING(dirname)->ptr); return dir; } /* * call-seq: * Dir.open( string ) => aDir * Dir.open( string ) {| aDir | block } => anObject * * With no block, <code>open</code> is a synonym for * <code>Dir::new</code>. If a block is present, it is passed * <i>aDir</i> as a parameter. The directory is closed at the end of * the block, and <code>Dir::open</code> returns the value of the * block. */ static VALUE dir_s_open(klass, dirname) VALUE klass, dirname; { struct dir_data *dp; VALUE dir = Data_Make_Struct(klass, struct dir_data, 0, free_dir, dp); dir_initialize(dir, dirname); if (rb_block_given_p()) { return rb_ensure(rb_yield, dir, dir_close, dir); } return dir; } static void dir_closed() { rb_raise(rb_eIOError, "closed directory"); } static void dir_check(dir) VALUE dir; { if (!OBJ_TAINTED(dir) && rb_safe_level() >= 4) rb_raise(rb_eSecurityError, "Insecure: operation on untainted Dir"); rb_check_frozen(dir); } #define GetDIR(obj, dirp) do {\ dir_check(dir);\ Data_Get_Struct(obj, struct dir_data, dirp);\ if (dirp->dir == NULL) dir_closed();\ } while (0) /* * call-seq: * dir.inspect => string * * Return a string describing this Dir object. */ static VALUE dir_inspect(dir) VALUE dir; { struct dir_data *dirp; GetDIR(dir, dirp); if (dirp->path) { char *c = rb_obj_classname(dir); int len = strlen(c) + strlen(dirp->path) + 4; VALUE s = rb_str_new(0, len); snprintf(RSTRING_PTR(s), len+1, "#<%s:%s>", c, dirp->path); return s; } return rb_funcall(dir, rb_intern("to_s"), 0, 0); } /* * call-seq: * dir.path => string or nil * * Returns the path parameter passed to <em>dir</em>'s constructor. * * d = Dir.new("..") * d.path #=> ".." */ static VALUE dir_path(dir) VALUE dir; { struct dir_data *dirp; GetDIR(dir, dirp); if (!dirp->path) return Qnil; return rb_str_new2(dirp->path); } /* * call-seq: * dir.read => string or nil * * Reads the next entry from <em>dir</em> and returns it as a string. * Returns <code>nil</code> at the end of the stream. * * d = Dir.new("testdir") * d.read #=> "." * d.read #=> ".." * d.read #=> "config.h" */ static VALUE dir_read(dir) VALUE dir; { struct dir_data *dirp; struct dirent *dp; GetDIR(dir, dirp); errno = 0; dp = readdir(dirp->dir); if (dp) { return rb_tainted_str_new(dp->d_name, NAMLEN(dp)); } else if (errno == 0) { /* end of stream */ return Qnil; } else { rb_sys_fail(0); } return Qnil; /* not reached */ } /* * call-seq: * dir.each { |filename| block } => dir * * Calls the block once for each entry in this directory, passing the * filename of each entry as a parameter to the block. * * d = Dir.new("testdir") * d.each {|x| puts "Got #{x}" } * * <em>produces:</em> * * Got . * Got .. * Got config.h * Got main.rb */ static VALUE dir_each(dir) VALUE dir; { struct dir_data *dirp; struct dirent *dp; GetDIR(dir, dirp); rewinddir(dirp->dir); for (dp = readdir(dirp->dir); dp != NULL; dp = readdir(dirp->dir)) { rb_yield(rb_tainted_str_new(dp->d_name, NAMLEN(dp))); if (dirp->dir == NULL) dir_closed(); } return dir; } /* * call-seq: * dir.pos => integer * dir.tell => integer * * Returns the current position in <em>dir</em>. See also * <code>Dir#seek</code>. * * d = Dir.new("testdir") * d.tell #=> 0 * d.read #=> "." * d.tell #=> 12 */ static VALUE dir_tell(dir) VALUE dir; { #ifdef HAVE_TELLDIR struct dir_data *dirp; long pos; GetDIR(dir, dirp); pos = telldir(dirp->dir); return rb_int2inum(pos); #else rb_notimplement(); #endif } /* * call-seq: * dir.seek( integer ) => dir * * Seeks to a particular location in <em>dir</em>. <i>integer</i> * must be a value returned by <code>Dir#tell</code>. * * d = Dir.new("testdir") #=> #<Dir:0x401b3c40> * d.read #=> "." * i = d.tell #=> 12 * d.read #=> ".." * d.seek(i) #=> #<Dir:0x401b3c40> * d.read #=> ".." */ static VALUE dir_seek(dir, pos) VALUE dir, pos; { struct dir_data *dirp; off_t p = NUM2OFFT(pos); GetDIR(dir, dirp); #ifdef HAVE_SEEKDIR seekdir(dirp->dir, p); return dir; #else rb_notimplement(); #endif } /* * call-seq: * dir.pos( integer ) => integer * * Synonym for <code>Dir#seek</code>, but returns the position * parameter. * * d = Dir.new("testdir") #=> #<Dir:0x401b3c40> * d.read #=> "." * i = d.pos #=> 12 * d.read #=> ".." * d.pos = i #=> 12 * d.read #=> ".." */ static VALUE dir_set_pos(dir, pos) VALUE dir, pos; { dir_seek(dir, pos); return pos; } /* * call-seq: * dir.rewind => dir * * Repositions <em>dir</em> to the first entry. * * d = Dir.new("testdir") * d.read #=> "." * d.rewind #=> #<Dir:0x401b3fb0> * d.read #=> "." */ static VALUE dir_rewind(dir) VALUE dir; { struct dir_data *dirp; if (rb_safe_level() >= 4 && !OBJ_TAINTED(dir)) { rb_raise(rb_eSecurityError, "Insecure: can't close"); } GetDIR(dir, dirp); rewinddir(dirp->dir); return dir; } /* * call-seq: * dir.close => nil * * Closes the directory stream. Any further attempts to access * <em>dir</em> will raise an <code>IOError</code>. * * d = Dir.new("testdir") * d.close #=> nil */ static VALUE dir_close(dir) VALUE dir; { struct dir_data *dirp; GetDIR(dir, dirp); closedir(dirp->dir); dirp->dir = NULL; return Qnil; } static void dir_chdir(path) VALUE path; { if (chdir(RSTRING(path)->ptr) < 0) rb_sys_fail(RSTRING(path)->ptr); } static int chdir_blocking = 0; static VALUE chdir_thread = Qnil; struct chdir_data { VALUE old_path, new_path; int done; }; static VALUE chdir_yield(args) struct chdir_data *args; { dir_chdir(args->new_path); args->done = Qtrue; chdir_blocking++; if (chdir_thread == Qnil) chdir_thread = rb_thread_current(); return rb_yield(args->new_path); } static VALUE chdir_restore(args) struct chdir_data *args; { if (args->done) { chdir_blocking--; if (chdir_blocking == 0) chdir_thread = Qnil; dir_chdir(args->old_path); } return Qnil; } /* * call-seq: * Dir.chdir( [ string] ) => 0 * Dir.chdir( [ string] ) {| path | block } => anObject * * Changes the current working directory of the process to the given * string. When called without an argument, changes the directory to * the value of the environment variable <code>HOME</code>, or * <code>LOGDIR</code>. <code>SystemCallError</code> (probably * <code>Errno::ENOENT</code>) if the target directory does not exist. * * If a block is given, it is passed the name of the new current * directory, and the block is executed with that as the current * directory. The original working directory is restored when the block * exits. The return value of <code>chdir</code> is the value of the * block. <code>chdir</code> blocks can be nested, but in a * multi-threaded program an error will be raised if a thread attempts * to open a <code>chdir</code> block while another thread has one * open. * * Dir.chdir("/var/spool/mail") * puts Dir.pwd * Dir.chdir("/tmp") do * puts Dir.pwd * Dir.chdir("/usr") do * puts Dir.pwd * end * puts Dir.pwd * end * puts Dir.pwd * * <em>produces:</em> * * /var/spool/mail * /tmp * /usr * /tmp * /var/spool/mail */ static VALUE dir_s_chdir(argc, argv, obj) int argc; VALUE *argv; VALUE obj; { VALUE path = Qnil; rb_secure(2); if (rb_scan_args(argc, argv, "01", &path) == 1) { SafeStringValue(path); } else { const char *dist = getenv("HOME"); if (!dist) { dist = getenv("LOGDIR"); if (!dist) rb_raise(rb_eArgError, "HOME/LOGDIR not set"); } path = rb_str_new2(dist); } if (chdir_blocking > 0) { if (!rb_block_given_p() || rb_thread_current() != chdir_thread) rb_warn("conflicting chdir during another chdir block"); } if (rb_block_given_p()) { struct chdir_data args; char *cwd = my_getcwd(); args.old_path = rb_tainted_str_new2(cwd); free(cwd); args.new_path = path; args.done = Qfalse; return rb_ensure(chdir_yield, (VALUE)&args, chdir_restore, (VALUE)&args); } dir_chdir(path); return INT2FIX(0); } /* * call-seq: * Dir.getwd => string * Dir.pwd => string * * Returns the path to the current working directory of this process as * a string. * * Dir.chdir("/tmp") #=> 0 * Dir.getwd #=> "/tmp" */ static VALUE dir_s_getwd(dir) VALUE dir; { char *path; VALUE cwd; rb_secure(4); path = my_getcwd(); cwd = rb_tainted_str_new2(path); free(path); return cwd; } static void check_dirname _((volatile VALUE *)); static void check_dirname(dir) volatile VALUE *dir; { char *path, *pend; SafeStringValue(*dir); rb_secure(2); path = RSTRING(*dir)->ptr; if (path && *(pend = rb_path_end(rb_path_skip_prefix(path)))) { *dir = rb_str_new(path, pend - path); } } /* * call-seq: * Dir.chroot( string ) => 0 * * Changes this process's idea of the file system root. Only a * privileged process may make this call. Not available on all * platforms. On Unix systems, see <code>chroot(2)</code> for more * information. */ static VALUE dir_s_chroot(dir, path) VALUE dir, path; { #if defined(HAVE_CHROOT) && !defined(__CHECKER__) check_dirname(&path); if (chroot(RSTRING(path)->ptr) == -1) rb_sys_fail(RSTRING(path)->ptr); return INT2FIX(0); #else rb_notimplement(); return Qnil; /* not reached */ #endif } /* * call-seq: * Dir.mkdir( string [, integer] ) => 0 * * Makes a new directory named by <i>string</i>, with permissions * specified by the optional parameter <i>anInteger</i>. The * permissions may be modified by the value of * <code>File::umask</code>, and are ignored on NT. Raises a * <code>SystemCallError</code> if the directory cannot be created. See * also the discussion of permissions in the class documentation for * <code>File</code>. * */ static VALUE dir_s_mkdir(argc, argv, obj) int argc; VALUE *argv; VALUE obj; { VALUE path, vmode; int mode; if (rb_scan_args(argc, argv, "11", &path, &vmode) == 2) { mode = NUM2INT(vmode); } else { mode = 0777; } check_dirname(&path); if (mkdir(RSTRING(path)->ptr, mode) == -1) rb_sys_fail(RSTRING(path)->ptr); return INT2FIX(0); } /* * call-seq: * Dir.delete( string ) => 0 * Dir.rmdir( string ) => 0 * Dir.unlink( string ) => 0 * * Deletes the named directory. Raises a subclass of * <code>SystemCallError</code> if the directory isn't empty. */ static VALUE dir_s_rmdir(obj, dir) VALUE obj, dir; { check_dirname(&dir); if (rmdir(RSTRING(dir)->ptr) < 0) rb_sys_fail(RSTRING(dir)->ptr); return INT2FIX(0); } static void sys_warning_1(mesg) const char* mesg; { rb_sys_warning("%s", mesg); } #define GLOB_VERBOSE (1UL << (sizeof(int) * CHAR_BIT - 1)) #define sys_warning(val) \ (void)((flags & GLOB_VERBOSE) && rb_protect((VALUE (*)_((VALUE)))sys_warning_1, (VALUE)(val), 0)) #define GLOB_ALLOC(type) (type *)malloc(sizeof(type)) #define GLOB_ALLOC_N(type, n) (type *)malloc(sizeof(type) * (n)) #define GLOB_JUMP_TAG(status) ((status == -1) ? rb_memerror() : rb_jump_tag(status)) /* * ENOTDIR can be returned by stat(2) if a non-leaf element of the path * is not a directory. */ #define to_be_ignored(e) ((e) == ENOENT || (e) == ENOTDIR) /* System call with warning */ static int do_stat(const char *path, struct stat *pst, int flags) { int ret = stat(path, pst); if (ret < 0 && !to_be_ignored(errno)) sys_warning(path); return ret; } static int do_lstat(const char *path, struct stat *pst, int flags) { int ret = lstat(path, pst); if (ret < 0 && !to_be_ignored(errno)) sys_warning(path); return ret; } static DIR * do_opendir(const char *path, int flags) { DIR *dirp = opendir(path); if (dirp == NULL && !to_be_ignored(errno)) sys_warning(path); return dirp; } /* Return nonzero if S has any special globbing chars in it. */ static int has_magic(s, flags) const char *s; int flags; { const int escape = !(flags & FNM_NOESCAPE); const int nocase = flags & FNM_CASEFOLD; register const char *p = s; register char c; while (c = *p++) { switch (c) { case '*': case '?': case '[': return 1; case '\\': if (escape && !(c = *p++)) return 0; continue; default: if (!FNM_SYSCASE && ISALPHA(c) && nocase) return 1; } p = Next(p-1); } return 0; } /* Find separator in globbing pattern. */ static char * find_dirsep(const char *s, int flags) { const int escape = !(flags & FNM_NOESCAPE); register const char *p = s; register char c; int open = 0; while (c = *p++) { switch (c) { case '[': open = 1; continue; case ']': open = 0; continue; case '/': if (!open) return (char *)p-1; continue; case '\\': if (escape && !(c = *p++)) return (char *)p-1; continue; } p = Next(p-1); } return (char *)p-1; } /* Remove escaping backslashes */ static void remove_backslashes(p) char *p; { char *t = p; char *s = p; while (*p) { if (*p == '\\') { if (t != s) memmove(t, s, p - s); t += p - s; s = ++p; if (!*p) break; } Inc(p); } while (*p++); if (t != s) memmove(t, s, p - s); /* move '\0' too */ } /* Globing pattern */ enum glob_pattern_type { PLAIN, MAGICAL, RECURSIVE, MATCH_ALL, MATCH_DIR }; struct glob_pattern { char *str; enum glob_pattern_type type; struct glob_pattern *next; }; static void glob_free_pattern(struct glob_pattern *list); static struct glob_pattern * glob_make_pattern(const char *p, int flags) { struct glob_pattern *list, *tmp, **tail = &list; int dirsep = 0; /* pattern is terminated with '/' */ while (*p) { tmp = GLOB_ALLOC(struct glob_pattern); if (!tmp) goto error; if (p[0] == '*' && p[1] == '*' && p[2] == '/') { /* fold continuous RECURSIVEs (needed in glob_helper) */ do { p += 3; } while (p[0] == '*' && p[1] == '*' && p[2] == '/'); tmp->type = RECURSIVE; tmp->str = 0; dirsep = 1; } else { const char *m = find_dirsep(p, flags); char *buf = GLOB_ALLOC_N(char, m-p+1); if (!buf) { free(tmp); goto error; } memcpy(buf, p, m-p); buf[m-p] = '\0'; tmp->type = has_magic(buf, flags) ? MAGICAL : PLAIN; tmp->str = buf; if (*m) { dirsep = 1; p = m + 1; } else { dirsep = 0; p = m; } } *tail = tmp; tail = &tmp->next; } tmp = GLOB_ALLOC(struct glob_pattern); if (!tmp) { error: *tail = 0; glob_free_pattern(list); return 0; } tmp->type = dirsep ? MATCH_DIR : MATCH_ALL; tmp->str = 0; *tail = tmp; tmp->next = 0; return list; } static void glob_free_pattern(struct glob_pattern *list) { while (list) { struct glob_pattern *tmp = list; list = list->next; if (tmp->str) free(tmp->str); free(tmp); } } static char * join_path(const char *path, int dirsep, const char *name) { long len = strlen(path); char *buf = GLOB_ALLOC_N(char, len+strlen(name)+(dirsep?1:0)+1); if (!buf) return 0; memcpy(buf, path, len); if (dirsep) { strcpy(buf+len, "/"); len++; } strcpy(buf+len, name); return buf; } enum answer { YES, NO, UNKNOWN }; #ifndef S_ISLNK # ifndef S_IFLNK # define S_ISLNK(m) (0) # else # define S_ISLNK(m) ((m & S_IFMT) == S_IFLNK) # endif #endif #ifndef S_ISDIR # define S_ISDIR(m) ((m & S_IFMT) == S_IFDIR) #endif struct glob_args { void (*func) _((const char*, VALUE)); const char *c; VALUE v; }; static VALUE glob_func_caller _((VALUE)); static VALUE glob_func_caller(val) VALUE val; { struct glob_args *args = (struct glob_args *)val; (*args->func)(args->c, args->v); return Qnil; } #define glob_call_func(func, path, arg) (*func)(path, arg) static int glob_helper _((const char *, int, enum answer, enum answer, struct glob_pattern **, struct glob_pattern **, int, ruby_glob_func *, VALUE)); static int glob_helper(path, dirsep, exist, isdir, beg, end, flags, func, arg) const char *path; int dirsep; /* '/' should be placed before appending child entry's name to 'path'. */ enum answer exist; /* Does 'path' indicate an existing entry? */ enum answer isdir; /* Does 'path' indicate a directory or a symlink to a directory? */ struct glob_pattern **beg; struct glob_pattern **end; int flags; ruby_glob_func *func; VALUE arg; { struct stat st; int status = 0; struct glob_pattern **cur, **new_beg, **new_end; int plain = 0, magical = 0, recursive = 0, match_all = 0, match_dir = 0; int escape = !(flags & FNM_NOESCAPE); for (cur = beg; cur < end; ++cur) { struct glob_pattern *p = *cur; if (p->type == RECURSIVE) { recursive = 1; p = p->next; } switch (p->type) { case PLAIN: plain = 1; break; case MAGICAL: magical = 1; break; case MATCH_ALL: match_all = 1; break; case MATCH_DIR: match_dir = 1; break; case RECURSIVE: rb_bug("continuous RECURSIVEs"); } } if (*path) { if (match_all && exist == UNKNOWN) { if (do_lstat(path, &st, flags) == 0) { exist = YES; isdir = S_ISDIR(st.st_mode) ? YES : S_ISLNK(st.st_mode) ? UNKNOWN : NO; } else { exist = NO; isdir = NO; } } if (match_dir && isdir == UNKNOWN) { if (do_stat(path, &st, flags) == 0) { exist = YES; isdir = S_ISDIR(st.st_mode) ? YES : NO; } else { exist = NO; isdir = NO; } } if (match_all && exist == YES) { status = glob_call_func(func, path, arg); if (status) return status; } if (match_dir && isdir == YES) { char *tmp = join_path(path, dirsep, ""); if (!tmp) return -1; status = glob_call_func(func, tmp, arg); free(tmp); if (status) return status; } } if (exist == NO || isdir == NO) return 0; if (magical || recursive) { struct dirent *dp; DIR *dirp = do_opendir(*path ? path : ".", flags); if (dirp == NULL) return 0; for (dp = readdir(dirp); dp != NULL; dp = readdir(dirp)) { char *buf = join_path(path, dirsep, dp->d_name); enum answer new_isdir = UNKNOWN; if (!buf) { status = -1; break; } if (recursive && strcmp(dp->d_name, ".") != 0 && strcmp(dp->d_name, "..") != 0 && fnmatch("*", dp->d_name, flags) == 0) { #ifndef _WIN32 if (do_lstat(buf, &st, flags) == 0) new_isdir = S_ISDIR(st.st_mode) ? YES : S_ISLNK(st.st_mode) ? UNKNOWN : NO; else new_isdir = NO; #else new_isdir = dp->d_isdir ? (!dp->d_isrep ? YES : UNKNOWN) : NO; #endif } new_beg = new_end = GLOB_ALLOC_N(struct glob_pattern *, (end - beg) * 2); if (!new_beg) { status = -1; break; } for (cur = beg; cur < end; ++cur) { struct glob_pattern *p = *cur; if (p->type == RECURSIVE) { if (new_isdir == YES) /* not symlink but real directory */ *new_end++ = p; /* append recursive pattern */ p = p->next; /* 0 times recursion */ } if (p->type == PLAIN || p->type == MAGICAL) { if (fnmatch(p->str, dp->d_name, flags) == 0) *new_end++ = p->next; } } status = glob_helper(buf, 1, YES, new_isdir, new_beg, new_end, flags, func, arg); free(buf); free(new_beg); if (status) break; } closedir(dirp); } else if (plain) { struct glob_pattern **copy_beg, **copy_end, **cur2; copy_beg = copy_end = GLOB_ALLOC_N(struct glob_pattern *, end - beg); if (!copy_beg) return -1; for (cur = beg; cur < end; ++cur) *copy_end++ = (*cur)->type == PLAIN ? *cur : 0; for (cur = copy_beg; cur < copy_end; ++cur) { if (*cur) { char *buf; char *name; name = GLOB_ALLOC_N(char, strlen((*cur)->str) + 1); if (!name) { status = -1; break; } strcpy(name, (*cur)->str); if (escape) remove_backslashes(name); new_beg = new_end = GLOB_ALLOC_N(struct glob_pattern *, end - beg); if (!new_beg) { free(name); status = -1; break; } *new_end++ = (*cur)->next; for (cur2 = cur + 1; cur2 < copy_end; ++cur2) { if (*cur2 && fnmatch((*cur2)->str, name, flags) == 0) { *new_end++ = (*cur2)->next; *cur2 = 0; } } buf = join_path(path, dirsep, name); free(name); if (!buf) { free(new_beg); status = -1; break; } status = glob_helper(buf, 1, UNKNOWN, UNKNOWN, new_beg, new_end, flags, func, arg); free(buf); free(new_beg); if (status) break; } } free(copy_beg); } return status; } static int ruby_glob0(path, flags, func, arg) const char *path; int flags; ruby_glob_func *func; VALUE arg; { struct glob_pattern *list; const char *root, *start; char *buf; int n; int status; start = root = path; flags |= FNM_SYSCASE; #if defined DOSISH root = rb_path_skip_prefix(root); #endif if (root && *root == '/') root++; n = root - start; buf = GLOB_ALLOC_N(char, n + 1); if (!buf) return -1; MEMCPY(buf, start, char, n); buf[n] = '\0'; list = glob_make_pattern(root, flags); if (!list) { free(buf); return -1; } status = glob_helper(buf, 0, UNKNOWN, UNKNOWN, &list, &list + 1, flags, func, arg); glob_free_pattern(list); free(buf); return status; } int ruby_glob(path, flags, func, arg) const char *path; int flags; ruby_glob_func *func; VALUE arg; { return ruby_glob0(path, flags & ~GLOB_VERBOSE, func, arg); } static int rb_glob_caller _((const char *, VALUE)); static int rb_glob_caller(path, a) const char *path; VALUE a; { int status; struct glob_args *args = (struct glob_args *)a; args->c = path; rb_protect(glob_func_caller, a, &status); return status; } static int rb_glob2(path, flags, func, arg) const char *path; int flags; void (*func) _((const char *, VALUE)); VALUE arg; { struct glob_args args; args.func = func; args.v = arg; if (flags & FNM_SYSCASE) { rb_warning("Dir.glob() ignores File::FNM_CASEFOLD"); } return ruby_glob0(path, flags | GLOB_VERBOSE, rb_glob_caller, (VALUE)&args); } void rb_glob(path, func, arg) const char *path; void (*func) _((const char*, VALUE)); VALUE arg; { int status = rb_glob2(path, 0, func, arg); if (status) GLOB_JUMP_TAG(status); } static void push_pattern _((const char* path, VALUE ary)); static void push_pattern(path, ary) const char *path; VALUE ary; { rb_ary_push(ary, rb_tainted_str_new2(path)); } int ruby_brace_expand(str, flags, func, arg) const char *str; int flags; ruby_glob_func *func; VALUE arg; { const int escape = !(flags & FNM_NOESCAPE); const char *p = str; const char *s = p; const char *lbrace = 0, *rbrace = 0; int nest = 0, status = 0; while (*p) { if (*p == '{' && nest++ == 0) { lbrace = p; } if (*p == '}' && --nest <= 0) { rbrace = p; break; } if (*p == '\\' && escape) { if (!*++p) break; } Inc(p); } if (lbrace && rbrace) { char *buf = GLOB_ALLOC_N(char, strlen(s) + 1); long shift; if (!buf) return -1; memcpy(buf, s, lbrace-s); shift = (lbrace-s); p = lbrace; while (p < rbrace) { const char *t = ++p; nest = 0; while (p < rbrace && !(*p == ',' && nest == 0)) { if (*p == '{') nest++; if (*p == '}') nest--; if (*p == '\\' && escape) { if (++p == rbrace) break; } Inc(p); } memcpy(buf+shift, t, p-t); strcpy(buf+shift+(p-t), rbrace+1); status = ruby_brace_expand(buf, flags, func, arg); if (status) break; } free(buf); } else if (!lbrace && !rbrace) { status = (*func)(s, arg); } return status; } struct brace_args { ruby_glob_func *func; VALUE value; int flags; }; static int glob_brace _((const char *, VALUE)); static int glob_brace(path, val) const char *path; VALUE val; { struct brace_args *arg = (struct brace_args *)val; return ruby_glob0(path, arg->flags, arg->func, arg->value); } static int ruby_brace_glob0(str, flags, func, arg) const char *str; int flags; ruby_glob_func *func; VALUE arg; { struct brace_args args; args.func = func; args.value = arg; args.flags = flags; return ruby_brace_expand(str, flags, glob_brace, (VALUE)&args); } int ruby_brace_glob(str, flags, func, arg) const char *str; int flags; ruby_glob_func *func; VALUE arg; { return ruby_brace_glob0(str, flags & ~GLOB_VERBOSE, func, arg); } static int push_glob(VALUE ary, const char *str, int flags) { struct glob_args args; args.func = push_pattern; args.v = ary; return ruby_brace_glob0(str, flags | GLOB_VERBOSE, rb_glob_caller, (VALUE)&args); } static VALUE rb_push_glob(str, flags) /* '\0' is delimiter */ VALUE str; int flags; { long offset = 0; VALUE ary; ary = rb_ary_new(); SafeStringValue(str); while (offset < RSTRING_LEN(str)) { int status = push_glob(ary, RSTRING(str)->ptr + offset, flags); char *p, *pend; if (status) GLOB_JUMP_TAG(status); if (offset >= RSTRING_LEN(str)) break; p = RSTRING(str)->ptr + offset; p += strlen(p) + 1; pend = RSTRING(str)->ptr + RSTRING_LEN(str); while (p < pend && !*p) p++; offset = p - RSTRING(str)->ptr; } return ary; } static VALUE dir_globs(argc, argv, flags) long argc; VALUE *argv; int flags; { VALUE ary = rb_ary_new(); long i; for (i = 0; i < argc; ++i) { int status; VALUE str = argv[i]; SafeStringValue(str); status = push_glob(ary, RSTRING(str)->ptr, flags); if (status) GLOB_JUMP_TAG(status); } return ary; } /* * call-seq: * Dir[ array ] => array * Dir[ string [, string ...] ] => array * * Equivalent to calling * <code>Dir.glob(</code><i>array,</i><code>0)</code> and * <code>Dir.glob([</code><i>string,...</i><code>],0)</code>. * */ static VALUE dir_s_aref(int argc, VALUE *argv, VALUE obj) { if (argc == 1) { return rb_push_glob(argv[0], 0); } return dir_globs(argc, argv, 0); } /* * call-seq: * Dir.glob( pattern, [flags] ) => array * Dir.glob( pattern, [flags] ) {| filename | block } => nil * * Returns the filenames found by expanding <i>pattern</i> which is * an +Array+ of the patterns or the pattern +String+, either as an * <i>array</i> or as parameters to the block. Note that this pattern * is not a regexp (it's closer to a shell glob). See * <code>File::fnmatch</code> for the meaning of the <i>flags</i> * parameter. Note that case sensitivity depends on your system (so * <code>File::FNM_CASEFOLD</code> is ignored) * * <code>*</code>:: Matches any file. Can be restricted by * other values in the glob. <code>*</code> * will match all files; <code>c*</code> will * match all files beginning with * <code>c</code>; <code>*c</code> will match * all files ending with <code>c</code>; and * <code>*c*</code> will match all files that * have <code>c</code> in them (including at * the beginning or end). Equivalent to * <code>/ .* /x</code> in regexp. * <code>**</code>:: Matches directories recursively. * <code>?</code>:: Matches any one character. Equivalent to * <code>/.{1}/</code> in regexp. * <code>[set]</code>:: Matches any one character in +set+. * Behaves exactly like character sets in * Regexp, including set negation * (<code>[^a-z]</code>). * <code>{p,q}</code>:: Matches either literal <code>p</code> or * literal <code>q</code>. Matching literals * may be more than one character in length. * More than two literals may be specified. * Equivalent to pattern alternation in * regexp. * <code>\</code>:: Escapes the next metacharacter. * * Dir["config.?"] #=> ["config.h"] * Dir.glob("config.?") #=> ["config.h"] * Dir.glob("*.[a-z][a-z]") #=> ["main.rb"] * Dir.glob("*.[^r]*") #=> ["config.h"] * Dir.glob("*.{rb,h}") #=> ["main.rb", "config.h"] * Dir.glob("*") #=> ["config.h", "main.rb"] * Dir.glob("*", File::FNM_DOTMATCH) #=> [".", "..", "config.h", "main.rb"] * * rbfiles = File.join("**", "*.rb") * Dir.glob(rbfiles) #=> ["main.rb", * "lib/song.rb", * "lib/song/karaoke.rb"] * libdirs = File.join("**", "lib") * Dir.glob(libdirs) #=> ["lib"] * * librbfiles = File.join("**", "lib", "**", "*.rb") * Dir.glob(librbfiles) #=> ["lib/song.rb", * "lib/song/karaoke.rb"] * * librbfiles = File.join("**", "lib", "*.rb") * Dir.glob(librbfiles) #=> ["lib/song.rb"] */ static VALUE dir_s_glob(argc, argv, obj) int argc; VALUE *argv; VALUE obj; { VALUE str, rflags, ary; int flags; if (rb_scan_args(argc, argv, "11", &str, &rflags) == 2) flags = NUM2INT(rflags); else flags = 0; ary = rb_check_array_type(str); if (NIL_P(ary)) { ary = rb_push_glob(str, flags); } else { volatile VALUE v = ary; ary = dir_globs(RARRAY_LEN(v), RARRAY_PTR(v), flags); } if (rb_block_given_p()) { rb_ary_each(ary); return Qnil; } return ary; } static VALUE dir_open_dir(path) VALUE path; { VALUE dir = rb_funcall(rb_cDir, rb_intern("open"), 1, path); if (TYPE(dir) != T_DATA || RDATA(dir)->dfree != (RUBY_DATA_FUNC)free_dir) { rb_raise(rb_eTypeError, "wrong argument type %s (expected Dir)", rb_obj_classname(dir)); } return dir; } /* * call-seq: * Dir.foreach( dirname ) {| filename | block } => nil * * Calls the block once for each entry in the named directory, passing * the filename of each entry as a parameter to the block. * * Dir.foreach("testdir") {|x| puts "Got #{x}" } * * <em>produces:</em> * * Got . * Got .. * Got config.h * Got main.rb * */ static VALUE dir_foreach(io, dirname) VALUE io, dirname; { VALUE dir; dir = dir_open_dir(dirname); rb_ensure(dir_each, dir, dir_close, dir); return Qnil; } /* * call-seq: * Dir.entries( dirname ) => array * * Returns an array containing all of the filenames in the given * directory. Will raise a <code>SystemCallError</code> if the named * directory doesn't exist. * * Dir.entries("testdir") #=> [".", "..", "config.h", "main.rb"] * */ static VALUE dir_entries(io, dirname) VALUE io, dirname; { VALUE dir; dir = dir_open_dir(dirname); return rb_ensure(rb_Array, dir, dir_close, dir); } /* * call-seq: * File.fnmatch( pattern, path, [flags] ) => (true or false) * File.fnmatch?( pattern, path, [flags] ) => (true or false) * * Returns true if <i>path</i> matches against <i>pattern</i> The * pattern is not a regular expression; instead it follows rules * similar to shell filename globbing. It may contain the following * metacharacters: * * <code>*</code>:: Matches any file. Can be restricted by * other values in the glob. <code>*</code> * will match all files; <code>c*</code> will * match all files beginning with * <code>c</code>; <code>*c</code> will match * all files ending with <code>c</code>; and * <code>*c*</code> will match all files that * have <code>c</code> in them (including at * the beginning or end). Equivalent to * <code>/ .* /x</code> in regexp. * <code>**</code>:: Matches directories recursively or files * expansively. * <code>?</code>:: Matches any one character. Equivalent to * <code>/.{1}/</code> in regexp. * <code>[set]</code>:: Matches any one character in +set+. * Behaves exactly like character sets in * Regexp, including set negation * (<code>[^a-z]</code>). * <code>\</code>:: Escapes the next metacharacter. * * <i>flags</i> is a bitwise OR of the <code>FNM_xxx</code> * parameters. The same glob pattern and flags are used by * <code>Dir::glob</code>. * * File.fnmatch('cat', 'cat') #=> true : match entire string * File.fnmatch('cat', 'category') #=> false : only match partial string * File.fnmatch('c{at,ub}s', 'cats') #=> false : { } isn't supported * * File.fnmatch('c?t', 'cat') #=> true : '?' match only 1 character * File.fnmatch('c??t', 'cat') #=> false : ditto * File.fnmatch('c*', 'cats') #=> true : '*' match 0 or more characters * File.fnmatch('c*t', 'c/a/b/t') #=> true : ditto * File.fnmatch('ca[a-z]', 'cat') #=> true : inclusive bracket expression * File.fnmatch('ca[^t]', 'cat') #=> false : exclusive bracket expression ('^' or '!') * * File.fnmatch('cat', 'CAT') #=> false : case sensitive * File.fnmatch('cat', 'CAT', File::FNM_CASEFOLD) #=> true : case insensitive * * File.fnmatch('?', '/', File::FNM_PATHNAME) #=> false : wildcard doesn't match '/' on FNM_PATHNAME * File.fnmatch('*', '/', File::FNM_PATHNAME) #=> false : ditto * File.fnmatch('[/]', '/', File::FNM_PATHNAME) #=> false : ditto * * File.fnmatch('\?', '?') #=> true : escaped wildcard becomes ordinary * File.fnmatch('\a', 'a') #=> true : escaped ordinary remains ordinary * File.fnmatch('\a', '\a', File::FNM_NOESCAPE) #=> true : FNM_NOESACPE makes '\' ordinary * File.fnmatch('[\?]', '?') #=> true : can escape inside bracket expression * * File.fnmatch('*', '.profile') #=> false : wildcard doesn't match leading * File.fnmatch('*', '.profile', File::FNM_DOTMATCH) #=> true period by default. * File.fnmatch('.*', '.profile') #=> true * * rbfiles = '**' '/' '*.rb' # you don't have to do like this. just write in single string. * File.fnmatch(rbfiles, 'main.rb') #=> false * File.fnmatch(rbfiles, './main.rb') #=> false * File.fnmatch(rbfiles, 'lib/song.rb') #=> true * File.fnmatch('**.rb', 'main.rb') #=> true * File.fnmatch('**.rb', './main.rb') #=> false * File.fnmatch('**.rb', 'lib/song.rb') #=> true * File.fnmatch('*', 'dave/.profile') #=> true * * pattern = '*' '/' '*' * File.fnmatch(pattern, 'dave/.profile', File::FNM_PATHNAME) #=> false * File.fnmatch(pattern, 'dave/.profile', File::FNM_PATHNAME | File::FNM_DOTMATCH) #=> true * * pattern = '**' '/' 'foo' * File.fnmatch(pattern, 'a/b/c/foo', File::FNM_PATHNAME) #=> true * File.fnmatch(pattern, '/a/b/c/foo', File::FNM_PATHNAME) #=> true * File.fnmatch(pattern, 'c:/a/b/c/foo', File::FNM_PATHNAME) #=> true * File.fnmatch(pattern, 'a/.b/c/foo', File::FNM_PATHNAME) #=> false * File.fnmatch(pattern, 'a/.b/c/foo', File::FNM_PATHNAME | File::FNM_DOTMATCH) #=> true */ static VALUE file_s_fnmatch(argc, argv, obj) int argc; VALUE *argv; VALUE obj; { VALUE pattern, path; VALUE rflags; int flags; if (rb_scan_args(argc, argv, "21", &pattern, &path, &rflags) == 3) flags = NUM2INT(rflags); else flags = 0; StringValue(pattern); StringValue(path); if (fnmatch(RSTRING(pattern)->ptr, RSTRING(path)->ptr, flags) == 0) return Qtrue; return Qfalse; } /* * Objects of class <code>Dir</code> are directory streams representing * directories in the underlying file system. They provide a variety of * ways to list directories and their contents. See also * <code>File</code>. * * The directory used in these examples contains the two regular files * (<code>config.h</code> and <code>main.rb</code>), the parent * directory (<code>..</code>), and the directory itself * (<code>.</code>). */ void Init_Dir() { rb_cDir = rb_define_class("Dir", rb_cObject); rb_include_module(rb_cDir, rb_mEnumerable); rb_define_alloc_func(rb_cDir, dir_s_alloc); rb_define_singleton_method(rb_cDir, "open", dir_s_open, 1); rb_define_singleton_method(rb_cDir, "foreach", dir_foreach, 1); rb_define_singleton_method(rb_cDir, "entries", dir_entries, 1); rb_define_method(rb_cDir,"initialize", dir_initialize, 1); rb_define_method(rb_cDir,"path", dir_path, 0); rb_define_method(rb_cDir,"read", dir_read, 0); rb_define_method(rb_cDir,"each", dir_each, 0); rb_define_method(rb_cDir,"rewind", dir_rewind, 0); rb_define_method(rb_cDir,"tell", dir_tell, 0); rb_define_method(rb_cDir,"seek", dir_seek, 1); rb_define_method(rb_cDir,"pos", dir_tell, 0); rb_define_method(rb_cDir,"pos=", dir_set_pos, 1); rb_define_method(rb_cDir,"close", dir_close, 0); rb_define_singleton_method(rb_cDir,"chdir", dir_s_chdir, -1); rb_define_singleton_method(rb_cDir,"getwd", dir_s_getwd, 0); rb_define_singleton_method(rb_cDir,"pwd", dir_s_getwd, 0); rb_define_singleton_method(rb_cDir,"chroot", dir_s_chroot, 1); rb_define_singleton_method(rb_cDir,"mkdir", dir_s_mkdir, -1); rb_define_singleton_method(rb_cDir,"rmdir", dir_s_rmdir, 1); rb_define_singleton_method(rb_cDir,"delete", dir_s_rmdir, 1); rb_define_singleton_method(rb_cDir,"unlink", dir_s_rmdir, 1); rb_define_singleton_method(rb_cDir,"glob", dir_s_glob, -1); rb_define_singleton_method(rb_cDir,"[]", dir_s_aref, -1); rb_define_singleton_method(rb_cFile,"fnmatch", file_s_fnmatch, -1); rb_define_singleton_method(rb_cFile,"fnmatch?", file_s_fnmatch, -1); rb_file_const("FNM_NOESCAPE", INT2FIX(FNM_NOESCAPE)); rb_file_const("FNM_PATHNAME", INT2FIX(FNM_PATHNAME)); rb_file_const("FNM_DOTMATCH", INT2FIX(FNM_DOTMATCH)); rb_file_const("FNM_CASEFOLD", INT2FIX(FNM_CASEFOLD)); rb_file_const("FNM_SYSCASE", INT2FIX(FNM_SYSCASE)); } /********************************************************************** dln.c - $Author: shyouhei $ $Date: 2008-06-15 15:25:08 +0200 (Sun, 15 Jun 2008) $ created at: Tue Jan 18 17:05:06 JST 1994 Copyright (C) 1993-2003 <NAME> **********************************************************************/ #include "ruby.h" #include "dln.h" #ifdef HAVE_STDLIB_H # include <stdlib.h> #endif #ifdef __CHECKER__ #undef HAVE_DLOPEN #undef USE_DLN_A_OUT #undef USE_DLN_DLOPEN #endif #ifdef USE_DLN_A_OUT char *dln_argv0; #endif #if defined(HAVE_ALLOCA_H) #include <alloca.h> #endif #ifdef HAVE_STRING_H # include <string.h> #else # include <strings.h> #endif #ifndef xmalloc void *xmalloc(); void *xcalloc(); void *xrealloc(); #endif #include <stdio.h> #if defined(_WIN32) || defined(__VMS) #include "missing/file.h" #endif #include <sys/types.h> #include <sys/stat.h> #ifndef S_ISDIR # define S_ISDIR(m) ((m & S_IFMT) == S_IFDIR) #endif #ifdef HAVE_SYS_PARAM_H # include <sys/param.h> #endif #ifndef MAXPATHLEN # define MAXPATHLEN 1024 #endif #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #ifndef _WIN32 char *getenv(); #endif #if defined(__VMS) #pragma builtins #include <dlfcn.h> #endif #ifdef __MACOS__ # include <TextUtils.h> # include <CodeFragments.h> # include <Aliases.h> # include "macruby_private.h" #endif #ifdef __BEOS__ # include <image.h> #endif #ifndef NO_DLN_LOAD #if defined(HAVE_DLOPEN) && !defined(USE_DLN_A_OUT) && !defined(_AIX) && !defined(__APPLE__) && !defined(_UNICOSMP) /* dynamic load with dlopen() */ # define USE_DLN_DLOPEN #endif #ifndef FUNCNAME_PATTERN # if defined(__hp9000s300) || (defined(__NetBSD__) && !defined(__ELF__)) || defined(__BORLANDC__) || (defined(__FreeBSD__) && !defined(__ELF__)) || (defined(__OpenBSD__) && !defined(__ELF__)) || defined(NeXT) || defined(__WATCOMC__) || defined(__APPLE__) # define FUNCNAME_PATTERN "_Init_%s" # else # define FUNCNAME_PATTERN "Init_%s" # endif #endif static int init_funcname_len(buf, file) char **buf; const char *file; { char *p; const char *slash; int len; /* Load the file as an object one */ for (slash = file-1; *file; file++) /* Find position of last '/' */ #ifdef __MACOS__ if (*file == ':') slash = file; #else if (*file == '/') slash = file; #endif len = strlen(FUNCNAME_PATTERN) + strlen(slash + 1); *buf = xmalloc(len); snprintf(*buf, len, FUNCNAME_PATTERN, slash + 1); for (p = *buf; *p; p++) { /* Delete suffix if it exists */ if (*p == '.') { *p = '\0'; break; } } return p - *buf; } #define init_funcname(buf, file) do {\ int len = init_funcname_len(buf, file);\ char *tmp = ALLOCA_N(char, len+1);\ if (!tmp) {\ free(*buf);\ rb_memerror();\ }\ strcpy(tmp, *buf);\ free(*buf);\ *buf = tmp;\ } while (0) #ifdef USE_DLN_A_OUT #ifndef LIBC_NAME # define LIBC_NAME "libc.a" #endif #ifndef DLN_DEFAULT_LIB_PATH # define DLN_DEFAULT_LIB_PATH "/lib:/usr/lib:/usr/local/lib:." #endif #include <errno.h> static int dln_errno; #define DLN_ENOEXEC ENOEXEC /* Exec format error */ #define DLN_ECONFL 1201 /* Symbol name conflict */ #define DLN_ENOINIT 1202 /* No initializer given */ #define DLN_EUNDEF 1203 /* Undefine symbol remains */ #define DLN_ENOTLIB 1204 /* Not a library file */ #define DLN_EBADLIB 1205 /* Malformed library file */ #define DLN_EINIT 1206 /* Not initialized */ static int dln_init_p = 0; #include <ar.h> #include <a.out.h> #ifndef N_COMM # define N_COMM 0x12 #endif #ifndef N_MAGIC # define N_MAGIC(x) (x).a_magic #endif #define INVALID_OBJECT(h) (N_MAGIC(h) != OMAGIC) #include "util.h" #include "st.h" static st_table *sym_tbl; static st_table *undef_tbl; static int load_lib(); static int load_header(fd, hdrp, disp) int fd; struct exec *hdrp; long disp; { int size; lseek(fd, disp, 0); size = read(fd, hdrp, sizeof(struct exec)); if (size == -1) { dln_errno = errno; return -1; } if (size != sizeof(struct exec) || N_BADMAG(*hdrp)) { dln_errno = DLN_ENOEXEC; return -1; } return 0; } #if defined(sequent) #define RELOC_SYMBOL(r) ((r)->r_symbolnum) #define RELOC_MEMORY_SUB_P(r) ((r)->r_bsr) #define RELOC_PCREL_P(r) ((r)->r_pcrel || (r)->r_bsr) #define RELOC_TARGET_SIZE(r) ((r)->r_length) #endif /* Default macros */ #ifndef RELOC_ADDRESS #define RELOC_ADDRESS(r) ((r)->r_address) #define RELOC_EXTERN_P(r) ((r)->r_extern) #define RELOC_SYMBOL(r) ((r)->r_symbolnum) #define RELOC_MEMORY_SUB_P(r) 0 #define RELOC_PCREL_P(r) ((r)->r_pcrel) #define RELOC_TARGET_SIZE(r) ((r)->r_length) #endif #if defined(sun) && defined(sparc) /* Sparc (Sun 4) macros */ # undef relocation_info # define relocation_info reloc_info_sparc # define R_RIGHTSHIFT(r) (reloc_r_rightshift[(r)->r_type]) # define R_BITSIZE(r) (reloc_r_bitsize[(r)->r_type]) # define R_LENGTH(r) (reloc_r_length[(r)->r_type]) static int reloc_r_rightshift[] = { 0, 0, 0, 0, 0, 0, 2, 2, 10, 0, 0, 0, 0, 0, 0, }; static int reloc_r_bitsize[] = { 8, 16, 32, 8, 16, 32, 30, 22, 22, 22, 13, 10, 32, 32, 16, }; static int reloc_r_length[] = { 0, 1, 2, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, }; # define R_PCREL(r) \ ((r)->r_type >= RELOC_DISP8 && (r)->r_type <= RELOC_WDISP22) # define R_SYMBOL(r) ((r)->r_index) #endif #if defined(sequent) #define R_SYMBOL(r) ((r)->r_symbolnum) #define R_MEMORY_SUB(r) ((r)->r_bsr) #define R_PCREL(r) ((r)->r_pcrel || (r)->r_bsr) #define R_LENGTH(r) ((r)->r_length) #endif #ifndef R_SYMBOL # define R_SYMBOL(r) ((r)->r_symbolnum) # define R_MEMORY_SUB(r) 0 # define R_PCREL(r) ((r)->r_pcrel) # define R_LENGTH(r) ((r)->r_length) #endif static struct relocation_info * load_reloc(fd, hdrp, disp) int fd; struct exec *hdrp; long disp; { struct relocation_info *reloc; int size; lseek(fd, disp + N_TXTOFF(*hdrp) + hdrp->a_text + hdrp->a_data, 0); size = hdrp->a_trsize + hdrp->a_drsize; reloc = (struct relocation_info*)xmalloc(size); if (reloc == NULL) { dln_errno = errno; return NULL; } if (read(fd, reloc, size) != size) { dln_errno = errno; free(reloc); return NULL; } return reloc; } static struct nlist * load_sym(fd, hdrp, disp) int fd; struct exec *hdrp; long disp; { struct nlist * buffer; struct nlist * sym; struct nlist * end; long displ; int size; lseek(fd, N_SYMOFF(*hdrp) + hdrp->a_syms + disp, 0); if (read(fd, &size, sizeof(int)) != sizeof(int)) { goto err_noexec; } buffer = (struct nlist*)xmalloc(hdrp->a_syms + size); if (buffer == NULL) { dln_errno = errno; return NULL; } lseek(fd, disp + N_SYMOFF(*hdrp), 0); if (read(fd, buffer, hdrp->a_syms + size) != hdrp->a_syms + size) { free(buffer); goto err_noexec; } sym = buffer; end = sym + hdrp->a_syms / sizeof(struct nlist); displ = (long)buffer + (long)(hdrp->a_syms); while (sym < end) { sym->n_un.n_name = (char*)sym->n_un.n_strx + displ; sym++; } return buffer; err_noexec: dln_errno = DLN_ENOEXEC; return NULL; } static st_table * sym_hash(hdrp, syms) struct exec *hdrp; struct nlist *syms; { st_table *tbl; struct nlist *sym = syms; struct nlist *end = syms + (hdrp->a_syms / sizeof(struct nlist)); tbl = st_init_strtable(); if (tbl == NULL) { dln_errno = errno; return NULL; } while (sym < end) { st_insert(tbl, sym->n_un.n_name, sym); sym++; } return tbl; } static int dln_init(prog) const char *prog; { char *file; int fd; struct exec hdr; struct nlist *syms; if (dln_init_p == 1) return 0; file = dln_find_exe(prog, NULL); if (file == NULL || (fd = open(file, O_RDONLY)) < 0) { dln_errno = errno; return -1; } if (load_header(fd, &hdr, 0) == -1) return -1; syms = load_sym(fd, &hdr, 0); if (syms == NULL) { close(fd); return -1; } sym_tbl = sym_hash(&hdr, syms); if (sym_tbl == NULL) { /* file may be start with #! */ char c = '\0'; char buf[MAXPATHLEN]; char *p; free(syms); lseek(fd, 0L, 0); if (read(fd, &c, 1) == -1) { dln_errno = errno; return -1; } if (c != '#') goto err_noexec; if (read(fd, &c, 1) == -1) { dln_errno = errno; return -1; } if (c != '!') goto err_noexec; p = buf; /* skip forwarding spaces */ while (read(fd, &c, 1) == 1) { if (c == '\n') goto err_noexec; if (c != '\t' && c != ' ') { *p++ = c; break; } } /* read in command name */ while (read(fd, p, 1) == 1) { if (*p == '\n' || *p == '\t' || *p == ' ') break; p++; if (p-buf >= MAXPATHLEN) { dln_errno = ENAMETOOLONG; return -1; } } *p = '\0'; return dln_init(buf); } dln_init_p = 1; undef_tbl = st_init_strtable(); close(fd); return 0; err_noexec: close(fd); dln_errno = DLN_ENOEXEC; return -1; } static long load_text_data(fd, hdrp, bss, disp) int fd; struct exec *hdrp; int bss; long disp; { int size; unsigned char* addr; lseek(fd, disp + N_TXTOFF(*hdrp), 0); size = hdrp->a_text + hdrp->a_data; if (bss == -1) size += hdrp->a_bss; else if (bss > 1) size += bss; addr = (unsigned char*)xmalloc(size); if (addr == NULL) { dln_errno = errno; return 0; } if (read(fd, addr, size) != size) { dln_errno = errno; free(addr); return 0; } if (bss == -1) { memset(addr + hdrp->a_text + hdrp->a_data, 0, hdrp->a_bss); } else if (bss > 0) { memset(addr + hdrp->a_text + hdrp->a_data, 0, bss); } return (long)addr; } static int undef_print(key, value) char *key, *value; { fprintf(stderr, " %s\n", key); return ST_CONTINUE; } static void dln_print_undef() { fprintf(stderr, " Undefined symbols:\n"); st_foreach(undef_tbl, undef_print, NULL); } static void dln_undefined() { if (undef_tbl->num_entries > 0) { fprintf(stderr, "dln: Calling undefined function\n"); dln_print_undef(); rb_exit(1); } } struct undef { char *name; struct relocation_info reloc; long base; char *addr; union { char c; short s; long l; } u; }; static st_table *reloc_tbl = NULL; static void link_undef(name, base, reloc) const char *name; long base; struct relocation_info *reloc; { static int u_no = 0; struct undef *obj; char *addr = (char*)(reloc->r_address + base); obj = (struct undef*)xmalloc(sizeof(struct undef)); obj->name = strdup(name); obj->reloc = *reloc; obj->base = base; switch (R_LENGTH(reloc)) { case 0: /* byte */ obj->u.c = *addr; break; case 1: /* word */ obj->u.s = *(short*)addr; break; case 2: /* long */ obj->u.l = *(long*)addr; break; } if (reloc_tbl == NULL) { reloc_tbl = st_init_numtable(); } st_insert(reloc_tbl, u_no++, obj); } struct reloc_arg { const char *name; long value; }; static int reloc_undef(no, undef, arg) int no; struct undef *undef; struct reloc_arg *arg; { int datum; char *address; #if defined(sun) && defined(sparc) unsigned int mask = 0; #endif if (strcmp(arg->name, undef->name) != 0) return ST_CONTINUE; address = (char*)(undef->base + undef->reloc.r_address); datum = arg->value; if (R_PCREL(&(undef->reloc))) datum -= undef->base; #if defined(sun) && defined(sparc) datum += undef->reloc.r_addend; datum >>= R_RIGHTSHIFT(&(undef->reloc)); mask = (1 << R_BITSIZE(&(undef->reloc))) - 1; mask |= mask -1; datum &= mask; switch (R_LENGTH(&(undef->reloc))) { case 0: *address = undef->u.c; *address &= ~mask; *address |= datum; break; case 1: *(short *)address = undef->u.s; *(short *)address &= ~mask; *(short *)address |= datum; break; case 2: *(long *)address = undef->u.l; *(long *)address &= ~mask; *(long *)address |= datum; break; } #else switch (R_LENGTH(&(undef->reloc))) { case 0: /* byte */ if (R_MEMORY_SUB(&(undef->reloc))) *address = datum - *address; else *address = undef->u.c + datum; break; case 1: /* word */ if (R_MEMORY_SUB(&(undef->reloc))) *(short*)address = datum - *(short*)address; else *(short*)address = undef->u.s + datum; break; case 2: /* long */ if (R_MEMORY_SUB(&(undef->reloc))) *(long*)address = datum - *(long*)address; else *(long*)address = undef->u.l + datum; break; } #endif free(undef->name); free(undef); return ST_DELETE; } static void unlink_undef(name, value) const char *name; long value; { struct reloc_arg arg; arg.name = name; arg.value = value; st_foreach(reloc_tbl, reloc_undef, &arg); } #ifdef N_INDR struct indr_data { char *name0, *name1; }; static int reloc_repl(no, undef, data) int no; struct undef *undef; struct indr_data *data; { if (strcmp(data->name0, undef->name) == 0) { free(undef->name); undef->name = strdup(data->name1); } return ST_CONTINUE; } #endif static int load_1(fd, disp, need_init) int fd; long disp; const char *need_init; { static char *libc = LIBC_NAME; struct exec hdr; struct relocation_info *reloc = NULL; long block = 0; long new_common = 0; /* Length of new common */ struct nlist *syms = NULL; struct nlist *sym; struct nlist *end; int init_p = 0; if (load_header(fd, &hdr, disp) == -1) return -1; if (INVALID_OBJECT(hdr)) { dln_errno = DLN_ENOEXEC; return -1; } reloc = load_reloc(fd, &hdr, disp); if (reloc == NULL) return -1; syms = load_sym(fd, &hdr, disp); if (syms == NULL) { free(reloc); return -1; } sym = syms; end = syms + (hdr.a_syms / sizeof(struct nlist)); while (sym < end) { struct nlist *old_sym; int value = sym->n_value; #ifdef N_INDR if (sym->n_type == (N_INDR | N_EXT)) { char *key = sym->n_un.n_name; if (st_lookup(sym_tbl, sym[1].n_un.n_name, &old_sym)) { if (st_delete(undef_tbl, (st_data_t*)&key, NULL)) { unlink_undef(key, old_sym->n_value); free(key); } } else { struct indr_data data; data.name0 = sym->n_un.n_name; data.name1 = sym[1].n_un.n_name; st_foreach(reloc_tbl, reloc_repl, &data); st_insert(undef_tbl, strdup(sym[1].n_un.n_name), NULL); if (st_delete(undef_tbl, (st_data_t*)&key, NULL)) { free(key); } } sym += 2; continue; } #endif if (sym->n_type == (N_UNDF | N_EXT)) { if (st_lookup(sym_tbl, sym->n_un.n_name, &old_sym) == 0) { old_sym = NULL; } if (value) { if (old_sym) { sym->n_type = N_EXT | N_COMM; sym->n_value = old_sym->n_value; } else { int rnd = value >= sizeof(double) ? sizeof(double) - 1 : value >= sizeof(long) ? sizeof(long) - 1 : sizeof(short) - 1; sym->n_type = N_COMM; new_common += rnd; new_common &= ~(long)rnd; sym->n_value = new_common; new_common += value; } } else { if (old_sym) { sym->n_type = N_EXT | N_COMM; sym->n_value = old_sym->n_value; } else { sym->n_value = (long)dln_undefined; st_insert(undef_tbl, strdup(sym->n_un.n_name), NULL); } } } sym++; } block = load_text_data(fd, &hdr, hdr.a_bss + new_common, disp); if (block == 0) goto err_exit; sym = syms; while (sym < end) { struct nlist *new_sym; char *key; switch (sym->n_type) { case N_COMM: sym->n_value += hdr.a_text + hdr.a_data; case N_TEXT|N_EXT: case N_DATA|N_EXT: sym->n_value += block; if (st_lookup(sym_tbl, sym->n_un.n_name, &new_sym) != 0 && new_sym->n_value != (long)dln_undefined) { dln_errno = DLN_ECONFL; goto err_exit; } key = sym->n_un.n_name; if (st_delete(undef_tbl, (st_data_t*)&key, NULL) != 0) { unlink_undef(key, sym->n_value); free(key); } new_sym = (struct nlist*)xmalloc(sizeof(struct nlist)); *new_sym = *sym; new_sym->n_un.n_name = strdup(sym->n_un.n_name); st_insert(sym_tbl, new_sym->n_un.n_name, new_sym); break; case N_TEXT: case N_DATA: sym->n_value += block; break; } sym++; } /* * First comes the text-relocation */ { struct relocation_info * rel = reloc; struct relocation_info * rel_beg = reloc + (hdr.a_trsize/sizeof(struct relocation_info)); struct relocation_info * rel_end = reloc + (hdr.a_trsize+hdr.a_drsize)/sizeof(struct relocation_info); while (rel < rel_end) { char *address = (char*)(rel->r_address + block); long datum = 0; #if defined(sun) && defined(sparc) unsigned int mask = 0; #endif if(rel >= rel_beg) address += hdr.a_text; if (rel->r_extern) { /* Look it up in symbol-table */ sym = &(syms[R_SYMBOL(rel)]); switch (sym->n_type) { case N_EXT|N_UNDF: link_undef(sym->n_un.n_name, block, rel); case N_EXT|N_COMM: case N_COMM: datum = sym->n_value; break; default: goto err_exit; } } /* end.. look it up */ else { /* is static */ switch (R_SYMBOL(rel)) { case N_TEXT: case N_DATA: datum = block; break; case N_BSS: datum = block + new_common; break; case N_ABS: break; } } /* end .. is static */ if (R_PCREL(rel)) datum -= block; #if defined(sun) && defined(sparc) datum += rel->r_addend; datum >>= R_RIGHTSHIFT(rel); mask = (1 << R_BITSIZE(rel)) - 1; mask |= mask -1; datum &= mask; switch (R_LENGTH(rel)) { case 0: *address &= ~mask; *address |= datum; break; case 1: *(short *)address &= ~mask; *(short *)address |= datum; break; case 2: *(long *)address &= ~mask; *(long *)address |= datum; break; } #else switch (R_LENGTH(rel)) { case 0: /* byte */ if (datum < -128 || datum > 127) goto err_exit; *address += datum; break; case 1: /* word */ *(short *)address += datum; break; case 2: /* long */ *(long *)address += datum; break; } #endif rel++; } } if (need_init) { int len; char **libs_to_be_linked = 0; char *buf; if (undef_tbl->num_entries > 0) { if (load_lib(libc) == -1) goto err_exit; } init_funcname(&buf, need_init); len = strlen(buf); for (sym = syms; sym<end; sym++) { char *name = sym->n_un.n_name; if (name[0] == '_' && sym->n_value >= block) { if (strcmp(name+1, "dln_libs_to_be_linked") == 0) { libs_to_be_linked = (char**)sym->n_value; } else if (strcmp(name+1, buf) == 0) { init_p = 1; ((int (*)())sym->n_value)(); } } } if (libs_to_be_linked && undef_tbl->num_entries > 0) { while (*libs_to_be_linked) { load_lib(*libs_to_be_linked); libs_to_be_linked++; } } } free(reloc); free(syms); if (need_init) { if (init_p == 0) { dln_errno = DLN_ENOINIT; return -1; } if (undef_tbl->num_entries > 0) { if (load_lib(libc) == -1) goto err_exit; if (undef_tbl->num_entries > 0) { dln_errno = DLN_EUNDEF; return -1; } } } return 0; err_exit: if (syms) free(syms); if (reloc) free(reloc); if (block) free((char*)block); return -1; } static int target_offset; static int search_undef(key, value, lib_tbl) const char *key; int value; st_table *lib_tbl; { long offset; if (st_lookup(lib_tbl, key, &offset) == 0) return ST_CONTINUE; target_offset = offset; return ST_STOP; } struct symdef { int rb_str_index; int lib_offset; }; char *dln_librrb_ary_path = DLN_DEFAULT_LIB_PATH; static int load_lib(lib) const char *lib; { char *path, *file; char armagic[SARMAG]; int fd, size; struct ar_hdr ahdr; st_table *lib_tbl = NULL; int *data, nsym; struct symdef *base; char *name_base; if (dln_init_p == 0) { dln_errno = DLN_ENOINIT; return -1; } if (undef_tbl->num_entries == 0) return 0; dln_errno = DLN_EBADLIB; if (lib[0] == '-' && lib[1] == 'l') { long len = strlen(lib) + 4; char *p = alloca(len); snprintf(p, len, "lib%s.a", lib+2); lib = p; } /* library search path: */ /* look for environment variable DLN_LIBRARY_PATH first. */ /* then variable dln_librrb_ary_path. */ /* if path is still NULL, use "." for path. */ path = getenv("DLN_LIBRARY_PATH"); if (path == NULL) path = dln_librrb_ary_path; file = dln_find_file(lib, path); fd = open(file, O_RDONLY); if (fd == -1) goto syserr; size = read(fd, armagic, SARMAG); if (size == -1) goto syserr; if (size != SARMAG) { dln_errno = DLN_ENOTLIB; goto badlib; } size = read(fd, &ahdr, sizeof(ahdr)); if (size == -1) goto syserr; if (size != sizeof(ahdr) || sscanf(ahdr.ar_size, "%d", &size) != 1) { goto badlib; } if (strncmp(ahdr.ar_name, "__.SYMDEF", 9) == 0) { /* make hash table from __.SYMDEF */ lib_tbl = st_init_strtable(); data = (int*)xmalloc(size); if (data == NULL) goto syserr; size = read(fd, data, size); nsym = *data / sizeof(struct symdef); base = (struct symdef*)(data + 1); name_base = (char*)(base + nsym) + sizeof(int); while (nsym > 0) { char *name = name_base + base->rb_str_index; st_insert(lib_tbl, name, base->lib_offset + sizeof(ahdr)); nsym--; base++; } for (;;) { target_offset = -1; st_foreach(undef_tbl, search_undef, lib_tbl); if (target_offset == -1) break; if (load_1(fd, target_offset, 0) == -1) { st_free_table(lib_tbl); free(data); goto badlib; } if (undef_tbl->num_entries == 0) break; } free(data); st_free_table(lib_tbl); } else { /* linear library, need to scan (FUTURE) */ for (;;) { int offset = SARMAG; int found = 0; struct exec hdr; struct nlist *syms, *sym, *end; while (undef_tbl->num_entries > 0) { found = 0; lseek(fd, offset, 0); size = read(fd, &ahdr, sizeof(ahdr)); if (size == -1) goto syserr; if (size == 0) break; if (size != sizeof(ahdr) || sscanf(ahdr.ar_size, "%d", &size) != 1) { goto badlib; } offset += sizeof(ahdr); if (load_header(fd, &hdr, offset) == -1) goto badlib; syms = load_sym(fd, &hdr, offset); if (syms == NULL) goto badlib; sym = syms; end = syms + (hdr.a_syms / sizeof(struct nlist)); while (sym < end) { if (sym->n_type == N_EXT|N_TEXT && st_lookup(undef_tbl, sym->n_un.n_name, NULL)) { break; } sym++; } if (sym < end) { found++; free(syms); if (load_1(fd, offset, 0) == -1) { goto badlib; } } offset += size; if (offset & 1) offset++; } if (found) break; } } close(fd); return 0; syserr: dln_errno = errno; badlib: if (fd >= 0) close(fd); return -1; } static int load(file) const char *file; { int fd; int result; if (dln_init_p == 0) { if (dln_init(dln_argv0) == -1) return -1; } result = strlen(file); if (file[result-1] == 'a') { return load_lib(file); } fd = open(file, O_RDONLY); if (fd == -1) { dln_errno = errno; return -1; } result = load_1(fd, 0, file); close(fd); return result; } void* dln_sym(name) const char *name; { struct nlist *sym; if (st_lookup(sym_tbl, name, &sym)) return (void*)sym->n_value; return NULL; } #endif /* USE_DLN_A_OUT */ #ifdef USE_DLN_DLOPEN # if defined(__NetBSD__) && defined(__NetBSD_Version__) && __NetBSD_Version__ < 105000000 # include <nlist.h> # include <link.h> # else # include <dlfcn.h> # endif #endif #ifdef __hpux #include <errno.h> #include "dl.h" #endif #if defined(_AIX) #include <ctype.h> /* for isdigit() */ #include <errno.h> /* for global errno */ #include <sys/ldr.h> #endif #ifdef NeXT #if NS_TARGET_MAJOR < 4 #include <mach-o/rld.h> #else #include <mach-o/dyld.h> #ifndef NSLINKMODULE_OPTION_BINDNOW #define NSLINKMODULE_OPTION_BINDNOW 1 #endif #endif #else #ifdef __APPLE__ #include <mach-o/dyld.h> #endif #endif #if defined _WIN32 && !defined __CYGWIN__ #include <windows.h> #endif #ifdef _WIN32_WCE #undef FormatMessage #define FormatMessage FormatMessageA #undef LoadLibrary #define LoadLibrary LoadLibraryA #undef GetProcAddress #define GetProcAddress GetProcAddressA #endif static const char * dln_strerror() { #ifdef USE_DLN_A_OUT char *strerror(); switch (dln_errno) { case DLN_ECONFL: return "Symbol name conflict"; case DLN_ENOINIT: return "No initializer given"; case DLN_EUNDEF: return "Unresolved symbols"; case DLN_ENOTLIB: return "Not a library file"; case DLN_EBADLIB: return "Malformed library file"; case DLN_EINIT: return "Not initialized"; default: return strerror(dln_errno); } #endif #ifdef USE_DLN_DLOPEN return (char*)dlerror(); #endif #if defined _WIN32 && !defined __CYGWIN__ static char message[1024]; int error = GetLastError(); char *p = message; p += sprintf(message, "%d: ", error); FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), p, sizeof message - strlen(message), NULL); for (p = message; *p; p++) { if (*p == '\n' || *p == '\r') *p = ' '; } return message; #endif } #if defined(_AIX) && ! defined(_IA64) static void aix_loaderror(const char *pathname) { char *message[8], errbuf[1024]; int i,j; struct errtab { int errnum; char *errstr; } load_errtab[] = { {L_ERROR_TOOMANY, "too many errors, rest skipped."}, {L_ERROR_NOLIB, "can't load library:"}, {L_ERROR_UNDEF, "can't find symbol in library:"}, {L_ERROR_RLDBAD, "RLD index out of range or bad relocation type:"}, {L_ERROR_FORMAT, "not a valid, executable xcoff file:"}, {L_ERROR_MEMBER, "file not an archive or does not contain requested member:"}, {L_ERROR_TYPE, "symbol table mismatch:"}, {L_ERROR_ALIGN, "text alignment in file is wrong."}, {L_ERROR_SYSTEM, "System error:"}, {L_ERROR_ERRNO, NULL} }; #define LOAD_ERRTAB_LEN (sizeof(load_errtab)/sizeof(load_errtab[0])) #define ERRBUF_APPEND(s) strncat(errbuf, s, sizeof(errbuf)-strlen(errbuf)-1) snprintf(errbuf, 1024, "load failed - %s ", pathname); if (!loadquery(1, &message[0], sizeof(message))) ERRBUF_APPEND(strerror(errno)); for(i = 0; message[i] && *message[i]; i++) { int nerr = atoi(message[i]); for (j=0; j<LOAD_ERRTAB_LEN; j++) { if (nerr == load_errtab[i].errnum && load_errtab[i].errstr) ERRBUF_APPEND(load_errtab[i].errstr); } while (isdigit(*message[i])) message[i]++; ERRBUF_APPEND(message[i]); ERRBUF_APPEND("\n"); } errbuf[strlen(errbuf)-1] = '\0'; /* trim off last newline */ rb_loaderror(errbuf); return; } #endif #if defined(__VMS) #include <starlet.h> #include <rms.h> #include <stsdef.h> #include <unixlib.h> #include <descrip.h> #include <lib$routines.h> static char *vms_filespec; static int vms_fileact(char *filespec, int type); static long vms_fisexh(long *sigarr, long *mecarr); #endif #endif /* NO_DLN_LOAD */
#!/bin/sh # Base16 Twilight - Shell color setup script # David Hart (http://hart-dev.com) if [ "${TERM%%-*}" = 'linux' ]; then # This script doesn't support linux console (use 'vconsole' template instead) return 2>/dev/null || exit 0 fi color00="1e/1e/1e" # Base 00 - Black color01="cf/6a/4c" # Base 08 - Red color02="8f/9d/6a" # Base 0B - Green color03="f9/ee/98" # Base 0A - Yellow color04="75/87/a6" # Base 0D - Blue color05="9b/85/9d" # Base 0E - Magenta color06="af/c4/db" # Base 0C - Cyan color07="a7/a7/a7" # Base 05 - White color08="5f/5a/60" # Base 03 - Bright Black color09=$color01 # Base 08 - Bright Red color10=$color02 # Base 0B - Bright Green color11=$color03 # Base 0A - Bright Yellow color12=$color04 # Base 0D - Bright Blue color13=$color05 # Base 0E - Bright Magenta color14=$color06 # Base 0C - Bright Cyan color15="ff/ff/ff" # Base 07 - Bright White color16="cd/a8/69" # Base 09 color17="9b/70/3f" # Base 0F color18="32/35/37" # Base 01 color19="46/4b/50" # Base 02 color20="83/81/84" # Base 04 color21="c3/c3/c3" # Base 06 color_foreground="a7/a7/a7" # Base 05 color_background="1e/1e/1e" # Base 00 color_cursor="a7/a7/a7" # Base 05 if [ -n "$TMUX" ]; then # tell tmux to pass the escape sequences through # (Source: http://permalink.gmane.org/gmane.comp.terminal-emulators.tmux.user/1324) printf_template="\033Ptmux;\033\033]4;%d;rgb:%s\007\033\\" printf_template_var="\033Ptmux;\033\033]%d;rgb:%s\007\033\\" printf_template_custom="\033Ptmux;\033\033]%s%s\007\033\\" elif [ "${TERM%%-*}" = "screen" ]; then # GNU screen (screen, screen-256color, screen-256color-bce) printf_template="\033P\033]4;%d;rgb:%s\007\033\\" printf_template_var="\033P\033]%d;rgb:%s\007\033\\" printf_template_custom="\033P\033]%s%s\007\033\\" else printf_template="\033]4;%d;rgb:%s\033\\" printf_template_var="\033]%d;rgb:%s\033\\" printf_template_custom="\033]%s%s\033\\" fi # 16 color space printf $printf_template 0 $color00 printf $printf_template 1 $color01 printf $printf_template 2 $color02 printf $printf_template 3 $color03 printf $printf_template 4 $color04 printf $printf_template 5 $color05 printf $printf_template 6 $color06 printf $printf_template 7 $color07 printf $printf_template 8 $color08 printf $printf_template 9 $color09 printf $printf_template 10 $color10 printf $printf_template 11 $color11 printf $printf_template 12 $color12 printf $printf_template 13 $color13 printf $printf_template 14 $color14 printf $printf_template 15 $color15 # 256 color space printf $printf_template 16 $color16 printf $printf_template 17 $color17 printf $printf_template 18 $color18 printf $printf_template 19 $color19 printf $printf_template 20 $color20 printf $printf_template 21 $color21 # foreground / background / cursor color if [ -n "$ITERM_SESSION_ID" ]; then # iTerm2 proprietary escape codes printf $printf_template_custom Pg a7a7a7 # forground printf $printf_template_custom Ph 1e1e1e # background printf $printf_template_custom Pi a7a7a7 # bold color printf $printf_template_custom Pj 464b50 # selection color printf $printf_template_custom Pk a7a7a7 # selected text color printf $printf_template_custom Pl a7a7a7 # cursor printf $printf_template_custom Pm 1e1e1e # cursor text else printf $printf_template_var 10 $color_foreground printf $printf_template_var 11 $color_background printf $printf_template_custom 12 ";7" # cursor (reverse video) fi # clean up unset printf_template unset printf_template_var unset color00 unset color01 unset color02 unset color03 unset color04 unset color05 unset color06 unset color07 unset color08 unset color09 unset color10 unset color11 unset color12 unset color13 unset color14 unset color15 unset color16 unset color17 unset color18 unset color19 unset color20 unset color21 unset color_foreground unset color_background unset color_cursor
import { HasPropsHandlers, PropsHandler } from "./PropsHandler" /** * TODO: Integrate this into the generated code, which duplicates for every class. */ export default class BasePropsHandler<T, U> implements HasPropsHandlers<T, U> { private propsHandlers: PropsHandler<T, U>[] constructor(propsHandlers: PropsHandler<T, U>[]) { this.propsHandlers = propsHandlers } getPropsHandlers(): PropsHandler<T, U>[] { return this.propsHandlers } addPropsHandler(propHandler: PropsHandler<T, U>): void { this.propsHandlers.push(propHandler) } }
macro_rules! generate_output { ($input:literal) => { { let input_str = $input; let trimmed_str = input_str.trim_start_matches("#[").trim_end_matches("]"); let parts: Vec<&str> = trimmed_str.split("=").map(|s| s.trim()).collect(); if parts.len() != 2 { panic!("Invalid input format"); } let variable = parts[0]; let value = parts[1].trim_matches('"'); format!("{}: {}", variable, value) } }; } fn main() { let output = generate_output!(#[foo = "bar"]); println!("{}", output); // Output: foo: bar }
#! /bin/bash # Copyright 2020 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This is a helper script to build Graphenized docker image for python worker. # Avalon python worker docker image name. IMAGE_NAME=avalon-python-worker-dev # Graphenized docker image name for python worker. GSC_IMAGE_NAME=gsc-$IMAGE_NAME # Check if TCF_HOME is set. If not exit. if [ -z "$TCF_HOME" ]; then echo "TCF_HOME is not set. Please set it to avalon repo top level directory" echo "In the current shell: export TCF_HOME=<avalon top level directory>" exit else echo "TCF_HOME is set to $TCF_HOME" fi # Check if GSC image exists. If so delete it first before building new image. GSC_IMAGE_EXISTS=`sudo docker image inspect $GSC_IMAGE_NAME >/dev/null 2>&1 && echo yes || echo no` if [ "$GSC_IMAGE_EXISTS" = "yes" ]; then echo "Remove existing GSC image" sudo docker rmi $GSC_IMAGE_NAME --force fi # Manifest files MANIFEST_FILE_DIR="${TCF_HOME}/examples/graphene_apps/python_worker/graphene" MANIFEST_FILES="python.manifest sh.manifest gcc.manifest collect2.manifest ld.manifest" # Generate list of manifest files LIST_MANIFEST_FILES="" for f in $MANIFEST_FILES do FILE_NAME=${MANIFEST_FILE_DIR}/$f if [ ! -f $FILE_NAME ]; then echo "ERROR:Manifest file $FILE_NAME doesn't exist" exit fi LIST_MANIFEST_FILES+=${MANIFEST_FILE_DIR}/$f LIST_MANIFEST_FILES+=" " done echo $LIST_MANIFEST_FILES # Build image echo "Build unsigned GSC image" ./gsc build --insecure-args $IMAGE_NAME $LIST_MANIFEST_FILES # Generate signing key if it doesn't exists SIGN_KEY_FILE=enclave-key.pem if [ ! -f "$SIGN_KEY_FILE" ]; then openssl genrsa -3 -out $SIGN_KEY_FILE 3072 fi # Sign image to generate final GSC image echo "Generate Signed GSC image" ./gsc sign-image $IMAGE_NAME $SIGN_KEY_FILE
#!/bin/bash # Copyright 2019 Marc-Antoine Ruel. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 # that can be found in the LICENSE file. # Only update code, not data. set -eu cd "$(dirname $0)" ./setup.sh source .venv/bin/activate echo "- Flashing code" pio run --target upload -s echo "" echo "Congratulations!" echo "If you want to use debugging, enable it in platform.ini," echo "then you can monitor the device over the serial port:" echo " .venv/bin/pio device monitor"
#!/usr/bin/env bash echo "Autoremoving..." apt-get -y autoremove
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jena.jdbc.connections; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import org.apache.jena.jdbc.JdbcCompatibility; import org.apache.jena.jdbc.statements.DatasetPreparedStatement; import org.apache.jena.jdbc.statements.DatasetStatement; import org.apache.jena.jdbc.statements.JenaPreparedStatement; import org.apache.jena.jdbc.statements.JenaStatement; import org.apache.jena.query.Dataset ; import org.apache.jena.query.ReadWrite ; /** * Represents a connection to a {@link Dataset} instance * */ public abstract class DatasetConnection extends JenaConnection { protected Dataset ds; private boolean readonly = false; private ThreadLocal<ReadWrite> transactionType = new ThreadLocal<ReadWrite>(); private ThreadLocal<Integer> transactionParticipants = new ThreadLocal<Integer>(); /** * Creates a new dataset connection * * @param ds * Dataset * @param holdability * Cursor holdability * @param autoCommit * Sets auto-commit behavior for the connection * @param transactionLevel * Sets transaction isolation level for the connection * @param compatibilityLevel * Sets JDBC compatibility level for the connection, see * {@link JdbcCompatibility} * @throws SQLException */ public DatasetConnection(Dataset ds, int holdability, boolean autoCommit, int transactionLevel, int compatibilityLevel) throws SQLException { super(holdability, autoCommit, transactionLevel, compatibilityLevel); this.ds = ds; } /** * Gets the dataset to which this connection pertains * * @return Dataset */ public final Dataset getJenaDataset() { return this.ds; } @Override protected void closeInternal() throws SQLException { try { if (this.ds != null) { ds.close(); ds = null; } } catch (Exception e) { throw new SQLException("Unexpected error closing a dataset backed connection", e); } finally { this.ds = null; } } @Override protected JenaStatement createStatementInternal(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { if (resultSetType == ResultSet.TYPE_SCROLL_SENSITIVE) throw new SQLFeatureNotSupportedException("Dataset backed connections do not support scroll sensitive result sets"); if (resultSetConcurrency != ResultSet.CONCUR_READ_ONLY) throw new SQLFeatureNotSupportedException("Dataset backed connections only supports read-only result sets"); return new DatasetStatement(this, resultSetType, ResultSet.FETCH_FORWARD, 0, resultSetHoldability, this.getAutoCommit(), this.getTransactionIsolation()); } @Override protected JenaPreparedStatement createPreparedStatementInternal(String sparql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { if (resultSetType == ResultSet.TYPE_SCROLL_SENSITIVE) throw new SQLFeatureNotSupportedException("Dataset backed connections do not support scroll sensitive result sets"); if (resultSetConcurrency != ResultSet.CONCUR_READ_ONLY) throw new SQLFeatureNotSupportedException("Dataset backed connections only supports read-only result sets"); return new DatasetPreparedStatement(sparql, this, resultSetType, ResultSet.FETCH_FORWARD, 0, resultSetHoldability, this.getAutoCommit(), this.getTransactionIsolation()); } @Override public boolean isClosed() { return this.ds == null; } @Override public boolean isReadOnly() { return this.readonly; } @Override public boolean isValid(int timeout) { return !this.isClosed(); } @Override public void setReadOnly(boolean readOnly) throws SQLException { if (this.isClosed()) throw new SQLException("Cannot set read-only mode on a closed connection"); this.readonly = readOnly; } @Override protected void checkTransactionIsolation(int level) throws SQLException { switch (level) { case TRANSACTION_NONE: return; case TRANSACTION_SERIALIZABLE: // Serializable is supported if the dataset supports transactions if (this.ds != null) if (this.ds.supportsTransactions()) return; // Otherwise we'll drop through and throw the error default: throw new SQLException(String.format("The Transaction level %d is not supported by this connection", level)); } } /** * Begins a new transaction * <p> * Transactions are typically thread scoped and are shared by each thread so * if there is an existing read transaction and another thread tries to * start a read transaction it will join the existing read transaction. * Trying to join a transaction not of the same type will produce an error. * </p> * * @param type * @throws SQLException */ public synchronized void begin(ReadWrite type) throws SQLException { try { if (this.isClosed()) throw new SQLException("Cannot start a transaction on a closed connection"); if (this.getTransactionIsolation() == Connection.TRANSACTION_NONE) throw new SQLException("Cannot start a transaction when transaction isolation is set to NONE"); if (ds.supportsTransactions()) { if (ds.isInTransaction()) { // Additional participant in existing transaction ReadWrite currType = this.transactionType.get(); if (currType.equals(type)) { this.transactionParticipants.set(this.transactionParticipants.get() + 1); } else { throw new SQLException( "Unable to start a transaction of a different type on the same thread as an existing transaction, please retry your operation on a different thread"); } } else { // Starting a new transaction this.transactionType.set(type); this.transactionParticipants.set(1); this.ds.begin(type); } } } catch (SQLException e) { throw e; } catch (Exception e) { throw new SQLException("Unexpected error starting a transaction", e); } } @Override protected synchronized void commitInternal() throws SQLException { try { if (ds.supportsTransactions()) { if (ds.isInTransaction()) { // How many participants are there in this transaction? int participants = this.transactionParticipants.get(); if (participants > 1) { // Transaction should remain active this.transactionParticipants.set(participants - 1); } else { // Now safe to commit ds.commit(); ds.end(); this.transactionParticipants.remove(); this.transactionType.remove(); } } else { throw new SQLException("Attempted to commit a transaction when there was no active transaction"); } } } catch (SQLException e) { throw e; } catch (Exception e) { throw new SQLException("Unexpected error committing the transaction", e); } } @Override protected synchronized void rollbackInternal() throws SQLException { try { if (ds.supportsTransactions()) { if (ds.isInTransaction()) { // Regardless of participants a rollback is always immediate ds.abort(); ds.end(); this.transactionType.remove(); this.transactionParticipants.remove(); } else { throw new SQLException("Attempted to rollback a transaction when there was no active transaction"); } } } catch (SQLException e) { throw e; } catch (Exception e) { throw new SQLException("Unexpected error rolling back the transaction", e); } } }
#!/bin/bash function display_help() { readonly script_name="./$(basename "$0")" echo "This script uploads the documentation and distribution.zip to the filemgmt.jboss.org." echo echo "Usage:" echo " $script_name PROJECT_VERSION SSH_KEY" echo " $script_name --help" } function create_latest_symlinks() { local _working_directory=$1 local _version=$2 pushd "$_working_directory" cd "$_working_directory" ln -s "$_version" latest if [[ "$_version" == *Final* ]]; then ln -s "$_version" latestFinal fi popd } if [[ $1 == "--help" ]]; then display_help exit 0 fi if [[ $# -ne 2 ]]; then echo "Illegal number of arguments." display_help exit 1 fi readonly remote_optaplanner_downloads=optaplanner@filemgmt-prod-sync.jboss.org:/downloads_htdocs/optaplanner readonly remote_optaplanner_docs=optaplanner@filemgmt-prod-sync.jboss.org:/docs_htdocs/optaplanner readonly version=$1 readonly optaplanner_ssh_key=$2 this_script_directory="${BASH_SOURCE%/*}" if [[ ! -d "$this_script_directory" ]]; then this_script_directory="$PWD" fi readonly project_root=$this_script_directory/../.. readonly distribution_zip="$project_root/optaweb-vehicle-routing-distribution/target/optaweb-vehicle-routing-distribution-$version.zip" readonly documentation_zip="$project_root/optaweb-vehicle-routing-docs/target/optaweb-vehicle-routing-docs-$version.zip" if [[ ! -f "$distribution_zip" ]]; then echo "The Optaweb Vehicle Routing distribution does not exist. Please run the maven build." exit 1 fi # Create the directory structure .../release/${version} readonly temp_release_directory=/tmp/optaweb-vehicle-routing-release-$version readonly local_optaplanner_downloads=$temp_release_directory/downloads/release readonly local_optaplanner_docs=$temp_release_directory/docs/release if [ -d "$temp_release_directory" ]; then rm -Rf "$temp_release_directory"; fi mkdir -p "$local_optaplanner_docs/$version/optaweb-vehicle-routing-docs" mkdir -p "$local_optaplanner_downloads/$version" # Upload the distribution.zip. cp "$distribution_zip" "$local_optaplanner_downloads/$version" readonly remote_shell="ssh -p 2222 -i $optaplanner_ssh_key" create_latest_symlinks "$local_optaplanner_downloads" "$version" rsync -a -r -e "$remote_shell" --protocol=28 "$local_optaplanner_downloads/.." "$remote_optaplanner_downloads" # Upload the documentation. unzip -q "$documentation_zip" -d "$local_optaplanner_docs/$version/optaweb-vehicle-routing-docs/" create_latest_symlinks "$local_optaplanner_docs" "$version" rsync -a -r -e "$remote_shell" --protocol=28 "$local_optaplanner_docs/.." "$remote_optaplanner_docs"
import jax import jax.numpy as jnp @jax.jit def _linear(x, y): n = len(x) sum_x = jnp.sum(x) sum_y = jnp.sum(y) sum_xy = jnp.sum(x * y) sum_x_squared = jnp.sum(x ** 2) m = (n * sum_xy - sum_x * sum_y) / (n * sum_x_squared - sum_x ** 2) c = (sum_y - m * sum_x) / n return m, c
var classarmnn_1_1optimizations_1_1_permute_and_batch_to_space_as_depth_to_space_impl = [ [ "Run", "classarmnn_1_1optimizations_1_1_permute_and_batch_to_space_as_depth_to_space_impl.xhtml#a5a8476ffc04ce7460bb09ad50d1d23de", null ] ];
export { default } from "./FilterSliderBank.jsx";
#!/bin/sh export DIR_DATA_PATH="$PWD" export CONTAINER_COMMAND="npm run start:dev" export CONTAINER_SCALE="1" export APP_PORT="7070" export CONTAINER_PORT="3000" export GQL_PLAYGROUND="true" docker-compose up --build
<reponame>Remolten/ld33<filename>assets/js/ecs/components.js var components = {}; var Component = {}; Component.prototype = {}; var Sprite = {}; Sprite.prototype = Object.create(Component.prototype); Sprite.prototype.id = 'sprite'; Sprite.prototype.init = function(x, y, img, frm) { this.sprite = game.add.sprite(x, y, img, frm || 0); }; components[Sprite.id] = Sprite.prototype; var Controllable = {}; Controllable.prototype = Object.create(Component.prototype); Controllable.prototype.id = 'controllable'; Controllable.prototype.init = function(cntrl) { this.controllable = cntrl; }; components[Controllable.id] = Controllable.prototype; var Speed = {}; Speed.prototype = Object.create(Component.prototype); Speed.prototype.id = 'speed'; Speed.prototype.init = function(spd) { this.speed = spd; }; components[Speed.id] = Speed.prototype;
<filename>core/impl/service/types.go /* * Copyright © 2019 <NAME>. */ package service import ( "context" "github.com/golang/protobuf/proto" "github.com/hedzr/voxr-api/api/v10" "github.com/labstack/echo" ) const ( LoginMethod = "Login" RefreshTokenMethod = "RefreshToken" ) type ( BuildInf struct { Entry string svc, pkg, pbsvc string FuncName string // grpc 调用函数名 preparingInputParam func(ctx echo.Context) (proto.Message, error) // 从RESTful请求中抽出参数形成grpc调用入参 realResultTemplate func() (out proto.Message) // 生成一个空白的结果类型,被用于 pbtypes.UnmarshalAny wrappedResult bool // true 如果接口返回类型为 v10.Result. onEverythingOk func(ret proto.Message) // restful 如需后处理返回消息的话,提供 onEverythinOk; grpc 调用时,等待返回消息抵达并作为返回值,故无需 onEverythingOk } FwdrFunc func(ctx context.Context, in proto.Message) (res proto.Message, err error) NotifiedUsers struct { ConversationId uint64 ConversationSection uint32 MsgId uint64 Users []uint64 TS int64 SortNum uint64 } Hooker interface { OnMessageSaveDone(ret proto.Message) } ) var ( // allow 500 messages buffered in UsersNeedNotified queue. UsersNeedNotified = make(chan *NotifiedUsers, 500) ) func (s *BuildInf) Result() proto.Message { if s.wrappedResult { return nil } return s.realResultTemplate() } func MakeNotifiedUsersFromNotifyMessage(uid uint64, nm *v10.NotifyMessage) (ret *NotifiedUsers) { if nm.ProtoOp == v10.Op_NotifyAck { tp := nm.GetTalking() if tp != nil { ret = MakeNotifiedUsersFromTalkingPush(uid, tp) } } return } func MakeNotifiedUsersFromTalkingPush(uid uint64, tp *v10.TalkingPush) (ret *NotifiedUsers) { ret = new(NotifiedUsers) ret.ConversationId = tp.SubscribeId ret.ConversationSection = tp.ConversationSection if len(tp.MsgIds) > 0 { ret.MsgId = tp.MsgIds[0] } ret.SortNum = tp.SortNum ret.Users = make([]uint64, 1) ret.Users[0] = uint64(uid) ret.TS = tp.Ts return } // MakeNotifiedUsers prepares a NotifiedUsers structure from storage.SaveMessageResponse{} func MakeNotifiedUsers(rr *v10.SaveMessageResponse) (ret *NotifiedUsers) { ret = new(NotifiedUsers) ret.ConversationId = rr.ConversationId ret.ConversationSection = rr.ConversationSection ret.MsgId = uint64(rr.MsgId) ret.SortNum = rr.SortNum ret.Users = make([]uint64, len(rr.ReceiveUserList)) for i, uid := range rr.ReceiveUserList { ret.Users[i] = uint64(uid) } ret.TS = rr.MsgTime // api.Int64ToTimestamp(rr.MsgTime) return }
#!/bin/bash #Running Database scripts for WSO2-IS echo "Running DB scripts for WSO2-IS..." #Define parameter values for Database Engine and Version DB_ENGINE='CF_DBMS_NAME' DB_ENGINE_VERSION='CF_DBMS_VERSION' WSO2_PRODUCT_VERSION='CF_PRODUCT_VERSION' USE_CONSENT_DB=false #Select product version if [ $WSO2_PRODUCT_VERSION = "5.2.0" ]; then WSO2_PRODUCT_VERSION_SHORT=is520 elif [ $WSO2_PRODUCT_VERSION = "5.3.0" ]; then WSO2_PRODUCT_VERSION_SHORT=is530 elif [ $WSO2_PRODUCT_VERSION = "5.4.0" ]; then WSO2_PRODUCT_VERSION_SHORT=is540 elif [ $WSO2_PRODUCT_VERSION = "5.4.1" ]; then WSO2_PRODUCT_VERSION_SHORT=is541 elif [ $WSO2_PRODUCT_VERSION = "5.5.0" ]; then WSO2_PRODUCT_VERSION_SHORT=is550 USE_CONSENT_DB=true elif [ $WSO2_PRODUCT_VERSION = "5.6.0" ]; then WSO2_PRODUCT_VERSION_SHORT=is560 USE_CONSENT_DB=true elif [ $WSO2_PRODUCT_VERSION = "5.7.0" ]; then WSO2_PRODUCT_VERSION_SHORT=is570 USE_CONSENT_DB=true fi #Run database scripts for given database engine and product version if [[ $DB_ENGINE = "postgres" ]]; then # DB Engine : Postgres echo "Postgres DB Engine Selected! Running WSO2-IS $WSO2_PRODUCT_VERSION DB Scripts for Postgres..." export PGPASSWORD=CF_DB_PASSWORD psql -U CF_DB_USERNAME -h CF_DB_HOST -p CF_DB_PORT -d postgres -f /home/ubuntu/is/$WSO2_PRODUCT_VERSION_SHORT/is_postgres.sql elif [[ $DB_ENGINE = "mysql" ]]; then # DB Engine : MySQL echo "MySQL DB Engine Selected! Running WSO2-IS $WSO2_PRODUCT_VERSION DB Scripts for MySQL..." if [[ $DB_ENGINE_VERSION = "5.7" ]]; then mysql -u CF_DB_USERNAME -pCF_DB_PASSWORD -h CF_DB_HOST -P CF_DB_PORT < /home/ubuntu/is/$WSO2_PRODUCT_VERSION_SHORT/is_mysql5.7.sql else mysql -u CF_DB_USERNAME -pCF_DB_PASSWORD -h CF_DB_HOST -P CF_DB_PORT < /home/ubuntu/is/$WSO2_PRODUCT_VERSION_SHORT/is_mysql.sql fi elif [[ $DB_ENGINE =~ 'oracle-se' ]]; then # DB Engine : Oracle echo "Oracle DB Engine Selected! Running WSO2-IS $WSO2_PRODUCT_VERSION DB Scripts for Oracle..." # Create users to the required DB echo "DECLARE USER_EXIST INTEGER;"$'\n'"BEGIN SELECT COUNT(*) INTO USER_EXIST FROM dba_users WHERE username='WSO2IS_REG_DB';"$'\n'"IF (USER_EXIST > 0) THEN EXECUTE IMMEDIATE 'DROP USER WSO2IS_REG_DB CASCADE';"$'\n'"END IF;"$'\n'"END;"$'\n'"/" >> /home/ubuntu/is/$WSO2_PRODUCT_VERSION_SHORT/is_oracle.sql echo "DECLARE USER_EXIST INTEGER;"$'\n'"BEGIN SELECT COUNT(*) INTO USER_EXIST FROM dba_users WHERE username='WSO2IS_BPS_DB';"$'\n'"IF (USER_EXIST > 0) THEN EXECUTE IMMEDIATE 'DROP USER WSO2IS_BPS_DB CASCADE';"$'\n'"END IF;"$'\n'"END;"$'\n'"/" >> /home/ubuntu/is/$WSO2_PRODUCT_VERSION_SHORT/is_oracle.sql echo "DECLARE USER_EXIST INTEGER;"$'\n'"BEGIN SELECT COUNT(*) INTO USER_EXIST FROM dba_users WHERE username='WSO2IS_USER_DB';"$'\n'"IF (USER_EXIST > 0) THEN EXECUTE IMMEDIATE 'DROP USER WSO2IS_USER_DB CASCADE';"$'\n'"END IF;"$'\n'"END;"$'\n'"/" >> /home/ubuntu/is/$WSO2_PRODUCT_VERSION_SHORT/is_oracle.sql echo "DECLARE USER_EXIST INTEGER;"$'\n'"BEGIN SELECT COUNT(*) INTO USER_EXIST FROM dba_users WHERE username='WSO2IS_IDENTITY_DB';"$'\n'"IF (USER_EXIST > 0) THEN EXECUTE IMMEDIATE 'DROP USER WSO2IS_IDENTITY_DB CASCADE';"$'\n'"END IF;"$'\n'"END;"$'\n'"/" >> /home/ubuntu/is/$WSO2_PRODUCT_VERSION_SHORT/is_oracle.sql echo "DECLARE USER_EXIST INTEGER;"$'\n'"BEGIN SELECT COUNT(*) INTO USER_EXIST FROM dba_users WHERE username='WSO2IS_CONSENT_DB';"$'\n'"IF (USER_EXIST > 0) THEN EXECUTE IMMEDIATE 'DROP USER WSO2IS_CONSENT_DB CASCADE';"$'\n'"END IF;"$'\n'"END;"$'\n'"/" >> /home/ubuntu/is/$WSO2_PRODUCT_VERSION_SHORT/is_oracle.sql echo "CREATE USER WSO2IS_REG_DB IDENTIFIED BY CF_DB_PASSWORD;"$'\n'"GRANT CONNECT, RESOURCE, DBA TO WSO2IS_REG_DB;"$'\n'"GRANT UNLIMITED TABLESPACE TO WSO2IS_REG_DB;" >> /home/ubuntu/is/$WSO2_PRODUCT_VERSION_SHORT/is_oracle.sql echo "CREATE USER WSO2IS_BPS_DB IDENTIFIED BY CF_DB_PASSWORD;"$'\n'"GRANT CONNECT, RESOURCE, DBA TO WSO2IS_BPS_DB;"$'\n'"GRANT UNLIMITED TABLESPACE TO WSO2IS_BPS_DB;" >> /home/ubuntu/is/$WSO2_PRODUCT_VERSION_SHORT/is_oracle.sql echo "CREATE USER WSO2IS_USER_DB IDENTIFIED BY CF_DB_PASSWORD;"$'\n'"GRANT CONNECT, RESOURCE, DBA TO WSO2IS_USER_DB;"$'\n'"GRANT UNLIMITED TABLESPACE TO WSO2IS_USER_DB;" >> /home/ubuntu/is/$WSO2_PRODUCT_VERSION_SHORT/is_oracle.sql echo "CREATE USER WSO2IS_IDENTITY_DB IDENTIFIED BY CF_DB_PASSWORD;"$'\n'"GRANT CONNECT, RESOURCE, DBA TO WSO2IS_IDENTITY_DB;"$'\n'"GRANT UNLIMITED TABLESPACE TO WSO2IS_IDENTITY_DB;" >> /home/ubuntu/is/$WSO2_PRODUCT_VERSION_SHORT/is_oracle.sql echo "CREATE USER WSO2IS_CONSENT_DB IDENTIFIED BY CF_DB_PASSWORD;"$'\n'"GRANT CONNECT, RESOURCE, DBA TO WSO2IS_CONSENT_DB;"$'\n'"GRANT UNLIMITED TABLESPACE TO WSO2IS_CONSENT_DB;" >> /home/ubuntu/is/$WSO2_PRODUCT_VERSION_SHORT/is_oracle.sql # Create the tables echo exit | sqlplus64 CF_DB_USERNAME/CF_DB_PASSWORD@//CF_DB_HOST:CF_DB_PORT/WSO2ISDB @/home/ubuntu/is/$WSO2_PRODUCT_VERSION_SHORT/is_oracle.sql echo exit | sqlplus64 WSO2IS_REG_DB/CF_DB_PASSWORD@//CF_DB_HOST:CF_DB_PORT/WSO2ISDB @/home/ubuntu/is/$WSO2_PRODUCT_VERSION_SHORT/is_oracle_common.sql echo exit | sqlplus64 WSO2IS_BPS_DB/CF_DB_PASSWORD@//CF_DB_HOST:CF_DB_PORT/WSO2ISDB @/home/ubuntu/is/$WSO2_PRODUCT_VERSION_SHORT/is_oracle_bps.sql echo exit | sqlplus64 WSO2IS_USER_DB/CF_DB_PASSWORD@//CF_DB_HOST:CF_DB_PORT/WSO2ISDB @/home/ubuntu/is/$WSO2_PRODUCT_VERSION_SHORT/is_oracle_common.sql echo exit | sqlplus64 WSO2IS_IDENTITY_DB/CF_DB_PASSWORD@//CF_DB_HOST:CF_DB_PORT/WSO2ISDB @/home/ubuntu/is/$WSO2_PRODUCT_VERSION_SHORT/is_oracle_identity.sql if $USE_CONSENT_DB; then echo exit | sqlplus64 WSO2IS_CONSENT_DB/CF_DB_PASSWORD@//CF_DB_HOST:CF_DB_PORT/WSO2ISDB @/home/ubuntu/is/$WSO2_PRODUCT_VERSION_SHORT/is_oracle_consent.sql else echo exit | sqlplus64 WSO2IS_CONSENT_DB/CF_DB_PASSWORD@//CF_DB_HOST:CF_DB_PORT/WSO2ISDB @/home/ubuntu/is/$WSO2_PRODUCT_VERSION_SHORT/is_oracle_common.sql fi elif [[ $DB_ENGINE =~ 'sqlserver-se' ]]; then # DB Engine : SQLServer echo "SQL Server DB Engine Selected! Running WSO2-IS $WSO2_PRODUCT_VERSION DB Scripts for SQL Server..." sqlcmd -S CF_DB_HOST -U CF_DB_USERNAME -P CF_DB_PASSWORD -i /home/ubuntu/is/$WSO2_PRODUCT_VERSION_SHORT/is_mssql.sql fi
import type { IncomingMessage, ServerResponse } from "http"; import { assertMethod, useBody } from "h3"; import axios, { AxiosError } from "axios"; import config from "#config"; import _ from "lodash"; const defaultQuery = ` query ($groupId: ID) { group(id: $groupId) { id name description link logo { baseUrl id } memberships { count } upcomingEvents(input: {}) { edges { node { id title eventUrl description eventType venue { name address city state postalCode } dateTime going image { baseUrl id } } } } } }`; export default async (req: IncomingMessage, res: ServerResponse) => { assertMethod(req, "POST"); const body = (await useBody(req)) || {}; body.query ||= defaultQuery; body.variables = _.defaults(body.variables || {}, { groupId: config.MEETUP_GROUP_ID, }); try { return (await axios.post(config.MEETUP_GQL, body)).data; } catch (_e) { const err: AxiosError = _e; res.statusCode = err.response.status; return err.response.data; } };
// generated from rosidl_generator_c/resource/idl__functions.c.em // with input from policy_translation:srv/NetworkPT.idl // generated code does not contain a copyright notice #include "policy_translation/srv/network_pt__functions.h" #include <assert.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> // Include directives for member types // Member `image` #include "sensor_msgs/msg/image__functions.h" // Member `language` #include "rosidl_generator_c/string_functions.h" // Member `robot` #include "rosidl_generator_c/primitives_sequence_functions.h" bool policy_translation__srv__NetworkPT_Request__init(policy_translation__srv__NetworkPT_Request * msg) { if (!msg) { return false; } // image if (!sensor_msgs__msg__Image__init(&msg->image)) { policy_translation__srv__NetworkPT_Request__fini(msg); return false; } // language if (!rosidl_generator_c__String__init(&msg->language)) { policy_translation__srv__NetworkPT_Request__fini(msg); return false; } // robot if (!rosidl_generator_c__float__Sequence__init(&msg->robot, 0)) { policy_translation__srv__NetworkPT_Request__fini(msg); return false; } // reset // plot return true; } void policy_translation__srv__NetworkPT_Request__fini(policy_translation__srv__NetworkPT_Request * msg) { if (!msg) { return; } // image sensor_msgs__msg__Image__fini(&msg->image); // language rosidl_generator_c__String__fini(&msg->language); // robot rosidl_generator_c__float__Sequence__fini(&msg->robot); // reset // plot } policy_translation__srv__NetworkPT_Request * policy_translation__srv__NetworkPT_Request__create() { policy_translation__srv__NetworkPT_Request * msg = (policy_translation__srv__NetworkPT_Request *)malloc(sizeof(policy_translation__srv__NetworkPT_Request)); if (!msg) { return NULL; } memset(msg, 0, sizeof(policy_translation__srv__NetworkPT_Request)); bool success = policy_translation__srv__NetworkPT_Request__init(msg); if (!success) { free(msg); return NULL; } return msg; } void policy_translation__srv__NetworkPT_Request__destroy(policy_translation__srv__NetworkPT_Request * msg) { if (msg) { policy_translation__srv__NetworkPT_Request__fini(msg); } free(msg); } bool policy_translation__srv__NetworkPT_Request__Sequence__init(policy_translation__srv__NetworkPT_Request__Sequence * array, size_t size) { if (!array) { return false; } policy_translation__srv__NetworkPT_Request * data = NULL; if (size) { data = (policy_translation__srv__NetworkPT_Request *)calloc(size, sizeof(policy_translation__srv__NetworkPT_Request)); if (!data) { return false; } // initialize all array elements size_t i; for (i = 0; i < size; ++i) { bool success = policy_translation__srv__NetworkPT_Request__init(&data[i]); if (!success) { break; } } if (i < size) { // if initialization failed finalize the already initialized array elements for (; i > 0; --i) { policy_translation__srv__NetworkPT_Request__fini(&data[i - 1]); } free(data); return false; } } array->data = data; array->size = size; array->capacity = size; return true; } void policy_translation__srv__NetworkPT_Request__Sequence__fini(policy_translation__srv__NetworkPT_Request__Sequence * array) { if (!array) { return; } if (array->data) { // ensure that data and capacity values are consistent assert(array->capacity > 0); // finalize all array elements for (size_t i = 0; i < array->capacity; ++i) { policy_translation__srv__NetworkPT_Request__fini(&array->data[i]); } free(array->data); array->data = NULL; array->size = 0; array->capacity = 0; } else { // ensure that data, size, and capacity values are consistent assert(0 == array->size); assert(0 == array->capacity); } } policy_translation__srv__NetworkPT_Request__Sequence * policy_translation__srv__NetworkPT_Request__Sequence__create(size_t size) { policy_translation__srv__NetworkPT_Request__Sequence * array = (policy_translation__srv__NetworkPT_Request__Sequence *)malloc(sizeof(policy_translation__srv__NetworkPT_Request__Sequence)); if (!array) { return NULL; } bool success = policy_translation__srv__NetworkPT_Request__Sequence__init(array, size); if (!success) { free(array); return NULL; } return array; } void policy_translation__srv__NetworkPT_Request__Sequence__destroy(policy_translation__srv__NetworkPT_Request__Sequence * array) { if (array) { policy_translation__srv__NetworkPT_Request__Sequence__fini(array); } free(array); } // Include directives for member types // Member `trajectory` // Member `confidence` // Member `weights` // already included above // #include "rosidl_generator_c/primitives_sequence_functions.h" bool policy_translation__srv__NetworkPT_Response__init(policy_translation__srv__NetworkPT_Response * msg) { if (!msg) { return false; } // trajectory if (!rosidl_generator_c__float__Sequence__init(&msg->trajectory, 0)) { policy_translation__srv__NetworkPT_Response__fini(msg); return false; } // confidence if (!rosidl_generator_c__float__Sequence__init(&msg->confidence, 0)) { policy_translation__srv__NetworkPT_Response__fini(msg); return false; } // timesteps // weights if (!rosidl_generator_c__float__Sequence__init(&msg->weights, 0)) { policy_translation__srv__NetworkPT_Response__fini(msg); return false; } // phase return true; } void policy_translation__srv__NetworkPT_Response__fini(policy_translation__srv__NetworkPT_Response * msg) { if (!msg) { return; } // trajectory rosidl_generator_c__float__Sequence__fini(&msg->trajectory); // confidence rosidl_generator_c__float__Sequence__fini(&msg->confidence); // timesteps // weights rosidl_generator_c__float__Sequence__fini(&msg->weights); // phase } policy_translation__srv__NetworkPT_Response * policy_translation__srv__NetworkPT_Response__create() { policy_translation__srv__NetworkPT_Response * msg = (policy_translation__srv__NetworkPT_Response *)malloc(sizeof(policy_translation__srv__NetworkPT_Response)); if (!msg) { return NULL; } memset(msg, 0, sizeof(policy_translation__srv__NetworkPT_Response)); bool success = policy_translation__srv__NetworkPT_Response__init(msg); if (!success) { free(msg); return NULL; } return msg; } void policy_translation__srv__NetworkPT_Response__destroy(policy_translation__srv__NetworkPT_Response * msg) { if (msg) { policy_translation__srv__NetworkPT_Response__fini(msg); } free(msg); } bool policy_translation__srv__NetworkPT_Response__Sequence__init(policy_translation__srv__NetworkPT_Response__Sequence * array, size_t size) { if (!array) { return false; } policy_translation__srv__NetworkPT_Response * data = NULL; if (size) { data = (policy_translation__srv__NetworkPT_Response *)calloc(size, sizeof(policy_translation__srv__NetworkPT_Response)); if (!data) { return false; } // initialize all array elements size_t i; for (i = 0; i < size; ++i) { bool success = policy_translation__srv__NetworkPT_Response__init(&data[i]); if (!success) { break; } } if (i < size) { // if initialization failed finalize the already initialized array elements for (; i > 0; --i) { policy_translation__srv__NetworkPT_Response__fini(&data[i - 1]); } free(data); return false; } } array->data = data; array->size = size; array->capacity = size; return true; } void policy_translation__srv__NetworkPT_Response__Sequence__fini(policy_translation__srv__NetworkPT_Response__Sequence * array) { if (!array) { return; } if (array->data) { // ensure that data and capacity values are consistent assert(array->capacity > 0); // finalize all array elements for (size_t i = 0; i < array->capacity; ++i) { policy_translation__srv__NetworkPT_Response__fini(&array->data[i]); } free(array->data); array->data = NULL; array->size = 0; array->capacity = 0; } else { // ensure that data, size, and capacity values are consistent assert(0 == array->size); assert(0 == array->capacity); } } policy_translation__srv__NetworkPT_Response__Sequence * policy_translation__srv__NetworkPT_Response__Sequence__create(size_t size) { policy_translation__srv__NetworkPT_Response__Sequence * array = (policy_translation__srv__NetworkPT_Response__Sequence *)malloc(sizeof(policy_translation__srv__NetworkPT_Response__Sequence)); if (!array) { return NULL; } bool success = policy_translation__srv__NetworkPT_Response__Sequence__init(array, size); if (!success) { free(array); return NULL; } return array; } void policy_translation__srv__NetworkPT_Response__Sequence__destroy(policy_translation__srv__NetworkPT_Response__Sequence * array) { if (array) { policy_translation__srv__NetworkPT_Response__Sequence__fini(array); } free(array); }
class Reason: def __init__(self, name): self.name = name def get_reason_name(self): return self.name # Example usage reason = Reason("Invalid input") print(reason.get_reason_name()) # This will print "Invalid input"
<filename>croslog/log_line_reader.cc // Copyright 2020 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "croslog/log_line_reader.h" #include <algorithm> #include <string> #include <utility> #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> #include "base/bind.h" #include "base/files/file.h" #include "base/files/file_util.h" #include "base/strings/string_util.h" #include "croslog/file_map_reader.h" namespace croslog { namespace { // Maximum length of line in bytes. static int64_t g_max_line_length = 1024 * 1024; } // namespace // static void LogLineReader::SetMaxLineLengthForTest(int64_t max_line_length) { CHECK_LE(max_line_length, FileMapReader::GetChunkSizeInBytes()); CHECK_GE(max_line_length, 0); g_max_line_length = max_line_length; } LogLineReader::LogLineReader(Backend backend_mode) : backend_mode_(backend_mode) { // Checks the assumption of this logic. DCHECK_GE(FileMapReader::GetChunkSizeInBytes(), g_max_line_length); } LogLineReader::~LogLineReader() { if (file_change_watcher_) file_change_watcher_->RemoveWatch(file_path_); } void LogLineReader::OpenFile(const base::FilePath& file_path) { CHECK(backend_mode_ == Backend::FILE || backend_mode_ == Backend::FILE_FOLLOW); // Ensure the values are not initialized. CHECK(file_path_.empty()); file_ = base::File(file_path, base::File::FLAG_OPEN | base::File::FLAG_READ); if (!file_.IsValid()) { LOG(ERROR) << "Could not open " << file_path; return; } file_path_ = file_path; pos_ = 0; // TODO(yoshiki): Use stat_wrapper_t and File::FStat after libchrome uprev. struct stat file_stat; if (fstat(file_.GetPlatformFile(), &file_stat) == 0) file_inode_ = file_stat.st_ino; DCHECK_NE(0, file_inode_); if (backend_mode_ == Backend::FILE_FOLLOW) { // Race may happen when the file rotates just after file opens. // TODO(yoshiki): detect the race. Maybe we can use /proc/self/fd/$fd. file_change_watcher_ = FileChangeWatcher::GetInstance(); bool ret = file_change_watcher_->AddWatch(file_path_, this); if (!ret) { LOG(ERROR) << "Failed to install FileChangeWatcher for " << file_path_ << "."; file_change_watcher_ = nullptr; } } reader_ = FileMapReader::CreateReader(file_.Duplicate()); } void LogLineReader::OpenMemoryBufferForTest(const char* buffer, size_t size) { CHECK(backend_mode_ == Backend::MEMORY_FOR_TEST); reader_ = FileMapReader::CreateFileMapReaderDelegateImplMemoryReaderForTest( (const uint8_t*)buffer, size); } void LogLineReader::SetPositionLast() { // At first, sets the position to EOF. pos_ = reader_->GetFileSize(); DCHECK_LE(0, pos_); // Calculates the maximum traversable range in the file and allocate a buffer. int64_t pos_traversal_start = std::max(pos_ - g_max_line_length, INT64_C(0)); int64_t traversal_length = std::min(g_max_line_length, pos_); // Allocates a buffer of the segment from |pos_traversal_start| to EOF. auto buffer = reader_->MapBuffer(pos_traversal_start, traversal_length); CHECK(buffer->valid()) << "Mmap failed. Maybe the file has been truncated."; // Traverses in reverse order to find the last LF. while (pos_ > pos_traversal_start && buffer->GetChar(pos_ - 1) != '\n') pos_--; if (pos_ != 0 && pos_ <= pos_traversal_start) { LOG(ERROR) << "The last line is too long to handle (more than: " << g_max_line_length << "bytes). Lines around here may be broken."; // Sets the position to the last as a sloppy solution. pos_ = reader_->GetFileSize(); } } // Ensure the file path is initialized. void LogLineReader::ReloadRotatedFile() { CHECK(backend_mode_ == Backend::FILE_FOLLOW); DCHECK(rotated_); DCHECK(PathExists(file_path_)); rotated_ = false; CHECK(file_change_watcher_); file_change_watcher_->RemoveWatch(file_path_); base::FilePath file_path = file_path_; file_path_.clear(); reader_.reset(); file_inode_ = 0; pos_ = 0; OpenFile(file_path); if (!file_.IsValid()) { LOG(FATAL) << "File looks rotated, but new file can't be opened."; } reader_ = FileMapReader::CreateReader(file_.Duplicate()); } base::Optional<std::string> LogLineReader::Forward() { DCHECK_LE(0, pos_); // Checks the current position is at the beginning of the line. if (pos_ != 0) { auto buffer = reader_->MapBuffer(pos_ - 1, 1); CHECK(buffer->valid()) << "Mmap failed. Maybe the file has been truncated" << " and the current read position got invalid."; if (buffer->GetChar(pos_ - 1) != '\n') { LOG(WARNING) << "The line is odd. The line is too long or the file is" << " unexpectedly changed."; } } // Calculate the maximum traversable size to allocate. int64_t traversal_length = std::min(g_max_line_length, reader_->GetFileSize() - pos_); int64_t pos_traversal_end = pos_ + traversal_length; // Allocates a buffer of the segment from |pos_| to |pos_traversal_end|. auto buffer = reader_->MapBuffer(pos_, traversal_length); CHECK(buffer->valid()) << "Mmap failed. Maybe the file has been truncated" << " and the current read position got invalid."; // Finds the next LF (end of line). int64_t pos_line_end = pos_; while (pos_line_end < pos_traversal_end && buffer->GetChar(pos_line_end) != '\n') { pos_line_end++; } if (pos_line_end == reader_->GetFileSize()) { // Reaches EOF without '\n'. int64_t unread_length = reader_->GetFileSize() - pos_; if (rotated_ && unread_length == 0 && PathExists(file_path_)) { // Free the mapped buffer so that another buffer map is allowed. buffer.reset(); ReloadRotatedFile(); return Forward(); } // If next file doesn't exist, leave the remaining string. // If next file exists, read the remaining string. if (!rotated_) return base::nullopt; pos_line_end = reader_->GetFileSize(); } else if (pos_line_end == (pos_ + g_max_line_length)) { LOG(ERROR) << "A line is too long to handle (more than " << g_max_line_length << "bytes). Lines around here may be broken."; } // Updates the current position. int64_t pos_line_start = pos_; int64_t line_length = pos_line_end - pos_; pos_ = pos_line_end; if (pos_ < reader_->GetFileSize()) { // Unless the line is too long, proceed the LF. if (buffer->GetChar(pos_) == '\n') pos_ += 1; } return GetString(std::move(buffer), pos_line_start, line_length); } base::Optional<std::string> LogLineReader::Backward() { DCHECK_LE(0, pos_); if (pos_ == 0) return base::nullopt; // Calculates the maximum traversable range in the file and allocate a buffer. int64_t pos_traversal_start = std::max(pos_ - g_max_line_length, INT64_C(0)); int64_t traversal_length = pos_ - pos_traversal_start; DCHECK_GE(traversal_length, 0); // Allocates a buffer of the segment from |pos_traversal_start| to |pos_|. auto buffer = reader_->MapBuffer(pos_traversal_start, traversal_length); CHECK(buffer->valid()) << "Mmap failed. Maybe the file has been truncated" << " and the current read position got invalid."; // Ensures the current position is the beginning of the previous line. if (buffer->GetChar(pos_ - 1) != '\n') { LOG(WARNING) << "The line is too long or the file is unexpectedly changed." << " The lines read may be broken."; } // Finds the next LF (at the beginning of the line). int64_t last_start = pos_ - 1; while (last_start > pos_traversal_start && buffer->GetChar(last_start - 1) != '\n') { last_start--; } // Ensures the next LF is found. if (last_start != 0 && last_start <= pos_traversal_start) { LOG(ERROR) << "A line is too long to handle (more than " << g_max_line_length << "bytes). Lines around here may be broken."; } // Updates the current position. int64_t line_length = pos_ - last_start - 1; pos_ = last_start; return GetString(std::move(buffer), last_start, line_length); } void LogLineReader::AddObserver(Observer* obs) { observers_.AddObserver(obs); } void LogLineReader::RemoveObserver(Observer* obs) { observers_.RemoveObserver(obs); } std::string LogLineReader::GetString( std::unique_ptr<FileMapReader::MappedBuffer> mapped_buffer, uint64_t offset, uint64_t length) const { std::pair<const uint8_t*, size_t> buffer = mapped_buffer->GetBuffer(offset, length); return std::string(reinterpret_cast<const char*>(buffer.first), buffer.second); } void LogLineReader::OnFileContentMaybeChanged() { CHECK(backend_mode_ == Backend::FILE_FOLLOW); CHECK(file_.IsValid()); // We didn't consider the case of content change without size change. It // shouldn't happen with normal log files. // Previous file size at (or shortly before) the previous mmap. const int64_t previous_file_size = reader_->GetFileSize(); // Current file size read from the file system. const int64_t current_file_size = file_.GetLength(); if (previous_file_size != current_file_size) { reader_->ApplyFileSizeExpansion(); for (Observer& obs : observers_) obs.OnFileChanged(this); } } void LogLineReader::OnFileNameMaybeChanged() { CHECK(backend_mode_ == Backend::FILE_FOLLOW); if (rotated_) return; if (!PathExists(file_path_)) { rotated_ = true; } else { // TODO(yoshiki): Use stat_wrapper_t and File::Stat after libchrome uprev. struct stat file_stat; bool inode_changed = ((stat(file_path_.value().c_str(), &file_stat) == 0) && (file_inode_ != file_stat.st_ino)); if (inode_changed) rotated_ = true; } if (rotated_) { for (Observer& obs : observers_) obs.OnFileChanged(this); } } } // namespace croslog
<filename>cplusplus/FuelSpent.cpp #include <iostream> class FuelSpent{ private: const static float km_l; int time_spent; int average_velocity; public: //constructor FuelSpent(); FuelSpent(int, int); //Functions float computeLitersHour(); }; const float FuelSpent::km_l = 12; FuelSpent::FuelSpent(){} FuelSpent::FuelSpent(int time, int velocity):time_spent{time},average_velocity{velocity}{ } float FuelSpent::computeLitersHour(){ return time_spent*average_velocity/FuelSpent::km_l; } int main(){ int a, b; std::cin >> a >> b; FuelSpent fs(a, b); printf("%.3f\n",fs.computeLitersHour()); return 0; }
kubectl get nodes cd ~/hello-kubernetes/ git status git remote -v echo $JENKINS_HOOK_URL echo $GIT_REPO_URL
<filename>traveldb/oracle/dbe_tdbsp.sql /*D************************************************************/ /* project: travelDB stored procedures for DataSet */ /* upd/del/ins */ /* ATTENTION !! types are hardcoded here !!! */ /* see tdb_tabletypes.xml */ /* */ /* copyright: yafra.org, Switzerland, 2004 */ /**************************************************************/ /* RCS Information: */ /* $Header: /yafra/cvstdbadmin/mapo/db/oracle/dbe_tdbsp.sql,v 1.1 2004-03-28 22:31:53 mwn Exp $ */ /* check for mpstadef.h and mpobjdef.h for codes */ -- //// Insert Stored Procedure. CREATE OR REPLACE PROCEDURE "TDBADMIN"."TDB_INSPROF" ( p_MPID IN MP_PROFIL.MPID%TYPE, p_MPUSER IN MP_PROFIL.MPUSER%TYPE, p_BCHST IN MP_PROFIL.BCHST%TYPE, p_SECLEVEL IN MP_PROFIL.SECLEVEL%TYPE, p_S_ID IN MP_PROFIL.S_ID%TYPE, p_LAND_ID IN MP_PROFIL.LAND_ID%TYPE, p_DLTT_ID IN MP_PROFIL.DLTT_ID%TYPE, p_DLT_ID IN MP_PROFIL.DLT_ID%TYPE, p_KAT_ID IN MP_PROFIL.KAT_ID%TYPE, p_DLAT_ID IN MP_PROFIL.DLAT_ID%TYPE, p_DLNT_ID IN MP_PROFIL.DLNT_ID%TYPE, p_SAI_ID IN MP_PROFIL.SAI_ID%TYPE, p_PRG_ID IN MP_PROFIL.PRG_ID%TYPE, p_A_ZEIT IN MP_PROFIL.A_ZEIT%TYPE, p_E_ZEIT IN MP_PROFIL.E_ZEIT%TYPE, p_P_RANGE IN MP_PROFIL.P_RANGE%TYPE ) AS BEGIN insert into MP_PROFIL ( MPID, MPUSER, BCHST, SECLEVEL, S_ID, LAND_ID, DLTT_ID, DLT_ID, KAT_ID, DLAT_ID, DLNT_ID, SAI_ID, PRG_ID, A_ZEIT, E_ZEIT, P_RANGE ) values ( p_MPID, p_MPUSER, p_BCHST, p_SECLEVEL, p_S_ID, p_LAND_ID, p_DLTT_ID, p_DLT_ID, p_KAT_ID, p_DLAT_ID, p_DLNT_ID, p_SAI_ID, p_PRG_ID, p_A_ZEIT, p_E_ZEIT, p_P_RANGE ); END; -- //// Update Stored Procedure Based On Primary Key. create or replace PROCEDURE "TDBADMIN"."TDB_UPDPROF" ( p_MPID IN MP_PROFIL.MPID%TYPE, p_MPUSER IN MP_PROFIL.MPUSER%TYPE, p_BCHST IN MP_PROFIL.BCHST%TYPE, p_SECLEVEL IN MP_PROFIL.SECLEVEL%TYPE, p_S_ID IN MP_PROFIL.S_ID%TYPE, p_LAND_ID IN MP_PROFIL.LAND_ID%TYPE, p_DLTT_ID IN MP_PROFIL.DLTT_ID%TYPE, p_DLT_ID IN MP_PROFIL.DLT_ID%TYPE, p_KAT_ID IN MP_PROFIL.KAT_ID%TYPE, p_DLAT_ID IN MP_PROFIL.DLAT_ID%TYPE, p_DLNT_ID IN MP_PROFIL.DLNT_ID%TYPE, p_SAI_ID IN MP_PROFIL.SAI_ID%TYPE, p_PRG_ID IN MP_PROFIL.PRG_ID%TYPE, p_A_ZEIT IN MP_PROFIL.A_ZEIT%TYPE, p_E_ZEIT IN MP_PROFIL.E_ZEIT%TYPE, p_P_RANGE IN MP_PROFIL.P_RANGE%TYPE ) AS BEGIN update MP_PROFIL set MPUSER = p_MPUSER, BCHST = p_BCHST, SECLEVEL = p_SECLEVEL, S_ID = p_S_ID, LAND_ID = p_LAND_ID, DLTT_ID = p_DLTT_ID, DLT_ID = p_DLT_ID, KAT_ID = p_KAT_ID, DLAT_ID = p_DLAT_ID, DLNT_ID = p_DLNT_ID, SAI_ID = p_SAI_ID, PRG_ID = p_PRG_ID, A_ZEIT = p_A_ZEIT, E_ZEIT = p_E_ZEIT, P_RANGE = p_P_RANGE where MPID = p_MPID; END; -- //// Delete Stored Procedure Based On Primary Key. create or replace PROCEDURE "TDBADMIN"."TDB_DELPROF" ( p_MPID IN MP_PROFIL.MPID%TYPE ) AS BEGIN delete from MP_PROFIL where MPID = p_MPID; END; COMMIT WORK;
import React, {Component} from 'react' import { connect } from 'react-redux' import {fetchCards, deleteCard} from 'actions/account/CreditCard' import AccountCreditCard from 'components/account/AccountCreditCard' import AjaxLoader from 'components/gui/Loaders/Ajaxloader' class StripeCards extends Component { render () { const { cards = [], deleteCard, submitting } = this.props return ( <div className='account-payment-methods__section'> <div className='row'> {cards ? ( cards.map((card, index) => ( <div key={`cc_${index}`} className='col-lg-4 col-md-6 col-sm-12 col-xs-12 account-payment-methods__section--bottom'> <AccountCreditCard cardType={card.brand} cardNumber={card.cardNumber} expiry={`${card.expiryMonth}/${card.expiryYear}`} postCode={card.postcode} onDelete={() => deleteCard(card.id)}/> </div> ))) : ( <div className='col-lg-6 col-md-8 col-sm-10 col-xs-12'> <p><i>It looks like no cards are linked to your account</i></p> </div> ) } </div> <AjaxLoader isVisible={submitting} /> </div> ) } componentDidMount () { this.props.fetchCards() } } const mapDispatchToProps = (dispatch, ownProps) => { return { fetchCards: () => { dispatch(fetchCards()) }, deleteCard: (id) => { dispatch(deleteCard(id)) } } } const mapStateToProps = ({account}, ownProps) => { const { creditCard } = account.addCreditCard return { cards: creditCard.cards, submitting: creditCard.submitting } } export default connect( mapStateToProps, mapDispatchToProps )(StripeCards)
// Algorithm to decide which stores should be open in a certain area. // Step 1: Collect data on the population density of the stores. // Step 2: Calculate the total number of people living within a certain distance from each store. // Step 3: Define a threshold population density to allow stores to open. // Step 4: Sort the stores by their population density, from highest to lowest. // Step 5: Decide which stores should open. The stores with a population density higher than the threshold should be the first to open. function openStores(stores, threshold) { // Step 1: Collect data population density of the stores. let data = stores.map(store => store.populationDensity); // Step 2: Calculate the total number of people living within a certain distance from each store. let totalPopulation = data.reduce((total, population) => total + population); // Step 3: Define a threshold population density to allow stores to open. let openingThreshold = totalPopulation * threshold; console.log(`Opening Threshold: ${openingThreshold}`); // Step 4: Sort the stores by their population density, from highest to lowest. let sortedStores = stores.sort((a, b) => b.populationDensity - a.populationDensity); // Step 5: Decide which stores should open. The stores with a population density higher than the threshold should be the first to open. let openStores = []; let populationCount = 0; for (let store of sortedStores) { if (populationCount < openingThreshold) { openStores.push(store); populationCount += store.populationDensity; } else { break; } } return openStores; }
<reponame>yogo/yogo class SystemRolesController < InheritedResources::Base respond_to :html, :json defaults :resource_class => SystemRole, :collection_name => 'system_roles', :instance_name => 'system_role' def create create! do |format| format.html { redirect_to(system_roles_url) } end end def update update! do |format| format.html { redirect_to(system_roles_url) } end end def delete delete! do |format| format.html { redirect_to(system_roles_url) } end end protected def collection @system_roles ||= resource_class.all end def resource @system_role ||= resource_class.get(params[:id]) end def resource_class SystemRole.access_as(current_user) end end
package com.learn.demomarket.coupon.dao; import com.learn.demomarket.coupon.entity.SpuBoundsEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * 商品spu积分设置 * * @author 996worker * @email * @date 2021-11-29 15:42:53 */ @Mapper public interface SpuBoundsDao extends BaseMapper<SpuBoundsEntity> { }
/* eslint-disable no-console */ const logger = require('winston'); const app = require('./app'); const port = process.env.PORT || app.get('port'); const server = app.listen(port); import queryGasPrice from './blockchain/gasPriceService'; import { queryEthConversion } from './services/ethconversion/getEthConversionService'; process.on('unhandledRejection', (reason, p) => logger.error('Unhandled Rejection at: Promise ', p, reason), ); server.on('listening', () => { logger.info(`Feathers application started on ${app.get('host')}:${port}`); logger.info(`Using DappMailer url ${app.get('dappMailerUrl')}`); }); queryGasPrice(); queryEthConversion(app);
<gh_stars>10-100 import * as ms from "milliseconds"; import { h } from "preact"; import { isNull } from "ts-type-guards"; import { disable } from "userscripter/lib/stylesheets"; import * as CONFIG from "~src/config"; import * as darkTheme from "~src/dark-theme"; import iconDarkThemeToggle from "~src/icons/dark-theme-toggle.svg"; import { insertAfter, renderIn } from "~src/operations/logic/render"; import { P, Preferences } from "~src/preferences"; import STYLESHEETS from "~src/stylesheets"; import * as T from "~src/text"; import { timeIsWithin } from "~src/time"; import { withMaybe } from "~src/utilities"; export function insertToggle(e: { menuLockToggle: HTMLElement, }) { renderIn(e.menuLockToggle.parentElement as Element, insertAfter(e.menuLockToggle), ( // Derived from the menu lock toggle. <li class="menu-lock menu-lock-active"> <div class="menu-lock-click" title={T.general.dark_theme_toggle_tooltip(darkTheme.AUTHOR)} onClick={() => set(!Preferences.get(P.dark_theme._.active))} /> <span class="menu-lock"> <svg class="icon" dangerouslySetInnerHTML={{ __html: iconDarkThemeToggle }} /> </span> </li> )); disable(STYLESHEETS.dark_theme_toggle_preparations); } export function manage(): void { if (Preferences.get(P.dark_theme._.active)) { apply(true); } if (Preferences.get(P.dark_theme._.auto)) { sheldon(); setInterval(sheldon, ms.seconds(Preferences.get(P.dark_theme._.interval))); } } function apply(newState: boolean): void { const url = withCacheInvalidation(darkTheme.URL.stylesheet, new Date()); if (newState) { if (isNull(document.getElementById(CONFIG.ID.darkThemeStylesheet))) { // Not document.head because it can be null, e.g. in a background tab in Firefox: const link = document.createElement("link"); link.rel = "stylesheet"; link.href = url; link.id = CONFIG.ID.darkThemeStylesheet; document.documentElement.appendChild(link); } } else { withMaybe(document.getElementById(CONFIG.ID.darkThemeStylesheet), element => element.remove()); } } function set(newState: boolean): void { Preferences.set(P.dark_theme._.active, newState); apply(newState); } function sheldon(): void { // Sheldon cannot do the same thing twice in a row, because the user must be able to override him. const whatSheldonWants = timeIsWithin({ start: Preferences.get(P.dark_theme._.time_on), end: Preferences.get(P.dark_theme._.time_off), })(new Date()); const whatSheldonDidLast = Preferences.get(P.dark_theme._.last_autoset_state); if (whatSheldonWants !== whatSheldonDidLast) { Preferences.set(P.dark_theme._.last_autoset_state, whatSheldonWants); set(whatSheldonWants); } // If the dark theme was toggled (auto or not) in another tab, Sheldon must toggle it here as well: apply(Preferences.get(P.dark_theme._.active)); } function withCacheInvalidation(url: string, date: Date): string { const yyyy = date.getFullYear(); const mm = (date.getMonth() + 1 /* 0-indexed */).toString().padStart(2, "0"); const dd = date.getDate().toString().padStart(2, "0"); return `${url}?v=${yyyy}${mm}${dd}`; }