Dataset Viewer
Auto-converted to Parquet Duplicate
code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
public class HundredIntegers { public static void main (String[] args) { for (int i = 1; i<=100; i++) { System.out.println(i); } } }
100integers
HundredIntegers.java
Java
epl
147
public class HundredIntegers { public static void main (String[] args) { for (int i = 1; i<=100; i++) { System.out.println(i); } } }
100integers
trunk/HundredIntegers.java
Java
epl
147
package Entity; public interface IOperatoerDTO { int getoprId(); void setoprId(int Id); String getoprNavn(); void setoprNavn(String Navn); String getini(); void setini(String In); String getcpr(); void setcpr(String cp); String getpassword(); void setpassword(String passwd); }
02324cdio-del1
https:/gezienajose@code.google.com/p/02324cdio-del1/COPY/Copy of Gruppe11CDIO1/src/Entity/IOperatoerDTO.java
Java
epl
325
package Entity; public class OperatoerDTO implements IOperatoerDTO { int oprId; String oprNavn; String ini; String cpr; String password; public OperatoerDTO() //Default Constructor { this.oprId = 0; this.oprNavn = ""; this.ini = ""; this.cpr = ""; this.password = ""; } public OperatoerDTO (int oId, String oNavn, String i, String cr, String pwd) //created constructor { this.oprId = oId; this.oprNavn = oNavn; this.ini = i; this.cpr = cr; this.password = pwd; } public int getoprId(){ return oprId;} //return must be oprId not 0; public void setoprId(int Id){ oprId = Id; } public String getoprNavn(){ return oprNavn; } public void setoprNavn(String Navn){ oprNavn = Navn; } public String getini(){ return ini; } public void setini(String In){ ini = In; } public String getcpr(){ return cpr; } public void setcpr(String cp){ cpr = cp; } public String getpassword(){ return password; } public void setpassword(String passwd){ password = passwd; } }//corrected setters and getters
02324cdio-del1
https:/gezienajose@code.google.com/p/02324cdio-del1/COPY/Copy of Gruppe11CDIO1/src/Entity/OperatoerDTO.java
Java
epl
1,149
package Controller; import Entity.OperatoerDTO; /* public class ChangePassword implements IOperatoerDAO { OperatoerDTO opr = new OperatoerDTO(); public String passwordGenerator(String passwd){ return passwd; } public String opChangePasswd(int Id) { return null; } */
02324cdio-del1
https:/gezienajose@code.google.com/p/02324cdio-del1/COPY/Copy of Gruppe11CDIO1/src/Controller/ChangePassword.java
Java
epl
300
package Controller; import java.util.ArrayList; import Entity.OperatoerDTO; public class OperatoerDAO implements IOperatoerDAO{ OperatoerDTO opr = new OperatoerDTO(); private ArrayList<OperatoerDTO> oDTO = new ArrayList<OperatoerDTO>();; //added an arraylist of type OperatoerDTO public OperatoerDAO() { } public OperatoerDTO getOperatoer(int oprId) throws DALException{ return opr; } public ArrayList<OperatoerDTO> getOperatoerList() throws DALException { return oDTO; } public void createOperatoer(OperatoerDTO opr) throws DALException{ oDTO.add(opr); } public void updateOperatoer(OperatoerDTO opr) throws DALException{} }
02324cdio-del1
https:/gezienajose@code.google.com/p/02324cdio-del1/COPY/Copy of Gruppe11CDIO1/src/Controller/OperatoerDAO.java
Java
epl
682
package Controller; import java.util.regex.Matcher; import java.util.regex.Pattern; public class PasswordValidator{ private Pattern pattern; private Matcher matcher; private static String PASSWORD_PATTERN = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})"; public PasswordValidator(){ pattern = Pattern.compile(PASSWORD_PATTERN); } /* * Validate password with regular expression * @param password password for validation * @return true valid password, false invalid password */ public boolean validate(String password){ matcher = pattern.matcher(password); return matcher.matches(); } }
02324cdio-del1
https:/gezienajose@code.google.com/p/02324cdio-del1/COPY/Copy of Gruppe11CDIO1/src/Controller/PasswordValidator.java
Java
epl
702
package Controller; import Entity.OperatoerDTO; /* public class LoginTjeck implements IOperatoerDAO { OperatoerDTO opr = new OperatoerDTO(); public int loginUser(String passwd, int id) { return 0; } }*/
02324cdio-del1
https:/gezienajose@code.google.com/p/02324cdio-del1/COPY/Copy of Gruppe11CDIO1/src/Controller/LoginTjeck.java
Java
epl
229
package Controller; import Entity.OperatoerDTO; /* public class Afvejning implements IOperatoerDAO { OperatoerDTO opr = new OperatoerDTO(); public double beregningNetto(double Tara, double Brutto) { return 0.0; } }*/
02324cdio-del1
https:/gezienajose@code.google.com/p/02324cdio-del1/COPY/Copy of Gruppe11CDIO1/src/Controller/Afvejning.java
Java
epl
243
package Controller; import Entity.OperatoerDTO; import java.util.ArrayList; public interface IOperatoerDAO { //int loginUser(String passwd, int id); OperatoerDTO getOperatoer(int oprId) throws DALException; ArrayList<OperatoerDTO> getOperatoerList() throws DALException; void createOperatoer(OperatoerDTO opr) throws DALException; void updateOperatoer(OperatoerDTO opr) throws DALException; // String passwordGenerator(String passwd); // String opchangepasswd(int Id); //double beregningNetto(double Tara, double Brutto); public class DALException extends Exception //added exception class { public DALException() { super( " findes ikke."); } } }
02324cdio-del1
https:/gezienajose@code.google.com/p/02324cdio-del1/COPY/Copy of Gruppe11CDIO1/src/Controller/IOperatoerDAO.java
Java
epl
706
package Boundary; import Entity.OperatoerDTO; import Controller.IOperatoerDAO.DALException; import Controller.OperatoerDAO; import Controller.PasswordValidator; import java.util.Scanner; public class Graenseflade { OperatoerDTO opr = new OperatoerDTO(); OperatoerDAO dao = new OperatoerDAO(); PasswordValidator pv = new PasswordValidator(); boolean go = true; public Graenseflade() //added user options { while(go){ System.out.println("1. Login"); System.out.println("2. Change Password"); System.out.println("3. Exit"); System.out.println("Enter your choice"); Scanner sc = new Scanner(System.in); //user input String choice = sc.next(); switch(choice) //checking admin login { case "1": Scanner user = new Scanner(System.in); System.out.println("Enter ID:"); String uname = user.next(); System.out.println("Enter password:"); String pwd = user.next(); if((uname.equals("BOB")) && (pwd.equals("DGMNZ123"))) { System.out.println("Login Successful"); System.out.println(); System.out.println("Select you choice"); System.out.println("1. Create Operator"); System.out.println("2. Udpate Operator"); System.out.println("3. Delete Operator"); } //Scanner s = new Scanner(System.in); //user input String ch = sc.next(); switch(ch) //Admin entering operator data { case "1": Scanner admin = new Scanner(System.in); System.out.println("Enter ID"); int ID = admin.nextInt(); opr.setoprId(ID); System.out.println("Enter Name"); String name = admin.next(); opr.setoprNavn(name); System.out.println("Enter CPR"); String cpr = admin.next(); opr.setcpr(cpr); System.out.println("Enter Password"); /* must contains one digit from 0-9 must contains one lowercase characters must contains one uppercase characters must contains one special symbols in the list "@#$%" match anything with previous condition checking length at least 6 characters and maximum of 20 */ String pass = admin.next(); while((pv.validate(pass)) == false) { System.out.println("Enter a new Password"); pass = admin.next(); } opr.setpassword(pass); try { //try catch for createOperatoer dao.createOperatoer(opr); } catch (DALException e) { // TODO Auto-generated catch block e.printStackTrace(); } } break; case "3": System.exit(0);; } System.out.println("Id: " + opr.getoprId() + "\nName: " + opr.getoprNavn() + "\nCPR: " + opr.getcpr() + "\nPassword: " + opr.getpassword()); System.out.println(); } } //Login interface /* if(Id == 10 && passwd == "02304it") { int Id = sysadminInt(); } */ //Operatorinterface //Sysadmininterface /* private int sysadminInt() { return 0; } */ //vægtdetaljerinterface }
02324cdio-del1
https:/gezienajose@code.google.com/p/02324cdio-del1/COPY/Copy of Gruppe11CDIO1/src/Boundary/Graenseflade.java
Java
epl
3,119
import Boundary.Graenseflade; public class Main { public static void main(String[] args) { Graenseflade g = new Graenseflade(); } }
02324cdio-del1
https:/gezienajose@code.google.com/p/02324cdio-del1/COPY/Copy of Gruppe11CDIO1/src/Main.java
Java
epl
140
// Copyright 2012 Google Inc. All Rights Reserved. // // 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. /** * @fileoverview Moog-like low pass audio filter. */ goog.provide('doodle.moog.LowPassFilter'); goog.require('doodle.moog.CompoundAudioNode'); /** * A dynamic low pass filter emulator. * @param {!AudioContext} audioContext Audio context to which this oscillator * will be bound. * @param {number} cutoffFrequency The cutoff frequency above which the * frequencies are attenuated. * @param {number} contour Amount of contour to apply to the filter envelope. * @param {number} attackTime Initial attack time in seconds. * @param {number} decayTime Initial decay time in seconds. * @param {number} sustainLevel Initial sustain level [0..1]. * @constructor * @implements {doodle.moog.CompoundAudioNode} */ doodle.moog.LowPassFilter = function( audioContext, cutoffFrequency, contour, attackTime, decayTime, sustainLevel) { /** * Audio context in which this filter operates. * @type {!AudioContext} * @private */ this.audioContext_ = audioContext; /** * The low pass filter Web Audio node. * @type {!BiquadFilterNode} * @private */ this.lowPassFilterNode_ = audioContext.createBiquadFilter(); this.lowPassFilterNode_.type = doodle.moog.LowPassFilter.LOW_PASS_FILTER_TYPE_ID_; /** * Frequency above which sound should be progressively attenuated. * @type {number} * @private */ this.cutoffFrequency_ = cutoffFrequency; /** * The amount of 'contour' to add to the low pass filter ADS (attack, decay, * sustain) envelope. Contour is essentially a variable cutoff frequency * coefficient. See doodle.moog.EnvelopeGenerator for an explanation of how * ADS envelopes work. * @type {number} * @private */ this.contour_ = contour; /** * The duration of the attack phase in seconds. * @type {number} * @private */ this.attackTime_ = attackTime; /** * The duration of the decay phase in seconds. * @type {number} * @private */ this.decayTime_ = decayTime; /** * The sustain frequency coefficient. * @type {number} * @private */ this.sustainLevel_ = sustainLevel; this.resetContourEnvelope_(); }; /** * Biquad Filter type ID for a low pass filter (from the Web Audio spec). * @type {number} * @const * @private */ doodle.moog.LowPassFilter.LOW_PASS_FILTER_TYPE_ID_ = 0; /** * Initiates the attack phase of the contour envelope (e.g., when a key is * pressed). */ doodle.moog.LowPassFilter.prototype.startAttack = function() { var now = this.audioContext_.currentTime; this.lowPassFilterNode_.frequency.cancelScheduledValues(now); this.lowPassFilterNode_.frequency.value = this.cutoffFrequency_; this.lowPassFilterNode_.frequency.setValueAtTime(this.cutoffFrequency_, now); var contourFrequency = this.contour_ * this.cutoffFrequency_; this.lowPassFilterNode_.frequency.exponentialRampToValueAtTime( contourFrequency, now + this.attackTime_); this.lowPassFilterNode_.frequency.exponentialRampToValueAtTime( this.cutoffFrequency_ + this.sustainLevel_ * (contourFrequency - this.cutoffFrequency_), now + this.attackTime_ + this.decayTime_); }; /** * Sets the filter cutoff frequency. * @param {number} cutoffFrequency The cutoff frequency above which the * frequencies are attenuated. */ doodle.moog.LowPassFilter.prototype.setCutoffFrequency = function( cutoffFrequency) { this.cutoffFrequency_ = cutoffFrequency; this.resetContourEnvelope_(); }; /** * Sets the filter envelope contour. * @param {number} contour Amount of contour to apply to the filter envelope. */ doodle.moog.LowPassFilter.prototype.setContour = function(contour) { this.contour_ = contour; this.resetContourEnvelope_(); }; /** * Sets attack phase duration. * @param {number} time Duration of the attack phase in seconds. */ doodle.moog.LowPassFilter.prototype.setContourAttackTime = function(time) { this.attackTime_ = time; this.resetContourEnvelope_(); }; /** * Sets decay phase duration. * @param {number} time Duration of the decay phase in seconds. */ doodle.moog.LowPassFilter.prototype.setContourDecayTime = function(time) { this.decayTime_ = time; this.resetContourEnvelope_(); }; /** * Sets the sustain level. * @param {number} level The sustain level, a number in the range [0, 1]. */ doodle.moog.LowPassFilter.prototype.setContourSustainLevel = function(level) { this.sustainLevel_ = level; this.resetContourEnvelope_(); }; /** * Resets the contour envelope AudioParam using current LowPassFilter state. * @private */ doodle.moog.LowPassFilter.prototype.resetContourEnvelope_ = function() { this.lowPassFilterNode_.frequency.cancelScheduledValues(0); this.lowPassFilterNode_.frequency.value = this.cutoffFrequency_; }; /** @inheritDoc */ doodle.moog.LowPassFilter.prototype.getSourceNode = function() { return this.lowPassFilterNode_; }; /** @inheritDoc */ doodle.moog.LowPassFilter.prototype.connect = function(destination) { this.lowPassFilterNode_.connect(destination); }; /** @inheritDoc */ doodle.moog.LowPassFilter.prototype.disconnect = function() { this.lowPassFilterNode_.disconnect(); };
010pepe010-moog
low_pass_filter.js
JavaScript
asf20
5,777
// Copyright 2012 Google Inc. All Rights Reserved. // // 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. goog.addDependency('../../../compound_audio_node.js', ['doodle.moog.CompoundAudioNode'], []); goog.addDependency('../../../envelope_generator.js', ['doodle.moog.EnvelopeGenerator'], []); goog.addDependency('../../../low_pass_filter.js', ['doodle.moog.LowPassFilter'], ['doodle.moog.CompoundAudioNode']); goog.addDependency('../../../master_mixer.js', ['doodle.moog.MasterMixer'], ['doodle.moog.MasterMixerInterface']); goog.addDependency('../../../master_mixer_interface.js', ['doodle.moog.MasterMixerInterface'], []); goog.addDependency('../../../moog.js', ['doodle.moog.Moog'], ['doodle.moog.LowPassFilter', 'doodle.moog.MasterMixer', 'doodle.moog.Oscillator', 'doodle.moog.OscillatorInterface', 'doodle.moog.Synthesizer', 'doodle.moog.WideBandPassFilter', 'goog.Disposable']); goog.addDependency('../../../oscillator.js', ['doodle.moog.Oscillator'], ['doodle.moog.EnvelopeGenerator', 'doodle.moog.OscillatorInterface']); goog.addDependency('../../../oscillator_interface.js', ['doodle.moog.OscillatorInterface', 'doodle.moog.OscillatorInterface.FillMode', 'doodle.moog.OscillatorInterface.Range', 'doodle.moog.OscillatorInterface.WaveForm'], []); goog.addDependency('../../../synthesizer.js', ['doodle.moog.Synthesizer'], ['doodle.moog.CompoundAudioNode', 'doodle.moog.OscillatorInterface', 'doodle.moog.SynthesizerInterface', 'goog.array', 'goog.userAgent']); goog.addDependency('../../../synthesizer_interface.js', ['doodle.moog.SynthesizerInterface'], []); goog.addDependency('../../../wide_band_pass_filter.js', ['doodle.moog.WideBandPassFilter'], ['doodle.moog.CompoundAudioNode']);
010pepe010-moog
deps.js
JavaScript
asf20
2,201
// Copyright 2012 Google Inc. All Rights Reserved. // // 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. /** * @fileoverview Voltage controlled oscillator emulators. */ goog.provide('doodle.moog.OscillatorInterface'); goog.provide('doodle.moog.OscillatorInterface.FillMode'); goog.provide('doodle.moog.OscillatorInterface.Range'); goog.provide('doodle.moog.OscillatorInterface.WaveForm'); /** * Oscillator interface to be implemented in WebAudio and FlashAudio. * @interface */ doodle.moog.OscillatorInterface = function() {}; /** * Different methods in which an oscillator can fill an audio buffer. * @enum {number} */ doodle.moog.OscillatorInterface.FillMode = { // Clobber any pre-existing data in the buffer. CLOBBER: 0, // Add signal to the buffer. ADD: 1, // Add signal to the buffer and then do an even mix down. MIX: 2 }; /** * Different 'ranges' (i.e., octaves in synth lingo) in which an oscillator can * generate a tone. 'LO' is a special Moog-ism that generates sub-audio clicks * and pops. * @enum {number} */ doodle.moog.OscillatorInterface.Range = { LO: 0.0625, R32: 2, R16: 4, R8: 8, R4: 16, R2: 32 }; /** * Different wave forms that can be generated by an oscillator, each of which * has a different overtone spectrum leading to a different base timbre. * @enum {number} */ doodle.moog.OscillatorInterface.WaveForm = { TRIANGLE: 0, SAWANGLE: 1, RAMP: 2, REVERSE_RAMP: 3, SQUARE: 4, FAT_PULSE: 5, PULSE: 6 }; /** * Sets the volume on this oscillator. * @param {number} volume Volume in the range of [0, 1]. */ doodle.moog.OscillatorInterface.prototype.setVolume = function(volume) {}; /** * Sets the wave form generated by this oscillator. * @param {!doodle.moog.OscillatorInterface.WaveForm} waveForm The wave form to * use. */ doodle.moog.OscillatorInterface.prototype.setWaveForm = function(waveForm) {}; /** * Sets the pitch bend on this oscillator. * @param {number} pitchBend Pitch bend amount in the range of [-1, 1]. */ doodle.moog.OscillatorInterface.prototype.setPitchBend = function(pitchBend) {}; /** * Sets the octave/range of this oscillator. * @param {!doodle.moog.OscillatorInterface.Range} range The range of this * oscillator. */ doodle.moog.OscillatorInterface.prototype.setRange = function(range) {}; /** * Turns on keyboard pitch control. */ doodle.moog.OscillatorInterface.prototype.turnOnKeyboardPitchControl = function() {}; /** * Turns off keyboard pitch control. */ doodle.moog.OscillatorInterface.prototype.turnOffKeyboardPitchControl = function() {}; /** * Turns on frequency modulation. */ doodle.moog.OscillatorInterface.prototype.turnOnFrequencyModulation = function() {}; /** * Turns off frequency modulation. */ doodle.moog.OscillatorInterface.prototype.turnOffFrequencyModulation = function() {}; /** * Sets the modulation signal level. * @param {number} modulatorLevel If a modulator, how strong the modulator * control signal should be [0..1]. */ doodle.moog.OscillatorInterface.prototype.setModulatorLevel = function(modulatorLevel) {}; /** * Turns on glide. */ doodle.moog.OscillatorInterface.prototype.turnOnGlide = function() {}; /** * Turns off glide. */ doodle.moog.OscillatorInterface.prototype.turnOffGlide = function() {}; /** * Sets the duration of gliding. * @param {number} time The time to glide between notes in seconds. */ doodle.moog.OscillatorInterface.prototype.setGlideDuration = function(time) {}; /** * Sets the note this oscillator should generate. * @param {number} note Chromatic index of the note to be played relative to the * beginning of the keyboard. */ doodle.moog.OscillatorInterface.prototype.setActiveNote = function(note) {}; /** * Sets the attack time for this oscillator's envelope generator. * @param {number} attackTime The new attack time. */ doodle.moog.OscillatorInterface.prototype.setEnvelopeGeneratorAttackTime = function(attackTime) {}; /** * Sets the decay time for this oscillator's envelope generator. * @param {number} decayTime The new decay time. */ doodle.moog.OscillatorInterface.prototype.setEnvelopeGeneratorDecayTime = function(decayTime) {}; /** * Sets the sustain level for this oscillator's envelope generator. * @param {number} sustainLevel The new sustain level. */ doodle.moog.OscillatorInterface.prototype.setEnvelopeGeneratorSustainLevel = function(sustainLevel) {};
010pepe010-moog
oscillator_interface.js
JavaScript
asf20
4,979
<!doctype html> <!-- // Copyright 2012 Google Inc. All Rights Reserved. // // 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. --> <html> <head> <meta charset="utf-8"> <title>Moog JS Demo</title> <style type="text/css"> #keyboard > button { background-color: #eee; border: 2px solid black; cursor: pointer; font-weight: bold; height: 50px; width: 50px; } </style> </head> <body> <h1>Moog Doodle Demo Page</h1> To get this running: <ul> <li>If you got this code by: <ul> <li>tarball/zip, then download <a href="http://code.google.com/p/closure-library/source/browse/#svn%2Ftrunk">Closure Library</a> to a folder named 'closure' in this directory.</li> <li>git clone, then run <code>git submodule init && git submodule update</code></li> </ul> </li> <li>Make sure volume is unmuted, speakers are on, etc.</li> <li>Open this file in a Web Audio enabled browser like Chrome.</li> <li>Press the buttons below to play tones.</li> </ul> <h2>Keys</h2> <div id=keyboard> <button>0</button> <button>1</button> <button>2</button> <button>3</button> <button>4</button> <button>5</button> <button>6</button> <button>7</button> <button>8</button> <button>9</button> </div> <h2>Cutoff Frequency</h2> <input id=cutoff type=range min=20 max=5000 value=2100 style=width:500px> <script src="closure/closure/goog/base.js"></script> <script src="closure/closure/goog/deps.js"></script> <script src="deps.js"></script> <script> goog.require('doodle.moog.Moog'); window.onload = function() { var moog = new doodle.moog.Moog(); moog.turnOnAudio(); var keyboard = document.getElementById('keyboard'); keyboard.addEventListener('mousedown', function(e) { if (e.target.tagName == 'BUTTON') { moog.synthesizers_[0].setKeyDown(parseInt(e.target.innerHTML, 10)); } }, false); keyboard.addEventListener('mouseup', function(e) { moog.synthesizers_[0].setKeyUp(); }, false); keyboard.addEventListener('mouseout', function(e) { moog.synthesizers_[0].setKeyUp(); }, false); var cutoff = document.getElementById('cutoff'); cutoff.addEventListener('change', function() { moog.synthesizers_[0].lowPassFilter.setCutoffFrequency(cutoff.value); }, false); }; </script> </body> </html>
010pepe010-moog
demo.html
HTML
asf20
2,825
// Copyright 2012 Google Inc. All Rights Reserved. // // 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. /** * @fileoverview A moog-like audio synthesizer built on top of the HTML5 Web * Audio API. */ goog.provide('doodle.moog.Synthesizer'); goog.require('doodle.moog.CompoundAudioNode'); goog.require('doodle.moog.OscillatorInterface'); goog.require('doodle.moog.SynthesizerInterface'); goog.require('goog.array'); goog.require('goog.userAgent'); /** * A Moog-like synthesizer built on top of the HTML5 Web Audio API. * @param {!AudioContext} audioContext Audio context in which this synthesizer * will operate. * @param {!Array.<!doodle.moog.Oscillator>} oscillators The oscillators used * within this synthesizer. * @param {!doodle.moog.LowPassFilter} lowPassFilter The low pass filter used * within this synthesizer. * @param {number} volume How much the gain should be adjusted. * @implements {doodle.moog.CompoundAudioNode} * @implements {doodle.moog.SynthesizerInterface} * @constructor */ doodle.moog.Synthesizer = function( audioContext, oscillators, lowPassFilter, volume) { /** * The audio context in which this synthesizer operates. * @type {!AudioContext} * @private */ this.audioContext_ = audioContext; /** * Oscillators used to generate synthesizer sounds. * @type {!Array.<!doodle.moog.Oscillator>} */ this.oscillators = oscillators; /** * Filter used to cut off high frequencies. * @type {!doodle.moog.LowPassFilter} */ this.lowPassFilter = lowPassFilter; /** * The volume Web Audio node. * @type {!AudioGainNode} * @private */ this.volumeNode_ = audioContext.createGainNode(); /** * Frequency analyser node. * @type {!RealtimeAnalyserNode} */ this.analyserNode = audioContext.createAnalyser(); this.analyserNode.smoothingTimeConstant = 0.5; /** * Volume/gain adjustment to apply to the output signal. * @type {number} * @private */ this.volume_; this.setVolume(volume); /** * Web Audio JavaScript node used by oscillators to generate sound. * Chrome 20+ won't connect a js node with no inputs for some reason. * @type {!JavaScriptAudioNode} * @private */ this.jsAudioNode_ = goog.userAgent.isVersion('20.0') ? audioContext.createJavaScriptNode( doodle.moog.Synthesizer.BUFFER_SIZE_, 1, 1) : audioContext.createJavaScriptNode( doodle.moog.Synthesizer.BUFFER_SIZE_, 0, 1); this.jsAudioNode_.onaudioprocess = goog.bind(this.fillAudioBuffer_, this); this.jsAudioNode_.connect(this.lowPassFilter.getSourceNode()); this.lowPassFilter.connect(this.volumeNode_); this.volumeNode_.connect(this.analyserNode); }; /** * How many samples to fill at a time in a JavaScript audio node callback. A * larger number here will decrease the chance of jitters/gaps at the expense of * control latency. * @type {number} * @const * @private */ doodle.moog.Synthesizer.BUFFER_SIZE_ = 1024; /** @inheritDoc */ doodle.moog.Synthesizer.prototype.setKeyDown = function(note) { goog.array.forEach(this.oscillators, function(oscillator) { oscillator.setActiveNote(note); oscillator.envelopeGenerator.startAttack(); }); this.lowPassFilter.startAttack(); }; /** @inheritDoc */ doodle.moog.Synthesizer.prototype.setKeyDownCallback = function(callback) { // No-op, since this is only required on non-WebAudio browsers. }; /** @inheritDoc */ doodle.moog.Synthesizer.prototype.setKeyUp = function() { goog.array.forEach(this.oscillators, function(oscillator) { oscillator.envelopeGenerator.startRelease(); }); }; /** @inheritDoc */ doodle.moog.Synthesizer.prototype.setLpCutoffFrequency = function(cutoffFrequency) { this.lowPassFilter.setCutoffFrequency(cutoffFrequency); }; /** @inheritDoc */ doodle.moog.Synthesizer.prototype.setLpContour = function(contour) { this.lowPassFilter.setContour(contour); }; /** @inheritDoc */ doodle.moog.Synthesizer.prototype.setLpContourAttackTime = function(time) { this.lowPassFilter.setContourAttackTime(time); }; /** @inheritDoc */ doodle.moog.Synthesizer.prototype.setLpContourDecayTime = function(time) { this.lowPassFilter.setContourDecayTime(time); }; /** @inheritDoc */ doodle.moog.Synthesizer.prototype.setLpContourSustainLevel = function(level) { this.lowPassFilter.setContourSustainLevel(level); }; /** * Fills the passed audio buffer with tones generated by oscillators. * @param {!AudioProcessingEvent} e The audio process event object. * @private */ doodle.moog.Synthesizer.prototype.fillAudioBuffer_ = function(e) { // NOTE: We fill oscillator 2 first since it generates a modulation control // signal on which oscillators 0 and 1 depend. this.oscillators[2].fillAudioBuffer( e, null, doodle.moog.OscillatorInterface.FillMode.CLOBBER); this.oscillators[0].fillAudioBuffer( e, this.oscillators[2].modulatorSignal, doodle.moog.OscillatorInterface.FillMode.ADD); this.oscillators[1].fillAudioBuffer( e, this.oscillators[2].modulatorSignal, doodle.moog.OscillatorInterface.FillMode.MIX, this.oscillators.length); }; /** @inheritDoc */ doodle.moog.Synthesizer.prototype.setVolume = function(volume) { this.volume_ = volume; this.volumeNode_.gain.value = volume; }; /** @override */ doodle.moog.Synthesizer.prototype.getSourceNode = function() { return this.jsAudioNode_; }; /** @override */ doodle.moog.Synthesizer.prototype.connect = function(destination) { this.analyserNode.connect(destination); }; /** @override */ doodle.moog.Synthesizer.prototype.disconnect = function() { this.analyserNode.disconnect(); };
010pepe010-moog
synthesizer.js
JavaScript
asf20
6,169
// Copyright 2012 Google Inc. All Rights Reserved. // // 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. /** * @fileoverview Attack, Decay, Sustain, Decay (ADSD) envelope generator. */ goog.provide('doodle.moog.EnvelopeGenerator'); /** * An ADSD envelope generator, used to control volume of a single synth note. * * See the Phase_ enum below for a description of how ADSD envelopes work. * * @param {number} sampleInterval How many seconds pass with each sample. * @param {number} attackTime Initial attack time in seconds. * @param {number} decayTime Initial decay time in seconds. * @param {number} sustainLevel Initial sustain level [0..1]. * @constructor */ doodle.moog.EnvelopeGenerator = function( sampleInterval, attackTime, decayTime, sustainLevel) { /** * How many seconds pass with each sample. * @type {number} * @private * @const */ this.SAMPLE_INTERVAL_ = sampleInterval; /** * The amount by which the tone associated with this envelope should be * scaled. A number in the range [0, 1]. * @type {number} * @private */ this.amplitudeCoefficient_ = 0; /** * The current phase of the envelope. * @type {!doodle.moog.EnvelopeGenerator.Phase_} * @private */ this.phase_ = doodle.moog.EnvelopeGenerator.Phase_.INACTIVE; /** * The duration of the attack phase in seconds. * @type {number} * @private */ this.attackTime_ = attackTime; /** * How much the amplitude should be increased for each sample in the attack * phase. * * NOTE: This variable and other 'step' variables can be computed from other * EnvelopeGenerator state. We explicitly store these values though since * they are precisely the data needed in getNextAmplitudeCoefficient which is * typically executed in a sound buffer filling loop and therefore performance * critical. * @type {number} * @private */ this.attackStep_; /** * The duration of the decay phase in seconds. * @type {number} * @private */ this.decayTime_ = decayTime; /** * How much the amplitude should be decreased for each sample in the decay * phase. * @type {number} * @private */ this.decayStep_; /** * The sustain amplitude coefficient. * @type {number} * @private */ this.sustainLevel_ = sustainLevel; /** * How much the amplitude should be decreased for each sample in the release * phase. * @type {number} * @private */ this.releaseStep_; this.recomputePhaseSteps_(); }; /** * The different phases of an ADSD envelope. When playing a key on a synth, * these phases are always executed in the order they're defined in this enum. * * @enum {number} * @private */ doodle.moog.EnvelopeGenerator.Phase_ = { // A linear ramp up from no volume (just before a key is struck) to maximum // volume. ATTACK: 0, // A linear ramp down from maximum volume to the sustain volume level. DECAY: 1, // Once the attack and decay phases have completed, the volume at which the // note is held until the key is released. SUSTAIN: 2, // A linear ramp down from the sustain volume to no volume after a key is // released. Moog instruments uniquely reuse the decay time parameter for the // release time (hence the "ADSD" acronym instead of "ADSR"). RELEASE: 3, // Meta state indicating that the envelope is not currently active. INACTIVE: 4 }; /** * Initiates the attack phase of the envelope (e.g., when a key is pressed). */ doodle.moog.EnvelopeGenerator.prototype.startAttack = function() { this.recomputePhaseSteps_(); this.amplitudeCoefficient_ = 0; this.phase_ = doodle.moog.EnvelopeGenerator.Phase_.ATTACK; }; /** * Initiates the release phase of the envelope (e.g., when a key is lifted). */ doodle.moog.EnvelopeGenerator.prototype.startRelease = function() { if (this.phase_ == doodle.moog.EnvelopeGenerator.Phase_.RELEASE) { return; } else { // Compute release step based on the current amplitudeCoefficient_. if (this.decayTime_ <= 0) { this.releaseStep_ = 1; } else { this.releaseStep_ = this.amplitudeCoefficient_ * this.SAMPLE_INTERVAL_ / this.decayTime_; } } this.phase_ = doodle.moog.EnvelopeGenerator.Phase_.RELEASE; }; /** * Gets the next amplitude coefficient that should be applied to the currently * playing note. This method must be called (and applied, natch) for each * sample filled for the duration of a note. * * @return {number} An amplitude coefficient in the range [0, 1] that should be * applied to the current sample. */ doodle.moog.EnvelopeGenerator.prototype.getNextAmplitudeCoefficient = function() { switch (this.phase_) { case doodle.moog.EnvelopeGenerator.Phase_.ATTACK: this.amplitudeCoefficient_ += this.attackStep_; if (this.amplitudeCoefficient_ >= 1) { this.amplitudeCoefficient_ = 1; this.phase_ = doodle.moog.EnvelopeGenerator.Phase_.DECAY; } break; case doodle.moog.EnvelopeGenerator.Phase_.DECAY: this.amplitudeCoefficient_ -= this.decayStep_; if (this.amplitudeCoefficient_ <= this.sustainLevel_) { this.amplitudeCoefficient_ = this.sustainLevel_; this.phase_ = doodle.moog.EnvelopeGenerator.Phase_.SUSTAIN; } break; case doodle.moog.EnvelopeGenerator.Phase_.SUSTAIN: // Just stay at the sustain level until a release is signaled. break; case doodle.moog.EnvelopeGenerator.Phase_.RELEASE: this.amplitudeCoefficient_ -= this.releaseStep_; if (this.amplitudeCoefficient_ <= 0) { this.amplitudeCoefficient_ = 0; this.phase_ = doodle.moog.EnvelopeGenerator.Phase_.INACTIVE; } break; case doodle.moog.EnvelopeGenerator.Phase_.INACTIVE: // Stay at 0, as set in the release transition (muted). break; } return this.amplitudeCoefficient_; }; /** * Sets attack phase duration. * @param {number} time Duration of the attack phase in seconds. */ doodle.moog.EnvelopeGenerator.prototype.setAttackTime = function(time) { this.attackTime_ = time; this.recomputePhaseSteps_(); }; /** * Sets decay phase duration. * @param {number} time Duration of the decay phase in seconds. */ doodle.moog.EnvelopeGenerator.prototype.setDecayTime = function(time) { this.decayTime_ = time; this.recomputePhaseSteps_(); }; /** * Sets the sustain level. * @param {number} level The sustain level, a number in the range [0, 1]. */ doodle.moog.EnvelopeGenerator.prototype.setSustainLevel = function(level) { this.sustainLevel_ = level; this.recomputePhaseSteps_(); }; /** * Updates phase step variables to reflect current EnvelopeGenerator state. * @private */ doodle.moog.EnvelopeGenerator.prototype.recomputePhaseSteps_ = function() { if (this.attackTime_ <= 0) { this.attackStep_ = 1; } else { this.attackStep_ = this.SAMPLE_INTERVAL_ / this.attackTime_; } if (this.decayTime_ <= 0) { this.decayStep_ = 1; this.releaseStep_ = 1; } else { this.decayStep_ = (1 - this.sustainLevel_) * this.SAMPLE_INTERVAL_ / this.decayTime_; this.releaseStep_ = this.sustainLevel_ * this.SAMPLE_INTERVAL_ / this.decayTime_; } };
010pepe010-moog
envelope_generator.js
JavaScript
asf20
7,743
// Copyright 2012 Google Inc. All Rights Reserved. // // 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. /** * @fileoverview Interface for compound Web Audio audio nodes. */ goog.provide('doodle.moog.CompoundAudioNode'); /** * Connection interface for compound Web Audio nodes. * @interface */ doodle.moog.CompoundAudioNode = function() {}; /** * Gets the source node for this compound node. * @return {!AudioNode} The input/source node for this compound node. */ doodle.moog.CompoundAudioNode.prototype.getSourceNode = function() {}; /** * Connects this compound node to a destination audio node. * @param {!AudioNode} destination The destination to connect this node to. */ doodle.moog.CompoundAudioNode.prototype.connect = function(destination) {}; /** * Disconnects this compound node from any destination audio node. */ doodle.moog.CompoundAudioNode.prototype.disconnect = function() { };
010pepe010-moog
compound_audio_node.js
JavaScript
asf20
1,421
// Copyright 2012 Google Inc. All Rights Reserved. // // 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. /** * @fileoverview A moog-like audio synthesizer built on top of the HTML5 Web * Audio API. */ goog.provide('doodle.moog.SynthesizerInterface'); /** * A Moog-like synthesizer built on top of the HTML5 Web Audio API. * @interface */ doodle.moog.SynthesizerInterface = function() {}; /** * Signals that a key on the synthesizer has been pressed. * @param {number} note Chromatic index of the note to be played relative to * the beginning of the keyboard. */ doodle.moog.SynthesizerInterface.prototype.setKeyDown = function(note) {}; /** * Binds a callback to a key down event. * @param {function(number)} callback The function called when a key is pressed. */ doodle.moog.SynthesizerInterface.prototype.setKeyDownCallback = function(callback) {}; /** * Signals that a key on the synthesizer has been released. Since the * synthesizer is monophonic, no note parameter is necessary. */ doodle.moog.SynthesizerInterface.prototype.setKeyUp = function() {}; /** * Increases/decreases the output gain. * @param {number} volume The output volume level. A number in the range * [0..1]. */ doodle.moog.SynthesizerInterface.prototype.setVolume = function(volume) {}; /** * Proxy to the synthesizer's low-pass filter setCutoffFrequency. * @param {number} cutoffFrequency The cutoff frequency above which the * frequencies are attenuated. */ doodle.moog.SynthesizerInterface.prototype.setLpCutoffFrequency = function(cutoffFrequency) {}; /** * Proxy to the synthesizer's low-pass filter setContour. * @param {number} contour Amount of contour to apply to the filter envelope. */ doodle.moog.SynthesizerInterface.prototype.setLpContour = function(contour) {}; /** * Proxy to the synthesizer's low-pass filter setContourAttackTime. * @param {number} time Duration of the attack phase in seconds. */ doodle.moog.SynthesizerInterface.prototype.setLpContourAttackTime = function(time) {}; /** * Proxy to the synthesizer's low-pass filter setContourDecayTime. * @param {number} time Duration of the decay phase in seconds. */ doodle.moog.SynthesizerInterface.prototype.setLpContourDecayTime = function(time) {}; /** * Proxy to the synthesizer's low-pass filter setContourSustainLevel. * @param {number} level The sustain level, a number in the range [0, 1]. */ doodle.moog.SynthesizerInterface.prototype.setLpContourSustainLevel = function(level) {};
010pepe010-moog
synthesizer_interface.js
JavaScript
asf20
3,037
// Copyright 2012 Google Inc. All Rights Reserved. // // 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. /** * @fileoverview Voltage controlled oscillator emulators. */ goog.provide('doodle.moog.Oscillator'); goog.require('doodle.moog.EnvelopeGenerator'); goog.require('doodle.moog.OscillatorInterface'); /** * A voltage controlled oscillator emulator built on the HTML5 Audio API. This * is the root source of all sound in the Moog doodle. * * @param {!AudioContext} audioContext Audio context to which this oscillator * will be bound. * @param {number} volume Initial volume level [0..1]. * @param {!doodle.moog.OscillatorInterface.WaveForm} waveForm Initial wave * form. * @param {!doodle.moog.OscillatorInterface.Range} range Initial pitch range. * @param {number} pitchBend Initial pitch bend [-1..1]. * @param {boolean} isAcceptingKeyboardPitch Whether keyboard control is on. * @param {boolean} isFrequencyModulationOn Whether this oscillator should * modulate its frequency using the modulator control signal. * @param {boolean} isModulator Whether this modulator should act as a modulator * control signal in addition to an audio signal. * @param {number} modulatorLevel If a modulator, how strong the modulator * control signal should be [0..1]. * @param {boolean} isGlideOn Whether glide is on. * @param {number} glideTime Glide time in seconds. * @param {number} attackTime Initial attack time in seconds. * @param {number} decayTime Initial decay time in seconds. * @param {number} sustainLevel Initial sustain level [0..1]. * @constructor * @implements {doodle.moog.OscillatorInterface} */ doodle.moog.Oscillator = function( audioContext, volume, waveForm, range, pitchBend, isAcceptingKeyboardPitch, isFrequencyModulationOn, isModulator, modulatorLevel, isGlideOn, glideTime, attackTime, decayTime, sustainLevel) { /** * How many seconds pass with each sample. * @type {number} * @private * @const */ this.SAMPLE_INTERVAL_ = 1 / audioContext.sampleRate; /** * How many seconds we have advanced in the current cycle. * @type {number} * @private */ this.phase_ = 0.0; /** * The amount of oscillator signal which is fed into the mixer. Mapped onto * the range [0.0, 1.0] where 0 means muted and 1.0 means full loudness. * @type {number} * @private */ this.volume_ = volume; /** * Shape of the wave this oscillator generates. * @type {!doodle.moog.OscillatorInterface.WaveForm} * @private */ this.waveForm_ = waveForm; /** * Octave/range in which the oscillator functions. * @type {!doodle.moog.OscillatorInterface.Range} * @private */ this.range_ = range; /** * Pitch bend to apply on top of the base frequency on the range [-1.0, 1.0]. * If isAcceptingKeyboardPitch_ is true, -1/1 are a major 6th down/up; 0 is no * pitch bend. If isAcceptingKeyboardPitch_ is false, -1/1 are 3 octaves * down/up; 0 is still no pitch bend. * @type {number} * @private */ this.pitchBend_ = pitchBend; /** * Whether the oscillator pitch is controlled by keyboard signals. If true, * the pitch follows the keyboard as one would expect on a piano-like * instrument. If false, pressing any key on the keyboard will result in the * same pitch (as set by range_ and pitchBend_). * @type {boolean} * @private */ this.isAcceptingKeyboardPitch_ = isAcceptingKeyboardPitch; /** * Whether this oscillator should modulate its frequency using the modulator * control signal. * @type {boolean} * @private */ this.isFrequencyModulationOn_ = isFrequencyModulationOn; /** * Whether this modulator should act as a modulator control signal in addition * to an audio signal. * @type {boolean} * @const * @private */ this.IS_MODULATOR_ = isModulator; /** * If this oscillator is also a modulator, how strong the modulator control * signal should be [0..1]. 0 fully attenuates the control signal; 1 fully * applies it. * @type {number} * @private */ this.modulatorLevel_ = modulatorLevel; /** * If this oscillator is also a modulator, a buffer for storing modulator * control signal samples. Null iff this oscillator does not act as a * modulator. * @type {Float32Array} */ this.modulatorSignal = null; /** * Whether glide (portamento sliding between notes) is enabled. * @type {boolean} * @private */ this.isGlideOn_ = isGlideOn; /** * Glide duration in seconds. * @type {number} * @private */ this.glideDuration_ = glideTime; /** * How much to advanced the frequency per sample while gliding. Null until * the first tone is played. * @type {?number} * @private */ this.glideDelta_ = null; /** * Current glide pitch. Null until the first tone is played. * @type {?number} * @private */ this.currentGlidePitch_ = null; /** * Target glide pitch. Null until the first tone is played. * @type {?number} * @private */ this.targetGlidePitch_ = null; /** * Chromatic index of the note to be played relative to the beginning of the * keyboard. * @type {number} * @private */ this.activeNote_ = 0; /** * Envelope generator that will shape the dynamics of this oscillator. * @type {!doodle.moog.EnvelopeGenerator} */ this.envelopeGenerator = new doodle.moog.EnvelopeGenerator( this.SAMPLE_INTERVAL_, attackTime, decayTime, sustainLevel); }; /** * The base frequency (in hertz) from which other notes' frequencies are * calculated. A low 'A'. * @type {number} * @const * @private */ doodle.moog.Oscillator.BASE_FREQUENCY_ = 55; /** * Frequency ratio of major sixth musical interval. * @type {number} * @const * @private */ doodle.moog.Oscillator.MAJOR_SIXTH_FREQUENCY_RATIO_ = 5 / 3; /** * Frequency ratio of a three octave musical interval. * @type {number} * @const * @private */ doodle.moog.Oscillator.THREE_OCTAVE_FREQUENCY_RATIO_ = 8; /** * The chromatic distance between keyboard notes (as passed to * getInstantaneousFrequency_) and low A. * @type {number} * @const * @private */ doodle.moog.Oscillator.NOTE_OFFSET_ = -4; /** @inheritDoc */ doodle.moog.Oscillator.prototype.setVolume = function(volume) { this.volume_ = volume; }; /** @inheritDoc */ doodle.moog.Oscillator.prototype.setWaveForm = function(waveForm) { this.waveForm_ = waveForm; }; /** @inheritDoc */ doodle.moog.Oscillator.prototype.setPitchBend = function(pitchBend) { this.pitchBend_ = pitchBend; }; /** @inheritDoc */ doodle.moog.Oscillator.prototype.setRange = function(range) { this.range_ = range; }; /** @inheritDoc */ doodle.moog.Oscillator.prototype.turnOnKeyboardPitchControl = function() { this.isAcceptingKeyboardPitch_ = true; }; /** @inheritDoc */ doodle.moog.Oscillator.prototype.turnOffKeyboardPitchControl = function() { this.isAcceptingKeyboardPitch_ = false; }; /** @inheritDoc */ doodle.moog.Oscillator.prototype.turnOnFrequencyModulation = function() { this.isFrequencyModulationOn_ = true; }; /** @inheritDoc */ doodle.moog.Oscillator.prototype.turnOffFrequencyModulation = function() { this.isFrequencyModulationOn_ = false; }; /** @inheritDoc */ doodle.moog.Oscillator.prototype.setModulatorLevel = function(modulatorLevel) { this.modulatorLevel_ = modulatorLevel; }; /** @inheritDoc */ doodle.moog.Oscillator.prototype.turnOnGlide = function() { this.isGlideOn_ = true; }; /** @inheritDoc */ doodle.moog.Oscillator.prototype.turnOffGlide = function() { this.isGlideOn_ = false; }; /** @inheritDoc */ doodle.moog.Oscillator.prototype.setGlideDuration = function(time) { this.glideDuration_ = time; }; /** @inheritDoc */ doodle.moog.Oscillator.prototype.setActiveNote = function(note) { this.activeNote_ = note; }; /** @inheritDoc */ doodle.moog.Oscillator.prototype.setEnvelopeGeneratorAttackTime = function(attackTime) { this.envelopeGenerator.setAttackTime(attackTime); }; /** @inheritDoc */ doodle.moog.Oscillator.prototype.setEnvelopeGeneratorDecayTime = function(decayTime) { this.envelopeGenerator.setDecayTime(decayTime); }; /** @inheritDoc */ doodle.moog.Oscillator.prototype.setEnvelopeGeneratorSustainLevel = function(sustainLevel) { this.envelopeGenerator.setSustainLevel(sustainLevel); }; /** * Gets the instantaneous frequency that this oscillator ought to be generating. * @param {number} note Chromatic index of the note to be played relative to * the beginning of the keyboard. * @return {number} The instantaneous frequency. * @private */ doodle.moog.Oscillator.prototype.getInstantaneousFrequency_ = function(note) { if (!this.isAcceptingKeyboardPitch_) { note = 0; } return doodle.moog.Oscillator.BASE_FREQUENCY_ * this.range_ * Math.pow(2, (note + doodle.moog.Oscillator.NOTE_OFFSET_) / 12); }; /** * Gets the pitch bend that should be applied to this oscillator. * @return {number} The frequency ratio that should be applied to the base * pitch. * @private */ doodle.moog.Oscillator.prototype.getPitchBend_ = function() { var pitchBendScale = doodle.moog.Oscillator.MAJOR_SIXTH_FREQUENCY_RATIO_; if (!this.isAcceptingKeyboardPitch_) { pitchBendScale = doodle.moog.Oscillator.THREE_OCTAVE_FREQUENCY_RATIO_; } var normalizedPitchBend = Math.abs(this.pitchBend_ * (pitchBendScale - 1)) + 1; return this.pitchBend_ >= 0 ? normalizedPitchBend : 1 / normalizedPitchBend; }; /** * Gets the frequency this oscillator ought to generate after undergoing * optional glide. * @param {number} target The target frequency to move towards. * @return {number} The frequency this oscillator should generate with glide. * @private */ doodle.moog.Oscillator.prototype.getGlideFrequency_ = function(target) { if (!this.isGlideOn_ || this.currentGlidePitch_ === null || this.glideDuration_ <= 0 || Math.abs(this.currentGlidePitch_ - target) <= Math.abs(this.glideDelta_)) { this.currentGlidePitch_ = this.targetGlidePitch_ = target; return target; } if (this.targetGlidePitch_ != target) { var glideDurationInSamples = this.glideDuration_ / this.SAMPLE_INTERVAL_; this.glideDelta_ = (target - this.currentGlidePitch_) / glideDurationInSamples; this.targetGlidePitch_ = target; } this.currentGlidePitch_ += this.glideDelta_; return this.currentGlidePitch_; }; /** * Gets the frequency this oscillator ought to generate after undergoing * optional frequency modulation. * @param {number} baseFrequency The base frequency to modulate. * @param {Float32Array} modulatorSignal Modulator signal buffer to apply to * this oscillator. If null, no modulation should be applied. * @param {number} index Sample index of the modulation signal to apply. * @return {number} The frequency this oscillator should generate with * modulation. * @private */ doodle.moog.Oscillator.prototype.getModulationFrequency_ = function( baseFrequency, modulatorSignal, index) { if (!modulatorSignal || !this.isFrequencyModulationOn_) { return baseFrequency; } // Linearly project modulation level [0..1] onto [0.5..2] (down/up an octave). // TODO: Re-evaluate this maximum frequency modulation range based on real // Moog behavior. return (modulatorSignal[index] * 0.75 + 1.25) * baseFrequency; }; /** * Advances the oscillator's phase of play. This helper function must be called * exactly once per sample. * @param {number} frequency The frequency being played. * @return {number} Progress made in the current cycle, projected on the range * [0, 1]. * @private */ doodle.moog.Oscillator.prototype.advancedPhase_ = function(frequency) { var cycleLengthInSeconds = 2 / frequency; if (this.phase_ > cycleLengthInSeconds) { this.phase_ -= cycleLengthInSeconds; } var progressInCycle = this.phase_ * frequency / 2; this.phase_ += this.SAMPLE_INTERVAL_; return progressInCycle; }; /** * Fills the passed audio buffer with the tone represented by this oscillator. * @param {!AudioProcessingEvent} e The audio process event object. * @param {Float32Array} modulatorSignal Modulator signal buffer to apply to * this oscillator. If null, no modulation will be applied. * @param {!doodle.moog.OscillatorInterface.FillMode} fillMode How the * oscillator should fill the passed audio buffer. * @param {number=} opt_mixDivisor Iff using FillMode.MIX, how much to mix down * the buffer. This should usually be the number of oscillators that have * added data to the buffer. */ doodle.moog.Oscillator.prototype.fillAudioBuffer = function( e, modulatorSignal, fillMode, opt_mixDivisor) { var buffer = e.outputBuffer; var left = buffer.getChannelData(1); var right = buffer.getChannelData(0); if (this.IS_MODULATOR_ && !this.modulatorSignal) { this.modulatorSignal = new Float32Array(buffer.length); } var targetFrequency = this.getInstantaneousFrequency_(this.activeNote_); var pitchBend = this.getPitchBend_(); var frequency = targetFrequency * pitchBend; var audioLevel, envelopeCoefficient, level, on, progressInCycle, ramp; for (var i = 0; i < buffer.length; ++i) { envelopeCoefficient = this.envelopeGenerator.getNextAmplitudeCoefficient(); progressInCycle = this.advancedPhase_( pitchBend * this.getModulationFrequency_( this.getGlideFrequency_(targetFrequency), modulatorSignal, i)); switch (this.waveForm_) { case doodle.moog.OscillatorInterface.WaveForm.TRIANGLE: level = 4 * ((progressInCycle > 0.5 ? 1 - progressInCycle : progressInCycle) - .25); break; case doodle.moog.OscillatorInterface.WaveForm.SAWANGLE: ramp = progressInCycle < 0.5; level = ramp ? (4 * progressInCycle - 1) : (-2 * progressInCycle + 1); break; case doodle.moog.OscillatorInterface.WaveForm.RAMP: level = 2 * (progressInCycle - 0.5); break; case doodle.moog.OscillatorInterface.WaveForm.REVERSE_RAMP: level = -2 * (progressInCycle - 0.5); break; case doodle.moog.OscillatorInterface.WaveForm.SQUARE: level = progressInCycle < 0.5 ? 1 : -1; break; case doodle.moog.OscillatorInterface.WaveForm.FAT_PULSE: level = progressInCycle < 1 / 3 ? 1 : -1; break; case doodle.moog.OscillatorInterface.WaveForm.PULSE: level = progressInCycle < 0.25 ? 1 : -1; break; } if (this.IS_MODULATOR_) { this.modulatorSignal[i] = level * this.modulatorLevel_; } audioLevel = level * this.volume_ * envelopeCoefficient; if (fillMode == doodle.moog.OscillatorInterface.FillMode.CLOBBER) { right[i] = audioLevel; } else if (fillMode == doodle.moog.OscillatorInterface.FillMode.ADD) { right[i] = right[i] + audioLevel; } else { // Otherwise FillMode.MIX. right[i] = (right[i] + audioLevel) / opt_mixDivisor; // In older versions of Chrome, Web Audio API always created two // channels even if you have requested monaural sound. However, this // is not the case in the newer (dev/canary) versions. This should // cover both. if (left) { left[i] = right[i]; } } } };
010pepe010-moog
oscillator.js
JavaScript
asf20
15,905
// Copyright 2012 Google Inc. All Rights Reserved. // // 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. /** * @fileoverview Provides a wide band pass filter to protect headphones and * speakers from really low and high frequencies. */ goog.provide('doodle.moog.WideBandPassFilter'); goog.require('doodle.moog.CompoundAudioNode'); /** * A wide band pass filter designed to filter out low and high frequencies that * might damage poorly made speakers connected to poorly made sound cards. * @param {!AudioContext} audioContext Audio context to which this oscillator * will be bound. * @param {number} lowCutoffFrequency The cutoff frequency below which sound is * attenuated. * @param {number} highCutoffFrequency The cutoff frequency above which sound is * attenuated. * @constructor * @implements {doodle.moog.CompoundAudioNode} */ doodle.moog.WideBandPassFilter = function( audioContext, lowCutoffFrequency, highCutoffFrequency) { /** * The low pass filter Web Audio node. * @type {!BiquadFilterNode} * @private */ this.lowPassFilterNode_ = audioContext.createBiquadFilter(); this.lowPassFilterNode_.type = doodle.moog.WideBandPassFilter.LOW_PASS_FILTER_TYPE_ID_; this.lowPassFilterNode_.frequency.value = highCutoffFrequency; /** * The high pass filter Web Audio node. * @type {!BiquadFilterNode} * @private */ this.highPassFilterNode_ = audioContext.createBiquadFilter(); this.highPassFilterNode_.type = doodle.moog.WideBandPassFilter.HIGH_PASS_FILTER_TYPE_ID_; this.highPassFilterNode_.frequency.value = lowCutoffFrequency; this.lowPassFilterNode_.connect(this.highPassFilterNode_); }; /** * Biquad Filter type ID for a low pass filter (from the Web Audio spec). * @type {number} * @const * @private */ doodle.moog.WideBandPassFilter.LOW_PASS_FILTER_TYPE_ID_ = 0; /** * Biquad Filter type ID for a low pass filter (from the Web Audio spec). * @type {number} * @const * @private */ doodle.moog.WideBandPassFilter.HIGH_PASS_FILTER_TYPE_ID_ = 1; /** @inheritDoc */ doodle.moog.WideBandPassFilter.prototype.getSourceNode = function() { return this.lowPassFilterNode_; }; /** @inheritDoc */ doodle.moog.WideBandPassFilter.prototype.connect = function(destination) { this.highPassFilterNode_.connect(destination); }; /** @inheritDoc */ doodle.moog.WideBandPassFilter.prototype.disconnect = function() { this.highPassFilterNode_.disconnect(); };
010pepe010-moog
wide_band_pass_filter.js
JavaScript
asf20
2,965
// Copyright 2012 Google Inc. All Rights Reserved. // // 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. /** * @fileoverview Master mixer interface for all doodle Web Audio sources. */ goog.provide('doodle.moog.MasterMixerInterface'); /** * Master mixer for the multiple virtual synthesizers that may play back * simultaneously via the Sequencer. * @interface */ doodle.moog.MasterMixerInterface = function() {}; /** * Turns on the mixer. */ doodle.moog.MasterMixerInterface.prototype.turnOn = function() {}; /** * Turns off the mixer. */ doodle.moog.MasterMixerInterface.prototype.turnOff = function() {};
010pepe010-moog
master_mixer_interface.js
JavaScript
asf20
1,129
// Copyright 2012 Google Inc. All Rights Reserved. // // 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. /** * @fileoverview Main module for the Dr. Robert Moog Synthesizer doodle. */ goog.provide('doodle.moog.Moog'); goog.require('doodle.moog.LowPassFilter'); goog.require('doodle.moog.MasterMixer'); goog.require('doodle.moog.Oscillator'); goog.require('doodle.moog.OscillatorInterface'); goog.require('doodle.moog.Synthesizer'); goog.require('doodle.moog.WideBandPassFilter'); goog.require('goog.Disposable'); /** * The Moog doodle manager. * @constructor * @extends {goog.Disposable} */ doodle.moog.Moog = function() { goog.base(this); /** * The set of available synthesizers. * @type {!Array.<!doodle.moog.SynthesizerInterface>} * @private */ this.synthesizers_ = []; /** * A reference to a master mixer instance. * @type {!doodle.moog.MasterMixerInterface} * @private */ this.masterMixer_; /** * @private */ this.isWebAudioEnabled_ = typeof webkitAudioContext === 'function'; if (this.isWebAudioEnabled_) { this.initializeWebAudio_(); } }; goog.inherits(doodle.moog.Moog, goog.Disposable); /** @inheritDoc */ doodle.moog.Moog.prototype.disposeInternal = function() { goog.base(this, 'disposeInternal'); this.turnOffAudio(); }; /** * Initializes the Moog doodle on WebAudio-compatible browsers. * @private */ doodle.moog.Moog.prototype.initializeWebAudio_ = function() { try { // Audio context creation can throw an error if the user is missing sound // drivers, etc. var audioContext = new webkitAudioContext(); } catch(e7) { // Abort the initialization sequence like we do with flash. return; } var oscillators = [ new doodle.moog.Oscillator( audioContext, 0.46, doodle.moog.OscillatorInterface.WaveForm.SQUARE, doodle.moog.OscillatorInterface.Range.R16, 0, true, false, false, 0, true, 0.05, 0, 0.4, 1), new doodle.moog.Oscillator( audioContext, 0.82, doodle.moog.OscillatorInterface.WaveForm.SQUARE, doodle.moog.OscillatorInterface.Range.R4, 0, true, false, false, 0, true, 0.05, 0, 0.4, 1), new doodle.moog.Oscillator( audioContext, 0.46, doodle.moog.OscillatorInterface.WaveForm.SQUARE, doodle.moog.OscillatorInterface.Range.R32, 0, true, false, true, 0.6, true, 0.05, 0, 0.4, 1) ]; var lowPassFilter = new doodle.moog.LowPassFilter( audioContext, 2100, 7, 0, .8, 0); this.synthesizers_.push(new doodle.moog.Synthesizer( audioContext, oscillators, lowPassFilter, 0.82)); var wideBandPassFilter = new doodle.moog.WideBandPassFilter( audioContext, 20, 20000); this.masterMixer_ = new doodle.moog.MasterMixer( audioContext, this.synthesizers_, wideBandPassFilter); }; /** * Turns on the audio pipeline. */ doodle.moog.Moog.prototype.turnOnAudio = function() { if (this.masterMixer_) { this.masterMixer_.turnOn(); } }; /** * Turns off the audio pipeline. */ doodle.moog.Moog.prototype.turnOffAudio = function() { if (this.masterMixer_) { this.masterMixer_.turnOff(); } };
010pepe010-moog
moog.js
JavaScript
asf20
3,633
// Copyright 2012 Google Inc. All Rights Reserved. // // 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. /** * @fileoverview Master mixer for all doodle Web Audio sources. */ goog.provide('doodle.moog.MasterMixer'); goog.require('doodle.moog.MasterMixerInterface'); /** * Master mixer for the multiple virtual synthesizers that may play back * simultaneously via the Sequencer. * @param {!AudioContext} audioContext Audio context in which this mixer will * operate. * @param {!Array.<!doodle.moog.SynthesizerInterface>} synthesizers The * synthesizers that feed into this mixer. * @param {!doodle.moog.WideBandPassFilter} wideBandPassFilter The wide band * pass filter used within this mixer. * @constructor * @implements {doodle.moog.MasterMixerInterface} */ doodle.moog.MasterMixer = function( audioContext, synthesizers, wideBandPassFilter) { /** * The audio context in which this mixer operates. * @type {!AudioContext} * @private */ this.audioContext_ = audioContext; /** * The synthesizers this mixer mixes. * @type {!Array.<!doodle.moog.Synthesizer>} * @private */ this.synthesizers_ = synthesizers; /** * Filter used to cut out really low/high frequencies. * @type {!doodle.moog.WideBandPassFilter} * @private */ this.wideBandPassFilter_ = wideBandPassFilter; for (var i = 0; i < synthesizers.length; i++) { synthesizers[i].connect(wideBandPassFilter.getSourceNode()); } }; /** @inheritDoc */ doodle.moog.MasterMixer.prototype.turnOn = function() { window.setTimeout(goog.bind(function() { // NOTE: The audio pipeline is connected in a setTimeout to avoid a Chrome // bug in which the audio will occasionally fail to initialize/play. this.wideBandPassFilter_.connect(this.audioContext_.destination); }, this), 0); }; /** @inheritDoc */ doodle.moog.MasterMixer.prototype.turnOff = function() { this.wideBandPassFilter_.disconnect(); };
010pepe010-moog
master_mixer.js
JavaScript
asf20
2,462
#include <iostream> using namespace std; int main() { int height; float eyesight; height = 175; eyesight = 0.8f; bool ok; ok = height >= 160 && height <=180 && eyesight >= 1.0f && eyesight <= 2.0f; cout << boolalpha; cout << ok << endl; return 0; }
103956-kirak-cpp
helloWorld/helloWorld/HelloWorld.cpp
C++
asf20
285
int main() { int a = 100; int b = 200; int c = 300; return 0; }
103956-kirak-cpp
test/test/test.cpp
C++
asf20
81
#include<iostream> using namespace std; void main() { int a[10], i; for(i=0; i<10; i++) a[i]=i+1; for(i=0; i<10; i++) cout << a[i] << " "; cout <<"\n"; }
103956-kirak-cpp
CLASS6_1/CLASS6_1/CLASS6.cpp
C++
asf20
210
if False: # set to True to insert test data store(store.product.id > 0).delete() store(store.category.id > 0).delete() if len(store(store.product.id > 0).select()) == 0: fantasy_id = store.category.insert(name='Fantasy', description='Fantasy books', small_image='testdata/hp1.jpg') hp1 = store.product.insert(name="Harry Potter and the Sorcerer's Stone", category=fantasy_id, price=7.91, small_image='testdata/hp1.jpg') hp2 = store.product.insert(name="Harry Potter and the Chamber of Secrets", category=fantasy_id, price=8.91, small_image='testdata/hp2.jpg') hp3 = store.product.insert(name="Harry Potter and the Prisoner of Azkaban", category=fantasy_id, price=8.91, small_image='testdata/hp3.jpg') hp4 = store.product.insert(name="Harry Potter and the Goblet of Fire", category=fantasy_id, price=9.91, small_image='testdata/hp4.jpg') hp5 = store.product.insert(name="Harry Potter and the Order of the Phoenix", category=fantasy_id, price=9.91, small_image='testdata/hp5.jpg') hp6 = store.product.insert(name="Harry Potter and the Half-Blood Prince", category=fantasy_id, price=9.91, small_image='testdata/hp6.jpg') store.option.insert(product=hp1, description='Bookmark', price=1.5) store.option.insert(product=hp1, description='Wizard hat', price=12) for p2 in (hp2, hp3, hp4, hp5, hp6): store.cross_sell.insert(p1=hp1, p2=p2) hp1_hard = store.product.insert(name="Harry Potter and the Sorcerer's Stone [hardcover]", category=fantasy_id, price=15.91, small_image='testdata/hp1.jpg') store.up_sell.insert(product=hp1, better=hp1_hard)
0707tim-web2pestore
models/testdata.py
Python
gpl2
1,693
UNDEFINED = -1 if request.env.web2py_runtime_gae: # if running on Google App Engine store = DAL('gae') # connect to Google BigTable session.connect(request, response, db=store) # and store sessions and tickets there else: store = DAL("sqlite://store.db") store.define_table('category', Field('name'), Field('description', 'text'), Field('small_image', 'upload'), ) store.define_table('product', Field('name'), Field('category', store.category), Field('description', 'text', default=''), Field('small_image', 'upload'), Field('large_image', 'upload', default=''), Field('quantity_in_stock', 'integer', default=UNDEFINED), # if UNDEFINED, don't show Field('max_quantity', 'integer', default=0), # maximum quantity that can be purchased in an order. If 0, no limit. If UNDEFINED, don't show. Field('price', 'double', default=1.0), Field('old_price', 'double', default=0.0), Field('weight_in_pounds', 'double', default=1), Field('tax_rate_in_your_state', 'double', default=10.0), Field('tax_rate_outside_your_state', 'double', default=0.0), Field('featured', 'boolean', default=False), Field('allow_rating', 'boolean', default=False), Field('rating', 'integer', default='0'), Field('viewed', 'integer', default='0'), Field('clicked', 'integer', default='0')) # each product can have optional addons store.define_table('option', Field('product', store.product), Field('description'), Field('price', 'double', default=1.0), ) # support for merchandising # for p1 show p2, and for p2 show p1 store.define_table('cross_sell', Field('p1', store.product), Field('p2', store.product), ) # for product, show better, but not the reverse store.define_table('up_sell', Field('product', store.product), Field('better', store.product), ) store.define_table('comment', Field('product', store.product), Field('author'), Field('email'), Field('body', 'text'), Field('rate', 'integer') ) store.define_table('info', Field('google_merchant_id', default='[google checkout id]', length=256), Field('name', default='[store name]'), Field('headline', default='[store headline]'), Field('address', default='[store address]'), Field('city', default='[store city]'), Field('state', default='[store state]'), Field('zip_code', default='[store zip]'), Field('phone', default='[store phone number]'), Field('fax', default='[store fax number]'), Field('email', requires=IS_EMAIL(), default='yourname@yourdomain.com'), Field('description', 'text', default='[about your store]'), Field('why_buy', 'text', default='[why buy at your store]'), Field('return_policy', 'text', default='[what is your return policy]'), Field('logo', 'upload', default=''), Field('color_background', length=10, default='white'), Field('color_foreground', length=10, default='black'), Field('color_header', length=10, default='#F6F6F6'), Field('color_link', length=10, default='#385ea2'), Field('font_family', length=32, default='arial, helvetica'), Field('ship_usps_express_mail', 'boolean', default=True), Field('ship_usps_express_mail_fc', 'double', default=0), Field('ship_usps_express_mail_vc', 'double', default=0), Field('ship_usps_express_mail_bc', 'double', default=0), Field('ship_usps_priority_mail', 'boolean', default=True), Field('ship_usps_priority_mail_fc', 'double', default=0), Field('ship_usps_priority_mail_vc', 'double', default=0), Field('ship_usps_priority_mail_bc', 'double', default=0), Field('ship_ups_next_day_air', 'boolean', default=True), Field('ship_ups_next_day_air_fc', 'double', default=0), Field('ship_ups_next_day_air_vc', 'double', default=0), Field('ship_ups_next_day_air_bc', 'double', default=0), Field('ship_ups_second_day_air', 'boolean', default=True), Field('ship_ups_second_day_air_fc', 'double', default=0), Field('ship_ups_second_day_air_vc', 'double', default=0), Field('ship_ups_second_day_air_bc', 'double', default=0), Field('ship_ups_ground', 'boolean', default=True), Field('ship_ups_ground_fc', 'double', default=0), Field('ship_ups_ground_vc', 'double', default=0), Field('ship_ups_ground_bc', 'double', default=0), Field('ship_fedex_priority_overnight', 'boolean', default=True), Field('ship_fedex_priority_overnight_fc', 'double', default=0), Field('ship_fedex_priority_overnight_vc', 'double', default=0), Field('ship_fedex_priority_overnight_bc', 'double', default=0), Field('ship_fedex_second_day', 'boolean', default=True), Field('ship_fedex_second_day_fc', 'double', default=0), Field('ship_fedex_second_day_vc', 'double', default=0), Field('ship_fedex_second_day_bc', 'double', default=0), Field('ship_fedex_ground', 'boolean', default=True), Field('ship_fedex_ground_fc', 'double', default=0), Field('ship_fedex_ground_vc', 'double', default=0), Field('ship_fedex_ground_bc', 'double', default=0) ) store.category.name.requires = IS_NOT_IN_DB(store, 'category.name') store.product.name.requires = IS_NOT_IN_DB(store, 'product.name') store.product.category.requires = IS_IN_DB(store, 'category.id', 'category.name') store.product.name.requires = IS_NOT_EMPTY() store.product.description.requires = IS_NOT_EMPTY() store.product.quantity_in_stock.requires = IS_INT_IN_RANGE(0, 1000) store.product.price.requires = IS_FLOAT_IN_RANGE(0, 10000) store.product.rating.requires = IS_INT_IN_RANGE(-10000, 10000) store.product.viewed.requires = IS_INT_IN_RANGE(0, 1000000) store.product.clicked.requires = IS_INT_IN_RANGE(0, 1000000) store.option.product.requires = IS_IN_DB(store, 'product.id', 'product.name') store.cross_sell.p1.requires = IS_IN_DB(store, 'product.id', 'product.name') store.cross_sell.p2.requires = IS_IN_DB(store, 'product.id', 'product.name') store.up_sell.product.requires = IS_IN_DB(store, 'product.id', 'product.name') store.up_sell.better.requires = IS_IN_DB(store, 'product.id', 'product.name') store.comment.product.requires = IS_IN_DB(store, 'product.id', 'product.name') store.comment.author.requires = IS_NOT_EMPTY() store.comment.email.requires = IS_EMAIL() store.comment.body.requires = IS_NOT_EMPTY() store.comment.rate.requires = IS_IN_SET(range(5, 0, -1)) for field in store.info.fields: if field[:-2] in ['fc', 'vc']: store.info[field].requires = IS_FLOAT_IN_RANGE(0, 100) if len(store(store.info.id > 0).select()) == 0: store.info.insert(name='[store name]') mystore = store(store.info.id > 0).select()[0]
0707tim-web2pestore
models/store.py
Python
gpl2
6,730
# import re # delimiter to use between words in URL URL_DELIMITER = '-' def pretty_url(id, name): """Create pretty URL from record name and ID """ return '%s%s%d' % (' '.join(re.sub('[^\w ]+', '', name).split()).replace(' ', URL_DELIMITER), URL_DELIMITER, id) def pretty_id(url): """Extract id from pretty URL """ return int(url.rpartition(URL_DELIMITER)[-1]) def pretty_text(s): "Make text pretty by capitalizing and using 'home' instead of 'default'" return s.replace('default', 'home').replace('_', ' ').capitalize() def title(): if response.title: return response.title elif request.function == 'index': return pretty_text(request.controller) else: return pretty_text(request.function)
0707tim-web2pestore
models/globals.py
Python
gpl2
779
########################################################### ### make sure administrator is on localhost ############################################################ import os, socket, datetime,copy import gluon.contenttype import gluon.fileutils ### crytical --- make a copy of the environment global_env=copy.copy(globals()) global_env['datetime']=datetime http_host = request.env.http_host.split(':')[0] remote_addr = request.env.remote_addr try: hosts=(http_host, socket.gethostbyname(remote_addr)) except: hosts=(http_host,) if remote_addr not in hosts: pass #raise HTTP(400) if not gluon.fileutils.check_credentials(request): redirect('/admin') response.view='appadmin.html' response.menu=[[T('design'),False,URL('admin','default','design', args=[request.application])], [T('db'),False,URL(r=request,f='index')], [T('state'),False,URL(r=request,f='state')]] ########################################################### ### auxiliary functions ############################################################ def get_databases(request): dbs={} for key,value in global_env.items(): cond=False try: cond=isinstance(value,GQLDB) except: cond=isinstance(value,SQLDB) if cond: dbs[key]=value return dbs databases=get_databases(None) def eval_in_global_env(text): exec('_ret=%s'%text,{},global_env) return global_env['_ret'] def get_database(request): if request.args and request.args[0] in databases: return eval_in_global_env(request.args[0]) else: session.flash=T('invalid request') redirect(URL(r=request,f='index')) def get_table(request): db=get_database(request) if len(request.args)>1 and request.args[1] in db.tables: return db,request.args[1] else: session.flash=T('invalid request') redirect(URL(r=request,f='index')) def get_query(request): try: return eval_in_global_env(request.vars.query) except Exception: return None ########################################################### ### list all databases and tables ############################################################ def index(): return dict(databases=databases) ########################################################### ### insert a new record ############################################################ def insert(): db,table=get_table(request) form=SQLFORM(db[table]) if form.accepts(request.vars,session): response.flash=T('new record inserted') return dict(form=form) ########################################################### ### list all records in table and insert new record ############################################################ def download(): import os db=get_database(request) filename=request.args[1] print filename ### for GAE only ### table,field=filename.split('.')[:2] if table in db.tables and field in db[table].fields: uploadfield=db[table][field].uploadfield if isinstance(uploadfield,str): from gluon.contenttype import contenttype response.headers['Content-Type']=contenttype(filename) rows=db(db[table][field]==filename).select() return rows[0][uploadfield] ### end for GAE ### path=os.path.join(request.folder,'uploads/',filename) return response.stream(open(path,'rb')) def csv(): import gluon.contenttype response.headers['Content-Type']=gluon.contenttype.contenttype('.csv') query=get_query(request) if not query: return None response.headers['Content-disposition']="attachment; filename=%s_%s.csv"%\ tuple(request.vars.query.split('.')[:2]) return str(db(query).select()) def import_csv(table,file): import csv reader = csv.reader(file) colnames=None for line in reader: if not colnames: colnames=[x[x.find('.')+1:] for x in line] c=[i for i in range(len(line)) if colnames[i]!='id'] else: items=[(colnames[i],line[i]) for i in c] table.insert(**dict(items)) def select(): import re db=get_database(request) dbname=request.args[0] regex=re.compile('(?P<table>\w+)\.(?P<field>\w+)=(?P<value>\d+)') if request.vars.query: match=regex.match(request.vars.query) if match: request.vars.query='%s.%s.%s==%s' % (request.args[0],match.group('table'),match.group('field'),match.group('value')) else: request.vars.query=session.last_query query=get_query(request) if request.vars.start: start=int(request.vars.start) else: start=0 nrows=0 stop=start+100 table=None rows=[] orderby=request.vars.orderby if orderby: orderby=dbname+'.'+orderby if orderby==session.last_orderby: if orderby[0]=='~': orderby=orderby[1:] else: orderby='~'+orderby session.last_orderby=orderby session.last_query=request.vars.query form=FORM(TABLE(TR('Query:','',INPUT(_style='width:400px',_name='query',_value=request.vars.query or '',requires=IS_NOT_EMPTY())), TR('Update:',INPUT(_name='update_check',_type='checkbox',value=False), INPUT(_style='width:400px',_name='update_fields',_value=request.vars.update_fields or '')), TR('Delete:',INPUT(_name='delete_check',_class='delete',_type='checkbox',value=False),''), TR('','',INPUT(_type='submit',_value='submit')))) if request.vars.csvfile!=None: try: import_csv(db[request.vars.table],request.vars.csvfile.file) response.flash=T('data uploaded') except: response.flash=T('unable to parse csv file') if form.accepts(request.vars,formname=None): regex=re.compile(request.args[0]+'\.(?P<table>\w+)\.id\>0') match=regex.match(form.vars.query.strip()) if match: table=match.group('table') try: nrows=db(query).count() if form.vars.update_check and form.vars.update_fields: db(query).update(**eval_in_global_env('dict(%s)'%form.vars.update_fields)) response.flash=T('%s rows updated',nrows) elif form.vars.delete_check: db(query).delete() response.flash=T('%s rows deleted',nrows) nrows=db(query).count() if orderby: rows=db(query).select(limitby=(start,stop), orderby=eval_in_global_env(orderby)) else: rows=db(query).select(limitby=(start,stop)) except: rows,nrows=[],0 response.flash=T('Invalid Query') return dict(form=form,table=table,start=start,stop=stop,nrows=nrows,rows=rows,query=request.vars.query) ########################################################### ### edit delete one record ############################################################ def update(): db,table=get_table(request) try: id=int(request.args[2]) record=db(db[table].id==id).select()[0] except: session.flash=T('record does not exist') redirect(URL(r=request,f='select',args=request.args[:1],vars=dict(query='%s.%s.id>0'%tuple(request.args[:2])))) form=SQLFORM(db[table],record,deletable=True, linkto=URL(r=request,f='select',args=request.args[:1]), upload=URL(r=request,f='download',args=request.args[:1])) if form.accepts(request.vars,session): response.flash=T('done!') redirect(URL(r=request,f='select',args=request.args[:1],vars=dict(query='%s.%s.id>0'%tuple(request.args[:2])))) return dict(form=form) ########################################################### ### get global variables ############################################################ def state(): return dict()
0707tim-web2pestore
controllers/appadmin.py
Python
gpl2
7,872
if not session.cart: # instantiate new cart session.cart, session.balance = [], 0 session.google_merchant_id = mystore.google_merchant_id response.menu = [ ['Store Front', request.function == 'index', URL(r=request, f='index')], ['About Us', request.function == 'aboutus', URL(r=request, f='aboutus')], ['Contact Us', request.function == 'contactus', URL(r=request, f='contactus')], ['Shopping Cart $%.2f' % float(session.balance), request.function == 'checkout', URL(r=request, f='checkout')] ] def index(): categories = store().select(store.category.ALL, orderby=store.category.name) featured = store(store.product.featured == True).select() return dict(categories=categories,featured=featured) def category(): if not request.args: redirect(URL(r=request, f='index')) category_id = pretty_id(request.args[0]) if len(request.args) == 3: # pagination start, stop = int(request.args[1]), int(request.args[2]) else: start, stop = 0, 20 categories = store().select(store.category.ALL, orderby=store.category.name) category_name = None for category in categories: if category.id == category_id: response.title = category_name = category.name if not category_name: redirect(URL(r=request, f='index')) if start == 0: featured = store(store.product.featured == True)(store.product.category == category_id).select() else: featured = [] ids = [p.id for p in featured] favourites = store(store.product.category == category_id).select(limitby=(start, stop)) favourites = [f for f in favourites if f.id not in ids] return dict(category_name=category_name, categories=categories, featured=featured, favourites=favourites) def product(): if not request.args: redirect(URL(r=request, f='index')) product_id = pretty_id(request.args[0]) products = store(store.product.id == product_id).select() if not products: redirect(URL(r=request, f='index')) product = products[0] response.title = product.name product.update_record(viewed=product.viewed+1) options = store(store.option.product == product.id).select() product_form = FORM( TABLE( [TR(TD(INPUT(_name='option', _value=option.id, _type='checkbox', _onchange="update_price(this, %.2f)" % option.price), option.description), H3('$%.2f' % option.price)) for option in options], TR( 'Price:', H2('$%.2f' % float(product.price), _id='total_price') ), BR(), TH('Qty:', INPUT(_name='quantity', _class='integer', _value=1, _size=1)), INPUT(_type='submit', _value='Add to cart'), ) ) if product_form.accepts(request.vars, session): quantity = int(product_form.vars.quantity) option_ids = product_form.vars.option if not isinstance(option_ids, list): option_ids = [option_ids] if option_ids else [] option_ids = [int(o) for o in option_ids] product.update_record(clicked=product.clicked+1) session.cart.append((product_id, quantity, option_ids)) redirect(URL(r=request, f='checkout')) # post a comment about a product comment_form = SQLFORM(store.comment, fields=['author', 'email', 'body', 'rate']) comment_form.vars.product = product.id if comment_form.accepts(request.vars, session): nc = store(store.comment.product == product.id).count() t = products[0].rating*nc + int(comment_form.vars.rate) products[0].update_record(rating=t/(nc+1)) response.flash = 'comment posted' if comment_form.errors: response.flash = 'invalid comment' comments = store(store.comment.product == product.id).select() better_ids = [row.better for row in store(store.up_sell.product == product.id).select(store.up_sell.better)] related_ids = [row.p2 for row in store(store.cross_sell.p1 == product.id).select()] + [row.p1 for row in store(store.cross_sell.p2 == product.id).select()] suggested = [store.product[id] for id in better_ids + related_ids] # XXXstore(store.product.id.belongs(better_ids + related_ids)).select() return dict(product=product, comments=comments, options=options, suggested=suggested, product_form=product_form, comment_form=comment_form) """ {{ if product.old_price: }} <b>was ${{= '%.2f' % float(product.old_price) }}</b> {{ pass }} </form> """ def remove_from_cart(): # remove product from cart del session.cart[int(request.args[0])] redirect(URL(r=request, f='checkout')) def empty_cart(): # empty cart of all products session.cart.clear() session.balance = 0 redirect(URL(r=request, f='checkout')) def checkout(): order = [] balance = 0 for product_id, qty, option_ids in session.cart: products = store(store.product.id == product_id).select() if products: product = products[0] options = [store.option[id] for id in option_ids]# XXX store(store.option.id.belongs(option_ids)).select() if option_ids else [] total_price = qty * (product.price + sum([option.price for option in options])) order.append((product_id, qty, total_price, product, options)) balance += total_price else: # invalid product pass session.balance = balance # XXX is updating in time? return dict(order=order, merchant_id=session.google_merchant_id) def popup(): return dict() def show(): response.session_id = None import gluon.contenttype, os filename = '/'.join(request.args) response.headers['Content-Type'] = gluon.contenttype.contenttype(filename) # XXX is this path going to be a problem on Windows? return open(os.path.join(request.folder, 'uploads', filename), 'rb').read() def aboutus(): return dict() def contactus(): return dict()
0707tim-web2pestore
controllers/default.py
Python
gpl2
5,948
########################################################### ### make sure administrator is on localhost ############################################################ import os from gluon.contenttype import contenttype from gluon.fileutils import check_credentials, listdir if not session.authorized and not request.function=='login': redirect(URL(r=request,f='login')) response.view='manage.html' response.menu=[['manage',True,'/%s/manage/index' % (request.application)], ['logout',False,'/%s/manage/logout' % (request.application)], ['back to store',False,'/%s/default/index' % (request.application)]] ########################################################### ### list all tables in database ############################################################ def login(): response.view='manage/login.html' from gluon.fileutils import check_credentials if check_credentials(request,'admin'): session.authorized=True redirect(URL(r=request,f='index')) return dict() def logout(): session.authorized=False redirect(URL(r=request,c='default',f='index')) def index(): import types as _types _dbs={} for _key,_value in globals().items(): try: if _value.__class__==SQLDB: tables=_dbs[_key]=[] for _tablename in _value.tables(): tables.append((_key,_tablename)) except: pass return dict(dbs=_dbs) ########################################################### ### insert a new record ############################################################ def insert(): try: dbname=request.args[0] db=eval(dbname) table=request.args[1] form=SQLFORM(db[table]) except: redirect(URL(r=request,f='index')) if form.accepts(request.vars,session): response.flash='new record inserted' redirect(URL(r=request,f='select',args=request.args)) elif len(request.vars): response.flash='There are error in your submission form' return dict(form=form) ########################################################### ### list all records in table and insert new record ############################################################ def download(): filename=request.args[0] response.headers['Content-Type']=contenttype(filename) return open(os.path.join(request.folder,'uploads/','%s' % filename),'rb').read() def csv(): import gluon.contenttype, csv, cStringIO response.headers['Content-Type']=gluon.contenttype.contenttype('.csv') try: dbname=request.vars.dbname db=eval(dbname) records=db(request.vars.query).select() except: redirect(URL(r=request,f='index')) s=cStringIO.StringIO() writer = csv.writer(s) writer.writerow(records.colnames) c=range(len(records.colnames)) for i in range(len(records)): writer.writerow([records.response[i][j] for j in c]) ### FILL HERE return s.getvalue() def import_csv(table,file): import csv reader = csv.reader(file) colnames=None for line in reader: if not colnames: colnames=[x[x.find('.')+1:] for x in line] c=[i for i in range(len(line)) if colnames[i]!='id'] else: items=[(colnames[i],line[i]) for i in c] table.insert(**dict(items)) def select(): try: dbname=request.args[0] db=eval(dbname) if not request.vars.query: table=request.args[1] query='%s.id>0' % table else: query=request.vars.query except: redirect(URL(r=request,f='index')) if request.vars.csvfile!=None: try: import_csv(db[table],request.vars.csvfile.file) response.flash='data uploaded' except: reponse.flash='unable to parse csv file' if request.vars.delete_all and request.vars.delete_all_sure=='yes': try: db(query).delete() response.flash='records deleted' except: response.flash='invalid SQL FILTER' elif request.vars.update_string: try: env=dict(db=db,query=query) exec('db(query).update('+request.vars.update_string+')') in env response.flash='records updated' except: response.flash='invalid SQL FILTER or UPDATE STRING' if request.vars.start: start=int(request.vars.start) else: start=0 limitby=(start,start+100) try: records=db(query).select(limitby=limitby) except: response.flash='invalid SQL FILTER' return dict(records='no records',nrecords=0,query=query,start=0) linkto=URL(r=request,f='update/%s'% (dbname)) upload=URL(r=request,f='download') return dict(start=start,query=query,\ nrecords=len(records),\ records=SQLTABLE(records,linkto,upload,_class='sortable')) ########################################################### ### edit delete one record ############################################################ def update(): try: dbname=request.args[0] db=eval(dbname) table=request.args[1] except: redirect(URL(r=request,f='index')) try: id=int(request.args[2]) record=db(db[table].id==id).select()[0] except: redirect(URL(r=request,f='select/%s/%s'%(dbname,table))) form=SQLFORM(db[table],record,deletable=True, linkto=URL(r=request,f='select/'+dbname), upload=URL(r=request,f='download/')) if form.accepts(request.vars,session): response.flash='done!' redirect(URL(r=request,f='select/%s/%s'%(dbname,table))) return dict(form=form) def cleanup(): app=request.application files=listdir('applications/%s/cache/' % app,'',0) for file in files: os.unlink(file) files=listdir('applications/%s/errors/' % app,'',0) for file in files: os.unlink(file) files=listdir('applications/%s/sessions/' % app,'',0) for file in files: os.unlink(file) session.flash="cache, errors and sessions cleaned" redirect(URL(r=request,f='index')) def setup(): response.view='manage/setup.html' form=SQLFORM(store.info,mystore) if form.accepts(request.vars,session): response.flash='that was easy! now go vist your store.' else: response.flash='welcome to the store-in-a-stick setup' return dict(form=form)
0707tim-web2pestore
controllers/manage.py
Python
gpl2
6,428
{{ def show(products, width=4, function='product'): }} <table> {{ for i, product in enumerate(products): }} {{ if i == 0: }} <tr> {{ elif i % width == 0: }} </tr> <tr> {{ pass }} <td style="text-align: center"> <a href="{{= URL(r=request, f=function, args=pretty_url(product.id, product.name)) }}"> <img src="{{= URL(r=request, f='show', args=product.small_image) }}" height="100px"/> <div>{{= product.name }}</div> </a> </td> {{ pass }} </tr> </table> {{ return }}
0707tim-web2pestore
views/catalog.html
HTML
gpl2
585
{{ extend 'layout.html' }} <h2>Login to the Administrative Interface</h2><br/> <form action="" method="post"> <table> <tr><td>Administrator Password:</td><td><input type="password" name="password"/></td></tr> <tr><td></td><td><input type="submit" value="login"/></td></tr> </table> </form>
0707tim-web2pestore
views/manage/login.html
HTML
gpl2
299
{{ extend 'layout.html' }} <h1>web2py Store Setup</h1> <h2>Instructions</h2> <ul> <li>Register with <a href="http://checkout.google.com">Google Checkout</a></li> <li>Google will assign you a "merchant id", insert it below</li> <li>web2py/store comes with some example products in the database. Access the <a href="/{{=request.application}}/manage/index">application administrative interface</a> to create/edit/delete products and categories</li> <li>Users can access the store <a href="/{{=request.application}}">here</a></li> </ul> <br/><br/> <h2>Merchant ID</h2> merchant id (as assigned by Google checkout):{{=form}} <br/><br/> <h2>Notes</h2> <p>You can try web2py/store without a merchant_id, just type something in the field below. You can come back to <a href="/{{=request.application}}/default/setup">this page</a> later and change it.</p> <p>Mind that, for you protection, web2py/store delegates to Google checkout the processing of your customers' shopping carts therefore web2py/store does not keep track of purchases and does not collect or store customers' credit card information. Google checkout will handle all that and will notify you, by email, when a purchase is completed.</p>
0707tim-web2pestore
views/manage/setup.html
HTML
gpl2
1,200
{{ extend 'layout.html' }} {{ import cgi }} <h1>Contact Us</h1> <h2>Address</h2> <p>{{= XML(cgi.escape(mystore.address).replace(', ','<br/>').replace('\n','</p><p>')) }}<br/> {{= A('directions',_href='http://maps.google.com/maps?f=q&hl=en&geocode=&time=&date=&ttype=&q=%s' % cgi.escape(mystore.address)) }}</p> <h2>Fax Number</h2> <p>{{= mystore.fax }}</p> <h2>Phone Number</h2> <p>{{= mystore.phone }}</p> <h2>Email</h2> <p>{{= A(mystore.email, _href='mailto:%s' % mystore.email) }}</p>
0707tim-web2pestore
views/default/contactus.html
HTML
gpl2
497
{{ extend 'layout.html' }} <h1>web2py Store Setup</h1> <h2>Instructions</h2> <ul> <li>Register with <a href="http://checkout.google.com">Google Checkout</a></li> <li>Google will assign you a "merchant id", insert it below</li> <li>web2py/store comes with some example products in the database. Access the <a href="/{{= request.application }}/manage/index">application administrative interface</a> to create/edit/delete products and categories</li> <li>Users can access the store <a href="/{{= request.application }}">here</a></li> </ul> <br/><br/> <h2>Merchant ID</h2> merchant id (as assigned by Google checkout):{{= form }} <br/><br/> <h2>Notes</h2> <p>You can try web2py/store without a merchant_id, just type something in the field below. You can come back to <a href="/{{=request.application }}/default/setup">this page</a> later and change it.</p> <p>Mind that, for you protection, web2py/store delegates to Google checkout the processing of your customers' shopping carts therefore web2py/store does not keep track of purchases and does not collect or store customers' credit card information. Google checkout will handle all that and will notify you, by email, when a purchase is completed.</p>
0707tim-web2pestore
views/default/setup.html
HTML
gpl2
1,224
{{ extend 'layout.html' }} {{ include 'catalog.html' }} <h1>Checkout</h1> {{ if not order: }} <h2>No products in your shopping cart</h2> {{ else: }} <h2>Products in your shopping cart</h2> <table> <tr> <th>Product</th> <th>Total</th> </tr> {{ for i, (product_id, qty, total_price, product, options) in enumerate(order): }} <tr> <td> {{= qty }} x {{= A(product.name, _href=URL(r=request, f='product', args=pretty_url(product.id, product.name))) }} <table> {{ for option in options: }} <tr> <td>+ {{= option.description }}</td> <td> ${{= option.price }}</td> </tr> {{ pass }} </table> </td> <td><h3>${{= total_price }}</h3></td> <td><a href="{{= URL(r=request, f='remove_from_cart', args=i) }}">remove</a></td> </tr> {{ pass }} <tr> <td style="text-align:right"><h3>Balance:</h3></td> <td><h2>${{= "%.2f" % session.balance }}</h2></td> </table> <br/> <br/> <form name="google_form" action="https://checkout.google.com/cws/v2/Merchant/{{= merchant_id }}/checkoutForm" id="BB_BuyButtonForm" method="post" name="BB_BuyButtonForm"> {{ for i, (product_id, qty, total_price, product, options) in enumerate(order): }} <input name="item_name_{{= i }}" type="hidden" value="{{= product.name }}"/> <input name="item_description_{{= i }}" type="hidden" value="{{= product.description }}"/> <input name="item_quantity_{{= i }}" type="hidden" value="{{= qty }}"/> <input name="item_price_{{= i }}" type="hidden" value="{{= total_price }}"/> <input name="item_weight_{{= i }}" unit="LB" type="hidden" value="{{= product.weight_in_pounds }}"/> <input name="item_currency_{{= i }}" type="hidden" value="USD"/> {{ pass }} <input name="_charset_" type="hidden" value="utf-8"/> <!-- fill in taxes and shipping options --> <input alt="" src="https://checkout.google.com/buttons/buy.gif?merchant_id={{=merchant_id}}&amp;w=117&amp;h=48&amp;style=white&amp;variant=text&amp;loc=en_US" type="image" onclick="process(google_form);return false;"/> </form> {{ pass }} <script language="text/javascript"> <!-- function process(form_name) { i = new Image() i.src = "/{{= request.application }}/default/empty_cart"; form_name.submit(); } //--> </script> {{ pass }}
0707tim-web2pestore
views/default/checkout.html
HTML
gpl2
2,421
{{ extend 'layout.html' }} {{ include 'catalog.html' }} <h1>{{= product.name }}</h1> <img src="{{= URL(r=request, f='show', args=(product.large_image if product.large_image else product.small_image)) }}" height="200px"/> {{= product_form }} <p>{{= XML(product.description) }}</p> {{ if product.allow_rating and product.rating > 0: }} {{= '%.1f' % product.rating }}/5.0 rating, {{ pass }} {{ if product.quantity_in_stock != UNDEFINED: }} {{ if product.quantity_in_stock < 1: }} low stock {{ else: }} {{= product.quantity_in_stock }} in stock {{ pass }} {{ pass }} {{ pass }} <br/> <br/> {{ if suggested: }} <h2>You may also be interested in:</h2> {{ show(suggested) }} {{ pass }} {{ if product.allow_rating: }} <br/> {{ if comments: }} <h2>Visitors' comments</h2> <p><ul> {{ for comment in comments: }} <li>{{= comment.author }} says <i>"{{= comment.body }}"</i></li> {{ pass }} </ul> </p> {{ pass }} {{= comment_form }} {{ pass }} <script type="text/javascript"> var total_price = {{= product.price }}; function update_price(e, option_price) { if($(e).is(':checked')) total_price += option_price; else total_price -= option_price; $("#total_price").text('$' + Math.round(100*total_price)/100); } </script>
0707tim-web2pestore
views/default/product.html
HTML
gpl2
1,378
{{ extend 'layout.html' }} {{ include 'catalog.html' }} <h2>Product Categories:</h2> {{ show(categories, function='category') }} <br/><br/> {{ if featured: }} <h1>Featured Products</h1> {{ show(featured) }} {{ pass }}
0707tim-web2pestore
views/default/index.html
HTML
gpl2
223
{{ extend 'layout.html' }} {{ include 'catalog.html' }} <h1>Products in {{= category_name }}</h1> {{ if featured or favourites: }} {{ show(featured) }} {{ show(favourites) }} {{ else: }} <h2>No products in category {{= category_name }}</h2> {{ pass }}
0707tim-web2pestore
views/default/category.html
HTML
gpl2
262
{{ extend 'layout.html' }} {{ import cgi }} <h1>About Us</h1> <h2>Our Store</h2> <p>{{= XML(cgi.escape(mystore.description).replace('\n', '</p><p>')) }}</p> <h2>Why Buy From Us?</h2> <p>{{= XML(cgi.escape(mystore.why_buy).replace('\n', '</p><p>')) }}</p> <h2>Return Policy</h2> <p>{{= XML(cgi.escape(mystore.return_policy).replace('\n', '</p><p>')) }}</p>
0707tim-web2pestore
views/default/aboutus.html
HTML
gpl2
363
<html> <head> <title>Product Image</title> <script language='javascript'> var arrTemp=self.location.href.split("?"); var picUrl = (arrTemp.length>0)?arrTemp[1]:""; var NS = (navigator.appName=="Netscape")?true:false; function FitPic() { iWidth = (NS)?window.innerWidth:document.body.clientWidth; iHeight = (NS)?window.innerHeight:document.body.clientHeight; iWidth = document.images[0].width - iWidth; iHeight = document.images[0].height - iHeight; window.resizeBy(iWidth, iHeight); self.focus(); }; </script> </head> <body bgcolor="#000000" onload='FitPic();' topmargin="0" marginheight="0" leftmargin="0" marginwidth="0"> <script language='javascript'> document.write( "<img src='" + picUrl + "' border=0>" ); </script> </body> </html>
0707tim-web2pestore
views/default/popup.html
HTML
gpl2
829
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta name="keywords" content="{{=response.keywords}}" /> <meta name="description" content="{{=response.description}}" /> <title>{{= response.title or title() }}</title> <link type="text/css" rel="stylesheet" href="/{{=request.application}}/static/textarea/SyntaxHighlighter.css"></link> <style> div.fluid { width: 93% !important; } div.fixed { width: 800px !important; } * { margin: 0em; padding: 0em; } body { background-color: {{= mystore.color_background }}; color: {{= mystore.color_foreground }}; font-size: 10pt; font-family: {{= mystore.font_family }}; } h1,h2,h3,h4,h5,h6 { font-weight: normal; letter-spacing: -1px; } h2,h3,h4,h5,h6 { color: {{= mystore.color_foreground }}; } br.clear { clear: both; } img.icon { border: 0px; vertical-align: middle; } img.floatTL { float: left; margin-right: 1.5em; margin-bottom: 1.5em; margin-top: 0.5em; } a { text-decoration: none; color: {{= mystore.color_link }}; } a:hover { text-decoration: underline; } textarea { font-family: courier; } ul { margin-left: 1.5em; } li { line-height: 1.5em; } dd { text-decoration: bold; } dt { text-decoration:none; margine-left: +10em; } p { line-height: 1.8em; } table, tr, td { text-align: left; vertical-align: top; } #header { width:100%; height:100px; background: {{=mystore.color_header}}; {{if mystore.logo:}}; url('/{{=request.application}}/default/show/{{=mystore.logo}}') repeat-x; {{pass}} } #header_inner { position: relative; width: 800px; height:70px; margin: 0 auto; } /* Logo */ #logo { position: absolute; left: 4em; bottom: 0.6em; } #logo h1 { display: inline; color: {{= mystore.color_foreground }}; font-size: 1.8em; } #logo h2 { display: inline; color: {{= mystore.color_foreground }}; font-size: 1.3em;} /* Menu */ #menu { position: absolute; right: 0em; bottom: -2.5em; } #menu ul { list-style: none; } #menu li { float: left; } #menu li a { margin-left: 0.5em; display: block; padding: 0.5em 0.5em 0.5em 0.5em; background: {{= mystore.color_background }} repeat-x; color: {{= mystore.color_link }}; font-weight: bold; font-size: 1.0em; text-decoration: none;} #menu li a.inactive { background: transparent; color: {{= mystore.color_foreground }}; border: solid 0px {{= mystore.color_link }} border-top: solid 0px {{= mystore.color_link }}; } /* Main */ #main { background: #fff 0px 1px repeat-x; } #main_inner p { text-align: justify; margin-bottom: 2.0em; } #main_inner ul { margin-bottom: 2.0em; } #main_inner { position: relative; width: 800px; margin: 0 auto; padding-top: 1.0em; } #main_inner h1 { border-bottom: dotted 1px #E1E1E1; position: relative; font-size: 2.1em; padding-bottom: 0.1em; margin-bottom: 0.8em; } #main_inner .post { position: relative; } #main_inner .post h3 { position: relative; font-size: 1.7em; padding-bottom: 1.2em; } #main_inner .post ul.post_info { list-style: none; position: absolute; top: 3em; font-size: 0.8em; } #main_inner .post ul.post_info li { background-position: 0em 0.2em; background-repeat: no-repeat; display: inline; padding-left: 18px; } /* Flash */ #flash { width: 600px; margin: 0 auto; text-align: center; clear: both; border: 1px #000000; background-color: {{= mystore.color_link }}; color: {{= mystore.color_background }}; margin-top: 0.0em; margin-bottom: 1.0em; padding-top: 1.0em; padding-bottom: 1.0em; } /* Footer */ #footer { width: 800px; margin: 0 auto; text-align: center; clear: both; border-top: dotted 1px #E1E1E1; margin-top: 1.0em; margin-bottom: 1.5em; padding-top: 1.0em; } /* Search */ input.button { background: #FF6C1F repeat-x; color: {{= mystore.color_background }}; border: solid 1px #DB7623; font-weight: bold; font-size: 0.8em; height: 2.0em; } input.text { border: solid 1px #F1F1F1; font-size: 1.0em; padding: 0.25em 0.25em 0.25em 0.25em; } /* LAYOUT - 3 COLUMNS */ /* Primary content */ #primaryContent_3columns { position: relative; margin-right: 34em; } #columnA_3columns { position: relative; float: left; width: 100%; margin-right: -34em; padding-right: 2em; } /* Secondary Content */ #secondaryContent_3columns { float: right; } #columnB_3columns { width: 13.0em; float: left; padding: 0em 2em 0.5em 2em; border-left: dotted 1px #E1E1E1; } #columnC_3columns { width: 13.0em; float: left; padding: 0em 0em 0.5em 2em; border-left: dotted 1px #E1E1E1; } /* LAYOUT - 2 COLUMNS */ /* Primary content */ #primaryContent_2columns { position: relative; margin-right: 17em; } #columnA_2columns { position: relative; float: left; width: 100%; margin-right: -17em; padding-right: 2em; } /* Secondary Content */ #secondaryContent_2columns { float: right; } #columnC_2columns { width: 13.0em; float: left; padding: 0em 0em 0.5em 2em; border-left: dotted 1px #E1E1E1; } /* LAYOUT - COLUMNLESS */ /* Primary content */ #primaryContent_columnless { position: relative; } #columnA_columnless { position: relative; width: 100%; } </style> {{ include 'web2py_ajax.html' }} </head> <body> <div id="header"> <div id="header_inner" class="fixed"> <div id="logo"> <h1><a href="{{= URL(r=request, c='default', f='index') }}">{{= mystore.name }}</a></h1><br/> <h2>{{= mystore.headline }}</h2> </div> {{ if response.menu: }} <div id="menu"> <ul> {{ for _name, _active, _link in response.menu: }} <li><a href="{{= _link }}" {{ if not _active: }}class="inactive"{{ pass }}>{{= _name }}</a></li> {{ pass }} </ul> </div> {{ pass }} </div> </div> <div id="main"> <div id="main_inner" class="fixed"> <div id="primaryContent_columnless"> <div id="columnA_columnless"> {{ if response.flash: }} <div id="flash">{{= response.flash }}</div> {{ pass }} {{ include }} </div> </div> <div id="footer" class="fixed"> {{= mystore.address }} </div> </div> </div> </body> </html>
0707tim-web2pestore
views/layout.html
HTML
gpl2
6,077
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script> {{import os if os.path.exists(os.path.join(request.folder,'static','calendar.js')):}} <link rel="stylesheet" href="/{{=request.application}}/static/calendar.css" type="text/css" media="screen" title="core css file" charset="utf-8" /> <script src="/{{=request.application}}/static/calendar.js" type="text/javascript" charset="utf-8"></script> {{pass}} <script type="text/javascript"><!-- /* Written by Massimo Di Pierro. Here for backward compatibility. */ function popup(url) { newwindow=window.open(url,'name','height=400,width=600'); if (window.focus) newwindow.focus(); return false; } function collapse(id) { $('#'+id).slideToggle(); } function fade(id,value) { if(value>0) $('#'+id).hide().fadeIn('slow'); else $('#'+id).show().fadeOut('slow'); } function ajax(u,s,t) { var query=""; for(i=0; i<s.length; i++) { if(i>0) query=query+"&"; query=query+encodeURIComponent(s[i])+"="+encodeURIComponent(document.getElementById(s[i]).value); } $.ajax({type: "POST", url: u, data: query, success: function(msg) { document.getElementById(t).innerHTML=msg; } }); } String.prototype.reverse = function () {return this.split('').reverse().join('');}; $(document).ready(function() { $('div.error').hide().slideDown('slow'); $('#flash').hide().slideDown('slow') $('#flash').click(function() { $(this).fadeOut('slow'); return false; }); $('input.integer').keyup(function(){this.value=this.value.reverse().replace(/[^0-9\-]|\-(?=.)/g,'').reverse();}); $('input.double').keyup(function(){this.value=this.value.reverse().replace(/[^0-9\-\.]|[\-](?=.)|[\.](?=[0-9]*[\.])/g,'').reverse();}); try {$("input.date").focus( function() {Calendar.setup({ inputField: this.id, ifFormat: "{{=T('%Y-%m-%d')}}", showsTime: false }); }); } catch(e) {}; try { $("input.datetime").focus( function() {Calendar.setup({ inputField: this.id, ifFormat: "{{=T('%Y-%m-%d %H:%M:%S')}}", showsTime: true, timeFormat: "24" }); }); } catch(e) {}; try { $("input.time").clockpick({ starthour : 0, endhour : 23, showminutes : true, military : true }); } catch(e) {}; }); //--></script>
0707tim-web2pestore
views/web2py_ajax.html
HTML
gpl2
2,230
{{extend 'layout.html'}} <script><!-- $(document).ready(function(){ $("table.sortable tbody tr").mouseover( function() { $(this).addClass("highlight"); }).mouseout( function() { $(this).removeClass("highlight"); }); $('table.sortable tbody tr:odd').addClass('odd'); $('table.sortable tbody tr:even').addClass('even'); }); //--></script> {{if request.function=='index':}} <h1>{{=T("Available databases and tables")}}</h1> {{if not databases:}}{{=T("No databases in this application")}}{{pass}} {{for db in sorted(databases):}} {{for table in databases[db].tables:}} <h2>{{=A("%s.%s"%(db,table),_href=URL(r=request,f='select',args=[db],vars=dict(query='%s.%s.id>0'%(db,table))))}}</h2> [ {{=A(str(T('insert new'))+' '+table,_href=URL(r=request,f='insert',args=[db,table]))}} ] <br /><br /> {{pass}} {{pass}} {{elif request.function=='select':}} <h1>{{=XML(str(T("database %s select"))%A(request.args[0],_href=URL(r=request,f='index'))) }} </h1> {{if table:}} [ {{=A(str(T('insert new %s'))%table,_href=URL(r=request,f='insert',args=[request.args[0],table]))}} ]<br/><br/> <h2>{{=T("Rows in table")}}</h2><br/> {{else:}} <h2>{{=T("Rows selected")}}</h2><br/> {{pass}} {{=form}} <p>{{=T('The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.')}}<br/> {{=T('Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.')}}<br/> {{=T('"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN')}}</p> <br/><br/> <h3>{{=nrows}} {{=T("selected")}}</h3> {{if start>0:}}[ {{=A(T('previous 100 rows'),_href=URL(r=request,f='select',args=request.args[0],vars=dict(start=start-100)))}} ]{{pass}} {{if stop<nrows:}}[ {{=A(T('next 100 rows'),_href=URL(r=request,f='select',args=request.args[0],vars=dict(start=start+100)))}} ]{{pass}} {{if rows:}} <div style="overflow: auto;" width="80%"> {{linkto=URL(r=request,f='update',args=request.args[0])}} {{upload=URL(r=request,f='download',args=request.args[0])}} {{=SQLTABLE(rows,linkto,upload,orderby=True,_class='sortable')}} </div> {{pass}} <br/><br/><h2>{{=T("Import/Export")}}</h2><br/> [ <a href="{{=URL(r=request,f='csv',args=request.args[0],vars=dict(query=query))}}">{{=T("export as csv file")}}</a> ] {{if table:}} {{=FORM(str(T('or import from csv file'))+" ",INPUT(_type='file',_name='csvfile'),INPUT(_type='hidden',_value=table,_name='table'),INPUT(_type='submit',_value='import'))}} {{pass}} {{elif request.function=='insert':}} <h1>{{=T("database")}} {{=A(request.args[0],_href=URL(r=request,f='index'))}} {{=T("table")}} {{=A(request.args[1],_href=URL(r=request,f='select',args=request.args[0],vars=dict(query='%s.%s.id>0'%tuple(request.args[:2]))))}} </h1> <h2>{{=T("New Record")}}</h2><br/> {{=form}} {{elif request.function=='update':}} <h1>{{=T("database")}} {{=A(request.args[0],_href=URL(r=request,f='index'))}} {{=T("table")}} {{=A(request.args[1],_href=URL(r=request,f='select',args=request.args[0],vars=dict(query='%s.%s.id>0'%tuple(request.args[:2]))))}} {{=T("record id")}} {{=A(request.args[2],_href=URL(r=request,f='update',args=request.args[:3]))}} </h1> <h2>{{=T("Edit current record")}}</h2><br/><br/>{{=form}} {{elif request.function=='state':}} <h1>{{=T("Internal State")}}</h1> <h2>{{=T("Current request")}}</h2> {{=BEAUTIFY(request)}} <br/><h2>{{=T("Current response")}}</h2> {{=BEAUTIFY(response)}} <br/><h2>{{=T("Current session")}}</h2> {{=BEAUTIFY(session)}} {{pass}}
0707tim-web2pestore
views/appadmin.html
HTML
gpl2
3,738
{{extend 'layout.html' }} <script src="/{{= request.application }}/static/sorttable.js"></script> <style> table.sortable thead { background-color:#eee; color:#666666; font-weight: bold; cursor: default; } </style> {{ try: }}{{= uplink }}{{ except: }}{{ pass }} <h1> {{ if request.function == 'state': }} Internal state {{ else: }} {{ if len(request.args) >= 1: }} database {{ if not request.vars.query: }}table {{= A(request.args[1],_href=URL(r=request, f='select/%s/%s' % tuple(request.args[:2]))) }} select {{ else: }} generic select/update/delete{{ pass }} {{ if len(request.args) == 3: }} record id {{= A(request.args[2],_href=URL(r=request, f='update/%s/%s/%s' % tuple(request.args[:3]))) }} {{ pass }} {{ else: }} Manage store {{ pass }} {{ pass }} </h1> {{ if request.function == 'index': }} <h2>{{= A("Setup", _href='/%s/manage/setup'%request.application) }}</h2> <i>Here you setup general store information</i> <br/><br/> <h2>{{= A("Store Categrories", _href=URL(r=request, f='select/store/category')) }}</h2> <i>Here you manage the categories of products</i> <br/><br/> <h2>{{= A("Store Products", _href=URL(r=request, f='select/store/product')) }}</h2> <i>Here you manage the actual products you sells</i> <br/><br/> <h2>{{= A("Store Comments", _href=URL(r=request, f='select/store/comment')) }}</h2> <i>Here you manage the comments posted by visitors</i> <br/><br/> <h2>{{= A("Cleanup Temporary Files", _href=URL(r=request, f='cleanup')) }}</h2> <i>This is a maintenance function, run it once a week.</i> <br/><br/> <br/><br/> {{ pass }} {{ if request.function == 'select' and len(request.args) > 1: }} [ {{= A('insert new %s' % request.args[1], _href=URL(r=request, f='insert/%s/%s' % tuple(request.args[:2]))) }} ]<br/><br/> <h2>Rows in table</h2><br/> {{ elif request.function=='select' and len(request.args) == 1: }} <h2>Rows selected</h2><br/> {{ pass }} {{ if request.function == 'select' and len(request.args) >= 1: }} <form action="{{= URL(r=request,args=request.args[:1]) }}" method="post"> <table> <tr><td width="150px">FILTER CONDITION:</td><td><input type="text" value="{{= query }}" name="query" size="60"/><input type="submit" value="apply"/></td></tr> {{ if len(request.args) == 1: }} <tr><td>UPDATE STRING:</td><td><input type="text" value="" name="update_string"/> or DELETE ALL: <input type="checkbox" name="delete_all"/> (sure?<select name="delete_all_sure"/><option selected>no</option><option>yes</option></select>)<br/><i>(The SQL FILTER is a condition like "table1.field1='value'". Something like "table1.field1=table2.field2" results in a SQL JOIN. Use AND, OR and (...) to build more complex filters. The UPDATE STRING is an optional expression like "field1='newvalue'". You cannot update or delete the results of a JOIN)</i> </td></tr> {{ pass }} </table> </form> <br/> <br/> {{ if start > 0: }}[ {{= A('previous 100 records',_href=URL(r=request, f='select/%s?query=%s&start=%s' % ('/'.join(request.args), query, start-100))) }} ]{{ pass }} {{ if nrecords == 100: }}[ {{= A('next 100 records',_href=URL(r=request, f='select/%s?query=%s&start=%s' % ('/'.join(request.args), query, start+100))) }} ]{{ pass }} {{= records }} <br/><br/><h2>CSV import/export</h2><br/> [ <a href="{{= URL(r=request,f='csv',vars=dict(dbname=request.args[0],query=query)) }}">export as csv file</a> ] {{ if len(request.args) == 2: }} {{= FORM('or import from csv file ', INPUT(_type='file', _name='csvfile'),INPUT(_type='submit', _value='import')) }} {{ pass }} {{ pass }} {{ if request.function == 'insert' and len(request.args) > 1: }} <h2>New Record</h2><br/> {{= form }} {{ pass }} {{ if request.function == 'update' and len(request.args) > 2: }} <h2>Edit current record</h2><br/><br/>{{= form }} {{ pass }} {{ if request.function == 'state': }} <h2>Current request</h2> {{= BEAUTIFY(request) }} <br/><h2>Current response</h2> {{= BEAUTIFY(response) }} <br/><h2>Current session</h2> {{= BEAUTIFY(session) }} {{ pass }}
0707tim-web2pestore
views/manage.html
HTML
gpl2
4,184
{{ extend 'layout.html' }} {{= BEAUTIFY(response._vars) }}
0707tim-web2pestore
views/generic.html
HTML
gpl2
58
/* * Copyright (C) 2011 Google Inc. * * 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. */ package com.googlecode.tesseract.android; import android.graphics.Bitmap; import android.graphics.Rect; import com.googlecode.leptonica.android.Pix; import com.googlecode.leptonica.android.ReadFile; import java.io.File; /** * Java interface for the Tesseract OCR engine. Does not implement all available * JNI methods, but does implement enough to be useful. Comments are adapted * from original Tesseract source. * * @author alanv@google.com (Alan Viverette) */ public class TessBaseAPI { /** * Used by the native implementation of the class. */ private int mNativeData; static { System.loadLibrary("lept"); System.loadLibrary("tess"); nativeClassInit(); } /** Fully automatic page segmentation. */ public static final int PSM_AUTO = 0; /** Assume a single column of text of variable sizes. */ public static final int PSM_SINGLE_COLUMN = 1; /** Assume a single uniform block of text. (Default) */ public static final int PSM_SINGLE_BLOCK = 2; /** Treat the image as a single text line. */ public static final int PSM_SINGLE_LINE = 3; /** Treat the image as a single word. */ public static final int PSM_SINGLE_WORD = 4; /** Treat the image as a single character. */ public static final int PSM_SINGLE_CHAR = 5; /** Default accuracy versus speed mode. */ public static final int AVS_FASTEST = 0; /** Slowest and most accurate mode. */ public static final int AVS_MOST_ACCURATE = 100; /** Whitelist of characters to recognize. */ public static final String VAR_CHAR_WHITELIST = "tessedit_char_whitelist"; /** Blacklist of characters to not recognize. */ public static final String VAR_CHAR_BLACKLIST = "tessedit_char_blacklist"; /** Accuracy versus speed setting. */ public static final String VAR_ACCURACYVSPEED = "tessedit_accuracyvspeed"; /** * Constructs an instance of TessBaseAPI. */ public TessBaseAPI() { nativeConstruct(); } /** * Called by the GC to clean up the native data that we set up when we * construct the object. */ @Override protected void finalize() throws Throwable { try { nativeFinalize(); } finally { super.finalize(); } } /** * Initializes the Tesseract engine with a specified language model. Returns * <code>true</code> on success. * <p> * Instances are now mostly thread-safe and totally independent, but some * global parameters remain. Basically it is safe to use multiple * TessBaseAPIs in different threads in parallel, UNLESS you use SetVariable * on some of the Params in classify and textord. If you do, then the effect * will be to change it for all your instances. * <p> * The datapath must be the name of the parent directory of tessdata and * must end in / . Any name after the last / will be stripped. The language * is (usually) an ISO 639-3 string or <code>null</code> will default to eng. * It is entirely safe (and eventually will be efficient too) to call Init * multiple times on the same instance to change language, or just to reset * the classifier. * <p> * <b>WARNING:</b> On changing languages, all Tesseract parameters are reset * back to their default values. (Which may vary between languages.) * <p> * If you have a rare need to set a Variable that controls initialization * for a second call to Init you should explicitly call End() and then use * SetVariable before Init. This is only a very rare use case, since there * are very few uses that require any parameters to be set before Init. * * @param datapath the parent directory of tessdata ending in a forward * slash * @param language (optional) an ISO 639-3 string representing the language * @return <code>true</code> on success */ public boolean init(String datapath, String language) { if (datapath == null) throw new IllegalArgumentException("Data path must not be null!"); if (!datapath.endsWith(File.separator)) datapath += File.separator; File tessdata = new File(datapath + "tessdata"); if (!tessdata.exists() || !tessdata.isDirectory()) throw new IllegalArgumentException("Data path must contain subfolder tessdata!"); return nativeInit(datapath, language); } /** * Frees up recognition results and any stored image data, without actually * freeing any recognition data that would be time-consuming to reload. * Afterwards, you must call SetImage or SetRectangle before doing any * Recognize or Get* operation. */ public void clear() { nativeClear(); } /** * Closes down tesseract and free up all memory. End() is equivalent to * destructing and reconstructing your TessBaseAPI. * <p> * Once End() has been used, none of the other API functions may be used * other than Init and anything declared above it in the class definition. */ public void end() { nativeEnd(); } /** * Set the value of an internal "variable" (of either old or new types). * Supply the name of the variable and the value as a string, just as you * would in a config file. * <p> * Example: <code>setVariable(VAR_TESSEDIT_CHAR_BLACKLIST, "xyz"); to ignore x, y and z. * setVariable(VAR_BLN_NUMERICMODE, "1"); to set numeric-only mode. * </code> * <p> * setVariable() may be used before open(), but settings will revert to * defaults on close(). * * @param var name of the variable * @param value value to set * @return false if the name lookup failed */ public boolean setVariable(String var, String value) { return nativeSetVariable(var, value); } /** * Sets the page segmentation mode. This controls how much processing the * OCR engine will perform before recognizing text. * * @param mode the page segmentation mode to set */ public void setPageSegMode(int mode) { nativeSetPageSegMode(mode); } /** * Sets debug mode. This controls how much information is displayed in the * log during recognition. * * @param enabled <code>true</code> to enable debugging mode */ public void setDebug(boolean enabled) { nativeSetDebug(enabled); } /** * Restricts recognition to a sub-rectangle of the image. Call after * SetImage. Each SetRectangle clears the recogntion results so multiple * rectangles can be recognized with the same image. * * @param rect the bounding rectangle */ public void setRectangle(Rect rect) { setRectangle(rect.left, rect.top, rect.width(), rect.height()); } /** * Restricts recognition to a sub-rectangle of the image. Call after * SetImage. Each SetRectangle clears the recogntion results so multiple * rectangles can be recognized with the same image. * * @param left the left bound * @param top the right bound * @param width the width of the bounding box * @param height the height of the bounding box */ public void setRectangle(int left, int top, int width, int height) { nativeSetRectangle(left, top, width, height); } /** * Provides an image for Tesseract to recognize. * * @param file absolute path to the image file */ public void setImage(File file) { Pix image = ReadFile.readFile(file); if (image == null) { throw new RuntimeException("Failed to read image file"); } nativeSetImagePix(image.getNativePix()); } /** * Provides an image for Tesseract to recognize. Does not copy the image * buffer. The source image must persist until after Recognize or * GetUTF8Chars is called. * * @param bmp bitmap representation of the image */ public void setImage(Bitmap bmp) { Pix image = ReadFile.readBitmap(bmp); if (image == null) { throw new RuntimeException("Failed to read bitmap"); } nativeSetImagePix(image.getNativePix()); } /** * Provides a Leptonica pix format image for Tesseract to recognize. Clones * the pix object. The source image may be destroyed immediately after * SetImage is called, but its contents may not be modified. * * @param image Leptonica pix representation of the image */ public void setImage(Pix image) { nativeSetImagePix(image.getNativePix()); } /** * Provides an image for Tesseract to recognize. Copies the image buffer. * The source image may be destroyed immediately after SetImage is called. * SetImage clears all recognition results, and sets the rectangle to the * full image, so it may be followed immediately by a GetUTF8Text, and it * will automatically perform recognition. * * @param imagedata byte representation of the image * @param width image width * @param height image height * @param bpp bytes per pixel * @param bpl bytes per line */ public void setImage(byte[] imagedata, int width, int height, int bpp, int bpl) { nativeSetImageBytes(imagedata, width, height, bpp, bpl); } /** * The recognized text is returned as a String which is coded as UTF8. * * @return the recognized text */ public String getUTF8Text() { // Trim because the text will have extra line breaks at the end String text = nativeGetUTF8Text(); return text.trim(); } /** * Returns the mean confidence of text recognition. * * @return the mean confidence */ public int meanConfidence() { return nativeMeanConfidence(); } /** * Returns all word confidences (between 0 and 100) in an array. The number * of confidences should correspond to the number of space-delimited words * in GetUTF8Text(). * * @return an array of word confidences (between 0 and 100) for each * space-delimited word returned by GetUTF8Text() */ public int[] wordConfidences() { int[] conf = nativeWordConfidences(); // We shouldn't return null confidences if (conf == null) conf = new int[0]; return conf; } // ****************** // * Native methods * // ****************** /** * Initializes static native data. Must be called on object load. */ private static native void nativeClassInit(); /** * Initializes native data. Must be called on object construction. */ private native void nativeConstruct(); /** * Finalizes native data. Must be called on object destruction. */ private native void nativeFinalize(); private native boolean nativeInit(String datapath, String language); private native void nativeClear(); private native void nativeEnd(); private native void nativeSetImageBytes( byte[] imagedata, int width, int height, int bpp, int bpl); private native void nativeSetImagePix(int nativePix); private native void nativeSetRectangle(int left, int top, int width, int height); private native String nativeGetUTF8Text(); private native int nativeMeanConfidence(); private native int[] nativeWordConfidences(); private native boolean nativeSetVariable(String var, String value); private native void nativeSetDebug(boolean debug); private native void nativeSetPageSegMode(int mode); }
1006373c-hello
tesseract-android-tools/src/com/googlecode/tesseract/android/TessBaseAPI.java
Java
asf20
12,348
/* * Copyright (C) 2011 Google Inc. * * 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. */ package com.googlecode.leptonica.android; import android.graphics.Rect; /** * Java representation of a native Leptonica PIX object. * * @author alanv@google.com (Alan Viverette) */ public class Pix { static { System.loadLibrary("lept"); } /** Index of the image width within the dimensions array. */ public static final int INDEX_W = 0; /** Index of the image height within the dimensions array. */ public static final int INDEX_H = 1; /** Index of the image bit-depth within the dimensions array. */ public static final int INDEX_D = 2; /** Package-accessible pointer to native pix */ final int mNativePix; private boolean mRecycled; /** * Creates a new Pix wrapper for the specified native PIX object. Never call * this twice on the same native pointer, because finalize() will attempt to * free native memory twice. * * @param nativePix A pointer to the native PIX object. */ public Pix(int nativePix) { mNativePix = nativePix; mRecycled = false; } public Pix(int width, int height, int depth) { if (width <= 0 || height <= 0) { throw new IllegalArgumentException("Pix width and height must be > 0"); } else if (depth != 1 && depth != 2 && depth != 4 && depth != 8 && depth != 16 && depth != 24 && depth != 32) { throw new IllegalArgumentException("Depth must be one of 1, 2, 4, 8, 16, or 32"); } mNativePix = nativeCreatePix(width, height, depth); mRecycled = false; } /** * Returns a pointer to the native Pix object. This is used by native code * and is only valid within the same process in which the Pix was created. * * @return a native pointer to the Pix object */ public int getNativePix() { return mNativePix; } /** * Return the raw bytes of the native PIX object. You can reconstruct the * Pix from this data using createFromPix(). * * @return a copy of this PIX object's raw data */ public byte[] getData() { int size = nativeGetDataSize(mNativePix); byte[] buffer = new byte[size]; if (!nativeGetData(mNativePix, buffer)) { throw new RuntimeException("native getData failed"); } return buffer; } /** * Returns an array of this image's dimensions. See Pix.INDEX_* for indices. * * @return an array of this image's dimensions or <code>null</code> on * failure */ public int[] getDimensions() { int[] dimensions = new int[4]; if (getDimensions(dimensions)) { return dimensions; } return null; } /** * Fills an array with this image's dimensions. The array must be at least 3 * elements long. * * @param dimensions An integer array with at least three elements. * @return <code>true</code> on success */ public boolean getDimensions(int[] dimensions) { return nativeGetDimensions(mNativePix, dimensions); } /** * Returns a clone of this Pix. This does NOT create a separate copy, just a * new pointer that can be recycled without affecting other clones. * * @return a clone (shallow copy) of the Pix */ @Override public Pix clone() { int nativePix = nativeClone(mNativePix); if (nativePix == 0) { throw new OutOfMemoryError(); } return new Pix(nativePix); } /** * Returns a deep copy of this Pix that can be modified without affecting * the original Pix. * * @return a copy of the Pix */ public Pix copy() { int nativePix = nativeCopy(mNativePix); if (nativePix == 0) { throw new OutOfMemoryError(); } return new Pix(nativePix); } /** * Inverts this Pix in-place. * * @return <code>true</code> on success */ public boolean invert() { return nativeInvert(mNativePix); } /** * Releases resources and frees any memory associated with this Pix. You may * not modify or access the pix after calling this method. */ public void recycle() { if (!mRecycled) { nativeDestroy(mNativePix); mRecycled = true; } } @Override protected void finalize() throws Throwable { recycle(); super.finalize(); } /** * Creates a new Pix from raw Pix data obtained from getData(). * * @param pixData Raw pix data obtained from getData(). * @param width The width of the original Pix. * @param height The height of the original Pix. * @param depth The bit-depth of the original Pix. * @return a new Pix or <code>null</code> on error */ public static Pix createFromPix(byte[] pixData, int width, int height, int depth) { int nativePix = nativeCreateFromData(pixData, width, height, depth); if (nativePix == 0) { throw new OutOfMemoryError(); } return new Pix(nativePix); } /** * Returns a Rect with the width and height of this Pix. * * @return a Rect with the width and height of this Pix */ public Rect getRect() { int w = getWidth(); int h = getHeight(); return new Rect(0, 0, w, h); } /** * Returns the width of this Pix. * * @return the width of this Pix */ public int getWidth() { return nativeGetWidth(mNativePix); } /** * Returns the height of this Pix. * * @return the height of this Pix */ public int getHeight() { return nativeGetHeight(mNativePix); } /** * Returns the depth of this Pix. * * @return the depth of this Pix */ public int getDepth() { return nativeGetDepth(mNativePix); } /** * Returns the {@link android.graphics.Color} at the specified location. * * @param x The x coordinate (0...width-1) of the pixel to return. * @param y The y coordinate (0...height-1) of the pixel to return. * @return The argb {@link android.graphics.Color} at the specified * coordinate. * @throws IllegalArgumentException If x, y exceeds the image bounds. */ public int getPixel(int x, int y) { if (x < 0 || x >= getWidth()) { throw new IllegalArgumentException("Supplied x coordinate exceeds image bounds"); } else if (y < 0 || y >= getHeight()) { throw new IllegalArgumentException("Supplied x coordinate exceeds image bounds"); } return nativeGetPixel(mNativePix, x, y); } /** * Sets the {@link android.graphics.Color} at the specified location. * * @param x The x coordinate (0...width-1) of the pixel to set. * @param y The y coordinate (0...height-1) of the pixel to set. * @param color The argb {@link android.graphics.Color} to set at the * specified coordinate. * @throws IllegalArgumentException If x, y exceeds the image bounds. */ public void setPixel(int x, int y, int color) { if (x < 0 || x >= getWidth()) { throw new IllegalArgumentException("Supplied x coordinate exceeds image bounds"); } else if (y < 0 || y >= getHeight()) { throw new IllegalArgumentException("Supplied x coordinate exceeds image bounds"); } nativeSetPixel(mNativePix, x, y, color); } // *************** // * NATIVE CODE * // *************** private static native int nativeCreatePix(int w, int h, int d); private static native int nativeCreateFromData(byte[] data, int w, int h, int d); private static native boolean nativeGetData(int nativePix, byte[] data); private static native int nativeGetDataSize(int nativePix); private static native int nativeClone(int nativePix); private static native int nativeCopy(int nativePix); private static native boolean nativeInvert(int nativePix); private static native void nativeDestroy(int nativePix); private static native boolean nativeGetDimensions(int nativePix, int[] dimensions); private static native int nativeGetWidth(int nativePix); private static native int nativeGetHeight(int nativePix); private static native int nativeGetDepth(int nativePix); private static native int nativeGetPixel(int nativePix, int x, int y); private static native void nativeSetPixel(int nativePix, int x, int y, int color); }
1006373c-hello
tesseract-android-tools/src/com/googlecode/leptonica/android/Pix.java
Java
asf20
9,231
/* * Copyright (C) 2011 Google Inc. * * 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. */ package com.googlecode.leptonica.android; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import java.io.File; /** * Image input and output methods. * * @author alanv@google.com (Alan Viverette) */ public class ReadFile { static { System.loadLibrary("lept"); } /** * Creates a 32bpp Pix object from encoded data. Supported formats are BMP * and JPEG. * * @param encodedData JPEG or BMP encoded byte data. * @return a 32bpp Pix object */ public static Pix readMem(byte[] encodedData) { if (encodedData == null) throw new IllegalArgumentException("Image data byte array must be non-null"); final BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inPreferredConfig = Bitmap.Config.ARGB_8888; final Bitmap bmp = BitmapFactory.decodeByteArray(encodedData, 0, encodedData.length, opts); final Pix pix = readBitmap(bmp); bmp.recycle(); return pix; } /** * Creates an 8bpp Pix object from raw 8bpp grayscale pixels. * * @param pixelData 8bpp grayscale pixel data. * @param width The width of the input image. * @param height The height of the input image. * @return an 8bpp Pix object */ public static Pix readBytes8(byte[] pixelData, int width, int height) { if (pixelData == null) throw new IllegalArgumentException("Byte array must be non-null"); if (width <= 0) throw new IllegalArgumentException("Image width must be greater than 0"); if (height <= 0) throw new IllegalArgumentException("Image height must be greater than 0"); if (pixelData.length < width * height) throw new IllegalArgumentException("Array length does not match dimensions"); int nativePix = nativeReadBytes8(pixelData, width, height); if (nativePix == 0) throw new RuntimeException("Failed to read pix from memory"); return new Pix(nativePix); } /** * Replaces the bytes in an 8bpp Pix object with raw grayscale 8bpp pixels. * Width and height be identical to the input Pix. * * @param pixs The Pix whose bytes will be replaced. * @param pixelData 8bpp grayscale pixel data. * @param width The width of the input image. * @param height The height of the input image. * @return an 8bpp Pix object */ public static boolean replaceBytes8(Pix pixs, byte[] pixelData, int width, int height) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); if (pixelData == null) throw new IllegalArgumentException("Byte array must be non-null"); if (width <= 0) throw new IllegalArgumentException("Image width must be greater than 0"); if (height <= 0) throw new IllegalArgumentException("Image height must be greater than 0"); if (pixelData.length < width * height) throw new IllegalArgumentException("Array length does not match dimensions"); if (pixs.getWidth() != width) throw new IllegalArgumentException("Source pix width does not match image width"); if (pixs.getHeight() != height) throw new IllegalArgumentException("Source pix width does not match image width"); return nativeReplaceBytes8(pixs.mNativePix, pixelData, width, height); } /** * Creates a Pixa object from encoded files in a directory. Supported * formats are BMP and JPEG. * * @param dir The directory containing the files. * @param prefix The prefix of the files to load into a Pixa. * @return a Pixa object containing one Pix for each file */ public static Pixa readFiles(File dir, String prefix) { if (dir == null) throw new IllegalArgumentException("Directory must be non-null"); if (!dir.exists()) throw new IllegalArgumentException("Directory does not exist"); if (!dir.canRead()) throw new IllegalArgumentException("Cannot read directory"); // TODO: Remove or fix this. throw new RuntimeException("readFiles() is not current supported"); } /** * Creates a Pix object from encoded file data. Supported formats are BMP * and JPEG. * * @param file The JPEG or BMP-encoded file to read in as a Pix. * @return a Pix object */ public static Pix readFile(File file) { if (file == null) throw new IllegalArgumentException("File must be non-null"); if (!file.exists()) throw new IllegalArgumentException("File does not exist"); if (!file.canRead()) throw new IllegalArgumentException("Cannot read file"); final BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inPreferredConfig = Bitmap.Config.ARGB_8888; final Bitmap bmp = BitmapFactory.decodeFile(file.getAbsolutePath(), opts); final Pix pix = readBitmap(bmp); bmp.recycle(); return pix; } /** * Creates a Pix object from Bitmap data. Currently supports only * ARGB_8888-formatted bitmaps. * * @param bmp The Bitmap object to convert to a Pix. * @return a Pix object */ public static Pix readBitmap(Bitmap bmp) { if (bmp == null) throw new IllegalArgumentException("Bitmap must be non-null"); if (bmp.getConfig() != Bitmap.Config.ARGB_8888) throw new IllegalArgumentException("Bitmap config must be ARGB_8888"); int nativePix = nativeReadBitmap(bmp); if (nativePix == 0) throw new RuntimeException("Failed to read pix from bitmap"); return new Pix(nativePix); } // *************** // * NATIVE CODE * // *************** private static native int nativeReadMem(byte[] data, int size); private static native int nativeReadBytes8(byte[] data, int w, int h); private static native boolean nativeReplaceBytes8(int nativePix, byte[] data, int w, int h); private static native int nativeReadFiles(String dirname, String prefix); private static native int nativeReadFile(String filename); private static native int nativeReadBitmap(Bitmap bitmap); }
1006373c-hello
tesseract-android-tools/src/com/googlecode/leptonica/android/ReadFile.java
Java
asf20
6,967
/* * Copyright (C) 2011 Google Inc. * * 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. */ package com.googlecode.leptonica.android; /** * Wrapper for Leptonica's native BOX. * * @author alanv@google.com (Alan Viverette) */ public class Box { static { System.loadLibrary("lept"); } /** The index of the X coordinate within the geometry array. */ public static final int INDEX_X = 0; /** The index of the Y coordinate within the geometry array. */ public static final int INDEX_Y = 1; /** The index of the width within the geometry array. */ public static final int INDEX_W = 2; /** The index of the height within the geometry array. */ public static final int INDEX_H = 3; /** * A pointer to the native Box object. This is used internally by native * code. */ final int mNativeBox; private boolean mRecycled = false; /** * Creates a new Box wrapper for the specified native BOX. * * @param nativeBox A pointer to the native BOX. */ Box(int nativeBox) { mNativeBox = nativeBox; mRecycled = false; } /** * Creates a box with the specified geometry. All dimensions should be * non-negative and specified in pixels. * * @param x X-coordinate of the top-left corner of the box. * @param y Y-coordinate of the top-left corner of the box. * @param w Width of the box. * @param h Height of the box. */ public Box(int x, int y, int w, int h) { if (x < 0 || y < 0 || w < 0 || h < 0) { throw new IllegalArgumentException("All box dimensions must be non-negative"); } int nativeBox = nativeCreate(x, y, w, h); if (nativeBox == 0) { throw new OutOfMemoryError(); } mNativeBox = nativeBox; mRecycled = false; } /** * Returns the box's x-coordinate in pixels. * * @return The box's x-coordinate in pixels. */ public int getX() { return nativeGetX(mNativeBox); } /** * Returns the box's y-coordinate in pixels. * * @return The box's y-coordinate in pixels. */ public int getY() { return nativeGetY(mNativeBox); } /** * Returns the box's width in pixels. * * @return The box's width in pixels. */ public int getWidth() { return nativeGetWidth(mNativeBox); } /** * Returns the box's height in pixels. * * @return The box's height in pixels. */ public int getHeight() { return nativeGetHeight(mNativeBox); } /** * Returns an array containing the coordinates of this box. See INDEX_* * constants for indices. * * @return an array of box oordinates */ public int[] getGeometry() { int[] geometry = new int[4]; if (getGeometry(geometry)) { return geometry; } return null; } /** * Fills an array containing the coordinates of this box. See INDEX_* * constants for indices. * * @param geometry A 4+ element integer array to fill with coordinates. * @return <code>true</code> on success */ public boolean getGeometry(int[] geometry) { if (geometry.length < 4) { throw new IllegalArgumentException("Geometry array must be at least 4 elements long"); } return nativeGetGeometry(mNativeBox, geometry); } /** * Releases resources and frees any memory associated with this Box. */ public void recycle() { if (!mRecycled) { nativeDestroy(mNativeBox); mRecycled = true; } } @Override protected void finalize() throws Throwable { recycle(); super.finalize(); } // *************** // * NATIVE CODE * // *************** private static native int nativeCreate(int x, int y, int w, int h); private static native int nativeGetX(int nativeBox); private static native int nativeGetY(int nativeBox); private static native int nativeGetWidth(int nativeBox); private static native int nativeGetHeight(int nativeBox); private static native void nativeDestroy(int nativeBox); private static native boolean nativeGetGeometry(int nativeBox, int[] geometry); }
1006373c-hello
tesseract-android-tools/src/com/googlecode/leptonica/android/Box.java
Java
asf20
4,880
/* * Copyright (C) 2011 Google Inc. * * 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. */ package com.googlecode.leptonica.android; /** * Image bit-depth conversion methods. * * @author alanv@google.com (Alan Viverette) */ public class Convert { static { System.loadLibrary("lept"); } /** * Converts an image of any bit depth to 8-bit grayscale. * * @param pixs Source pix of any bit-depth. * @return a new Pix image or <code>null</code> on error */ public static Pix convertTo8(Pix pixs) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int nativePix = nativeConvertTo8(pixs.mNativePix); if (nativePix == 0) throw new RuntimeException("Failed to natively convert pix"); return new Pix(nativePix); } // *************** // * NATIVE CODE * // *************** private static native int nativeConvertTo8(int nativePix); }
1006373c-hello
tesseract-android-tools/src/com/googlecode/leptonica/android/Convert.java
Java
asf20
1,506
/* * Copyright (C) 2011 Google Inc. * * 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. */ package com.googlecode.leptonica.android; import android.graphics.Rect; import java.io.File; import java.util.ArrayList; import java.util.Iterator; /** * Java representation of a native PIXA object. This object contains multiple * PIX objects and their associated bounding BOX objects. * * @author alanv@google.com (Alan Viverette) */ public class Pixa implements Iterable<Pix> { static { System.loadLibrary("lept"); } /** A pointer to the native PIXA object. This is used internally by native code. */ final int mNativePixa; /** The specified width of this Pixa. */ final int mWidth; /** The specified height of this Pixa. */ final int mHeight; private boolean mRecycled; /** * Creates a new Pixa with the specified minimum capacity. The Pixa will * expand automatically as new Pix are added. * * @param size The minimum capacity of this Pixa. * @return a new Pixa or <code>null</code> on error */ public static Pixa createPixa(int size) { return createPixa(size, 0, 0); } /** * Creates a new Pixa with the specified minimum capacity. The Pixa will * expand automatically as new Pix are added. * <p> * If non-zero, the specified width and height will be used to specify the * bounds of output images. * * * @param size The minimum capacity of this Pixa. * @param width (Optional) The width of this Pixa, use 0 for default. * @param height (Optional) The height of this Pixa, use 0 for default. * @return a new Pixa or <code>null</code> on error */ public static Pixa createPixa(int size, int width, int height) { int nativePixa = nativeCreate(size); if (nativePixa == 0) { throw new OutOfMemoryError(); } return new Pixa(nativePixa, width, height); } /** * Creates a wrapper for the specified native Pixa pointer. * * @param nativePixa Native pointer to a PIXA object. * @param width The width of the PIXA. * @param height The height of the PIXA. */ public Pixa(int nativePixa, int width, int height) { mNativePixa = nativePixa; mWidth = width; mHeight = height; mRecycled = false; } /** * Returns a pointer to the native PIXA object. This is used by native code. * * @return a pointer to the native PIXA object */ public int getNativePixa() { return mNativePixa; } /** * Creates a shallow copy of this Pixa. Contained Pix are cloned, and the * resulting Pixa may be recycled separately from the original. * * @return a shallow copy of this Pixa */ public Pixa copy() { int nativePixa = nativeCopy(mNativePixa); if (nativePixa == 0) { throw new OutOfMemoryError(); } return new Pixa(nativePixa, mWidth, mHeight); } /** * Sorts this Pixa using the specified field and order. See * Constants.L_SORT_BY_* and Constants.L_SORT_INCREASING or * Constants.L_SORT_DECREASING. * * @param field The field to sort by. See Constants.L_SORT_BY_*. * @param order The order in which to sort. Must be either * Constants.L_SORT_INCREASING or Constants.L_SORT_DECREASING. * @return a sorted copy of this Pixa */ public Pixa sort(int field, int order) { int nativePixa = nativeSort(mNativePixa, field, order); if (nativePixa == 0) { throw new OutOfMemoryError(); } return new Pixa(nativePixa, mWidth, mHeight); } /** * Returns the number of elements in this Pixa. * * @return the number of elements in this Pixa */ public int size() { return nativeGetCount(mNativePixa); } /** * Recycles this Pixa and frees natively allocated memory. You may not * access or modify the Pixa after calling this method. * <p> * Any Pix obtained from this Pixa or copies of this Pixa will still be * accessible until they are explicitly recycled or finalized by the garbage * collector. */ public synchronized void recycle() { if (!mRecycled) { nativeDestroy(mNativePixa); mRecycled = true; } } @Override protected void finalize() throws Throwable { recycle(); super.finalize(); } /** * Merges the contents of another Pixa into this one. * * @param otherPixa * @return <code>true</code> on success */ public boolean join(Pixa otherPixa) { return nativeJoin(mNativePixa, otherPixa.mNativePixa); } /** * Adds a Pix to this Pixa. * * @param pix The Pix to add. * @param mode The mode in which to add this Pix, typically * Constants.L_CLONE. */ public void addPix(Pix pix, int mode) { nativeAddPix(mNativePixa, pix.mNativePix, mode); } /** * Adds a Box to this Pixa. * * @param box The Box to add. * @param mode The mode in which to add this Box, typically * Constants.L_CLONE. */ public void addBox(Box box, int mode) { nativeAddBox(mNativePixa, box.mNativeBox, mode); } /** * Adds a Pix and associated Box to this Pixa. * * @param pix The Pix to add. * @param box The Box to add. * @param mode The mode in which to add this Pix and Box, typically * Constants.L_CLONE. */ public void add(Pix pix, Box box, int mode) { nativeAdd(mNativePixa, pix.mNativePix, box.mNativeBox, mode); } /** * Returns the Box at the specified index, or <code>null</code> on error. * * @param index The index of the Box to return. * @return the Box at the specified index, or <code>null</code> on error */ public Box getBox(int index) { int nativeBox = nativeGetBox(mNativePixa, index); if (nativeBox == 0) { return null; } return new Box(nativeBox); } /** * Returns the Pix at the specified index, or <code>null</code> on error. * * @param index The index of the Pix to return. * @return the Pix at the specified index, or <code>null</code> on error */ public Pix getPix(int index) { int nativePix = nativeGetPix(mNativePixa, index); if (nativePix == 0) { return null; } return new Pix(nativePix); } /** * Returns the width of this Pixa, or 0 if one was not set when it was * created. * * @return the width of this Pixa, or 0 if one was not set when it was * created */ public int getWidth() { return mWidth; } /** * Returns the height of this Pixa, or 0 if one was not set when it was * created. * * @return the height of this Pixa, or 0 if one was not set when it was * created */ public int getHeight() { return mHeight; } /** * Returns a bounding Rect for this Pixa, which may be (0,0,0,0) if width * and height were not specified on creation. * * @return a bounding Rect for this Pixa */ public Rect getRect() { return new Rect(0, 0, mWidth, mHeight); } /** * Returns a bounding Rect for the Box at the specified index. * * @param index The index of the Box to get the bounding Rect of. * @return a bounding Rect for the Box at the specified index */ public Rect getBoxRect(int index) { int[] dimensions = getBoxGeometry(index); if (dimensions == null) { return null; } int x = dimensions[Box.INDEX_X]; int y = dimensions[Box.INDEX_Y]; int w = dimensions[Box.INDEX_W]; int h = dimensions[Box.INDEX_H]; Rect bound = new Rect(x, y, x + w, y + h); return bound; } /** * Returns a geometry array for the Box at the specified index. See * Box.INDEX_* for indices. * * @param index The index of the Box to get the geometry of. * @return a bounding Rect for the Box at the specified index */ public int[] getBoxGeometry(int index) { int[] dimensions = new int[4]; if (getBoxGeometry(index, dimensions)) { return dimensions; } return null; } /** * Fills an array with the geometry of the Box at the specified index. See * Box.INDEX_* for indices. * * @param index The index of the Box to get the geometry of. * @param dimensions The array to fill with Box geometry. Must be at least 4 * elements. * @return <code>true</code> on success */ public boolean getBoxGeometry(int index, int[] dimensions) { return nativeGetBoxGeometry(mNativePixa, index, dimensions); } /** * Returns an ArrayList of Box bounding Rects. * * @return an ArrayList of Box bounding Rects */ public ArrayList<Rect> getBoxRects() { final int pixaCount = nativeGetCount(mNativePixa); final int[] buffer = new int[4]; final ArrayList<Rect> rects = new ArrayList<Rect>(pixaCount); for (int i = 0; i < pixaCount; i++) { getBoxGeometry(i, buffer); final int x = buffer[Box.INDEX_X]; final int y = buffer[Box.INDEX_Y]; final Rect bound = new Rect(x, y, x + buffer[Box.INDEX_W], y + buffer[Box.INDEX_H]); rects.add(bound); } return rects; } /** * Replaces the Pix and Box at the specified index with the specified Pix * and Box, both of which may be recycled after calling this method. * * @param index The index of the Pix to replace. * @param pix The Pix to replace the existing Pix. * @param box The Box to replace the existing Box. */ public void replacePix(int index, Pix pix, Box box) { nativeReplacePix(mNativePixa, index, pix.mNativePix, box.mNativeBox); } /** * Merges the Pix at the specified indices and removes the Pix at the second * index. * * @param indexA The index of the first Pix. * @param indexB The index of the second Pix, which will be removed after * merging. */ public void mergeAndReplacePix(int indexA, int indexB) { nativeMergeAndReplacePix(mNativePixa, indexA, indexB); } /** * Writes the components of this Pix to a bitmap-formatted file using a * random color map. * * @param file The file to write to. * @return <code>true</code> on success */ public boolean writeToFileRandomCmap(File file) { return nativeWriteToFileRandomCmap(mNativePixa, file.getAbsolutePath(), mWidth, mHeight); } @Override public Iterator<Pix> iterator() { return new PixIterator(); } private class PixIterator implements Iterator<Pix> { private int mIndex; private PixIterator() { mIndex = 0; } @Override public boolean hasNext() { final int size = size(); return (size > 0 && mIndex < size); } @Override public Pix next() { return getPix(mIndex++); } @Override public void remove() { throw new UnsupportedOperationException(); } } // *************** // * NATIVE CODE * // *************** private static native int nativeCreate(int size); private static native int nativeCopy(int nativePixa); private static native int nativeSort(int nativePixa, int field, int order); private static native boolean nativeJoin(int nativePixa, int otherPixa); private static native int nativeGetCount(int nativePixa); private static native void nativeDestroy(int nativePixa); private static native void nativeAddPix(int nativePixa, int nativePix, int mode); private static native void nativeAddBox(int nativePixa, int nativeBox, int mode); private static native void nativeAdd(int nativePixa, int nativePix, int nativeBox, int mode); private static native boolean nativeWriteToFileRandomCmap( int nativePixa, String fileName, int width, int height); private static native void nativeReplacePix( int nativePixa, int index, int nativePix, int nativeBox); private static native void nativeMergeAndReplacePix(int nativePixa, int indexA, int indexB); private static native int nativeGetBox(int nativePix, int index); private static native int nativeGetPix(int nativePix, int index); private static native boolean nativeGetBoxGeometry(int nativePixa, int index, int[] dimensions); }
1006373c-hello
tesseract-android-tools/src/com/googlecode/leptonica/android/Pixa.java
Java
asf20
13,432
/* * Copyright (C) 2011 Google Inc. * * 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. */ package com.googlecode.leptonica.android; import android.graphics.Bitmap; import java.io.File; /** * @author alanv@google.com (Alan Viverette) */ public class WriteFile { static { System.loadLibrary("lept"); } /* Default JPEG quality */ public static final int DEFAULT_QUALITY = 85; /* Default JPEG progressive encoding */ public static final boolean DEFAULT_PROGRESSIVE = true; /** * Write an 8bpp Pix to a flat byte array. * * @param pixs The 8bpp source image. * @return a byte array where each byte represents a single 8-bit pixel */ public static byte[] writeBytes8(Pix pixs) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int size = pixs.getWidth() * pixs.getHeight(); if (pixs.getDepth() != 8) { Pix pix8 = Convert.convertTo8(pixs); pixs.recycle(); pixs = pix8; } byte[] data = new byte[size]; writeBytes8(pixs, data); return data; } /** * Write an 8bpp Pix to a flat byte array. * * @param pixs The 8bpp source image. * @param data A byte array large enough to hold the pixels of pixs. * @return the number of bytes written to data */ public static int writeBytes8(Pix pixs, byte[] data) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); int size = pixs.getWidth() * pixs.getHeight(); if (data.length < size) throw new IllegalArgumentException("Data array must be large enough to hold image bytes"); int bytesWritten = nativeWriteBytes8(pixs.mNativePix, data); return bytesWritten; } /** * Writes all the images in a Pixa array to individual files using the * specified format. The output file extension will be determined by the * format. * <p> * Output file names will take the format <path>/<prefix><index>.<extension> * * @param pixas The source Pixa image array. * @param path The output directory. * @param prefix The prefix to give output files. * @param format The format to use for output files. * @return <code>true</code> on success */ public static boolean writeFiles(Pixa pixas, File path, String prefix, int format) { if (pixas == null) throw new IllegalArgumentException("Source pixa must be non-null"); if (path == null) throw new IllegalArgumentException("Destination path non-null"); if (prefix == null) throw new IllegalArgumentException("Filename prefix must be non-null"); String rootname = new File(path, prefix).getAbsolutePath(); throw new RuntimeException("writeFiles() is not currently supported"); } /** * Write a Pix to a byte array using the specified encoding from * Constants.IFF_*. * * @param pixs The source image. * @param format A format from Constants.IFF_*. * @return a byte array containing encoded bytes */ public static byte[] writeMem(Pix pixs, int format) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); return nativeWriteMem(pixs.mNativePix, format); } /** * Writes a Pix to file using the file extension as the output format; * supported formats are .jpg or .jpeg for JPEG and .bmp for bitmap. * <p> * Uses default quality and progressive encoding settings. * * @param pixs Source image. * @param file The file to write. * @return <code>true</code> on success */ public static boolean writeImpliedFormat(Pix pixs, File file) { return writeImpliedFormat(pixs, file, DEFAULT_QUALITY, DEFAULT_PROGRESSIVE); } /** * Writes a Pix to file using the file extension as the output format; * supported formats are .jpg or .jpeg for JPEG and .bmp for bitmap. * <p> * Notes: * <ol> * <li>This determines the output format from the filename extension. * <li>The last two args are ignored except for requests for jpeg files. * <li>The jpeg default quality is 75. * </ol> * * @param pixs Source image. * @param file The file to write. * @param quality (Only for lossy formats) Quality between 1 - 100, 0 for * default. * @param progressive (Only for JPEG) Whether to encode as progressive. * @return <code>true</code> on success */ public static boolean writeImpliedFormat( Pix pixs, File file, int quality, boolean progressive) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); if (file == null) throw new IllegalArgumentException("File must be non-null"); return nativeWriteImpliedFormat( pixs.mNativePix, file.getAbsolutePath(), quality, progressive); } /** * Writes a Pix to an Android Bitmap object. The output Bitmap will always * be in ARGB_8888 format, but the input Pixs may be any bit-depth. * * @param pixs The source image. * @return a Bitmap containing a copy of the source image, or <code>null * </code> on failure */ public static Bitmap writeBitmap(Pix pixs) { if (pixs == null) throw new IllegalArgumentException("Source pix must be non-null"); final int[] dimensions = pixs.getDimensions(); final int width = dimensions[Pix.INDEX_W]; final int height = dimensions[Pix.INDEX_H]; //final int depth = dimensions[Pix.INDEX_D]; final Bitmap.Config config = Bitmap.Config.ARGB_8888; final Bitmap bitmap = Bitmap.createBitmap(width, height, config); if (nativeWriteBitmap(pixs.mNativePix, bitmap)) { return bitmap; } bitmap.recycle(); return null; } // *************** // * NATIVE CODE * // *************** private static native int nativeWriteBytes8(int nativePix, byte[] data); private static native boolean nativeWriteFiles(int nativePix, String rootname, int format); private static native byte[] nativeWriteMem(int nativePix, int format); private static native boolean nativeWriteImpliedFormat( int nativePix, String fileName, int quality, boolean progressive); private static native boolean nativeWriteBitmap(int nativePix, Bitmap bitmap); }
1006373c-hello
tesseract-android-tools/src/com/googlecode/leptonica/android/WriteFile.java
Java
asf20
7,145
End of preview. Expand in Data Studio

Google Code Archive Dataset

Dataset Description

This dataset was compiled from the Google Code Archive, a preserved snapshot of projects hosted on Google Code, Google's open-source project hosting service that operated from 2006 to 2016. Google Code was one of the major code hosting platforms of its era, hosting hundreds of thousands of open-source projects before its shutdown. The archive provides a unique historical record of open-source development during a formative period of modern software engineering.

Dataset Summary

Statistic Value
Total Files 65,825,565
Total Repositories 488,618
Total Size 47 GB (compressed Parquet)
Programming Languages 454
File Format Parquet with Zstd compression (71 files)

Key Features

  • Historical open-source corpus: Contains code from over 488K repositories hosted on Google Code during 2006-2016
  • Diverse language coverage: Spans 454 programming languages identified by go-enry (based on GitHub Linguist rules)
  • Rich metadata: Includes repository name, file path, detected language, license information, and file size
  • Quality filtered: Extensive filtering to remove vendor code, build artifacts, generated files, and low-quality content
  • Era-specific patterns: Captures coding conventions and library usage from the pre-modern era of software development

Languages

The dataset includes 454 programming languages. The top 30 languages by file count:

Rank Language File Count
1 Java 16,331,993
2 PHP 12,764,574
3 HTML 5,705,184
4 C++ 5,090,685
5 JavaScript 4,937,765
6 C 4,179,202
7 C# 3,872,245
8 Python 2,207,240
9 CSS 1,697,385
10 Objective-C 1,186,050
11 Shell 639,183
12 Java Server Pages 541,498
13 ActionScript 540,557
14 Makefile 481,563
15 ASP.NET 381,389
16 Smarty 339,555
17 Ruby 331,743
18 Go 316,427
19 Perl 307,960
20 Vim Script 216,236
21 Lua 215,226
22 HTML+PHP 150,781
23 HTML+Razor 149,131
24 MATLAB 145,686
25 Batchfile 138,523
26 Pascal 135,992
27 Visual Basic .NET 118,732
28 TeX 110,379
29 Less 98,221
30 Unix Assembly 94,758

Licenses

The dataset includes files from repositories with various licenses as specified in the Google Code Archive:

License File Count
Apache License 2.0 (asf20) 21,568,143
GNU GPL v3 (gpl3) 14,843,470
GNU GPL v2 (gpl2) 6,824,185
Other Open Source (oos) 5,433,436
MIT License (mit) 4,754,567
GNU LGPL (lgpl) 4,073,137
BSD License (bsd) 3,787,348
Artistic License (art) 1,910,047
Eclipse Public License (epl) 1,587,289
Mozilla Public License 1.1 (mpl11) 580,102
Multiple Licenses (multiple) 372,457
Google Summer of Code (gsoc) 63,292
Public Domain (publicdomain) 28,092

Dataset Structure

Data Fields

Field Type Description
code string Content of the source file (UTF-8 encoded)
repo_name string Name of the Google Code project
path string Path of the file within the repository (relative to repo root)
language string Programming language as identified by go-enry
license string License of the repository (Google Code license identifier)
size int64 Size of the source file in bytes

Data Format

  • Format: Apache Parquet with Zstd compression
  • File Structure: 71 files (google_code_0000.parquet to google_code_0070.parquet)

Data Splits

All examples are in the train split. There is no validation or test split.

Example Data Point

{
    'code': 'public class HundredIntegers {\n\tpublic static void main (String[] args) {\n\t\tfor (int i = 1; i<=100; i++) {\n\t\t\tSystem.out.println(i);\n\t\t}\n\t}\n}',
    'repo_name': '100integers',
    'path': 'HundredIntegers.java',
    'language': 'Java',
    'license': 'epl',
    'size': 147
}

Dataset Creation

Pipeline Overview

The dataset was created through a multi-stage pipeline:

  1. Project Discovery: Fetching project metadata from the Google Code Archive
  2. Source Filtering: Selecting projects that have source code available (hasSource: true)
  3. Archive Downloading: Downloading source archives from the Google Code Archive storage
  4. Content Extraction: Extracting and filtering source code files
  5. Parquet Generation: Writing filtered records to Parquet shards with Zstd compression

Language Detection

Programming languages are detected using go-enry, a Go port of GitHub's Linguist library. Only files classified as Programming or Markup language types are included (Data and Prose types are excluded).

License Detection

Licenses are obtained directly from the Google Code Archive project metadata. The archive preserves the original license selection made by project owners when creating their repositories on Google Code.

File Filtering

Extensive filtering is applied to ensure data quality:

Size Limits

Limit Value
Max repository archive size 64 MB
Max single file size 2 MB
Max line length 1,000 characters

Excluded Directories

  • Configuration: .git/, .github/, .gitlab/, .vscode/, .idea/, .vs/, .settings/, .eclipse/, .project/, .metadata/
  • Vendor/Dependencies: node_modules/, bower_components/, jspm_packages/, vendor/, third_party/, 3rdparty/, external/, packages/, deps/, lib/vendor/, target/dependency/, Pods/
  • Build Output: build/, dist/, out/, bin/, target/, release/, debug/, .next/, .nuxt/, _site/, _build/, __pycache__/, .pytest_cache/, cmake-build-*, .gradle/, .maven/

Excluded Files

  • Lock Files: package-lock.json, yarn.lock, pnpm-lock.yaml, Gemfile.lock, Cargo.lock, poetry.lock, Pipfile.lock, composer.lock, go.sum, mix.lock
  • Minified Files: Any file containing .min. in the name
  • Binary Files: .exe, .dll, .so, .dylib, .a, .lib, .o, .obj, .jar, .war, .ear, .class, .pyc, .pyo, .wasm, .bin, .dat, .pdf, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .zip, .tar, .gz, .bz2, .7z, .rar, .jpg, .jpeg, .png, .gif, .bmp, .ico, .svg, .mp3, .mp4, .avi, .mov, .wav, .flac, .ttf, .otf, .woff, .woff2, .eot
  • System Files: .DS_Store, thumbs.db

Content Filtering

  • UTF-8 Validation: Files must be valid UTF-8 encoded text
  • Binary Detection: Files detected as binary by go-enry are excluded
  • Generated Files: Files with generation markers in the first 500 bytes are excluded:
    • generated by, do not edit, auto-generated, autogenerated, @generated, <auto-generated
  • Empty Files: Files that are empty or contain only whitespace are excluded
  • Long Lines: Files with any line exceeding 1,000 characters are excluded
  • go-enry Filters: Additional filtering using go-enry's IsVendor(), IsImage(), IsDotFile(), IsTest(), and IsGenerated() functions
  • Documentation-only Repos: Repositories containing only documentation files (no actual code) are skipped

Source Data

All data originates from the Google Code Archive, which preserves projects hosted on Google Code before its shutdown in January 2016.

Considerations for Using the Data

Historical Context

This dataset represents code from 2006-2016 and may contain:

  • Outdated coding patterns and deprecated APIs
  • Legacy library dependencies that are no longer maintained
  • Security vulnerabilities that have since been discovered and patched
  • Code written for older language versions (Python 2, older Java versions, etc.)

Users should be aware that this code reflects historical practices and may not represent modern best practices.

Personal and Sensitive Information

The dataset may contain:

  • Email addresses in code comments or configuration files
  • API keys or credentials that were accidentally committed
  • Personal information in comments or documentation

Users should exercise caution and implement appropriate filtering when using this data.

Licensing Information

This dataset is a collection of source code from repositories with various licenses. Any use of all or part of the code gathered in this dataset must abide by the terms of the original licenses, including attribution clauses when relevant. The license field in each data point indicates the license of the source repository.

Downloads last month
96

Collection including nyuuzyou/google-code-archive