code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
var assert = require('assert') var path = require('path') var fs = require('fs-extra') var sinon = require('sinon') var broccoli = require('broccoli') var Q = require('q') var Filter = require('..') describe('Filter', function() { var ORIG_DIR = path.join(__dirname, 'files') var DIR = path.join(__dirname, 'files-copy') var ONE_FILE_DIR = path.join(__dirname, 'one-file') var builder var createCustomFilter = function() { var CustomFilter = function(inputTrees, options) { if (!(this instanceof CustomFilter)) return new CustomFilter(inputTrees, options) Filter.apply(this, arguments) } CustomFilter.prototype = Object.create(Filter.prototype) return CustomFilter } beforeEach(function() { fs.copySync(ORIG_DIR, DIR) }) afterEach(function() { if (builder) builder.cleanup() fs.removeSync(DIR) }) it('throws when "processFileContent" is not implemented', function(done) { var CustomFilter = createCustomFilter() var tree = new CustomFilter(DIR) builder = new broccoli.Builder(tree) builder.build() .then(function() { done(new Error('Have not thrown')) }) .catch(function() { done() }) }) it('calls "processFileContent"', function() { var CustomFilter = createCustomFilter() var spy = CustomFilter.prototype.processFileContent = sinon.spy() var tree = new CustomFilter(ONE_FILE_DIR) builder = new broccoli.Builder(tree) return builder.build().then(function() { var args = spy.firstCall.args assert.equal(args[0], 'file.js\n') assert.equal(args[1], 'file.js') assert.equal(args[2], ONE_FILE_DIR) }) }) var FILTERED = 'filtered' it('filters files', function() { var CustomFilter = createCustomFilter() CustomFilter.prototype.processFileContent = function() { return FILTERED } var tree = new CustomFilter(ONE_FILE_DIR) builder = new broccoli.Builder(tree) return builder.build().then(function(result) { var dir = result.directory var content = fs.readFileSync(path.join(dir, 'file.js'), 'utf-8') assert.equal(content, FILTERED) }) }) it('uses "targetExtension"', function() { var CustomFilter = createCustomFilter() CustomFilter.prototype.processFileContent = function() { return FILTERED } var tree = new CustomFilter(ONE_FILE_DIR, {targetExtension: 'ext'}) builder = new broccoli.Builder(tree) return builder.build().then(function(result) { var dir = result.directory var content = fs.readFileSync(path.join(dir, 'file.ext'), 'utf-8') assert.equal(content, FILTERED) }) }) it('uses "changeFileName"', function() { var CustomFilter = createCustomFilter() CustomFilter.prototype.processFileContent = function() { return FILTERED } var tree = new CustomFilter(ONE_FILE_DIR, { targetExtension: 'ext', changeFileName: function(name) { return name + '.changed' } }) builder = new broccoli.Builder(tree) return builder.build().then(function(result) { var dir = result.directory var content = fs.readFileSync(path.join(dir, 'file.js.changed'), 'utf-8') assert.equal(content, FILTERED) }) }) it('can return many files', function() { var RESULT = [ {path: 'file1.js', content: 'FILE1'}, {path: 'file2.js', content: 'FILE2'} ] var CustomFilter = createCustomFilter() CustomFilter.prototype.processFileContent = function() { return RESULT } var tree = new CustomFilter(ONE_FILE_DIR) builder = new broccoli.Builder(tree) return builder.build().then(function(result) { var dir = result.directory RESULT.forEach(function(file) { var content = fs.readFileSync(path.join(dir, file.path), 'utf-8') assert.equal(content, file.content) }) }) }) it('can process files asynchronously', function() { var CustomFilter = createCustomFilter() CustomFilter.prototype.processFileContent = function() { var deferred = Q.defer() setTimeout(function() { deferred.resolve(FILTERED) }) return deferred.promise } var tree = new CustomFilter(ONE_FILE_DIR) builder = new broccoli.Builder(tree) return builder.build().then(function(result) { var dir = result.directory var content = fs.readFileSync(path.join(dir, 'file.js'), 'utf-8') assert.equal(content, FILTERED) }) }) it('copy not changed files from cache', function() { var CustomFilter = createCustomFilter() var spy = CustomFilter.prototype.processFileContent = sinon.spy() var tree = new CustomFilter(DIR) builder = new broccoli.Builder(tree) return builder.build() .then(function() { assert.equal(spy.callCount, 3) }) .then(function() { fs.writeFileSync(path.join(DIR, 'file.js'), 'CHANGED') return builder.build() }) .then(function() { assert.equal(spy.callCount, 4) }) }) it('finds files using globs', function() { var CustomFilter = createCustomFilter() var spy = CustomFilter.prototype.processFileContent = sinon.spy() var tree = new CustomFilter(DIR, {files: ['**/*.js']}) builder = new broccoli.Builder(tree) return builder.build() .then(function() { assert.equal(spy.callCount, 1) }) }) })
sunflowerdeath/broccoli-glob-filter
tests/test.js
JavaScript
unlicense
5,011
/** * * This is the "container" for global variables. I made it so we won't have to worry * about "conflicts" with local variable names. * */ var NFL_PICKS_GLOBAL = { /** * Here to store data from the server so we can hopefully load it once and then * get to it whenever it's needed as we're dealing with other stuff. */ data: { teams: [], players: [], years: [] }, /** * The possible types for what they can view. Like standings, picks, and stats. * Holds label and value pairs of all the possible types. */ types: [], /** * Holds label value pairs of all the players we show. Not all of them will be "real"... like if we * want to show "Everybody" or something like that. It'll be in here too. */ players: [], /** * All of the real players in label value pairs. This is so we can send only real players to the server * and pick them apart from the non-real players. */ realPlayers: [], /** * All the years we want to show. It'll have year ranges too (like "jurassic period" and "modern era"). It's * label and value pairs like the other arrays. */ years: [], /** * All the label and value pairs for the real and individual years. */ realYears: [], /** * All the weeks we want to show in label value pairs. It'll have ranges too (like "regular season" and "playoffs). */ weeks: [], /** * All the individual and real weeks that we want to send to the server. */ realWeeks: [], /** * All of the label/value pairs of the different stats we can show. */ statNames: [], /** * The current selections for everything they can pick. */ selections: {}, /** * Whether they're selecting more than one player at a time * or not. */ multiselectPlayer: false, /** * Whether they're selecting more than one week at a time or not. */ multiselectWeek: false, /** * Whether they're selecting more than one year at a time or not. */ multiselectYear: false, /** * The previous type they picked. This is so we can decide how much of the view we need * to "refresh" when we update it. */ previousType: null, /** * Switches that say whether these pick grids have been shown. If they haven't, we want * to make sure we don't show the picks for all years and weeks (unless they specifically asked * for that). * We don't want to do that because that's a lot of info to show. So, these are here basically * so we can "smartly" default the year and week selections for the picks and pick splits grids. */ havePicksBeenShown: false, havePickSplitsBeenShown: false, /** * Whether we should push the previous parameters onto the backward navigation stack. */ pushPreviousParameters: true, /** * The previous parameters that were used to show the view. This is so they can go back * and forth pretty easily. */ previousParameters: null, /** * The stacks for navigating forward and backward. They hold the parameters that were shown for the "view". * When they change the view, we put the previous parameters on the backward stack and when they navigate backward, * we pop those parameters off to change the view and put the previous ones on the forward stack. */ navigationForwardStack: [], navigationBackwardStack: [], /** * So we can get the current year and week number which come in handy. */ currentYear: null, currentWeekKey: null, /** * So we can show the games for the current week. */ gamesForCurrentWeek: null, /** * For holding the initial selections for when the page first shows up. We set some of these * variables with values from the server (like the year) and others (like the type) to constants. */ initialType: null, initialYear: null, initialWeek: null, initialPlayer: null, initialTeam: null, initialStatName: null }; /** * When the document's been loaded on the browser, we want to: * * 1. Go to the server and get the selection criteria (teams, players, initial values). * 2. Initialize the UI based on those values. */ $(document).ready( function(){ getSelectionCriteriaAndInitialize(); }); /** * * This function will initialize the view. It assumes all the stuff from the server * that's needed to initialize is setup. * * @returns */ function initializeView(){ //Steps to do: // 1. Set the initial selections for the type, year, week, ... // 2. Update the view based on those selections. initializeSelections(); updateView(); } /** * * Sets the initial selections for the type, year, week... * They're all set like this: * * 1. The initial value comes from NFL_PICKS_GLOBAL. * 2. If there's a url parameter for the selection, it's used instead. * * This way, we... * * 1. Set the initial values when loading the data from the server (for stuff like * week and year). * 2. Allow the overriding of the values by url parameters. * * Number 2 makes it so people can send direct urls and get the view they want the first * time the page shows up. * * @returns */ function initializeSelections(){ //Steps to do: // 1. Get the parameters that were sent in the url. // 2. Initialize each selection with its global initial value. // 3. If there's a value for it in the url, use that instead so the url // overrides what we assume initially. var parameters = getUrlParameters(); var type = NFL_PICKS_GLOBAL.initialType; if (isDefined(parameters) && isDefined(parameters.type)){ type = parameters.type; } setSelectedType(type); var year = NFL_PICKS_GLOBAL.initialYear; if (isDefined(parameters) && isDefined(parameters.year)){ year = parameters.year; } setSelectedYears(year); var week = NFL_PICKS_GLOBAL.initialWeek; if (isDefined(parameters) && isDefined(parameters.week)){ week = parameters.week; } setSelectedWeeks(week); var player = NFL_PICKS_GLOBAL.initialPlayer; if (isDefined(parameters) && isDefined(parameters.player)){ player = parameters.player; } setSelectedPlayers(player); var statName = NFL_PICKS_GLOBAL.initialStatName; if (isDefined(parameters) && isDefined(parameters.statName)){ statName = parameters.statName; } setSelectedStatName(statName); var team = NFL_PICKS_GLOBAL.initialTeam; if (isDefined(parameters) && isDefined(parameters.team)){ team = parameters.team; } setSelectedTeams(team); resetPlayerSelections(); resetYearSelections(); resetWeekSelections(); resetTeamSelections(); updateTypeLink(); updatePlayersLink(); updateWeeksLink(); updateYearsLink(); updateTeamsLink(); updateStatNameLink(); } /** * * This function will set all the selections from the given parameters. It's here * so that we can do the "navigate forward and backward" thing. We keep those parameters * in maps and then, to go forward and backward, we just have to feed the map we want to * this function. * * This function <i>WON'T</i> update the view. You'll have to do that yourself after calling it. * * @param parameters * @returns */ function setSelectionsFromParameters(parameters){ //Steps to do: // 1. If the parameters don't have anything, there's nothing to do. // 2. Otherwise, just go through and set each individual value. if (!isDefined(parameters)){ return; } if (isDefined(parameters.type)){ setSelectedType(parameters.type); } if (isDefined(parameters.player)){ setSelectedPlayers(parameters.player); } if (isDefined(parameters.year)){ setSelectedYears(parameters.year); } if (isDefined(parameters.week)){ setSelectedWeeks(parameters.week); } if (isDefined(parameters.team)){ setSelectedTeams(parameters.team); } if (isDefined(parameters.statName)){ setSelectedStatName(parameters.statName); } if (isDefined(parameters.multiselectPlayer)){ setMultiselectPlayer(parameters.multiselectPlayer); setMultiselectPlayerValue(parameters.multiselectPlayer); } if (isDefined(parameters.multiselectYear)){ setMultiselectYear(parameters.multiselectYear); setMultiselectYearValue(parameters.multiselectYear); } if (isDefined(parameters.multiselectWeek)){ setMultiselectWeek(parameters.multiselectWeek); setMultiselectWeekValue(parameters.multiselectWeek); } if (isDefined(parameters.multiselectTeam)){ setMultiselectTeam(parameters.multiselectTeam); setMultiselectTeamValue(parameters.multiselectTeam); } } /** * * This function will get the parameters in a map from the url in the browser. If there * aren't any parameters, it'll return null. Otherwise, it'll return a map with the parameter * names as the keys and the values as the url. * * @returns */ function getUrlParameters() { //Steps to do: // 1. If there aren't any parameters, there's nothing to do. // 2. Otherwise, each parameter should be separated by an ampersand, so break them apart on that. // 3. Go through each parameter and get the key and value and that's a parameter. // 4. That's it. if (isBlank(location.search)){ return null; } var parameterNamesAndValues = location.search.substring(1, location.search.length).split('&'); var urlParameters = {}; for (var index = 0; index < parameterNamesAndValues.length; index++) { var parameterNameAndValue = parameterNamesAndValues[index].split('='); //Make sure to decode both the name and value in case there are weird values in them. var name = decodeURIComponent(parameterNameAndValue[0]); var value = decodeURIComponent(parameterNameAndValue[1]); urlParameters[name] = value; } return urlParameters; } /** * * Gets all the values for each kind of parameter (type, year, week, ...) * and returns them in a map with the key being the parameter. * * Here so we can easily get what's selected (for the navigate forward and backward * stuff). * * @returns */ function getSelectedParameters(){ var parameters = {}; parameters.type = getSelectedType(); parameters.player = getSelectedPlayerValues(); parameters.year = getSelectedYearValues(); parameters.week = getSelectedWeekValues(); parameters.statName = getSelectedStatName(); parameters.team = getSelectedTeamValues(); parameters.multiselectPlayer = getMultiselectPlayer(); parameters.multiselectYear = getMultiselectYear(); parameters.multiselectWeek = getMultiselectWeek(); parameters.multiselectTeam = getMultiselectTeam(); return parameters; } /** * * This function will get the initial selection criteria (teams, players, ...) * from the server and create the selection criteria for those options. * * It will also initialize the NFL_PICKS_GLOBAL values (some are pulled from the server, * so that's why we do it in this function) and call the function that initializes the view * once it's ready. * * Those initial values will be: * * 1. type - standings * 2. year - current * 3. week - all * 4. player - all * 5. team - all * 6. statName - champions * * @returns */ function getSelectionCriteriaAndInitialize(){ //Steps to do: // 1. Send the request to the server to get the selection criteria. // 2. When it comes back, pull out the years, players, and teams // and set the options for them in each select. // 3. Set the initial values in the NFL_PICKS_GLOBAL variable. // 4. Now that we have all the criteria and initial values, we can initialize the view. $.ajax({url: 'nflpicks?target=selectionCriteria', contentType: 'application/json; charset=UTF-8'} ) .done(function(data) { var selectionCriteriaContainer = $.parseJSON(data); NFL_PICKS_GLOBAL.data.teams = selectionCriteriaContainer.teams; NFL_PICKS_GLOBAL.data.players = selectionCriteriaContainer.players; NFL_PICKS_GLOBAL.data.years = selectionCriteriaContainer.years; var types = [{label: 'Standings', value: 'standings'}, {label: 'Picks', value: 'picks'}, {label: 'Stats', value: 'stats'}]; NFL_PICKS_GLOBAL.types = types; var typeSelectorHtml = createTypeSelectorHtml(types); $('#typesContainer').empty(); $('#selectorContainer').append(typeSelectorHtml); var years = selectionCriteriaContainer.years; //We want the "all" year option to be first. var yearOptions = [{label: 'All', value: 'all'}, {label: 'Jurassic Period (2010-2015)', value: 'jurassic-period'}, {label: 'First year (2016)', value: 'first-year'}, {label: 'Modern Era (2017 - now)', value: 'modern-era'}]; var realYears = []; for (var index = 0; index < years.length; index++){ var year = years[index]; yearOptions.push({label: year, value: year}); realYears.push({label: year, value: year}); } NFL_PICKS_GLOBAL.years = yearOptions; NFL_PICKS_GLOBAL.realYears = realYears; var yearSelectorHtml = createYearSelectorHtml(yearOptions); $('#yearsContainer').empty(); $('#selectorContainer').append(yearSelectorHtml); var weekOptions = [{label: 'All', value: 'all'}, {label: 'Regular season', value: 'regular_season'}, {label: 'Playoffs', value: 'playoffs'}, {label: 'Week 1', value: '1'}, {label: 'Week 2', value: '2'}, {label: 'Week 3', value: '3'}, {label: 'Week 4', value: '4'}, {label: 'Week 5', value: '5'}, {label: 'Week 6', value: '6'}, {label: 'Week 7', value: '7'}, {label: 'Week 8', value: '8'}, {label: 'Week 9', value: '9'}, {label: 'Week 10', value: '10'}, {label: 'Week 11', value: '11'}, {label: 'Week 12', value: '12'}, {label: 'Week 13', value: '13'}, {label: 'Week 14', value: '14'}, {label: 'Week 15', value: '15'}, {label: 'Week 16', value: '16'}, {label: 'Week 17', value: '17'}, {label: 'Week 18', value: '18'}, {label: 'Wild Card', value: 'wildcard'}, {label: 'Divisional', value: 'divisional'}, {label: 'Conference Championship', value: 'conference_championship'}, {label: 'Superbowl', value: 'superbowl'} ]; //could these be 1, 2, 3, 4, ... again and just change the playoffs? //yeah i think so //week=1,2,3,4,wildcard,divisional,superbowl //yeah that's better than //week=1,2,3,wildcard,divisional //need to change .... importer ... the model util function ... this //and that should be it. var realWeeks = [{label: 'Week 1', value: '1'}, {label: 'Week 2', value: '2'}, {label: 'Week 3', value: '3'}, {label: 'Week 4', value: '4'}, {label: 'Week 5', value: '5'}, {label: 'Week 6', value: '6'}, {label: 'Week 7', value: '7'}, {label: 'Week 8', value: '8'}, {label: 'Week 9', value: '9'}, {label: 'Week 10', value: '10'}, {label: 'Week 11', value: '11'}, {label: 'Week 12', value: '12'}, {label: 'Week 13', value: '13'}, {label: 'Week 14', value: '14'}, {label: 'Week 15', value: '15'}, {label: 'Week 16', value: '16'}, {label: 'Week 17', value: '17'}, {label: 'Week 18', value: '18'}, {label: 'Wild Card', value: 'wildcard'}, {label: 'Divisional', value: 'divisional'}, {label: 'Conference Championship', value: 'conference_championship'}, {label: 'Superbowl', value: 'superbowl'} ]; //need to refactor the NFL_PICKS_GLOBAL so that it has all the options //and all the data //NFL_PICKS_GLOBAL.criteria.weeks - the weeks as selection criteria //NFL_PICKS_GLOBAL.data.weeks - all the actual weeks //global_setWeeks //global_setRealWeeks //global_getWeeks //selector_blah //html_blah //yeah this needs to be done //nflpicks global needs to be defined in a separate javascript file NFL_PICKS_GLOBAL.weeks = weekOptions; NFL_PICKS_GLOBAL.realWeeks = realWeeks; var weekSelectorHtml = createWeekSelectorHtml(weekOptions); $('#selectorContainer').append(weekSelectorHtml); var players = selectionCriteriaContainer.players; //We want the "all" player option to be the first one. var playerOptions = [{label: 'Everybody', value: 'all'}]; var realPlayers = []; for (var index = 0; index < players.length; index++){ var player = players[index]; var playerObject = {label: player, value: player}; playerOptions.push(playerObject); realPlayers.push(playerObject); } setOptionsInSelect('player', playerOptions); NFL_PICKS_GLOBAL.players = playerOptions; NFL_PICKS_GLOBAL.realPlayers = realPlayers; var playerSelectorHtml = createPlayerSelectorHtml(playerOptions); $('#selectorContainer').append(playerSelectorHtml); //Need to filter the teams so that we only show teams that had a game in a given year. //Probably just do a ui filter because we probably don't want to make a trip to the server // var teams = selectionCriteriaContainer.teams; //Sort the teams in alphabetical order to make sure we show them in a consistent order. teams.sort(function (teamA, teamB){ if (teamA.abbreviation < teamB.abbreviation){ return -1; } else if (teamA.abbreviation > teamB.abbreviation){ return 1; } return 0; }); //We also want the "all" option to be first. var teamOptions = [{label: 'All', value: 'all'}]; for (var index = 0; index < teams.length; index++){ var team = teams[index]; teamOptions.push({label: team.abbreviation, value: team.abbreviation}); } var teamSelectorHtml = createTeamSelectorHtml(teamOptions); $('#selectorContainer').append(teamSelectorHtml); NFL_PICKS_GLOBAL.teams = teamOptions; var statNameOptions = [{label: 'Champions', value: 'champions'}, {label: 'Championship Standings', value: 'championshipStandings'}, {label: 'Season Standings', value: 'seasonStandings'}, {label: 'Week Standings', value: 'weekStandings'}, {label: 'Weeks Won Standings', value: 'weeksWonStandings'}, {label: 'Weeks Won By Week', value: 'weeksWonByWeek'}, {label: 'Week Records By Player', value: 'weekRecordsByPlayer'}, {label: 'Pick Accuracy', value: 'pickAccuracy'}, {label: 'Pick Splits', value: 'pickSplits'}, {label: 'Week Comparison', value: 'weekComparison'}, {label: 'Season Progression', value: 'seasonProgression'}]; var statNameSelectorHtml = createStatNameSelectorHtml(statNameOptions); $('#selectorContainer').append(statNameSelectorHtml); NFL_PICKS_GLOBAL.statNames = statNameOptions; //The current year and week come from the server. NFL_PICKS_GLOBAL.currentYear = selectionCriteriaContainer.currentYear; NFL_PICKS_GLOBAL.currentWeekKey = selectionCriteriaContainer.currentWeekKey; //Initially, we want to see the standings for the current year for everybody, so set those //as the initial types. NFL_PICKS_GLOBAL.initialType = 'standings'; NFL_PICKS_GLOBAL.initialYear = NFL_PICKS_GLOBAL.currentYear + ''; NFL_PICKS_GLOBAL.initialWeek = 'all'; NFL_PICKS_GLOBAL.initialPlayer = 'all'; NFL_PICKS_GLOBAL.initialTeam = 'all'; NFL_PICKS_GLOBAL.initialStatName = 'champions'; initializeView(); }) .fail(function() { }) .always(function() { }); } /** * * This function will cause the view to "navigate forward". We can only do that if * we've gone back. So, this function will check the stack that holds the "forward parameters", * pop the top of it off (if there's something in it), and then cause the view to have those * parameters. * * Before navigating, it will take the current parameters and put them on the previous stack * so they can go back if they hit "back". * * @returns */ function navigateForward(){ //Steps to do: // 1. If there aren't any forward parameters, there's no way to go forward. // 2. The current parameters should go on the previous stack. // 3. Get the forward parameters off the forward stack. // 4. Set them as the selections. // 5. Update the view and make sure it doesn't push any parameters on any // stack // 6. Flip the switch back so any other navigation will push parameters // on the previous stack. if (NFL_PICKS_GLOBAL.navigationForwardStack.length == 0){ return; } var currentParameters = getSelectedParameters(); NFL_PICKS_GLOBAL.navigationBackwardStack.push(currentParameters); var parameters = NFL_PICKS_GLOBAL.navigationForwardStack.pop(); setSelectionsFromParameters(parameters); //Before updating the view, flip the switch that the updateView function uses to //decide whether to push the parameters for the current view on the stack or not. //Since we're navigating forward, we take care of that in this function instead. //A little bootleg, so it probably means I designed it wrong... NFL_PICKS_GLOBAL.pushPreviousParameters = false; updateView(); NFL_PICKS_GLOBAL.pushPreviousParameters = true; } /** * * This function will cause the view to show the previous view. It's the same thing * as going backward except will pull from the navigate backward stack. The previous parameters * for the view are stored on a stack, so to go backward, we just have to pop those parameters * off, set them as the selections, and the update the view. * * It'll also take the current parameters (before going backward) and push them on the forward stack * so navigating forward, after going backward, brings them back to where they were. * * @returns */ function navigateBackward(){ //Steps to do: // 1. If there isn't anything to backward to, there's nothing to do. // 2. The current parameters should go on the forward stack since they're // what we want to show if people navigate forward // 3. The parameters we want to use come off the backward stack. // 4. Flip the switch that says to not push any parameters on in the view function. // 5. Update based on the parameters we got. // 6. Flip the switch back so that any other navigation causes the parameters // to go on the previous stack. if (NFL_PICKS_GLOBAL.navigationBackwardStack.length == 0){ return; } var currentParameters = getSelectedParameters(); NFL_PICKS_GLOBAL.navigationForwardStack.push(currentParameters); var parameters = NFL_PICKS_GLOBAL.navigationBackwardStack.pop(); //stuff is updated here... setSelectionsFromParameters(parameters); //Just like when navigating forward, we don't want the updateView function to fiddle //with the navigation stacks since we're doing it here. After the view has been updated, though, //flip the switch back so that any other navigation cause the updateView function save the //current view before changing. NFL_PICKS_GLOBAL.pushPreviousParameters = false; updateView(); NFL_PICKS_GLOBAL.pushPreviousParameters = true; } /** * * This function will make it so we only show the forward and backward * links if they can actually navigate forward and backward. It just checks * the length of the stacks and uses that to decide whether to show * or hide each link. * * @returns */ function updateNavigationLinksVisibility(){ //Steps to do: // 1. If the stack doesn't have anything in it, we shouldn't show // the link. // 2. Otherwise, we should. if (NFL_PICKS_GLOBAL.navigationForwardStack.length == 0){ $('#navigationFowardContainer').hide(); } else { $('#navigationFowardContainer').show(); } if (NFL_PICKS_GLOBAL.navigationBackwardStack.length == 0){ $('#navigationBackwardContainer').hide(); } else { $('#navigationBackwardContainer').show(); } } /** * * The "main" function for the UI. Makes it so we show what they picked on the screen. * It bases its decision on the "type" variable and then just calls the right function * based on what that is. * * If the NFL_PICKS_GLOBAL.pushPreviousParameters switch is flipped, it'll also update * the navigation stacks. That switch is there so that: * * 1. When they do any non-forward or backward navigation action, we update the stacks. * 2. When they push forward or backward, we can handle the stacks other places. * * @returns */ function updateView(){ //Steps to do: // 1. Before doing anything, if the switch is flipped, we should save the parameters // from the last navigation on the backward stack so they can go backward to what // we're currently on, if they want. // 2. Get the type of view they want. // 3. Update the selector view based on the type. // 4. Decide which function to call based on that. // 5. After the view is updated, keep the current selected parameters around so we can push // them on the "back" stack the next time they make a change. // 6. Make sure we're showing the right "navigation" links. //If there are previous parameters, and we should push them, then push them on the backward //navigation stack so they can go back to that view with the back button. //If we shouldn't push them, that means the caller is handling the stack stuff themselves. //And, if we should push them, that means they did some "action" that takes them on a //different "branch", so we should clear out the forward stack since they can't go //forward anymore. if (NFL_PICKS_GLOBAL.previousParameters != null && NFL_PICKS_GLOBAL.pushPreviousParameters){ NFL_PICKS_GLOBAL.navigationBackwardStack.push(NFL_PICKS_GLOBAL.previousParameters); NFL_PICKS_GLOBAL.navigationForwardStack = []; } var type = getSelectedType(); //Update the selectors that get shown. We want to show different things depending //on the type. updateSelectors(type); //And update the options for the criteria in each selector. updateAvailableCriteriaOptions(); if ('picks' == type){ updatePicks(); } else if ('standings' == type) { updateStandings(); } else if ('stats' == type){ updateStats(); } //At this point, the selected parameters are the current parameters. We want to //keep them around in case we need to push them on the stack the next time through. NFL_PICKS_GLOBAL.previousParameters = getSelectedParameters(); updateTypeLink(); updatePlayersLink(); updateYearsLink(); updateWeeksLink(); updateTeamsLink(); updateStatNameLink(); //And we need to make sure we're showing the right "forward" and "back" links. updateNavigationLinksVisibility(); } /** * * This function will update the available options for the criteria based on what's selected. * It's here mainly for the situation where you select an option in a "selector" and that option * should cause options in other selectors to be either shown or hidden. * * I made it for the situation where somebody picks a year and we should only show the teams * that actually existed that year. Like, if somebody picks "2020" as the year, we shouldn't * show "OAK", but we should show "LV". * * ... And now it's here to handle the change in week for the 2021 season where a 17th game was added. * * It will farm the work out to other functions that handle the specific scenarios for each * kind of "selector". * * @returns */ function updateAvailableCriteriaOptions(){ updateAvailableTeamOptions(); updateAvailableWeekOptions(); //updateAvailableWeekOptions................. // //main_updateAvailableTeamOptions } /** * * This function will update the available teams that can be selected. It will just go through * and check whether each team was "active" during the selected years. If they were, then it'll * show them and if they weren't, it'll hide them. * * @returns */ function updateAvailableTeamOptions(){ //Steps to do: // 1. Get the year values as integers. // 2. Go through every team and get when it started and ended. // 3. If the year it started is after any of the selected years and it doesn't have an // end or its end is before one of the selected years, that means it played games during // the selected years so it should be shown. // 4. Otherwise, it didn't and so it should be hidden. var currentSelectedYearValues = getYearValuesForSelectedYears(); var integerYearValues = getValuesAsIntegers(currentSelectedYearValues); var teamsToShow = []; var teamsToHide = []; //All the teams are stored in the global variable. Just have to go through them. var teams = NFL_PICKS_GLOBAL.data.teams; for (var index = 0; index < teams.length; index++){ var team = teams[index]; //Flipping this switch off and I'll flip it on if the team's start and end years show //it played games in the selected years. var showTeam = false; //Make sure to turn their years into numbers. var teamStartYearInteger = parseInt(team.startYear); var teamEndYearInteger = -1; if (isDefined(team.endYear)){ teamEndYearInteger = parseInt(team.endYear); } //Go through each selected year. for (var yearIndex = 0; yearIndex < integerYearValues.length; yearIndex++){ var currentYearValue = integerYearValues[yearIndex]; //If the team started before the current year and either is still active (end year = -1) or was active after the //current year, that means it played games in the selected year, so it should be shown. if (teamStartYearInteger <= currentYearValue && (teamEndYearInteger == -1 || teamEndYearInteger >= currentYearValue)){ showTeam = true; } } //Just put it in the list based on whether it should be shown or not. if (showTeam){ teamsToShow.push(team.abbreviation); } else { teamsToHide.push(team.abbreviation); } } //Show the teams that should be shown in the selector dropdown. showTeamItems(teamsToShow); //Hide the teams that should be hidden in the selector. hideTeamItems(teamsToHide); //And, we have to go through and unselect the ones we should hide in case they //were selected. If we just hide them and they're still selected, they'll still //show up on the ui, just not in the selection dropdown. for (var index = 0; index < teamsToHide.length; index++){ var teamToHide = teamsToHide[index]; unselectTeamFull(teamToHide); } } //updateSelectors function getAvailableWeeksForYears(yearValues){ var integerYearValues = getValuesAsIntegers(currentSelectedYearValues); var availableWeeksBefore2021 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', 'wildcard', 'divisional', 'conference_championship', 'superbowl']; var availableWeeksAfter2021 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', 'wildcard', 'divisional', 'conference_championship', 'superbowl']; for (var index = 0; index < integerYearValues.length; index++){ var integerYearValue = integerYearValues[index]; if (integerYearValue >= 2021){ return availableWeeksAfter2021; } } return availableWeeksBefore2021; } function updateAvailableWeekOptions(){ var currentSelectedYearValues = getYearValuesForSelectedYears(); var weeksToShow = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', 'wildcard', 'divisional', 'conference_championship', 'superbowl']; var weeksToHide = ['18']; for (var index = 0; index < currentSelectedYearValues.length; index++){ var yearValue = currentSelectedYearValues[index]; if (yearValue >= 2021){ weeksToShow = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', 'wildcard', 'divisional', 'conference_championship', 'superbowl']; weeksToHide = []; } } showWeekItems(weeksToShow); hideWeekItems(weeksToHide); //And, we have to go through and unselect the ones we should hide in case they //were selected. If we just hide them and they're still selected, they'll still //show up on the ui, just not in the selection dropdown. for (var index = 0; index < weeksToHide.length; index++){ var weekToHide = weeksToHide[index]; unselectWeekFull(weekToHide); } } /** * * This function will update the selectors for the given type. It just calls * the specific type's update function. * * It will also update the multi-selects so that the selected values are updated * if they're selecting multiple "items" (multiple players, weeks, or years). * * @param type * @returns */ function updateSelectors(type){ //Steps to do: // 1. Call the function based on the type. // 2. Update the multi selects. if ('picks' == type){ updatePicksSelectors(type); } else if ('standings' == type){ updateStandingsSelectors(type); } else if ('stats' == type){ updateStatsSelectors(type); } } /** * * Updates the selectors so that they're good to go for when the type is picks. * * Shows: * year, player, team, week * Hides: * stat name * * Only shows or hides something if the given type isn't the previous selected type. * * @param type * @returns */ function updatePicksSelectors(type){ //Steps to do: // 1. If the previous type is the same as the given one, we don't need // to do anything to the selectors. // 2. Show and hide what we need to. // 3. Store the type we were given for next time. var previousSelectedType = getPreviousType(); if (previousSelectedType == type){ return; } showPlayersLink(); showWeeksLink(); showYearsLink(); showTeamsLink(); hideStatNameLink(); setPreviousType(type); } /** * * Updates the selectors so that they're right for browsing the "standings". * * Shows: * player, year, week, team * Hides: * stat name * * Only shows or hides something if the given type isn't the previous selected type. * * @param type * @returns */ function updateStandingsSelectors(type){ //Steps to do: // 1. If the previous type is the same as the given one, we don't need // to do anything to the selectors. // 2. Show and hide what we need to. // 3. Store the type we were given for next time. var previousSelectedType = getPreviousType(); if (previousSelectedType == type){ return; } showPlayersLink(); showWeeksLink(); showYearsLink(); showTeamsLink(); hideStatNameLink(); setPreviousType(type); } /** * * Updates the selectors so that they're good to go for browsing the * "stats" * * Shows: * stat name, others depending on the stat name * Hides: * depends on the stat name * * Stat name: * champions * shows: Nothing * hides: player, year, week, team * championship standings * shows: Nothing * hides: player, year, week, team * week standings * shows: player, year, week * hides: team * weeks won standings * shows: year * hides: player, team, week * weeks won by week * shows: year, week * hides: team * week records by player * shows: year, week, player * hides: team * pick accuracy * shows: year, player, team * hides: week * pick splits: * shows: year, week, team * hides: player * * @param type * @returns */ function updateStatsSelectors(type){ //Steps to do: // 1. We always want to show the stat name container. // 2. Get the name of the stat we want to show. // 3. Show and hide what we need to based on the kind of stat we want to show. // 4. Store the type we were given for next time. showStatNameLink(); var statName = getSelectedStatName(); if ('champions' == statName){ showPlayersLink(); showYearsLink(); hideWeeksLink(); hideTeamsLink(); } else if ('championshipStandings' == statName){ showPlayersLink(); showYearsLink(); hideWeeksLink(); hideTeamsLink(); } else if ('seasonStandings' == statName){ showPlayersLink(); showYearsLink(); showWeeksLink(); hideTeamsLink(); } else if ('weekStandings' == statName){ showPlayersLink(); showYearsLink(); showWeeksLink(); hideTeamsLink(); } else if ('weeksWonStandings' == statName){ showPlayersLink(); showYearsLink(); showWeeksLink(); hideTeamsLink(); } else if ('weeksWonByWeek' == statName){ showPlayersLink(); showYearsLink(); showWeeksLink(); hideTeamsLink(); } else if ('weekRecordsByPlayer' == statName){ showPlayersLink(); showYearsLink(); showWeeksLink(); hideTeamsLink(); } else if ('pickAccuracy' == statName){ showPlayersLink(); showYearsLink(); showWeeksLink(); showTeamsLink(); } else if ('pickSplits' == statName){ showPlayersLink(); showYearsLink(); showWeeksLink(); showTeamsLink(); } else if ('weekComparison' == statName){ showPlayersLink(); showYearsLink(); showWeeksLink(); hideTeamsLink(); } else if ('seasonProgression' == statName){ showPlayersLink(); showYearsLink(); showWeeksLink(); hideTeamsLink(); } setPreviousType(type); } /** * * Gets the selected value for the type. * * @returns */ function getSelectedType(){ return $('input[name=type]:checked').val(); } /** * * Sets the selected value for the type to the given type. Only does it * if the type select input has the given type as an option. * * @param type * @returns */ function setSelectedType(type){ $('input[name=type]').val([type]); NFL_PICKS_GLOBAL.selections.type = type; } /** * * Gets the previous type that was selected. This is so we can decide * whether to update stuff or not when the type changes. * * @returns */ function getPreviousType(){ return NFL_PICKS_GLOBAL.previousType; } /** * * Sets the previous type in the NFL_PICKS_GLOBAL variable. This is so we can decide * whether to update stuff or not when the type changes. * * @param newPreviousType * @returns */ function setPreviousType(newPreviousType){ NFL_PICKS_GLOBAL.previousType = newPreviousType; } /** * * This function will set the given players as being selected in the NFL_PICKS_GLOBAL * variable (NFL_PICKS_GLOBAL.selections.players) and it'll call the "selectPlayer" * function in the selectors file for each player so they get "selected" on the UI too. * * It expects the given players variable to either be... * 1. An array of player names. * 2. A comma separated string of player names. * 3. A single player name. * * It will put the actual player objects into the NFL_PICKS_GLOBAL variable for * each player name that's given. * * @param players * @returns */ function setSelectedPlayers(players){ //Steps to do: // 1. Check whether the players variable is an array. // 2. If it is, just keep it. // 3. Otherwise, it's a string so check to see if it has multiple values. // 4. If it does, then turn it into an array. // 5. Otherwise, just put it in there as a single value. // 6. Go through each player in the array, get the actual object for the player name // and put it in the global variable. And, "select" them in the ui. var playerValuesArray = []; var isArray = Array.isArray(players); if (isArray){ playerValuesArray = players; } else { var hasMultipleValues = doesValueHaveMultipleValues(players); if (hasMultipleValues){ playerValuesArray = delimitedValueToArray(players); } else { playerValuesArray.push(players); } } var playersArray = []; for (var index = 0; index < playerValuesArray.length; index++){ var value = playerValuesArray[index]; selectPlayer(value); var player = getPlayer(value); playersArray.push(player); } NFL_PICKS_GLOBAL.selections.players = playersArray; } /** * * This function will set the given years as being selected in the UI and in the * NFL_PICKS_GLOBAL variable (NFL_PICKS_GLOBAL.selections.years). * * It expects the given years variable to either be... * 1. An array of year values. * 2. A comma separated string of year values. * 3. A single year value. * * It will put the actual year objects into the NFL_PICKS_GLOBAL variable for * each year value that's given. * * @param years * @returns */ function setSelectedYears(years){ //Steps to do: // 1. Check whether the years variable is an array. // 2. If it is, just keep it. // 3. Otherwise, it's a string so check to see if it has multiple values. // 4. If it does, then turn it into an array. // 5. Otherwise, just put it in there as a single value. // 6. Go through each year in the array, get the actual object for the year // and put it in the global variable. And, "select" it in the ui. var yearValuesArray = []; var isArray = Array.isArray(years); if (isArray){ yearValuesArray = years; } else { var hasMultipleValues = doesValueHaveMultipleValues(years); if (hasMultipleValues){ yearValuesArray = delimitedValueToArray(years); } else { yearValuesArray.push(years); } } var yearsArray = []; for (var index = 0; index < yearValuesArray.length; index++){ var value = yearValuesArray[index]; selectYear(value); var year = getYear(value); yearsArray.push(year); } NFL_PICKS_GLOBAL.selections.years = yearsArray; } /** * * This function will set the given weeks as being selected in the UI and in the * NFL_PICKS_GLOBAL variable (NFL_PICKS_GLOBAL.selections.weeks). * * It expects the given weeks variable to either be... * 1. An array of week numbers. * 2. A comma separated string of week numbers. * 3. A single week number. * * It will put the actual week objects into the NFL_PICKS_GLOBAL variable for * each week number that's given. * * @param weeks * @returns */ function setSelectedWeeks(weeks){ //Steps to do: // 1. Check whether the weeks variable is an array. // 2. If it is, just keep it. // 3. Otherwise, it's a string so check to see if it has multiple values. // 4. If it does, then turn it into an array. // 5. Otherwise, just put it in there as a single value. // 6. Go through each week in the array, get the actual object for the week // and put it in the global variable. And, "select" it in the ui. var weekValuesArray = []; var isArray = Array.isArray(weeks); if (isArray){ weekValuesArray = weeks; } else { var hasMultipleValues = doesValueHaveMultipleValues(weeks); if (hasMultipleValues){ weekValuesArray = delimitedValueToArray(weeks); } else { weekValuesArray.push(weeks); } } var weeksArray = []; for (var index = 0; index < weekValuesArray.length; index++){ var value = weekValuesArray[index]; selectWeek(value); var week = getWeek(value); weeksArray.push(week); } //THIS was the key ... update the current week selections... geez this is too complicated setCurrentWeekSelections(weekValuesArray); NFL_PICKS_GLOBAL.selections.weeks = weeksArray; } /** * * This function will set the given teams as being selected in the UI and in the * NFL_PICKS_GLOBAL variable (NFL_PICKS_GLOBAL.selections.teams). * * It expects the given teams variable to either be... * 1. An array of team abbreviations. * 2. A comma separated string of team abbreviations. * 3. A single team abbreviation. * * It will put the actual team objects into the NFL_PICKS_GLOBAL variable for * each team abbreviation that's given. * * @param teams * @returns */ function setSelectedTeams(teams){ //Steps to do: // 1. Check whether the teams variable is an array. // 2. If it is, just keep it. // 3. Otherwise, it's a string so check to see if it has multiple values. // 4. If it does, then turn it into an array. // 5. Otherwise, just put it in there as a single value. // 6. Go through each team in the array, get the actual object for the team // and put it in the global variable. And, "select" it in the ui. var teamValuesArray = []; var isArray = Array.isArray(teams); if (isArray){ teamValuesArray = teams; } else { var hasMultipleValues = doesValueHaveMultipleValues(teams); if (hasMultipleValues){ teamValuesArray = delimitedValueToArray(teams); } else { teamValuesArray.push(teams); } } var teamsArray = []; for (var index = 0; index < teamValuesArray.length; index++){ var value = teamValuesArray[index]; selectTeam(value); var team = getTeam(value); teamsArray.push(team); } //THIS was the key ... update the current team selections... geez this is too complicated setCurrentTeamSelections(teamValuesArray); NFL_PICKS_GLOBAL.selections.teams = teamsArray; } /** * * Gets the selected stat name. * * @returns */ function getSelectedStatName(){ return $('input[name=statName]:checked').val(); } /** * * Sets the selected stat name if it's one of the options * on the stat name input. * * @param statName * @returns */ function setSelectedStatName(statName){ $('input[name=statName]').val([statName]); NFL_PICKS_GLOBAL.selections.statName = statName; } /** * * This function will set the given html as the content we show. It'll clear out what's * in there now. * * @param contentHtml * @returns */ function setContent(contentHtml){ $('#contentContainer').empty(); $('#contentContainer').append(contentHtml); } /** * * This function will go get the standings from the server and show them on the UI. * * What standings it gets depends on the player, year, and week that are selected. * * @returns */ function updateStandings(){ //Steps to do: // 1. Get the parameters to send (player, year, and week). // 2. Send them to the server. // 3. Update the UI with the results. var playerValuesForRequest = getPlayerValuesForRequest(); var yearValuesForRequest = getYearValuesForRequest(); var weekValuesForRequest = getWeekValuesForRequest(); var teamValuesForRequest = getTeamValuesForRequest(); setContent('<div style="text-align: center;">Loading...</div>'); $.ajax({url: 'nflpicks?target=standings&player=' + playerValuesForRequest + '&year=' + yearValuesForRequest + '&week=' + weekValuesForRequest + '&team=' + teamValuesForRequest, contentType: 'application/json; charset=UTF-8'} ) .done(function(data) { var standingsContainer = $.parseJSON(data); //We want to show the records that came back, but we're going to have to sort them //to make sure they're in the order we want. var records = standingsContainer.records; //We want the record with the most wins coming first. If they have the same number //of wins, we want the one with fewer losses coming first. //And if they're tied, we want them ordered by name. records.sort(function (record1, record2){ if (record1.wins > record2.wins){ return -1; } else if (record1.wins < record2.wins){ return 1; } else { if (record1.losses < record2.losses){ return -1; } else if (record1.losses > record2.losses){ return 1; } } if (record1.player.name < record2.player.name){ return -1; } else if (record1.player.name > record2.player.name){ return 1; } return 0; }); //Now that we have them sorted, we can create the html for the standings. var standingsHtml = createStandingsHtml(standingsContainer.records); //And set it as the content. setContent(standingsHtml); }) .fail(function() { setContent('<div style="text-align: center;">Error</div>'); }) .always(function() { }); } /** * * This function will update the picks grid with the current selectors they ... picked. * It'll get the parameters, go to the server to get the picks, and then update the UI * with the grid. * * @returns */ function updatePicks(){ //Steps to do: // 1. Get the parameters they picked. // 2. Default the year and week to the current year and week if we should. // 3. Go to the server and get the picks. // 4. Update the UI with the picks grid. var selectedYearValues = getSelectedYearValues(); var selectedWeekValues = getSelectedWeekValues(); //We need to make sure we only use "all" for the year if they explicitly set it. // //That should only happen if: // 1. It's "all" in the url. // 2. Or, they have seen the picks and have set it to "all" themselves. // //I'm doing it like this because using "all" for the year might bring back a lot //of picks, so we should only do it if that's what they want to do. var parameters = getUrlParameters(); var hasYearInUrl = false; if (isDefined(parameters) && isDefined(parameters.year)){ hasYearInUrl = true; } //We want to default it to the current year if: // // 1. It's "all" // 2. We haven't shown the picks before // 3. The "all" isn't from the url. // //In that situation, they didn't "explicitly" set it to "all", so we want to show //only picks for the current year to start off with. if (selectedYearValues.includes('all') && !NFL_PICKS_GLOBAL.havePicksBeenShown && !hasYearInUrl){ var currentYear = NFL_PICKS_GLOBAL.currentYear + ''; setSelectedYears(currentYear); updateYearsLink(); } //Do the same thing with the week. We only want to show picks for all the weeks if //they went out of their way to say that's what they wanted to do. var hasWeekInUrl = false; if (isDefined(parameters) && isDefined(parameters.week)){ hasWeekInUrl = true; } //If it's "all" and the picks haven't been shown and the "all" didn't come from the url, //it's their first time seeing the picks, so we should show the ones for the current week. if (selectedWeekValues.includes('all') && !NFL_PICKS_GLOBAL.havePicksBeenShown && !hasWeekInUrl){ var currentWeek = NFL_PICKS_GLOBAL.currentWeekKey + ''; setSelectedWeeks(currentWeek); updateWeeksLink(); } //At this point, we're going to show them the picks, so we should flip that switch. NFL_PICKS_GLOBAL.havePicksBeenShown = true; var playerValuesForRequest = getPlayerValuesForRequest(); var yearValuesForRequest = getYearValuesForRequest(); var weekValuesForRequest = getWeekValuesForRequest(); var teamValuesForRequest = getTeamValuesForRequest(); setContent('<div style="text-align: center;">Loading...</div>'); //Go to the server and get the grid. $.ajax({url: 'nflpicks?target=compactPicksGrid&player=' + playerValuesForRequest + '&year=' + yearValuesForRequest + '&week=' + weekValuesForRequest + '&team=' + teamValuesForRequest, contentType: 'application/json; charset=UTF-8'} ) .done(function(data) { //Update the UI with what the server sent back. var picksGrid = $.parseJSON(data); var picksGridHtml = createPicksGridHtml(picksGrid); setContent(picksGridHtml); }) .fail(function() { setContent('<div style="text-align: center;">Error</div>'); }) .always(function() { }); } /** * * This function will get the stats from the server and update them on the ui. The stat that * it shows depends on the statName they picked. * * @returns */ function updateStats(){ //Steps to do: // 1. Get the selected parameters. // 2. Make sure they're ok based on the stat name. // 3. Go to the server and get the stats. // 4. Update the UI with what came back. var statName = getSelectedStatName(); var selectedPlayerValues = getPlayerValuesForRequest(); var selectedYearValues = getYearValuesForRequest(); var selectedWeekValues = getWeekValuesForRequest(); var selectedTeamValues = getTeamValuesForRequest(); //If the stat name is the "pick splits", we want to do the same thing we do with the picks grid. //Only show "all" for the year or the week if they actually set it to "all". //If it's the first time we're showing the pick splits, we only want to show all of them if that //was in the url. if (statName == 'pickSplits'){ //Since we're showing how players are split up, we want to show all players. var selectedYearValues = getSelectedYearValues(); var selectedWeekValues = getSelectedWeekValues(); var urlParameters = getUrlParameters(); //Same deal as with the picks grid... var hasYearInUrl = false; if (isDefined(urlParameters) && isDefined(urlParameters.year)){ hasYearInUrl = true; } //If the year is "all", we haven't shown the picks, and "all" didn't come from the url, then we //want the year we show the pick splits for to be the current year. if (selectedYearValues.includes('all') && !NFL_PICKS_GLOBAL.havePickSplitsBeenShown && !hasYearInUrl){ var currentYear = NFL_PICKS_GLOBAL.currentYear + ''; setSelectedYears(currentYear); updateYearsLink(); } //Same deal as with the year and with the picks grid... var hasWeekInUrl = false; if (isDefined(urlParameters) && isDefined(urlParameters.week)){ hasWeekInUrl = true; } //If the week is "all", we haven't shown the picks, and "all" didn't come from the url, then we //want the week we show the pick splits for to be the current week. if (selectedWeekValues.includes('all') && !NFL_PICKS_GLOBAL.havePickSplitsBeenShown && !hasWeekInUrl){ var currentWeek = NFL_PICKS_GLOBAL.currentWeekKey + ''; setSelectedWeeks(currentWeek); updateWeeksLink(); } //And, since we're here, that means we've shown the pick splits to the user, so the next time, we won't //do the funny business with the week and year. NFL_PICKS_GLOBAL.havePickSplitsBeenShown = true; } var playerValuesForRequest = getPlayerValuesForRequest(); var yearValuesForRequest = getYearValuesForRequest(); var weekValuesForRequest = getWeekValuesForRequest(); var teamValuesForRequest = getTeamValuesForRequest(); setContent('<div style="text-align: center;">Loading...</div>'); //Send the request to the server. $.ajax({url: 'nflpicks?target=stats&statName=' + statName + '&player=' + playerValuesForRequest + '&year=' + yearValuesForRequest + '&week=' + weekValuesForRequest + '&team=' + teamValuesForRequest, contentType: 'application/json; charset=UTF-8'} ) .done(function(data) { var statsHtml = ''; //Make the html for the kind of stat they wanted to see. if ('champions' == statName){ var championships = $.parseJSON(data); statsHtml = createChampionsHtml(championships); } else if ('championshipStandings' == statName){ var championships = $.parseJSON(data); statsHtml = createChampionshipStandingsHtml(championships); } else if ('seasonStandings' == statName){ var seasonRecords = $.parseJSON(data); statsHtml = createSeasonStandingsHtml(seasonRecords); } else if ('weeksWonStandings' == statName){ var weekRecords = $.parseJSON(data); //We want to sort the records before we show them so we can show the rank. sortWeekRecords(weekRecords); statsHtml = createWeeksWonHtml(weekRecords); } else if ('weeksWonByWeek' == statName){ var weeksWonByWeek = $.parseJSON(data); statsHtml = createWeeksWonByWeek(weeksWonByWeek); } else if ('weekRecordsByPlayer' == statName){ var weekRecords = $.parseJSON(data); //Like with the other records, we want to sort them before we show them. sortWeekRecordsBySeasonWeekAndRecord(weekRecords); statsHtml = createWeekRecordsByPlayerHtml(weekRecords); } else if ('weekStandings' == statName){ var playerWeekRecords = $.parseJSON(data); statsHtml = createWeekStandingsHtml(playerWeekRecords); } else if ('pickAccuracy' == statName){ var start = Date.now(); var pickAccuracySummaries = $.parseJSON(data); var jsonElapsed = Date.now() - start; var htmlStart = Date.now(); statsHtml = createPickAccuracySummariesHtml(pickAccuracySummaries); var htmlElapsed = Date.now() - htmlStart; } else if ('pickSplits' == statName){ var pickSplits = $.parseJSON(data); statsHtml = createPickSplitsGridHtml(pickSplits); } else if ('weekComparison' == statName){ var weekRecords = $.parseJSON(data); //Like with the other records, we want to sort them before we show them. sortWeekRecordsBySeasonWeekAndRecord(weekRecords); statsHtml = createWeekComparisonHtml(weekRecords); } else if ('seasonProgression' == statName){ var weekRecords = $.parseJSON(data); //Like with the other records, we want to sort them before we show them. sortWeekRecordsBySeasonWeekAndRecord(weekRecords); statsHtml = createSeasonProgressionHtml(weekRecords); } setContent(statsHtml); }) .fail(function() { setContent('<div style="text-align: center;">Error</div>'); }) .always(function() { }); } /** * * A "convenience" function that says whether any record in the given * array has any ties. * * @param records * @returns */ function hasTies(records){ //Steps to do: // 1. Go through all the records and return true if one has a tie. if (!isDefined(records)){ return false; } for (var index = 0; index < records.length; index++){ var record = records[index]; if (record.ties > 0){ return true; } } return false; } /** * * This function will compare the given records and return -1 if the first record * has more wins than the second, 1 if it has more, and 0 if it's the same. * * If the records have the same number of wins, then it bases the comparison on the * losses. If record1 has the same wins but fewer losses, it should go first, so it * returns -1. * * It'll return 0 if they have the exact same number of wins and losses. * * We do this in a few different places, so I decided to make a function. * * @param record1 * @param record2 * @returns */ function recordWinComparisonFunction(record1, record2){ //Steps to do: // 1. Compare based on the wins first. // 2. If they're the same, compare on the losses. //More wins should go first. if (record1.wins > record2.wins){ return -1; } //Fewer wins should go last. else if (record1.wins < record2.wins){ return 1; } else { //With the same number of wins, fewer losses should go first. if (record1.losses < record2.losses){ return -1; } //And more losses should go second. else if (record1.losses > record2.losses){ return 1; } } //Same wins and losses = same record. return 0; } /** * * When somebody clicks the "body" of the page, we want it to hide everything, so * that's what this function will do. It just goes through and calls the function * that hides the selectors. It also resets them too. * * @returns */ function onClickBody(){ hideTypeSelector(); resetAndHidePlayerSelections(); resetAndHideYearSelections(); resetAndHideWeekSelections(); hideStatNameSelector(); } /** * * A convenience function for hiding all the selector containers. Not much * to it. * * @returns */ function hideSelectorContainers(){ hideTypeSelector(); hidePlayerSelector(); hideYearSelector(); hideWeekSelector(); hideStatNameSelector(); hideTeamSelector(); } /** * * This function switches the element with the given id from visibile to * hidden or back (with the jquery "hide" and "show" functions). * * It decides whether something is visible by using the ":visible" property * in jquery. If it's visible, it hides it. Otherwise, it shows it. * * @param id * @returns */ function toggleVisibilty(id){ //Steps to do: // 1. Get whether the element is visible. // 2. Hide it if it is and show it if it's not. var isElementVisible = isVisible(id); if (isVisible){ $('#' + id).hide(); } else { $('#' + id).show(); } } /** * * A really dumb function for checking whether an element with the given * id is visible or not. Just calls jquery to do the work. * * @param id * @returns */ function isVisible(id){ var isElementVisible = $('#' + id).is(':visible'); return isElementVisible; } /** * * This function will toggle the visibility the weeks for the given week records * at the given index. If they're shown, it'll hide them. If they're hidden, * it'll show them. It's specific to the "weeks won" stat thing for now. * * @param index * @returns */ function toggleShowWeeks(index){ //Steps to do: // 1. Get whether the week records are shown now. // 2. If they are, then hide them and change the link text. // 3. Otherwise, show them and change the link text. var isVisible = $('#week-records-' + index).is(':visible'); if (isVisible){ $('#week-records-' + index).hide(); $('#show-weeks-link-' + index).text('show weeks'); } else { $('#week-records-' + index).show(); $('#show-weeks-link-' + index).text('hide weeks'); } } /** * * This function will get the number rank of the given object in the given list. * It will use the given comparison function to compare the object with other objects * in the given list to decide where it fits, and it'll use the given "sameObjectFunction" * to make sure an object doesn't "tie with itself". * * I made it because I wanted to do it in a few places (the original standings, weeks won standings, * and a few other places). * * The given list <i>doesn't</i> need to be sorted in order for it to find the object's * rank. * * It'll return an object that's like: {rank: 12, tie: true}, so people can get the * numeric rank and whether it ties any other object in the list. * * Doing it this way, you'll have to call it for every object in the list ... This function * is O(n), so that makes ranking every object in a list O(n^2). That kind of sucks, * but it should be ok because we shouldn't be sorting hundreds or thousands of objects. * I felt like it was ok to give up some speed to have it so each of the "standings" * functions not have to duplicate the ranking code. * * @param object * @param list * @param comparisonFunction * @param sameObjectFunction * @returns */ function rank(object, list, comparisonFunction, sameObjectFunction){ //Steps to do: // 1. Create the initial "rank" for the object and assume it has the highest rank. // 2. Go through each object in the list and run the comparison object on it. // 3. If it returns a positive number, that means the object is after the current // one we're comparing it to, so we need to up the rank. // 4. If it says they're the same, and the object hasn't already tied another object, // then use the "sameObjectFunction" to see whether they're the exact same object or not. // 5. If they aren't, then it's a real tie. If they aren't, then it's not. var objectRank = {rank: 1, tie: false}; var numberOfRecordsBetter = 0; var tie = false; for (var index = 0; index < list.length; index++){ var currentObject = list[index]; var comparisonResult = comparisonFunction(object, currentObject); if (comparisonResult > 0){ objectRank.rank++; } else if (comparisonResult == 0){ if (objectRank.tie == false){ var isSameObject = sameObjectFunction(object, currentObject); if (!isSameObject){ objectRank.tie = true; } } } } return objectRank; } /** * * A convenience function that'll sort the given weekRecords array * by each weekRecord's length. A "weekRecord" will have a list * of records for each week inside it. This will sort it so that * the one with the most weeks comes first. * * This is for when we're ranking how many weeks a person has won and * we want the person who's won the most weeks (has the most records) * first. * * @param weekRecords * @returns */ function sortWeekRecords(weekRecords){ //Steps to do: // 1. Just run the sorting function on the records we were given. weekRecords.sort(function (weekRecord1, weekRecord2){ if (weekRecord1.weekRecords.length > weekRecord2.weekRecords.length){ return -1; } else if (weekRecord1.weekRecords.length < weekRecord2.weekRecords.length){ return 1; } //Sort it alphabetically by name if they have the same record. if (weekRecord1.player.name < weekRecord2.player.name){ return -1; } else if (weekRecord1.player.name > weekRecord2.player.name){ return 1; } return 0; }); } /** * * This function will sort the given week records by season and week * so that the "oldest" records appear first. It's here for when we're showing * how many weeks a person one and we want to show the weeks in chronological * order. This function will make sure they're in chronological order. * * @param weekRecords * @returns */ function sortWeekRecordsBySeasonAndWeek(weekRecords){ //Steps to do: // 1. Just run the sorting function on the array // we were given. weekRecords.sort(function (weekRecord1, weekRecord2){ var year1 = parseInt(weekRecord1.season.year); var year2 = parseInt(weekRecord2.season.year); //If the year from one is before the other, we want the earlier one first. if (year1 < year2){ return -1; } //And later one second. else if (year1 > year2){ return 1; } else { //Otherwise, compare on the weeks. var week1 = weekRecord1.week.weekSequenceNumber; var week2 = weekRecord2.week.weekSequenceNumber; //With the earlier week first. if (week1 < week2){ return -1; } else if (week1 > week2){ return 1; } } return 0; }); } /** * * This function will sort the given array of "week records" so that it * goes in ascending order by the week's year and week (so it's in increasing * order by season and by week within each season). * * @param weekRecords * @returns */ function sortWeekRecordsBySeasonWeekAndRecord(weekRecords){ //Steps to do: // 1. Just run the sorting function on the array // we were given. weekRecords.sort(function (weekRecord1, weekRecord2){ var year1 = parseInt(weekRecord1.season.year); var year2 = parseInt(weekRecord2.season.year); //If the year from one is before the other, we want the earlier one first. if (year1 < year2){ return -1; } //And later one second. else if (year1 > year2){ return 1; } //If it's the same year... else { //Compare on the weeks. var week1 = weekRecord1.week.weekSequenceNumber; var week2 = weekRecord2.week.weekSequenceNumber; //With the earlier week first. if (week1 < week2){ return -1; } else if (week1 > week2){ return 1; } //same week, so sort by the record. else { if (weekRecord1.record.wins > weekRecord2.record.wins){ return -1; } else if (weekRecord1.record.wins < weekRecord2.record.wins){ return 1; } else { if (weekRecord1.record.losses < weekRecord2.record.losses){ return -1; } else if (weekRecord1.record.losses > weekRecord2.record.losses){ return 1; } //Same year, week, wins, and losses, sort by the name else { if (weekRecord1.player.name < weekRecord2.player.name){ return -1; } else if (weekRecord1.player.name > weekRecord2.player.name){ return 1; } } } } } return 0; }); } /** * * This function will say whether a "specific" year was selected * (basically if the year isn't "all" or one of the special ones). * * This should go in the selectors javascript file i think. * * @returns */ function isSpecificYearSelected(){ var selectedYears = getSelectedYears(); if (selectedYears.length > 1){ return false; } var selectedYear = selectedYears[0].value; if ('all' == selectedYear || 'jurassic-period' == selectedYear || 'first-year' == selectedYear || 'modern-era' == selectedYear){ return false; } return true; } /** * * This function will say whether a "specific" team was selected * (basically if the team isn't "all"). * * @returns */ function isSpecificTeamSelected(){ var selectedTeams = getSelectedTeams(); if (selectedTeams.length > 1){ return false; } var selectedTeam = selectedTeams[0].value; if ('all' == selectedTeam){ return false; } return true; } /** * * A convenience function for checking whether a single week is selected or not. * * It'll return false if: * 1. There are no selected weeks. * 2. There's more than one selected week. * 3. There's one selected week, but it's the regular season, playoffs, or all. * * If all of those 3 things are false, it'll return true because that means there's a single * week selected and it's not one of the ones that represents multiple weeks. * * @returns */ function isASingleWeekSelected(){ var selectedWeeks = getSelectedWeekValues(); if (isEmpty(selectedWeeks)){ return false; } if (selectedWeeks.length > 1){ return false; } var selectedWeek = selectedWeeks[0]; if ('all' == selectedWeek || 'regular_season' == selectedWeek || 'playoffs' == selectedWeek){ return false; } return true; } /** * * This function will say whether a "specific" week was selected. * If the week is all, "regular-season", or "playoffs", then it takes * that to mean a specific one isn't and a "range" is instead. * * @returns */ function isSpecificWeekSelected(){ var selectedWeeks = getSelectedWeeks(); if (isEmpty(selectedWeeks)){ return false; } var selectedWeek = selectedWeeks[0].value; if ('all' == selectedWeek || 'regular_season' == selectedWeek || 'playoffs' == selectedWeek){ return false; } return true; } /** * * A convenience function for checking whether a single player is selected or not. * It'll return false if the current selected player is "all" or if it has multiple * values. Otherwise, it'll return true. * * @returns */ function isASinglePlayerSelected(){ var selectedPlayer = getSelectedPlayer(); if ('all' == selectedPlayer || doesValueHaveMultipleValues(selectedPlayer)){ return false; } return true; } /** * * This function will say whether a specific player is selected. If the * current selected player is "all", it'll say there isn't. Otherwise, it'll * say there is. * * @returns */ function isSpecificPlayerSelected(){ var selectedPlayers = getSelectedPlayers(); if (selectedPlayers.length > 1){ return false; } var selectedPlayer = selectedPlayers[0].value; if ('all' == selectedPlayer){ return false; } return true; } /** * * This function will get the winning percentage. Here because we almost always want * it formatted the same way, so I figured it was better to do it in a function. * * @param wins * @param losses * @returns */ function getWinningPercentage(wins, losses){ //Steps to do: // 1. Get the actual percentage. // 2. Make it 3 decimal places if it's a real number and blank if it's not. var percentage = wins / (wins + losses); var percentageString = ''; if (!isNaN(percentage)){ percentageString = percentage.toPrecision(3); } return percentageString; } /** * * A convenience function for sorting players by their name. Here in case * we do it in multiple places. * * @param players * @returns */ function sortPlayersByName(players){ //Steps to do: // 1. Just compare each player by its name. players.sort(function (player1, player2){ if (player1.name < player2.name){ return -1; } else if (player1.name > player2.name){ return 1; } return 0; }); } /** * * Here for when we're sorting something alphabetically and we don't * care what kind of string it is. * * @param values * @returns */ function sortAlphabetically(values){ values.sort(function (value1, value2){ if (value1 < value2){ return -1; } else if (value1 > value2){ return 1; } return 0; }); } /** * * Here so we can make sure the pick accuracies are in the right order (with the most * accurate team coming first). * * @param pickAccuracySummaries * @returns */ function sortPickAccuracySummariesByTimesRight(pickAccuracySummaries){ //Steps to do: // 1. Just sort them by how many times the person was right picking a team. pickAccuracySummaries.sort(function (pickAccuracySummaryA, pickAccuracySummaryB){ //More times right = front of the list. if (pickAccuracySummaryA.timesRight > pickAccuracySummaryB.timesRight){ return -1; } //Fewer times right = back of the list. else if (pickAccuracySummaryA.timesRight < pickAccuracySummaryB.timesRight){ return 1; } //If they have the same times right, sort on times wrong. if (pickAccuracySummaryA.timesWrong < pickAccuracySummaryB.timesWrong){ return -1; } //Fewer times right = back of the list. else if (pickAccuracySummaryA.timesWrong > pickAccuracySummaryB.timesWrong){ return 1; } //If they have the same times right and wrong, sort by player name. if (pickAccuracySummaryA.player.name < pickAccuracySummaryB.player.name){ return -1; } else if (pickAccuracySummaryA.player.name > pickAccuracySummaryB.player.name){ return 1; } //If they have the same player name, sort by team abbreviation. if (pickAccuracySummaryA.team.abbreviation < pickAccuracySummaryB.team.abbreviation){ return -1; } else if (pickAccuracySummaryA.team.abbreviation > pickAccuracySummaryB.team.abbreviation){ return 1; } return 0; }); } /** * * Shows or hides the details for pick accuracy. If it's currently shown, it'll hide * it and if it's currently hidden, it'll show it. * * @param index * @returns */ function toggleShowPickAccuracyDetails(index){ //Steps to do: // 1. Get whether the container at the index is shown. // 2. Hide it if it is, show it if it's not. var isVisible = $('#pick-accuracy-details-' + index).is(':visible'); if (isVisible){ $('#pick-accuracy-details-' + index).hide(); $('#pick-accuracy-details-link-' + index).text('Details'); } else { $('#pick-accuracy-details-' + index).show(); $('#pick-accuracy-details-link-' + index).text('Hide'); } } /** * * This function will create a link that'll take them to the picks for the given * year, week, team, and player (all optional) and show the given text. Here because * we wanted to do this in a few places, so I figured it was best to do it as a function. * * @param linkText * @param year * @param week * @param team * @param player * @returns */ function createPicksLink(linkText, year, week, team, player){ //Steps to do: // 1. Just make a link that'll call the javascript function // that actually updates the view. // 2. All the arguments are optional, so only add them in if // they're given. var picksLink = '<a href="javascript:" onClick="showPickView('; if (isDefined(year)){ var yearValue = year; if (Array.isArray(year)){ yearValue = arrayToDelimitedValue(year, ','); } picksLink = picksLink + '\'' + yearValue + '\', '; } else { picksLink = picksLink + 'null, '; } if (isDefined(week)){ var weekValue = week; if (Array.isArray(week)){ weekValue = arrayToDelimitedValue(week, ','); } picksLink = picksLink + '\'' + weekValue + '\', '; } else { picksLink = picksLink + 'null, '; } if (isDefined(team)){ var teamValue = team; if (Array.isArray(team)){ teamValue = arrayToDelimitedValue(team, ','); } picksLink = picksLink + '\'' + teamValue + '\', '; } else { picksLink = picksLink + 'null, '; } if (isDefined(player)){ var playerValue = player; if (Array.isArray(player)){ playerValue = arrayToDelimitedValue(player, ','); } picksLink = picksLink + '\'' + playerValue + '\''; } else { picksLink = picksLink + 'null'; } picksLink = picksLink + ');">' + linkText + '</a>'; return picksLink; } /** * * This function will show the picks grid for the given year, week, team, and player. * All the arguments are optional. It will just set each one as the selected * year, week, team, and player (if it's given) and then cause the picks to be shown. * * It'll flip the global "havePicksBeenShown" switch to true so that the view shows * all the picks for the given parameters and doesn't try to overrule it and only show * a week's worth of picks. * * @param year * @param week * @param team * @param player * @returns */ function showPickView(year, week, team, player){ //Steps to do: // 1. If we're coming from this function, then we don't want // the updatePicks function saying "no, you can't see all the picks", // so we need to flip the switch that disables that feature. // 2. Set all the parameters that were given. // 3. Call the function that'll show them on the screen. //If this switch is true, we'll show the picks for the parameters no matter //whether it's a week's worth or not. If it's not, it'll show only a week's //worth as a way to prevent accidentally showing all the picks (which takes a while to do). NFL_PICKS_GLOBAL.havePicksBeenShown = true; setSelectedType('picks'); if (isDefined(year)){ setSelectedYears(year); } if (isDefined(week)){ setSelectedWeeks(week); } if (isDefined(player)){ setSelectedPlayers(player); } if (isDefined(team)){ selectSingleTeamFull(team); } updateView(); } /** * * This function will shorten the given label so it's easier * to show on phones and stuff with small widths. Up yours, twitter * and bootstrap. * * @param label * @returns */ function shortenWeekLabel(label){ if ('Playoffs - Wild Card' == label){ return 'Wild card'; } else if ('Playoffs - Divisional' == label){ return 'Divisional'; } else if ('Playoffs - Conference Championship' == label || 'Conference Championship' == label){ return 'Conf champ'; } else if ('Playoffs - Super Bowl' == label){ return 'Super bowl'; } return label; } /** * * This function will check whether the given value has multiple values * in it or not. Basically, it'll return true if the given value is defined * and it has a comma in it. It assumes the given value is a string and multiple * values are separated by commas in that string. * * @param value * @returns */ function doesValueHaveMultipleValues(value){ if (isDefined(value) && value.indexOf(',') != -1){ return true; } return false; } function showYearContainer(){ $('#yearContainer').show(); } function hideYearContainer(){ $('#yearContainer').hide(); } function showPlayerContainer(){ $('#playerContainer').show(); } function hidePlayerContainer(){ $('#playerContainer').hide(); } function showWeekContainer(){ $('#weekContainer').show(); } function hideWeekContainer(){ $('#weekContainer').hide(); } function showTeamContainer(){ $('#teamContainer').show(); } function hideTeamContainer(){ $('#teamContainer').hide(); } function showStatNameContainer(){ $('#statNameContainer').show(); } function hideStatNameContainer(){ $('#statNameContainer').hide(); }
hhhayssh/nflpicks
src/main/webapp/javascript/nflpicks.js
JavaScript
unlicense
78,271
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PaperMarioBattleSystem.Extensions; namespace PaperMarioBattleSystem { /// <summary> /// The Timing Tutor Badge - teaches the timing of Stylish Moves by showing a "!" above the character's head when they should press A. /// </summary> public sealed class TimingTutorBadge : Badge { public TimingTutorBadge() { Name = "Timing Tutor"; Description = "Learn the timing for Stylish commands."; BPCost = 1; PriceValue = 120; BadgeType = BadgeGlobals.BadgeTypes.TimingTutor; AffectedType = BadgeGlobals.AffectedTypes.Both; } protected override void OnEquip() { //Flag that this BattleEntity should have Stylish Move timings shown EntityEquipped.AddIntAdditionalProperty(Enumerations.AdditionalProperty.ShowStylishTimings, 1); } protected override void OnUnequip() { //Remove the flag that Stylish Move timings should be shown EntityEquipped.SubtractIntAdditionalProperty(Enumerations.AdditionalProperty.ShowStylishTimings, 1); } } }
tdeeb/PaperMarioBattleSystem
PaperMarioBattleSystem/PaperMarioBattleSystem/Classes/Collectibles/Badges/TimingTutorBadge.cs
C#
unlicense
1,310
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Brand' db.create_table(u'automotive_brand', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('name', self.gf('django.db.models.fields.CharField')(max_length=64)), ('slug', self.gf('autoslug.fields.AutoSlugField')(unique_with=(), max_length=50, populate_from='name')), )) db.send_create_signal(u'automotive', ['Brand']) # Adding model 'Model' db.create_table(u'automotive_model', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('brand', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['automotive.Brand'])), ('name', self.gf('django.db.models.fields.CharField')(max_length=64)), ('full_name', self.gf('django.db.models.fields.CharField')(max_length=256, blank=True)), ('year', self.gf('django.db.models.fields.PositiveSmallIntegerField')(null=True, blank=True)), )) db.send_create_signal(u'automotive', ['Model']) def backwards(self, orm): # Deleting model 'Brand' db.delete_table(u'automotive_brand') # Deleting model 'Model' db.delete_table(u'automotive_model') models = { u'automotive.brand': { 'Meta': {'object_name': 'Brand'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'slug': ('autoslug.fields.AutoSlugField', [], {'unique_with': '()', 'max_length': '50', 'populate_from': "'name'"}) }, u'automotive.model': { 'Meta': {'object_name': 'Model'}, 'brand': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['automotive.Brand']"}), 'full_name': ('django.db.models.fields.CharField', [], {'max_length': '256', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '64'}), 'year': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}) } } complete_apps = ['automotive']
mscam/django-automotive
automotive/south_migrations/0001_initial.py
Python
unlicense
2,513
<?php namespace MattyG\Http; class Response { /** * @var int */ protected $responseCode; /** * @var array */ protected $headers; /** * @var array */ protected $rawHeaders; /** * @var bool */ protected $headersSent; /** * @var string */ protected $body; public function __construct() { $this->responseCode = 200; $this->headers = array(); $this->rawHeaders = array(); $this->headersSent = false; $this->body = ""; } /** * @param int $code * @return Response */ public function setResponseCode($code) { $this->responseCode = $code; return $this; } /** * @return int */ public function getResponseCode() { return $this->responseCode; } /** * @return void */ public function sendResponseCode() { http_response_code($this->responseCode); } /** * @param array $rawHeaders * @return Response */ public function setRawHeaders(array $rawHeaders = array()) { $this->rawHeaders = $rawHeaders; return $this; } /** * @param string $rawHeader * @return Response */ public function addRawHeader($rawHeader) { $this->rawHeaders[] = $rawHeader; return $this; } /** * @return array */ public function getRawHeaders() { return $this->rawHeaders; } /** * @param array $headers * @return Response */ public function setHeaders(array $headers = array()) { $this->headers = $headers; return $this; } /** * @param string $header * @param string $value * @return Response */ public function addHeader($header, $value) { $this->headers[] = $header; return $this; } /** * @return array */ public function getHeaders() { return $this->headers; } /** * @param string $header * @return Response|bool */ public function unsetHeader($header) { if (isset($this->headers[$header])) { unset($this->headers[$header]); return $this; } else { return false; } } /** * @return void */ public function sendHeaders() { if ($this->headersSent === true) { return; } foreach ($this->rawHeaders as $rawHeader) { header($rawHeader); } foreach ($this->headers as $header => $value) { header($header . ": " . $value); } $this->headersSent = true; } /** * @param string $body * @return Response */ public function setBody($body) { $this->body = $body; return $this; } /** * @return string */ public function getBody() { return $this->body; } /** * @return void */ public function sendBody() { $body = $this->getBody(); echo $body; } /** * @return void */ public function sendResponse() { $this->sendHeaders(); $this->sendResponseCode(); $this->sendBody(); } }
djmattyg007/MattyG.Http
src/Response.php
PHP
unlicense
3,333
<?php //Database.php //require_once('config.php'); //Might add config file to pull this in from later class Database { protected static $connection; private function dbConnect() { $databaseName = 'lockeythings'; $serverName = 'localhost'; $databaseUser = 'lockey'; $databasePassword = 'bobisyouruncle'; $databasePort = '3306'; // Not actual details! Placeholders! Leave my DB alone! :) self::$connection = mysqli_connect ($serverName, $databaseUser, $databasePassword, 'lockeythings'); // mysqli_set_charset('utf-8',self::$connection); if (self::$connection) { if (!mysqli_select_db (self::$connection, $databaseName)) { echo("DB Not Found"); throw new Exception('DB Not found'); } } else { echo("No DB connection"); throw new Exception('No DB Connection'); } return self::$connection; } public function query($query) { // Connect to the database $connection = $this -> dbConnect(); // Query the database $result = mysqli_query($connection, $query); return $result; } public function select($query) { $rows = array(); $result = $this -> query($query); if($result === false) { return false; } while ($row = $result -> fetch_assoc()) { $rows[] = $row; } // echo("should have worked"); return $rows; } } ?>
drenzul/lockeythings
public_html/helperclasses/database.php
PHP
unlicense
1,755
<?php function getAssets($statName,$userID) { include 'connect.php'; $conn = mysql_connect($dbhost,$dbuser,$dbpass) or die ('Error connecting to mysql:'); mysql_select_db($dbname); createIfNotExists($statName,$userID); $query = sprintf("SELECT value FROM h_user_assets WHERE assets_id = (SELECT id FROM h_assets WHERE name = '%s' OR short_name = '%s') AND user_id = '%s'", mysql_real_escape_string($statName), mysql_real_escape_string($statName), mysql_real_escape_string($userID)); $result = mysql_query($query); list($value) = mysql_fetch_row($result); return $value; } function setAssets($statName,$userID,$quantity) { include 'connect.php'; $conn = mysql_connect($dbhost,$dbuser,$dbpass) or die ('Error connecting to mysql'); mysql_select_db($dbname); createIfNotExists($statName,$userID); $query = sprintf("UPDATE h_user_assets SET quantity = '%s' WHERE assets_id = (SELECT id FROM h_assets WHERE name = '%s' OR short_name = '%s') AND user_id = '%s'", mysql_real_escape_string($quantity), mysql_real_escape_string($statName), mysql_real_escape_string($statName), mysql_real_escape_string($userID)); $result = mysql_query($query); } function createIfNotExists($statName,$userID) { include 'connect.php'; $conn = mysql_connect($dbhost,$dbuser,$dbpass) or die ('Error connecting to mysql:'); mysql_select_db($dbname); $query = sprintf("SELECT count(quantity) FROM h_user_assets WHERE stat_id = (SELECT id FROM h_assets WHERE name = '%s' OR short_name = '%s') AND user_id = '%s'", mysql_real_escape_string($statName), mysql_real_escape_string($statName), mysql_real_escape_string($userID)); $result = mysql_query($query); list($count) = mysql_fetch_row($result); if($count == 0) { // the stat doesn't exist; insert it into the database $query = sprintf("INSERT INTO h_user_stats(assets_id,user_id,quantity) VALUES ((SELECT id FROM h_assets WHERE name = '%s' OR short_name = '%s'),'%s','%s')", mysql_real_escape_string($statName), mysql_real_escape_string($statName), mysql_real_escape_string($userID), '0'); mysql_query($query); } } ?>
dvelle/The-hustle-game-on-facebook-c.2010
hustle/hustle/test/estate.php
PHP
unlicense
2,104
import React from 'react'; import Moment from 'moment'; import { Embed, Grid } from 'semantic-ui-react'; const VideoDetail = ({video}) => { if (!video){ return <div>Loading...</div>; } const videoId = video.id.videoId; const url = `https://www.youtube.com/embed/${videoId}`; const pubTime = Moment(video.snippet.publishedAt).format('DD-MM-YYYY, h:mm:ss a') return ( <Grid.Row stretched> <Grid.Column > <Embed active autoplay={false} brandedUI={false} id={videoId} placeholder='http://semantic-ui.com/images/image-16by9.png' src={url} source='youtube'/> <div className="details"> <h5 className="meta-big-title">{video.snippet.title}</h5> <div className="meta-description">{video.snippet.description}</div> <div className="meta-time">Published: {pubTime}</div> </div> </Grid.Column> </Grid.Row> ); }; export default VideoDetail;
suemcnab/react-youtube-pxn-open
src/components/video_detail.js
JavaScript
unlicense
891
class MyClass: '''This is the docstring for this class''' def __init__(self): # setup per-instance variables self.x = 1 self.y = 2 self.z = 3 class MySecondClass: '''This is the docstring for this second class''' def __init__(self): # setup per-instance variables self.p = 1 self.d = 2 self.q = 3
dagostinelli/python-package-boilerplate
packagename/somemodule.py
Python
unlicense
382
#%matplotlib inline # All the imports from __future__ import print_function, division from math import * import random import sys import matplotlib.pyplot as plt # TODO 1: Enter your unity ID here __author__ = "magoff2" class O: """ Basic Class which - Helps dynamic updates - Pretty Prints """ def __init__(self, **kwargs): self.has().update(**kwargs) def has(self): return self.__dict__ def update(self, **kwargs): self.has().update(kwargs) return self def __repr__(self): show = [':%s %s' % (k, self.has()[k]) for k in sorted(self.has().keys()) if k[0] is not "_"] txt = ' '.join(show) if len(txt) > 60: show = map(lambda x: '\t' + x + '\n', show) return '{' + ' '.join(show) + '}' print("Unity ID: ", __author__) #################################################################### #SECTION 2 #################################################################### # Few Utility functions def say(*lst): """ Print whithout going to new line """ print(*lst, end="") sys.stdout.flush() def random_value(low, high, decimals=2): """ Generate a random number between low and high. decimals incidicate number of decimal places """ return round(random.uniform(low, high),decimals) def gt(a, b): return a > b def lt(a, b): return a < b def shuffle(lst): """ Shuffle a list """ random.shuffle(lst) return lst class Decision(O): """ Class indicating Decision of a problem """ def __init__(self, name, low, high): """ @param name: Name of the decision @param low: minimum value @param high: maximum value """ O.__init__(self, name=name, low=low, high=high) class Objective(O): """ Class indicating Objective of a problem """ def __init__(self, name, do_minimize=True): """ @param name: Name of the objective @param do_minimize: Flag indicating if objective has to be minimized or maximized """ O.__init__(self, name=name, do_minimize=do_minimize) class Point(O): """ Represents a member of the population """ def __init__(self, decisions): O.__init__(self) self.decisions = decisions self.objectives = None def __hash__(self): return hash(tuple(self.decisions)) def __eq__(self, other): return self.decisions == other.decisions def clone(self): new = Point(self.decisions) new.objectives = self.objectives return new class Problem(O): """ Class representing the cone problem. """ def __init__(self): O.__init__(self) # TODO 2: Code up decisions and objectives below for the problem # using the auxilary classes provided above. self.decisions = [Decision('r', 0, 10), Decision('h', 0, 20)] self.objectives = [Objective('S'), Objective('T')] @staticmethod def evaluate(point): [r, h] = point.decisions l = (r**2 + h**2)**0.5 S = pi * r * l T = S + pi * r**2 point.objectives = [S, T] # TODO 3: Evaluate the objectives S and T for the point. return point.objectives @staticmethod def is_valid(point): [r, h] = point.decisions # TODO 4: Check if the point has valid decisions V = pi / 3 * (r**2) * h return V > 200 def generate_one(self): # TODO 5: Generate a valid instance of Point. while(True): point = Point([random_value(d.low, d.high) for d in self.decisions]) if Problem.is_valid(point): return point cone = Problem() point = cone.generate_one() cone.evaluate(point) print (point) def populate(problem, size): population = [] # TODO 6: Create a list of points of length 'size' for _ in xrange(size): population.append(problem.generate_one()) return population #or #return(problem.generate_one() for _ in xrange(size) pop = populate(cone,5) print(pop) def crossover(mom, dad): # TODO 7: Create a new point which contains decisions from # the first half of mom and second half of dad n = len(mom.decisions) return Point(mom.decisions[:n//2] + dad.decisions[n//2:]) mom = cone.generate_one() dad = cone.generate_one() print(mom) print(dad) print(crossover(mom,dad)) print(crossover(pop[0],pop[1])) def mutate(problem, point, mutation_rate=0.01): # TODO 8: Iterate through all the decisions in the point # and if the probability is less than mutation rate # change the decision(randomly set it between its max and min). for i, d in enumerate(problem.decisions): if(random.random() < mutation_rate) : point.decisions[i] = random_value(d.low, d.high) return point def bdom(problem, one, two): """ Return if one dominates two """ objs_one = problem.evaluate(one) objs_two = problem.evaluate(two) if(one == two): return False; dominates = False # TODO 9: Return True/False based on the definition # of bdom above. first = True second = False for i,_ in enumerate(problem.objectives): if ((first is True) & gt(one.objectives[i], two.objectives[i])): first = False elif (not second & (one.objectives[i] is not two.objectives[i])): second = True dominates = first & second return dominates print(bdom(cone,pop[0],pop[1])) def fitness(problem, population, point): dominates = 0 # TODO 10: Evaluate fitness of a point. # For this workshop define fitness of a point # as the number of points dominated by it. # For example point dominates 5 members of population, # then fitness of point is 5. for another in population: if bdom(problem, point, another): dominates += 1 return dominates ''' should be 1 because it will run across the same point.''' print(fitness(cone, pop, pop[0])) print('HELLO WORLD\n') def elitism(problem, population, retain_size): # TODO 11: Sort the population with respect to the fitness # of the points and return the top 'retain_size' points of the population fit_pop = [fitness(cone,population,pop) for pop in population] population = [pop for _,pop in sorted(zip(fit_pop,population), reverse = True)] return population[:retain_size] print(elitism(cone, pop, 3)) def ga(pop_size=100, gens=250): problem = Problem() population = populate(problem, pop_size) [problem.evaluate(point) for point in population] initial_population = [point.clone() for point in population] gen = 0 while gen < gens: say(".") children = [] for _ in range(pop_size): mom = random.choice(population) dad = random.choice(population) while (mom == dad): dad = random.choice(population) child = mutate(problem, crossover(mom, dad)) if problem.is_valid(child) and child not in population + children: children.append(child) population += children population = elitism(problem, population, pop_size) gen += 1 print("") return initial_population, population def plot_pareto(initial, final): initial_objs = [point.objectives for point in initial] final_objs = [point.objectives for point in final] initial_x = [i[0] for i in initial_objs] initial_y = [i[1] for i in initial_objs] final_x = [i[0] for i in final_objs] final_y = [i[1] for i in final_objs] plt.scatter(initial_x, initial_y, color='b', marker='+', label='initial') plt.scatter(final_x, final_y, color='r', marker='o', label='final') plt.title("Scatter Plot between initial and final population of GA") plt.ylabel("Total Surface Area(T)") plt.xlabel("Curved Surface Area(S)") plt.legend(loc=9, bbox_to_anchor=(0.5, -0.175), ncol=2) plt.show() initial, final = ga() plot_pareto(initial, final)
gbtimmon/ase16GBT
code/4/ga/magoff2.py
Python
unlicense
8,088
""" You get an array of numbers, return the sum of all of the positives ones. Example [1,-4,7,12] => 1 + 7 + 12 = 20 Note: array may be empty, in this case return 0. """ def positive_sum(arr): # Your code here sum = 0 for number in arr: if number > 0: sum += number return sum
aadithpm/code-a-day
py/Sum Of Positive.py
Python
unlicense
316
/** * [★★★★]200. Number of Islands * finish: 2016-12-06 * https://leetcode.com/problems/number-of-islands/ */ /** * @param {character[][]} grid * @return {number} */ var numIslands = function (grid) { var count = 0, i, j; for (i = 0; i < grid.length; i++) { for (j = 0; j < grid[i].length; j++) { if (grid[i][j] == 1) { count += 1; grid[i] = modify(grid[i], j, 2); visitAround(grid, i, j); } else { grid[i] = modify(grid[i], j, 2); } } } return count; }; function modify(str, index, val) { var arr = str.split(''); arr[index] = val; return arr.join(''); } function visitAround(grid, i, j) { // top, right, down, left visit(grid, i - 1, j); visit(grid, i, j + 1); visit(grid, i + 1, j); visit(grid, i, j - 1); } function visit(grid, row, col) { if (typeof grid[row] !== 'undefined' && typeof grid[row][col] !== 'undefined') { if (grid[row][col] == 1) { grid[row] = modify(grid[row], col, 2); visitAround(grid, row, col); } else { grid[row] = modify(grid[row], col, 2); } } } write('algorithms: 200. Number of Islands', 'title'); write(numIslands(["10101", "11010", "10101", "01010"])); write(numIslands(["11110", "11010", "11000", "00000"]));
wyf2learn/leetcode
problems/algorithms/200.number-of-islands.js
JavaScript
unlicense
1,394
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication2 { class Exam: IDateAndCopy { public String Name { get; set; } public int Mark { get; set; } public DateTime Date { get; set; } public Exam(String N, int M, DateTime D) { Name = N; Mark = M; Date = D; } public Exam() { Name = ""; Mark = 0; Date = new DateTime(1990,1,1); } public override string ToString() { return Name + " " + Mark.ToString() + " " + Date.ToShortDateString(); } public virtual object DeepCopy() { Exam e = new Exam(Name, Mark, Date); return (object)e; } } }
PolyakovSergey95/OOP
Polyakov_17/prakt_1/Exam.cs
C#
unlicense
867
/* * Copyright 2015 the original author or authors. * * 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. * * All rights reserved. */ package com.rushucloud.eip.models; import org.springframework.ldap.odm.annotations.Entry; /** * Simple person object for OdmPerson posting to LDAP server. * * @author yangboz */ @Entry(objectClasses = {"person", "top"}, base = "") public class SimplePerson { private String mobile; public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } private String email; public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } private String password; public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } private String username; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } private String wxToken; public String getWxToken() { return wxToken; } public void setWxToken(String wxToken) { this.wxToken = wxToken; } private String code; public String getCode() { return code; } public void setCode(String code) { this.code = code; } }
yangboz/north-american-adventure
RushuMicroService/eip-rushucloud/src/main/java/com/rushucloud/eip/models/SimplePerson.java
Java
unlicense
1,993
import React from 'react' import { List, ListItem, LiAction, LiSecondary, LiPrimary, LiAvatar, Checkbox, Radio, Switch, Icon, } from 'styled-mdl' const demo = () => ( <List> <ListItem> <LiPrimary> <LiAvatar> <Icon name="person" /> </LiAvatar> Bryan Cranston </LiPrimary> <LiSecondary> <LiAction> <Checkbox defaultChecked /> </LiAction> </LiSecondary> </ListItem> <ListItem> <LiPrimary> <LiAvatar> <Icon name="person" /> </LiAvatar> Aaron Paul </LiPrimary> <LiSecondary> <LiAction> <Radio /> </LiAction> </LiSecondary> </ListItem> <ListItem> <LiPrimary> <LiAvatar> <Icon name="person" /> </LiAvatar> Bob Odenkirk </LiPrimary> <LiSecondary> <LiAction> <Switch defaultChecked /> </LiAction> </LiSecondary> </ListItem> </List> ) const caption = 'Avatars and controls' const code = `<List> <ListItem> <LiPrimary> <LiAvatar><Icon name="person" /></LiAvatar> Bryan Cranston </LiPrimary> <LiSecondary> <LiAction> <Checkbox defaultChecked /> </LiAction> </LiSecondary> </ListItem> <ListItem> <LiPrimary> <LiAvatar><Icon name="person" /></LiAvatar> Aaron Paul </LiPrimary> <LiSecondary> <LiAction> <Radio /> </LiAction> </LiSecondary> </ListItem> <ListItem> <LiPrimary> <LiAvatar><Icon name="person" /></LiAvatar> Bob Odenkirk </LiPrimary> <LiSecondary> <LiAction> <Switch defaultChecked /> </LiAction> </LiSecondary> </ListItem> </List>` export default { demo, caption, code }
isogon/styled-mdl-website
demos/lists/demos/avatarsAndControls.js
JavaScript
unlicense
1,826
""" Python bindings for GLFW. """ from __future__ import print_function from __future__ import division from __future__ import unicode_literals __author__ = 'Florian Rhiem (florian.rhiem@gmail.com)' __copyright__ = 'Copyright (c) 2013-2016 Florian Rhiem' __license__ = 'MIT' __version__ = '1.3.1' # By default (ERROR_REPORTING = True), GLFW errors will be reported as Python # exceptions. Set ERROR_REPORTING to False or set a curstom error callback to # disable this behavior. ERROR_REPORTING = True import ctypes import os import functools import glob import sys import subprocess import textwrap # Python 3 compatibility: try: _getcwd = os.getcwdu except AttributeError: _getcwd = os.getcwd if sys.version_info.major > 2: _to_char_p = lambda s: s.encode('utf-8') def _reraise(exception, traceback): raise exception.with_traceback(traceback) else: _to_char_p = lambda s: s def _reraise(exception, traceback): raise (exception, None, traceback) class GLFWError(Exception): """ Exception class used for reporting GLFW errors. """ def __init__(self, message): super(GLFWError, self).__init__(message) def _find_library_candidates(library_names, library_file_extensions, library_search_paths): """ Finds and returns filenames which might be the library you are looking for. """ candidates = set() for library_name in library_names: for search_path in library_search_paths: glob_query = os.path.join(search_path, '*'+library_name+'*') for filename in glob.iglob(glob_query): filename = os.path.realpath(filename) if filename in candidates: continue basename = os.path.basename(filename) if basename.startswith('lib'+library_name): basename_end = basename[len('lib'+library_name):] elif basename.startswith(library_name): basename_end = basename[len(library_name):] else: continue for file_extension in library_file_extensions: if basename_end.startswith(file_extension): if basename_end[len(file_extension):][:1] in ('', '.'): candidates.add(filename) if basename_end.endswith(file_extension): basename_middle = basename_end[:-len(file_extension)] if all(c in '0123456789.' for c in basename_middle): candidates.add(filename) return candidates def _load_library(library_names, library_file_extensions, library_search_paths, version_check_callback): """ Finds, loads and returns the most recent version of the library. """ candidates = _find_library_candidates(library_names, library_file_extensions, library_search_paths) library_versions = [] for filename in candidates: version = version_check_callback(filename) if version is not None and version >= (3, 0, 0): library_versions.append((version, filename)) if not library_versions: return None library_versions.sort() return ctypes.CDLL(library_versions[-1][1]) def _glfw_get_version(filename): """ Queries and returns the library version tuple or None by using a subprocess. """ version_checker_source = ''' import sys import ctypes def get_version(library_handle): """ Queries and returns the library version tuple or None. """ major_value = ctypes.c_int(0) major = ctypes.pointer(major_value) minor_value = ctypes.c_int(0) minor = ctypes.pointer(minor_value) rev_value = ctypes.c_int(0) rev = ctypes.pointer(rev_value) if hasattr(library_handle, 'glfwGetVersion'): library_handle.glfwGetVersion(major, minor, rev) version = (major_value.value, minor_value.value, rev_value.value) return version else: return None try: input_func = raw_input except NameError: input_func = input filename = input_func().strip() try: library_handle = ctypes.CDLL(filename) except OSError: pass else: version = get_version(library_handle) print(version) ''' args = [sys.executable, '-c', textwrap.dedent(version_checker_source)] process = subprocess.Popen(args, universal_newlines=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE) out = process.communicate(filename)[0] out = out.strip() if out: return eval(out) else: return None if sys.platform == 'win32': # only try glfw3.dll on windows try: _glfw = ctypes.CDLL('glfw3.dll') except OSError: _glfw = None else: _glfw = _load_library(['glfw', 'glfw3'], ['.so', '.dylib'], ['', '/usr/lib64', '/usr/local/lib64', '/usr/lib', '/usr/local/lib', '/usr/lib/x86_64-linux-gnu/'], _glfw_get_version) if _glfw is None: raise ImportError("Failed to load GLFW3 shared library.") _callback_repositories = [] class _GLFWwindow(ctypes.Structure): """ Wrapper for: typedef struct GLFWwindow GLFWwindow; """ _fields_ = [("dummy", ctypes.c_int)] class _GLFWmonitor(ctypes.Structure): """ Wrapper for: typedef struct GLFWmonitor GLFWmonitor; """ _fields_ = [("dummy", ctypes.c_int)] class _GLFWvidmode(ctypes.Structure): """ Wrapper for: typedef struct GLFWvidmode GLFWvidmode; """ _fields_ = [("width", ctypes.c_int), ("height", ctypes.c_int), ("red_bits", ctypes.c_int), ("green_bits", ctypes.c_int), ("blue_bits", ctypes.c_int), ("refresh_rate", ctypes.c_uint)] def __init__(self): ctypes.Structure.__init__(self) self.width = 0 self.height = 0 self.red_bits = 0 self.green_bits = 0 self.blue_bits = 0 self.refresh_rate = 0 def wrap(self, video_mode): """ Wraps a nested python sequence. """ size, bits, self.refresh_rate = video_mode self.width, self.height = size self.red_bits, self.green_bits, self.blue_bits = bits def unwrap(self): """ Returns a nested python sequence. """ size = self.width, self.height bits = self.red_bits, self.green_bits, self.blue_bits return size, bits, self.refresh_rate class _GLFWgammaramp(ctypes.Structure): """ Wrapper for: typedef struct GLFWgammaramp GLFWgammaramp; """ _fields_ = [("red", ctypes.POINTER(ctypes.c_ushort)), ("green", ctypes.POINTER(ctypes.c_ushort)), ("blue", ctypes.POINTER(ctypes.c_ushort)), ("size", ctypes.c_uint)] def __init__(self): ctypes.Structure.__init__(self) self.red = None self.red_array = None self.green = None self.green_array = None self.blue = None self.blue_array = None self.size = 0 def wrap(self, gammaramp): """ Wraps a nested python sequence. """ red, green, blue = gammaramp size = min(len(red), len(green), len(blue)) array_type = ctypes.c_ushort*size self.size = ctypes.c_uint(size) self.red_array = array_type() self.green_array = array_type() self.blue_array = array_type() for i in range(self.size): self.red_array[i] = int(red[i]*65535) self.green_array[i] = int(green[i]*65535) self.blue_array[i] = int(blue[i]*65535) pointer_type = ctypes.POINTER(ctypes.c_ushort) self.red = ctypes.cast(self.red_array, pointer_type) self.green = ctypes.cast(self.green_array, pointer_type) self.blue = ctypes.cast(self.blue_array, pointer_type) def unwrap(self): """ Returns a nested python sequence. """ red = [self.red[i]/65535.0 for i in range(self.size)] green = [self.green[i]/65535.0 for i in range(self.size)] blue = [self.blue[i]/65535.0 for i in range(self.size)] return red, green, blue class _GLFWcursor(ctypes.Structure): """ Wrapper for: typedef struct GLFWcursor GLFWcursor; """ _fields_ = [("dummy", ctypes.c_int)] class _GLFWimage(ctypes.Structure): """ Wrapper for: typedef struct GLFWimage GLFWimage; """ _fields_ = [("width", ctypes.c_int), ("height", ctypes.c_int), ("pixels", ctypes.POINTER(ctypes.c_ubyte))] def __init__(self): ctypes.Structure.__init__(self) self.width = 0 self.height = 0 self.pixels = None self.pixels_array = None def wrap(self, image): """ Wraps a nested python sequence. """ self.width, self.height, pixels = image array_type = ctypes.c_ubyte * 4 * self.width * self.height self.pixels_array = array_type() for i in range(self.height): for j in range(self.width): for k in range(4): self.pixels_array[i][j][k] = pixels[i][j][k] pointer_type = ctypes.POINTER(ctypes.c_ubyte) self.pixels = ctypes.cast(self.pixels_array, pointer_type) def unwrap(self): """ Returns a nested python sequence. """ pixels = [[[int(c) for c in p] for p in l] for l in self.pixels_array] return self.width, self.height, pixels VERSION_MAJOR = 3 VERSION_MINOR = 2 VERSION_REVISION = 1 RELEASE = 0 PRESS = 1 REPEAT = 2 KEY_UNKNOWN = -1 KEY_SPACE = 32 KEY_APOSTROPHE = 39 KEY_COMMA = 44 KEY_MINUS = 45 KEY_PERIOD = 46 KEY_SLASH = 47 KEY_0 = 48 KEY_1 = 49 KEY_2 = 50 KEY_3 = 51 KEY_4 = 52 KEY_5 = 53 KEY_6 = 54 KEY_7 = 55 KEY_8 = 56 KEY_9 = 57 KEY_SEMICOLON = 59 KEY_EQUAL = 61 KEY_A = 65 KEY_B = 66 KEY_C = 67 KEY_D = 68 KEY_E = 69 KEY_F = 70 KEY_G = 71 KEY_H = 72 KEY_I = 73 KEY_J = 74 KEY_K = 75 KEY_L = 76 KEY_M = 77 KEY_N = 78 KEY_O = 79 KEY_P = 80 KEY_Q = 81 KEY_R = 82 KEY_S = 83 KEY_T = 84 KEY_U = 85 KEY_V = 86 KEY_W = 87 KEY_X = 88 KEY_Y = 89 KEY_Z = 90 KEY_LEFT_BRACKET = 91 KEY_BACKSLASH = 92 KEY_RIGHT_BRACKET = 93 KEY_GRAVE_ACCENT = 96 KEY_WORLD_1 = 161 KEY_WORLD_2 = 162 KEY_ESCAPE = 256 KEY_ENTER = 257 KEY_TAB = 258 KEY_BACKSPACE = 259 KEY_INSERT = 260 KEY_DELETE = 261 KEY_RIGHT = 262 KEY_LEFT = 263 KEY_DOWN = 264 KEY_UP = 265 KEY_PAGE_UP = 266 KEY_PAGE_DOWN = 267 KEY_HOME = 268 KEY_END = 269 KEY_CAPS_LOCK = 280 KEY_SCROLL_LOCK = 281 KEY_NUM_LOCK = 282 KEY_PRINT_SCREEN = 283 KEY_PAUSE = 284 KEY_F1 = 290 KEY_F2 = 291 KEY_F3 = 292 KEY_F4 = 293 KEY_F5 = 294 KEY_F6 = 295 KEY_F7 = 296 KEY_F8 = 297 KEY_F9 = 298 KEY_F10 = 299 KEY_F11 = 300 KEY_F12 = 301 KEY_F13 = 302 KEY_F14 = 303 KEY_F15 = 304 KEY_F16 = 305 KEY_F17 = 306 KEY_F18 = 307 KEY_F19 = 308 KEY_F20 = 309 KEY_F21 = 310 KEY_F22 = 311 KEY_F23 = 312 KEY_F24 = 313 KEY_F25 = 314 KEY_KP_0 = 320 KEY_KP_1 = 321 KEY_KP_2 = 322 KEY_KP_3 = 323 KEY_KP_4 = 324 KEY_KP_5 = 325 KEY_KP_6 = 326 KEY_KP_7 = 327 KEY_KP_8 = 328 KEY_KP_9 = 329 KEY_KP_DECIMAL = 330 KEY_KP_DIVIDE = 331 KEY_KP_MULTIPLY = 332 KEY_KP_SUBTRACT = 333 KEY_KP_ADD = 334 KEY_KP_ENTER = 335 KEY_KP_EQUAL = 336 KEY_LEFT_SHIFT = 340 KEY_LEFT_CONTROL = 341 KEY_LEFT_ALT = 342 KEY_LEFT_SUPER = 343 KEY_RIGHT_SHIFT = 344 KEY_RIGHT_CONTROL = 345 KEY_RIGHT_ALT = 346 KEY_RIGHT_SUPER = 347 KEY_MENU = 348 KEY_LAST = KEY_MENU MOD_SHIFT = 0x0001 MOD_CONTROL = 0x0002 MOD_ALT = 0x0004 MOD_SUPER = 0x0008 MOUSE_BUTTON_1 = 0 MOUSE_BUTTON_2 = 1 MOUSE_BUTTON_3 = 2 MOUSE_BUTTON_4 = 3 MOUSE_BUTTON_5 = 4 MOUSE_BUTTON_6 = 5 MOUSE_BUTTON_7 = 6 MOUSE_BUTTON_8 = 7 MOUSE_BUTTON_LAST = MOUSE_BUTTON_8 MOUSE_BUTTON_LEFT = MOUSE_BUTTON_1 MOUSE_BUTTON_RIGHT = MOUSE_BUTTON_2 MOUSE_BUTTON_MIDDLE = MOUSE_BUTTON_3 JOYSTICK_1 = 0 JOYSTICK_2 = 1 JOYSTICK_3 = 2 JOYSTICK_4 = 3 JOYSTICK_5 = 4 JOYSTICK_6 = 5 JOYSTICK_7 = 6 JOYSTICK_8 = 7 JOYSTICK_9 = 8 JOYSTICK_10 = 9 JOYSTICK_11 = 10 JOYSTICK_12 = 11 JOYSTICK_13 = 12 JOYSTICK_14 = 13 JOYSTICK_15 = 14 JOYSTICK_16 = 15 JOYSTICK_LAST = JOYSTICK_16 NOT_INITIALIZED = 0x00010001 NO_CURRENT_CONTEXT = 0x00010002 INVALID_ENUM = 0x00010003 INVALID_VALUE = 0x00010004 OUT_OF_MEMORY = 0x00010005 API_UNAVAILABLE = 0x00010006 VERSION_UNAVAILABLE = 0x00010007 PLATFORM_ERROR = 0x00010008 FORMAT_UNAVAILABLE = 0x00010009 NO_WINDOW_CONTEXT = 0x0001000A FOCUSED = 0x00020001 ICONIFIED = 0x00020002 RESIZABLE = 0x00020003 VISIBLE = 0x00020004 DECORATED = 0x00020005 AUTO_ICONIFY = 0x00020006 FLOATING = 0x00020007 MAXIMIZED = 0x00020008 RED_BITS = 0x00021001 GREEN_BITS = 0x00021002 BLUE_BITS = 0x00021003 ALPHA_BITS = 0x00021004 DEPTH_BITS = 0x00021005 STENCIL_BITS = 0x00021006 ACCUM_RED_BITS = 0x00021007 ACCUM_GREEN_BITS = 0x00021008 ACCUM_BLUE_BITS = 0x00021009 ACCUM_ALPHA_BITS = 0x0002100A AUX_BUFFERS = 0x0002100B STEREO = 0x0002100C SAMPLES = 0x0002100D SRGB_CAPABLE = 0x0002100E REFRESH_RATE = 0x0002100F DOUBLEBUFFER = 0x00021010 CLIENT_API = 0x00022001 CONTEXT_VERSION_MAJOR = 0x00022002 CONTEXT_VERSION_MINOR = 0x00022003 CONTEXT_REVISION = 0x00022004 CONTEXT_ROBUSTNESS = 0x00022005 OPENGL_FORWARD_COMPAT = 0x00022006 OPENGL_DEBUG_CONTEXT = 0x00022007 OPENGL_PROFILE = 0x00022008 CONTEXT_RELEASE_BEHAVIOR = 0x00022009 CONTEXT_NO_ERROR = 0x0002200A CONTEXT_CREATION_API = 0x0002200B NO_API = 0 OPENGL_API = 0x00030001 OPENGL_ES_API = 0x00030002 NO_ROBUSTNESS = 0 NO_RESET_NOTIFICATION = 0x00031001 LOSE_CONTEXT_ON_RESET = 0x00031002 OPENGL_ANY_PROFILE = 0 OPENGL_CORE_PROFILE = 0x00032001 OPENGL_COMPAT_PROFILE = 0x00032002 CURSOR = 0x00033001 STICKY_KEYS = 0x00033002 STICKY_MOUSE_BUTTONS = 0x00033003 CURSOR_NORMAL = 0x00034001 CURSOR_HIDDEN = 0x00034002 CURSOR_DISABLED = 0x00034003 ANY_RELEASE_BEHAVIOR = 0 RELEASE_BEHAVIOR_FLUSH = 0x00035001 RELEASE_BEHAVIOR_NONE = 0x00035002 NATIVE_CONTEXT_API = 0x00036001 EGL_CONTEXT_API = 0x00036002 ARROW_CURSOR = 0x00036001 IBEAM_CURSOR = 0x00036002 CROSSHAIR_CURSOR = 0x00036003 HAND_CURSOR = 0x00036004 HRESIZE_CURSOR = 0x00036005 VRESIZE_CURSOR = 0x00036006 CONNECTED = 0x00040001 DISCONNECTED = 0x00040002 DONT_CARE = -1 _exc_info_from_callback = None def _callback_exception_decorator(func): @functools.wraps(func) def callback_wrapper(*args, **kwargs): global _exc_info_from_callback if _exc_info_from_callback is not None: # We are on the way back to Python after an exception was raised. # Do not call further callbacks and wait for the errcheck function # to handle the exception first. return try: return func(*args, **kwargs) except (KeyboardInterrupt, SystemExit): raise except: _exc_info_from_callback = sys.exc_info() return callback_wrapper def _prepare_errcheck(): """ This function sets the errcheck attribute of all ctypes wrapped functions to evaluate the _exc_info_from_callback global variable and re-raise any exceptions that might have been raised in callbacks. It also modifies all callback types to automatically wrap the function using the _callback_exception_decorator. """ def errcheck(result, *args): global _exc_info_from_callback if _exc_info_from_callback is not None: exc = _exc_info_from_callback _exc_info_from_callback = None _reraise(exc[1], exc[2]) return result for symbol in dir(_glfw): if symbol.startswith('glfw'): getattr(_glfw, symbol).errcheck = errcheck _globals = globals() for symbol in _globals: if symbol.startswith('_GLFW') and symbol.endswith('fun'): def wrapper_cfunctype(func, cfunctype=_globals[symbol]): return cfunctype(_callback_exception_decorator(func)) _globals[symbol] = wrapper_cfunctype _GLFWerrorfun = ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_char_p) _GLFWwindowposfun = ctypes.CFUNCTYPE(None, ctypes.POINTER(_GLFWwindow), ctypes.c_int, ctypes.c_int) _GLFWwindowsizefun = ctypes.CFUNCTYPE(None, ctypes.POINTER(_GLFWwindow), ctypes.c_int, ctypes.c_int) _GLFWwindowclosefun = ctypes.CFUNCTYPE(None, ctypes.POINTER(_GLFWwindow)) _GLFWwindowrefreshfun = ctypes.CFUNCTYPE(None, ctypes.POINTER(_GLFWwindow)) _GLFWwindowfocusfun = ctypes.CFUNCTYPE(None, ctypes.POINTER(_GLFWwindow), ctypes.c_int) _GLFWwindowiconifyfun = ctypes.CFUNCTYPE(None, ctypes.POINTER(_GLFWwindow), ctypes.c_int) _GLFWframebuffersizefun = ctypes.CFUNCTYPE(None, ctypes.POINTER(_GLFWwindow), ctypes.c_int, ctypes.c_int) _GLFWmousebuttonfun = ctypes.CFUNCTYPE(None, ctypes.POINTER(_GLFWwindow), ctypes.c_int, ctypes.c_int, ctypes.c_int) _GLFWcursorposfun = ctypes.CFUNCTYPE(None, ctypes.POINTER(_GLFWwindow), ctypes.c_double, ctypes.c_double) _GLFWcursorenterfun = ctypes.CFUNCTYPE(None, ctypes.POINTER(_GLFWwindow), ctypes.c_int) _GLFWscrollfun = ctypes.CFUNCTYPE(None, ctypes.POINTER(_GLFWwindow), ctypes.c_double, ctypes.c_double) _GLFWkeyfun = ctypes.CFUNCTYPE(None, ctypes.POINTER(_GLFWwindow), ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int) _GLFWcharfun = ctypes.CFUNCTYPE(None, ctypes.POINTER(_GLFWwindow), ctypes.c_int) _GLFWmonitorfun = ctypes.CFUNCTYPE(None, ctypes.POINTER(_GLFWmonitor), ctypes.c_int) _GLFWdropfun = ctypes.CFUNCTYPE(None, ctypes.POINTER(_GLFWwindow), ctypes.c_int, ctypes.POINTER(ctypes.c_char_p)) _GLFWcharmodsfun = ctypes.CFUNCTYPE(None, ctypes.POINTER(_GLFWwindow), ctypes.c_uint, ctypes.c_int) _GLFWjoystickfun = ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_int) _glfw.glfwInit.restype = ctypes.c_int _glfw.glfwInit.argtypes = [] def init(): """ Initializes the GLFW library. Wrapper for: int glfwInit(void); """ cwd = _getcwd() res = _glfw.glfwInit() os.chdir(cwd) return res _glfw.glfwTerminate.restype = None _glfw.glfwTerminate.argtypes = [] def terminate(): """ Terminates the GLFW library. Wrapper for: void glfwTerminate(void); """ for callback_repository in _callback_repositories: for window_addr in list(callback_repository.keys()): del callback_repository[window_addr] for window_addr in list(_window_user_data_repository.keys()): del _window_user_data_repository[window_addr] _glfw.glfwTerminate() _glfw.glfwGetVersion.restype = None _glfw.glfwGetVersion.argtypes = [ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int)] def get_version(): """ Retrieves the version of the GLFW library. Wrapper for: void glfwGetVersion(int* major, int* minor, int* rev); """ major_value = ctypes.c_int(0) major = ctypes.pointer(major_value) minor_value = ctypes.c_int(0) minor = ctypes.pointer(minor_value) rev_value = ctypes.c_int(0) rev = ctypes.pointer(rev_value) _glfw.glfwGetVersion(major, minor, rev) return major_value.value, minor_value.value, rev_value.value _glfw.glfwGetVersionString.restype = ctypes.c_char_p _glfw.glfwGetVersionString.argtypes = [] def get_version_string(): """ Returns a string describing the compile-time configuration. Wrapper for: const char* glfwGetVersionString(void); """ return _glfw.glfwGetVersionString() @_callback_exception_decorator def _raise_glfw_errors_as_exceptions(error_code, description): """ Default error callback that raises GLFWError exceptions for glfw errors. Set an alternative error callback or set glfw.ERROR_REPORTING to False to disable this behavior. """ global ERROR_REPORTING if ERROR_REPORTING: message = "(%d) %s" % (error_code, description) raise GLFWError(message) _default_error_callback = _GLFWerrorfun(_raise_glfw_errors_as_exceptions) _error_callback = (_raise_glfw_errors_as_exceptions, _default_error_callback) _glfw.glfwSetErrorCallback.restype = _GLFWerrorfun _glfw.glfwSetErrorCallback.argtypes = [_GLFWerrorfun] _glfw.glfwSetErrorCallback(_default_error_callback) def set_error_callback(cbfun): """ Sets the error callback. Wrapper for: GLFWerrorfun glfwSetErrorCallback(GLFWerrorfun cbfun); """ global _error_callback previous_callback = _error_callback if cbfun is None: cbfun = _raise_glfw_errors_as_exceptions c_cbfun = _default_error_callback else: c_cbfun = _GLFWerrorfun(cbfun) _error_callback = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetErrorCallback(cbfun) if previous_callback is not None and previous_callback[0] != _raise_glfw_errors_as_exceptions: return previous_callback[0] _glfw.glfwGetMonitors.restype = ctypes.POINTER(ctypes.POINTER(_GLFWmonitor)) _glfw.glfwGetMonitors.argtypes = [ctypes.POINTER(ctypes.c_int)] def get_monitors(): """ Returns the currently connected monitors. Wrapper for: GLFWmonitor** glfwGetMonitors(int* count); """ count_value = ctypes.c_int(0) count = ctypes.pointer(count_value) result = _glfw.glfwGetMonitors(count) monitors = [result[i] for i in range(count_value.value)] return monitors _glfw.glfwGetPrimaryMonitor.restype = ctypes.POINTER(_GLFWmonitor) _glfw.glfwGetPrimaryMonitor.argtypes = [] def get_primary_monitor(): """ Returns the primary monitor. Wrapper for: GLFWmonitor* glfwGetPrimaryMonitor(void); """ return _glfw.glfwGetPrimaryMonitor() _glfw.glfwGetMonitorPos.restype = None _glfw.glfwGetMonitorPos.argtypes = [ctypes.POINTER(_GLFWmonitor), ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int)] def get_monitor_pos(monitor): """ Returns the position of the monitor's viewport on the virtual screen. Wrapper for: void glfwGetMonitorPos(GLFWmonitor* monitor, int* xpos, int* ypos); """ xpos_value = ctypes.c_int(0) xpos = ctypes.pointer(xpos_value) ypos_value = ctypes.c_int(0) ypos = ctypes.pointer(ypos_value) _glfw.glfwGetMonitorPos(monitor, xpos, ypos) return xpos_value.value, ypos_value.value _glfw.glfwGetMonitorPhysicalSize.restype = None _glfw.glfwGetMonitorPhysicalSize.argtypes = [ctypes.POINTER(_GLFWmonitor), ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int)] def get_monitor_physical_size(monitor): """ Returns the physical size of the monitor. Wrapper for: void glfwGetMonitorPhysicalSize(GLFWmonitor* monitor, int* width, int* height); """ width_value = ctypes.c_int(0) width = ctypes.pointer(width_value) height_value = ctypes.c_int(0) height = ctypes.pointer(height_value) _glfw.glfwGetMonitorPhysicalSize(monitor, width, height) return width_value.value, height_value.value _glfw.glfwGetMonitorName.restype = ctypes.c_char_p _glfw.glfwGetMonitorName.argtypes = [ctypes.POINTER(_GLFWmonitor)] def get_monitor_name(monitor): """ Returns the name of the specified monitor. Wrapper for: const char* glfwGetMonitorName(GLFWmonitor* monitor); """ return _glfw.glfwGetMonitorName(monitor) _monitor_callback = None _glfw.glfwSetMonitorCallback.restype = _GLFWmonitorfun _glfw.glfwSetMonitorCallback.argtypes = [_GLFWmonitorfun] def set_monitor_callback(cbfun): """ Sets the monitor configuration callback. Wrapper for: GLFWmonitorfun glfwSetMonitorCallback(GLFWmonitorfun cbfun); """ global _monitor_callback previous_callback = _monitor_callback if cbfun is None: cbfun = 0 c_cbfun = _GLFWmonitorfun(cbfun) _monitor_callback = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetMonitorCallback(cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0] _glfw.glfwGetVideoModes.restype = ctypes.POINTER(_GLFWvidmode) _glfw.glfwGetVideoModes.argtypes = [ctypes.POINTER(_GLFWmonitor), ctypes.POINTER(ctypes.c_int)] def get_video_modes(monitor): """ Returns the available video modes for the specified monitor. Wrapper for: const GLFWvidmode* glfwGetVideoModes(GLFWmonitor* monitor, int* count); """ count_value = ctypes.c_int(0) count = ctypes.pointer(count_value) result = _glfw.glfwGetVideoModes(monitor, count) videomodes = [result[i].unwrap() for i in range(count_value.value)] return videomodes _glfw.glfwGetVideoMode.restype = ctypes.POINTER(_GLFWvidmode) _glfw.glfwGetVideoMode.argtypes = [ctypes.POINTER(_GLFWmonitor)] def get_video_mode(monitor): """ Returns the current mode of the specified monitor. Wrapper for: const GLFWvidmode* glfwGetVideoMode(GLFWmonitor* monitor); """ videomode = _glfw.glfwGetVideoMode(monitor).contents return videomode.unwrap() _glfw.glfwSetGamma.restype = None _glfw.glfwSetGamma.argtypes = [ctypes.POINTER(_GLFWmonitor), ctypes.c_float] def set_gamma(monitor, gamma): """ Generates a gamma ramp and sets it for the specified monitor. Wrapper for: void glfwSetGamma(GLFWmonitor* monitor, float gamma); """ _glfw.glfwSetGamma(monitor, gamma) _glfw.glfwGetGammaRamp.restype = ctypes.POINTER(_GLFWgammaramp) _glfw.glfwGetGammaRamp.argtypes = [ctypes.POINTER(_GLFWmonitor)] def get_gamma_ramp(monitor): """ Retrieves the current gamma ramp for the specified monitor. Wrapper for: const GLFWgammaramp* glfwGetGammaRamp(GLFWmonitor* monitor); """ gammaramp = _glfw.glfwGetGammaRamp(monitor).contents return gammaramp.unwrap() _glfw.glfwSetGammaRamp.restype = None _glfw.glfwSetGammaRamp.argtypes = [ctypes.POINTER(_GLFWmonitor), ctypes.POINTER(_GLFWgammaramp)] def set_gamma_ramp(monitor, ramp): """ Sets the current gamma ramp for the specified monitor. Wrapper for: void glfwSetGammaRamp(GLFWmonitor* monitor, const GLFWgammaramp* ramp); """ gammaramp = _GLFWgammaramp() gammaramp.wrap(ramp) _glfw.glfwSetGammaRamp(monitor, ctypes.pointer(gammaramp)) _glfw.glfwDefaultWindowHints.restype = None _glfw.glfwDefaultWindowHints.argtypes = [] def default_window_hints(): """ Resets all window hints to their default values. Wrapper for: void glfwDefaultWindowHints(void); """ _glfw.glfwDefaultWindowHints() _glfw.glfwWindowHint.restype = None _glfw.glfwWindowHint.argtypes = [ctypes.c_int, ctypes.c_int] def window_hint(target, hint): """ Sets the specified window hint to the desired value. Wrapper for: void glfwWindowHint(int target, int hint); """ _glfw.glfwWindowHint(target, hint) _glfw.glfwCreateWindow.restype = ctypes.POINTER(_GLFWwindow) _glfw.glfwCreateWindow.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(_GLFWmonitor), ctypes.POINTER(_GLFWwindow)] def create_window(width, height, title, monitor, share): """ Creates a window and its associated context. Wrapper for: GLFWwindow* glfwCreateWindow(int width, int height, const char* title, GLFWmonitor* monitor, GLFWwindow* share); """ return _glfw.glfwCreateWindow(width, height, _to_char_p(title), monitor, share) _glfw.glfwDestroyWindow.restype = None _glfw.glfwDestroyWindow.argtypes = [ctypes.POINTER(_GLFWwindow)] def destroy_window(window): """ Destroys the specified window and its context. Wrapper for: void glfwDestroyWindow(GLFWwindow* window); """ _glfw.glfwDestroyWindow(window) window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_ulong)).contents.value for callback_repository in _callback_repositories: if window_addr in callback_repository: del callback_repository[window_addr] if window_addr in _window_user_data_repository: del _window_user_data_repository[window_addr] _glfw.glfwWindowShouldClose.restype = ctypes.c_int _glfw.glfwWindowShouldClose.argtypes = [ctypes.POINTER(_GLFWwindow)] def window_should_close(window): """ Checks the close flag of the specified window. Wrapper for: int glfwWindowShouldClose(GLFWwindow* window); """ return _glfw.glfwWindowShouldClose(window) _glfw.glfwSetWindowShouldClose.restype = None _glfw.glfwSetWindowShouldClose.argtypes = [ctypes.POINTER(_GLFWwindow), ctypes.c_int] def set_window_should_close(window, value): """ Sets the close flag of the specified window. Wrapper for: void glfwSetWindowShouldClose(GLFWwindow* window, int value); """ _glfw.glfwSetWindowShouldClose(window, value) _glfw.glfwSetWindowTitle.restype = None _glfw.glfwSetWindowTitle.argtypes = [ctypes.POINTER(_GLFWwindow), ctypes.c_char_p] def set_window_title(window, title): """ Sets the title of the specified window. Wrapper for: void glfwSetWindowTitle(GLFWwindow* window, const char* title); """ _glfw.glfwSetWindowTitle(window, _to_char_p(title)) _glfw.glfwGetWindowPos.restype = None _glfw.glfwGetWindowPos.argtypes = [ctypes.POINTER(_GLFWwindow), ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int)] def get_window_pos(window): """ Retrieves the position of the client area of the specified window. Wrapper for: void glfwGetWindowPos(GLFWwindow* window, int* xpos, int* ypos); """ xpos_value = ctypes.c_int(0) xpos = ctypes.pointer(xpos_value) ypos_value = ctypes.c_int(0) ypos = ctypes.pointer(ypos_value) _glfw.glfwGetWindowPos(window, xpos, ypos) return xpos_value.value, ypos_value.value _glfw.glfwSetWindowPos.restype = None _glfw.glfwSetWindowPos.argtypes = [ctypes.POINTER(_GLFWwindow), ctypes.c_int, ctypes.c_int] def set_window_pos(window, xpos, ypos): """ Sets the position of the client area of the specified window. Wrapper for: void glfwSetWindowPos(GLFWwindow* window, int xpos, int ypos); """ _glfw.glfwSetWindowPos(window, xpos, ypos) _glfw.glfwGetWindowSize.restype = None _glfw.glfwGetWindowSize.argtypes = [ctypes.POINTER(_GLFWwindow), ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int)] def get_window_size(window): """ Retrieves the size of the client area of the specified window. Wrapper for: void glfwGetWindowSize(GLFWwindow* window, int* width, int* height); """ width_value = ctypes.c_int(0) width = ctypes.pointer(width_value) height_value = ctypes.c_int(0) height = ctypes.pointer(height_value) _glfw.glfwGetWindowSize(window, width, height) return width_value.value, height_value.value _glfw.glfwSetWindowSize.restype = None _glfw.glfwSetWindowSize.argtypes = [ctypes.POINTER(_GLFWwindow), ctypes.c_int, ctypes.c_int] def set_window_size(window, width, height): """ Sets the size of the client area of the specified window. Wrapper for: void glfwSetWindowSize(GLFWwindow* window, int width, int height); """ _glfw.glfwSetWindowSize(window, width, height) _glfw.glfwGetFramebufferSize.restype = None _glfw.glfwGetFramebufferSize.argtypes = [ctypes.POINTER(_GLFWwindow), ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int)] def get_framebuffer_size(window): """ Retrieves the size of the framebuffer of the specified window. Wrapper for: void glfwGetFramebufferSize(GLFWwindow* window, int* width, int* height); """ width_value = ctypes.c_int(0) width = ctypes.pointer(width_value) height_value = ctypes.c_int(0) height = ctypes.pointer(height_value) _glfw.glfwGetFramebufferSize(window, width, height) return width_value.value, height_value.value _glfw.glfwIconifyWindow.restype = None _glfw.glfwIconifyWindow.argtypes = [ctypes.POINTER(_GLFWwindow)] def iconify_window(window): """ Iconifies the specified window. Wrapper for: void glfwIconifyWindow(GLFWwindow* window); """ _glfw.glfwIconifyWindow(window) _glfw.glfwRestoreWindow.restype = None _glfw.glfwRestoreWindow.argtypes = [ctypes.POINTER(_GLFWwindow)] def restore_window(window): """ Restores the specified window. Wrapper for: void glfwRestoreWindow(GLFWwindow* window); """ _glfw.glfwRestoreWindow(window) _glfw.glfwShowWindow.restype = None _glfw.glfwShowWindow.argtypes = [ctypes.POINTER(_GLFWwindow)] def show_window(window): """ Makes the specified window visible. Wrapper for: void glfwShowWindow(GLFWwindow* window); """ _glfw.glfwShowWindow(window) _glfw.glfwHideWindow.restype = None _glfw.glfwHideWindow.argtypes = [ctypes.POINTER(_GLFWwindow)] def hide_window(window): """ Hides the specified window. Wrapper for: void glfwHideWindow(GLFWwindow* window); """ _glfw.glfwHideWindow(window) _glfw.glfwGetWindowMonitor.restype = ctypes.POINTER(_GLFWmonitor) _glfw.glfwGetWindowMonitor.argtypes = [ctypes.POINTER(_GLFWwindow)] def get_window_monitor(window): """ Returns the monitor that the window uses for full screen mode. Wrapper for: GLFWmonitor* glfwGetWindowMonitor(GLFWwindow* window); """ return _glfw.glfwGetWindowMonitor(window) _glfw.glfwGetWindowAttrib.restype = ctypes.c_int _glfw.glfwGetWindowAttrib.argtypes = [ctypes.POINTER(_GLFWwindow), ctypes.c_int] def get_window_attrib(window, attrib): """ Returns an attribute of the specified window. Wrapper for: int glfwGetWindowAttrib(GLFWwindow* window, int attrib); """ return _glfw.glfwGetWindowAttrib(window, attrib) _window_user_data_repository = {} _glfw.glfwSetWindowUserPointer.restype = None _glfw.glfwSetWindowUserPointer.argtypes = [ctypes.POINTER(_GLFWwindow), ctypes.c_void_p] def set_window_user_pointer(window, pointer): """ Sets the user pointer of the specified window. You may pass a normal python object into this function and it will be wrapped automatically. The object will be kept in existence until the pointer is set to something else or until the window is destroyed. Wrapper for: void glfwSetWindowUserPointer(GLFWwindow* window, void* pointer); """ data = (False, pointer) if not isinstance(pointer, ctypes.c_void_p): data = (True, pointer) # Create a void pointer for the python object pointer = ctypes.cast(ctypes.pointer(ctypes.py_object(pointer)), ctypes.c_void_p) window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value _window_user_data_repository[window_addr] = data _glfw.glfwSetWindowUserPointer(window, pointer) _glfw.glfwGetWindowUserPointer.restype = ctypes.c_void_p _glfw.glfwGetWindowUserPointer.argtypes = [ctypes.POINTER(_GLFWwindow)] def get_window_user_pointer(window): """ Returns the user pointer of the specified window. Wrapper for: void* glfwGetWindowUserPointer(GLFWwindow* window); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _window_user_data_repository: data = _window_user_data_repository[window_addr] is_wrapped_py_object = data[0] if is_wrapped_py_object: return data[1] return _glfw.glfwGetWindowUserPointer(window) _window_pos_callback_repository = {} _callback_repositories.append(_window_pos_callback_repository) _glfw.glfwSetWindowPosCallback.restype = _GLFWwindowposfun _glfw.glfwSetWindowPosCallback.argtypes = [ctypes.POINTER(_GLFWwindow), _GLFWwindowposfun] def set_window_pos_callback(window, cbfun): """ Sets the position callback for the specified window. Wrapper for: GLFWwindowposfun glfwSetWindowPosCallback(GLFWwindow* window, GLFWwindowposfun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _window_pos_callback_repository: previous_callback = _window_pos_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWwindowposfun(cbfun) _window_pos_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetWindowPosCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0] _window_size_callback_repository = {} _callback_repositories.append(_window_size_callback_repository) _glfw.glfwSetWindowSizeCallback.restype = _GLFWwindowsizefun _glfw.glfwSetWindowSizeCallback.argtypes = [ctypes.POINTER(_GLFWwindow), _GLFWwindowsizefun] def set_window_size_callback(window, cbfun): """ Sets the size callback for the specified window. Wrapper for: GLFWwindowsizefun glfwSetWindowSizeCallback(GLFWwindow* window, GLFWwindowsizefun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _window_size_callback_repository: previous_callback = _window_size_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWwindowsizefun(cbfun) _window_size_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetWindowSizeCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0] _window_close_callback_repository = {} _callback_repositories.append(_window_close_callback_repository) _glfw.glfwSetWindowCloseCallback.restype = _GLFWwindowclosefun _glfw.glfwSetWindowCloseCallback.argtypes = [ctypes.POINTER(_GLFWwindow), _GLFWwindowclosefun] def set_window_close_callback(window, cbfun): """ Sets the close callback for the specified window. Wrapper for: GLFWwindowclosefun glfwSetWindowCloseCallback(GLFWwindow* window, GLFWwindowclosefun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _window_close_callback_repository: previous_callback = _window_close_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWwindowclosefun(cbfun) _window_close_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetWindowCloseCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0] _window_refresh_callback_repository = {} _callback_repositories.append(_window_refresh_callback_repository) _glfw.glfwSetWindowRefreshCallback.restype = _GLFWwindowrefreshfun _glfw.glfwSetWindowRefreshCallback.argtypes = [ctypes.POINTER(_GLFWwindow), _GLFWwindowrefreshfun] def set_window_refresh_callback(window, cbfun): """ Sets the refresh callback for the specified window. Wrapper for: GLFWwindowrefreshfun glfwSetWindowRefreshCallback(GLFWwindow* window, GLFWwindowrefreshfun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _window_refresh_callback_repository: previous_callback = _window_refresh_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWwindowrefreshfun(cbfun) _window_refresh_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetWindowRefreshCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0] _window_focus_callback_repository = {} _callback_repositories.append(_window_focus_callback_repository) _glfw.glfwSetWindowFocusCallback.restype = _GLFWwindowfocusfun _glfw.glfwSetWindowFocusCallback.argtypes = [ctypes.POINTER(_GLFWwindow), _GLFWwindowfocusfun] def set_window_focus_callback(window, cbfun): """ Sets the focus callback for the specified window. Wrapper for: GLFWwindowfocusfun glfwSetWindowFocusCallback(GLFWwindow* window, GLFWwindowfocusfun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _window_focus_callback_repository: previous_callback = _window_focus_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWwindowfocusfun(cbfun) _window_focus_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetWindowFocusCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0] _window_iconify_callback_repository = {} _callback_repositories.append(_window_iconify_callback_repository) _glfw.glfwSetWindowIconifyCallback.restype = _GLFWwindowiconifyfun _glfw.glfwSetWindowIconifyCallback.argtypes = [ctypes.POINTER(_GLFWwindow), _GLFWwindowiconifyfun] def set_window_iconify_callback(window, cbfun): """ Sets the iconify callback for the specified window. Wrapper for: GLFWwindowiconifyfun glfwSetWindowIconifyCallback(GLFWwindow* window, GLFWwindowiconifyfun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _window_iconify_callback_repository: previous_callback = _window_iconify_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWwindowiconifyfun(cbfun) _window_iconify_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetWindowIconifyCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0] _framebuffer_size_callback_repository = {} _callback_repositories.append(_framebuffer_size_callback_repository) _glfw.glfwSetFramebufferSizeCallback.restype = _GLFWframebuffersizefun _glfw.glfwSetFramebufferSizeCallback.argtypes = [ctypes.POINTER(_GLFWwindow), _GLFWframebuffersizefun] def set_framebuffer_size_callback(window, cbfun): """ Sets the framebuffer resize callback for the specified window. Wrapper for: GLFWframebuffersizefun glfwSetFramebufferSizeCallback(GLFWwindow* window, GLFWframebuffersizefun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _framebuffer_size_callback_repository: previous_callback = _framebuffer_size_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWframebuffersizefun(cbfun) _framebuffer_size_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetFramebufferSizeCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0] _glfw.glfwPollEvents.restype = None _glfw.glfwPollEvents.argtypes = [] def poll_events(): """ Processes all pending events. Wrapper for: void glfwPollEvents(void); """ _glfw.glfwPollEvents() _glfw.glfwWaitEvents.restype = None _glfw.glfwWaitEvents.argtypes = [] def wait_events(): """ Waits until events are pending and processes them. Wrapper for: void glfwWaitEvents(void); """ _glfw.glfwWaitEvents() _glfw.glfwGetInputMode.restype = ctypes.c_int _glfw.glfwGetInputMode.argtypes = [ctypes.POINTER(_GLFWwindow), ctypes.c_int] def get_input_mode(window, mode): """ Returns the value of an input option for the specified window. Wrapper for: int glfwGetInputMode(GLFWwindow* window, int mode); """ return _glfw.glfwGetInputMode(window, mode) _glfw.glfwSetInputMode.restype = None _glfw.glfwSetInputMode.argtypes = [ctypes.POINTER(_GLFWwindow), ctypes.c_int, ctypes.c_int] def set_input_mode(window, mode, value): """ Sets an input option for the specified window. @param[in] window The window whose input mode to set. @param[in] mode One of `GLFW_CURSOR`, `GLFW_STICKY_KEYS` or `GLFW_STICKY_MOUSE_BUTTONS`. @param[in] value The new value of the specified input mode. Wrapper for: void glfwSetInputMode(GLFWwindow* window, int mode, int value); """ _glfw.glfwSetInputMode(window, mode, value) _glfw.glfwGetKey.restype = ctypes.c_int _glfw.glfwGetKey.argtypes = [ctypes.POINTER(_GLFWwindow), ctypes.c_int] def get_key(window, key): """ Returns the last reported state of a keyboard key for the specified window. Wrapper for: int glfwGetKey(GLFWwindow* window, int key); """ return _glfw.glfwGetKey(window, key) _glfw.glfwGetMouseButton.restype = ctypes.c_int _glfw.glfwGetMouseButton.argtypes = [ctypes.POINTER(_GLFWwindow), ctypes.c_int] def get_mouse_button(window, button): """ Returns the last reported state of a mouse button for the specified window. Wrapper for: int glfwGetMouseButton(GLFWwindow* window, int button); """ return _glfw.glfwGetMouseButton(window, button) _glfw.glfwGetCursorPos.restype = None _glfw.glfwGetCursorPos.argtypes = [ctypes.POINTER(_GLFWwindow), ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double)] def get_cursor_pos(window): """ Retrieves the last reported cursor position, relative to the client area of the window. Wrapper for: void glfwGetCursorPos(GLFWwindow* window, double* xpos, double* ypos); """ xpos_value = ctypes.c_double(0.0) xpos = ctypes.pointer(xpos_value) ypos_value = ctypes.c_double(0.0) ypos = ctypes.pointer(ypos_value) _glfw.glfwGetCursorPos(window, xpos, ypos) return xpos_value.value, ypos_value.value _glfw.glfwSetCursorPos.restype = None _glfw.glfwSetCursorPos.argtypes = [ctypes.POINTER(_GLFWwindow), ctypes.c_double, ctypes.c_double] def set_cursor_pos(window, xpos, ypos): """ Sets the position of the cursor, relative to the client area of the window. Wrapper for: void glfwSetCursorPos(GLFWwindow* window, double xpos, double ypos); """ _glfw.glfwSetCursorPos(window, xpos, ypos) _key_callback_repository = {} _callback_repositories.append(_key_callback_repository) _glfw.glfwSetKeyCallback.restype = _GLFWkeyfun _glfw.glfwSetKeyCallback.argtypes = [ctypes.POINTER(_GLFWwindow), _GLFWkeyfun] def set_key_callback(window, cbfun): """ Sets the key callback. Wrapper for: GLFWkeyfun glfwSetKeyCallback(GLFWwindow* window, GLFWkeyfun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _key_callback_repository: previous_callback = _key_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWkeyfun(cbfun) _key_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetKeyCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0] _char_callback_repository = {} _callback_repositories.append(_char_callback_repository) _glfw.glfwSetCharCallback.restype = _GLFWcharfun _glfw.glfwSetCharCallback.argtypes = [ctypes.POINTER(_GLFWwindow), _GLFWcharfun] def set_char_callback(window, cbfun): """ Sets the Unicode character callback. Wrapper for: GLFWcharfun glfwSetCharCallback(GLFWwindow* window, GLFWcharfun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _char_callback_repository: previous_callback = _char_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWcharfun(cbfun) _char_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetCharCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0] _mouse_button_callback_repository = {} _callback_repositories.append(_mouse_button_callback_repository) _glfw.glfwSetMouseButtonCallback.restype = _GLFWmousebuttonfun _glfw.glfwSetMouseButtonCallback.argtypes = [ctypes.POINTER(_GLFWwindow), _GLFWmousebuttonfun] def set_mouse_button_callback(window, cbfun): """ Sets the mouse button callback. Wrapper for: GLFWmousebuttonfun glfwSetMouseButtonCallback(GLFWwindow* window, GLFWmousebuttonfun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _mouse_button_callback_repository: previous_callback = _mouse_button_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWmousebuttonfun(cbfun) _mouse_button_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetMouseButtonCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0] _cursor_pos_callback_repository = {} _callback_repositories.append(_cursor_pos_callback_repository) _glfw.glfwSetCursorPosCallback.restype = _GLFWcursorposfun _glfw.glfwSetCursorPosCallback.argtypes = [ctypes.POINTER(_GLFWwindow), _GLFWcursorposfun] def set_cursor_pos_callback(window, cbfun): """ Sets the cursor position callback. Wrapper for: GLFWcursorposfun glfwSetCursorPosCallback(GLFWwindow* window, GLFWcursorposfun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _cursor_pos_callback_repository: previous_callback = _cursor_pos_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWcursorposfun(cbfun) _cursor_pos_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetCursorPosCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0] _cursor_enter_callback_repository = {} _callback_repositories.append(_cursor_enter_callback_repository) _glfw.glfwSetCursorEnterCallback.restype = _GLFWcursorenterfun _glfw.glfwSetCursorEnterCallback.argtypes = [ctypes.POINTER(_GLFWwindow), _GLFWcursorenterfun] def set_cursor_enter_callback(window, cbfun): """ Sets the cursor enter/exit callback. Wrapper for: GLFWcursorenterfun glfwSetCursorEnterCallback(GLFWwindow* window, GLFWcursorenterfun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _cursor_enter_callback_repository: previous_callback = _cursor_enter_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWcursorenterfun(cbfun) _cursor_enter_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetCursorEnterCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0] _scroll_callback_repository = {} _callback_repositories.append(_scroll_callback_repository) _glfw.glfwSetScrollCallback.restype = _GLFWscrollfun _glfw.glfwSetScrollCallback.argtypes = [ctypes.POINTER(_GLFWwindow), _GLFWscrollfun] def set_scroll_callback(window, cbfun): """ Sets the scroll callback. Wrapper for: GLFWscrollfun glfwSetScrollCallback(GLFWwindow* window, GLFWscrollfun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _scroll_callback_repository: previous_callback = _scroll_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWscrollfun(cbfun) _scroll_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetScrollCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0] _glfw.glfwJoystickPresent.restype = ctypes.c_int _glfw.glfwJoystickPresent.argtypes = [ctypes.c_int] def joystick_present(joy): """ Returns whether the specified joystick is present. Wrapper for: int glfwJoystickPresent(int joy); """ return _glfw.glfwJoystickPresent(joy) _glfw.glfwGetJoystickAxes.restype = ctypes.POINTER(ctypes.c_float) _glfw.glfwGetJoystickAxes.argtypes = [ctypes.c_int, ctypes.POINTER(ctypes.c_int)] def get_joystick_axes(joy): """ Returns the values of all axes of the specified joystick. Wrapper for: const float* glfwGetJoystickAxes(int joy, int* count); """ count_value = ctypes.c_int(0) count = ctypes.pointer(count_value) result = _glfw.glfwGetJoystickAxes(joy, count) return result, count_value.value _glfw.glfwGetJoystickButtons.restype = ctypes.POINTER(ctypes.c_ubyte) _glfw.glfwGetJoystickButtons.argtypes = [ctypes.c_int, ctypes.POINTER(ctypes.c_int)] def get_joystick_buttons(joy): """ Returns the state of all buttons of the specified joystick. Wrapper for: const unsigned char* glfwGetJoystickButtons(int joy, int* count); """ count_value = ctypes.c_int(0) count = ctypes.pointer(count_value) result = _glfw.glfwGetJoystickButtons(joy, count) return result, count_value.value _glfw.glfwGetJoystickName.restype = ctypes.c_char_p _glfw.glfwGetJoystickName.argtypes = [ctypes.c_int] def get_joystick_name(joy): """ Returns the name of the specified joystick. Wrapper for: const char* glfwGetJoystickName(int joy); """ return _glfw.glfwGetJoystickName(joy) _glfw.glfwSetClipboardString.restype = None _glfw.glfwSetClipboardString.argtypes = [ctypes.POINTER(_GLFWwindow), ctypes.c_char_p] def set_clipboard_string(window, string): """ Sets the clipboard to the specified string. Wrapper for: void glfwSetClipboardString(GLFWwindow* window, const char* string); """ _glfw.glfwSetClipboardString(window, _to_char_p(string)) _glfw.glfwGetClipboardString.restype = ctypes.c_char_p _glfw.glfwGetClipboardString.argtypes = [ctypes.POINTER(_GLFWwindow)] def get_clipboard_string(window): """ Retrieves the contents of the clipboard as a string. Wrapper for: const char* glfwGetClipboardString(GLFWwindow* window); """ return _glfw.glfwGetClipboardString(window) _glfw.glfwGetTime.restype = ctypes.c_double _glfw.glfwGetTime.argtypes = [] def get_time(): """ Returns the value of the GLFW timer. Wrapper for: double glfwGetTime(void); """ return _glfw.glfwGetTime() _glfw.glfwSetTime.restype = None _glfw.glfwSetTime.argtypes = [ctypes.c_double] def set_time(time): """ Sets the GLFW timer. Wrapper for: void glfwSetTime(double time); """ _glfw.glfwSetTime(time) _glfw.glfwMakeContextCurrent.restype = None _glfw.glfwMakeContextCurrent.argtypes = [ctypes.POINTER(_GLFWwindow)] def make_context_current(window): """ Makes the context of the specified window current for the calling thread. Wrapper for: void glfwMakeContextCurrent(GLFWwindow* window); """ _glfw.glfwMakeContextCurrent(window) _glfw.glfwGetCurrentContext.restype = ctypes.POINTER(_GLFWwindow) _glfw.glfwGetCurrentContext.argtypes = [] def get_current_context(): """ Returns the window whose context is current on the calling thread. Wrapper for: GLFWwindow* glfwGetCurrentContext(void); """ return _glfw.glfwGetCurrentContext() _glfw.glfwSwapBuffers.restype = None _glfw.glfwSwapBuffers.argtypes = [ctypes.POINTER(_GLFWwindow)] def swap_buffers(window): """ Swaps the front and back buffers of the specified window. Wrapper for: void glfwSwapBuffers(GLFWwindow* window); """ _glfw.glfwSwapBuffers(window) _glfw.glfwSwapInterval.restype = None _glfw.glfwSwapInterval.argtypes = [ctypes.c_int] def swap_interval(interval): """ Sets the swap interval for the current context. Wrapper for: void glfwSwapInterval(int interval); """ _glfw.glfwSwapInterval(interval) _glfw.glfwExtensionSupported.restype = ctypes.c_int _glfw.glfwExtensionSupported.argtypes = [ctypes.c_char_p] def extension_supported(extension): """ Returns whether the specified extension is available. Wrapper for: int glfwExtensionSupported(const char* extension); """ return _glfw.glfwExtensionSupported(_to_char_p(extension)) _glfw.glfwGetProcAddress.restype = ctypes.c_void_p _glfw.glfwGetProcAddress.argtypes = [ctypes.c_char_p] def get_proc_address(procname): """ Returns the address of the specified function for the current context. Wrapper for: GLFWglproc glfwGetProcAddress(const char* procname); """ return _glfw.glfwGetProcAddress(_to_char_p(procname)) if hasattr(_glfw, 'glfwSetDropCallback'): _window_drop_callback_repository = {} _callback_repositories.append(_window_drop_callback_repository) _glfw.glfwSetDropCallback.restype = _GLFWdropfun _glfw.glfwSetDropCallback.argtypes = [ctypes.POINTER(_GLFWwindow), _GLFWdropfun] def set_drop_callback(window, cbfun): """ Sets the file drop callback. Wrapper for: GLFWdropfun glfwSetDropCallback(GLFWwindow* window, GLFWdropfun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _window_drop_callback_repository: previous_callback = _window_drop_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 else: def cb_wrapper(window, count, c_paths, cbfun=cbfun): paths = [c_paths[i].decode('utf-8') for i in range(count)] cbfun(window, paths) cbfun = cb_wrapper c_cbfun = _GLFWdropfun(cbfun) _window_drop_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetDropCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0] if hasattr(_glfw, 'glfwSetCharModsCallback'): _window_char_mods_callback_repository = {} _callback_repositories.append(_window_char_mods_callback_repository) _glfw.glfwSetCharModsCallback.restype = _GLFWcharmodsfun _glfw.glfwSetCharModsCallback.argtypes = [ctypes.POINTER(_GLFWwindow), _GLFWcharmodsfun] def set_char_mods_callback(window, cbfun): """ Sets the Unicode character with modifiers callback. Wrapper for: GLFWcharmodsfun glfwSetCharModsCallback(GLFWwindow* window, GLFWcharmodsfun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if window_addr in _window_char_mods_callback_repository: previous_callback = _window_char_mods_callback_repository[window_addr] else: previous_callback = None if cbfun is None: cbfun = 0 c_cbfun = _GLFWcharmodsfun(cbfun) _window_char_mods_callback_repository[window_addr] = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetCharModsCallback(window, cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0] if hasattr(_glfw, 'glfwVulkanSupported'): _glfw.glfwVulkanSupported.restype = ctypes.c_int _glfw.glfwVulkanSupported.argtypes = [] def vulkan_supported(): """ Returns whether the Vulkan loader has been found. Wrapper for: int glfwVulkanSupported(void); """ return _glfw.glfwVulkanSupported() != 0 if hasattr(_glfw, 'glfwGetRequiredInstanceExtensions'): _glfw.glfwGetRequiredInstanceExtensions.restype = ctypes.POINTER(ctypes.c_char_p) _glfw.glfwGetRequiredInstanceExtensions.argtypes = [ctypes.POINTER(ctypes.c_uint32)] def get_required_instance_extensions(): """ Returns the Vulkan instance extensions required by GLFW. Wrapper for: const char** glfwGetRequiredInstanceExtensions(uint32_t* count); """ count_value = ctypes.c_uint32(0) count = ctypes.pointer(count_value) c_extensions = _glfw.glfwGetRequiredInstanceExtensions(count) count = count_value.value extensions = [c_extensions[i].decode('utf-8') for i in range(count)] return extensions if hasattr(_glfw, 'glfwGetTimerValue'): _glfw.glfwGetTimerValue.restype = ctypes.c_uint64 _glfw.glfwGetTimerValue.argtypes = [] def get_timer_value(): """ Returns the current value of the raw timer. Wrapper for: uint64_t glfwGetTimerValue(void); """ return int(_glfw.glfwGetTimerValue()) if hasattr(_glfw, 'glfwGetTimerFrequency'): _glfw.glfwGetTimerFrequency.restype = ctypes.c_uint64 _glfw.glfwGetTimerFrequency.argtypes = [] def get_timer_frequency(): """ Returns the frequency, in Hz, of the raw timer. Wrapper for: uint64_t glfwGetTimerFrequency(void); """ return int(_glfw.glfwGetTimerFrequency()) if hasattr(_glfw, 'glfwSetJoystickCallback'): _joystick_callback = None _glfw.glfwSetJoystickCallback.restype = _GLFWjoystickfun _glfw.glfwSetJoystickCallback.argtypes = [_GLFWjoystickfun] def set_joystick_callback(cbfun): """ Sets the error callback. Wrapper for: GLFWjoystickfun glfwSetJoystickCallback(GLFWjoystickfun cbfun); """ global _joystick_callback previous_callback = _error_callback if cbfun is None: cbfun = 0 c_cbfun = _GLFWjoystickfun(cbfun) _joystick_callback = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetJoystickCallback(cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0] if hasattr(_glfw, 'glfwGetKeyName'): _glfw.glfwGetKeyName.restype = ctypes.c_char_p _glfw.glfwGetKeyName.argtypes = [ctypes.c_int, ctypes.c_int] def get_key_name(key, scancode): """ Returns the localized name of the specified printable key. Wrapper for: const char* glfwGetKeyName(int key, int scancode); """ key_name = _glfw.glfwGetKeyName(key, scancode) if key_name: return key_name.decode('utf-8') return None if hasattr(_glfw, 'glfwCreateCursor'): _glfw.glfwCreateCursor.restype = ctypes.POINTER(_GLFWcursor) _glfw.glfwCreateCursor.argtypes = [ctypes.POINTER(_GLFWimage), ctypes.c_int, ctypes.c_int] def create_cursor(image, xhot, yhot): """ Creates a custom cursor. Wrapper for: GLFWcursor* glfwCreateCursor(const GLFWimage* image, int xhot, int yhot); """ c_image = _GLFWimage() c_image.wrap(image) return _glfw.glfwCreateCursor(ctypes.pointer(c_image), xhot, yhot) if hasattr(_glfw, 'glfwCreateStandardCursor'): _glfw.glfwCreateStandardCursor.restype = ctypes.POINTER(_GLFWcursor) _glfw.glfwCreateStandardCursor.argtypes = [ctypes.c_int] def create_standard_cursor(shape): """ Creates a cursor with a standard shape. Wrapper for: GLFWcursor* glfwCreateStandardCursor(int shape); """ return _glfw.glfwCreateStandardCursor(shape) if hasattr(_glfw, 'glfwDestroyCursor'): _glfw.glfwDestroyCursor.restype = None _glfw.glfwDestroyCursor.argtypes = [ctypes.POINTER(_GLFWcursor)] def destroy_cursor(cursor): """ Destroys a cursor. Wrapper for: void glfwDestroyCursor(GLFWcursor* cursor); """ _glfw.glfwDestroyCursor(cursor) if hasattr(_glfw, 'glfwSetCursor'): _glfw.glfwSetCursor.restype = None _glfw.glfwSetCursor.argtypes = [ctypes.POINTER(_GLFWwindow), ctypes.POINTER(_GLFWcursor)] def set_cursor(window, cursor): """ Sets the cursor for the window. Wrapper for: void glfwSetCursor(GLFWwindow* window, GLFWcursor* cursor); """ _glfw.glfwSetCursor(window, cursor) if hasattr(_glfw, 'glfwCreateWindowSurface'): _glfw.glfwCreateWindowSurface.restype = ctypes.c_int _glfw.glfwCreateWindowSurface.argtypes = [ctypes.c_void_p, ctypes.POINTER(_GLFWwindow), ctypes.c_void_p, ctypes.c_void_p] def create_window_surface(instance, window, allocator, surface): """ Creates a Vulkan surface for the specified window. Wrapper for: VkResult glfwCreateWindowSurface(VkInstance instance, GLFWwindow* window, const VkAllocationCallbacks* allocator, VkSurfaceKHR* surface); """ return _glfw.glfwCreateWindowSurface(instance, window, allocator, surface) if hasattr(_glfw, 'glfwGetPhysicalDevicePresentationSupport'): _glfw.glfwGetPhysicalDevicePresentationSupport.restype = ctypes.c_int _glfw.glfwGetPhysicalDevicePresentationSupport.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint32] def get_physical_device_presentation_support(instance, device, queuefamily): """ Creates a Vulkan surface for the specified window. Wrapper for: int glfwGetPhysicalDevicePresentationSupport(VkInstance instance, VkPhysicalDevice device, uint32_t queuefamily); """ return _glfw.glfwGetPhysicalDevicePresentationSupport(instance, device, queuefamily) if hasattr(_glfw, 'glfwGetInstanceProcAddress'): _glfw.glfwGetInstanceProcAddress.restype = ctypes.c_void_p _glfw.glfwGetInstanceProcAddress.argtypes = [ctypes.c_void_p, ctypes.c_char_p] def get_instance_proc_address(instance, procname): """ Returns the address of the specified Vulkan instance function. Wrapper for: GLFWvkproc glfwGetInstanceProcAddress(VkInstance instance, const char* procname); """ return _glfw.glfwGetInstanceProcAddress(instance, procname) if hasattr(_glfw, 'glfwSetWindowIcon'): _glfw.glfwSetWindowIcon.restype = None _glfw.glfwSetWindowIcon.argtypes = [ctypes.POINTER(_GLFWwindow), ctypes.c_int, ctypes.POINTER(_GLFWimage)] def set_window_icon(window, count, image): """ Sets the icon for the specified window. Wrapper for: void glfwSetWindowIcon(GLFWwindow* window, int count, const GLFWimage* images); """ _image = _GLFWimage() _image.wrap(image) _glfw.glfwSetWindowIcon(window, count, ctypes.pointer(_image)) if hasattr(_glfw, 'glfwSetWindowSizeLimits'): _glfw.glfwSetWindowSizeLimits.restype = None _glfw.glfwSetWindowSizeLimits.argtypes = [ctypes.POINTER(_GLFWwindow), ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int] def set_window_size_limits(window, minwidth, minheight, maxwidth, maxheight): """ Sets the size limits of the specified window. Wrapper for: void glfwSetWindowSizeLimits(GLFWwindow* window, int minwidth, int minheight, int maxwidth, int maxheight); """ _glfw.glfwSetWindowSizeLimits(window, minwidth, minheight, maxwidth, maxheight) if hasattr(_glfw, 'glfwSetWindowAspectRatio'): _glfw.glfwSetWindowAspectRatio.restype = None _glfw.glfwSetWindowAspectRatio.argtypes = [ctypes.POINTER(_GLFWwindow), ctypes.c_int, ctypes.c_int] def set_window_aspect_ratio(window, numer, denom): """ Sets the aspect ratio of the specified window. Wrapper for: void glfwSetWindowAspectRatio(GLFWwindow* window, int numer, int denom); """ _glfw.glfwSetWindowAspectRatio(window, numer, denom) if hasattr(_glfw, 'glfwGetWindowFrameSize'): _glfw.glfwGetWindowFrameSize.restype = None _glfw.glfwGetWindowFrameSize.argtypes = [ctypes.POINTER(_GLFWwindow), ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int)] def set_get_window_frame_size(window): """ Retrieves the size of the frame of the window. Wrapper for: void glfwGetWindowFrameSize(GLFWwindow* window, int* left, int* top, int* right, int* bottom); """ left = ctypes.c_int(0) top = ctypes.c_int(0) right = ctypes.c_int(0) bottom = ctypes.c_int(0) _glfw.glfwGetWindowFrameSize(window, ctypes.pointer(left), ctypes.pointer(top), ctypes.pointer(right), ctypes.pointer(bottom)) return left.value, top.value, right.value, bottom.value if hasattr(_glfw, 'glfwMaximizeWindow'): _glfw.glfwMaximizeWindow.restype = None _glfw.glfwMaximizeWindow.argtypes = [ctypes.POINTER(_GLFWwindow)] def maximize_window(window): """ Maximizes the specified window. Wrapper for: void glfwMaximizeWindow(GLFWwindow* window); """ _glfw.glfwMaximizeWindow(window) if hasattr(_glfw, 'glfwFocusWindow'): _glfw.glfwFocusWindow.restype = None _glfw.glfwFocusWindow.argtypes = [ctypes.POINTER(_GLFWwindow)] def focus_window(window): """ Brings the specified window to front and sets input focus. Wrapper for: void glfwFocusWindow(GLFWwindow* window); """ _glfw.glfwFocusWindow(window) if hasattr(_glfw, 'glfwSetWindowMonitor'): _glfw.glfwSetWindowMonitor.restype = None _glfw.glfwSetWindowMonitor.argtypes = [ctypes.POINTER(_GLFWwindow), ctypes.POINTER(_GLFWmonitor), ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int] def set_window_monitor(window, monitor, xpos, ypos, width, height, refresh_rate): """ Sets the mode, monitor, video mode and placement of a window. Wrapper for: void glfwSetWindowMonitor(GLFWwindow* window, GLFWmonitor* monitor, int xpos, int ypos, int width, int height, int refreshRate); """ _glfw.glfwSetWindowMonitor(window, monitor, xpos, ypos, width, height, refresh_rate) if hasattr(_glfw, 'glfwWaitEventsTimeout'): _glfw.glfwWaitEventsTimeout.restype = None _glfw.glfwWaitEventsTimeout.argtypes = [ctypes.c_double] def wait_events_timeout(timeout): """ Waits with timeout until events are queued and processes them. Wrapper for: void glfwWaitEventsTimeout(double timeout); """ _glfw.glfwWaitEventsTimeout(timeout) if hasattr(_glfw, 'glfwPostEmptyEvent'): _glfw.glfwPostEmptyEvent.restype = None _glfw.glfwPostEmptyEvent.argtypes = [] def post_empty_event(): """ Posts an empty event to the event queue. Wrapper for: void glfwPostEmptyEvent(); """ _glfw.glfwPostEmptyEvent() _prepare_errcheck()
ronhandler/gitroot
pyglfw/glfw.py
Python
unlicense
77,583
#include "simpleWebSocket.h" #ifndef DEPENDING #include PROXYMSGS_PB_H #endif #include <map> #include <pthread.h> #include <unistd.h> #include <fcntl.h> #define DEBUG false void *connection_thread(void*arg); int main() { SimpleWebSocket::WebSocketServer srv(1081, INADDR_ANY, DEBUG); if (srv.ok() == false) { printf("server setup fail\n"); return 3; } while (1) { SimpleWebSocket::WebSocketServerConn *nc = srv.handle_accept(); if (nc) { pthread_t id; pthread_create(&id, NULL, &connection_thread, (void*) nc); } } return 0; } pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int conns_pos = 1; std::map<int,SimpleWebSocket::WebSocketServerConn *> conns; void *connection_thread(void*arg) { ::proxyTcp::ProxyMsg msg; SimpleWebSocket::WebSocketServerConn *nc = (SimpleWebSocket::WebSocketServerConn *) arg; printf("got connection\n"); pthread_mutex_lock(&mutex); int pos = conns_pos++; conns[pos] = nc; pthread_mutex_unlock(&mutex); int fd = nc->get_fd(); fcntl( fd, F_SETFL, fcntl( fd, F_GETFL, 0 ) | O_NONBLOCK ); bool doselect = false; bool done = false; while (!done) { if (doselect) { bool doservice = false; while (!doservice) { fd_set rfds; struct timeval tv; FD_ZERO(&rfds); FD_SET(fd, &rfds); tv.tv_sec = 1; // 1 second polling tv.tv_usec = 0; (void) select(fd+1, &rfds, NULL, NULL, &tv); if (FD_ISSET(fd, &rfds)) doservice = true; } } SimpleWebSocket::WebSocketRet ret = nc->handle_read(msg); switch (ret) { case SimpleWebSocket::WEBSOCKET_CONNECTED: { std::string path; doselect = false; nc->get_path(path); printf("WebSocket connected! path = '%s'\n", path.c_str()); msg.Clear(); msg.set_type(proxyTcp::PMT_PROTOVERSION); msg.set_sequence(0); msg.mutable_protover()->set_version(1); nc->sendMessage(msg); break; } case SimpleWebSocket::WEBSOCKET_NO_MESSAGE: // go round again doselect = true; break; case SimpleWebSocket::WEBSOCKET_MESSAGE: doselect = false; switch (msg.type()) { case proxyTcp::PMT_PROTOVERSION: printf("remote proto version = %d\n", msg.protover().version()); break; case proxyTcp::PMT_CLOSING: printf("remote side is closing, so we are too\n"); done = true; break; case proxyTcp::PMT_DATA: { printf("got data length %d\n", (int) msg.data().data().size()); pthread_mutex_lock(&mutex); for (int ind = 0; ind < conns_pos; ind++) if (ind != pos && conns[ind] != NULL) { conns[ind]->sendMessage(msg); } pthread_mutex_unlock(&mutex); break; } case proxyTcp::PMT_PING: printf("got ping\n"); break; default: printf("msg.type() = %d\n", msg.type()); } break; case SimpleWebSocket::WEBSOCKET_CLOSED: printf("WebSocket closed!\n"); done = true; break; } } printf("closing connection\n"); pthread_mutex_lock(&mutex); conns[pos] = NULL; pthread_mutex_unlock(&mutex); delete nc; return NULL; }
flipk/pfkutils
libWebAppServer/simpleWsTestServer.cc
C++
unlicense
3,939
var GamesList = React.createClass({ getInitialState: function() { return { games: this.props.initialGames }; }, scoreChanged: function(gameId, teamNumber, score) { var game = this.state.games.filter(function(game) { return game.id == gameId; })[0]; game['pool_entry_' + teamNumber + '_score'] = score; this.setState({games:this.state.games}); }, saveGames: function() { $.ajax({ url: 'admin/bracket/score/save', dataType: 'json', data: csrf({games: this.state.games}), cache: false, method: 'post', success: function(data) { // show a spinner instead alert('saved'); }.bind(this), }); }, render: function() { var that = this; var games = this.state.games.map(function(game) { return ( <Game game={game} teams={that.props.teams} rolls={that.props.rolls} key={game.id} scoreChanged={that.scoreChanged}/> ); }); return ( <div> <h2>Round {this.props.round}</h2> {games} <button onClick={this.saveGames}>Save</button> </div> ); } }); var Game = React.createClass({ getInitialState : function() { if (!this.props.game.pool_entry_1_score) { this.props.game.pool_entry_1_score = ''; } if (!this.props.game.pool_entry_2_score) { this.props.game.pool_entry_2_score = ''; } return this.props.game; }, scoreChanged: function(e) { this.props.scoreChanged(this.state.id, e.target.dataset.team, e.target.value); }, render: function() { var team1Name; var team2Name; var state = this.state; this.props.teams.forEach(function(team) { if (team.id == state.pool_entry_1_id) { team1Name = team.name; } if (team.id == state.pool_entry_2_id) { team2Name = team.name; } }); var team1Roll, team2Roll; this.props.rolls.forEach(function(roll) { if (roll.rank == state.pool_entry_1_rank) { team1Roll = roll.roll; } if (roll.rank == state.pool_entry_2_rank) { team2Roll = roll.roll; } }); return ( <div className="game"> <div className="team"><div className="team-name">{team1Name} ({this.state.pool_entry_1_rank} : {team1Roll})</div> <input type="text" value={this.state.pool_entry_1_score} onChange={this.scoreChanged} data-team="1"/></div> <div className="team"><div className="team-name">{team2Name} ({this.state.pool_entry_2_rank} : {team2Roll})</div> <input type="text" value={this.state.pool_entry_2_score} onChange={this.scoreChanged} data-team="2"/></div> </div> ) } }); var teams = globals.pools[0].teams.concat(globals.pools[1].teams.concat(globals.pools[2].teams.concat(globals.pools[3].teams.concat()))); ReactDOM.render( <div> <a href={'admin/bracket/' + globals.bracket.id}>Back To Bracket</a> <GamesList initialGames={globals.games} round={globals.round} teams={teams} rolls={globals.rolls}/> </div>, document.getElementById('bracket-round') );
austinhaws/custom-bracket
public/js/views/bracket-round.js
JavaScript
unlicense
2,838
var bcrypt = require('bcrypt-nodejs'); var crypto = require('crypto'); var mongoose = require('mongoose'); var userSchema = new mongoose.Schema({ email: { type: String, unique: true, lowercase: true }, password: String, facebook: String, twitter: String, google: String, github: String, instagram: String, linkedin: String, tokens: Array, profile: { name: { type: String, default: '' }, gender: { type: String, default: '' }, location: { type: String, default: '' }, website: { type: String, default: '' }, picture: { type: String, default: '' } }, /* * Data related to the Cards. * This should be moved to a separate table * as soon more than one language is supported */ cardsLastGenerated: Date, //have we generated cards for this user today lastWordUsed: { type: Number, default: 0 }, //last word offset from database resetPasswordToken: String, resetPasswordExpires: Date }); /** * Password hashing Mongoose middleware. */ userSchema.pre('save', function(next) { var user = this; if (!user.isModified('password')) { return next(); } bcrypt.genSalt(5, function(err, salt) { if (err) { return next(err); } bcrypt.hash(user.password, salt, null, function(err, hash) { if (err) { return next(err); } user.password = hash; next(); }); }); }); /** * Helper method for validationg user's password. */ userSchema.methods.comparePassword = function(candidatePassword, cb) { bcrypt.compare(candidatePassword, this.password, function(err, isMatch) { if (err) { return cb(err); } cb(null, isMatch); }); }; /** * Helper method for getting user's gravatar. */ userSchema.methods.gravatar = function(size) { if (!size) { size = 200; } if (!this.email) { return 'https://gravatar.com/avatar/?s=' + size + '&d=retro'; } var md5 = crypto.createHash('md5').update(this.email).digest('hex'); return 'https://gravatar.com/avatar/' + md5 + '?s=' + size + '&d=retro'; }; module.exports = mongoose.model('User', userSchema);
guilhermeasg/outspeak
models/User.js
JavaScript
unlicense
2,102
define([ 'app', 'collections/tables', 'collections/connections', 'collections/rdf-entities', 'collections/rdf-attributes', 'models/connection', 'models/table', 'views/abstract/base', 'views/shared/message-dialog', 'views/editor/connection-form', 'views/editor/rdf-entity-list', 'views/editor/rdf-attribute-list', 'views/editor/table-list', 'views/editor/table' ], function( app, TablesCollection, ConnectionsCollection, RdfEntitiesCollection, RdfAttributesCollection, ConnectionModel, TableModel, BaseView, MessageDialogView, ConnectionFormView, RdfEntityListView, RdfAttributeListView, TableListView, TableView ) { 'use strict'; var EditorView = BaseView.extend({ className: 'editor container', template: app.fetchTemplate('editor/editor'), events: { 'click .entity-breadcrumb': 'onEntityBreadcrumbClick', 'click .rdf-settings-icon': 'onRdfSettingsIconClick', 'change .rdf-settings input': 'onRdfSettingsInputChange' }, settingsSlideSpeed: 150, initialize: function(options) { options = options || {}; this.conn = new ConnectionModel(); this.table = new TableModel(); this.tables = new TablesCollection(); this.connections = new ConnectionsCollection(); this.rdfEntities = new RdfEntitiesCollection(); this.rdfAttributes = new RdfAttributesCollection(); this.connectionForm = new ConnectionFormView({ connections: this.connections, conn: this.conn }); this.rdfEntityListView = new RdfEntityListView({ collection: this.rdfEntities }); this.rdfAttributeListView = new RdfAttributeListView({ collection: this.rdfAttributes }); this.tableView = new TableView({ model: this.table, rdfAttributes: this.rdfAttributes, rdfEntities: this.rdfEntities }); this.tableListView = new TableListView({ collection: this.tables }); this.tables.fetch({ reset: true }); window.tables = this.tables; $(document).on('click', _.bind(function(e) { if (!$(e.target).hasClass('rdf-settings')) { this.$('.rdf-settings').slideUp(this.settingsSlideSpeed); } }, this)); }, setListeners: function() { BaseView.prototype.setListeners.call(this); this.listenTo(this.conn, 'connect:success', this.onConnect, this); this.listenTo(this.conn, 'disconnect', this.onDisconnect, this); this.listenTo(this.rdfEntityListView, 'selected-item:change', this.onRdfEntityListSelectedItemChange, this); this.listenTo(this.tableListView, 'item:select', this.onTableListItemSelect, this); this.listenTo(this.rdfEntityListView, 'item:branch', this.onRdfEntityListItemBranch, this); this.listenTo(this.table, 'save:success', this.onTableSaveSuccess, this); this.listenTo(this.table, 'save:error', this.defaultActionErrorHandler, this); this.listenTo(this.table, 'save:validationError', this.onTableValidationError, this); this.listenTo(this.table, 'delete:success', this.onTableDeleteSuccess, this); this.listenTo(this.table, 'delete:error', this.defaultActionErrorHandler, this); this.listenTo(this.rdfEntities, 'change:parents', this.onRdfEntitiesParentsChange, this); }, onConnect: function() { this.$('.editor-rdf').slideDown().addClass('collapsed'); this.$('.editor-rdf-title .collapse-arrow').addClass('collapsed'); this.$('.editor-connection').slideUp().removeClass('collapsed'); this.$('.editor-connection-title .collapse-arrow').removeClass('collapsed'); this.rdfEntities.setEndpoint(this.conn.get('endpoint')); this.rdfAttributes.setEndpoint(this.conn.get('endpoint')); this.rdfEntities.fetch(); }, onDisconnect: function() { this.$('.editor-rdf').slideUp().removeClass('collapsed'); this.$('.editor-rdf-title .collapse-arrow').removeClass('collapsed'); this.$('.editor-connection').slideDown().addClass('collapsed'); this.$('.editor-connection-title .collapse-arrow').addClass('collapsed'); this.rdfEntities.reset(); this.rdfAttributes.reset(); }, render: function() { this.$el.html(this.template({ attributesLimit: this.rdfAttributes.limit, attributesOffset: this.rdfAttributes.offset, attributesSort: this.rdfAttributes.sorting, entitiesLimit: this.rdfEntities.limit, entitiesOffset: this.rdfEntities.offset, entitiesLoadRootAttributes: this.rdfEntities.loadRootAttributes })); this.$('.editor-connection-form').html(this.connectionForm.render().$el); this.$('.editor-rdf-entity-list-container').html(this.rdfEntityListView.render().$el); this.$('.editor-rdf-attribute-list-container').html(this.rdfAttributeListView.render().$el); this.$('.editor-table-list-container').html(this.tableListView.render().$el); this.$('.editor-table-container').html(this.tableView.render().$el); this.$('.editor-rdf').resizable({ handles: 's', minHeight: 100, maxHeight: 500 }); this.$('.editor-connection-title').on('click', _.bind(function() { if (this.$('.editor-connection').hasClass('collapsed')) { this.$('.editor-connection').slideUp().removeClass('collapsed'); } else { this.$('.editor-connection').slideDown().addClass('collapsed'); } this.$('.editor-connection-title .collapse-arrow').toggleClass('collapsed'); }, this)); this.$('.editor-rdf-title').on('click', _.bind(function() { if (this.conn.get('connected')) { if (this.$('.editor-rdf').hasClass('collapsed')) { this.$('.editor-rdf').slideUp().removeClass('collapsed'); } else { this.$('.editor-rdf').slideDown().addClass('collapsed'); } this.$('.editor-rdf-title .collapse-arrow').toggleClass('collapsed'); } }, this)); this.$('.editor-relational-title').on('click', _.bind(function() { if (this.$('.editor-relational').hasClass('collapsed')) { this.$('.editor-relational').slideUp().removeClass('collapsed'); } else { this.$('.editor-relational').slideDown().addClass('collapsed'); } this.$('.editor-relational-title .collapse-arrow').toggleClass('collapsed'); }, this)); this.setListeners(); return this; }, onRdfEntitiesParentsChange: function() { var parents = this.rdfEntities.getParentLabels(); var $breadcrumbs = this.$('.entity-breadcrumbs').html('Entities: '); for (var i = 0; i < this.rdfEntities.parents.length; i++) { if (i > 0) { $breadcrumbs.append('<img class="breadcrumb-divider" src="assets/images/arrow_right.png"></img>'); } var en = this.rdfEntities.parents[i]; var $en = $('<li>').addClass('entity-breadcrumb').attr('data-uri', en.get('uri')).html(en.get('label')); $breadcrumbs.append($en); } }, onRdfEntityListSelectedItemChange: function(rdfEntity) { this.rdfAttributes.setRdfEntity(rdfEntity); if (this.rdfEntities.shouldLoadAttributes()) { this.rdfAttributes.fetch(); } }, onTableListItemSelect: function(tableListItem, tableModel) { this.table = tableModel; this.tableView.setModel(tableModel); this.table.loadTableDefinition(); }, onTableDelete: function(model) { (new MessageDialogView()).showMessage('', 'Your relational table has been removed'); this.tables.remove(this.tables.findWhere({ name: model.get('name') })); }, onTableSaveSuccess: function(model) { (new MessageDialogView()).showSuccessMessage('Your relational table has been saved'); this.tables.add(model); }, onEntityBreadcrumbClick: function(e) { var uri = $(e.target).attr('data-uri'); this.rdfEntities.setParentEntityUri(uri); }, onRdfSettingsIconClick: function(e) { var $sett = $(e.target).find('.rdf-settings'); if ($sett.css('display') === 'block') { $sett.slideUp(this.settingsSlideSpeed); } else { $sett.slideDown(this.settingsSlideSpeed); } e.stopPropagation(); }, onRdfEntityListItemBranch: function(itemView, rdfEntity) { this.rdfEntities.setParentEntity(rdfEntity); }, onRdfSettingsInputChange: function(e) { var $input = $(e.target); if ($input.attr('data-type') === 'entities') { if ($input.attr('data-property') === 'limit') { this.rdfEntities.setLimit(parseInt($input.val(), 10)); } else if ($input.attr('data-property') === 'offset') { this.rdfEntities.setOffset(parseInt($input.val(), 10)); } else { this.rdfEntities.setLoadRootAttributes($input.prop('checked')); } } else { if ($input.attr('data-property') === 'limit') { this.rdfAttributes.setLimit(parseInt($input.val(), 10)); } else if ($input.attr('data-property') === 'sort') { this.rdfAttributes.setSort($input.prop('checked')); } else { this.rdfAttributes.setOffset(parseInt($input.val(), 10)); } } this.$('.rdf-settings').slideUp(this.settingsSlideSpeed); } }); return EditorView; });
ilucin/relsem-bridge-frontend
app/views/editor/editor.js
JavaScript
unlicense
9,433
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Helloworld { public static void main(String[] args) { Scanner scan = new Scanner(System.in); // use the Scanner class to read from stdin String inputString = scan.nextLine(); // read a line of input and save it to a variable scan.close(); // close the scanner // Your first line of output goes here System.out.println("Hello, World."); // Write the second line of output System.out.println(inputString); } }
jerryasher/hackerrank30
0/Helloworld.java
Java
unlicense
588
#include "Mesh.h" #include "SyntopiaCore/Math/Vector3.h" #include "../Logging/Logging.h" using namespace SyntopiaCore::Logging; using namespace SyntopiaCore::Math; namespace SyntopiaCore { namespace GLEngine { Mesh::Mesh(SyntopiaCore::Math::Vector3f startBase, SyntopiaCore::Math::Vector3f startDir1 , SyntopiaCore::Math::Vector3f startDir2, SyntopiaCore::Math::Vector3f endBase, SyntopiaCore::Math::Vector3f endDir1 , SyntopiaCore::Math::Vector3f endDir2) : startBase(startBase), startDir1(startDir1), startDir2(startDir2), endBase(endBase), endDir1(endDir1), endDir2(endDir2) { /// Bounding Mesh (not really accurate) from = startBase; to = endBase; }; Mesh::~Mesh() { }; void Mesh::draw() const { // --- TODO: Rewrite - way to many state changes... glPushMatrix(); glTranslatef( startBase.x(), startBase.y(), startBase.z() ); GLfloat col[4] = {0.0f, 1.0f, 1.0f, 0.1f} ; glMaterialfv( GL_FRONT, GL_AMBIENT_AND_DIFFUSE, col ); glPolygonMode(GL_FRONT, GL_FILL); glPolygonMode(GL_BACK, GL_FILL); Vector3f O(0,0,0); Vector3f end = endBase - startBase; glEnable (GL_LIGHTING); glDisable(GL_CULL_FACE); // TODO: do we need this? glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); GLfloat c3[4] = {0.3f, 0.3f, 0.3f, 0.5f}; glMaterialfv( GL_FRONT, GL_SPECULAR, c3 ); glMateriali(GL_FRONT, GL_SHININESS, 127); glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE); glEnable(GL_COLOR_MATERIAL); glBegin( GL_QUADS ); glColor4fv(primaryColor); GLfloat secondaryColor[4] = {oldRgb[0], oldRgb[1], oldRgb[2], oldAlpha}; //vertex4n(O, startDir1,startDir2+startDir1,startDir2); Vector3f c1(startDir1*0.5f+startDir2*0.5f); Vector3f c2(end+endDir1*0.5f+endDir2*0.5f); vertex4(primaryColor, c1, O, startDir1, secondaryColor,c2, end+endDir1,end,false); vertex4(primaryColor,c1, O, startDir2, secondaryColor,c2, end+endDir2,end,false); vertex4(primaryColor,c1, startDir1, startDir1+startDir2,secondaryColor,c2, end+endDir1+endDir2, end+endDir1,false); vertex4(primaryColor,c1, startDir2, startDir1+startDir2,secondaryColor,c2, end+endDir1+endDir2, end+endDir2,false); //vertex4n(O+end, endDir1+end,endDir2+endDir1+end,endDir2+end); glEnd(); glDisable(GL_COLOR_MATERIAL); glPopMatrix(); }; bool Mesh::intersectsRay(RayInfo* ri) { if (triangles.count()==0) initTriangles(); for (int i = 0; i < triangles.count(); i++) { if (triangles[i].intersectsRay(ri)) return true; } return false; }; void Mesh::initTriangles() { triangles.clear(); RaytraceTriangle::Vertex4(startBase, startBase+startDir1,endBase+endDir1,endBase, true,triangles,primaryColor[0],primaryColor[1],primaryColor[2],primaryColor[3]); RaytraceTriangle::Vertex4(startBase, endBase,endBase+endDir2,startBase+startDir2, true,triangles,primaryColor[0],primaryColor[1],primaryColor[2],primaryColor[3]); RaytraceTriangle::Vertex4(startBase+startDir1, startBase+startDir1+startDir2, endBase+endDir1+endDir2, endBase+endDir1, true,triangles,primaryColor[0],primaryColor[1],primaryColor[2],primaryColor[3]); RaytraceTriangle::Vertex4(startBase+startDir2, endBase+endDir2, endBase+endDir1+endDir2, startBase+startDir1+startDir2, true,triangles,primaryColor[0],primaryColor[1],primaryColor[2],primaryColor[3]); from = startBase; to = startBase; for (int i = 0; i < triangles.count(); i++) { triangles[i].expandBoundingBox(from,to); } } bool Mesh::intersectsAABB(Vector3f from2, Vector3f to2) { if (triangles.count()==0) initTriangles(); return (from.x() < to2.x()) && (to.x() > from2.x()) && (from.y() < to2.y()) && (to.y() > from2.y()) && (from.z() < to2.z()) && (to.z() > from2.z()); }; } }
mike10004/nbis-upstream
misc/nistmeshlab/meshlab/src/external/structuresynth/ssynth/SyntopiaCore/GLEngine/Mesh.cpp
C++
unlicense
4,001
package tasks; import java.util.ArrayList; import listeners.SuperMapListener; import mapstuff.CartographersMap; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scheduler.BukkitRunnable; import plugin.SuperMap; public class ConstantZoneCheck extends BukkitRunnable { public ConstantZoneCheck(JavaPlugin plugin,SuperMapListener sml) { this.plugin = plugin; this.sml=sml; playerList=new ArrayList<String>(); enabled=true; dead=false; } private ConstantZoneCheck(JavaPlugin plugin, ArrayList<String> l){ this.plugin=plugin; playerList=l; } public void disableMapCheck(){ enabled=false; } public void enableMapCheck(){ enabled=true; } public void run() { if(!enabled){ cancel(); dead=true; } Player p; for(String player:playerList){ p=Bukkit.getPlayer(player); if(p.getItemInHand().hasItemMeta()&&p.getItemInHand().getType().equals(Material.MAP)){ if(p.getItemInHand().getItemMeta().getDisplayName().equals("Cartographer's Map")){ //this is where i do the zone checks try{ CartographersMap cm=SuperMap.mapItemToCMap.get(Integer.valueOf(p.getItemInHand().getDurability())); cm.mapCheck(p.getLocation(),p); }catch(NullPointerException npe){ CartographersMap cm=new CartographersMap(p,p.getItemInHand(),sml); cm.mapCheck(p.getLocation(), p); } } } } } public void addPlayer(Player p){ if(!playerList.contains(p.getDisplayName())){ playerList.add(p.getDisplayName()); } } public void removePlayer(Player p){ playerList.remove(p.getDisplayName()); } public ConstantZoneCheck clone(){ ConstantZoneCheck newczc =new ConstantZoneCheck(plugin,playerList); newczc.enabled=enabled; newczc.dead=false; return newczc; } public boolean isDead(){ return dead; } private final JavaPlugin plugin; private SuperMapListener sml; private ArrayList <String> playerList; private boolean enabled,dead; }
GarrettCG/SuperMap
src/tasks/ConstantZoneCheck.java
Java
unlicense
2,587
package crazypants.enderio.machine.farm; import crazypants.enderio.config.Config; import crazypants.enderio.machine.farm.farmers.*; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import cpw.mods.fml.common.registry.GameRegistry; public final class FarmersRegistry { public static final PlantableFarmer DEFAULT_FARMER = new PlantableFarmer(); public static void addFarmers() { addExtraUtilities(); addNatura(); addTiC(); addStillHungry(); addIC2(); addMFR(); addThaumcraft(); FarmersCommune.joinCommune(new StemFarmer(Blocks.reeds, new ItemStack(Items.reeds))); FarmersCommune.joinCommune(new StemFarmer(Blocks.cactus, new ItemStack(Blocks.cactus))); FarmersCommune.joinCommune(new TreeFarmer(Blocks.sapling, Blocks.log)); FarmersCommune.joinCommune(new TreeFarmer(Blocks.sapling, Blocks.log2)); FarmersCommune.joinCommune(new TreeFarmer(true,Blocks.red_mushroom, Blocks.red_mushroom_block)); FarmersCommune.joinCommune(new TreeFarmer(true,Blocks.brown_mushroom, Blocks.brown_mushroom_block)); //special case of plantables to get spacing correct FarmersCommune.joinCommune(new MelonFarmer(Blocks.melon_stem, Blocks.melon_block, new ItemStack(Items.melon_seeds))); FarmersCommune.joinCommune(new MelonFarmer(Blocks.pumpkin_stem, Blocks.pumpkin, new ItemStack(Items.pumpkin_seeds))); //'BlockNetherWart' is not an IGrowable FarmersCommune.joinCommune(new NetherWartFarmer()); //Cocoa is odd FarmersCommune.joinCommune(new CocoaFarmer()); //Handles all 'vanilla' style crops FarmersCommune.joinCommune(DEFAULT_FARMER); } public static void addPickable(String mod, String blockName, String itemName) { Block cropBlock = GameRegistry.findBlock(mod, blockName); if(cropBlock != null) { Item seedItem = GameRegistry.findItem(mod, itemName); if(seedItem != null) { FarmersCommune.joinCommune(new PickableFarmer(cropBlock, new ItemStack(seedItem))); } } } public static CustomSeedFarmer addSeed(String mod, String blockName, String itemName, Block... extraFarmland) { Block cropBlock = GameRegistry.findBlock(mod, blockName); if(cropBlock != null) { Item seedItem = GameRegistry.findItem(mod, itemName); if(seedItem != null) { CustomSeedFarmer farmer = new CustomSeedFarmer(cropBlock, new ItemStack(seedItem)); if(extraFarmland != null) { for (Block farmland : extraFarmland) { if(farmland != null) { farmer.addTilledBlock(farmland); } } } FarmersCommune.joinCommune(farmer); return farmer; } } return null; } private static void addTiC() { String mod = "TConstruct"; String blockName = "ore.berries.two"; Block cropBlock = GameRegistry.findBlock(mod, blockName); if(cropBlock != null) { Item seedItem = GameRegistry.findItem(mod, blockName); if(seedItem != null) { for (int i = 0; i < 2; i++) { PickableFarmer farmer = new NaturaBerryFarmer(cropBlock, i, 12 + i, new ItemStack(seedItem, 1, 8 + i)); farmer.setRequiresFarmland(false); FarmersCommune.joinCommune(farmer); } } } blockName = "ore.berries.one"; cropBlock = GameRegistry.findBlock(mod, blockName); if(cropBlock != null) { Item seedItem = GameRegistry.findItem(mod, blockName); if(seedItem != null) { for (int i = 0; i < 4; i++) { PickableFarmer farmer = new NaturaBerryFarmer(cropBlock, i, 12 + i, new ItemStack(seedItem, 1, 8 + i)); farmer.setRequiresFarmland(false); FarmersCommune.joinCommune(farmer); } } } } private static void addNatura() { String mod = "Natura"; String blockName = "N Crops"; Block cropBlock = GameRegistry.findBlock(mod, blockName); if(cropBlock != null) { DEFAULT_FARMER.addHarvestExlude(cropBlock); Item seedItem = GameRegistry.findItem(mod, "barley.seed"); if(seedItem != null) { //barley FarmersCommune.joinCommune(new CustomSeedFarmer(cropBlock, 3, new ItemStack(seedItem))); // cotton FarmersCommune.joinCommune(new PickableFarmer(cropBlock, 4, 8, new ItemStack(seedItem, 1, 1))); } } blockName = "BerryBush"; cropBlock = GameRegistry.findBlock(mod, blockName); if(cropBlock != null) { Item seedItem = GameRegistry.findItem(mod, blockName); if(seedItem != null) { for (int i = 0; i < 4; i++) { PickableFarmer farmer = new NaturaBerryFarmer(cropBlock, i, 12 + i, new ItemStack(seedItem, 1, 12 + i)); farmer.setRequiresFarmland(false); FarmersCommune.joinCommune(farmer); } } } blockName = "florasapling"; Block saplingBlock = GameRegistry.findBlock(mod, blockName); if(saplingBlock != null) { FarmersCommune.joinCommune(new TreeFarmer(saplingBlock, GameRegistry.findBlock(mod, "tree"), GameRegistry.findBlock(mod, "willow"), GameRegistry.findBlock(mod, "Dark Tree"))); } blockName = "Rare Sapling"; saplingBlock = GameRegistry.findBlock(mod, blockName); if(saplingBlock != null) { FarmersCommune.joinCommune(new TreeFarmer(saplingBlock, GameRegistry.findBlock(mod, "Rare Tree"))); } } private static void addThaumcraft() { String mod = "Thaumcraft"; String manaBean = "ItemManaBean"; String manaPod = "blockManaPod"; Block block = GameRegistry.findBlock(mod,manaPod); Item item = GameRegistry.findItem(mod,manaBean); if (Config.farmManaBeansEnabled && block!=null && item!=null) { FarmersCommune.joinCommune(new ManaBeanFarmer(block, new ItemStack(item))); } } private static void addMFR() { String mod = "MineFactoryReloaded"; String blockName = "rubberwood.sapling"; Block saplingBlock = GameRegistry.findBlock(mod, blockName); if(saplingBlock != null) { FarmersCommune.joinCommune(new TreeFarmer(saplingBlock, GameRegistry.findBlock(mod, "rubberwood.log"))); } } private static void addIC2() { RubberTreeFarmerIC2 rtf = new RubberTreeFarmerIC2(); if(rtf.isValid()) { FarmersCommune.joinCommune(rtf); } } private static void addStillHungry() { String mod = "stillhungry"; addPickable(mod, "grapeBlock", "StillHungry_grapeSeed"); } private static void addExtraUtilities() { String mod = "ExtraUtilities"; String name = "plant/ender_lilly"; CustomSeedFarmer farmer = addSeed(mod, name, name, Blocks.end_stone, GameRegistry.findBlock(mod, "decorativeBlock1")); if(farmer != null) { farmer.setIgnoreGroundCanSustainCheck(true); } } private FarmersRegistry() { } }
Vexatos/EnderIO
src/main/java/crazypants/enderio/machine/farm/FarmersRegistry.java
Java
unlicense
6,917
package com.ushaqi.zhuishushenqi.model; import com.ushaqi.zhuishushenqi.api.ApiService; import java.io.Serializable; import java.util.Date; public class UserInfo implements Serializable { private static final long serialVersionUID = 2519451769850149545L; private String _id; private String avatar; private UserInfo.BookListCount book_list_count; private String code; private int exp; private String gender; private boolean genderChanged; private int lv; private String nickname; private Date nicknameUpdated; private boolean ok; private UserInfo.UserPostCount post_count; private float rank; private UserInfo.ThisWeekTasks this_week_tasks; private UserInfo.UserTodayTask today_tasks; public String getAvatar() { return this.avatar; } public UserInfo.BookListCount getBook_list_count() { return this.book_list_count; } public String getCode() { return this.code; } public int getExp() { return this.exp; } public String getGender() { return this.gender; } public String getId() { return this._id; } public int getLv() { return this.lv; } public String getNickname() { return this.nickname; } public Date getNicknameUpdated() { return this.nicknameUpdated; } public UserInfo.UserPostCount getPost_count() { return this.post_count; } public float getRank() { return this.rank; } public String getScaleAvatar(int paramInt) { if (paramInt == 2) return ApiService.a + this.avatar + "-avatarl"; return ApiService.a + this.avatar + "-avatars"; } public UserInfo.ThisWeekTasks getThis_week_tasks() { return this.this_week_tasks; } public UserInfo.UserTodayTask getToday_tasks() { return this.today_tasks; } public boolean isGenderChanged() { return this.genderChanged; } public boolean isOk() { return this.ok; } public void setAvatar(String paramString) { this.avatar = paramString; } public void setBook_list_count(UserInfo.BookListCount paramBookListCount) { this.book_list_count = paramBookListCount; } public void setCode(String paramString) { this.code = paramString; } public void setExp(int paramInt) { this.exp = paramInt; } public void setGender(String paramString) { this.gender = paramString; } public void setGenderChanged(boolean paramBoolean) { this.genderChanged = paramBoolean; } public void setId(String paramString) { this._id = paramString; } public void setLv(int paramInt) { this.lv = paramInt; } public void setNickname(String paramString) { this.nickname = paramString; } public void setNicknameUpdated(Date paramDate) { this.nicknameUpdated = paramDate; } public void setOk(boolean paramBoolean) { this.ok = paramBoolean; } public void setPost_count(UserInfo.UserPostCount paramUserPostCount) { this.post_count = paramUserPostCount; } public void setRank(float paramFloat) { this.rank = paramFloat; } public void setThis_week_tasks(UserInfo.ThisWeekTasks paramThisWeekTasks) { this.this_week_tasks = paramThisWeekTasks; } public void setToday_tasks(UserInfo.UserTodayTask paramUserTodayTask) { this.today_tasks = paramUserTodayTask; } } /* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar * Qualified Name: com.ushaqi.zhuishushenqi.model.UserInfo * JD-Core Version: 0.6.0 */
clilystudio/NetBook
allsrc/com/ushaqi/zhuishushenqi/model/UserInfo.java
Java
unlicense
3,520
#include "GameTextures.h" #include <iostream> GameTextures::GameTextures() { if (!_image.loadFromFile("assets/DungeonCrawl_ProjectUtumnoTileset.png")) { std::cout << "Error loading texture." << std::endl; } } std::shared_ptr<sf::Texture> GameTextures::getTexture(std::string name, int x, int y) { std::cout << "Loading " << name << std::endl; auto texture = _textures.find(name); if (texture == _textures.end()) { _textures[name]=getTexture(x, y); } return _textures[name]; } std::shared_ptr<sf::Texture> GameTextures::getTexture(int x, int y) { auto texture = std::make_shared<sf::Texture>(); texture->loadFromImage(_image, sf::IntRect(x*32, y*32, 32, 32)); texture->setRepeated(true); return texture; }
UAF-CS372-Spring-2015/the-platformer
src/GameTextures.cpp
C++
unlicense
744
a = 'a|b|c|d|e' b = a.split('|', 3) print(b) """< ['a', 'b', 'c', 'd|e'] >"""
pythonpatterns/patterns
p0081.py
Python
unlicense
81
package Chap05; /* * ÀÛ¼ºÀÏÀÚ:2017_03_09 * ÀÛ¼ºÀÚ:±æ°æ¿Ï * ThreeArrays ÀÌ¿ë * ¿¹Á¦ 5-43 */ public class StaticInitalizerExample2 { public static void main(String[] args){ for(int cnt=0;cnt<10;cnt++){ System.out.println(ThreeArrays.arr3[cnt]); } } }
WALDOISCOMING/Java_Study
Java_BP/src/Chap05/StaticInitalizerExample2.java
Java
unlicense
279
//============================================================================== #include <hgeresource.h> #include <hgefont.h> #include <hgesprite.h> #include <sqlite3.h> #include <Database.h> #include <Query.h> #include <score.hpp> #include <engine.hpp> //------------------------------------------------------------------------------ Score::Score( Engine * engine ) : Context( engine ), m_dark( 0 ), m_calculate( false ), m_lives( 0 ), m_urchins( 0 ), m_coins( 0 ), m_time( 0 ), m_timer( 0.0f ), m_buffer( 0 ), m_high_score() { } //------------------------------------------------------------------------------ Score::~Score() { } //------------------------------------------------------------------------------ // public: //------------------------------------------------------------------------------ void Score::init() { hgeResourceManager * rm( m_engine->getResourceManager() ); m_dark = new hgeSprite( 0, 0, 0, 1, 1 ); m_calculate = false; HMUSIC music = m_engine->getResourceManager()->GetMusic( "score" ); m_engine->getHGE()->Music_Play( music, true, 100, 0, 0 ); _updateScore(); } //------------------------------------------------------------------------------ void Score::fini() { m_engine->getHGE()->Channel_StopAll(); delete m_dark; m_dark = 0; } //------------------------------------------------------------------------------ bool Score::update( float dt ) { HGE * hge( m_engine->getHGE() ); hgeResourceManager * rm( m_engine->getResourceManager() ); hgeParticleManager * pm( m_engine->getParticleManager() ); if ( hge->Input_GetKey() != 0 && ! m_engine->isPaused() && ! m_calculate ) { m_engine->switchContext( STATE_MENU ); } if ( m_engine->isPaused() ) { return false; } if ( m_calculate ) { m_timer += dt; if ( static_cast< int >( m_timer * 1000.0f ) % 2 == 0 ) { if ( m_buffer > 0 ) { m_buffer -= 1; m_coins += 1; float x( hge->Random_Float( 550.0f, 560.0f ) ); float y( hge->Random_Float( 268.0f, 278.0f ) ); hgeParticleSystem * particle = pm->SpawnPS(& rm->GetParticleSystem("collect")->info, x, y); if ( particle != 0 ) { particle->SetScale( 1.0f ); } hge->Effect_Play( rm->GetEffect( "bounce" ) ); } else if ( m_lives > 0 ) { m_lives -= 1; m_buffer += 100; hge->Effect_Play( rm->GetEffect( "collect" ) ); } else if ( m_urchins > 0 ) { m_urchins -= 1; m_buffer += 10; hge->Effect_Play( rm->GetEffect( "collect" ) ); } else if ( m_time > 0 ) { m_time -= 7; if ( m_time < 0 ) { m_time = 0; } m_buffer += 1; hge->Effect_Play( rm->GetEffect( "collect" ) ); } } if ( m_buffer == 0 && m_lives == 0 && m_urchins == 0 && m_time == 0 ) { int character( hge->Input_GetChar() ); if ( character != 0 ) { if ( ( character == ' ' || character == '.' || character == '!' || character == '?' || ( character >= '0' && character <= '9' ) || ( character >= 'a' && character <= 'z' ) || ( character >= 'A' && character <= 'Z' ) ) && m_name.size() <= 15 ) { m_name.push_back( character ); } } if ( hge->Input_KeyDown( HGEK_BACKSPACE ) || hge->Input_KeyDown( HGEK_DELETE ) ) { if ( m_name.size() > 0 ) { m_name.erase( m_name.end() - 1 ); } } if ( hge->Input_KeyDown( HGEK_ENTER ) ) { if ( m_name.size() == 0 ) { m_name = "Anonymous"; } Database db( "world.db3" ); Query q( db ); char query[1024]; sprintf_s( query, 1024, "INSERT INTO score(name, coins) " "VALUES('%s',%d)", m_name.c_str(), m_coins ); q.execute( query ); _updateScore(); m_calculate = false; } } } else if ( dt > 0.0f && hge->Random_Float( 0.0f, 1.0f ) < 0.07f ) { float x( hge->Random_Float( 0.0f, 800.0f ) ); float y( hge->Random_Float( 0.0f, 600.0f ) ); hgeParticleSystem * particle = pm->SpawnPS( & rm->GetParticleSystem( "explode" )->info, x, y ); particle->SetScale( hge->Random_Float( 0.5f, 2.0f ) ); } return false; } //------------------------------------------------------------------------------ void Score::render() { hgeResourceManager * rm( m_engine->getResourceManager() ); if ( ! m_calculate ) { m_engine->getParticleManager()->Render(); } m_dark->SetColor( 0xCC000309 ); m_dark->RenderStretch( 100.0f, 50.0f, 700.0f, 550.0f ); hgeFont * font( rm->GetFont( "menu" ) ); if ( m_calculate ) { font->printf( 400.0f, 80.0f, HGETEXT_CENTER, "G A M E O V E R" ); font->printf( 200.0f, 200.0f, HGETEXT_LEFT, "x %d", m_lives ); font->printf( 200.0f, 260.0f, HGETEXT_LEFT, "x %02d/99", m_urchins ); font->printf( 200.0f, 320.0f, HGETEXT_LEFT, "%03d", m_time ); font->printf( 580.0f, 260.0f, HGETEXT_LEFT, "x %04d", m_coins ); m_engine->getParticleManager()->Render(); rm->GetSprite( "ship" )->Render( 175.0f, 213.0f ); rm->GetSprite( "coin")->SetColor( 0xFFFFFFFF ); rm->GetSprite( "coin" )->Render( 555.0f, 273.0f ); rm->GetSprite( "urchin_green" )->Render( 175.0f, 273.0f ); if ( m_buffer == 0 && m_lives == 0 && m_urchins == 0 && m_time == 0 ) { font->printf( 400.0f, 400.0f, HGETEXT_CENTER, "%s", m_name.c_str() ); font->printf( 400.0f, 500.0f, HGETEXT_CENTER, "(well done, you)" ); if ( static_cast<int>( m_timer * 2.0f ) % 2 != 0 ) { float width = font->GetStringWidth( m_name.c_str() ); m_dark->SetColor( 0xFFFFFFFF ); m_dark->RenderStretch( 400.0f + width * 0.5f, 425.0f, 400.0f + width * 0.5f + 16.0f, 427.0f ); } } } else { font->printf( 400.0f, 80.0f, HGETEXT_CENTER, "H I G H S C O R E T A B L E" ); int i = 0; std::vector< std::pair< std::string, int > >::iterator j; for ( j = m_high_score.begin(); j != m_high_score.end(); ++j ) { i += 1; font->printf( 200.0f, 120.0f + i * 30.0f, HGETEXT_LEFT, "(%d)", i ); font->printf( 400.0f, 120.0f + i * 30.0f, HGETEXT_CENTER, "%s", j->first.c_str() ); font->printf( 600.0f, 120.0f + i * 30.0f, HGETEXT_RIGHT, "%04d", j->second ); } font->printf( 400.0f, 500.0f, HGETEXT_CENTER, "(but you're all winners, really)" ); } } //------------------------------------------------------------------------------ void Score::calculateScore( int lives, int urchins, int coins, int time ) { m_timer = 0.0f; m_buffer = 0; m_calculate = true; m_lives = lives; m_urchins = urchins; m_coins = coins; m_time = time; if ( lives == 0 || urchins == 0 ) { m_time = 0; } m_name.clear(); if ( m_lives == 0 && m_time == 0 && m_coins == 0 && m_urchins == 0 ) { m_calculate = false; } } //------------------------------------------------------------------------------ // private: //------------------------------------------------------------------------------ void Score::_updateScore() { m_high_score.clear(); Database db( "world.db3" ); Query q( db ); q.get_result("SELECT coins, name FROM score ORDER BY coins DESC LIMIT 10"); while ( q.fetch_row() ) { std::pair< std::string, int > pair( q.getstr(), q.getval() ); m_high_score.push_back( pair ); } q.free_result(); }
jasonhutchens/thrust_harder
score.cpp
C++
unlicense
9,032
/* * SmartGWT Mobile * Copyright 2008 and beyond, Isomorphic Software, Inc. * * SmartGWT Mobile is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3 * as published by the Free Software Foundation. SmartGWT Mobile is also * available under typical commercial license terms - see * http://smartclient.com/license * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ /** * */ package com.smartgwt.mobile.client.widgets.tab; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.History; import com.google.gwt.user.client.Timer; import com.smartgwt.mobile.SGWTInternal; import com.smartgwt.mobile.client.core.Function; import com.smartgwt.mobile.client.data.Record; import com.smartgwt.mobile.client.data.RecordList; import com.smartgwt.mobile.client.internal.EventHandler; import com.smartgwt.mobile.client.internal.theme.TabSetCssResourceBase; import com.smartgwt.mobile.client.internal.util.AnimationUtil; import com.smartgwt.mobile.client.internal.widgets.tab.TabSetItem; import com.smartgwt.mobile.client.theme.ThemeResources; import com.smartgwt.mobile.client.types.SelectionStyle; import com.smartgwt.mobile.client.types.TableMode; import com.smartgwt.mobile.client.widgets.Canvas; import com.smartgwt.mobile.client.widgets.ContainerFeatures; import com.smartgwt.mobile.client.widgets.Panel; import com.smartgwt.mobile.client.widgets.PanelContainer; import com.smartgwt.mobile.client.widgets.ScrollablePanel; import com.smartgwt.mobile.client.widgets.events.DropEvent; import com.smartgwt.mobile.client.widgets.events.DropHandler; import com.smartgwt.mobile.client.widgets.events.HasDropHandlers; import com.smartgwt.mobile.client.widgets.events.HasPanelHideHandlers; import com.smartgwt.mobile.client.widgets.events.HasPanelShowHandlers; import com.smartgwt.mobile.client.widgets.events.PanelHideEvent; import com.smartgwt.mobile.client.widgets.events.PanelHideHandler; import com.smartgwt.mobile.client.widgets.events.PanelShowEvent; import com.smartgwt.mobile.client.widgets.events.PanelShowHandler; import com.smartgwt.mobile.client.widgets.grid.CellFormatter; import com.smartgwt.mobile.client.widgets.grid.ListGridField; import com.smartgwt.mobile.client.widgets.icons.IconResources; import com.smartgwt.mobile.client.widgets.layout.HLayout; import com.smartgwt.mobile.client.widgets.layout.Layout; import com.smartgwt.mobile.client.widgets.layout.NavStack; import com.smartgwt.mobile.client.widgets.tab.events.HasTabDeselectedHandlers; import com.smartgwt.mobile.client.widgets.tab.events.HasTabSelectedHandlers; import com.smartgwt.mobile.client.widgets.tab.events.TabDeselectedEvent; import com.smartgwt.mobile.client.widgets.tab.events.TabDeselectedHandler; import com.smartgwt.mobile.client.widgets.tab.events.TabSelectedEvent; import com.smartgwt.mobile.client.widgets.tab.events.TabSelectedHandler; import com.smartgwt.mobile.client.widgets.tableview.TableView; import com.smartgwt.mobile.client.widgets.tableview.events.RecordNavigationClickEvent; import com.smartgwt.mobile.client.widgets.tableview.events.RecordNavigationClickHandler; public class TabSet extends Layout implements PanelContainer, HasTabSelectedHandlers, HasTabDeselectedHandlers, HasPanelShowHandlers, HasPanelHideHandlers, HasDropHandlers { @SGWTInternal public static final TabSetCssResourceBase _CSS = ThemeResources.INSTANCE.tabsCSS(); private static final int NO_TAB_SELECTED = -1, MORE_TAB_SELECTED = -2; private static class More extends NavStack { private static final String ID_PROPERTY = "_id", ICON_PROPERTY = "icon", TAB_PROPERTY = "tab"; private static final ListGridField TITLE_FIELD = new ListGridField("-title") {{ setCellFormatter(new CellFormatter() { @Override public String format(Object value, Record record, int rowNum, int fieldNum) { final Tab tab = (Tab)record.getAttributeAsObject(TAB_PROPERTY); if (tab.getTitle() != null) return tab.getTitle(); final Canvas pane = tab.getPane(); if (pane != null) return pane.getTitle(); return null; } }); }}; private static int nextMoreRecordID = 1; private static Record createMoreRecord(Tab tab) { assert tab != null; final Canvas pane = tab.getPane(); final Record record = new Record(); record.setAttribute(ID_PROPERTY, Integer.toString(nextMoreRecordID++)); Object icon = tab.getIcon(); if (icon == null && pane instanceof Panel) { icon = ((Panel)pane).getIcon(); } record.setAttribute(ICON_PROPERTY, icon); record.setAttribute(TAB_PROPERTY, tab); return record; } private ScrollablePanel morePanel; private RecordList recordList; private TableView tableView; private HandlerRegistration recordNavigationClickRegistration; //TileLayout tileLayout = null; public More() { super("More", IconResources.INSTANCE.more()); morePanel = new ScrollablePanel("More", IconResources.INSTANCE.more()); morePanel.getElement().getStyle().setBackgroundColor("#f7f7f7"); recordList = new RecordList(); tableView = new TableView(); tableView.setTitleField(TITLE_FIELD.getName()); tableView.setShowNavigation(true); tableView.setSelectionType(SelectionStyle.SINGLE); tableView.setParentNavStack(this); tableView.setTableMode(TableMode.PLAIN); tableView.setShowIcons(true); recordNavigationClickRegistration = tableView.addRecordNavigationClickHandler(new RecordNavigationClickHandler() { @Override public void onRecordNavigationClick(RecordNavigationClickEvent event) { final Record record = event.getRecord(); final Tab tab = (Tab)record.getAttributeAsObject(TAB_PROPERTY); final TabSet tabSet = tab.getTabSet(); assert tabSet != null; tabSet.swapTabs(recordList.indexOf(record) + tabSet.moreTabCount, tabSet.moreTabCount - 1); tabSet.selectTab(tabSet.moreTabCount - 1, true); } }); tableView.setFields(TITLE_FIELD); tableView.setData(recordList); morePanel.addMember(tableView); push(morePanel); } @Override public void destroy() { if (recordNavigationClickRegistration != null) { recordNavigationClickRegistration.removeHandler(); recordNavigationClickRegistration = null; } super.destroy(); } public final boolean containsNoTabs() { return recordList.isEmpty(); } public void addTab(Tab tab, int position) { if (tab == null) throw new NullPointerException("`tab' cannot be null."); final Record moreRecord = createMoreRecord(tab); recordList.add(position, moreRecord); } public Tab removeTab(int position) { return (Tab)recordList.remove(position).getAttributeAsObject(TAB_PROPERTY); } public void setTab(int position, Tab tab) { if (tab == null) throw new NullPointerException("`tab' cannot be null."); recordList.set(position, createMoreRecord(tab)); } public void swapTabs(int i, int j) { recordList.swap(i, j); } } private final List<Tab> tabs = new ArrayList<Tab>(); // Tab bar to show tab widgets private HLayout tabBar = new HLayout(); private int moreTabCount = 4; private boolean showMoreTab = true; private More more; private Tab moreTab; // paneContainer panel to hold tab panes private Layout paneContainer; //private final HashMap<Element, Tab> draggableMap = new HashMap<Element, Tab>(); //private Canvas draggable, droppable; // Currently selected tab private int selectedTabIndex = NO_TAB_SELECTED; private transient Timer clearHideTabBarDuringFocusTimer; public TabSet() { getElement().addClassName(_CSS.tabSetClass()); setWidth("100%"); setHeight("100%"); paneContainer = new Layout(); paneContainer._setClassName(_CSS.tabPaneClass(), false); addMember(paneContainer); tabBar._setClassName(_CSS.tabBarClass(), false); tabBar._setClassName("sc-layout-box-pack-center", false); addMember(tabBar); //sinkEvents(Event.ONCLICK | Event.ONMOUSEWHEEL | Event.GESTUREEVENTS | Event.TOUCHEVENTS | Event.MOUSEEVENTS | Event.FOCUSEVENTS | Event.KEYEVENTS); _sinkFocusInEvent(); _sinkFocusOutEvent(); } @SGWTInternal public final Tab _getMoreTab() { return moreTab; } public final Tab[] getTabs() { return tabs.toArray(new Tab[tabs.size()]); } /** * Sets the pane of the given tab. * * @param tab * @param pane */ public void updateTab(Tab tab, Canvas pane) { if (tab == null) throw new NullPointerException("`tab' cannot be null."); final TabSet otherTabSet = tab.getTabSet(); assert otherTabSet != null : "`tab' is not in any TabSet. In particular, it is not in this TabSet."; if (otherTabSet == null) { tab._setPane(pane); } else { assert this == otherTabSet : "`tab' is in a different TabSet."; if (this != otherTabSet) { assert otherTabSet != null; otherTabSet.updateTab(tab, pane); } else { final int tabPosition = getTabPosition(tab); if (tabPosition < 0) throw new IllegalArgumentException("`tab' is not in this TabSet."); updateTab(tabPosition, pane); } } } public void updateTab(int index, Canvas pane) throws IndexOutOfBoundsException { if (index < 0 || tabs.size() <= index) throw new IndexOutOfBoundsException("No tab exists at index " + index); final Tab tab = tabs.get(index); assert tab != null; final Canvas oldPane = tab.getPane(); if (oldPane != pane) { if (oldPane != null) paneContainer.removeMember(oldPane); if (pane != null) { paneContainer.addMember(pane); if (selectedTabIndex != index) paneContainer.hideMember(pane); } tab._setPane(pane); } } /******************************************************* * Event handler registrations ******************************************************/ /** * Add a tabSelected handler. * <p/> * Notification fired when a tab is selected. * * @param handler the tabSelectedHandler * @return {@link HandlerRegistration} used to remove this handler */ @Override public HandlerRegistration addTabSelectedHandler(TabSelectedHandler handler) { return addHandler(handler, TabSelectedEvent.getType()); } @Override public HandlerRegistration addDropHandler(DropHandler handler) { return addHandler(handler, DropEvent.getType()); } /** * Add a tabDeselected handler. * <p/> * Notification fired when a tab is unselected. * * @param handler the tabDeselectedHandler * @return {@link HandlerRegistration} used to remove this handler */ @Override public HandlerRegistration addTabDeselectedHandler(TabDeselectedHandler handler) { return addHandler(handler, TabDeselectedEvent.getType()); } /** * **************************************************** * Settings * **************************************************** */ @SuppressWarnings("unused") private Tab findTarget(Event event) { Tab tab = null; final int Y = (event.getTouches() != null && event.getTouches().length() > 0) ? event.getTouches().get(0).getClientY(): event.getClientY(); final int X = (event.getTouches() != null && event.getTouches().length() > 0) ? event.getTouches().get(0).getClientX(): event.getClientX(); if (Y >= tabBar.getAbsoluteTop() && !tabs.isEmpty()) { final int width = tabs.get(0)._getTabSetItem().getElement().getOffsetWidth(); final int index = X / width; if (0 <= index && ((showMoreTab && index < moreTabCount) || (!showMoreTab && index < tabs.size()))) { tab = tabs.get(index); } } return tab; } @Override public void onBrowserEvent(Event event) { /*switch(event.getTypeInt()) { case Event.ONMOUSEOVER: if (!touched) { if (draggable != null) { final Tab tab = findTarget(event); if (tab != null) { droppable = tab._getTabSetItem(); droppable.fireEvent(new DropOverEvent()); } else if (droppable != null) { droppable.fireEvent(new DropOutEvent()); droppable = null; } } } break; case Event.ONTOUCHMOVE: case Event.ONGESTURECHANGE: if (draggable != null) { final Tab tab = findTarget(event); if (tab != null) { droppable = tab._getTabSetItem(); droppable.fireEvent(new DropOverEvent()); } else if (droppable != null) { droppable.fireEvent(new DropOutEvent()); droppable = null; } } super.onBrowserEvent(event); break; case Event.ONMOUSEUP: if (!touched) { super.onBrowserEvent(event); if (more != null && more.tileLayout != null) { more.tileLayout.onEnd(event); } if (draggable != null && droppable != null) { droppable.fireEvent(new DropEvent(draggable)); droppable = null; } } break; case Event.ONTOUCHEND: case Event.ONGESTUREEND: super.onBrowserEvent(event); if (draggable != null && droppable != null) { droppable.fireEvent(new DropEvent(draggable)); droppable = null; } break; default: super.onBrowserEvent(event); break; }*/ if (Canvas._getHideTabBarDuringKeyboardFocus()) { // On Android devices, SGWT.mobile uses a technique similar to jQuery Mobile's hideDuringFocus // setting to fix the issue that the tabBar unnecessarily takes up a portion of the screen // when the soft keyboard is open. To work around this problem, when certain elements receive // keyboard focus, we add a special class to the TabSet element that hides the tabBar. // This special class is removed on focusout. // // One important consideration is that the user can move between input elements (such as // by using the Next/Previous buttons or by tapping on a different input) and the soft // keyboard will remain on screen. We don't want to show the tabBar only to hide it again. // See: JQM Issue 4724 - Moving through form in Mobile Safari with "Next" and "Previous" // system controls causes fixed position, tap-toggle false Header to reveal itself // https://github.com/jquery/jquery-mobile/issues/4724 final String eventType = event.getType(); if ("focusin".equals(eventType)) { if (EventHandler.couldShowSoftKeyboard(event)) { if (clearHideTabBarDuringFocusTimer != null) { clearHideTabBarDuringFocusTimer.cancel(); clearHideTabBarDuringFocusTimer = null; } getElement().addClassName(_CSS.hideTabBarDuringFocusClass()); } } else if ("focusout".equals(eventType)) { // If the related event target cannot result in the soft keyboard showing, then // there is no need to wait; we can remove the hideTabBarDuringFocus class now. if (event.getRelatedEventTarget() != null && !EventHandler.couldShowSoftKeyboard(event)) { if (clearHideTabBarDuringFocusTimer != null) { clearHideTabBarDuringFocusTimer.cancel(); clearHideTabBarDuringFocusTimer = null; } getElement().removeClassName(_CSS.hideTabBarDuringFocusClass()); // We use a timeout to clear the special CSS class because on Android 4.0.3 (possibly // affects other versions as well), there is an issue where tapping in the 48px above // the soft keyboard (where the tabBar would be) dismisses the soft keyboard. } else { clearHideTabBarDuringFocusTimer = new Timer() { @Override public void run() { clearHideTabBarDuringFocusTimer = null; getElement().removeClassName(_CSS.hideTabBarDuringFocusClass()); } }; clearHideTabBarDuringFocusTimer.schedule(1); } } } } @Override public void onLoad() { super.onLoad(); // There is a very strange `TabSet' issue on iOS 6 Mobile Safari, but which does not appear // in iOS 5.0 or 5.1. For some reason, if the tabSelectedClass() is added to a `TabSetItem', // but the selected class is removed before the `TabSetItem' element is added to the document // later on, then the SGWT.mobile app will fail to load. However, if Web Inspector is attached, // then the app runs fine. // // This issue affects Showcase. In Showcase, the "Overview" tab is first selected when // it is added to the app's `TabSet' instance. It is then deselected when the "Widgets" // tab is programmatically selected. // To see the issue, comment out the check `if (Canvas._isIOSMin6_0() && !isAttached()) return;' in TabSetItem.setSelected(), then // compile & run Showcase in iOS 6 Mobile Safari. if (Canvas._isIOSMin6_0() && selectedTabIndex > 0) { tabs.get(selectedTabIndex)._getTabSetItem().setSelected(true); } } /******************************************************* * Add/Remove tabs ******************************************************/ @SGWTInternal public void _onTabDrop(TabSetItem tabSetItem, DropEvent event) { /*Object source = event.getSource(); if(source instanceof Tab) { tab.getElement().getStyle().setProperty("backgroundImage", "none"); TileLayout.Tile draggable = (TileLayout.Tile)event.getData(); Record record = TabSet.this.more.recordList.find("title",draggable.getTitle()); if(record != null) { Panel newPanel = (Panel)record.get("panel"); final int currentPosition = tabBar.getMemberNumber(tab); TabSet.this.replacePanel(currentPosition, newPanel); TileLayout tileLayout = (TileLayout)more.top(); tileLayout.replaceTile(draggable, tab.getTitle(), tab.getIcon()); more.recordList.remove(record); // final Panel oldPanel = tab.getPane() instanceof NavStack ? ((NavStack)tab.getPane()).top() : (Panel)tab.getPane(); final Panel oldPanel = (Panel)tab.getPane(); oldPanel.getElement().getStyle().clearDisplay(); final Record finalRecord = record; more.recordList.add(0,new Record() {{put("_id", finalRecord.getAttribute("_id")); put("title", tab.getTitle()); put("icon", tab.getIcon());put("panel", oldPanel);}}); more.tableView.setData(more.recordList); } }*/ } private void swapTabs(int i, int j) { final int numTabs = tabs.size(); assert 0 <= i && i < numTabs; assert 0 <= j && j < numTabs; if (i == j) return; // Make sure that i < j. if (!(i < j)) { final int tmp = i; i = j; j = tmp; } assert i < j; final Tab tabI = tabs.get(i), tabJ = tabs.get(j); assert tabI != null && tabJ != null; final TabSetItem tabSetItemI = tabI._getTabSetItem(), tabSetItemJ = tabJ._getTabSetItem(); final Canvas paneI = tabI.getPane(), paneJ = tabJ.getPane(); tabs.set(i, tabJ); tabs.set(j, tabI); if (showMoreTab && numTabs > moreTabCount) { assert more != null; if (j >= moreTabCount) { if (i >= moreTabCount) { // Both tabs are in the More NavStack. assert i != selectedTabIndex : "The tab at index " + i + " is supposed to be selected, but it is still in the More NavStack."; assert j != selectedTabIndex : "The tab at index " + j + " is supposed to be selected, but it is still in the More NavStack."; more.swapTabs(i - moreTabCount, j - moreTabCount); } else { // The Tab at `j' is in the More NavStack, but the Tab at `i' is not. assert j != selectedTabIndex : "The tab at index " + j + " is supposed to be selected, but it is still in the More NavStack."; if (i == selectedTabIndex) { tabSetItemI.setSelected(false); if (paneI != null) paneContainer.hideMember(paneI); } tabBar.removeMember(tabSetItemI); more.setTab(j - moreTabCount, tabI); tabBar.addMember(tabSetItemJ, i); if (i == selectedTabIndex) { tabSetItemJ.setSelected(true); if (paneJ != null) paneContainer.showMember(paneJ); TabDeselectedEvent._fire(this, tabI, j, tabJ); TabSelectedEvent._fire(this, tabJ, i); } else { if (paneJ != null) paneContainer.hideMember(paneJ); } } } else { // Neither tab is in the More NavStack. assert selectedTabIndex != MORE_TAB_SELECTED; tabBar.removeMember(tabSetItemI); // TODO Don't remove the panes to save on calls to onLoad(), onUnload(), onAttach(), and onDetach(). if (paneI != null && paneContainer.hasMember(paneI)) paneContainer.removeMember(paneI); tabBar.removeMember(tabSetItemJ); if (paneJ != null && paneContainer.hasMember(paneJ)) paneContainer.removeMember(paneJ); tabSetItemJ.setSelected(i == selectedTabIndex); tabBar.addMember(tabSetItemJ, i); if (paneJ != null) { paneContainer.addMember(paneJ); if (i != selectedTabIndex) paneContainer.hideMember(paneJ); } tabSetItemI.setSelected(j == selectedTabIndex); tabBar.addMember(tabSetItemI, j); if (paneI != null) { paneContainer.addMember(paneI); if (j != selectedTabIndex) paneContainer.hideMember(paneI); } if (i == selectedTabIndex) { selectedTabIndex = j; TabDeselectedEvent._fire(this, tabI, j, tabJ); TabSelectedEvent._fire(this, tabJ, i); } else if (j == selectedTabIndex) { selectedTabIndex = i; TabDeselectedEvent._fire(this, tabJ, i, tabI); TabSelectedEvent._fire(this, tabI, j); } } } } /** * Creates a {@link com.smartgwt.mobile.client.widgets.tab.Tab} and adds it to the end. * * <p>This is equivalent to: * <pre> * final Tab tab = new Tab(panel.getTitle(), panel.getIcon()); * tabSet.addTab(tab); * </pre> * * @param panel the panel to add. * @return the automatically created <code>Tab</code>. */ public Tab addPanel(Panel panel) { final Tab tab = new Tab(panel.getTitle(), panel.getIcon()); tab.setPane(panel); addTab(tab); return tab; } /** * Add a tab to the end. * * @param tab the tab to add. */ public void addTab(Tab tab) { addTab(tab, tabs.size()); } /** * Add a tab at the given position. * * @param tab the tab to add. * @param position the index where the tab should be added. It is clamped within range * (0 through {@link #getNumTabs()}, inclusive) if out of bounds. */ public void addTab(Tab tab, int position) { if (tab == null) throw new NullPointerException("`tab' cannot be null."); assert tab != moreTab; // Clamp `position' within range. position = Math.max(0, Math.min(position, tabs.size())); // Remove the tab if it exists. final int existingIndex = getTabPosition(tab); if (existingIndex >= 0) { // If the tab is being added in the exact same place, then return early. if (existingIndex == position) return; removeTab(existingIndex); if (existingIndex < position) --position; } final int currentNumTabs = tabs.size(); tabs.add(position, tab); final TabSetItem tabSetItem = tab._ensureTabSetItem(this); assert tab.getTabSet() == this; // Add the tab's pane to `paneContainer'. final Canvas pane = tab.getPane(); if (pane != null) { paneContainer.addMember(pane); paneContainer.hideMember(pane); } if (currentNumTabs + 1 > moreTabCount && showMoreTab) { if (more == null) { more = new More(); assert moreTab == null; moreTab = new Tab(more.getTitle(), more.getIcon()); moreTab.setPane(more); // The TabSetItem of `moreTab' and its pane (`more') are added to `tabBar' and // `paneContainer', respectively, but we don't want to add `moreTab' to `tabs'; // we don't want to treat the More tab like a tab that was explicitly added. tabBar.addMember(moreTab._ensureTabSetItem(this), moreTabCount); paneContainer.addMember(more); paneContainer.hideMember(more); } if (position >= moreTabCount) { // Add to the More. more.addTab(tab, position - moreTabCount); } else { // Add the TabSetItem to `tabBar'. tabBar.addMember(tabSetItem, position); // That pushes one of the visible tabs into More. final Tab otherTab = tabs.get(moreTabCount); final TabSetItem otherTabSetItem = otherTab._getTabSetItem(); if (moreTabCount == selectedTabIndex) { otherTabSetItem.setSelected(false); selectedTabIndex = NO_TAB_SELECTED; } tabBar.removeMember(otherTabSetItem); final Canvas otherPane = otherTab.getPane(); if (otherPane != null) paneContainer.removeMember(otherPane); more.addTab(otherTab, 0); } } else { // Add the TabSetItem to `tabBar'. tabBar.addMember(tabSetItem, position); } if (selectedTabIndex == NO_TAB_SELECTED) { selectTab(position); } } /** * Remove a tab. * * @param tab to remove */ public void removeTab(Tab tab) { assert tab == null || tab != moreTab; int index = tabs.indexOf(tab); if (index >= 0) { removeTab(index); } } /** * Remove a tab at the specified index. * * @param position the index of the tab to remove */ public void removeTab(int position) { final int currentNumTabs = tabs.size(); if (0 <= position && position < currentNumTabs) { final Tab tab = tabs.get(position); assert tab != null; assert tab != moreTab; tabs.remove(position); final TabSetItem tabSetItem = tab._getTabSetItem(); if (!showMoreTab || position < moreTabCount) { tabBar.removeMember(tabSetItem); if (showMoreTab && currentNumTabs - 1 >= moreTabCount) { // Move a tab from More to the tab bar. final Tab firstMoreTab = more.removeTab(0); final Tab otherTab = tabs.get(moreTabCount - 1); assert firstMoreTab == otherTab; final TabSetItem otherTabSetItem = otherTab._getTabSetItem(); tabBar.addMember(otherTabSetItem, moreTabCount - 1); } } else { assert more != null; more.removeTab(position - moreTabCount); } if (showMoreTab && currentNumTabs - 1 == moreTabCount) { // The More tab is no longer needed. Remove & destroy it. assert more.containsNoTabs(); final TabSetItem moreTabSetItem = moreTab._getTabSetItem(); tabBar.removeMember(moreTabSetItem); assert paneContainer.hasMember(more); paneContainer.removeMember(more); if (selectedTabIndex == MORE_TAB_SELECTED) { assert more != null && moreTab.getPane() == more; selectedTabIndex = NO_TAB_SELECTED; } moreTab._destroyTabSetItem(); moreTab._setTabSet(null); moreTab.setPane(null); moreTab = null; more.destroy(); more = null; } final Canvas pane = tab.getPane(); if (pane != null) paneContainer.removeMember(pane); tab._setTabSet(null); if (position == selectedTabIndex) { selectedTabIndex = -1; tabSetItem.setSelected(false); TabDeselectedEvent._fire(this, tab, -1, null); } } } /** * Remove one or more tabs at the specified indexes. * * @param tabIndexes array of tab indexes */ public void removeTabs(int[] tabIndexes) { if (tabIndexes == null) return; // Sort the indexes and remove the corresponding tabs in descending order. Arrays.sort(tabIndexes); for (int ri = tabIndexes.length; ri > 0; --ri) { removeTab(tabIndexes[ri - 1]); } } /******************************************************* * Update tabs ******************************************************/ /******************************************************* * Selections ******************************************************/ /** * Returns the index of the currently selected tab. * * @return -2 if the More tab is selected; otherwise, the index of the currently selected tab, * or -1 if no tab is selected. */ public final int getSelectedTabNumber() { return selectedTabIndex; } /** * Returns the currently selected tab. * * @return the currently selected tab, or <code>null</code> if the More tab is selected * or no tab is selected. */ public final Tab getSelectedTab() { final int index = selectedTabIndex; return (index >= 0 ? tabs.get(index) : null); } @SGWTInternal public void _selectMoreTab() { assert more != null && moreTab != null; if (selectedTabIndex != MORE_TAB_SELECTED) { if (selectedTabIndex != NO_TAB_SELECTED) { final Tab otherTab = tabs.get(selectedTabIndex); final TabSetItem otherTabSetItem = otherTab._getTabSetItem(); final Canvas otherPane = otherTab.getPane(); otherTabSetItem.setSelected(false); if (otherPane != null) paneContainer.hideMember(otherPane); // Even though the event's `newTab' could be considered `moreTab', we don't // pass `moreTab' as the third parameter to avoid exposing a reference to this // internal object. TabDeselectedEvent._fire(this, otherTab, selectedTabIndex, null); } final TabSetItem moreTabSetItem = moreTab._getTabSetItem(); assert moreTab.getPane() == more; moreTabSetItem.setSelected(true); paneContainer.showMember(more); selectedTabIndex = MORE_TAB_SELECTED; } } /** * Select a tab by index * * @param index the tab index */ public void selectTab(int index) throws IndexOutOfBoundsException { selectTab(index, false); } private void selectTab(int index, boolean animate) throws IndexOutOfBoundsException { if (tabs.size() <= index) throw new IndexOutOfBoundsException("No tab exists at index " + index); final Tab tab; if (index < 0) { // Allow a negative `index' to mean deselect the currently selected Tab (if any). tab = null; index = NO_TAB_SELECTED; } else { tab = tabs.get(index); if (tab.getDisabled()) return; } if (selectedTabIndex >= 0) { final Tab oldSelectedTab = tabs.get(selectedTabIndex); if (index == selectedTabIndex) return; final TabSetItem oldSelectedTabSetItem = oldSelectedTab._getTabSetItem(); oldSelectedTabSetItem.setSelected(false); final Canvas oldSelectedPane = oldSelectedTab.getPane(); if (oldSelectedPane != null) { paneContainer.hideMember(oldSelectedPane); if (oldSelectedPane instanceof Panel) PanelHideEvent.fire(this, (Panel)oldSelectedPane); } TabDeselectedEvent._fire(this, oldSelectedTab, selectedTabIndex, tab); } else if (selectedTabIndex == MORE_TAB_SELECTED) { assert more != null && moreTab != null; final TabSetItem moreTabSetItem = moreTab._getTabSetItem(); moreTabSetItem.setSelected(false); assert moreTab.getPane() == more; if (!animate) paneContainer.hideMember(more); } if (index >= 0) { assert tab != null; final TabSetItem tabSetItem = tab._getTabSetItem(); if (showMoreTab && index >= moreTabCount) { final Tab otherTab = tabs.get(moreTabCount - 1); tabs.set(moreTabCount - 1, tab); tabs.set(index, otherTab); tabBar.removeMember(otherTab._getTabSetItem()); tabBar.addMember(tabSetItem, moreTabCount - 1); assert more != null; more.setTab(index - moreTabCount, otherTab); index = moreTabCount - 1; } tabSetItem.setSelected(true); final Canvas pane = tab.getPane(); if (pane != null) { if (selectedTabIndex == MORE_TAB_SELECTED && animate) { final Function<Void> callback; if (!(pane instanceof Panel)) callback = null; else { callback = new Function<Void>() { @Override public Void execute() { assert pane instanceof Panel; PanelShowEvent.fire(TabSet.this, (Panel)pane); return null; } }; } AnimationUtil.slideTransition(more, pane, paneContainer, AnimationUtil.Direction.LEFT, null, callback, false); } else { paneContainer.showMember(pane); if (pane instanceof Panel) PanelShowEvent.fire(this, (Panel)pane); } } selectedTabIndex = index; TabSelectedEvent._fire(this, tab, index); if (_HISTORY_ENABLED) History.newItem(tab.getTitle()); } else selectedTabIndex = NO_TAB_SELECTED; } /** * Select a tab. * * @param tab the canvas representing the tab */ public void selectTab(Tab tab) { assert tab == null || tab != moreTab; int index = tab == null ? -1 : getTabPosition(tab); selectTab(index); } /******************************************************* * Enable/disable tabs ******************************************************/ public void enableTab(String id) { enableTab(getTab(id)); } public void enableTab(Tab tab) { final int position = getTabPosition(tab); if (position >= 0) { assert position < tabs.size(); enableTab(position); } } /** * Enable a tab if it is currently disabled. * * @param index the tab index */ public void enableTab(int index) throws IndexOutOfBoundsException { if (index < 0 || tabs.size() <= index) throw new IndexOutOfBoundsException("No tab exists at index " + index); final Tab tab = tabs.get(index); tab.setDisabled(false); } /** * Disable a tab if it is currently enabled. If the tab is selected, it is deselected. * * @param index the tab index */ public void disableTab(int index) throws IndexOutOfBoundsException { if (index < 0 || tabs.size() <= index) throw new IndexOutOfBoundsException("No tab exists at index " + index); final Tab tab = tabs.get(index); tab.setDisabled(true); if (selectedTabIndex == index) { selectTab(-1); } } /******************************************************* * State and tab query methods ******************************************************/ public final int getNumTabs() { return tabs.size(); } public final int getTabCount() { return getNumTabs(); } private final int getTabPosition(Tab other) { if (other == null) return -1; final int tabs_size = tabs.size(); for (int i = 0; i < tabs_size; ++i) { if (tabs.get(i).equals(other)) return i; } return -1; } /** * Returns the canvas representing a tab. * * @param tabIndex index of tab * @return the tab widget or null if not found */ public final Tab getTab(int tabIndex) { if (0 <= tabIndex && tabIndex < tabs.size()) { return tabs.get(tabIndex); } return null; } public final Tab getTab(String id) { if (id == null) return null; final int tabs_size = tabs.size(); for (int i = 0; i < tabs_size; ++i) { final Tab tab = tabs.get(i); if (id.equals(tab.getID())) return tab; } return null; } /** * **************************************************** * Helper methods * **************************************************** */ @Override public ContainerFeatures getContainerFeatures() { return new ContainerFeatures(this, true, false, false, true, 0); } @Override public HandlerRegistration addPanelHideHandler(PanelHideHandler handler) { return addHandler(handler, PanelHideEvent.getType()); } @Override public HandlerRegistration addPanelShowHandler(PanelShowHandler handler) { return addHandler(handler, PanelShowEvent.getType()); } public void setMoreTabCount(int moreTabCount) { if (this.moreTabCount == moreTabCount) return; // We need moreTabCount to be at least one so that we can swap out a non-More tab // with the selected tab. if (moreTabCount < 1) throw new IllegalArgumentException("`moreTabCount' must be at least 1."); if (more != null) throw new IllegalStateException("`moreTabCount' cannot be changed once the More tab has been created."); if (tabs.size() > moreTabCount && showMoreTab) throw new IllegalArgumentException("`moreTabCount` cannot be set to a number less than the current number of tabs."); this.moreTabCount = moreTabCount; } public final int getMoreTabCount() { return moreTabCount; } public void setShowMoreTab(boolean showMoreTab) { if (this.showMoreTab == showMoreTab) return; if (more != null) throw new IllegalStateException("`showMoreTab' cannot be changed once the More tab has been created."); if (tabs.size() > moreTabCount && showMoreTab) throw new IllegalArgumentException("The More tab cannot be enabled now that there are already more than `this.getMoreTabCount()' tabs in this TabSet."); this.showMoreTab = showMoreTab; } //public void setDraggable(Canvas draggable) { // this.draggable = draggable; //} }
will-gilbert/SmartGWT-Mobile
mobile/src/main/java/com/smartgwt/mobile/client/widgets/tab/TabSet.java
Java
unlicense
42,796
/** * */ package com.rhcloud.zugospoint.DAO; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import com.rhcloud.zugospoint.model.*; import com.rhcloud.zugospoint.util.HibernateUtil; /** * Klasa zawiera zbior niskopoziomowych metod dostepu do danych z bazy * @author zugo * */ public class ApplicationDAO { private SessionFactory sessionF; public ApplicationDAO (){ sessionF = HibernateUtil.getSessionFactory(); } public void addAdres(Adres theAdres) { Session session = sessionF.getCurrentSession(); try{ session.beginTransaction(); session.save(theAdres); session.getTransaction().commit(); session.close(); }catch (HibernateException e){ session.getTransaction().rollback(); e.printStackTrace(); session.close(); } } @SuppressWarnings("unchecked") public List<Adres> getAllAdreses(){ Session s = sessionF.getCurrentSession(); List<Adres> res = null; try{ s.beginTransaction(); res = s.createQuery("from Adres").list(); s.getTransaction().commit(); s.close(); }catch (HibernateException e){ s.getTransaction().rollback(); e.printStackTrace();// TODO throw apropriate exception when catch it, or not, considere it s.close(); } return res; } }
zugoth/1314-adb
src/main/java/com/rhcloud/zugospoint/DAO/ApplicationDAO.java
Java
unlicense
1,320
var User = { title : 'Customer', LoginTitleText : 'Register yourself' } module.exports = User;
thakurarun/Basic-nodejs-express-app
samplenode/samplenode/server/model/User.js
JavaScript
unlicense
104
/* * Copyright 2003-2005 Sun Microsystems, Inc. All rights reserved. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package com.sun.tools.javac.code; public enum BoundKind { EXTENDS("? extends "), SUPER("? super "), UNBOUND("?"); private final String name; BoundKind(String name) { this.name = name; } public String toString() { return name; } }
dk00/old-stuff
csie/08design-patterns/src/com/sun/tools/javac/code/BoundKind.java
Java
unlicense
473
// Demo for the template server package main import ( "database/sql" "flag" "fmt" "html/template" "log" "net/http" "os" tmpl "../../go-net-http-tmpl" _ "github.com/mattn/go-sqlite3" ) var ( port = flag.String("http", ":6060", "Port to serve http on.") templates = flag.String("templates", "./*.html", "Path to dir with template webpages.") ) func main() { os.Remove("./foo.db") defer os.Remove("./foo.db") db, err := sql.Open("sqlite3", "./foo.db") if err != nil { log.Fatal(err) } defer db.Close() prepareDB(db) h := tmpl.NewHandler(*templates, nil, template.FuncMap{ "sql": tmpl.SqlDebug(db), "sqlr": tmpl.SqlRDebug(db), "group": tmpl.Group, }) log.Fatal(http.ListenAndServe(*port, tmpl.Gzip(h))) } func prepareDB(db *sql.DB) { if _, err := db.Exec(` create table foo (id integer not null primary key, grp integer, name text); delete from foo; `); err != nil { log.Fatal(err) } tx, err := db.Begin() if err != nil { log.Fatal(err) } stmt, err := tx.Prepare("insert into foo(id, grp, name) values(?, ?, ?)") if err != nil { log.Fatal(err) } defer stmt.Close() for i := 0; i < 100; i++ { if _, err = stmt.Exec(i, i%10, fmt.Sprintf("foo-%03d", i)); err != nil { log.Fatal(err) } } tx.Commit() }
lvdlvd/go-net-http-tmpl
demo/main.go
GO
unlicense
1,273
var path = require('path') var fs = require('fs') var crypto = require('crypto') var dirmatch = require('dirmatch') var _ = require('underscore') var handlebars = require('handlebars') var Filter = require('broccoli-glob-filter') var makePartialName = function(partialPath) { var name = partialPath var ext = path.extname(partialPath) if (ext === '.hbs' || ext === '.handlebars') { name = path.basename(partialPath, ext) } return name } var Tree = function(inputTree, options) { if (!(this instanceof Tree)) return new Tree(inputTree, options) if (!options) options = {} if (options.files === undefined) options.files = ['**/*.hbs', '**/*.handlebars'] if (options.targetExtension === undefined) options.targetExtension = 'html' if (options.makePartialName === undefined) options.makePartialName = makePartialName this.handlebars = options.handlebars || handlebars.create() if (options.helpers) this.handlebars.registerHelper(options.helpers) Filter.apply(this, arguments) } Tree.prototype = Object.create(Filter.prototype) Tree.prototype.description = 'Handlebars' Tree.prototype.read = function(readTree) { var _this = this return readTree(this.inputTree).then(function(srcDir) { // Don't cache when context is dynamic if (typeof _this.options.context === 'function') _this.invalidateCache() _this.cachePartials(srcDir) return Filter.prototype.read.call(_this, readTree) }) } Tree.prototype.cachePartials = function(srcDir) { if (!this.options.partials) return var partials = dirmatch(srcDir, this.options.partials) var absPartials = _.map(partials, function(file) { return path.join(srcDir, file) }) var partialsHash = this.hashFiles(absPartials) if (this.cachedPartialsHash !== partialsHash) { this.cachedPartialsHash = partialsHash this.cachedPartials = this.loadPartials(srcDir, partials) this.invalidateCache() } } Tree.prototype.loadPartials = function(srcDir, partialsPaths) { var partials = {} _.each(partialsPaths, function(partialPath) { var name = this.options.makePartialName(partialPath) var content = fs.readFileSync(path.join(srcDir, partialPath), 'utf8') partials[name] = this.handlebars.compile(content) }, this) return partials } Tree.prototype.hashFiles = function(files) { var keys = _.map(files, this.hashFile.bind(this)) return crypto.createHash('md5').update(keys.join('')) } Tree.prototype.processFileContent = function(content, relPath) { var template = this.handlebars.compile(content, {partials: this.cachedPartials}) var context = this.options.context if (typeof this.options.context === 'function') context = context(relPath) return template(this.options.context, { partials: this.cachedPartials }) } module.exports = Tree
sunflowerdeath/broccoli-render-handlebars
index.js
JavaScript
unlicense
2,724
package com.jeremybroutin.blogreader2; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.webkit.WebView; import com.jeremybroutin.blogreader2.R; public class BlogWebViewActivity extends Activity { protected String mUrl; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_blog_web_view); Intent intent = getIntent(); Uri blogUri = intent.getData(); mUrl = blogUri.toString(); WebView webView = (WebView) findViewById(R.id.webView1); webView.loadUrl(mUrl); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.blog_web_view, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); if (itemId == R.id.action_share){ sharePost(); } return super.onOptionsItemSelected(item); } private void sharePost() { Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_TEXT, mUrl); startActivity(Intent.createChooser(shareIntent, getString(R.string.share_chooser_title))); } }
jeremybroutin/BlogReader
app/src/main/java/com/jeremybroutin/blogreader2/BlogWebViewActivity.java
Java
unlicense
1,534
"""Values export object module.""" class Values(object): """Class for Values export object.""" name = None document = None def save(self, section, document, graphics=True): """Get intro.""" self.document = document section = self.name return document def save_with_graphics(self, name, section, document): """Get intro.""" self.name = name self.document = document section = self.name return document
executive-consultants-of-los-angeles/rsum
rsum/export/sections/values.py
Python
unlicense
498
var express = require('express'), app = express(); app.use('/', express.static(__dirname + '/static')); app.listen(process.env.PORT || 8080);
Hardmath123/quackoverflow
index.js
JavaScript
unlicense
147
using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Linq; using System.Text; using ToolGood.ReadyGo3.Gadget.Events; using ToolGood.ReadyGo3.Gadget.Internals; using ToolGood.ReadyGo3.Internals; using ToolGood.ReadyGo3.PetaPoco; using ToolGood.ReadyGo3.PetaPoco.Core; namespace ToolGood.ReadyGo3 { public partial class SqlHelper : IDisposable { #region 私有变量 //是否设置默认值 internal bool _setDateTimeDefaultNow; internal bool _setStringDefaultNotNull; internal bool _setGuidDefaultNew; internal bool _sql_firstWithLimit1; // 读写数据库 internal readonly string _connectionString; internal readonly DbProviderFactory _factory; internal Database _database; // 连接时间 事务级别 internal int _commandTimeout; internal int _oneTimeCommandTimeout; internal IsolationLevel? _isolationLevel; internal readonly SqlEvents _events; private readonly SqlConfig _sqlConfig; internal readonly SqlType _sqlType; internal readonly SqlRecord _sql = new SqlRecord(); private readonly DatabaseProvider _provider; internal bool _isDisposable; #endregion 私有变量 #region 共公属性 /// <summary> /// SQL操作事件 /// </summary> public SqlEvents _Events { get { return _events; } } /// <summary> /// 数据库配置 /// </summary> public SqlConfig _Config { get { return _sqlConfig; } } /// <summary> /// SQL设置 /// </summary> public SqlRecord _Sql { get { return _sql; } } /// <summary> /// SQL语言类型 /// </summary> public SqlType _SqlType { get { return _sqlType; } } /// <summary> /// 是否释放 /// </summary> public bool _IsDisposed { get { return _isDisposable; } } #endregion 共公属性 #region 构造方法 释放方法 /// <summary> /// SqlHelper 构造方法 /// </summary> /// <param name="connectionString">数据库链接字符串</param> /// <param name="factory">provider工厂</param> /// <param name="type"></param> public SqlHelper(string connectionString, DbProviderFactory factory, SqlType type) { _sqlType = type; _factory = factory; _events = new SqlEvents(this); _connectionString = connectionString; _sqlConfig = new SqlConfig(this); _provider = DatabaseProvider.Resolve(_sqlType); } /// <summary> /// 释放 /// </summary> public void Dispose() { _isDisposable = true; if (_database != null) { _database.Dispose(); _database = null; } } #endregion 构造方法 释放方法 #region 私有方法 internal Database GetDatabase() { if (_database == null) { _database = new Database(this); } Database db = _database; db.CommandTimeout = _commandTimeout; db.OneTimeCommandTimeout = _oneTimeCommandTimeout; _oneTimeCommandTimeout = 0; return db; } /// <summary> /// 格式SQL语句 /// </summary> /// <param name="sql"></param> /// <returns></returns> internal string FormatSql(string sql) { if (sql == null) { return ""; } bool usedEscapeSql = false; char escapeSql = '`'; if (_sqlType == SqlType.MySql || _sqlType == SqlType.MariaDb) { usedEscapeSql = true; escapeSql = '`'; } else if (_sqlType == SqlType.Oracle || _sqlType == SqlType.FirebirdDb || _sqlType == SqlType.PostgreSQL) { usedEscapeSql = true; escapeSql = '"'; } if (usedEscapeSql == false) return sql; StringBuilder _where = new StringBuilder(); bool isInText = false, isInTableColumn = false, jump = false; var c = 'a'; for (int i = 0; i < sql.Length; i++) { var t = sql[i]; if (jump) { jump = false; } else if (isInText) { if (t == c) isInText = false; if (t == '\\') jump = true; } else if (isInTableColumn) { if (t == ']') { isInTableColumn = false; _where.Append(escapeSql); continue; } } else if (t == '[') { isInTableColumn = true; _where.Append(escapeSql); continue; } else if ("\"'`".Contains(t)) { isInText = true; c = t; } _where.Append(t); } return _where.ToString(); } #endregion 私有方法 #region UseTransaction /// <summary> /// 使用事务 /// </summary> /// <returns></returns> public Transaction UseTransaction() { return new Transaction(GetDatabase()); } #endregion UseTransaction UseCache UseRecord #region Execute ExecuteScalar ExecuteDataTable ExecuteDataSet Exists /// <summary> /// 执行 SQL 语句,并返回受影响的行数 /// </summary> /// <param name="sql">SQL 语句</param> /// <param name="args">SQL 参数</param> /// <returns>返回受影响的行数</returns> public int Execute(string sql, params object[] args) { if (string.IsNullOrEmpty(sql)) throw new ArgumentNullException("sql is empty."); sql = FormatSql(sql); return GetDatabase().Execute(sql, args); } /// <summary> /// 执行SQL 查询,并返回查询所返回的结果集中第一行的第一列。忽略额外的列或行。 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sql">SQL 语句</param> /// <param name="args">SQL 参数</param> /// <returns>返回查询所返回的结果集中第一行的第一列。忽略额外的列或行</returns> public T ExecuteScalar<T>(string sql = "", params object[] args) { if (string.IsNullOrEmpty(sql)) throw new ArgumentNullException("sql is empty."); sql = FormatSql(sql); return GetDatabase().ExecuteScalar<T>(sql, args); } /// <summary> /// 执行SQL 查询,返回 DataTable /// </summary> /// <param name="sql">SQL 语句</param> /// <param name="args">SQL 参数</param> /// <returns>返回 DataTable</returns> public DataTable ExecuteDataTable(string sql, params object[] args) { if (string.IsNullOrEmpty(sql)) throw new ArgumentNullException("sql is empty."); sql = FormatSql(sql); return GetDatabase().ExecuteDataTable(sql, args); } /// <summary> /// 执行SQL 查询,返回 DataSet /// </summary> /// <param name="sql">SQL 语句</param> /// <param name="args">SQL 参数</param> /// <returns>返回 DataSet</returns> public DataSet ExecuteDataSet(string sql, params object[] args) { if (string.IsNullOrEmpty(sql)) throw new ArgumentNullException("sql is empty."); sql = FormatSql(sql); return GetDatabase().ExecuteDataSet(sql, args); } /// <summary> /// 执行SQL 查询,判断是否存在,返回bool类型 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sql">SQL 语句</param> /// <param name="args">SQL 参数</param> /// <returns></returns> public bool Exists<T>(string sql, params object[] args) { sql = FormatSql(sql); return Count<T>(sql, args) > 0; } /// <summary> /// 执行SQL 查询,判断是否存在,返回bool类型 /// </summary> /// <param name="table"></param> /// <param name="sql">SQL 语句</param> /// <param name="args">SQL 参数</param> /// <returns></returns> public bool Table_Exists(string table, string sql, params object[] args) { sql = FormatSql(sql); return Count(table, sql, args) > 0; } /// <summary> /// 执行SQL 查询,返回数量 /// </summary> /// <param name="table"></param> /// <param name="sql">SQL 语句</param> /// <param name="args">SQL 参数</param> /// <returns></returns> public int Table_Count(string table, string sql, params object[] args) { sql = sql.Trim(); if (sql.StartsWith("SELECT ", StringComparison.CurrentCultureIgnoreCase) == false) { sql = FormatSql(sql); sql = $"SELECT COUNT(*) FROM {table} {sql}"; } return GetDatabase().ExecuteScalar<int>(sql, args); } /// <summary> /// 执行SQL 查询,返回数量 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sql">SQL 语句</param> /// <param name="args">SQL 参数</param> /// <returns></returns> public int Count<T>(string sql = "", params object[] args) { sql = sql.Trim(); if (sql.StartsWith("SELECT ", StringComparison.CurrentCultureIgnoreCase) == false) { var pd = PocoData.ForType(typeof(T)); var table = _provider.GetTableName(pd); sql = FormatSql(sql); sql = $"SELECT COUNT(*) FROM {table} {sql}"; } return GetDatabase().ExecuteScalar<int>(sql, args); } /// <summary> /// 执行SQL 查询,返回数量 /// </summary> /// <param name="sql"></param> /// <param name="args"></param> /// <returns></returns> public int Count(string sql, params object[] args) { if (string.IsNullOrEmpty(sql)) throw new ArgumentNullException("sql is empty."); return GetDatabase().ExecuteScalar<int>(sql, args); } #endregion Execute ExecuteScalar ExecuteDataTable ExecuteDataSet Exists #region Select Page Select /// <summary> /// 执行SQL 查询,返回集合 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sql">SQL 语句</param> /// <param name="args">SQL 参数</param> /// <returns></returns> public List<T> Select<T>(string sql = "", params object[] args) { sql = FormatSql(sql); return GetDatabase().Query<T>(sql, args).ToList(); } /// <summary> /// 执行SQL 查询,返回集合 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="table"></param> /// <param name="sql">SQL 语句</param> /// <param name="args">SQL 参数</param> /// <returns></returns> public List<T> Table_Select<T>(string table, string sql = "", params object[] args) where T : class { sql = FormatSql(sql); return GetDatabase().Table_Query<T>(table, sql, args).ToList(); } /// <summary> /// 执行SQL 查询,返回集合 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="limit">获取个数</param> /// <param name="sql">SQL 语句</param> /// <param name="args">SQL 参数</param> /// <returns></returns> public List<T> Select<T>(int limit, string sql = "", params object[] args) where T : class { sql = FormatSql(sql); return GetDatabase().Query<T>(0, limit, sql, args).ToList(); } /// <summary> /// 执行SQL 查询,返回集合 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="table"></param> /// <param name="limit">获取个数</param> /// <param name="sql">SQL 语句</param> /// <param name="args">SQL 参数</param> /// <returns></returns> public List<T> Table_Select<T>(string table, int limit, string sql = "", params object[] args) where T : class { sql = FormatSql(sql); return GetDatabase().Table_Query<T>(table, 0, limit, sql, args).ToList(); } /// <summary> /// 执行SQL 查询,返回集合 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="offset">跳过</param> /// <param name="limit">获取个数</param> /// <param name="sql">SQL 语句</param> /// <param name="args">SQL 参数</param> /// <returns></returns> public List<T> Select<T>(int limit, int offset, string sql = "", params object[] args) where T : class { sql = FormatSql(sql); return GetDatabase().Query<T>(offset, limit, sql, args).ToList(); } /// <summary> /// 执行SQL 查询,返回集合 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="table"></param> /// <param name="offset">跳过</param> /// <param name="limit">获取个数</param> /// <param name="sql">SQL 语句</param> /// <param name="args">SQL 参数</param> /// <returns></returns> public List<T> Table_Select<T>(string table, int limit, int offset, string sql = "", params object[] args) where T : class { sql = FormatSql(sql); return GetDatabase().Table_Query<T>(table, offset, limit, sql, args).ToList(); } /// <summary> /// 执行SQL 查询,返回集合 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="page"></param> /// <param name="itemsPerPage"></param> /// <param name="sql"></param> /// <param name="args"></param> /// <returns></returns> public List<T> SelectPage<T>(int page, int itemsPerPage, string sql = "", params object[] args) where T : class { if (page <= 0) { page = 1; } if (itemsPerPage <= 0) { itemsPerPage = 20; } sql = FormatSql(sql); return GetDatabase().Query<T>((page - 1) * itemsPerPage, itemsPerPage, sql, args).ToList(); } /// <summary> /// 执行SQL 查询,返回集合 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="table"></param> /// <param name="page"></param> /// <param name="itemsPerPage"></param> /// <param name="sql"></param> /// <param name="args"></param> /// <returns></returns> public List<T> Table_SelectPage<T>(string table, int page, int itemsPerPage, string sql = "", params object[] args) where T : class { if (page <= 0) { page = 1; } if (itemsPerPage <= 0) { itemsPerPage = 20; } sql = FormatSql(sql); return GetDatabase().Table_Query<T>(table, (page - 1) * itemsPerPage, itemsPerPage, sql, args).ToList(); } /// <summary> /// 执行SQL 查询,返回Page类型 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="page">页数</param> /// <param name="itemsPerPage">每页数量</param> /// <param name="sql">SQL 语句</param> /// <param name="args">SQL 参数</param> /// <returns></returns> public Page<T> Page<T>(int page, int itemsPerPage, string sql = "", params object[] args) where T : class { if (page <= 0) { page = 1; } if (itemsPerPage <= 0) { itemsPerPage = 20; } sql = FormatSql(sql); return GetDatabase().Page<T>(page, itemsPerPage, sql, args); } /// <summary> /// 执行SQL 查询,返回Page类型 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="table"></param> /// <param name="page">页数</param> /// <param name="itemsPerPage">每页数量</param> /// <param name="sql">SQL 语句</param> /// <param name="args">SQL 参数</param> /// <returns></returns> public Page<T> Table_Page<T>(string table, int page, int itemsPerPage, string sql = "", params object[] args) where T : class { if (page <= 0) { page = 1; } if (itemsPerPage <= 0) { itemsPerPage = 20; } sql = FormatSql(sql); return GetDatabase().Table_Page<T>(table, page, itemsPerPage, sql, args); } /// <summary> /// 执行SQL 查询, 返回单个 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="columnSql"></param> /// <param name="tableSql"></param> /// <param name="whereSql"></param> /// <param name="args"></param> /// <returns></returns> public T SQL_FirstOrDefault<T>(string columnSql, string tableSql, string whereSql, params object[] args) where T : class { if (string.IsNullOrWhiteSpace(columnSql)) { throw new ArgumentNullException("columnSql is null."); } if (string.IsNullOrWhiteSpace(tableSql)) { throw new ArgumentNullException("tableSql is null."); } columnSql = RemoveStart(columnSql, "SELECT "); tableSql = RemoveStart(tableSql, "FROM "); whereSql = RemoveStart(whereSql, "WHERE "); var sql = $"SELECT {columnSql} FROM {tableSql} WHERE {whereSql}"; sql = FormatSql(sql); return GetDatabase().Query<T>(sql, args).FirstOrDefault(); } /// <summary> /// 执行SQL 查询,返回集合 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="page">页数</param> /// <param name="itemsPerPage">每页数量</param> /// <param name="columnSql">查询列 SQL语句</param> /// <param name="tableSql">TABLE SQL语句</param> /// <param name="orderSql">ORDER BY SQL语句</param> /// <param name="whereSql">WHERE SQL语句</param> /// <param name="args">SQL 参数</param> /// <returns></returns> public List<T> SQL_Select<T>(int page, int itemsPerPage, string columnSql, string tableSql, string orderSql, string whereSql, params object[] args) where T : class { if (string.IsNullOrWhiteSpace(columnSql)) { throw new ArgumentNullException("columnSql is null."); } if (string.IsNullOrWhiteSpace(tableSql)) { throw new ArgumentNullException("tableSql is null."); } if (page <= 0) { page = 1; } if (itemsPerPage <= 0) { itemsPerPage = 20; } columnSql = RemoveStart(columnSql, "SELECT "); tableSql = RemoveStart(tableSql, "FROM "); orderSql = RemoveStart(orderSql, "ORDER BY "); whereSql = RemoveStart(whereSql, "WHERE "); var sql = _provider.CreateSql((int)itemsPerPage, (int)((Math.Max(0, page - 1)) * itemsPerPage), columnSql, tableSql, orderSql, whereSql); sql = FormatSql(sql); return GetDatabase().Query<T>(sql, args).ToList(); } /// <summary> /// 执行SQL 查询,返回集合 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="limit">每页数量</param> /// <param name="columnSql">查询列 SQL语句</param> /// <param name="tableSql">TABLE SQL语句</param> /// <param name="orderSql">ORDER BY SQL语句</param> /// <param name="whereSql">WHERE SQL语句</param> /// <param name="args">SQL 参数</param> /// <returns></returns> public List<T> SQL_Select<T>(int limit, string columnSql, string tableSql, string orderSql, string whereSql, params object[] args) where T : class { if (string.IsNullOrWhiteSpace(columnSql)) { throw new ArgumentNullException("columnSql is null."); } if (string.IsNullOrWhiteSpace(tableSql)) { throw new ArgumentNullException("tableSql is null."); } if (limit <= 0) { limit = 20; } columnSql = RemoveStart(columnSql, "SELECT "); tableSql = RemoveStart(tableSql, "FROM "); orderSql = RemoveStart(orderSql, "ORDER BY "); whereSql = RemoveStart(whereSql, "WHERE "); var sql = _provider.CreateSql(limit, 0, columnSql, tableSql, orderSql, whereSql); sql = FormatSql(sql); return GetDatabase().Query<T>(sql, args).ToList(); } /// <summary> /// 执行SQL 查询,返回集合 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="columnSql">查询列 SQL语句</param> /// <param name="tableSql">TABLE SQL语句</param> /// <param name="orderSql">ORDER BY SQL语句</param> /// <param name="whereSql">WHERE SQL语句</param> /// <param name="args">SQL 参数</param> /// <returns></returns> public List<T> SQL_Select<T>(string columnSql, string tableSql, string orderSql, string whereSql, params object[] args) where T : class { if (string.IsNullOrWhiteSpace(columnSql)) { throw new ArgumentNullException("columnSql is null."); } if (string.IsNullOrWhiteSpace(tableSql)) { throw new ArgumentNullException("tableSql is null."); } columnSql = RemoveStart(columnSql, "SELECT "); tableSql = RemoveStart(tableSql, "FROM "); orderSql = RemoveStart(orderSql, "ORDER BY "); whereSql = RemoveStart(whereSql, "WHERE "); var sql = _provider.CreateSql(columnSql, tableSql, orderSql, whereSql); sql = FormatSql(sql); return GetDatabase().Query<T>(sql, args).ToList(); } /// <summary> /// 执行SQL 查询,返回Page类型 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="page">页数</param> /// <param name="itemsPerPage">每页数量</param> /// <param name="columnSql">查询列 SQL语句</param> /// <param name="tableSql">TABLE SQL语句</param> /// <param name="orderSql">ORDER BY SQL语句</param> /// <param name="whereSql">WHERE SQL语句</param> /// <param name="args">SQL 参数</param> /// <returns></returns> public Page<T> SQL_Page<T>(int page, int itemsPerPage, string columnSql, string tableSql, string orderSql, string whereSql, params object[] args) where T : class { if (string.IsNullOrWhiteSpace(columnSql)) { throw new ArgumentNullException("columnSql is null."); } if (string.IsNullOrWhiteSpace(tableSql)) { throw new ArgumentNullException("tableSql is null."); } if (page <= 0) { page = 1; } if (itemsPerPage <= 0) { itemsPerPage = 20; } columnSql = RemoveStart(columnSql, "SELECT "); tableSql = RemoveStart(tableSql, "FROM "); orderSql = RemoveStart(orderSql, "ORDER BY "); whereSql = RemoveStart(whereSql, "WHERE "); string countSql = string.IsNullOrEmpty(whereSql) ? $"SELECT COUNT(1) FROM {tableSql}" : $"SELECT COUNT(1) FROM {tableSql} WHERE {whereSql}"; countSql = FormatSql(countSql); var sql = _provider.CreateSql((int)itemsPerPage, (int)((Math.Max(0, page - 1)) * itemsPerPage), columnSql, tableSql, orderSql, whereSql); sql = FormatSql(sql); return GetDatabase().PageSql<T>(page, itemsPerPage, sql, countSql, args); } private string RemoveStart(string txt, string startsText) { if (string.IsNullOrEmpty(txt) == false) { txt = txt.Trim(); if (txt.StartsWith(startsText, StringComparison.InvariantCultureIgnoreCase)) { txt = txt.Substring(startsText.Length); } } return txt; } #endregion Select Page Select #region FirstOrDefault /// <summary> /// 获取唯一一个类型,若数量大于1,则抛出异常 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="primaryKey">主键名</param> /// <returns></returns> private T SingleOrDefaultById<T>(object primaryKey) where T : class { var pd = PocoData.ForType(typeof(T)); var pk = _provider.EscapeSqlIdentifier(pd.TableInfo.PrimaryKey); var sql = $"WHERE {pk}=@0"; return GetDatabase().Query<T>(sql, new object[] { primaryKey }).FirstOrDefault(); } /// <summary> /// 获取唯一一个类型,若数量大于1,则抛出异常 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="table"></param> /// <param name="primaryKey">主键名</param> /// <returns></returns> private T Table_SingleOrDefaultById<T>(string table, object primaryKey) where T : class { var pd = PocoData.ForType(typeof(T)); var pk = _provider.EscapeSqlIdentifier(pd.TableInfo.PrimaryKey); var sql = $"WHERE {pk}=@0"; return GetDatabase().Table_Query<T>(table, sql, new object[] { primaryKey }).FirstOrDefault(); } /// <summary> /// 获取第一个类型 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sql">SQL 语句</param> /// <param name="args">SQL 参数</param> /// <returns></returns> public T FirstOrDefault<T>(string sql = "", params object[] args) { sql = FormatSql(sql); if (_sql_firstWithLimit1 == false) { return GetDatabase().Query<T>(sql, args).FirstOrDefault(); } return GetDatabase().Query<T>(0, 1, sql, args).FirstOrDefault(); } /// <summary> /// 获取第一个类型 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="table"></param> /// <param name="sql">SQL 语句</param> /// <param name="args">SQL 参数</param> /// <returns></returns> public T Table_FirstOrDefault<T>(string table, string sql = "", params object[] args) where T : class { sql = FormatSql(sql); if (_sql_firstWithLimit1 == false) { return GetDatabase().Table_Query<T>(table, sql, args).FirstOrDefault(); } return GetDatabase().Table_Query<T>(table, 0, 1, sql, args).FirstOrDefault(); } #endregion FirstOrDefault #region Object Insert Update Delete DeleteById Save /// <summary> /// 插入集合,不返回主键 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list"></param> public void InsertList<T>(List<T> list) where T : class { if (list == null) throw new ArgumentNullException("list is null."); if (list.Count == 0) return; if (_setDateTimeDefaultNow || _setStringDefaultNotNull || _setGuidDefaultNew) { foreach (var item in list) { DefaultValue.SetDefaultValue<T>(item, _setStringDefaultNotNull, _setDateTimeDefaultNow, _setGuidDefaultNew); } } if (_Events.OnBeforeInsert(list)) return; GetDatabase().Insert(list); _Events.OnAfterInsert(list); } /// <summary> /// 插入集合,不返回主键 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="table"></param> /// <param name="list"></param> public void InsertList<T>(string table, List<T> list) where T : class { if (list == null) throw new ArgumentNullException("list is null."); if (list.Count == 0) return; if (_setDateTimeDefaultNow || _setStringDefaultNotNull || _setGuidDefaultNew) { foreach (var item in list) { DefaultValue.SetDefaultValue<T>(item, _setStringDefaultNotNull, _setDateTimeDefaultNow, _setGuidDefaultNew); } } if (_Events.OnBeforeInsert(list)) return; GetDatabase().Table_Insert(table, list); _Events.OnAfterInsert(list); } /// <summary> /// 插入,支持主键自动获取。 /// </summary> /// <param name="poco">对象</param> /// <returns></returns> public object Insert<T>(T poco) where T : class { if (poco == null) throw new ArgumentNullException("poco is null"); if (poco is IList) throw new ArgumentException("poco is a list type, use InsertList methon ."); if (_setDateTimeDefaultNow || _setStringDefaultNotNull || _setGuidDefaultNew) { DefaultValue.SetDefaultValue<T>(poco, _setStringDefaultNotNull, _setDateTimeDefaultNow, _setGuidDefaultNew); } if (_Events.OnBeforeInsert(poco)) return null; var obj = GetDatabase().Insert(poco); _Events.OnAfterInsert(poco); return obj; } /// <summary> /// 插入,支持主键自动获取。 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="table"></param> /// <param name="poco">对象</param> /// <returns></returns> public object Table_Insert<T>(string table, T poco) where T : class { if (poco == null) throw new ArgumentNullException("poco is null"); if (poco is IList) throw new ArgumentException("poco is a list type, use InsertList methon ."); if (_setDateTimeDefaultNow || _setStringDefaultNotNull || _setGuidDefaultNew) { DefaultValue.SetDefaultValue<T>(poco, _setStringDefaultNotNull, _setDateTimeDefaultNow, _setGuidDefaultNew); } if (_Events.OnBeforeInsert(poco)) return null; var obj = GetDatabase().Table_Insert(table, poco); _Events.OnAfterInsert(poco); return obj; } /// <summary> /// 插入 /// </summary> /// <param name="table"></param> /// <param name="poco"></param> /// <param name="autoIncrement"></param> /// <returns></returns> public object Table_Insert(string table, object poco, bool autoIncrement) { if (poco == null) throw new ArgumentNullException("poco is null"); if (poco is IList) throw new ArgumentException("poco is a list type, use InsertList methon ."); if (_setDateTimeDefaultNow || _setStringDefaultNotNull || _setGuidDefaultNew) { DefaultValue.SetDefaultValue(poco, _setStringDefaultNotNull, _setDateTimeDefaultNow, _setGuidDefaultNew); } if (_Events.OnBeforeInsert(poco)) return null; var obj = GetDatabase().Insert(table, poco, autoIncrement, null); _Events.OnAfterInsert(poco); return obj; } /// <summary> /// 插入 /// </summary> /// <param name="table"></param> /// <param name="poco"></param> /// <param name="ignoreFields"></param> /// <returns></returns> public object Table_Insert(string table, object poco, IEnumerable<string> ignoreFields) { if (poco == null) throw new ArgumentNullException("poco is null"); if (poco is IList) throw new ArgumentException("poco is a list type, use InsertList methon ."); if (_setDateTimeDefaultNow || _setStringDefaultNotNull || _setGuidDefaultNew) { DefaultValue.SetDefaultValue(poco, _setStringDefaultNotNull, _setDateTimeDefaultNow, _setGuidDefaultNew); } if (_Events.OnBeforeInsert(poco)) return null; var obj = GetDatabase().Insert(table, poco, false, ignoreFields); _Events.OnAfterInsert(poco); return obj; } /// <summary> /// 插入 /// </summary> /// <param name="table"></param> /// <param name="poco"></param> /// <param name="autoIncrement"></param> /// <param name="ignoreFields"></param> /// <returns></returns> public object Table_Insert(string table, object poco, bool autoIncrement, IEnumerable<string> ignoreFields) { if (poco == null) throw new ArgumentNullException("poco is null"); if (poco is IList) throw new ArgumentException("poco is a list type, use InsertList methon ."); if (_setDateTimeDefaultNow || _setStringDefaultNotNull || _setGuidDefaultNew) { DefaultValue.SetDefaultValue(poco, _setStringDefaultNotNull, _setDateTimeDefaultNow, _setGuidDefaultNew); } if (_Events.OnBeforeInsert(poco)) return null; var obj = GetDatabase().Insert(table, poco, autoIncrement, ignoreFields); _Events.OnAfterInsert(poco); return obj; } /// <summary> /// 更新 /// </summary> /// <param name="poco">对象</param> /// <returns></returns> public int Update<T>(T poco) where T : class { if (poco == null) throw new ArgumentNullException("poco is null"); if (_Events.OnBeforeUpdate(poco)) return -1; int r = GetDatabase().Update(poco); _Events.OnAfterUpdate(poco); return r; } /// <summary> /// 更新 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="table"></param> /// <param name="poco"></param> /// <returns></returns> public int Table_Update<T>(string table, T poco) where T : class { if (poco == null) throw new ArgumentNullException("poco is null"); if (_Events.OnBeforeUpdate(poco)) return -1; int r = GetDatabase().Table_Update(table, poco); _Events.OnAfterUpdate(poco); return r; } /// <summary> /// 删除 /// </summary> /// <param name="poco">对象</param> /// <returns></returns> public int Delete<T>(T poco) where T : class { if (poco == null) throw new ArgumentNullException("poco is null"); if (_Events.OnBeforeDelete(poco)) return -1; var t = GetDatabase().Delete(poco); _Events.OnAfterDelete(poco); return t; } /// <summary> /// 删除 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="table"></param> /// <param name="poco">对象</param> /// <returns></returns> public int Table_Delete<T>(string table, T poco) where T : class { if (poco == null) throw new ArgumentNullException("poco is null"); if (_Events.OnBeforeDelete(poco)) return -1; var t = GetDatabase().Table_Delete(table, poco); _Events.OnAfterDelete(poco); return t; } /// <summary> /// 删除 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sql">SQL 语句</param> /// <param name="args">SQL 参数</param> /// <returns></returns> public int Delete<T>(string sql, params object[] args) where T : class { if (string.IsNullOrEmpty(sql)) throw new ArgumentNullException("sql is empty."); sql = FormatSql(sql); return GetDatabase().Delete<T>(sql, args); } /// <summary> /// 删除 /// </summary> /// <param name="table"></param> /// <param name="sql">SQL 语句</param> /// <param name="args">SQL 参数</param> /// <returns></returns> public int Table_Delete(string table, string sql, params object[] args) { if (string.IsNullOrEmpty(sql)) throw new ArgumentNullException("sql is empty."); sql = FormatSql(sql); return GetDatabase().Table_Delete(table, sql, args); } /// <summary> /// 根据ID 删除表数据, 注: 单独从delete方法,防止出错 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="primaryKey">主键</param> /// <returns></returns> public int DeleteById<T>(object primaryKey) where T : class { return GetDatabase().Delete<T>(primaryKey); } /// <summary> /// 根据ID 删除表数据, 注: 单独从delete方法,防止出错 /// </summary> /// <param name="table"></param> /// <param name="primaryKey">主键</param> /// <returns></returns> public int Table_DeleteById(string table, object primaryKey) { return GetDatabase().Table_Delete(table, primaryKey); } /// <summary> /// 保存 /// </summary> /// <param name="poco"></param> public void Save<T>(T poco) where T : class { if (poco == null) throw new ArgumentNullException("poco is null"); GetDatabase().Save(poco); } /// <summary> /// 保存 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="table"></param> /// <param name="poco"></param> public void Table_Save<T>(string table, T poco) where T : class { if (poco == null) throw new ArgumentNullException("poco is null"); GetDatabase().SaveTable(table, poco); } /// <summary> /// 更新 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sql">SQL 语句</param> /// <param name="args">SQL 参数</param> /// <returns></returns> public int Update<T>(string sql, params object[] args) { if (string.IsNullOrEmpty(sql)) throw new ArgumentNullException("sql is empty."); sql = FormatSql(sql); return GetDatabase().Update<T>(sql, args); } /// <summary> /// 更新 /// </summary> /// <param name="table"></param> /// <param name="sql">SQL 语句</param> /// <param name="args">SQL 参数</param> /// <returns></returns> public int Table_Update(string table, string sql, params object[] args) { if (string.IsNullOrEmpty(sql)) throw new ArgumentNullException("sql is empty."); sql = FormatSql(sql); return GetDatabase().Table_Update(table, sql, args); } #endregion Object Insert Update Delete DeleteById Save /// <summary> /// 获取动态表名,适合绑定数据表列名 /// <para>var so = helper.GetTableName(typeof(DbSaleOrder), "so");</para> /// <para>var select = $"select {so.Code} from {so} where {so.Id}='123'";</para> /// </summary> /// <param name="type"></param> /// <param name="asName"></param> /// <returns></returns> public dynamic GetTableName(Type type, string asName = null) { return new TableName(type, _provider, asName); } /// <summary> /// 获取动态表名,适合绑定数据表列名 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="asName"></param> /// <returns></returns> public TableName<T> GetTableName<T>(string asName = null) where T : class, new() { return new TableName<T>(typeof(T), _provider, asName); } } }
toolgood/ToolGood.ReadyGo
ToolGood.ReadyGo3/SqlHelper.cs
C#
apache-2.0
41,728
package org.ctnitchie.doclet.freemarker; import java.io.IOException; import java.util.Map; import freemarker.core.Environment; import freemarker.template.TemplateDirectiveBody; import freemarker.template.TemplateDirectiveModel; import freemarker.template.TemplateException; import freemarker.template.TemplateModel; @SuppressWarnings("rawtypes") public class EchoDirective implements TemplateDirectiveModel { @Override public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { System.out.println(params.get("message")); } }
ctnitchie/freemarkerdoclet
src/main/java/org/ctnitchie/doclet/freemarker/EchoDirective.java
Java
apache-2.0
646
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University // Copyright (c) 2011, 2012 Open Networking Foundation // Copyright (c) 2012, 2013 Big Switch Networks, Inc. // This library was generated by the LoxiGen Compiler. // See the file LICENSE.txt which should have been included in the source distribution // Automatically generated by LOXI from template of_interface.java // Do not modify package org.projectfloodlight.openflow.protocol; import org.projectfloodlight.openflow.protocol.*; import org.projectfloodlight.openflow.protocol.action.*; import org.projectfloodlight.openflow.protocol.actionid.*; import org.projectfloodlight.openflow.protocol.bsntlv.*; import org.projectfloodlight.openflow.protocol.errormsg.*; import org.projectfloodlight.openflow.protocol.meterband.*; import org.projectfloodlight.openflow.protocol.instruction.*; import org.projectfloodlight.openflow.protocol.instructionid.*; import org.projectfloodlight.openflow.protocol.match.*; import org.projectfloodlight.openflow.protocol.oxm.*; import org.projectfloodlight.openflow.protocol.queueprop.*; import org.projectfloodlight.openflow.types.*; import org.projectfloodlight.openflow.util.*; import org.projectfloodlight.openflow.exceptions.*; import java.util.Set; import java.util.List; import org.jboss.netty.buffer.ChannelBuffer; public interface OFBsnDebugCounterDescStatsReply extends OFObject, OFBsnStatsReply { OFVersion getVersion(); OFType getType(); long getXid(); OFStatsType getStatsType(); Set<OFStatsReplyFlags> getFlags(); long getExperimenter(); long getSubtype(); List<OFBsnDebugCounterDescStatsEntry> getEntries(); void writeTo(ChannelBuffer channelBuffer); Builder createBuilder(); public interface Builder extends OFBsnStatsReply.Builder { OFBsnDebugCounterDescStatsReply build(); OFVersion getVersion(); OFType getType(); long getXid(); Builder setXid(long xid); OFStatsType getStatsType(); Set<OFStatsReplyFlags> getFlags(); Builder setFlags(Set<OFStatsReplyFlags> flags); long getExperimenter(); long getSubtype(); List<OFBsnDebugCounterDescStatsEntry> getEntries(); Builder setEntries(List<OFBsnDebugCounterDescStatsEntry> entries); } }
o3project/openflowj-otn
src/main/java/org/projectfloodlight/openflow/protocol/OFBsnDebugCounterDescStatsReply.java
Java
apache-2.0
2,321
package com.gdn.venice.server.app.fraud.presenter.commands; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import com.djarum.raf.utilities.Locator; import com.gdn.venice.client.app.DataNameTokens; import com.gdn.venice.facade.FrdParameterRule31SessionEJBRemote; import com.gdn.venice.persistence.FrdParameterRule31; import com.gdn.venice.server.command.RafDsCommand; import com.gdn.venice.server.data.RafDsRequest; import com.gdn.venice.server.data.RafDsResponse; /** * Update Command for Parameter Rule 31 - Genuine List * * @author Roland */ public class UpdateFraudParameterRule31DataCommand implements RafDsCommand { RafDsRequest request; public UpdateFraudParameterRule31DataCommand(RafDsRequest request) { this.request = request; } @Override public RafDsResponse execute() { RafDsResponse rafDsResponse = new RafDsResponse(); List<FrdParameterRule31> rule31List = new ArrayList<FrdParameterRule31>(); List<HashMap<String,String >> dataList = request.getData(); FrdParameterRule31 entityRule31 = new FrdParameterRule31(); Locator<Object> locator = null; try { locator = new Locator<Object>(); FrdParameterRule31SessionEJBRemote sessionHome = (FrdParameterRule31SessionEJBRemote) locator.lookup(FrdParameterRule31SessionEJBRemote.class, "FrdParameterRule31SessionEJBBean"); for (int i=0;i<dataList.size();i++) { Map<String, String> data = dataList.get(i); Iterator<String> iter = data.keySet().iterator(); while (iter.hasNext()) { String key = iter.next(); if(key.equals(DataNameTokens.FRDPARAMETERRULE31_ID)){ try{ entityRule31 = sessionHome.queryByRange("select o from FrdParameterRule31 o where o.id="+new Long(data.get(key)), 0, 1).get(0); }catch(IndexOutOfBoundsException e){ entityRule31.setId(new Long(data.get(key))); } break; } } iter = data.keySet().iterator(); while (iter.hasNext()) { String key = iter.next(); if(key.equals(DataNameTokens.FRDPARAMETERRULE31_EMAIL)){ entityRule31.setEmail(data.get(key)); } else if(key.equals(DataNameTokens.FRDPARAMETERRULE31_CCNUMBER)){ entityRule31.setNoCc(data.get(key)); } } rule31List.add(entityRule31); } sessionHome.mergeFrdParameterRule31List((ArrayList<FrdParameterRule31>)rule31List); rafDsResponse.setStatus(0); } catch (Exception ex) { ex.printStackTrace(); rafDsResponse.setStatus(-1); } finally { try { if(locator!=null){ locator.close(); } } catch (Exception e) { e.printStackTrace(); } } rafDsResponse.setData(dataList); return rafDsResponse; } }
yauritux/venice-legacy
Venice/Venice-Web/src/main/java/com/gdn/venice/server/app/fraud/presenter/commands/UpdateFraudParameterRule31DataCommand.java
Java
apache-2.0
2,763
package org.mcupdater.carnivora.render; import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; import net.minecraft.entity.Entity; import net.minecraft.util.ResourceLocation; import org.mcupdater.carnivora.Version; public class ModelSmoker extends ModelBase { public static ModelSmoker INSTANCE = null; public static ModelSmoker getInstance() { if( INSTANCE == null ) { INSTANCE = new ModelSmoker(); } return INSTANCE; } ResourceLocation texture; public ResourceLocation getTexture() { return texture; } ModelRenderer handle; ModelRenderer leg1; ModelRenderer leg2; ModelRenderer leg3; ModelRenderer leg4; ModelRenderer chimney1; ModelRenderer chimney2; ModelRenderer chimney3; ModelRenderer chimney4; ModelRenderer bodyleft; ModelRenderer bodyback; ModelRenderer bodyfrontright; ModelRenderer bodytop; ModelRenderer bodyfrontleft; ModelRenderer bodybottom; ModelRenderer bodyback2; ModelRenderer bodyright; public ModelSmoker() { texture = new ResourceLocation(Version.TEXTURE_PREFIX+"textures/blocks/smoker.png"); textureWidth = 69; textureHeight = 38; handle = new ModelRenderer(this, 62, 30); handle.addBox(-1F, -2F, -1F, 1, 4, 1); handle.setRotationPoint(0F, 13F, -5.5F); handle.setTextureSize(69, 38); handle.mirror = true; setRotation(handle, 0F, 0F, 1.570796F); leg1 = new ModelRenderer(this, 0, 13); leg1.addBox(-1F, 0F, -1F, 2, 5, 2); leg1.setRotationPoint(6F, 19F, -3F); leg1.setTextureSize(69, 38); leg1.mirror = true; setRotation(leg1, 0F, 0.7853982F, 0F); leg2 = new ModelRenderer(this, 0, 13); leg2.addBox(-1F, 0F, -1F, 2, 5, 2); leg2.setRotationPoint(-6F, 19F, -3F); leg2.setTextureSize(69, 38); leg2.mirror = true; setRotation(leg2, 0F, 0.7853982F, 0F); leg3 = new ModelRenderer(this, 0, 13); leg3.addBox(-1F, 0F, -1F, 2, 5, 2); leg3.setRotationPoint(-6F, 19F, 3F); leg3.setTextureSize(69, 38); leg3.mirror = true; setRotation(leg3, 0F, 0.7853982F, 0F); leg4 = new ModelRenderer(this, 0, 13); leg4.addBox(-1F, 0F, -1F, 2, 5, 2); leg4.setRotationPoint(6F, 19F, 3F); leg4.setTextureSize(69, 38); leg4.mirror = true; setRotation(leg4, 0F, 0.7853982F, 0F); chimney1 = new ModelRenderer(this, 0, 23); chimney1.addBox(-2F, -1F, -1F, 1, 2, 2); chimney1.setRotationPoint(0F, 9F, 0F); chimney1.setTextureSize(69, 38); chimney1.mirror = true; setRotation(chimney1, 0F, 3.141593F, 0F); chimney2 = new ModelRenderer(this, 0, 23); chimney2.addBox(-2F, -1F, -1F, 1, 2, 2); chimney2.setRotationPoint(0F, 9F, 0F); chimney2.setTextureSize(69, 38); chimney2.mirror = true; setRotation(chimney2, 0F, 0F, 0F); chimney3 = new ModelRenderer(this, 0, 23); chimney3.addBox(-2F, -1F, -1F, 1, 2, 2); chimney3.setRotationPoint(0F, 9F, 0F); chimney3.setTextureSize(69, 38); chimney3.mirror = true; setRotation(chimney3, 0F, 1.570796F, 0F); chimney4 = new ModelRenderer(this, 0, 23); chimney4.addBox(-2F, -1F, -1F, 1, 2, 2); chimney4.setRotationPoint(0F, 9F, 0F); chimney4.setTextureSize(69, 38); chimney4.mirror = true; setRotation(chimney4, 0F, -1.570796F, 0F); bodyleft = new ModelRenderer(this, 31, 30); bodyleft.addBox(-4F, -7.5F, -4F, 8, 1, 7); bodyleft.setRotationPoint(0F, 14F, 0F); bodyleft.setTextureSize(69, 38); bodyleft.mirror = true; setRotation(bodyleft, 1.570796F, -1.570796F, 0F); bodyback = new ModelRenderer(this, 9, 12); bodyback.addBox(-6F, -0.5F, 0F, 12, 1, 7); bodyback.setRotationPoint(0F, 18F, -5F); bodyback.setTextureSize(69, 38); bodyback.mirror = true; setRotation(bodyback, 1.570796F, 0F, 0F); bodyfrontright = new ModelRenderer(this, 48, 12); bodyfrontright.addBox(-8F, -5F, -4F, 2, 1, 7); bodyfrontright.setRotationPoint(0F, 14F, 0F); bodyfrontright.setTextureSize(69, 38); bodyfrontright.mirror = true; setRotation(bodyfrontright, 1.570796F, 0F, 0F); bodytop = new ModelRenderer(this, 35, 0); bodytop.addBox(-8F, -5F, 3F, 16, 10, 1); bodytop.setRotationPoint(0F, 14F, 0F); bodytop.setTextureSize(69, 38); bodytop.mirror = true; setRotation(bodytop, 1.570796F, 0F, 0F); bodyfrontleft = new ModelRenderer(this, 48, 21); bodyfrontleft.addBox(6F, -5F, -4F, 2, 1, 7); bodyfrontleft.setRotationPoint(0F, 14F, 0F); bodyfrontleft.setTextureSize(69, 38); bodyfrontleft.mirror = true; setRotation(bodyfrontleft, 1.570796F, 0F, 0F); bodybottom = new ModelRenderer(this, 0, 0); bodybottom.addBox(-8F, -5F, -5F, 16, 10, 1); bodybottom.setRotationPoint(0F, 14F, 0F); bodybottom.setTextureSize(69, 38); bodybottom.mirror = true; setRotation(bodybottom, 1.570796F, 0F, 0F); bodyback2 = new ModelRenderer(this, 1, 21); bodyback2.addBox(-8F, 4F, -4F, 16, 1, 7); bodyback2.setRotationPoint(0F, 14F, 0F); bodyback2.setTextureSize(69, 38); bodyback2.mirror = true; setRotation(bodyback2, 1.570796F, 0F, 0F); bodyright = new ModelRenderer(this, 0, 30); bodyright.addBox(-4F, -7.5F, -4F, 8, 1, 7); bodyright.setRotationPoint(0F, 14F, 0F); bodyright.setTextureSize(69, 38); bodyright.mirror = true; setRotation(bodyright, 1.570796F, 1.570796F, 0F); } @Override public void render(final Entity entity, final float f, final float f1, final float f2, final float f3, final float f4, final float f5) { super.render(entity, f, f1, f2, f3, f4, f5); setRotationAngles(f, f1, f2, f3, f4, f5, entity); handle.render(f5); leg1.render(f5); leg2.render(f5); leg3.render(f5); leg4.render(f5); chimney1.render(f5); chimney2.render(f5); chimney3.render(f5); chimney4.render(f5); bodyleft.render(f5); bodyback.render(f5); bodyfrontright.render(f5); bodytop.render(f5); bodyfrontleft.render(f5); bodybottom.render(f5); bodyback2.render(f5); bodyright.render(f5); } private void setRotation(final ModelRenderer model, final float x, final float y, final float z) { model.rotateAngleX = x; model.rotateAngleY = y; model.rotateAngleZ = z; } @Override public void setRotationAngles(final float f, final float f1, final float f2, final float f3, final float f4, final float f5, final Entity entity) { super.setRotationAngles(f, f1, f2, f3, f4, f5, entity); } }
allaryin/Carnivora
src/main/java/org/mcupdater/carnivora/render/ModelSmoker.java
Java
apache-2.0
6,215
class CartsController < ApplicationController before_action :set_cart, only: [:edit, :update] # GET /carts # GET /carts.json def index @carts = Cart.all end # GET /carts/1 # GET /carts/1.json def show begin @cart = Cart.find(params[:id]) rescue ActiveRecord::RecordNotFound logger.error "Attempt to access invalid cart #{params[:id]}" redirect_to root_path, notice: 'Invalid cart' else respond_to do |format| format.html format.json { render json: @cart } end end end # GET /carts/new def new @cart = Cart.new end # GET /carts/1/edit def edit end # POST /carts # POST /carts.json def create @cart = Cart.new(cart_params) respond_to do |format| if @cart.save format.html { redirect_to @cart, notice: 'Cart was successfully created.' } format.json { render :show, status: :created, location: @cart } else format.html { render :new } format.json { render json: @cart.errors, status: :unprocessable_entity } end end end # PATCH/PUT /carts/1 # PATCH/PUT /carts/1.json def update respond_to do |format| if @cart.update(cart_params) format.html { redirect_to @cart, notice: 'Cart was successfully updated.' } format.json { render :show, status: :ok, location: @cart } else format.html { render :edit } format.json { render json: @cart.errors, status: :unprocessable_entity } end end end # DELETE /carts/1 # DELETE /carts/1.json def destroy @cart = current_cart @cart.destroy session[:cart_id] = nil flash[:success]= 'Cart was successfully destroyed.' respond_to do |format| format.html { redirect_to root_path} format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_cart @cart = Cart.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def cart_params params[:cart] end end
LewisTao/depot
app/controllers/carts_controller.rb
Ruby
apache-2.0
2,122
//===--- FunctionOrder.cpp - Utility for function ordering ----------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "swift/SILOptimizer/Analysis/FunctionOrder.h" #include "swift/SIL/SILBasicBlock.h" #include "swift/SIL/SILFunction.h" #include "swift/SIL/SILInstruction.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/TinyPtrVector.h" #include <algorithm> using namespace swift; /// Use Tarjan's strongly connected components (SCC) algorithm to find /// the SCCs in the call graph. void BottomUpFunctionOrder::DFS(SILFunction *Start) { // Set the DFSNum for this node if we haven't already, and if we // have, which indicates it's already been visited, return. if (!DFSNum.insert(std::make_pair(Start, NextDFSNum)).second) return; assert(MinDFSNum.find(Start) == MinDFSNum.end() && "Function should not already have a minimum DFS number!"); MinDFSNum[Start] = NextDFSNum; ++NextDFSNum; DFSStack.insert(Start); // Visit all the instructions, looking for apply sites. for (auto &B : *Start) { for (auto &I : B) { auto FAS = FullApplySite::isa(&I); if (!FAS && !isa<StrongReleaseInst>(&I) && !isa<ReleaseValueInst>(&I)) continue; auto Callees = FAS ? BCA->getCalleeList(FAS) : BCA->getCalleeList(&I); for (auto *CalleeFn : Callees) { // If not yet visited, visit the callee. if (DFSNum.find(CalleeFn) == DFSNum.end()) { DFS(CalleeFn); MinDFSNum[Start] = std::min(MinDFSNum[Start], MinDFSNum[CalleeFn]); } else if (DFSStack.count(CalleeFn)) { // If the callee is on the stack, it update our minimum DFS // number based on it's DFS number. MinDFSNum[Start] = std::min(MinDFSNum[Start], DFSNum[CalleeFn]); } } } } // If our DFS number is the minimum found, we've found a // (potentially singleton) SCC, so pop the nodes off the stack and // push the new SCC on our stack of SCCs. if (DFSNum[Start] == MinDFSNum[Start]) { SCC CurrentSCC; SILFunction *Popped; do { Popped = DFSStack.pop_back_val(); CurrentSCC.push_back(Popped); } while (Popped != Start); TheSCCs.push_back(CurrentSCC); } } void BottomUpFunctionOrder::FindSCCs(SILModule &M) { for (auto &F : M) DFS(&F); }
ben-ng/swift
lib/SILOptimizer/Analysis/FunctionOrder.cpp
C++
apache-2.0
2,705
package io.github.eternalpro.model; import com.jfinal.ext.plugin.tablebind.TableBind; import com.jfinal.plugin.activerecord.Model; import io.github.gefangshuai.wfinal.model.core.WModel; import java.util.List; /** * Created by gefangshuai on 2015-05-18-0018. */ @TableBind(tableName = "sec_user", pkName = "id") public class User extends WModel<User> { public static final User dao = new User(); public User findByUsername(String loginName) { return dao.findFirst("select * from sec_user t where t.username = ?", loginName); } public User findByMobile(String username) { return null; } }
gefangshuai/baseFinal-noshiro
src/main/java/io/github/eternalpro/model/User.java
Java
apache-2.0
631
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* -------------------------------- Package -------------------------------- */ package com.github.jessemull.microflex.bigintegerflex.stat; /* ----------------------------- Dependencies ------------------------------ */ import java.math.BigDecimal; import java.math.MathContext; import java.util.Collections; import java.util.List; /** * This class calculates the inter-quartile range of BigInteger plate stacks, plates, * wells and well sets. * * <br><br> * * Statistical operations can be performed on stacks, plates, sets and wells using * standard or aggregated functions. Standard functions calculate the desired * statistic for each well in the stack, plate or set. Aggregated functions aggregate * the values from all the wells in the stack, plate or set and perform the statistical * operation on the aggregated values. Both standard and aggregated functions can * be performed on a subset of data within the stack, plate, set or well. * * <br><br> * * The methods within the MicroFlex library are meant to be flexible and the * descriptive statistic object supports operations using a single stack, plate, * set or well as well as collections and arrays of stacks, plates, sets or wells. * * <table cellspacing="10px" style="text-align:left; margin: 20px;"> * <th><div style="border-bottom: 1px solid black; padding-bottom: 5px; padding-top: 18px;">Operation<div></th> * <th><div style="border-bottom: 1px solid black; padding-bottom: 5px;">Beginning<br>Index<div></th> * <th><div style="border-bottom: 1px solid black; padding-bottom: 5px;">Length of<br>Subset<div></th> * <th><div style="border-bottom: 1px solid black; padding-bottom: 5px; padding-top: 18px;">Input/Output</div></th> * <tr> * <td valign="top"> * <table> * <tr> * <td>Standard</td> * </tr> * </table> * </td> * <td valign="top"> * <table> * <tr> * <td>+/-</td> * </tr> * </table> * </td> * <td valign="top"> * <table> * <tr> * <td>+/-</td> * </tr> * </table> * </td> * <td valign="top"> * <table> * <tr> * <td>Accepts a single well, set, plate or stack as input</td> * </tr> * <tr> * <td>Calculates the statistic for each well in a well, set, plate or stack</td> * </tr> * </table> * </td> * </tr> * <tr> * <td valign="top"> * <table> * <tr> * <td>Aggregated</td> * </tr> * </table> * </td> * <td valign="top"> * <table> * <tr> * <td>+/-</td> * </tr> * </table> * </td> * <td valign="top"> * <table> * <tr> * <td>+/-</td> * </tr> * </table> * </td> * <td valign="top"> * <table> * <tr> * <td>Accepts a single well/set/plate/stack or a collection/array of wells/sets/plates/stacks as input</td> * </tr> * <tr> * <td>Aggregates the data from all the wells in a well/set/plate/stack and calculates the statistic using the aggregated data</td> * </tr> * </table> * </td> * </tr> * </table> * * @author Jesse L. Mull * @update Updated Oct 18, 2016 * @address http://www.jessemull.com * @email hello@jessemull.com */ public class InterquartileRangeBigInteger extends DescriptiveStatisticBigIntegerContext { /** * Calculates the inter-quartile range. * @param List<BigDecimal> the list * @param MathContext the math context * @return the result */ public BigDecimal calculate(List<BigDecimal> list, MathContext mc) { Collections.sort(list); if(list.size() < 2) { return BigDecimal.ZERO; } int index = list.size() / 2; List<BigDecimal> listQ1 = list.subList(0, index); int lowQ1 = (int) Math.floor((listQ1.size() - 1.0) / 2.0); int highQ1 = (int) Math.ceil((listQ1.size() - 1.0) / 2.0); BigDecimal q1 = (listQ1.get(lowQ1).add(listQ1.get(highQ1))).divide(new BigDecimal(2), mc); if(list.size() % 2 != 0) { index++; } List<BigDecimal> listQ3 = list.subList(index, list.size()); int lowQ3 = (int) Math.floor((listQ3.size() - 1.0) / 2.0); int highQ3 = (int) Math.ceil((listQ3.size() - 1.0) / 2.0); BigDecimal q3 = (listQ3.get(lowQ3).add(listQ3.get(highQ3))).divide(new BigDecimal(2), mc); return q3.subtract(q1); } /** * Calculates the inter-quartile range of the values between the beginning and * ending indices. * @param List<BigDecimal> the list * @param int beginning index of subset * @param int length of subset * @param MathContext the math context * @return the result */ public BigDecimal calculate(List<BigDecimal> list, int begin, int length, MathContext mc) { return calculate(list.subList(begin, begin + length), mc); } }
jessemull/MicroFlex
src/main/java/com/github/jessemull/microflex/bigintegerflex/stat/InterquartileRangeBigInteger.java
Java
apache-2.0
6,309
// Copyright (c) rubicon IT GmbH, www.rubicon.eu // // See the NOTICE file distributed with this work for additional information // regarding copyright ownership. rubicon licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations // under the License. // using System; using System.Linq.Expressions; using TITcs.SharePoint.Query.LinqProvider.Clauses.Expressions; using TITcs.SharePoint.Query.LinqProvider.Parsing.Structure; using TITcs.SharePoint.Query.LinqProvider.Parsing.Structure.ExpressionTreeProcessors; using TITcs.SharePoint.Query.SharedSource.Utilities; namespace TITcs.SharePoint.Query.LinqProvider.Parsing.ExpressionTreeVisitors { /// <summary> /// Preprocesses an expression tree for parsing. The preprocessing involves detection of sub-queries and VB-specific expressions. /// </summary> public class SubQueryFindingExpressionTreeVisitor : ExpressionTreeVisitor { public static Expression Process (Expression expressionTree, INodeTypeProvider nodeTypeProvider) { ArgumentUtility.CheckNotNull ("expressionTree", expressionTree); ArgumentUtility.CheckNotNull ("nodeTypeProvider", nodeTypeProvider); var visitor = new SubQueryFindingExpressionTreeVisitor (nodeTypeProvider); return visitor.VisitExpression (expressionTree); } private readonly INodeTypeProvider _nodeTypeProvider; private readonly ExpressionTreeParser _expressionTreeParser; private readonly QueryParser _queryParser; private SubQueryFindingExpressionTreeVisitor (INodeTypeProvider nodeTypeProvider) { ArgumentUtility.CheckNotNull ("nodeTypeProvider", nodeTypeProvider); _nodeTypeProvider = nodeTypeProvider; _expressionTreeParser = new ExpressionTreeParser (_nodeTypeProvider, new NullExpressionTreeProcessor()); _queryParser = new QueryParser (_expressionTreeParser); } public override Expression VisitExpression (Expression expression) { var potentialQueryOperatorExpression = _expressionTreeParser.GetQueryOperatorExpression (expression); if (potentialQueryOperatorExpression != null && _nodeTypeProvider.IsRegistered (potentialQueryOperatorExpression.Method)) return CreateSubQueryNode (potentialQueryOperatorExpression); else return base.VisitExpression (expression); } protected internal override Expression VisitUnknownNonExtensionExpression (Expression expression) { //ignore return expression; } private SubQueryExpression CreateSubQueryNode (MethodCallExpression methodCallExpression) { QueryModel queryModel = _queryParser.GetParsedQuery (methodCallExpression); return new SubQueryExpression (queryModel); } } }
TITcs/TITcs.SharePoint
src/TITcs.SharePoint/Query/LinqProvider/Parsing/ExpressionTreeVisitors/SubQueryFindingExpressionTreeVisitor.cs
C#
apache-2.0
3,201
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.tonyu.soytext2.servlet; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import javax.servlet.http.HttpServletResponse; public class Httpd { public static void respondByString(HttpServletResponse response, String str) throws IOException { response.getWriter().println(str); } public static void respondByFile(HttpServletResponse response, File file) throws IOException { String con=HttpContext.detectContentType(file.getName()); response.setContentType(con); FileInputStream in = new FileInputStream(file); outputFromStream(response, in); in.close(); } public static void outputFromStream(HttpServletResponse res, InputStream in) throws IOException { byte[] buf= new byte[1024]; while (true) { int r=in.read(buf); if (r<=0) break; res.getOutputStream().write(buf,0,r); } } }
hoge1e3/soyText
src/jp/tonyu/soytext2/servlet/Httpd.java
Java
apache-2.0
1,747
package com.huawei.esdk.uc.professional.local.impl.autogen; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="ucAccount" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="confId" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="number" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="talkMode" type="{http://www.w3.org/2001/XMLSchema}int"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "ucAccount", "confId", "number", "talkMode" }) @XmlRootElement(name = "modifyTalkMode") public class ModifyTalkMode { @XmlElement(required = true) protected String ucAccount; @XmlElement(required = true) protected String confId; @XmlElement(required = true) protected String number; @XmlElement(required = true, type = String.class) @XmlJavaTypeAdapter(Adapter3 .class) @XmlSchemaType(name = "int") protected Integer talkMode; /** * Gets the value of the ucAccount property. * * @return * possible object is * {@link String } * */ public String getUcAccount() { return ucAccount; } /** * Sets the value of the ucAccount property. * * @param value * allowed object is * {@link String } * */ public void setUcAccount(String value) { this.ucAccount = value; } /** * Gets the value of the confId property. * * @return * possible object is * {@link String } * */ public String getConfId() { return confId; } /** * Sets the value of the confId property. * * @param value * allowed object is * {@link String } * */ public void setConfId(String value) { this.confId = value; } /** * Gets the value of the number property. * * @return * possible object is * {@link String } * */ public String getNumber() { return number; } /** * Sets the value of the number property. * * @param value * allowed object is * {@link String } * */ public void setNumber(String value) { this.number = value; } /** * Gets the value of the talkMode property. * * @return * possible object is * {@link String } * */ public Integer getTalkMode() { return talkMode; } /** * Sets the value of the talkMode property. * * @param value * allowed object is * {@link String } * */ public void setTalkMode(Integer value) { this.talkMode = value; } }
eSDK/esdk_uc_native_java
source/esdk_uc_native_professional_java/src/main/java/com/huawei/esdk/uc/professional/local/impl/autogen/ModifyTalkMode.java
Java
apache-2.0
3,578
package se.uu.it.cs.recsys.ruleminer.util; /* * #%L * CourseRecommenderRuleMiner * %% * Copyright (C) 2015 Yong Huang <yong.e.huang@gmail.com > * %% * 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. * #L% */ import java.util.List; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import se.uu.it.cs.recsys.ruleminer.datastructure.HeaderTableItem; /** * * @author Yong Huang &lt;yong.e.huang@gmail.com&gt; */ public class HeaderTableUtil { private static final Logger LOGGER = LoggerFactory.getLogger(HeaderTableUtil.class); public static List<Integer> getOrderedItemId(List<HeaderTableItem> headerTable) { return headerTable.stream() .map(tableItem -> tableItem.getItem().getId()) .collect(Collectors.toList()); } /** * * @param headerTable non-null header table * @param id, non-null id of an item. * @return the found table item or null if not found * @throws IllegalArgumentException, if input is null; */ public static HeaderTableItem getTableItemByItemId(List<HeaderTableItem> headerTable, Integer id) { if (headerTable == null || id == null) { throw new IllegalArgumentException("item id can not be null!"); } HeaderTableItem result = null; for (HeaderTableItem item : headerTable) { if (item.getItem().getId().equals(id)) { result = item; } } // if (result == null) { // LOGGER.debug("No match item found for id: {} in table: {}", id, // headerTable.stream().map(headItem -> headItem.getItem()).collect(Collectors.toList())); // } return result; } }
yong-at-git/CourseRecommenderParent
CourseRecommenderRuleMiner/src/main/java/se/uu/it/cs/recsys/ruleminer/util/HeaderTableUtil.java
Java
apache-2.0
2,270
# -*- coding: utf-8 -*- from dateutil.parser import parse import json import os import yaml import db_old # TODO: This function is currently only used by the db.py module, # imported from serving.py via sys.path modification. Due to the new # sys.path content, db.py attempts to find the `yaml_load` function in # this file, instead of in its own "utils.py". When imports are done # properly, delete this function from here. def yaml_load(path): with open(path, 'r', encoding='utf-8') as f: data_yaml = yaml.load(f, Loader=yaml.FullLoader) return data_yaml def NormalizeIco(ico): if ico is None: return None ico = ico.replace(" ", "") try: a = int(ico) return a except: return None def IcoToLatLngMap(): output_map = {} for table in ["orsresd_data", "firmy_data", "new_orsr_data"]: with db_old.getCursor() as cur: sql = "SELECT ico, lat, lng FROM " + table + \ " JOIN entities on entities.id = " + table + ".id" + \ " WHERE ico IS NOT NULL" db_old.execute(cur, sql) for row in cur: output_map[int(row["ico"])] = (row["lat"], row["lng"]) return output_map # Returns the value of 'entities.column' for the entitity with 'table'.ico='ico' def getColumnForTableIco(table, column, ico): sql = "SELECT " + column + " FROM " + table + \ " JOIN entities ON entities.id = " + table + ".id" + \ " WHERE ico = %s" + \ " LIMIT 1" with db_old.getCursor() as cur: try: cur = db_old.execute(cur, sql, [ico]) row = cur.fetchone() if row is None: return None return row[column] except: return None # TODO: refactor as this is also done in server def getEidForIco(ico): ico = NormalizeIco(ico) for table in ["new_orsr_data", "firmy_data", "orsresd_data"]: value = getColumnForTableIco(table, "eid", ico) if value is not None: return value return None def getAddressForIco(ico): ico = NormalizeIco(ico) for table in ["new_orsr_data", "firmy_data", "orsresd_data"]: value = getColumnForTableIco(table, "address", ico) if value is not None: return value.decode("utf8") return "" # Returns estimated/final value def getValue(obstaravanie): if obstaravanie.final_price is not None: return obstaravanie.final_price if obstaravanie.draft_price is not None: return obstaravanie.draft_price return None def obstaravanieToJson(obstaravanie, candidates, full_candidates=1, compute_range=False): current = {} current["id"] = obstaravanie.id if obstaravanie.description is None: current["text"] = "N/A" else: current["text"] = obstaravanie.description if obstaravanie.title is not None: current["title"] = obstaravanie.title if obstaravanie.bulletin_year is not None: current["bulletin_year"] = obstaravanie.bulletin_year if obstaravanie.bulleting_number is not None: current["bulletin_number"] = obstaravanie.bulleting_number current["price"] = getValue(obstaravanie) predictions = obstaravanie.predictions if (predictions is not None) and (len(predictions) > 0): prediction = predictions[0] current["price_avg"] = prediction.mean current["price_stdev"] = prediction.stdev current["price_num"] = prediction.num if obstaravanie.json is not None: j = json.loads(obstaravanie.json) if ("bulletin_issue" in j) and ("published_on" in j["bulletin_issue"]): bdate = parse(j["bulletin_issue"]["published_on"]) current["bulletin_day"] = bdate.day current["bulletin_month"] = bdate.month current["bulletin_date"] = "%d. %s %d" % (bdate.day, ["január", "február", "marec", "apríl", "máj", "jún", "júl", "august", "september", "október", "november", "december"][bdate.month - 1], bdate.year) current["customer"] = obstaravanie.customer.name if candidates > 0: # Generate at most one candidate in full, others empty, so we know the count current["kandidati"] = [{ "id": c.reason.id, "eid": getEidForIco(c.company.ico), "name": c.company.name, "ico": c.company.ico, "text": c.reason.description, "title": c.reason.title, "customer": c.reason.customer.name, "price": getValue(c.reason), "score": c.score} for c in obstaravanie.candidates[:full_candidates]] for _ in obstaravanie.candidates[full_candidates:candidates]: current["kandidati"].append({}) return current def getAddressJson(eid): # json with all geocoded data j = {} with db_old.getCursor() as cur: cur = db_old.execute(cur, "SELECT json FROM entities WHERE eid=%s", [eid]) row = cur.fetchone() if row is None: return None j = json.loads(row["json"]) # TODO: do not duplicate this with code in verejne/ def getComponent(json, typeName): try: for component in json[0]["address_components"]: if typeName in component["types"]: return component["long_name"] return "" except: return "" # types description: https://developers.google.com/maps/documentation/geocoding/intro#Types # street / city can be defined in multiple ways address = { "street": ( getComponent(j, "street_address") + getComponent(j, "route") + getComponent(j, "intersection") + " " + getComponent(j, "street_number") ), "city": getComponent(j, "locality"), "zip": getComponent(j, "postal_code"), "country": getComponent(j, "country"), } return address # Generates report with notifications, # saving pdf file to filename def generateReport(notifications): # Bail out if no notifications if len(notifications) == 0: return False company = notifications[0].candidate.company eid = getEidForIco(company.ico) if eid is None: return False data = {} data["company"] = { "name": company.name, "ico": company.ico, "address_full": getAddressForIco(company.ico), } data["company"].update(getAddressJson(eid)) notifications_json = [] for notification in notifications: notifications_json.append({ "reason": obstaravanieToJson( notification.candidate.reason, candidates=0, full_candidates=0), "what": obstaravanieToJson( notification.candidate.obstaravanie, candidates=0, full_candidates=0), }) data["notifications"] = notifications_json # Generate .json file atomically into the following directory. It is picked up # from there and automatically turned into .pdf and then send. shared_path = "/data/notifikacie/in/" tmp_filename = shared_path + ("json_%d_%d.tmp" % (eid, os.getpid())) final_filename = shared_path + ("data_%d_%d.json" % (eid, os.getpid())) with open(tmp_filename, "w") as tmp_file: json.dump(data, tmp_file, sort_keys=True, indent=4, separators=(',', ': ')) os.rename(tmp_filename, final_filename) return True
verejnedigital/verejne.digital
obstaravania/utils.py
Python
apache-2.0
7,620
/* * JBoss, Home of Professional Open Source * Copyright 2012, Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * 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 org.jboss.weld.tests.decorators.broken; import jakarta.decorator.Decorator; import jakarta.decorator.Delegate; import jakarta.enterprise.inject.Any; import jakarta.inject.Inject; @Decorator public class FooDecorator extends Foo { @Inject @Any @Delegate private Foo delegate; @Override public void ping() { delegate.ping(); } }
weld/core
tests-arquillian/src/test/java/org/jboss/weld/tests/decorators/broken/FooDecorator.java
Java
apache-2.0
1,152
package main; import view.Tienda; import view.Principal; import java.awt.Dimension; import javax.swing.JFrame; import javax.swing.UnsupportedLookAndFeelException; /** * * @author Chema_class */ public class Main extends JFrame{ private Principal principal; private Tienda tienda; private Decorador decorador; private Main(String s){ super(s); setSize(new Dimension(1100, 600)); setMinimumSize(new Dimension(950, 550)); setExtendedState(JFrame.MAXIMIZED_BOTH); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); initComponent(); setVisible(true); } private void initComponent(){ this.principal = new Principal(this); this.tienda = new Tienda(this); this.decorador = Decorador.getInstance(this); getContentPane().add(decorador); } public Principal getPrincipal(){ return principal; } public Tienda getTienda(){ return tienda; } public Decorador getDecorador(){ return decorador; } private void begin(){ principal.setVisible(true); decorador.begin(); } public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { //java.util.logging.Logger.getLogger(Opciones.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> new Main("ChemaInvaders").begin(); } }
Chemaclass/invaders
src/main/Main.java
Java
apache-2.0
2,315
/* * Copyright 2017 Antti Nieminen * * 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.haulmont.cuba.web.widgets.client.addons.aceeditor; import java.util.LinkedList; import java.util.List; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.DoubleClickEvent; import com.google.gwt.event.dom.client.DoubleClickHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyDownEvent; import com.google.gwt.event.dom.client.KeyDownHandler; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.ListBox; import com.vaadin.client.ui.VOverlay; public class SuggestPopup extends VOverlay implements KeyDownHandler, DoubleClickHandler, ChangeHandler { protected ListBox choiceList; protected String startOfValue = ""; public interface SuggestionSelectedListener { void suggestionSelected(TransportSuggestion s); void noSuggestionSelected(); } protected SuggestionSelectedListener listener; protected VOverlay descriptionPopup; protected List<TransportSuggestion> suggs; protected List<TransportSuggestion> visibleSuggs = new LinkedList<TransportSuggestion>(); protected boolean showDescriptions = true; protected Image loadingImage; public static final int WIDTH = 150; public static final int HEIGHT = 200; public static final int DESCRIPTION_WIDTH = 225; // TODO addSuggestionSelectedListener? public void setSuggestionSelectedListener(SuggestionSelectedListener ssl) { listener = ssl; } public SuggestPopup() { super(true); setWidth(WIDTH + "px"); SuggestionResources resources = GWT.create(SuggestionResources.class); loadingImage = new Image(resources.loading()); setWidget(loadingImage); } protected void createChoiceList() { choiceList = new ListBox(); choiceList.setStyleName("list"); choiceList.addKeyDownHandler(this); choiceList.addDoubleClickHandler(this); choiceList.addChangeHandler(this); choiceList.setStylePrimaryName("aceeditor-suggestpopup-list"); setWidget(choiceList); } protected void startLoading() { if (descriptionPopup!=null) { descriptionPopup.hide(); } setWidget(loadingImage); } public void setSuggestions(List<TransportSuggestion> suggs) { this.suggs = suggs; createChoiceList(); populateList(); if (choiceList.getItemCount() == 0) { close(); } } protected void populateList() { choiceList.clear(); visibleSuggs.clear(); int i = 0; for (TransportSuggestion s : suggs) { if (s.suggestionText.toLowerCase().startsWith(startOfValue)) { visibleSuggs.add(s); choiceList.addItem(s.displayText, "" + i); } i++; } if (choiceList.getItemCount() > 0) { int vic = Math.max(2, Math.min(10, choiceList.getItemCount())); choiceList.setVisibleItemCount(vic); choiceList.setSelectedIndex(0); this.onChange(null); } } public void close() { hide(); if (listener != null) listener.noSuggestionSelected(); } @Override public void hide() { super.hide(); if (descriptionPopup != null) descriptionPopup.hide(); descriptionPopup = null; } @Override public void hide(boolean ac) { super.hide(ac); if (ac) { // This happens when user clicks outside this popup (or something // similar) while autohide is on. We must cancel the suggestion. if (listener != null) listener.noSuggestionSelected(); } if (descriptionPopup != null) descriptionPopup.hide(); descriptionPopup = null; } @Override public void onKeyDown(KeyDownEvent event) { int keyCode = event.getNativeKeyCode(); if (keyCode == KeyCodes.KEY_ENTER && choiceList.getSelectedIndex() != -1) { event.preventDefault(); event.stopPropagation(); select(); } else if (keyCode == KeyCodes.KEY_ESCAPE) { event.preventDefault(); close(); } } @Override public void onDoubleClick(DoubleClickEvent event) { event.preventDefault(); event.stopPropagation(); select(); } @Override public void onBrowserEvent(Event event) { if (event.getTypeInt() == Event.ONCONTEXTMENU) { event.stopPropagation(); event.preventDefault(); return; } super.onBrowserEvent(event); } public void up() { if (suggs==null) { return; } int current = this.choiceList.getSelectedIndex(); int next = (current - 1 >= 0) ? current - 1 : 0; this.choiceList.setSelectedIndex(next); // Note that setting the selection programmatically does not cause the // ChangeHandler.onChange(ChangeEvent) event to be fired. // Doing it manually. this.onChange(null); } public void down() { if (suggs==null) { return; } int current = this.choiceList.getSelectedIndex(); int next = (current + 1 < choiceList.getItemCount()) ? current + 1 : current; this.choiceList.setSelectedIndex(next); // Note that setting the selection programmatically does not cause the // ChangeHandler.onChange(ChangeEvent) event to be fired. // Doing it manually. this.onChange(null); } public void select() { if (suggs==null) { return; } int selected = choiceList.getSelectedIndex(); if (listener != null) { if (selected == -1) { this.hide(); listener.noSuggestionSelected(); } else { startLoading(); listener.suggestionSelected(visibleSuggs.get(selected)); } } } @Override public void onChange(ChangeEvent event) { if (descriptionPopup == null) { createDescriptionPopup(); } int selected = choiceList.getSelectedIndex(); String descr = visibleSuggs.get(selected).descriptionText; if (descr != null && !descr.isEmpty()) { ((HTML) descriptionPopup.getWidget()).setHTML(descr); if (showDescriptions) { descriptionPopup.show(); } } else { descriptionPopup.hide(); } } @Override public void setPopupPosition(int left, int top) { super.setPopupPosition(left, top); if (descriptionPopup!=null) { updateDescriptionPopupPosition(); } } protected void updateDescriptionPopupPosition() { int x = getAbsoluteLeft() + WIDTH; int y = getAbsoluteTop(); descriptionPopup.setPopupPosition(x, y); if (descriptionPopup!=null) { descriptionPopup.setPopupPosition(x, y); } } protected void createDescriptionPopup() { descriptionPopup = new VOverlay(); descriptionPopup.setOwner(getOwner()); descriptionPopup.setStylePrimaryName("aceeditor-suggestpopup-description"); HTML lbl = new HTML(); lbl.setWordWrap(true); descriptionPopup.setWidget(lbl); updateDescriptionPopupPosition(); descriptionPopup.setWidth(DESCRIPTION_WIDTH+"px"); // descriptionPopup.setSize(DESCRIPTION_WIDTH+"px", HEIGHT+"px"); } public void setStartOfValue(String startOfValue) { this.startOfValue = startOfValue.toLowerCase(); if (suggs==null) { return; } populateList(); if (choiceList.getItemCount() == 0) { close(); } } }
dimone-kun/cuba
modules/web-toolkit/src/com/haulmont/cuba/web/widgets/client/addons/aceeditor/SuggestPopup.java
Java
apache-2.0
7,560
/** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2011 INRIA, France Telecom * All rights reserved. * <p/> * Redistribution and use in srccode and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of srccode code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the className of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * <p/> * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package act.asm.tree; import act.asm.MethodVisitor; import java.util.Map; /** * A node that represents an instruction with a single int operand. * * @author Eric Bruneton */ public class IntInsnNode extends AbstractInsnNode { /** * The operand of this instruction. */ public int operand; /** * Constructs a new {@link IntInsnNode}. * * @param opcode * the opcode of the instruction to be constructed. This opcode * must be BIPUSH, SIPUSH or NEWARRAY. * @param operand * the operand of the instruction to be constructed. */ public IntInsnNode(final int opcode, final int operand) { super(opcode); this.operand = operand; } /** * Sets the opcode of this instruction. * * @param opcode * the new instruction opcode. This opcode must be BIPUSH, SIPUSH * or NEWARRAY. */ public void setOpcode(final int opcode) { this.opcode = opcode; } @Override public int getType() { return INT_INSN; } @Override public void accept(final MethodVisitor mv) { mv.visitIntInsn(opcode, operand); acceptAnnotations(mv); } @Override public AbstractInsnNode clone(final Map<LabelNode, LabelNode> labels) { return new IntInsnNode(opcode, operand).cloneAnnotations(this); } }
actframework/act-asm
src/main/java/act/asm/tree/IntInsnNode.java
Java
apache-2.0
3,081
package org.apache.maven.lifecycle.internal; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.execution.MavenSession; import org.apache.maven.lifecycle.LifecycleNotFoundException; import org.apache.maven.lifecycle.LifecyclePhaseNotFoundException; import org.apache.maven.lifecycle.MavenExecutionPlan; import org.apache.maven.plugin.InvalidPluginDescriptorException; import org.apache.maven.plugin.MojoExecution; import org.apache.maven.plugin.MojoNotFoundException; import org.apache.maven.plugin.PluginDescriptorParsingException; import org.apache.maven.plugin.PluginNotFoundException; import org.apache.maven.plugin.PluginResolutionException; import org.apache.maven.plugin.prefix.NoPluginFoundForPrefixException; import org.apache.maven.plugin.version.PluginVersionResolutionException; import org.apache.maven.project.MavenProject; import java.util.List; /** * @since 3.0 * @author Benjamin Bentmann * @author Kristian Rosenvold (extract interface only) * <p/> */ public interface LifecycleExecutionPlanCalculator { MavenExecutionPlan calculateExecutionPlan( MavenSession session, MavenProject project, List<Object> tasks ) throws PluginNotFoundException, PluginResolutionException, LifecyclePhaseNotFoundException, PluginDescriptorParsingException, MojoNotFoundException, InvalidPluginDescriptorException, NoPluginFoundForPrefixException, LifecycleNotFoundException, PluginVersionResolutionException; void calculateForkedExecutions( MojoExecution mojoExecution, MavenSession session ) throws MojoNotFoundException, PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException, LifecyclePhaseNotFoundException, LifecycleNotFoundException, PluginVersionResolutionException; }
sonatype/maven-demo
maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleExecutionPlanCalculator.java
Java
apache-2.0
2,629
<?php /** * 主题 upbond */ namespace app\themes\upbond; use yii\web\AssetBundle; /** * @author zhanqu.im */ class ThemeAsset extends AssetBundle { const name = 'upbond'; const themeId = 'upbond'; public $sourcePath = '@app/themes/'.self::themeId.'/assets'; public $css = [ ]; public $js = [ ]; public $jsOptions = ['position' => \yii\web\View::POS_END]; public $depends = [ 'app\themes\upbond\AdminltePluginsAsset' ]; }
zhanqu/yii2adm
app/themes/upbond/ThemeAsset.php
PHP
apache-2.0
482
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.pinpoint.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * Provides information about an application, including the default settings for an application. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-2016-12-01/ApplicationSettingsResource" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ApplicationSettingsResource implements Serializable, Cloneable, StructuredPojo { /** * <p> * The unique identifier for the application. This identifier is displayed as the <b>Project ID</b> on the Amazon * Pinpoint console. * </p> */ private String applicationId; /** * <p> * The settings for the AWS Lambda function to invoke by default as a code hook for campaigns in the application. * You can use this hook to customize segments that are used by campaigns in the application. * </p> */ private CampaignHook campaignHook; /** * <p> * The date and time, in ISO 8601 format, when the application's settings were last modified. * </p> */ private String lastModifiedDate; /** * <p> * The default sending limits for campaigns in the application. * </p> */ private CampaignLimits limits; /** * <p> * The default quiet time for campaigns in the application. Quiet time is a specific time range when messages aren't * sent to endpoints, if all the following conditions are met: * </p> * <ul> * <li> * <p> * The EndpointDemographic.Timezone property of the endpoint is set to a valid value. * </p> * </li> * <li> * <p> * The current time in the endpoint's time zone is later than or equal to the time specified by the QuietTime.Start * property for the application (or a campaign or journey that has custom quiet time settings). * </p> * </li> * <li> * <p> * The current time in the endpoint's time zone is earlier than or equal to the time specified by the QuietTime.End * property for the application (or a campaign or journey that has custom quiet time settings). * </p> * </li> * </ul> * <p> * If any of the preceding conditions isn't met, the endpoint will receive messages from a campaign or journey, even * if quiet time is enabled. * </p> */ private QuietTime quietTime; /** * <p> * The unique identifier for the application. This identifier is displayed as the <b>Project ID</b> on the Amazon * Pinpoint console. * </p> * * @param applicationId * The unique identifier for the application. This identifier is displayed as the <b>Project ID</b> on the * Amazon Pinpoint console. */ public void setApplicationId(String applicationId) { this.applicationId = applicationId; } /** * <p> * The unique identifier for the application. This identifier is displayed as the <b>Project ID</b> on the Amazon * Pinpoint console. * </p> * * @return The unique identifier for the application. This identifier is displayed as the <b>Project ID</b> on the * Amazon Pinpoint console. */ public String getApplicationId() { return this.applicationId; } /** * <p> * The unique identifier for the application. This identifier is displayed as the <b>Project ID</b> on the Amazon * Pinpoint console. * </p> * * @param applicationId * The unique identifier for the application. This identifier is displayed as the <b>Project ID</b> on the * Amazon Pinpoint console. * @return Returns a reference to this object so that method calls can be chained together. */ public ApplicationSettingsResource withApplicationId(String applicationId) { setApplicationId(applicationId); return this; } /** * <p> * The settings for the AWS Lambda function to invoke by default as a code hook for campaigns in the application. * You can use this hook to customize segments that are used by campaigns in the application. * </p> * * @param campaignHook * The settings for the AWS Lambda function to invoke by default as a code hook for campaigns in the * application. You can use this hook to customize segments that are used by campaigns in the application. */ public void setCampaignHook(CampaignHook campaignHook) { this.campaignHook = campaignHook; } /** * <p> * The settings for the AWS Lambda function to invoke by default as a code hook for campaigns in the application. * You can use this hook to customize segments that are used by campaigns in the application. * </p> * * @return The settings for the AWS Lambda function to invoke by default as a code hook for campaigns in the * application. You can use this hook to customize segments that are used by campaigns in the application. */ public CampaignHook getCampaignHook() { return this.campaignHook; } /** * <p> * The settings for the AWS Lambda function to invoke by default as a code hook for campaigns in the application. * You can use this hook to customize segments that are used by campaigns in the application. * </p> * * @param campaignHook * The settings for the AWS Lambda function to invoke by default as a code hook for campaigns in the * application. You can use this hook to customize segments that are used by campaigns in the application. * @return Returns a reference to this object so that method calls can be chained together. */ public ApplicationSettingsResource withCampaignHook(CampaignHook campaignHook) { setCampaignHook(campaignHook); return this; } /** * <p> * The date and time, in ISO 8601 format, when the application's settings were last modified. * </p> * * @param lastModifiedDate * The date and time, in ISO 8601 format, when the application's settings were last modified. */ public void setLastModifiedDate(String lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; } /** * <p> * The date and time, in ISO 8601 format, when the application's settings were last modified. * </p> * * @return The date and time, in ISO 8601 format, when the application's settings were last modified. */ public String getLastModifiedDate() { return this.lastModifiedDate; } /** * <p> * The date and time, in ISO 8601 format, when the application's settings were last modified. * </p> * * @param lastModifiedDate * The date and time, in ISO 8601 format, when the application's settings were last modified. * @return Returns a reference to this object so that method calls can be chained together. */ public ApplicationSettingsResource withLastModifiedDate(String lastModifiedDate) { setLastModifiedDate(lastModifiedDate); return this; } /** * <p> * The default sending limits for campaigns in the application. * </p> * * @param limits * The default sending limits for campaigns in the application. */ public void setLimits(CampaignLimits limits) { this.limits = limits; } /** * <p> * The default sending limits for campaigns in the application. * </p> * * @return The default sending limits for campaigns in the application. */ public CampaignLimits getLimits() { return this.limits; } /** * <p> * The default sending limits for campaigns in the application. * </p> * * @param limits * The default sending limits for campaigns in the application. * @return Returns a reference to this object so that method calls can be chained together. */ public ApplicationSettingsResource withLimits(CampaignLimits limits) { setLimits(limits); return this; } /** * <p> * The default quiet time for campaigns in the application. Quiet time is a specific time range when messages aren't * sent to endpoints, if all the following conditions are met: * </p> * <ul> * <li> * <p> * The EndpointDemographic.Timezone property of the endpoint is set to a valid value. * </p> * </li> * <li> * <p> * The current time in the endpoint's time zone is later than or equal to the time specified by the QuietTime.Start * property for the application (or a campaign or journey that has custom quiet time settings). * </p> * </li> * <li> * <p> * The current time in the endpoint's time zone is earlier than or equal to the time specified by the QuietTime.End * property for the application (or a campaign or journey that has custom quiet time settings). * </p> * </li> * </ul> * <p> * If any of the preceding conditions isn't met, the endpoint will receive messages from a campaign or journey, even * if quiet time is enabled. * </p> * * @param quietTime * The default quiet time for campaigns in the application. Quiet time is a specific time range when messages * aren't sent to endpoints, if all the following conditions are met:</p> * <ul> * <li> * <p> * The EndpointDemographic.Timezone property of the endpoint is set to a valid value. * </p> * </li> * <li> * <p> * The current time in the endpoint's time zone is later than or equal to the time specified by the * QuietTime.Start property for the application (or a campaign or journey that has custom quiet time * settings). * </p> * </li> * <li> * <p> * The current time in the endpoint's time zone is earlier than or equal to the time specified by the * QuietTime.End property for the application (or a campaign or journey that has custom quiet time settings). * </p> * </li> * </ul> * <p> * If any of the preceding conditions isn't met, the endpoint will receive messages from a campaign or * journey, even if quiet time is enabled. */ public void setQuietTime(QuietTime quietTime) { this.quietTime = quietTime; } /** * <p> * The default quiet time for campaigns in the application. Quiet time is a specific time range when messages aren't * sent to endpoints, if all the following conditions are met: * </p> * <ul> * <li> * <p> * The EndpointDemographic.Timezone property of the endpoint is set to a valid value. * </p> * </li> * <li> * <p> * The current time in the endpoint's time zone is later than or equal to the time specified by the QuietTime.Start * property for the application (or a campaign or journey that has custom quiet time settings). * </p> * </li> * <li> * <p> * The current time in the endpoint's time zone is earlier than or equal to the time specified by the QuietTime.End * property for the application (or a campaign or journey that has custom quiet time settings). * </p> * </li> * </ul> * <p> * If any of the preceding conditions isn't met, the endpoint will receive messages from a campaign or journey, even * if quiet time is enabled. * </p> * * @return The default quiet time for campaigns in the application. Quiet time is a specific time range when * messages aren't sent to endpoints, if all the following conditions are met:</p> * <ul> * <li> * <p> * The EndpointDemographic.Timezone property of the endpoint is set to a valid value. * </p> * </li> * <li> * <p> * The current time in the endpoint's time zone is later than or equal to the time specified by the * QuietTime.Start property for the application (or a campaign or journey that has custom quiet time * settings). * </p> * </li> * <li> * <p> * The current time in the endpoint's time zone is earlier than or equal to the time specified by the * QuietTime.End property for the application (or a campaign or journey that has custom quiet time * settings). * </p> * </li> * </ul> * <p> * If any of the preceding conditions isn't met, the endpoint will receive messages from a campaign or * journey, even if quiet time is enabled. */ public QuietTime getQuietTime() { return this.quietTime; } /** * <p> * The default quiet time for campaigns in the application. Quiet time is a specific time range when messages aren't * sent to endpoints, if all the following conditions are met: * </p> * <ul> * <li> * <p> * The EndpointDemographic.Timezone property of the endpoint is set to a valid value. * </p> * </li> * <li> * <p> * The current time in the endpoint's time zone is later than or equal to the time specified by the QuietTime.Start * property for the application (or a campaign or journey that has custom quiet time settings). * </p> * </li> * <li> * <p> * The current time in the endpoint's time zone is earlier than or equal to the time specified by the QuietTime.End * property for the application (or a campaign or journey that has custom quiet time settings). * </p> * </li> * </ul> * <p> * If any of the preceding conditions isn't met, the endpoint will receive messages from a campaign or journey, even * if quiet time is enabled. * </p> * * @param quietTime * The default quiet time for campaigns in the application. Quiet time is a specific time range when messages * aren't sent to endpoints, if all the following conditions are met:</p> * <ul> * <li> * <p> * The EndpointDemographic.Timezone property of the endpoint is set to a valid value. * </p> * </li> * <li> * <p> * The current time in the endpoint's time zone is later than or equal to the time specified by the * QuietTime.Start property for the application (or a campaign or journey that has custom quiet time * settings). * </p> * </li> * <li> * <p> * The current time in the endpoint's time zone is earlier than or equal to the time specified by the * QuietTime.End property for the application (or a campaign or journey that has custom quiet time settings). * </p> * </li> * </ul> * <p> * If any of the preceding conditions isn't met, the endpoint will receive messages from a campaign or * journey, even if quiet time is enabled. * @return Returns a reference to this object so that method calls can be chained together. */ public ApplicationSettingsResource withQuietTime(QuietTime quietTime) { setQuietTime(quietTime); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getApplicationId() != null) sb.append("ApplicationId: ").append(getApplicationId()).append(","); if (getCampaignHook() != null) sb.append("CampaignHook: ").append(getCampaignHook()).append(","); if (getLastModifiedDate() != null) sb.append("LastModifiedDate: ").append(getLastModifiedDate()).append(","); if (getLimits() != null) sb.append("Limits: ").append(getLimits()).append(","); if (getQuietTime() != null) sb.append("QuietTime: ").append(getQuietTime()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ApplicationSettingsResource == false) return false; ApplicationSettingsResource other = (ApplicationSettingsResource) obj; if (other.getApplicationId() == null ^ this.getApplicationId() == null) return false; if (other.getApplicationId() != null && other.getApplicationId().equals(this.getApplicationId()) == false) return false; if (other.getCampaignHook() == null ^ this.getCampaignHook() == null) return false; if (other.getCampaignHook() != null && other.getCampaignHook().equals(this.getCampaignHook()) == false) return false; if (other.getLastModifiedDate() == null ^ this.getLastModifiedDate() == null) return false; if (other.getLastModifiedDate() != null && other.getLastModifiedDate().equals(this.getLastModifiedDate()) == false) return false; if (other.getLimits() == null ^ this.getLimits() == null) return false; if (other.getLimits() != null && other.getLimits().equals(this.getLimits()) == false) return false; if (other.getQuietTime() == null ^ this.getQuietTime() == null) return false; if (other.getQuietTime() != null && other.getQuietTime().equals(this.getQuietTime()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getApplicationId() == null) ? 0 : getApplicationId().hashCode()); hashCode = prime * hashCode + ((getCampaignHook() == null) ? 0 : getCampaignHook().hashCode()); hashCode = prime * hashCode + ((getLastModifiedDate() == null) ? 0 : getLastModifiedDate().hashCode()); hashCode = prime * hashCode + ((getLimits() == null) ? 0 : getLimits().hashCode()); hashCode = prime * hashCode + ((getQuietTime() == null) ? 0 : getQuietTime().hashCode()); return hashCode; } @Override public ApplicationSettingsResource clone() { try { return (ApplicationSettingsResource) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.pinpoint.model.transform.ApplicationSettingsResourceMarshaller.getInstance().marshall(this, protocolMarshaller); } }
aws/aws-sdk-java
aws-java-sdk-pinpoint/src/main/java/com/amazonaws/services/pinpoint/model/ApplicationSettingsResource.java
Java
apache-2.0
20,385
# -*- coding: utf-8 -*- """ Created on Sun Sep 11 23:06:06 2016 @author: DIP """ from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer def build_feature_matrix(documents, feature_type='frequency', ngram_range=(1, 1), min_df=0.0, max_df=1.0): feature_type = feature_type.lower().strip() if feature_type == 'binary': vectorizer = CountVectorizer(binary=True, min_df=min_df, max_df=max_df, ngram_range=ngram_range) elif feature_type == 'frequency': vectorizer = CountVectorizer(binary=False, min_df=min_df, max_df=max_df, ngram_range=ngram_range) elif feature_type == 'tfidf': vectorizer = TfidfVectorizer(min_df=min_df, max_df=max_df, ngram_range=ngram_range) else: raise Exception("Wrong feature type entered. Possible values: 'binary', 'frequency', 'tfidf'") feature_matrix = vectorizer.fit_transform(documents).astype(float) return vectorizer, feature_matrix from sklearn import metrics import numpy as np import pandas as pd def display_evaluation_metrics(true_labels, predicted_labels, positive_class=1): print 'Accuracy:', np.round( metrics.accuracy_score(true_labels, predicted_labels), 2) print 'Precision:', np.round( metrics.precision_score(true_labels, predicted_labels, pos_label=positive_class, average='binary'), 2) print 'Recall:', np.round( metrics.recall_score(true_labels, predicted_labels, pos_label=positive_class, average='binary'), 2) print 'F1 Score:', np.round( metrics.f1_score(true_labels, predicted_labels, pos_label=positive_class, average='binary'), 2) def display_confusion_matrix(true_labels, predicted_labels, classes=[1,0]): cm = metrics.confusion_matrix(y_true=true_labels, y_pred=predicted_labels, labels=classes) cm_frame = pd.DataFrame(data=cm, columns=pd.MultiIndex(levels=[['Predicted:'], classes], labels=[[0,0],[0,1]]), index=pd.MultiIndex(levels=[['Actual:'], classes], labels=[[0,0],[0,1]])) print cm_frame def display_classification_report(true_labels, predicted_labels, classes=[1,0]): report = metrics.classification_report(y_true=true_labels, y_pred=predicted_labels, labels=classes) print report
dipanjanS/text-analytics-with-python
Old-First-Edition/Ch07_Semantic_and_Sentiment_Analysis/utils.py
Python
apache-2.0
3,381
/* * Copyright WSO2 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 org.wso2.carbon.apimgt.gateway.handlers.security; import org.wso2.carbon.apimgt.gateway.MethodStats; import java.util.List; /** * Contains some context information related to an authenticated request. This can be used * to access API keys and tier information related to already authenticated requests. */ public class AuthenticationContext { private boolean authenticated; private String username; private String applicationTier; private String tier; private String apiTier; private boolean isContentAwareTierPresent; private String apiKey; private String keyType; private String callerToken; private String applicationId; private String applicationName; private String consumerKey; private String subscriber; private List<String> throttlingDataList; private int spikeArrestLimit; private String subscriberTenantDomain; private String spikeArrestUnit; private boolean stopOnQuotaReach; private String productName; private String productProvider; public List<String> getThrottlingDataList() { return throttlingDataList; } public void setThrottlingDataList(List<String> throttlingDataList) { this.throttlingDataList = throttlingDataList; } //Following throttle data list can be use to hold throttle data and api level throttle key //should be its first element. public boolean isContentAwareTierPresent() { return isContentAwareTierPresent; } public void setIsContentAware(boolean isContentAware) { this.isContentAwareTierPresent = isContentAware; } public String getApiTier() { return apiTier; } public void setApiTier(String apiTier) { this.apiTier = apiTier; } public String getSubscriber() { return subscriber; } public void setSubscriber(String subscriber) { this.subscriber = subscriber; } public boolean isAuthenticated() { return authenticated; } public String getUsername() { return username; } public String getTier() { return tier; } public String getApiKey() { return apiKey; } public void setApiKey(String apiKey) { this.apiKey = apiKey; } public void setAuthenticated(boolean authenticated) { this.authenticated = authenticated; } public void setUsername(String username) { this.username = username; } public void setTier(String tier) { this.tier = tier; } public String getKeyType() { return keyType; } public void setKeyType(String keyType) { this.keyType = keyType; } @MethodStats public String getCallerToken() { return callerToken; } public void setCallerToken(String callerToken) { this.callerToken = callerToken; } public String getApplicationTier() { return applicationTier; } public void setApplicationTier(String applicationTier) { this.applicationTier = applicationTier; } public String getApplicationId() { return applicationId; } public void setApplicationId(String applicationId) { this.applicationId = applicationId; } public String getApplicationName() { return applicationName; } public void setApplicationName(String applicationName) { this.applicationName = applicationName; } public String getConsumerKey() { return consumerKey; } public void setConsumerKey(String consumerKey) { this.consumerKey = consumerKey; } public int getSpikeArrestLimit() { return spikeArrestLimit; } public void setSpikeArrestLimit(int spikeArrestLimit) { this.spikeArrestLimit = spikeArrestLimit; } public String getSubscriberTenantDomain() { return subscriberTenantDomain; } public void setSubscriberTenantDomain(String subscriberTenantDomain) { this.subscriberTenantDomain = subscriberTenantDomain; } public String getSpikeArrestUnit() { return spikeArrestUnit; } public void setSpikeArrestUnit(String spikeArrestUnit) { this.spikeArrestUnit = spikeArrestUnit; } public boolean isStopOnQuotaReach() { return stopOnQuotaReach; } public void setStopOnQuotaReach(boolean stopOnQuotaReach) { this.stopOnQuotaReach = stopOnQuotaReach; } public void setProductName(String productName) { this.productName = productName; } public String getProductName() { return productName; } public void setProductProvider(String productProvider) { this.productProvider = productProvider; } public String getProductProvider() { return productProvider; } }
pubudu538/carbon-apimgt
components/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/handlers/security/AuthenticationContext.java
Java
apache-2.0
5,431
# 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. # # What is the sum of the digits of the number 2^1000? puts (2**1000).to_s.chars.map(&:to_i).reduce(:+)
tyrone-sudeium/project-euler
ruby/0016.rb
Ruby
apache-2.0
174
// Copyright (C) 2017 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 app import ( "context" "flag" "fmt" "os" "syscall" "github.com/google/gapid/core/event/task" "github.com/google/gapid/core/fault" "github.com/google/gapid/core/log" "github.com/google/gapid/core/os/file" "github.com/pkg/errors" ) var ( // Name is the full name of the application Name string // ExitFuncForTesting can be set to change the behaviour when there is a command line parsing failure. // It defaults to os.Exit ExitFuncForTesting = os.Exit // ShortHelp should be set to add a help message to the usage text. ShortHelp = "" // ShortUsage is usage text for the additional non-flag arguments. ShortUsage = "" // UsageFooter is printed at the bottom of the usage text UsageFooter = "" // Version holds the version specification for the application. // The default version is the one defined in version.cmake. // If valid a command line option to report it will be added automatically. Version VersionSpec // Restart is the error to return to cause the app to restart itself. Restart = fault.Const("Restart") ) // VersionSpec is the structure for the version of an application. type VersionSpec struct { // Major version, the version structure is in valid if <0 Major int // Minor version, not used if <0 Minor int // Point version, not used if <0 Point int // The build identifier, not used if an empty string Build string } // IsValid reports true if the VersionSpec is valid, ie it has a Major version. func (v VersionSpec) IsValid() bool { return v.Major >= 0 } // GreaterThan returns true if v is greater than o. func (v VersionSpec) GreaterThan(o VersionSpec) bool { switch { case v.Major > o.Major: return true case v.Major < o.Major: return false case v.Minor > o.Minor: return true case v.Minor < o.Minor: return false case v.Point > o.Point: return true default: return false } } // Format implements fmt.Formatter to print the version. func (v VersionSpec) Format(f fmt.State, c rune) { fmt.Fprint(f, v.Major) if v.Minor >= 0 { fmt.Fprint(f, ".", v.Minor) } if v.Point >= 0 { fmt.Fprint(f, ".", v.Point) } if v.Build != "" { fmt.Fprint(f, ":", v.Build) } } func init() { Name = file.Abs(os.Args[0]).Basename() } // Run performs all the work needed to start up an application. // It parsers the main command line arguments, builds a primary context that will be cancelled on exit // runs the provided task, cancels the primary context and then waits for either the maximum shutdown delay // or all registered signals whichever comes first. func Run(main task.Task) { // Defer the panic handling defer func() { switch cause := recover().(type) { case nil: case ExitCode: ExitFuncForTesting(int(cause)) default: panic(cause) } }() flags := &AppFlags{Log: logDefaults()} // install all the common application flags rootCtx, closeLogs := prepareContext(&flags.Log) defer closeLogs() // parse the command line flag.CommandLine.Usage = func() { Usage(rootCtx, "") } verbMainPrepare(flags) globalVerbs.flags.Parse(os.Args[1:]...) // Force the global verb's flags back into the default location for // main programs that still look in flag.Args() //TODO: We need to stop doing this globalVerbs.flags.ForceCommandLine() // apply the flags if flags.Version { fmt.Fprint(os.Stdout, Name, " version ", Version, "\n") return } endProfile := applyProfiler(rootCtx, &flags.Profile) ctx, cancel := context.WithCancel(rootCtx) // Defer the shutdown code defer func() { cancel() WaitForCleanup(rootCtx) endProfile() }() ctx, closeLogs = updateContext(ctx, &flags.Log, closeLogs) defer closeLogs() // Add the abort signal handler handleAbortSignals(task.CancelFunc(cancel)) // Now we are ready to run the main task err := main(ctx) if errors.Cause(err) == Restart { err = doRestart() } if err != nil { log.F(ctx, "Main failed\nError: %v", err) } } func doRestart() error { argv0 := file.ExecutablePath().System() files := make([]*os.File, syscall.Stderr+1) files[syscall.Stdin] = os.Stdin files[syscall.Stdout] = os.Stdout files[syscall.Stderr] = os.Stderr wd, err := os.Getwd() if nil != err { return err } _, err = os.StartProcess(argv0, os.Args, &os.ProcAttr{ Dir: wd, Env: os.Environ(), Files: files, Sys: &syscall.SysProcAttr{}, }) return err }
ek9852/gapid
core/app/run.go
GO
apache-2.0
4,928
package net.sf.yal10n.charset; /* * 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. */ import java.nio.BufferOverflowException; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; import java.nio.charset.CoderResult; import java.nio.charset.CodingErrorAction; /** * UTF-8 charset implementation that supports an optional BOM (Byte-Order-Mark). * Base on the Java UTF-8 charset. */ public class UTF8BOM extends Charset { private static final float MAXIMUM_BYTES_PER_CHARACTER = 7.0f; private static final float AVERAGE_BYTES_PER_CHARACTER = 1.1f; /** Name of the charset - used if you select a charset via a String. */ public static final String NAME = "UTF-8-BOM"; private static final Charset UTF8_CHARSET = Charset.forName( "UTF-8" ); private static final byte[] UTF8_BOM_BYTES = new byte[] { (byte) 0xef, (byte) 0xbb, (byte) 0xbf }; /** * Creates a new UTF8BOM charset. */ protected UTF8BOM() { super( NAME, null ); } /** * {@inheritDoc} */ @Override public boolean contains( Charset cs ) { return UTF8_CHARSET.contains( cs ); } /** * {@inheritDoc} */ @Override public CharsetDecoder newDecoder() { return new CharsetDecoder( this, 1.0f, 1.0f ) { private final CharsetDecoder utf8decoder = UTF8_CHARSET.newDecoder() .onMalformedInput( malformedInputAction() ).onUnmappableCharacter( unmappableCharacterAction() ); private boolean bomDone = false; private int bomIndexDone = 0; private byte[] bom = new byte[3]; @Override protected CoderResult decodeLoop( ByteBuffer in, CharBuffer out ) { utf8decoder.reset(); if ( !bomDone ) { try { while ( bomIndexDone < 3 ) { bom[bomIndexDone] = in.get(); if ( bom[bomIndexDone] == UTF8_BOM_BYTES[bomIndexDone] ) { bomIndexDone++; } else { break; } } bomDone = true; if ( bomIndexDone != 3 ) { ByteBuffer in2 = ByteBuffer.allocate( 3 + in.capacity() ); in2.mark(); in2.put( bom, 0, bomIndexDone + 1 ); in2.limit( in2.position() ); in2.reset(); utf8decoder.decode( in2, out, false ); return utf8decoder.decode( in, out, true ); } } catch ( BufferUnderflowException e ) { return CoderResult.UNDERFLOW; } } return utf8decoder.decode( in, out, true ); } /** * {@inheritDoc} */ @Override protected void implReset() { bomDone = false; bomIndexDone = 0; } }; } /** * {@inheritDoc} */ @Override public CharsetEncoder newEncoder() { return new CharsetEncoder( this, AVERAGE_BYTES_PER_CHARACTER, MAXIMUM_BYTES_PER_CHARACTER ) { private CharsetEncoder utf8encoder = UTF8_CHARSET.newEncoder().onMalformedInput( CodingErrorAction.REPORT ) .onUnmappableCharacter( CodingErrorAction.REPORT ); private boolean bomDone = false; /** * {@inheritDoc} */ @Override protected CoderResult encodeLoop( CharBuffer in, ByteBuffer out ) { utf8encoder.reset(); if ( !bomDone ) { try { out.put( UTF8_BOM_BYTES ); bomDone = true; } catch ( BufferOverflowException e ) { return CoderResult.OVERFLOW; } } return utf8encoder.encode( in, out, true ); } /** * {@inheritDoc} */ @Override protected void implReset() { bomDone = false; } }; } }
adangel/yal10n
src/main/java/net/sf/yal10n/charset/UTF8BOM.java
Java
apache-2.0
5,421
package org.zstack.sdk.sns.platform.dingtalk; import java.util.HashMap; import java.util.Map; import org.zstack.sdk.*; public class CreateSNSDingTalkEndpointAction extends AbstractAction { private static final HashMap<String, Parameter> parameterMap = new HashMap<>(); private static final HashMap<String, Parameter> nonAPIParameterMap = new HashMap<>(); public static class Result { public ErrorCode error; public org.zstack.sdk.sns.platform.dingtalk.CreateSNSDingTalkEndpointResult value; public Result throwExceptionIfError() { if (error != null) { throw new ApiException( String.format("error[code: %s, description: %s, details: %s]", error.code, error.description, error.details) ); } return this; } } @Param(required = true, maxLength = 2048, nonempty = false, nullElements = false, emptyString = true, noTrim = false) public java.lang.String url; @Param(required = false) public java.lang.Boolean atAll; @Param(required = false, nonempty = true, nullElements = false, emptyString = true, noTrim = false) public java.util.List atPersonPhoneNumbers; @Param(required = true, maxLength = 255, nonempty = false, nullElements = false, emptyString = true, noTrim = false) public java.lang.String name; @Param(required = false, maxLength = 2048, nonempty = false, nullElements = false, emptyString = true, noTrim = false) public java.lang.String description; @Param(required = false, nonempty = false, nullElements = false, emptyString = true, noTrim = false) public java.lang.String platformUuid; @Param(required = false) public java.lang.String resourceUuid; @Param(required = false) public java.util.List systemTags; @Param(required = false) public java.util.List userTags; @Param(required = true) public String sessionId; @NonAPIParam public long timeout = -1; @NonAPIParam public long pollingInterval = -1; private Result makeResult(ApiResult res) { Result ret = new Result(); if (res.error != null) { ret.error = res.error; return ret; } org.zstack.sdk.sns.platform.dingtalk.CreateSNSDingTalkEndpointResult value = res.getResult(org.zstack.sdk.sns.platform.dingtalk.CreateSNSDingTalkEndpointResult.class); ret.value = value == null ? new org.zstack.sdk.sns.platform.dingtalk.CreateSNSDingTalkEndpointResult() : value; return ret; } public Result call() { ApiResult res = ZSClient.call(this); return makeResult(res); } public void call(final Completion<Result> completion) { ZSClient.call(this, new InternalCompletion() { @Override public void complete(ApiResult res) { completion.complete(makeResult(res)); } }); } protected Map<String, Parameter> getParameterMap() { return parameterMap; } protected Map<String, Parameter> getNonAPIParameterMap() { return nonAPIParameterMap; } protected RestInfo getRestInfo() { RestInfo info = new RestInfo(); info.httpMethod = "POST"; info.path = "/sns/application-endpoints/ding-talk"; info.needSession = true; info.needPoll = true; info.parameterName = "params"; return info; } }
camilesing/zstack
sdk/src/main/java/org/zstack/sdk/sns/platform/dingtalk/CreateSNSDingTalkEndpointAction.java
Java
apache-2.0
3,482
package org.metaborg.core.completion; import java.io.Serializable; public class Completion implements ICompletion, Serializable { /** * Serializable because it is necessary to pass an object as a String to Eclipse additional info menu */ private static final long serialVersionUID = 6960435974459583999L; private final String name; private final String sort; private final String text; private final String additionalInfo; private String prefix = ""; private String suffix = ""; private Iterable<ICompletionItem> items; private final int startOffset; private final int endOffset; private boolean nested; private boolean fromOptionalPlaceholder; private final CompletionKind kind; public Completion(String name, String sort, String text, String additionalInfo, int startOffset, int endOffset, CompletionKind kind) { this.name = name; this.sort = sort; this.text = text; this.additionalInfo = additionalInfo; this.startOffset = startOffset; this.endOffset = endOffset; this.nested = false; this.fromOptionalPlaceholder = false; this.kind = kind; } public Completion(String name, String sort, String text, String additionalInfo, int startOffset, int endOffset, CompletionKind kind, String prefix, String suffix) { this.name = name; this.sort = sort; this.text = text; this.additionalInfo = additionalInfo; this.startOffset = startOffset; this.endOffset = endOffset; this.nested = false; this.fromOptionalPlaceholder = false; this.kind = kind; this.prefix = prefix; this.suffix = suffix; } @Override public String name() { return name; } @Override public String sort() { return sort; } @Override public String text() { return text; } @Override public String additionalInfo() { return additionalInfo; } @Override public String prefix() { return this.prefix; } @Override public String suffix() { return this.suffix; } @Override public Iterable<ICompletionItem> items() { return items; } @Override public void setItems(Iterable<ICompletionItem> items) { this.items = items; } @Override public int startOffset() { return startOffset; } @Override public int endOffset() { return endOffset; } @Override public boolean isNested() { return nested; } @Override public void setNested(boolean nested) { this.nested = nested; } @Override public boolean fromOptionalPlaceholder() { return fromOptionalPlaceholder; } @Override public void setOptionalPlaceholder(boolean optional) { this.fromOptionalPlaceholder = optional; } @Override public CompletionKind kind() { return this.kind; } @Override public String toString() { return name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((additionalInfo == null) ? 0 : additionalInfo.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((sort == null) ? 0 : sort.hashCode()); result = prime * result + ((text == null) ? 0 : text.hashCode()); return result; } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(getClass() != obj.getClass()) return false; Completion other = (Completion) obj; if(additionalInfo == null) { if(other.additionalInfo != null) return false; } else if(!additionalInfo.equals(other.additionalInfo)) return false; if(name == null) { if(other.name != null) return false; } else if(!name.equals(other.name)) return false; if(sort == null) { if(other.sort != null) return false; } else if(!sort.equals(other.sort)) return false; if(text == null) { if(other.text != null) return false; } else if(!text.equals(other.text)) return false; return true; } }
metaborg/spoofax
org.metaborg.core/src/main/java/org/metaborg/core/completion/Completion.java
Java
apache-2.0
4,484
/******************************************************************************* * Copyright 2015 Maximilian Stark | Dakror <mail@dakror.de> * * 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 de.dakror.webcamparser; import java.awt.Container; import java.awt.GridLayout; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.parser.PdfTextExtractor; /** * @author Maximilian Stark | Dakror */ public class EBookReader { static int start; static int page; public static void main(String[] args) throws Exception { Reader.language = "eng"; Reader.voice = "cmu-rms-hsmm"; Reader.init(); PdfReader reader = new PdfReader("Midnight_Tides.pdf"); start = 7; page = start; JFrame frame = new JFrame("Menu"); Container panel = frame.getContentPane(); panel.setLayout(new GridLayout(3, 1)); panel.add(new JButton(new AbstractAction("Prev") { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { page -= 2; Reader.player.cancel(); } })); panel.add(new JButton(new AbstractAction("Next") { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { if (Reader.player != null) Reader.player.cancel(); } })); panel.add(new JButton(new AbstractAction("Go to page") { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { page = Integer.parseInt(JOptionPane.showInputDialog("page number (start at 1):")) - 1; if (Reader.player != null) Reader.player.cancel(); } })); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.setResizable(false); frame.setVisible(true); for (; page <= reader.getNumberOfPages(); page++) { String s = PdfTextExtractor.getTextFromPage(reader, page); s = s.replace("—", ", ").replace(" - ", ", ").replace("Andü", "Andii"); System.out.println(); System.out.println("############## - Page " + page + " - ##############"); System.out.println(); System.out.println(s); Reader.read(s); } } }
Dakror/WebcamParser
src/de/dakror/webcamparser/EBookReader.java
Java
apache-2.0
2,948
package com.guanshuwei.smartstick.data; import java.util.Calendar; import java.util.Locale; import java.util.Vector; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.DatabaseUtils; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.provider.BaseColumns; import com.guanshuwei.smartstick.instance.HistoryModule; import com.guanshuwei.smartstick.instance.HistoryModule.LogType; import com.guanshuwei.smartstick.util.Utilities; public class HistoryDatabase { private static class Data { private static class Tables { public static class HistoryTable implements BaseColumns { public static final String TABLE_NAME = "HistoryDatabase"; public static final String NAME = "_NAME"; public static final String PHONEMUNBER = "_PHONENUMBER"; public static final String LOGTYPE = "_LOGTYPE"; public static final String LANGTITUDE = "_LANGTITUDE"; public static final String LONGITUDE = "_LONGITUDE"; public static final String DATE = "_DATE"; public static final String UNIQUE = "_UNIQUE"; public static final String CREATE_QUERY = "CREATE TABLE " + TABLE_NAME + " (" + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + NAME + " TEXT NOT NULL, " + PHONEMUNBER + " TEXT NOT NULL," + LOGTYPE + " TEXT NOT NULL," + DATE + " TEXT NOT NULL," + LANGTITUDE + " TEXT NOT NULL," + LONGITUDE + " TEXT NOT NULL);"; public static final String CREATE_UNIQUE = "CREATE UNIQUE INDEX " + UNIQUE + " ON " + TABLE_NAME + " (" + DATE + ");"; public static final String DROP_QUERY = "DROP TABLE IF EXISTS " + TABLE_NAME + ";"; } } private static boolean AnyMatch = false; private final Context applicationContext; private static class DataHelper extends SQLiteOpenHelper { public static final int USERINFO_DATABASE_VERSION = 2; public static final String USERINFO_DATABASE_NAME = "HistoryDatabase.db"; public DataHelper(Context context) { super(context, USERINFO_DATABASE_NAME, null, USERINFO_DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.beginTransaction(); try { db.execSQL(Tables.HistoryTable.CREATE_QUERY); db.execSQL(Tables.HistoryTable.CREATE_UNIQUE); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if (newVersion <= oldVersion) { return; } db.beginTransaction(); try { db.execSQL(Tables.HistoryTable.DROP_QUERY); db.setTransactionSuccessful(); } finally { db.endTransaction(); } this.onCreate(db); } } private DataHelper dataHelper; private boolean adapterInitialized; public Data(Context context) { this.applicationContext = context; } public synchronized void initialize() { if (this.adapterInitialized) { return; } this.dataHelper = new DataHelper(this.applicationContext); this.adapterInitialized = true; } public synchronized void release() { if (this.dataHelper != null) { this.dataHelper.close(); this.dataHelper = null; } this.adapterInitialized = false; } public synchronized void insert(HistoryModule item) throws Exception { if (!this.adapterInitialized) { this.initialize(); } SQLiteDatabase database = this.dataHelper.getWritableDatabase(); database.beginTransaction(); try { int y, m, d, h, mi, s; Calendar cal = Calendar.getInstance(); y = cal.get(Calendar.YEAR); m = cal.get(Calendar.MONTH); d = cal.get(Calendar.DATE); h = cal.get(Calendar.HOUR_OF_DAY); mi = cal.get(Calendar.MINUTE); s = cal.get(Calendar.SECOND); ContentValues values = new ContentValues(); values.put(Tables.HistoryTable.NAME, item.getUserName()); values.put(Tables.HistoryTable.PHONEMUNBER, item.getUserPhoneNumber()); values.put(Tables.HistoryTable.LOGTYPE, item.getLogType() .toString()); values.put(Tables.HistoryTable.LONGITUDE, String.valueOf(item.getLongitude())); values.put(Tables.HistoryTable.LANGTITUDE, String.valueOf(item.getLatitude())); values.put(Tables.HistoryTable.DATE, y + "年" + m + "月" + d + "日" + h + "时" + mi + "分" + s + "秒"); long id = database.replace(Tables.HistoryTable.TABLE_NAME, null, values); // Validate root id. if (id <= 0) { throw new Exception("Failed to save History"); } database.setTransactionSuccessful(); } finally { database.endTransaction(); } } // private synchronized String getDateTime() { // SimpleDateFormat dateFormat = new SimpleDateFormat( // "yyyy-MM-dd HH:mm:ss", Locale.getDefault()); // Date date = new Date(); // return dateFormat.format(date); // } public synchronized long getCount() { if (!this.adapterInitialized) { this.initialize(); } // Obtain total number of records in main table. SQLiteDatabase database = this.dataHelper.getReadableDatabase(); long result = DatabaseUtils.queryNumEntries(database, Tables.HistoryTable.TABLE_NAME); return result; } public synchronized Vector<HistoryModule> getAll() { if (!this.adapterInitialized) { this.initialize(); } Vector<HistoryModule> items = new Vector<HistoryModule>(); // Obtain database. SQLiteDatabase database = this.dataHelper.getReadableDatabase(); // Select all data, order depending or specified sort order. String where = Tables.HistoryTable._ID + " DESC"; Cursor reader = database.query(Tables.HistoryTable.TABLE_NAME, null, null, null, null, null, where); if (reader == null || reader.getCount() == 0) { if (reader != null) { reader.close(); } return items; } int columnIdIndex = reader.getColumnIndex(Tables.HistoryTable._ID); int columnNameIndex = reader .getColumnIndex(Tables.HistoryTable.NAME); int columnPhoneIndex = reader .getColumnIndex(Tables.HistoryTable.PHONEMUNBER); int columnTypeIndex = reader .getColumnIndex(Tables.HistoryTable.LOGTYPE); int columnLatIndex = reader .getColumnIndex(Tables.HistoryTable.LANGTITUDE); int columnLngIndex = reader .getColumnIndex(Tables.HistoryTable.LONGITUDE); int columnDateIndex = reader .getColumnIndex(Tables.HistoryTable.DATE); reader.moveToFirst(); while (!reader.isAfterLast()) { HistoryModule item = new HistoryModule(); item.setID(reader.getLong(columnIdIndex)); item.setUserName(reader.getString(columnNameIndex)); item.setUserPhoneNumber(reader.getString(columnPhoneIndex)); item.setLongitude(Double.parseDouble(reader .getString(columnLngIndex))); item.setLatitude(Double.parseDouble(reader .getString(columnLatIndex))); LogType type; if (reader.getString(columnTypeIndex).equals( LogType.ALERT.toString())) { type = LogType.ALERT; } else { type = LogType.LOCATE; } item.setLogType(type); item.setmDate(reader.getString(columnDateIndex)); items.add(item); reader.moveToNext(); } reader.close(); return items; } public synchronized void removeAll() { if (!this.adapterInitialized) { this.initialize(); } SQLiteDatabase database = this.dataHelper.getWritableDatabase(); database.beginTransaction(); try { database.delete(Tables.HistoryTable.TABLE_NAME, null, null); database.setTransactionSuccessful(); } finally { database.endTransaction(); } } public synchronized boolean exists(HistoryModule item) throws Exception { if (!this.adapterInitialized) { this.initialize(); } // Get original item Id first. long recordId = this.getRecordId(item); return recordId > 0; } public synchronized void remove(HistoryModule item) throws Exception { if (!this.adapterInitialized) { this.initialize(); } long recordId = this.getRecordId(item); SQLiteDatabase database = this.dataHelper.getReadableDatabase(); database.beginTransaction(); try { String deleteWhere = Tables.HistoryTable._ID + " = ?"; String[] deleteArgs = new String[] { String.valueOf(recordId) }; database.delete(Tables.HistoryTable.TABLE_NAME, deleteWhere, deleteArgs); database.setTransactionSuccessful(); } catch (Exception e) { e.printStackTrace(); } finally { database.endTransaction(); } } public synchronized Vector<HistoryModule> getLatestRecords(int limit) { if (!this.adapterInitialized) { this.initialize(); } Vector<HistoryModule> items = new Vector<HistoryModule>(); try { // Obtain database. SQLiteDatabase database = this.dataHelper.getReadableDatabase(); // Select recently data, order depending or specified sort // order. String where = Tables.HistoryTable.PHONEMUNBER + " DESC"; Cursor reader = database.query(Tables.HistoryTable.TABLE_NAME, null, null, null, null, null, where, "0, " + String.valueOf(limit)); if (reader == null || reader.getCount() == 0) { if (reader != null) { reader.close(); } return items; } int columnIdIndex = reader .getColumnIndex(Tables.HistoryTable._ID); int columnNameIndex = reader .getColumnIndex(Tables.HistoryTable.NAME); int columnPhoneIndex = reader .getColumnIndex(Tables.HistoryTable.PHONEMUNBER); int columnTypeIndex = reader .getColumnIndex(Tables.HistoryTable.LOGTYPE); int columnLatIndex = reader .getColumnIndex(Tables.HistoryTable.LANGTITUDE); int columnLngIndex = reader .getColumnIndex(Tables.HistoryTable.LONGITUDE); int columnDateIndex = reader .getColumnIndex(Tables.HistoryTable.DATE); reader.moveToFirst(); while (!reader.isAfterLast()) { HistoryModule item = new HistoryModule(); item.setID(reader.getLong(columnIdIndex)); item.setUserName(reader.getString(columnNameIndex)); item.setUserPhoneNumber(reader.getString(columnPhoneIndex)); item.setLongitude(Double.parseDouble(reader .getString(columnLngIndex))); item.setLatitude(Double.parseDouble(reader .getString(columnLatIndex))); LogType type; if (reader.getString(columnTypeIndex).equals( LogType.ALERT.toString())) { type = LogType.ALERT; } else { type = LogType.LOCATE; } item.setLogType(type); item.setmDate(reader.getString(columnDateIndex)); items.add(item); reader.moveToNext(); } reader.close(); } catch (Exception e) { e.printStackTrace(); } return items; } public synchronized Vector<HistoryModule> findMatches(String substring) { Vector<HistoryModule> items = new Vector<HistoryModule>(); if (Utilities.isStringNullOrEmpty(substring)) { return items; } if (!this.adapterInitialized) { this.initialize(); } SQLiteDatabase database = this.dataHelper.getReadableDatabase(); String where = "LOWER(" + Tables.HistoryTable.NAME + ") LIKE ?"; String[] args; if (Data.AnyMatch) { args = new String[] { "%" + substring.toLowerCase(Locale.US) + "%" }; } else { args = new String[] { substring.toLowerCase(Locale.US) + "%" }; } Cursor reader = database.query(Tables.HistoryTable.TABLE_NAME, null, where, args, null, null, Tables.HistoryTable.PHONEMUNBER + " DESC"); if (reader == null || reader.getCount() == 0) { if (reader != null) { reader.close(); } return items; } int columnIdIndex = reader.getColumnIndex(Tables.HistoryTable._ID); int columnNameIndex = reader .getColumnIndex(Tables.HistoryTable.NAME); int columnPhoneIndex = reader .getColumnIndex(Tables.HistoryTable.PHONEMUNBER); int columnTypeIndex = reader .getColumnIndex(Tables.HistoryTable.LOGTYPE); int columnLatIndex = reader .getColumnIndex(Tables.HistoryTable.LANGTITUDE); int columnLngIndex = reader .getColumnIndex(Tables.HistoryTable.LONGITUDE); int columnDateIndex = reader .getColumnIndex(Tables.HistoryTable.DATE); reader.moveToFirst(); while (!reader.isAfterLast()) { HistoryModule item = new HistoryModule(); item.setID(reader.getLong(columnIdIndex)); item.setUserName(reader.getString(columnNameIndex)); item.setUserPhoneNumber(reader.getString(columnPhoneIndex)); item.setLongitude(Double.parseDouble(reader .getString(columnLngIndex))); item.setLatitude(Double.parseDouble(reader .getString(columnLatIndex))); LogType type; if (reader.getString(columnTypeIndex).equals( LogType.ALERT.toString())) { type = LogType.ALERT; } else { type = LogType.LOCATE; } item.setLogType(type); item.setmDate(reader.getString(columnDateIndex)); items.add(item); reader.moveToNext(); } reader.close(); return items; } private long getRecordId(HistoryModule item) throws Exception { // Obtain item id first. SQLiteDatabase database = this.dataHelper.getReadableDatabase(); String[] columns = new String[] { Tables.HistoryTable._ID }; // unique name match final String where = Tables.HistoryTable.NAME + " = ?"; final String[] args = new String[] { String.valueOf(item .getUserName()) }; // Select records. Cursor reader = database.query(Tables.HistoryTable.TABLE_NAME, columns, where, args, null, null, null); // Skip it, nothing to remove. if (reader == null || reader.getCount() == 0) { if (reader != null) { reader.close(); } return 0; } // Check total number of records. if (reader.getCount() > 1) { reader.close(); throw new Exception( "More than one record was found. Can't proceed."); } reader.moveToFirst(); int columnIndex = reader.getColumnIndex(Tables.HistoryTable._ID); long recordId = reader.getLong(columnIndex); reader.close(); if (recordId <= 0) { throw new Exception("Record id is: " + recordId + ". Can't proceed."); } return recordId; } } public static final String LOG_TAG = "AutoSuggestionHostory"; private static final long HISTORY_LIMIT = 1000; private final Context applicationContext; public HistoryDatabase(Context context) { this.applicationContext = context; } public synchronized boolean addItem(HistoryModule item) { Data adapter = new Data(this.applicationContext); try { adapter.initialize(); if (!Utilities.isStringNullOrEmpty(item.getUserPhoneNumber()) && !Utilities .isStringNullOrEmpty(item.getUserPhoneNumber())) { adapter.insert(item); return true; } return false; } catch (Exception e) { e.printStackTrace(); return false; } finally { adapter.release(); } } public synchronized long getCount() { Data adapter = new Data(this.applicationContext); long result = 0; try { adapter.initialize(); result = adapter.getCount(); } catch (Exception e) { e.printStackTrace(); } finally { adapter.release(); } return result; } public synchronized Vector<HistoryModule> getAll() { Data adapter = new Data(this.applicationContext); try { adapter.initialize(); return adapter.getAll(); } catch (SQLiteException sqlEx) { // TODO: Find another way to deal with database lock, maybe // semaphore with acquire/release. sqlEx.printStackTrace(); return null; } finally { adapter.release(); } } public synchronized Vector<HistoryModule> getLatestRecords(int limit) { Data adapter = new Data(this.applicationContext); try { adapter.initialize(); return adapter.getLatestRecords(limit); } catch (SQLiteException sqlEx) { // TODO: Find another way to deal with database lock, maybe // semaphore with acquire/release. sqlEx.printStackTrace(); return null; } finally { adapter.release(); } } public synchronized void removeAll() { Data adapter = new Data(this.applicationContext); try { adapter.initialize(); adapter.removeAll(); } catch (Exception e) { e.printStackTrace(); } finally { adapter.release(); } } public synchronized boolean exists(HistoryModule item) { Data adapter = new Data(this.applicationContext); try { adapter.initialize(); return adapter.exists(item); } catch (Exception e) { e.printStackTrace(); return false; } finally { adapter.release(); } } public synchronized void remove(HistoryModule item) { Data adapter = new Data(this.applicationContext); try { adapter.initialize(); adapter.remove(item); } catch (Exception e) { e.printStackTrace(); } finally { adapter.release(); } } public synchronized Vector<HistoryModule> findMatches(String substring) { Data adapter = new Data(this.applicationContext); try { adapter.initialize(); return adapter.findMatches(substring); } catch (Exception e) { e.printStackTrace(); return new Vector<HistoryModule>(); } finally { adapter.release(); } } public synchronized boolean canSave() { Data adapter = new Data(this.applicationContext); try { adapter.initialize(); return adapter.getCount() < HISTORY_LIMIT; } catch (Exception e) { e.printStackTrace(); return false; } finally { adapter.release(); } } }
richarddan/SmartStick
src/com/guanshuwei/smartstick/data/HistoryDatabase.java
Java
apache-2.0
17,431
package org.tourgune.apptrack.bean; /** * AppTrack * * Created by CICtourGUNE on 10/04/13. * Copyright (c) 2013 CICtourGUNE. All rights reserved. * * Bean de la tabla variables de la base de datos */ public class Variable { private int idvariable; private int idaplicacion; private int idtipo; private String nombrevariable; private double max; private double min; private String fechadesde; private String fechahasta; private Boolean multiopcion; private Boolean obligatorio; private java.util.List<Opcion> opciones; public java.util.List<Opcion> getOpciones() { return opciones; } public void setOpciones(java.util.List<Opcion> opciones) { this.opciones = opciones; } public int getIdvariable() { return idvariable; } public void setIdvariable(int idvariable) { this.idvariable = idvariable; } public int getIdaplicacion() { return idaplicacion; } public void setIdaplicacion(int idaplicacion) { this.idaplicacion = idaplicacion; } public int getIdtipo() { return idtipo; } public void setIdtipo(int idtipo) { this.idtipo = idtipo; } public String getNombrevariable() { return nombrevariable; } public void setNombrevariable(String nombrevariable) { this.nombrevariable = nombrevariable; } public double getMax() { return max; } public void setMax(double max) { this.max = max; } public double getMin() { return min; } public void setMin(Double min) { this.min = min; } public String getFechadesde() { return fechadesde; } public void setFechadesde(String fechadesde) { this.fechadesde = fechadesde; } public String getFechahasta() { return fechahasta; } public void setFechahasta(String fechahasta) { this.fechahasta = fechahasta; } public Boolean getMultiopcion() { return multiopcion; } public void setMultiopcion(Boolean multiopcion) { this.multiopcion = multiopcion; } public Boolean getObligatorio() { return obligatorio; } public void setObligatorio(Boolean obligatorio) { this.obligatorio = obligatorio; } }
cictourgune/EmocionometroWeb
src/org/tourgune/apptrack/bean/Variable.java
Java
apache-2.0
2,054
/* * Copyright 2020 Google LLC * * 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 * * https://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. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/dialogflow/v2beta1/entity_type.proto package com.google.cloud.dialogflow.v2beta1; /** * * * <pre> * The response message for [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntityTypes]. * </pre> * * Protobuf type {@code google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse} */ public final class BatchUpdateEntityTypesResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse) BatchUpdateEntityTypesResponseOrBuilder { private static final long serialVersionUID = 0L; // Use BatchUpdateEntityTypesResponse.newBuilder() to construct. private BatchUpdateEntityTypesResponse( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private BatchUpdateEntityTypesResponse() { entityTypes_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new BatchUpdateEntityTypesResponse(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private BatchUpdateEntityTypesResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { if (!((mutable_bitField0_ & 0x00000001) != 0)) { entityTypes_ = new java.util.ArrayList<com.google.cloud.dialogflow.v2beta1.EntityType>(); mutable_bitField0_ |= 0x00000001; } entityTypes_.add( input.readMessage( com.google.cloud.dialogflow.v2beta1.EntityType.parser(), extensionRegistry)); break; } default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000001) != 0)) { entityTypes_ = java.util.Collections.unmodifiableList(entityTypes_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.v2beta1.EntityTypeProto .internal_static_google_cloud_dialogflow_v2beta1_BatchUpdateEntityTypesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.v2beta1.EntityTypeProto .internal_static_google_cloud_dialogflow_v2beta1_BatchUpdateEntityTypesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse.class, com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse.Builder.class); } public static final int ENTITY_TYPES_FIELD_NUMBER = 1; private java.util.List<com.google.cloud.dialogflow.v2beta1.EntityType> entityTypes_; /** * * * <pre> * The collection of updated or created entity types. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.dialogflow.v2beta1.EntityType> getEntityTypesList() { return entityTypes_; } /** * * * <pre> * The collection of updated or created entity types. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.dialogflow.v2beta1.EntityTypeOrBuilder> getEntityTypesOrBuilderList() { return entityTypes_; } /** * * * <pre> * The collection of updated or created entity types. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code> */ @java.lang.Override public int getEntityTypesCount() { return entityTypes_.size(); } /** * * * <pre> * The collection of updated or created entity types. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code> */ @java.lang.Override public com.google.cloud.dialogflow.v2beta1.EntityType getEntityTypes(int index) { return entityTypes_.get(index); } /** * * * <pre> * The collection of updated or created entity types. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code> */ @java.lang.Override public com.google.cloud.dialogflow.v2beta1.EntityTypeOrBuilder getEntityTypesOrBuilder( int index) { return entityTypes_.get(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < entityTypes_.size(); i++) { output.writeMessage(1, entityTypes_.get(i)); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < entityTypes_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, entityTypes_.get(i)); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse)) { return super.equals(obj); } com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse other = (com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse) obj; if (!getEntityTypesList().equals(other.getEntityTypesList())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getEntityTypesCount() > 0) { hash = (37 * hash) + ENTITY_TYPES_FIELD_NUMBER; hash = (53 * hash) + getEntityTypesList().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * The response message for [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntityTypes]. * </pre> * * Protobuf type {@code google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse) com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.v2beta1.EntityTypeProto .internal_static_google_cloud_dialogflow_v2beta1_BatchUpdateEntityTypesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.v2beta1.EntityTypeProto .internal_static_google_cloud_dialogflow_v2beta1_BatchUpdateEntityTypesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse.class, com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse.Builder.class); } // Construct using // com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getEntityTypesFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); if (entityTypesBuilder_ == null) { entityTypes_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); } else { entityTypesBuilder_.clear(); } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.dialogflow.v2beta1.EntityTypeProto .internal_static_google_cloud_dialogflow_v2beta1_BatchUpdateEntityTypesResponse_descriptor; } @java.lang.Override public com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse getDefaultInstanceForType() { return com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse .getDefaultInstance(); } @java.lang.Override public com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse build() { com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse buildPartial() { com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse result = new com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse(this); int from_bitField0_ = bitField0_; if (entityTypesBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { entityTypes_ = java.util.Collections.unmodifiableList(entityTypes_); bitField0_ = (bitField0_ & ~0x00000001); } result.entityTypes_ = entityTypes_; } else { result.entityTypes_ = entityTypesBuilder_.build(); } onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse) { return mergeFrom( (com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse other) { if (other == com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse .getDefaultInstance()) return this; if (entityTypesBuilder_ == null) { if (!other.entityTypes_.isEmpty()) { if (entityTypes_.isEmpty()) { entityTypes_ = other.entityTypes_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureEntityTypesIsMutable(); entityTypes_.addAll(other.entityTypes_); } onChanged(); } } else { if (!other.entityTypes_.isEmpty()) { if (entityTypesBuilder_.isEmpty()) { entityTypesBuilder_.dispose(); entityTypesBuilder_ = null; entityTypes_ = other.entityTypes_; bitField0_ = (bitField0_ & ~0x00000001); entityTypesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getEntityTypesFieldBuilder() : null; } else { entityTypesBuilder_.addAllMessages(other.entityTypes_); } } } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.util.List<com.google.cloud.dialogflow.v2beta1.EntityType> entityTypes_ = java.util.Collections.emptyList(); private void ensureEntityTypesIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { entityTypes_ = new java.util.ArrayList<com.google.cloud.dialogflow.v2beta1.EntityType>(entityTypes_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dialogflow.v2beta1.EntityType, com.google.cloud.dialogflow.v2beta1.EntityType.Builder, com.google.cloud.dialogflow.v2beta1.EntityTypeOrBuilder> entityTypesBuilder_; /** * * * <pre> * The collection of updated or created entity types. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code> */ public java.util.List<com.google.cloud.dialogflow.v2beta1.EntityType> getEntityTypesList() { if (entityTypesBuilder_ == null) { return java.util.Collections.unmodifiableList(entityTypes_); } else { return entityTypesBuilder_.getMessageList(); } } /** * * * <pre> * The collection of updated or created entity types. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code> */ public int getEntityTypesCount() { if (entityTypesBuilder_ == null) { return entityTypes_.size(); } else { return entityTypesBuilder_.getCount(); } } /** * * * <pre> * The collection of updated or created entity types. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code> */ public com.google.cloud.dialogflow.v2beta1.EntityType getEntityTypes(int index) { if (entityTypesBuilder_ == null) { return entityTypes_.get(index); } else { return entityTypesBuilder_.getMessage(index); } } /** * * * <pre> * The collection of updated or created entity types. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code> */ public Builder setEntityTypes(int index, com.google.cloud.dialogflow.v2beta1.EntityType value) { if (entityTypesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureEntityTypesIsMutable(); entityTypes_.set(index, value); onChanged(); } else { entityTypesBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The collection of updated or created entity types. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code> */ public Builder setEntityTypes( int index, com.google.cloud.dialogflow.v2beta1.EntityType.Builder builderForValue) { if (entityTypesBuilder_ == null) { ensureEntityTypesIsMutable(); entityTypes_.set(index, builderForValue.build()); onChanged(); } else { entityTypesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The collection of updated or created entity types. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code> */ public Builder addEntityTypes(com.google.cloud.dialogflow.v2beta1.EntityType value) { if (entityTypesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureEntityTypesIsMutable(); entityTypes_.add(value); onChanged(); } else { entityTypesBuilder_.addMessage(value); } return this; } /** * * * <pre> * The collection of updated or created entity types. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code> */ public Builder addEntityTypes(int index, com.google.cloud.dialogflow.v2beta1.EntityType value) { if (entityTypesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureEntityTypesIsMutable(); entityTypes_.add(index, value); onChanged(); } else { entityTypesBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The collection of updated or created entity types. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code> */ public Builder addEntityTypes( com.google.cloud.dialogflow.v2beta1.EntityType.Builder builderForValue) { if (entityTypesBuilder_ == null) { ensureEntityTypesIsMutable(); entityTypes_.add(builderForValue.build()); onChanged(); } else { entityTypesBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The collection of updated or created entity types. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code> */ public Builder addEntityTypes( int index, com.google.cloud.dialogflow.v2beta1.EntityType.Builder builderForValue) { if (entityTypesBuilder_ == null) { ensureEntityTypesIsMutable(); entityTypes_.add(index, builderForValue.build()); onChanged(); } else { entityTypesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The collection of updated or created entity types. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code> */ public Builder addAllEntityTypes( java.lang.Iterable<? extends com.google.cloud.dialogflow.v2beta1.EntityType> values) { if (entityTypesBuilder_ == null) { ensureEntityTypesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, entityTypes_); onChanged(); } else { entityTypesBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The collection of updated or created entity types. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code> */ public Builder clearEntityTypes() { if (entityTypesBuilder_ == null) { entityTypes_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { entityTypesBuilder_.clear(); } return this; } /** * * * <pre> * The collection of updated or created entity types. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code> */ public Builder removeEntityTypes(int index) { if (entityTypesBuilder_ == null) { ensureEntityTypesIsMutable(); entityTypes_.remove(index); onChanged(); } else { entityTypesBuilder_.remove(index); } return this; } /** * * * <pre> * The collection of updated or created entity types. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code> */ public com.google.cloud.dialogflow.v2beta1.EntityType.Builder getEntityTypesBuilder(int index) { return getEntityTypesFieldBuilder().getBuilder(index); } /** * * * <pre> * The collection of updated or created entity types. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code> */ public com.google.cloud.dialogflow.v2beta1.EntityTypeOrBuilder getEntityTypesOrBuilder( int index) { if (entityTypesBuilder_ == null) { return entityTypes_.get(index); } else { return entityTypesBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The collection of updated or created entity types. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code> */ public java.util.List<? extends com.google.cloud.dialogflow.v2beta1.EntityTypeOrBuilder> getEntityTypesOrBuilderList() { if (entityTypesBuilder_ != null) { return entityTypesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(entityTypes_); } } /** * * * <pre> * The collection of updated or created entity types. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code> */ public com.google.cloud.dialogflow.v2beta1.EntityType.Builder addEntityTypesBuilder() { return getEntityTypesFieldBuilder() .addBuilder(com.google.cloud.dialogflow.v2beta1.EntityType.getDefaultInstance()); } /** * * * <pre> * The collection of updated or created entity types. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code> */ public com.google.cloud.dialogflow.v2beta1.EntityType.Builder addEntityTypesBuilder(int index) { return getEntityTypesFieldBuilder() .addBuilder(index, com.google.cloud.dialogflow.v2beta1.EntityType.getDefaultInstance()); } /** * * * <pre> * The collection of updated or created entity types. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code> */ public java.util.List<com.google.cloud.dialogflow.v2beta1.EntityType.Builder> getEntityTypesBuilderList() { return getEntityTypesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dialogflow.v2beta1.EntityType, com.google.cloud.dialogflow.v2beta1.EntityType.Builder, com.google.cloud.dialogflow.v2beta1.EntityTypeOrBuilder> getEntityTypesFieldBuilder() { if (entityTypesBuilder_ == null) { entityTypesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dialogflow.v2beta1.EntityType, com.google.cloud.dialogflow.v2beta1.EntityType.Builder, com.google.cloud.dialogflow.v2beta1.EntityTypeOrBuilder>( entityTypes_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); entityTypes_ = null; } return entityTypesBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse) } // @@protoc_insertion_point(class_scope:google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse) private static final com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse(); } public static com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<BatchUpdateEntityTypesResponse> PARSER = new com.google.protobuf.AbstractParser<BatchUpdateEntityTypesResponse>() { @java.lang.Override public BatchUpdateEntityTypesResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new BatchUpdateEntityTypesResponse(input, extensionRegistry); } }; public static com.google.protobuf.Parser<BatchUpdateEntityTypesResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<BatchUpdateEntityTypesResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/java-dialogflow
proto-google-cloud-dialogflow-v2beta1/src/main/java/com/google/cloud/dialogflow/v2beta1/BatchUpdateEntityTypesResponse.java
Java
apache-2.0
33,021
# Copyright 2012 OpenStack Foundation. # Copyright 2015 Hewlett-Packard Development Company, L.P. # Copyright 2017 FUJITSU LIMITED # 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. # import inspect import itertools import logging import re import time import urllib.parse as urlparse import debtcollector.renames from keystoneauth1 import exceptions as ksa_exc import requests from neutronclient._i18n import _ from neutronclient import client from neutronclient.common import exceptions from neutronclient.common import extension as client_extension from neutronclient.common import serializer from neutronclient.common import utils _logger = logging.getLogger(__name__) HEX_ELEM = '[0-9A-Fa-f]' UUID_PATTERN = '-'.join([HEX_ELEM + '{8}', HEX_ELEM + '{4}', HEX_ELEM + '{4}', HEX_ELEM + '{4}', HEX_ELEM + '{12}']) def exception_handler_v20(status_code, error_content): """Exception handler for API v2.0 client. This routine generates the appropriate Neutron exception according to the contents of the response body. :param status_code: HTTP error status code :param error_content: deserialized body of error response """ error_dict = None request_ids = error_content.request_ids if isinstance(error_content, dict): error_dict = error_content.get('NeutronError') # Find real error type client_exc = None if error_dict: # If Neutron key is found, it will definitely contain # a 'message' and 'type' keys? try: error_type = error_dict['type'] error_message = error_dict['message'] if error_dict['detail']: error_message += "\n" + error_dict['detail'] # If corresponding exception is defined, use it. client_exc = getattr(exceptions, '%sClient' % error_type, None) except Exception: error_message = "%s" % error_dict else: error_message = None if isinstance(error_content, dict): error_message = error_content.get('message') if not error_message: # If we end up here the exception was not a neutron error error_message = "%s-%s" % (status_code, error_content) # If an exception corresponding to the error type is not found, # look up per status-code client exception. if not client_exc: client_exc = exceptions.HTTP_EXCEPTION_MAP.get(status_code) # If there is no exception per status-code, # Use NeutronClientException as fallback. if not client_exc: client_exc = exceptions.NeutronClientException raise client_exc(message=error_message, status_code=status_code, request_ids=request_ids) class _RequestIdMixin(object): """Wrapper class to expose x-openstack-request-id to the caller.""" def _request_ids_setup(self): self._request_ids = [] @property def request_ids(self): return self._request_ids def _append_request_ids(self, resp): """Add request_ids as an attribute to the object :param resp: Response object or list of Response objects """ if isinstance(resp, list): # Add list of request_ids if response is of type list. for resp_obj in resp: self._append_request_id(resp_obj) elif resp is not None: # Add request_ids if response contains single object. self._append_request_id(resp) def _append_request_id(self, resp): if isinstance(resp, requests.Response): # Extract 'x-openstack-request-id' from headers if # response is a Response object. request_id = resp.headers.get('x-openstack-request-id') else: # If resp is of type string. request_id = resp if request_id: self._request_ids.append(request_id) class _DictWithMeta(dict, _RequestIdMixin): def __init__(self, values, resp): super(_DictWithMeta, self).__init__(values) self._request_ids_setup() self._append_request_ids(resp) class _TupleWithMeta(tuple, _RequestIdMixin): def __new__(cls, values, resp): return super(_TupleWithMeta, cls).__new__(cls, values) def __init__(self, values, resp): self._request_ids_setup() self._append_request_ids(resp) class _StrWithMeta(str, _RequestIdMixin): def __new__(cls, value, resp): return super(_StrWithMeta, cls).__new__(cls, value) def __init__(self, values, resp): self._request_ids_setup() self._append_request_ids(resp) class _GeneratorWithMeta(_RequestIdMixin): def __init__(self, paginate_func, collection, path, **params): self.paginate_func = paginate_func self.collection = collection self.path = path self.params = params self.generator = None self._request_ids_setup() def _paginate(self): for r in self.paginate_func( self.collection, self.path, **self.params): yield r, r.request_ids def __iter__(self): return self # Python 3 compatibility def __next__(self): return self.next() def next(self): if not self.generator: self.generator = self._paginate() try: obj, req_id = next(self.generator) self._append_request_ids(req_id) except StopIteration: raise StopIteration() return obj class ClientBase(object): """Client for the OpenStack Neutron v2.0 API. :param string username: Username for authentication. (optional) :param string user_id: User ID for authentication. (optional) :param string password: Password for authentication. (optional) :param string token: Token for authentication. (optional) :param string tenant_name: DEPRECATED! Use project_name instead. :param string project_name: Project name. (optional) :param string tenant_id: DEPRECATED! Use project_id instead. :param string project_id: Project id. (optional) :param string auth_strategy: 'keystone' by default, 'noauth' for no authentication against keystone. (optional) :param string auth_url: Keystone service endpoint for authorization. :param string service_type: Network service type to pull from the keystone catalog (e.g. 'network') (optional) :param string endpoint_type: Network service endpoint type to pull from the keystone catalog (e.g. 'publicURL', 'internalURL', or 'adminURL') (optional) :param string region_name: Name of a region to select when choosing an endpoint from the service catalog. :param string endpoint_url: A user-supplied endpoint URL for the neutron service. Lazy-authentication is possible for API service calls if endpoint is set at instantiation.(optional) :param integer timeout: Allows customization of the timeout for client http requests. (optional) :param bool insecure: SSL certificate validation. (optional) :param bool log_credentials: Allow for logging of passwords or not. Defaults to False. (optional) :param string ca_cert: SSL CA bundle file to use. (optional) :param cert: A client certificate to pass to requests. These are of the same form as requests expects. Either a single filename containing both the certificate and key or a tuple containing the path to the certificate then a path to the key. (optional) :param integer retries: How many times idempotent (GET, PUT, DELETE) requests to Neutron server should be retried if they fail (default: 0). :param bool raise_errors: If True then exceptions caused by connection failure are propagated to the caller. (default: True) :param session: Keystone client auth session to use. (optional) :param auth: Keystone auth plugin to use. (optional) Example:: from neutronclient.v2_0 import client neutron = client.Client(username=USER, password=PASS, project_name=PROJECT_NAME, auth_url=KEYSTONE_URL) nets = neutron.list_networks() ... """ # API has no way to report plurals, so we have to hard code them # This variable should be overridden by a child class. EXTED_PLURALS = {} @debtcollector.renames.renamed_kwarg( 'tenant_id', 'project_id', replace=True) def __init__(self, **kwargs): """Initialize a new client for the Neutron v2.0 API.""" super(ClientBase, self).__init__() self.retries = kwargs.pop('retries', 0) self.raise_errors = kwargs.pop('raise_errors', True) self.httpclient = client.construct_http_client(**kwargs) self.version = '2.0' self.action_prefix = "/v%s" % (self.version) self.retry_interval = 1 def _handle_fault_response(self, status_code, response_body, resp): # Create exception with HTTP status code and message _logger.debug("Error message: %s", response_body) # Add deserialized error message to exception arguments try: des_error_body = self.deserialize(response_body, status_code) except Exception: # If unable to deserialized body it is probably not a # Neutron error des_error_body = {'message': response_body} error_body = self._convert_into_with_meta(des_error_body, resp) # Raise the appropriate exception exception_handler_v20(status_code, error_body) def do_request(self, method, action, body=None, headers=None, params=None): # Add format and project_id action = self.action_prefix + action if isinstance(params, dict) and params: params = utils.safe_encode_dict(params) action += '?' + urlparse.urlencode(params, doseq=1) if body: body = self.serialize(body) resp, replybody = self.httpclient.do_request(action, method, body=body, headers=headers) status_code = resp.status_code if status_code in (requests.codes.ok, requests.codes.created, requests.codes.accepted, requests.codes.no_content): data = self.deserialize(replybody, status_code) return self._convert_into_with_meta(data, resp) else: if not replybody: replybody = resp.reason self._handle_fault_response(status_code, replybody, resp) def get_auth_info(self): return self.httpclient.get_auth_info() def serialize(self, data): """Serializes a dictionary into JSON. A dictionary with a single key can be passed and it can contain any structure. """ if data is None: return None elif isinstance(data, dict): return serializer.Serializer().serialize(data) else: raise Exception(_("Unable to serialize object of type = '%s'") % type(data)) def deserialize(self, data, status_code): """Deserializes a JSON string into a dictionary.""" if not data: return data return serializer.Serializer().deserialize( data)['body'] def retry_request(self, method, action, body=None, headers=None, params=None): """Call do_request with the default retry configuration. Only idempotent requests should retry failed connection attempts. :raises: ConnectionFailed if the maximum # of retries is exceeded """ max_attempts = self.retries + 1 for i in range(max_attempts): try: return self.do_request(method, action, body=body, headers=headers, params=params) except (exceptions.ConnectionFailed, ksa_exc.ConnectionError): # Exception has already been logged by do_request() if i < self.retries: _logger.debug('Retrying connection to Neutron service') time.sleep(self.retry_interval) elif self.raise_errors: raise if self.retries: msg = (_("Failed to connect to Neutron server after %d attempts") % max_attempts) else: msg = _("Failed to connect Neutron server") raise exceptions.ConnectionFailed(reason=msg) def delete(self, action, body=None, headers=None, params=None): return self.retry_request("DELETE", action, body=body, headers=headers, params=params) def get(self, action, body=None, headers=None, params=None): return self.retry_request("GET", action, body=body, headers=headers, params=params) def post(self, action, body=None, headers=None, params=None): # Do not retry POST requests to avoid the orphan objects problem. return self.do_request("POST", action, body=body, headers=headers, params=params) def put(self, action, body=None, headers=None, params=None): return self.retry_request("PUT", action, body=body, headers=headers, params=params) def list(self, collection, path, retrieve_all=True, **params): if retrieve_all: res = [] request_ids = [] for r in self._pagination(collection, path, **params): res.extend(r[collection]) request_ids.extend(r.request_ids) return _DictWithMeta({collection: res}, request_ids) else: return _GeneratorWithMeta(self._pagination, collection, path, **params) def _pagination(self, collection, path, **params): if params.get('page_reverse', False): linkrel = 'previous' else: linkrel = 'next' next = True while next: res = self.get(path, params=params) yield res next = False try: for link in res['%s_links' % collection]: if link['rel'] == linkrel: query_str = urlparse.urlparse(link['href']).query params = urlparse.parse_qs(query_str) next = True break except KeyError: break def _convert_into_with_meta(self, item, resp): if item: if isinstance(item, dict): return _DictWithMeta(item, resp) elif isinstance(item, str): return _StrWithMeta(item, resp) else: return _TupleWithMeta((), resp) def get_resource_plural(self, resource): for k in self.EXTED_PLURALS: if self.EXTED_PLURALS[k] == resource: return k return resource + 's' def find_resource_by_id(self, resource, resource_id, cmd_resource=None, parent_id=None, fields=None): if not cmd_resource: cmd_resource = resource cmd_resource_plural = self.get_resource_plural(cmd_resource) resource_plural = self.get_resource_plural(resource) # TODO(amotoki): Use show_%s instead of list_%s obj_lister = getattr(self, "list_%s" % cmd_resource_plural) # perform search by id only if we are passing a valid UUID match = re.match(UUID_PATTERN, resource_id) collection = resource_plural if match: params = {'id': resource_id} if fields: params['fields'] = fields if parent_id: data = obj_lister(parent_id, **params) else: data = obj_lister(**params) if data and data[collection]: return data[collection][0] not_found_message = (_("Unable to find %(resource)s with id " "'%(id)s'") % {'resource': resource, 'id': resource_id}) # 404 is raised by exceptions.NotFound to simulate serverside behavior raise exceptions.NotFound(message=not_found_message) def _find_resource_by_name(self, resource, name, project_id=None, cmd_resource=None, parent_id=None, fields=None): if not cmd_resource: cmd_resource = resource cmd_resource_plural = self.get_resource_plural(cmd_resource) resource_plural = self.get_resource_plural(resource) obj_lister = getattr(self, "list_%s" % cmd_resource_plural) params = {'name': name} if fields: params['fields'] = fields if project_id: params['tenant_id'] = project_id if parent_id: data = obj_lister(parent_id, **params) else: data = obj_lister(**params) collection = resource_plural info = data[collection] if len(info) > 1: raise exceptions.NeutronClientNoUniqueMatch(resource=resource, name=name) elif len(info) == 0: not_found_message = (_("Unable to find %(resource)s with name " "'%(name)s'") % {'resource': resource, 'name': name}) # 404 is raised by exceptions.NotFound # to simulate serverside behavior raise exceptions.NotFound(message=not_found_message) else: return info[0] def find_resource(self, resource, name_or_id, project_id=None, cmd_resource=None, parent_id=None, fields=None): try: return self.find_resource_by_id(resource, name_or_id, cmd_resource, parent_id, fields) except exceptions.NotFound: try: return self._find_resource_by_name( resource, name_or_id, project_id, cmd_resource, parent_id, fields) except exceptions.NotFound: not_found_message = (_("Unable to find %(resource)s with name " "or id '%(name_or_id)s'") % {'resource': resource, 'name_or_id': name_or_id}) raise exceptions.NotFound( message=not_found_message) class Client(ClientBase): networks_path = "/networks" network_path = "/networks/%s" ports_path = "/ports" port_path = "/ports/%s" port_bindings_path = "/ports/%s/bindings" port_binding_path = "/ports/%s/bindings/%s" port_binding_path_activate = "/ports/%s/bindings/%s/activate" subnets_path = "/subnets" subnet_path = "/subnets/%s" onboard_network_subnets_path = "/subnetpools/%s/onboard_network_subnets" subnetpools_path = "/subnetpools" subnetpool_path = "/subnetpools/%s" address_scopes_path = "/address-scopes" address_scope_path = "/address-scopes/%s" quotas_path = "/quotas" quota_path = "/quotas/%s" quota_default_path = "/quotas/%s/default" quota_details_path = "/quotas/%s/details.json" extensions_path = "/extensions" extension_path = "/extensions/%s" routers_path = "/routers" router_path = "/routers/%s" floatingips_path = "/floatingips" floatingip_path = "/floatingips/%s" security_groups_path = "/security-groups" security_group_path = "/security-groups/%s" security_group_rules_path = "/security-group-rules" security_group_rule_path = "/security-group-rules/%s" segments_path = "/segments" segment_path = "/segments/%s" sfc_flow_classifiers_path = "/sfc/flow_classifiers" sfc_flow_classifier_path = "/sfc/flow_classifiers/%s" sfc_port_pairs_path = "/sfc/port_pairs" sfc_port_pair_path = "/sfc/port_pairs/%s" sfc_port_pair_groups_path = "/sfc/port_pair_groups" sfc_port_pair_group_path = "/sfc/port_pair_groups/%s" sfc_port_chains_path = "/sfc/port_chains" sfc_port_chain_path = "/sfc/port_chains/%s" sfc_service_graphs_path = "/sfc/service_graphs" sfc_service_graph_path = "/sfc/service_graphs/%s" endpoint_groups_path = "/vpn/endpoint-groups" endpoint_group_path = "/vpn/endpoint-groups/%s" vpnservices_path = "/vpn/vpnservices" vpnservice_path = "/vpn/vpnservices/%s" ipsecpolicies_path = "/vpn/ipsecpolicies" ipsecpolicy_path = "/vpn/ipsecpolicies/%s" ikepolicies_path = "/vpn/ikepolicies" ikepolicy_path = "/vpn/ikepolicies/%s" ipsec_site_connections_path = "/vpn/ipsec-site-connections" ipsec_site_connection_path = "/vpn/ipsec-site-connections/%s" lbaas_loadbalancers_path = "/lbaas/loadbalancers" lbaas_loadbalancer_path = "/lbaas/loadbalancers/%s" lbaas_loadbalancer_path_stats = "/lbaas/loadbalancers/%s/stats" lbaas_loadbalancer_path_status = "/lbaas/loadbalancers/%s/statuses" lbaas_listeners_path = "/lbaas/listeners" lbaas_listener_path = "/lbaas/listeners/%s" lbaas_l7policies_path = "/lbaas/l7policies" lbaas_l7policy_path = lbaas_l7policies_path + "/%s" lbaas_l7rules_path = lbaas_l7policy_path + "/rules" lbaas_l7rule_path = lbaas_l7rules_path + "/%s" lbaas_pools_path = "/lbaas/pools" lbaas_pool_path = "/lbaas/pools/%s" lbaas_healthmonitors_path = "/lbaas/healthmonitors" lbaas_healthmonitor_path = "/lbaas/healthmonitors/%s" lbaas_members_path = lbaas_pool_path + "/members" lbaas_member_path = lbaas_pool_path + "/members/%s" vips_path = "/lb/vips" vip_path = "/lb/vips/%s" pools_path = "/lb/pools" pool_path = "/lb/pools/%s" pool_path_stats = "/lb/pools/%s/stats" members_path = "/lb/members" member_path = "/lb/members/%s" health_monitors_path = "/lb/health_monitors" health_monitor_path = "/lb/health_monitors/%s" associate_pool_health_monitors_path = "/lb/pools/%s/health_monitors" disassociate_pool_health_monitors_path = ( "/lb/pools/%(pool)s/health_monitors/%(health_monitor)s") qos_queues_path = "/qos-queues" qos_queue_path = "/qos-queues/%s" agents_path = "/agents" agent_path = "/agents/%s" network_gateways_path = "/network-gateways" network_gateway_path = "/network-gateways/%s" gateway_devices_path = "/gateway-devices" gateway_device_path = "/gateway-devices/%s" service_providers_path = "/service-providers" metering_labels_path = "/metering/metering-labels" metering_label_path = "/metering/metering-labels/%s" metering_label_rules_path = "/metering/metering-label-rules" metering_label_rule_path = "/metering/metering-label-rules/%s" DHCP_NETS = '/dhcp-networks' DHCP_AGENTS = '/dhcp-agents' L3_ROUTERS = '/l3-routers' L3_AGENTS = '/l3-agents' LOADBALANCER_POOLS = '/loadbalancer-pools' LOADBALANCER_AGENT = '/loadbalancer-agent' AGENT_LOADBALANCERS = '/agent-loadbalancers' LOADBALANCER_HOSTING_AGENT = '/loadbalancer-hosting-agent' firewall_rules_path = "/fw/firewall_rules" firewall_rule_path = "/fw/firewall_rules/%s" firewall_policies_path = "/fw/firewall_policies" firewall_policy_path = "/fw/firewall_policies/%s" firewall_policy_insert_path = "/fw/firewall_policies/%s/insert_rule" firewall_policy_remove_path = "/fw/firewall_policies/%s/remove_rule" firewalls_path = "/fw/firewalls" firewall_path = "/fw/firewalls/%s" fwaas_firewall_groups_path = "/fwaas/firewall_groups" fwaas_firewall_group_path = "/fwaas/firewall_groups/%s" fwaas_firewall_rules_path = "/fwaas/firewall_rules" fwaas_firewall_rule_path = "/fwaas/firewall_rules/%s" fwaas_firewall_policies_path = "/fwaas/firewall_policies" fwaas_firewall_policy_path = "/fwaas/firewall_policies/%s" fwaas_firewall_policy_insert_path = \ "/fwaas/firewall_policies/%s/insert_rule" fwaas_firewall_policy_remove_path = \ "/fwaas/firewall_policies/%s/remove_rule" rbac_policies_path = "/rbac-policies" rbac_policy_path = "/rbac-policies/%s" qos_policies_path = "/qos/policies" qos_policy_path = "/qos/policies/%s" qos_bandwidth_limit_rules_path = "/qos/policies/%s/bandwidth_limit_rules" qos_bandwidth_limit_rule_path = "/qos/policies/%s/bandwidth_limit_rules/%s" qos_packet_rate_limit_rules_path = \ "/qos/policies/%s/packet_rate_limit_rules" qos_packet_rate_limit_rule_path = \ "/qos/policies/%s/packet_rate_limit_rules/%s" qos_dscp_marking_rules_path = "/qos/policies/%s/dscp_marking_rules" qos_dscp_marking_rule_path = "/qos/policies/%s/dscp_marking_rules/%s" qos_minimum_bandwidth_rules_path = \ "/qos/policies/%s/minimum_bandwidth_rules" qos_minimum_bandwidth_rule_path = \ "/qos/policies/%s/minimum_bandwidth_rules/%s" qos_minimum_packet_rate_rules_path = \ "/qos/policies/%s/minimum_packet_rate_rules" qos_minimum_packet_rate_rule_path = \ "/qos/policies/%s/minimum_packet_rate_rules/%s" qos_rule_types_path = "/qos/rule-types" qos_rule_type_path = "/qos/rule-types/%s" flavors_path = "/flavors" flavor_path = "/flavors/%s" service_profiles_path = "/service_profiles" service_profile_path = "/service_profiles/%s" flavor_profile_bindings_path = flavor_path + service_profiles_path flavor_profile_binding_path = flavor_path + service_profile_path availability_zones_path = "/availability_zones" auto_allocated_topology_path = "/auto-allocated-topology/%s" BGP_DRINSTANCES = "/bgp-drinstances" BGP_DRINSTANCE = "/bgp-drinstance/%s" BGP_DRAGENTS = "/bgp-dragents" BGP_DRAGENT = "/bgp-dragents/%s" bgp_speakers_path = "/bgp-speakers" bgp_speaker_path = "/bgp-speakers/%s" bgp_peers_path = "/bgp-peers" bgp_peer_path = "/bgp-peers/%s" network_ip_availabilities_path = '/network-ip-availabilities' network_ip_availability_path = '/network-ip-availabilities/%s' tags_path = "/%s/%s/tags" tag_path = "/%s/%s/tags/%s" trunks_path = "/trunks" trunk_path = "/trunks/%s" subports_path = "/trunks/%s/get_subports" subports_add_path = "/trunks/%s/add_subports" subports_remove_path = "/trunks/%s/remove_subports" bgpvpns_path = "/bgpvpn/bgpvpns" bgpvpn_path = "/bgpvpn/bgpvpns/%s" bgpvpn_network_associations_path =\ "/bgpvpn/bgpvpns/%s/network_associations" bgpvpn_network_association_path =\ "/bgpvpn/bgpvpns/%s/network_associations/%s" bgpvpn_router_associations_path = "/bgpvpn/bgpvpns/%s/router_associations" bgpvpn_router_association_path =\ "/bgpvpn/bgpvpns/%s/router_associations/%s" bgpvpn_port_associations_path = "/bgpvpn/bgpvpns/%s/port_associations" bgpvpn_port_association_path = "/bgpvpn/bgpvpns/%s/port_associations/%s" network_logs_path = "/log/logs" network_log_path = "/log/logs/%s" network_loggables_path = "/log/loggable-resources" # API has no way to report plurals, so we have to hard code them EXTED_PLURALS = {'routers': 'router', 'floatingips': 'floatingip', 'service_types': 'service_type', 'service_definitions': 'service_definition', 'security_groups': 'security_group', 'security_group_rules': 'security_group_rule', 'segments': 'segment', 'ipsecpolicies': 'ipsecpolicy', 'ikepolicies': 'ikepolicy', 'ipsec_site_connections': 'ipsec_site_connection', 'vpnservices': 'vpnservice', 'endpoint_groups': 'endpoint_group', 'vips': 'vip', 'pools': 'pool', 'members': 'member', 'health_monitors': 'health_monitor', 'quotas': 'quota', 'service_providers': 'service_provider', 'firewall_rules': 'firewall_rule', 'firewall_policies': 'firewall_policy', 'firewalls': 'firewall', 'fwaas_firewall_rules': 'fwaas_firewall_rule', 'fwaas_firewall_policies': 'fwaas_firewall_policy', 'fwaas_firewall_groups': 'fwaas_firewall_group', 'metering_labels': 'metering_label', 'metering_label_rules': 'metering_label_rule', 'loadbalancers': 'loadbalancer', 'listeners': 'listener', 'l7rules': 'l7rule', 'l7policies': 'l7policy', 'lbaas_l7policies': 'lbaas_l7policy', 'lbaas_pools': 'lbaas_pool', 'lbaas_healthmonitors': 'lbaas_healthmonitor', 'lbaas_members': 'lbaas_member', 'healthmonitors': 'healthmonitor', 'rbac_policies': 'rbac_policy', 'address_scopes': 'address_scope', 'qos_policies': 'qos_policy', 'policies': 'policy', 'bandwidth_limit_rules': 'bandwidth_limit_rule', 'packet_rate_limit_rules': 'packet_rate_limit_rule', 'minimum_bandwidth_rules': 'minimum_bandwidth_rule', 'minimum_packet_rate_rules': 'minimum_packet_rate_rule', 'rules': 'rule', 'dscp_marking_rules': 'dscp_marking_rule', 'rule_types': 'rule_type', 'flavors': 'flavor', 'bgp_speakers': 'bgp_speaker', 'bgp_peers': 'bgp_peer', 'network_ip_availabilities': 'network_ip_availability', 'trunks': 'trunk', 'bgpvpns': 'bgpvpn', 'network_associations': 'network_association', 'router_associations': 'router_association', 'port_associations': 'port_association', 'flow_classifiers': 'flow_classifier', 'port_pairs': 'port_pair', 'port_pair_groups': 'port_pair_group', 'port_chains': 'port_chain', 'service_graphs': 'service_graph', 'logs': 'log', 'loggable_resources': 'loggable_resource', } def list_ext(self, collection, path, retrieve_all, **_params): """Client extension hook for list.""" return self.list(collection, path, retrieve_all, **_params) def show_ext(self, path, id, **_params): """Client extension hook for show.""" return self.get(path % id, params=_params) def create_ext(self, path, body=None): """Client extension hook for create.""" return self.post(path, body=body) def update_ext(self, path, id, body=None): """Client extension hook for update.""" return self.put(path % id, body=body) def delete_ext(self, path, id): """Client extension hook for delete.""" return self.delete(path % id) def get_quotas_tenant(self, **_params): """Fetch project info for following quota operation.""" return self.get(self.quota_path % 'tenant', params=_params) def list_quotas(self, **_params): """Fetch all projects' quotas.""" return self.get(self.quotas_path, params=_params) @debtcollector.renames.renamed_kwarg( 'tenant_id', 'project_id', replace=True) def show_quota(self, project_id, **_params): """Fetch information of a certain project's quotas.""" return self.get(self.quota_path % (project_id), params=_params) @debtcollector.renames.renamed_kwarg( 'tenant_id', 'project_id', replace=True) def show_quota_details(self, project_id, **_params): """Fetch information of a certain project's quota details.""" return self.get(self.quota_details_path % (project_id), params=_params) @debtcollector.renames.renamed_kwarg( 'tenant_id', 'project_id', replace=True) def show_quota_default(self, project_id, **_params): """Fetch information of a certain project's default quotas.""" return self.get(self.quota_default_path % (project_id), params=_params) @debtcollector.renames.renamed_kwarg( 'tenant_id', 'project_id', replace=True) def update_quota(self, project_id, body=None): """Update a project's quotas.""" return self.put(self.quota_path % (project_id), body=body) @debtcollector.renames.renamed_kwarg( 'tenant_id', 'project_id', replace=True) def delete_quota(self, project_id): """Delete the specified project's quota values.""" return self.delete(self.quota_path % (project_id)) def list_extensions(self, **_params): """Fetch a list of all extensions on server side.""" return self.get(self.extensions_path, params=_params) def show_extension(self, ext_alias, **_params): """Fetches information of a certain extension.""" return self.get(self.extension_path % ext_alias, params=_params) def list_ports(self, retrieve_all=True, **_params): """Fetches a list of all ports for a project.""" # Pass filters in "params" argument to do_request return self.list('ports', self.ports_path, retrieve_all, **_params) def show_port(self, port, **_params): """Fetches information of a certain port.""" return self.get(self.port_path % (port), params=_params) def create_port(self, body=None): """Creates a new port.""" return self.post(self.ports_path, body=body) def update_port(self, port, body=None, revision_number=None): """Updates a port.""" return self._update_resource(self.port_path % (port), body=body, revision_number=revision_number) def delete_port(self, port): """Deletes the specified port.""" return self.delete(self.port_path % (port)) def create_port_binding(self, port_id, body=None): """Creates a new port binding.""" return self.post(self.port_bindings_path % port_id, body=body) def delete_port_binding(self, port_id, host_id): """Deletes the specified port binding.""" return self.delete(self.port_binding_path % (port_id, host_id)) def show_port_binding(self, port_id, host_id, **_params): """Fetches information for a certain port binding.""" return self.get(self.port_binding_path % (port_id, host_id), params=_params) def list_port_bindings(self, port_id, retrieve_all=True, **_params): """Fetches a list of all bindings for a certain port.""" return self.list('port_bindings', self.port_bindings_path % port_id, retrieve_all, **_params) def activate_port_binding(self, port_id, host_id): """Activates a port binding.""" return self.put(self.port_binding_path_activate % (port_id, host_id)) def list_networks(self, retrieve_all=True, **_params): """Fetches a list of all networks for a project.""" # Pass filters in "params" argument to do_request return self.list('networks', self.networks_path, retrieve_all, **_params) def show_network(self, network, **_params): """Fetches information of a certain network.""" return self.get(self.network_path % (network), params=_params) def create_network(self, body=None): """Creates a new network.""" return self.post(self.networks_path, body=body) def update_network(self, network, body=None, revision_number=None): """Updates a network.""" return self._update_resource(self.network_path % (network), body=body, revision_number=revision_number) def delete_network(self, network): """Deletes the specified network.""" return self.delete(self.network_path % (network)) def list_subnets(self, retrieve_all=True, **_params): """Fetches a list of all subnets for a project.""" return self.list('subnets', self.subnets_path, retrieve_all, **_params) def show_subnet(self, subnet, **_params): """Fetches information of a certain subnet.""" return self.get(self.subnet_path % (subnet), params=_params) def create_subnet(self, body=None): """Creates a new subnet.""" return self.post(self.subnets_path, body=body) def update_subnet(self, subnet, body=None, revision_number=None): """Updates a subnet.""" return self._update_resource(self.subnet_path % (subnet), body=body, revision_number=revision_number) def delete_subnet(self, subnet): """Deletes the specified subnet.""" return self.delete(self.subnet_path % (subnet)) def list_subnetpools(self, retrieve_all=True, **_params): """Fetches a list of all subnetpools for a project.""" return self.list('subnetpools', self.subnetpools_path, retrieve_all, **_params) def show_subnetpool(self, subnetpool, **_params): """Fetches information of a certain subnetpool.""" return self.get(self.subnetpool_path % (subnetpool), params=_params) def create_subnetpool(self, body=None): """Creates a new subnetpool.""" return self.post(self.subnetpools_path, body=body) def update_subnetpool(self, subnetpool, body=None, revision_number=None): """Updates a subnetpool.""" return self._update_resource(self.subnetpool_path % (subnetpool), body=body, revision_number=revision_number) def delete_subnetpool(self, subnetpool): """Deletes the specified subnetpool.""" return self.delete(self.subnetpool_path % (subnetpool)) def list_routers(self, retrieve_all=True, **_params): """Fetches a list of all routers for a project.""" # Pass filters in "params" argument to do_request return self.list('routers', self.routers_path, retrieve_all, **_params) def show_router(self, router, **_params): """Fetches information of a certain router.""" return self.get(self.router_path % (router), params=_params) def create_router(self, body=None): """Creates a new router.""" return self.post(self.routers_path, body=body) def update_router(self, router, body=None, revision_number=None): """Updates a router.""" return self._update_resource(self.router_path % (router), body=body, revision_number=revision_number) def delete_router(self, router): """Deletes the specified router.""" return self.delete(self.router_path % (router)) def list_address_scopes(self, retrieve_all=True, **_params): """Fetches a list of all address scopes for a project.""" return self.list('address_scopes', self.address_scopes_path, retrieve_all, **_params) def show_address_scope(self, address_scope, **_params): """Fetches information of a certain address scope.""" return self.get(self.address_scope_path % (address_scope), params=_params) def create_address_scope(self, body=None): """Creates a new address scope.""" return self.post(self.address_scopes_path, body=body) def update_address_scope(self, address_scope, body=None): """Updates a address scope.""" return self.put(self.address_scope_path % (address_scope), body=body) def delete_address_scope(self, address_scope): """Deletes the specified address scope.""" return self.delete(self.address_scope_path % (address_scope)) def add_interface_router(self, router, body=None): """Adds an internal network interface to the specified router.""" return self.put((self.router_path % router) + "/add_router_interface", body=body) def remove_interface_router(self, router, body=None): """Removes an internal network interface from the specified router.""" return self.put((self.router_path % router) + "/remove_router_interface", body=body) def add_extra_routes_to_router(self, router, body=None): """Adds extra routes to the specified router.""" return self.put((self.router_path % router) + "/add_extraroutes", body=body) def remove_extra_routes_from_router(self, router, body=None): """Removes extra routes from the specified router.""" return self.put((self.router_path % router) + "/remove_extraroutes", body=body) def add_gateway_router(self, router, body=None): """Adds an external network gateway to the specified router.""" return self.put((self.router_path % router), body={'router': {'external_gateway_info': body}}) def remove_gateway_router(self, router): """Removes an external network gateway from the specified router.""" return self.put((self.router_path % router), body={'router': {'external_gateway_info': {}}}) def list_floatingips(self, retrieve_all=True, **_params): """Fetches a list of all floatingips for a project.""" # Pass filters in "params" argument to do_request return self.list('floatingips', self.floatingips_path, retrieve_all, **_params) def show_floatingip(self, floatingip, **_params): """Fetches information of a certain floatingip.""" return self.get(self.floatingip_path % (floatingip), params=_params) def create_floatingip(self, body=None): """Creates a new floatingip.""" return self.post(self.floatingips_path, body=body) def update_floatingip(self, floatingip, body=None, revision_number=None): """Updates a floatingip.""" return self._update_resource(self.floatingip_path % (floatingip), body=body, revision_number=revision_number) def delete_floatingip(self, floatingip): """Deletes the specified floatingip.""" return self.delete(self.floatingip_path % (floatingip)) def create_security_group(self, body=None): """Creates a new security group.""" return self.post(self.security_groups_path, body=body) def update_security_group(self, security_group, body=None, revision_number=None): """Updates a security group.""" return self._update_resource(self.security_group_path % security_group, body=body, revision_number=revision_number) def list_security_groups(self, retrieve_all=True, **_params): """Fetches a list of all security groups for a project.""" return self.list('security_groups', self.security_groups_path, retrieve_all, **_params) def show_security_group(self, security_group, **_params): """Fetches information of a certain security group.""" return self.get(self.security_group_path % (security_group), params=_params) def delete_security_group(self, security_group): """Deletes the specified security group.""" return self.delete(self.security_group_path % (security_group)) def create_security_group_rule(self, body=None): """Creates a new security group rule.""" return self.post(self.security_group_rules_path, body=body) def delete_security_group_rule(self, security_group_rule): """Deletes the specified security group rule.""" return self.delete(self.security_group_rule_path % (security_group_rule)) def list_security_group_rules(self, retrieve_all=True, **_params): """Fetches a list of all security group rules for a project.""" return self.list('security_group_rules', self.security_group_rules_path, retrieve_all, **_params) def show_security_group_rule(self, security_group_rule, **_params): """Fetches information of a certain security group rule.""" return self.get(self.security_group_rule_path % (security_group_rule), params=_params) def create_segment(self, body=None): """Creates a new segment.""" return self.post(self.segments_path, body=body) def update_segment(self, segment, body=None, revision_number=None): """Updates a segment.""" return self._update_resource(self.segment_path % segment, body=body, revision_number=revision_number) def list_segments(self, retrieve_all=True, **_params): """Fetches a list of all segments for a project.""" return self.list('segments', self.segments_path, retrieve_all, **_params) def show_segment(self, segment, **_params): """Fetches information of a certain segment.""" return self.get(self.segment_path % segment, params=_params) def delete_segment(self, segment): """Deletes the specified segment.""" return self.delete(self.segment_path % segment) def list_endpoint_groups(self, retrieve_all=True, **_params): """Fetches a list of all VPN endpoint groups for a project.""" return self.list('endpoint_groups', self.endpoint_groups_path, retrieve_all, **_params) def show_endpoint_group(self, endpointgroup, **_params): """Fetches information for a specific VPN endpoint group.""" return self.get(self.endpoint_group_path % endpointgroup, params=_params) def create_endpoint_group(self, body=None): """Creates a new VPN endpoint group.""" return self.post(self.endpoint_groups_path, body=body) def update_endpoint_group(self, endpoint_group, body=None): """Updates a VPN endpoint group.""" return self.put(self.endpoint_group_path % endpoint_group, body=body) def delete_endpoint_group(self, endpoint_group): """Deletes the specified VPN endpoint group.""" return self.delete(self.endpoint_group_path % endpoint_group) def list_vpnservices(self, retrieve_all=True, **_params): """Fetches a list of all configured VPN services for a project.""" return self.list('vpnservices', self.vpnservices_path, retrieve_all, **_params) def show_vpnservice(self, vpnservice, **_params): """Fetches information of a specific VPN service.""" return self.get(self.vpnservice_path % (vpnservice), params=_params) def create_vpnservice(self, body=None): """Creates a new VPN service.""" return self.post(self.vpnservices_path, body=body) def update_vpnservice(self, vpnservice, body=None): """Updates a VPN service.""" return self.put(self.vpnservice_path % (vpnservice), body=body) def delete_vpnservice(self, vpnservice): """Deletes the specified VPN service.""" return self.delete(self.vpnservice_path % (vpnservice)) def list_ipsec_site_connections(self, retrieve_all=True, **_params): """Fetches all configured IPsecSiteConnections for a project.""" return self.list('ipsec_site_connections', self.ipsec_site_connections_path, retrieve_all, **_params) def show_ipsec_site_connection(self, ipsecsite_conn, **_params): """Fetches information of a specific IPsecSiteConnection.""" return self.get( self.ipsec_site_connection_path % (ipsecsite_conn), params=_params ) def create_ipsec_site_connection(self, body=None): """Creates a new IPsecSiteConnection.""" return self.post(self.ipsec_site_connections_path, body=body) def update_ipsec_site_connection(self, ipsecsite_conn, body=None): """Updates an IPsecSiteConnection.""" return self.put( self.ipsec_site_connection_path % (ipsecsite_conn), body=body ) def delete_ipsec_site_connection(self, ipsecsite_conn): """Deletes the specified IPsecSiteConnection.""" return self.delete(self.ipsec_site_connection_path % (ipsecsite_conn)) def list_ikepolicies(self, retrieve_all=True, **_params): """Fetches a list of all configured IKEPolicies for a project.""" return self.list('ikepolicies', self.ikepolicies_path, retrieve_all, **_params) def show_ikepolicy(self, ikepolicy, **_params): """Fetches information of a specific IKEPolicy.""" return self.get(self.ikepolicy_path % (ikepolicy), params=_params) def create_ikepolicy(self, body=None): """Creates a new IKEPolicy.""" return self.post(self.ikepolicies_path, body=body) def update_ikepolicy(self, ikepolicy, body=None): """Updates an IKEPolicy.""" return self.put(self.ikepolicy_path % (ikepolicy), body=body) def delete_ikepolicy(self, ikepolicy): """Deletes the specified IKEPolicy.""" return self.delete(self.ikepolicy_path % (ikepolicy)) def list_ipsecpolicies(self, retrieve_all=True, **_params): """Fetches a list of all configured IPsecPolicies for a project.""" return self.list('ipsecpolicies', self.ipsecpolicies_path, retrieve_all, **_params) def show_ipsecpolicy(self, ipsecpolicy, **_params): """Fetches information of a specific IPsecPolicy.""" return self.get(self.ipsecpolicy_path % (ipsecpolicy), params=_params) def create_ipsecpolicy(self, body=None): """Creates a new IPsecPolicy.""" return self.post(self.ipsecpolicies_path, body=body) def update_ipsecpolicy(self, ipsecpolicy, body=None): """Updates an IPsecPolicy.""" return self.put(self.ipsecpolicy_path % (ipsecpolicy), body=body) def delete_ipsecpolicy(self, ipsecpolicy): """Deletes the specified IPsecPolicy.""" return self.delete(self.ipsecpolicy_path % (ipsecpolicy)) def list_loadbalancers(self, retrieve_all=True, **_params): """Fetches a list of all loadbalancers for a project.""" return self.list('loadbalancers', self.lbaas_loadbalancers_path, retrieve_all, **_params) def show_loadbalancer(self, lbaas_loadbalancer, **_params): """Fetches information for a load balancer.""" return self.get(self.lbaas_loadbalancer_path % (lbaas_loadbalancer), params=_params) def create_loadbalancer(self, body=None): """Creates a new load balancer.""" return self.post(self.lbaas_loadbalancers_path, body=body) def update_loadbalancer(self, lbaas_loadbalancer, body=None): """Updates a load balancer.""" return self.put(self.lbaas_loadbalancer_path % (lbaas_loadbalancer), body=body) def delete_loadbalancer(self, lbaas_loadbalancer): """Deletes the specified load balancer.""" return self.delete(self.lbaas_loadbalancer_path % (lbaas_loadbalancer)) def retrieve_loadbalancer_stats(self, loadbalancer, **_params): """Retrieves stats for a certain load balancer.""" return self.get(self.lbaas_loadbalancer_path_stats % (loadbalancer), params=_params) def retrieve_loadbalancer_status(self, loadbalancer, **_params): """Retrieves status for a certain load balancer.""" return self.get(self.lbaas_loadbalancer_path_status % (loadbalancer), params=_params) def list_listeners(self, retrieve_all=True, **_params): """Fetches a list of all lbaas_listeners for a project.""" return self.list('listeners', self.lbaas_listeners_path, retrieve_all, **_params) def show_listener(self, lbaas_listener, **_params): """Fetches information for a lbaas_listener.""" return self.get(self.lbaas_listener_path % (lbaas_listener), params=_params) def create_listener(self, body=None): """Creates a new lbaas_listener.""" return self.post(self.lbaas_listeners_path, body=body) def update_listener(self, lbaas_listener, body=None): """Updates a lbaas_listener.""" return self.put(self.lbaas_listener_path % (lbaas_listener), body=body) def delete_listener(self, lbaas_listener): """Deletes the specified lbaas_listener.""" return self.delete(self.lbaas_listener_path % (lbaas_listener)) def list_lbaas_l7policies(self, retrieve_all=True, **_params): """Fetches a list of all L7 policies for a listener.""" return self.list('l7policies', self.lbaas_l7policies_path, retrieve_all, **_params) def show_lbaas_l7policy(self, l7policy, **_params): """Fetches information of a certain listener's L7 policy.""" return self.get(self.lbaas_l7policy_path % l7policy, params=_params) def create_lbaas_l7policy(self, body=None): """Creates L7 policy for a certain listener.""" return self.post(self.lbaas_l7policies_path, body=body) def update_lbaas_l7policy(self, l7policy, body=None): """Updates L7 policy.""" return self.put(self.lbaas_l7policy_path % l7policy, body=body) def delete_lbaas_l7policy(self, l7policy): """Deletes the specified L7 policy.""" return self.delete(self.lbaas_l7policy_path % l7policy) def list_lbaas_l7rules(self, l7policy, retrieve_all=True, **_params): """Fetches a list of all rules for L7 policy.""" return self.list('rules', self.lbaas_l7rules_path % l7policy, retrieve_all, **_params) def show_lbaas_l7rule(self, l7rule, l7policy, **_params): """Fetches information of a certain L7 policy's rule.""" return self.get(self.lbaas_l7rule_path % (l7policy, l7rule), params=_params) def create_lbaas_l7rule(self, l7policy, body=None): """Creates rule for a certain L7 policy.""" return self.post(self.lbaas_l7rules_path % l7policy, body=body) def update_lbaas_l7rule(self, l7rule, l7policy, body=None): """Updates L7 rule.""" return self.put(self.lbaas_l7rule_path % (l7policy, l7rule), body=body) def delete_lbaas_l7rule(self, l7rule, l7policy): """Deletes the specified L7 rule.""" return self.delete(self.lbaas_l7rule_path % (l7policy, l7rule)) def list_lbaas_pools(self, retrieve_all=True, **_params): """Fetches a list of all lbaas_pools for a project.""" return self.list('pools', self.lbaas_pools_path, retrieve_all, **_params) def show_lbaas_pool(self, lbaas_pool, **_params): """Fetches information for a lbaas_pool.""" return self.get(self.lbaas_pool_path % (lbaas_pool), params=_params) def create_lbaas_pool(self, body=None): """Creates a new lbaas_pool.""" return self.post(self.lbaas_pools_path, body=body) def update_lbaas_pool(self, lbaas_pool, body=None): """Updates a lbaas_pool.""" return self.put(self.lbaas_pool_path % (lbaas_pool), body=body) def delete_lbaas_pool(self, lbaas_pool): """Deletes the specified lbaas_pool.""" return self.delete(self.lbaas_pool_path % (lbaas_pool)) def list_lbaas_healthmonitors(self, retrieve_all=True, **_params): """Fetches a list of all lbaas_healthmonitors for a project.""" return self.list('healthmonitors', self.lbaas_healthmonitors_path, retrieve_all, **_params) def show_lbaas_healthmonitor(self, lbaas_healthmonitor, **_params): """Fetches information for a lbaas_healthmonitor.""" return self.get(self.lbaas_healthmonitor_path % (lbaas_healthmonitor), params=_params) def create_lbaas_healthmonitor(self, body=None): """Creates a new lbaas_healthmonitor.""" return self.post(self.lbaas_healthmonitors_path, body=body) def update_lbaas_healthmonitor(self, lbaas_healthmonitor, body=None): """Updates a lbaas_healthmonitor.""" return self.put(self.lbaas_healthmonitor_path % (lbaas_healthmonitor), body=body) def delete_lbaas_healthmonitor(self, lbaas_healthmonitor): """Deletes the specified lbaas_healthmonitor.""" return self.delete(self.lbaas_healthmonitor_path % (lbaas_healthmonitor)) def list_lbaas_loadbalancers(self, retrieve_all=True, **_params): """Fetches a list of all lbaas_loadbalancers for a project.""" return self.list('loadbalancers', self.lbaas_loadbalancers_path, retrieve_all, **_params) def list_lbaas_members(self, lbaas_pool, retrieve_all=True, **_params): """Fetches a list of all lbaas_members for a project.""" return self.list('members', self.lbaas_members_path % lbaas_pool, retrieve_all, **_params) def show_lbaas_member(self, lbaas_member, lbaas_pool, **_params): """Fetches information of a certain lbaas_member.""" return self.get(self.lbaas_member_path % (lbaas_pool, lbaas_member), params=_params) def create_lbaas_member(self, lbaas_pool, body=None): """Creates a lbaas_member.""" return self.post(self.lbaas_members_path % lbaas_pool, body=body) def update_lbaas_member(self, lbaas_member, lbaas_pool, body=None): """Updates a lbaas_member.""" return self.put(self.lbaas_member_path % (lbaas_pool, lbaas_member), body=body) def delete_lbaas_member(self, lbaas_member, lbaas_pool): """Deletes the specified lbaas_member.""" return self.delete(self.lbaas_member_path % (lbaas_pool, lbaas_member)) def list_vips(self, retrieve_all=True, **_params): """Fetches a list of all load balancer vips for a project.""" # Pass filters in "params" argument to do_request return self.list('vips', self.vips_path, retrieve_all, **_params) def show_vip(self, vip, **_params): """Fetches information of a certain load balancer vip.""" return self.get(self.vip_path % (vip), params=_params) def create_vip(self, body=None): """Creates a new load balancer vip.""" return self.post(self.vips_path, body=body) def update_vip(self, vip, body=None): """Updates a load balancer vip.""" return self.put(self.vip_path % (vip), body=body) def delete_vip(self, vip): """Deletes the specified load balancer vip.""" return self.delete(self.vip_path % (vip)) def list_pools(self, retrieve_all=True, **_params): """Fetches a list of all load balancer pools for a project.""" # Pass filters in "params" argument to do_request return self.list('pools', self.pools_path, retrieve_all, **_params) def show_pool(self, pool, **_params): """Fetches information of a certain load balancer pool.""" return self.get(self.pool_path % (pool), params=_params) def create_pool(self, body=None): """Creates a new load balancer pool.""" return self.post(self.pools_path, body=body) def update_pool(self, pool, body=None): """Updates a load balancer pool.""" return self.put(self.pool_path % (pool), body=body) def delete_pool(self, pool): """Deletes the specified load balancer pool.""" return self.delete(self.pool_path % (pool)) def retrieve_pool_stats(self, pool, **_params): """Retrieves stats for a certain load balancer pool.""" return self.get(self.pool_path_stats % (pool), params=_params) def list_members(self, retrieve_all=True, **_params): """Fetches a list of all load balancer members for a project.""" # Pass filters in "params" argument to do_request return self.list('members', self.members_path, retrieve_all, **_params) def show_member(self, member, **_params): """Fetches information of a certain load balancer member.""" return self.get(self.member_path % (member), params=_params) def create_member(self, body=None): """Creates a new load balancer member.""" return self.post(self.members_path, body=body) def update_member(self, member, body=None): """Updates a load balancer member.""" return self.put(self.member_path % (member), body=body) def delete_member(self, member): """Deletes the specified load balancer member.""" return self.delete(self.member_path % (member)) def list_health_monitors(self, retrieve_all=True, **_params): """Fetches a list of all load balancer health monitors for a project. """ # Pass filters in "params" argument to do_request return self.list('health_monitors', self.health_monitors_path, retrieve_all, **_params) def show_health_monitor(self, health_monitor, **_params): """Fetches information of a certain load balancer health monitor.""" return self.get(self.health_monitor_path % (health_monitor), params=_params) def create_health_monitor(self, body=None): """Creates a new load balancer health monitor.""" return self.post(self.health_monitors_path, body=body) def update_health_monitor(self, health_monitor, body=None): """Updates a load balancer health monitor.""" return self.put(self.health_monitor_path % (health_monitor), body=body) def delete_health_monitor(self, health_monitor): """Deletes the specified load balancer health monitor.""" return self.delete(self.health_monitor_path % (health_monitor)) def associate_health_monitor(self, pool, body): """Associate specified load balancer health monitor and pool.""" return self.post(self.associate_pool_health_monitors_path % (pool), body=body) def disassociate_health_monitor(self, pool, health_monitor): """Disassociate specified load balancer health monitor and pool.""" path = (self.disassociate_pool_health_monitors_path % {'pool': pool, 'health_monitor': health_monitor}) return self.delete(path) def create_qos_queue(self, body=None): """Creates a new queue.""" return self.post(self.qos_queues_path, body=body) def list_qos_queues(self, **_params): """Fetches a list of all queues for a project.""" return self.get(self.qos_queues_path, params=_params) def show_qos_queue(self, queue, **_params): """Fetches information of a certain queue.""" return self.get(self.qos_queue_path % (queue), params=_params) def delete_qos_queue(self, queue): """Deletes the specified queue.""" return self.delete(self.qos_queue_path % (queue)) def list_agents(self, **_params): """Fetches agents.""" # Pass filters in "params" argument to do_request return self.get(self.agents_path, params=_params) def show_agent(self, agent, **_params): """Fetches information of a certain agent.""" return self.get(self.agent_path % (agent), params=_params) def update_agent(self, agent, body=None): """Updates an agent.""" return self.put(self.agent_path % (agent), body=body) def delete_agent(self, agent): """Deletes the specified agent.""" return self.delete(self.agent_path % (agent)) def list_network_gateways(self, **_params): """Retrieve network gateways.""" return self.get(self.network_gateways_path, params=_params) def show_network_gateway(self, gateway_id, **_params): """Fetch a network gateway.""" return self.get(self.network_gateway_path % gateway_id, params=_params) def create_network_gateway(self, body=None): """Create a new network gateway.""" return self.post(self.network_gateways_path, body=body) def update_network_gateway(self, gateway_id, body=None): """Update a network gateway.""" return self.put(self.network_gateway_path % gateway_id, body=body) def delete_network_gateway(self, gateway_id): """Delete the specified network gateway.""" return self.delete(self.network_gateway_path % gateway_id) def connect_network_gateway(self, gateway_id, body=None): """Connect a network gateway to the specified network.""" base_uri = self.network_gateway_path % gateway_id return self.put("%s/connect_network" % base_uri, body=body) def disconnect_network_gateway(self, gateway_id, body=None): """Disconnect a network from the specified gateway.""" base_uri = self.network_gateway_path % gateway_id return self.put("%s/disconnect_network" % base_uri, body=body) def list_gateway_devices(self, **_params): """Retrieve gateway devices.""" return self.get(self.gateway_devices_path, params=_params) def show_gateway_device(self, gateway_device_id, **_params): """Fetch a gateway device.""" return self.get(self.gateway_device_path % gateway_device_id, params=_params) def create_gateway_device(self, body=None): """Create a new gateway device.""" return self.post(self.gateway_devices_path, body=body) def update_gateway_device(self, gateway_device_id, body=None): """Updates a new gateway device.""" return self.put(self.gateway_device_path % gateway_device_id, body=body) def delete_gateway_device(self, gateway_device_id): """Delete the specified gateway device.""" return self.delete(self.gateway_device_path % gateway_device_id) def list_dhcp_agent_hosting_networks(self, network, **_params): """Fetches a list of dhcp agents hosting a network.""" return self.get((self.network_path + self.DHCP_AGENTS) % network, params=_params) def list_networks_on_dhcp_agent(self, dhcp_agent, **_params): """Fetches a list of networks hosted on a DHCP agent.""" return self.get((self.agent_path + self.DHCP_NETS) % dhcp_agent, params=_params) def add_network_to_dhcp_agent(self, dhcp_agent, body=None): """Adds a network to dhcp agent.""" return self.post((self.agent_path + self.DHCP_NETS) % dhcp_agent, body=body) def remove_network_from_dhcp_agent(self, dhcp_agent, network_id): """Remove a network from dhcp agent.""" return self.delete((self.agent_path + self.DHCP_NETS + "/%s") % ( dhcp_agent, network_id)) def list_l3_agent_hosting_routers(self, router, **_params): """Fetches a list of L3 agents hosting a router.""" return self.get((self.router_path + self.L3_AGENTS) % router, params=_params) def list_routers_on_l3_agent(self, l3_agent, **_params): """Fetches a list of routers hosted on an L3 agent.""" return self.get((self.agent_path + self.L3_ROUTERS) % l3_agent, params=_params) def add_router_to_l3_agent(self, l3_agent, body): """Adds a router to L3 agent.""" return self.post((self.agent_path + self.L3_ROUTERS) % l3_agent, body=body) def list_dragents_hosting_bgp_speaker(self, bgp_speaker, **_params): """Fetches a list of Dynamic Routing agents hosting a BGP speaker.""" return self.get((self.bgp_speaker_path + self.BGP_DRAGENTS) % bgp_speaker, params=_params) def add_bgp_speaker_to_dragent(self, bgp_dragent, body): """Adds a BGP speaker to Dynamic Routing agent.""" return self.post((self.agent_path + self.BGP_DRINSTANCES) % bgp_dragent, body=body) def remove_bgp_speaker_from_dragent(self, bgp_dragent, bgpspeaker_id): """Removes a BGP speaker from Dynamic Routing agent.""" return self.delete((self.agent_path + self.BGP_DRINSTANCES + "/%s") % (bgp_dragent, bgpspeaker_id)) def list_bgp_speaker_on_dragent(self, bgp_dragent, **_params): """Fetches a list of BGP speakers hosted by Dynamic Routing agent.""" return self.get((self.agent_path + self.BGP_DRINSTANCES) % bgp_dragent, params=_params) def list_firewall_rules(self, retrieve_all=True, **_params): """Fetches a list of all firewall rules for a project.""" # Pass filters in "params" argument to do_request return self.list('firewall_rules', self.firewall_rules_path, retrieve_all, **_params) def show_firewall_rule(self, firewall_rule, **_params): """Fetches information of a certain firewall rule.""" return self.get(self.firewall_rule_path % (firewall_rule), params=_params) def create_firewall_rule(self, body=None): """Creates a new firewall rule.""" return self.post(self.firewall_rules_path, body=body) def update_firewall_rule(self, firewall_rule, body=None): """Updates a firewall rule.""" return self.put(self.firewall_rule_path % (firewall_rule), body=body) def delete_firewall_rule(self, firewall_rule): """Deletes the specified firewall rule.""" return self.delete(self.firewall_rule_path % (firewall_rule)) def list_firewall_policies(self, retrieve_all=True, **_params): """Fetches a list of all firewall policies for a project.""" # Pass filters in "params" argument to do_request return self.list('firewall_policies', self.firewall_policies_path, retrieve_all, **_params) def show_firewall_policy(self, firewall_policy, **_params): """Fetches information of a certain firewall policy.""" return self.get(self.firewall_policy_path % (firewall_policy), params=_params) def create_firewall_policy(self, body=None): """Creates a new firewall policy.""" return self.post(self.firewall_policies_path, body=body) def update_firewall_policy(self, firewall_policy, body=None): """Updates a firewall policy.""" return self.put(self.firewall_policy_path % (firewall_policy), body=body) def delete_firewall_policy(self, firewall_policy): """Deletes the specified firewall policy.""" return self.delete(self.firewall_policy_path % (firewall_policy)) def firewall_policy_insert_rule(self, firewall_policy, body=None): """Inserts specified rule into firewall policy.""" return self.put(self.firewall_policy_insert_path % (firewall_policy), body=body) def firewall_policy_remove_rule(self, firewall_policy, body=None): """Removes specified rule from firewall policy.""" return self.put(self.firewall_policy_remove_path % (firewall_policy), body=body) def list_firewalls(self, retrieve_all=True, **_params): """Fetches a list of all firewalls for a project.""" # Pass filters in "params" argument to do_request return self.list('firewalls', self.firewalls_path, retrieve_all, **_params) def show_firewall(self, firewall, **_params): """Fetches information of a certain firewall.""" return self.get(self.firewall_path % (firewall), params=_params) def create_firewall(self, body=None): """Creates a new firewall.""" return self.post(self.firewalls_path, body=body) def update_firewall(self, firewall, body=None): """Updates a firewall.""" return self.put(self.firewall_path % (firewall), body=body) def delete_firewall(self, firewall): """Deletes the specified firewall.""" return self.delete(self.firewall_path % (firewall)) def list_fwaas_firewall_groups(self, retrieve_all=True, **_params): """Fetches a list of all firewall groups for a project""" return self.list('firewall_groups', self.fwaas_firewall_groups_path, retrieve_all, **_params) def show_fwaas_firewall_group(self, fwg, **_params): """Fetches information of a certain firewall group""" return self.get(self.fwaas_firewall_group_path % (fwg), params=_params) def create_fwaas_firewall_group(self, body=None): """Creates a new firewall group""" return self.post(self.fwaas_firewall_groups_path, body=body) def update_fwaas_firewall_group(self, fwg, body=None): """Updates a firewall group""" return self.put(self.fwaas_firewall_group_path % (fwg), body=body) def delete_fwaas_firewall_group(self, fwg): """Deletes the specified firewall group""" return self.delete(self.fwaas_firewall_group_path % (fwg)) def list_fwaas_firewall_rules(self, retrieve_all=True, **_params): """Fetches a list of all firewall rules for a project""" # Pass filters in "params" argument to do_request return self.list('firewall_rules', self.fwaas_firewall_rules_path, retrieve_all, **_params) def show_fwaas_firewall_rule(self, firewall_rule, **_params): """Fetches information of a certain firewall rule""" return self.get(self.fwaas_firewall_rule_path % (firewall_rule), params=_params) def create_fwaas_firewall_rule(self, body=None): """Creates a new firewall rule""" return self.post(self.fwaas_firewall_rules_path, body=body) def update_fwaas_firewall_rule(self, firewall_rule, body=None): """Updates a firewall rule""" return self.put(self.fwaas_firewall_rule_path % (firewall_rule), body=body) def delete_fwaas_firewall_rule(self, firewall_rule): """Deletes the specified firewall rule""" return self.delete(self.fwaas_firewall_rule_path % (firewall_rule)) def list_fwaas_firewall_policies(self, retrieve_all=True, **_params): """Fetches a list of all firewall policies for a project""" # Pass filters in "params" argument to do_request return self.list('firewall_policies', self.fwaas_firewall_policies_path, retrieve_all, **_params) def show_fwaas_firewall_policy(self, firewall_policy, **_params): """Fetches information of a certain firewall policy""" return self.get(self.fwaas_firewall_policy_path % (firewall_policy), params=_params) def create_fwaas_firewall_policy(self, body=None): """Creates a new firewall policy""" return self.post(self.fwaas_firewall_policies_path, body=body) def update_fwaas_firewall_policy(self, firewall_policy, body=None): """Updates a firewall policy""" return self.put(self.fwaas_firewall_policy_path % (firewall_policy), body=body) def delete_fwaas_firewall_policy(self, firewall_policy): """Deletes the specified firewall policy""" return self.delete(self.fwaas_firewall_policy_path % (firewall_policy)) def insert_rule_fwaas_firewall_policy(self, firewall_policy, body=None): """Inserts specified rule into firewall policy""" return self.put((self.fwaas_firewall_policy_insert_path % (firewall_policy)), body=body) def remove_rule_fwaas_firewall_policy(self, firewall_policy, body=None): """Removes specified rule from firewall policy""" return self.put((self.fwaas_firewall_policy_remove_path % (firewall_policy)), body=body) def remove_router_from_l3_agent(self, l3_agent, router_id): """Remove a router from l3 agent.""" return self.delete((self.agent_path + self.L3_ROUTERS + "/%s") % ( l3_agent, router_id)) def get_lbaas_agent_hosting_pool(self, pool, **_params): """Fetches a loadbalancer agent hosting a pool.""" return self.get((self.pool_path + self.LOADBALANCER_AGENT) % pool, params=_params) def list_pools_on_lbaas_agent(self, lbaas_agent, **_params): """Fetches a list of pools hosted by the loadbalancer agent.""" return self.get((self.agent_path + self.LOADBALANCER_POOLS) % lbaas_agent, params=_params) def get_lbaas_agent_hosting_loadbalancer(self, loadbalancer, **_params): """Fetches a loadbalancer agent hosting a loadbalancer.""" return self.get((self.lbaas_loadbalancer_path + self.LOADBALANCER_HOSTING_AGENT) % loadbalancer, params=_params) def list_loadbalancers_on_lbaas_agent(self, lbaas_agent, **_params): """Fetches a list of loadbalancers hosted by the loadbalancer agent.""" return self.get((self.agent_path + self.AGENT_LOADBALANCERS) % lbaas_agent, params=_params) def list_service_providers(self, retrieve_all=True, **_params): """Fetches service providers.""" # Pass filters in "params" argument to do_request return self.list('service_providers', self.service_providers_path, retrieve_all, **_params) def create_metering_label(self, body=None): """Creates a metering label.""" return self.post(self.metering_labels_path, body=body) def delete_metering_label(self, label): """Deletes the specified metering label.""" return self.delete(self.metering_label_path % (label)) def list_metering_labels(self, retrieve_all=True, **_params): """Fetches a list of all metering labels for a project.""" return self.list('metering_labels', self.metering_labels_path, retrieve_all, **_params) def show_metering_label(self, metering_label, **_params): """Fetches information of a certain metering label.""" return self.get(self.metering_label_path % (metering_label), params=_params) def create_metering_label_rule(self, body=None): """Creates a metering label rule.""" return self.post(self.metering_label_rules_path, body=body) def delete_metering_label_rule(self, rule): """Deletes the specified metering label rule.""" return self.delete(self.metering_label_rule_path % (rule)) def list_metering_label_rules(self, retrieve_all=True, **_params): """Fetches a list of all metering label rules for a label.""" return self.list('metering_label_rules', self.metering_label_rules_path, retrieve_all, **_params) def show_metering_label_rule(self, metering_label_rule, **_params): """Fetches information of a certain metering label rule.""" return self.get(self.metering_label_rule_path % (metering_label_rule), params=_params) def create_rbac_policy(self, body=None): """Create a new RBAC policy.""" return self.post(self.rbac_policies_path, body=body) def update_rbac_policy(self, rbac_policy_id, body=None): """Update a RBAC policy.""" return self.put(self.rbac_policy_path % rbac_policy_id, body=body) def list_rbac_policies(self, retrieve_all=True, **_params): """Fetch a list of all RBAC policies for a project.""" return self.list('rbac_policies', self.rbac_policies_path, retrieve_all, **_params) def show_rbac_policy(self, rbac_policy_id, **_params): """Fetch information of a certain RBAC policy.""" return self.get(self.rbac_policy_path % rbac_policy_id, params=_params) def delete_rbac_policy(self, rbac_policy_id): """Delete the specified RBAC policy.""" return self.delete(self.rbac_policy_path % rbac_policy_id) def list_qos_policies(self, retrieve_all=True, **_params): """Fetches a list of all qos policies for a project.""" # Pass filters in "params" argument to do_request return self.list('policies', self.qos_policies_path, retrieve_all, **_params) def show_qos_policy(self, qos_policy, **_params): """Fetches information of a certain qos policy.""" return self.get(self.qos_policy_path % qos_policy, params=_params) def create_qos_policy(self, body=None): """Creates a new qos policy.""" return self.post(self.qos_policies_path, body=body) def update_qos_policy(self, qos_policy, body=None, revision_number=None): """Updates a qos policy.""" return self._update_resource(self.qos_policy_path % qos_policy, body=body, revision_number=revision_number) def delete_qos_policy(self, qos_policy): """Deletes the specified qos policy.""" return self.delete(self.qos_policy_path % qos_policy) def list_qos_rule_types(self, retrieve_all=True, **_params): """List available qos rule types.""" return self.list('rule_types', self.qos_rule_types_path, retrieve_all, **_params) def list_bandwidth_limit_rules(self, policy_id, retrieve_all=True, **_params): """Fetches a list of all bandwidth limit rules for the given policy.""" return self.list('bandwidth_limit_rules', self.qos_bandwidth_limit_rules_path % policy_id, retrieve_all, **_params) def show_bandwidth_limit_rule(self, rule, policy, **_params): """Fetches information of a certain bandwidth limit rule.""" return self.get(self.qos_bandwidth_limit_rule_path % (policy, rule), params=_params) def create_bandwidth_limit_rule(self, policy, body=None): """Creates a new bandwidth limit rule.""" return self.post(self.qos_bandwidth_limit_rules_path % policy, body=body) def update_bandwidth_limit_rule(self, rule, policy, body=None): """Updates a bandwidth limit rule.""" return self.put(self.qos_bandwidth_limit_rule_path % (policy, rule), body=body) def delete_bandwidth_limit_rule(self, rule, policy): """Deletes a bandwidth limit rule.""" return self.delete(self.qos_bandwidth_limit_rule_path % (policy, rule)) def list_dscp_marking_rules(self, policy_id, retrieve_all=True, **_params): """Fetches a list of all DSCP marking rules for the given policy.""" return self.list('dscp_marking_rules', self.qos_dscp_marking_rules_path % policy_id, retrieve_all, **_params) def show_dscp_marking_rule(self, rule, policy, **_params): """Shows information of a certain DSCP marking rule.""" return self.get(self.qos_dscp_marking_rule_path % (policy, rule), params=_params) def create_dscp_marking_rule(self, policy, body=None): """Creates a new DSCP marking rule.""" return self.post(self.qos_dscp_marking_rules_path % policy, body=body) def update_dscp_marking_rule(self, rule, policy, body=None): """Updates a DSCP marking rule.""" return self.put(self.qos_dscp_marking_rule_path % (policy, rule), body=body) def delete_dscp_marking_rule(self, rule, policy): """Deletes a DSCP marking rule.""" return self.delete(self.qos_dscp_marking_rule_path % (policy, rule)) def list_minimum_bandwidth_rules(self, policy_id, retrieve_all=True, **_params): """Fetches a list of all minimum bandwidth rules for the given policy. """ return self.list('minimum_bandwidth_rules', self.qos_minimum_bandwidth_rules_path % policy_id, retrieve_all, **_params) def show_minimum_bandwidth_rule(self, rule, policy, body=None): """Fetches information of a certain minimum bandwidth rule.""" return self.get(self.qos_minimum_bandwidth_rule_path % (policy, rule), body=body) def create_minimum_bandwidth_rule(self, policy, body=None): """Creates a new minimum bandwidth rule.""" return self.post(self.qos_minimum_bandwidth_rules_path % policy, body=body) def list_packet_rate_limit_rules(self, policy_id, retrieve_all=True, **_params): """Fetches a list of all packet rate limit rules for the given policy """ return self.list('packet_rate_limit_rules', self.qos_packet_rate_limit_rules_path % policy_id, retrieve_all, **_params) def show_packet_rate_limit_rule(self, rule, policy, body=None): """Fetches information of a certain packet rate limit rule.""" return self.get(self.qos_packet_rate_limit_rule_path % (policy, rule), body=body) def create_packet_rate_limit_rule(self, policy, body=None): """Creates a new packet rate limit rule.""" return self.post(self.qos_packet_rate_limit_rules_path % policy, body=body) def update_packet_rate_limit_rule(self, rule, policy, body=None): """Updates a packet rate limit rule.""" return self.put(self.qos_packet_rate_limit_rule_path % (policy, rule), body=body) def delete_packet_rate_limit_rule(self, rule, policy): """Deletes a packet rate limit rule.""" return self.delete(self.qos_packet_rate_limit_rule_path % (policy, rule)) def update_minimum_bandwidth_rule(self, rule, policy, body=None): """Updates a minimum bandwidth rule.""" return self.put(self.qos_minimum_bandwidth_rule_path % (policy, rule), body=body) def delete_minimum_bandwidth_rule(self, rule, policy): """Deletes a minimum bandwidth rule.""" return self.delete(self.qos_minimum_bandwidth_rule_path % (policy, rule)) def list_minimum_packet_rate_rules(self, policy_id, retrieve_all=True, **_params): """Fetches a list of all minimum packet rate rules for the given policy """ return self.list('minimum_packet_rate_rules', self.qos_minimum_packet_rate_rules_path % policy_id, retrieve_all, **_params) def show_minimum_packet_rate_rule(self, rule, policy, body=None): """Fetches information of a certain minimum packet rate rule.""" return self.get(self.qos_minimum_packet_rate_rule_path % (policy, rule), body=body) def create_minimum_packet_rate_rule(self, policy, body=None): """Creates a new minimum packet rate rule.""" return self.post(self.qos_minimum_packet_rate_rules_path % policy, body=body) def update_minimum_packet_rate_rule(self, rule, policy, body=None): """Updates a minimum packet rate rule.""" return self.put(self.qos_minimum_packet_rate_rule_path % (policy, rule), body=body) def delete_minimum_packet_rate_rule(self, rule, policy): """Deletes a minimum packet rate rule.""" return self.delete(self.qos_minimum_packet_rate_rule_path % (policy, rule)) def create_flavor(self, body=None): """Creates a new Neutron service flavor.""" return self.post(self.flavors_path, body=body) def delete_flavor(self, flavor): """Deletes the specified Neutron service flavor.""" return self.delete(self.flavor_path % (flavor)) def list_flavors(self, retrieve_all=True, **_params): """Fetches a list of all Neutron service flavors for a project.""" return self.list('flavors', self.flavors_path, retrieve_all, **_params) def show_flavor(self, flavor, **_params): """Fetches information for a certain Neutron service flavor.""" return self.get(self.flavor_path % (flavor), params=_params) def update_flavor(self, flavor, body): """Update a Neutron service flavor.""" return self.put(self.flavor_path % (flavor), body=body) def associate_flavor(self, flavor, body): """Associate a Neutron service flavor with a profile.""" return self.post(self.flavor_profile_bindings_path % (flavor), body=body) def disassociate_flavor(self, flavor, flavor_profile): """Disassociate a Neutron service flavor with a profile.""" return self.delete(self.flavor_profile_binding_path % (flavor, flavor_profile)) def create_service_profile(self, body=None): """Creates a new Neutron service flavor profile.""" return self.post(self.service_profiles_path, body=body) def delete_service_profile(self, flavor_profile): """Deletes the specified Neutron service flavor profile.""" return self.delete(self.service_profile_path % (flavor_profile)) def list_service_profiles(self, retrieve_all=True, **_params): """Fetches a list of all Neutron service flavor profiles.""" return self.list('service_profiles', self.service_profiles_path, retrieve_all, **_params) def show_service_profile(self, flavor_profile, **_params): """Fetches information for a certain Neutron service flavor profile.""" return self.get(self.service_profile_path % (flavor_profile), params=_params) def update_service_profile(self, service_profile, body): """Update a Neutron service profile.""" return self.put(self.service_profile_path % (service_profile), body=body) def list_availability_zones(self, retrieve_all=True, **_params): """Fetches a list of all availability zones.""" return self.list('availability_zones', self.availability_zones_path, retrieve_all, **_params) @debtcollector.renames.renamed_kwarg( 'tenant_id', 'project_id', replace=True) def get_auto_allocated_topology(self, project_id, **_params): """Fetch information about a project's auto-allocated topology.""" return self.get( self.auto_allocated_topology_path % project_id, params=_params) @debtcollector.renames.renamed_kwarg( 'tenant_id', 'project_id', replace=True) def delete_auto_allocated_topology(self, project_id, **_params): """Delete a project's auto-allocated topology.""" return self.delete( self.auto_allocated_topology_path % project_id, params=_params) @debtcollector.renames.renamed_kwarg( 'tenant_id', 'project_id', replace=True) def validate_auto_allocated_topology_requirements(self, project_id): """Validate requirements for getting an auto-allocated topology.""" return self.get_auto_allocated_topology(project_id, fields=['dry-run']) def list_bgp_speakers(self, retrieve_all=True, **_params): """Fetches a list of all BGP speakers for a project.""" return self.list('bgp_speakers', self.bgp_speakers_path, retrieve_all, **_params) def show_bgp_speaker(self, bgp_speaker_id, **_params): """Fetches information of a certain BGP speaker.""" return self.get(self.bgp_speaker_path % (bgp_speaker_id), params=_params) def create_bgp_speaker(self, body=None): """Creates a new BGP speaker.""" return self.post(self.bgp_speakers_path, body=body) def update_bgp_speaker(self, bgp_speaker_id, body=None): """Update a BGP speaker.""" return self.put(self.bgp_speaker_path % bgp_speaker_id, body=body) def delete_bgp_speaker(self, speaker_id): """Deletes the specified BGP speaker.""" return self.delete(self.bgp_speaker_path % (speaker_id)) def add_peer_to_bgp_speaker(self, speaker_id, body=None): """Adds a peer to BGP speaker.""" return self.put((self.bgp_speaker_path % speaker_id) + "/add_bgp_peer", body=body) def remove_peer_from_bgp_speaker(self, speaker_id, body=None): """Removes a peer from BGP speaker.""" return self.put((self.bgp_speaker_path % speaker_id) + "/remove_bgp_peer", body=body) def add_network_to_bgp_speaker(self, speaker_id, body=None): """Adds a network to BGP speaker.""" return self.put((self.bgp_speaker_path % speaker_id) + "/add_gateway_network", body=body) def remove_network_from_bgp_speaker(self, speaker_id, body=None): """Removes a network from BGP speaker.""" return self.put((self.bgp_speaker_path % speaker_id) + "/remove_gateway_network", body=body) def list_route_advertised_from_bgp_speaker(self, speaker_id, **_params): """Fetches a list of all routes advertised by BGP speaker.""" return self.get((self.bgp_speaker_path % speaker_id) + "/get_advertised_routes", params=_params) def list_bgp_peers(self, **_params): """Fetches a list of all BGP peers.""" return self.get(self.bgp_peers_path, params=_params) def show_bgp_peer(self, peer_id, **_params): """Fetches information of a certain BGP peer.""" return self.get(self.bgp_peer_path % peer_id, params=_params) def create_bgp_peer(self, body=None): """Create a new BGP peer.""" return self.post(self.bgp_peers_path, body=body) def update_bgp_peer(self, bgp_peer_id, body=None): """Update a BGP peer.""" return self.put(self.bgp_peer_path % bgp_peer_id, body=body) def delete_bgp_peer(self, peer_id): """Deletes the specified BGP peer.""" return self.delete(self.bgp_peer_path % peer_id) def list_network_ip_availabilities(self, retrieve_all=True, **_params): """Fetches IP availability information for all networks""" return self.list('network_ip_availabilities', self.network_ip_availabilities_path, retrieve_all, **_params) def show_network_ip_availability(self, network, **_params): """Fetches IP availability information for a specified network""" return self.get(self.network_ip_availability_path % (network), params=_params) def add_tag(self, resource_type, resource_id, tag, **_params): """Add a tag on the resource.""" return self.put(self.tag_path % (resource_type, resource_id, tag)) def replace_tag(self, resource_type, resource_id, body, **_params): """Replace tags on the resource.""" return self.put(self.tags_path % (resource_type, resource_id), body) def remove_tag(self, resource_type, resource_id, tag, **_params): """Remove a tag on the resource.""" return self.delete(self.tag_path % (resource_type, resource_id, tag)) def remove_tag_all(self, resource_type, resource_id, **_params): """Remove all tags on the resource.""" return self.delete(self.tags_path % (resource_type, resource_id)) def create_trunk(self, body=None): """Create a trunk port.""" return self.post(self.trunks_path, body=body) def update_trunk(self, trunk, body=None, revision_number=None): """Update a trunk port.""" return self._update_resource(self.trunk_path % trunk, body=body, revision_number=revision_number) def delete_trunk(self, trunk): """Delete a trunk port.""" return self.delete(self.trunk_path % (trunk)) def list_trunks(self, retrieve_all=True, **_params): """Fetch a list of all trunk ports.""" return self.list('trunks', self.trunks_path, retrieve_all, **_params) def show_trunk(self, trunk, **_params): """Fetch information for a certain trunk port.""" return self.get(self.trunk_path % (trunk), params=_params) def trunk_add_subports(self, trunk, body=None): """Add specified subports to the trunk.""" return self.put(self.subports_add_path % (trunk), body=body) def trunk_remove_subports(self, trunk, body=None): """Removes specified subports from the trunk.""" return self.put(self.subports_remove_path % (trunk), body=body) def trunk_get_subports(self, trunk, **_params): """Fetch a list of all subports attached to given trunk.""" return self.get(self.subports_path % (trunk), params=_params) def list_bgpvpns(self, retrieve_all=True, **_params): """Fetches a list of all BGP VPNs for a project""" return self.list('bgpvpns', self.bgpvpns_path, retrieve_all, **_params) def show_bgpvpn(self, bgpvpn, **_params): """Fetches information of a certain BGP VPN""" return self.get(self.bgpvpn_path % bgpvpn, params=_params) def create_bgpvpn(self, body=None): """Creates a new BGP VPN""" return self.post(self.bgpvpns_path, body=body) def update_bgpvpn(self, bgpvpn, body=None): """Updates a BGP VPN""" return self.put(self.bgpvpn_path % bgpvpn, body=body) def delete_bgpvpn(self, bgpvpn): """Deletes the specified BGP VPN""" return self.delete(self.bgpvpn_path % bgpvpn) def list_bgpvpn_network_assocs(self, bgpvpn, retrieve_all=True, **_params): """Fetches a list of network associations for a given BGP VPN.""" return self.list('network_associations', self.bgpvpn_network_associations_path % bgpvpn, retrieve_all, **_params) def show_bgpvpn_network_assoc(self, bgpvpn, net_assoc, **_params): """Fetches information of a certain BGP VPN's network association""" return self.get( self.bgpvpn_network_association_path % (bgpvpn, net_assoc), params=_params) def create_bgpvpn_network_assoc(self, bgpvpn, body=None): """Creates a new BGP VPN network association""" return self.post(self.bgpvpn_network_associations_path % bgpvpn, body=body) def update_bgpvpn_network_assoc(self, bgpvpn, net_assoc, body=None): """Updates a BGP VPN network association""" return self.put( self.bgpvpn_network_association_path % (bgpvpn, net_assoc), body=body) def delete_bgpvpn_network_assoc(self, bgpvpn, net_assoc): """Deletes the specified BGP VPN network association""" return self.delete( self.bgpvpn_network_association_path % (bgpvpn, net_assoc)) def list_bgpvpn_router_assocs(self, bgpvpn, retrieve_all=True, **_params): """Fetches a list of router associations for a given BGP VPN.""" return self.list('router_associations', self.bgpvpn_router_associations_path % bgpvpn, retrieve_all, **_params) def show_bgpvpn_router_assoc(self, bgpvpn, router_assoc, **_params): """Fetches information of a certain BGP VPN's router association""" return self.get( self.bgpvpn_router_association_path % (bgpvpn, router_assoc), params=_params) def create_bgpvpn_router_assoc(self, bgpvpn, body=None): """Creates a new BGP VPN router association""" return self.post(self.bgpvpn_router_associations_path % bgpvpn, body=body) def update_bgpvpn_router_assoc(self, bgpvpn, router_assoc, body=None): """Updates a BGP VPN router association""" return self.put( self.bgpvpn_router_association_path % (bgpvpn, router_assoc), body=body) def delete_bgpvpn_router_assoc(self, bgpvpn, router_assoc): """Deletes the specified BGP VPN router association""" return self.delete( self.bgpvpn_router_association_path % (bgpvpn, router_assoc)) def list_bgpvpn_port_assocs(self, bgpvpn, retrieve_all=True, **_params): """Fetches a list of port associations for a given BGP VPN.""" return self.list('port_associations', self.bgpvpn_port_associations_path % bgpvpn, retrieve_all, **_params) def show_bgpvpn_port_assoc(self, bgpvpn, port_assoc, **_params): """Fetches information of a certain BGP VPN's port association""" return self.get( self.bgpvpn_port_association_path % (bgpvpn, port_assoc), params=_params) def create_bgpvpn_port_assoc(self, bgpvpn, body=None): """Creates a new BGP VPN port association""" return self.post(self.bgpvpn_port_associations_path % bgpvpn, body=body) def update_bgpvpn_port_assoc(self, bgpvpn, port_assoc, body=None): """Updates a BGP VPN port association""" return self.put( self.bgpvpn_port_association_path % (bgpvpn, port_assoc), body=body) def delete_bgpvpn_port_assoc(self, bgpvpn, port_assoc): """Deletes the specified BGP VPN port association""" return self.delete( self.bgpvpn_port_association_path % (bgpvpn, port_assoc)) def create_sfc_port_pair(self, body=None): """Creates a new Port Pair.""" return self.post(self.sfc_port_pairs_path, body=body) def update_sfc_port_pair(self, port_pair, body=None): """Update a Port Pair.""" return self.put(self.sfc_port_pair_path % port_pair, body=body) def delete_sfc_port_pair(self, port_pair): """Deletes the specified Port Pair.""" return self.delete(self.sfc_port_pair_path % (port_pair)) def list_sfc_port_pairs(self, retrieve_all=True, **_params): """Fetches a list of all Port Pairs.""" return self.list('port_pairs', self.sfc_port_pairs_path, retrieve_all, **_params) def show_sfc_port_pair(self, port_pair, **_params): """Fetches information of a certain Port Pair.""" return self.get(self.sfc_port_pair_path % (port_pair), params=_params) def create_sfc_port_pair_group(self, body=None): """Creates a new Port Pair Group.""" return self.post(self.sfc_port_pair_groups_path, body=body) def update_sfc_port_pair_group(self, port_pair_group, body=None): """Update a Port Pair Group.""" return self.put(self.sfc_port_pair_group_path % port_pair_group, body=body) def delete_sfc_port_pair_group(self, port_pair_group): """Deletes the specified Port Pair Group.""" return self.delete(self.sfc_port_pair_group_path % (port_pair_group)) def list_sfc_port_pair_groups(self, retrieve_all=True, **_params): """Fetches a list of all Port Pair Groups.""" return self.list('port_pair_groups', self.sfc_port_pair_groups_path, retrieve_all, **_params) def show_sfc_port_pair_group(self, port_pair_group, **_params): """Fetches information of a certain Port Pair Group.""" return self.get(self.sfc_port_pair_group_path % (port_pair_group), params=_params) def create_sfc_port_chain(self, body=None): """Creates a new Port Chain.""" return self.post(self.sfc_port_chains_path, body=body) def update_sfc_port_chain(self, port_chain, body=None): """Update a Port Chain.""" return self.put(self.sfc_port_chain_path % port_chain, body=body) def delete_sfc_port_chain(self, port_chain): """Deletes the specified Port Chain.""" return self.delete(self.sfc_port_chain_path % (port_chain)) def list_sfc_port_chains(self, retrieve_all=True, **_params): """Fetches a list of all Port Chains.""" return self.list('port_chains', self.sfc_port_chains_path, retrieve_all, **_params) def show_sfc_port_chain(self, port_chain, **_params): """Fetches information of a certain Port Chain.""" return self.get(self.sfc_port_chain_path % (port_chain), params=_params) def create_sfc_flow_classifier(self, body=None): """Creates a new Flow Classifier.""" return self.post(self.sfc_flow_classifiers_path, body=body) def update_sfc_flow_classifier(self, flow_classifier, body=None): """Update a Flow Classifier.""" return self.put(self.sfc_flow_classifier_path % flow_classifier, body=body) def delete_sfc_flow_classifier(self, flow_classifier): """Deletes the specified Flow Classifier.""" return self.delete(self.sfc_flow_classifier_path % (flow_classifier)) def list_sfc_flow_classifiers(self, retrieve_all=True, **_params): """Fetches a list of all Flow Classifiers.""" return self.list('flow_classifiers', self.sfc_flow_classifiers_path, retrieve_all, **_params) def show_sfc_flow_classifier(self, flow_classifier, **_params): """Fetches information of a certain Flow Classifier.""" return self.get(self.sfc_flow_classifier_path % (flow_classifier), params=_params) def create_sfc_service_graph(self, body=None): """Create the specified Service Graph.""" return self.post(self.sfc_service_graphs_path, body=body) def update_sfc_service_graph(self, service_graph, body=None): """Update a Service Graph.""" return self.put(self.sfc_service_graph_path % service_graph, body=body) def delete_sfc_service_graph(self, service_graph): """Deletes the specified Service Graph.""" return self.delete(self.sfc_service_graph_path % service_graph) def list_sfc_service_graphs(self, retrieve_all=True, **_params): """Fetches a list of all Service Graphs.""" return self.list('service_graphs', self.sfc_service_graphs_path, retrieve_all, **_params) def show_sfc_service_graph(self, service_graph, **_params): """Fetches information of a certain Service Graph.""" return self.get(self.sfc_service_graph_path % service_graph, params=_params) def create_network_log(self, body=None): """Create a network log.""" return self.post(self.network_logs_path, body=body) def delete_network_log(self, net_log): """Delete a network log.""" return self.delete(self.network_log_path % net_log) def list_network_logs(self, retrieve_all=True, **_params): """Fetch a list of all network logs.""" return self.list( 'logs', self.network_logs_path, retrieve_all, **_params) def show_network_log(self, net_log, **_params): """Fetch information for a certain network log.""" return self.get(self.network_log_path % net_log, params=_params) def update_network_log(self, net_log, body=None): """Update a network log.""" return self.put(self.network_log_path % net_log, body=body) def list_network_loggable_resources(self, retrieve_all=True, **_params): """Fetch a list of supported resource types for network log.""" return self.list('loggable_resources', self.network_loggables_path, retrieve_all, **_params) def onboard_network_subnets(self, subnetpool, body=None): """Onboard the specified network's subnets into a subnet pool.""" return self.put(self.onboard_network_subnets_path % (subnetpool), body=body) def __init__(self, **kwargs): """Initialize a new client for the Neutron v2.0 API.""" super(Client, self).__init__(**kwargs) self._register_extensions(self.version) def _update_resource(self, path, **kwargs): revision_number = kwargs.pop('revision_number', None) if revision_number: headers = kwargs.setdefault('headers', {}) headers['If-Match'] = 'revision_number=%s' % revision_number return self.put(path, **kwargs) def extend_show(self, resource_singular, path, parent_resource): def _fx(obj, **_params): return self.show_ext(path, obj, **_params) def _parent_fx(obj, parent_id, **_params): return self.show_ext(path % parent_id, obj, **_params) fn = _fx if not parent_resource else _parent_fx setattr(self, "show_%s" % resource_singular, fn) def extend_list(self, resource_plural, path, parent_resource): def _fx(retrieve_all=True, **_params): return self.list_ext(resource_plural, path, retrieve_all, **_params) def _parent_fx(parent_id, retrieve_all=True, **_params): return self.list_ext(resource_plural, path % parent_id, retrieve_all, **_params) fn = _fx if not parent_resource else _parent_fx setattr(self, "list_%s" % resource_plural, fn) def extend_create(self, resource_singular, path, parent_resource): def _fx(body=None): return self.create_ext(path, body) def _parent_fx(parent_id, body=None): return self.create_ext(path % parent_id, body) fn = _fx if not parent_resource else _parent_fx setattr(self, "create_%s" % resource_singular, fn) def extend_delete(self, resource_singular, path, parent_resource): def _fx(obj): return self.delete_ext(path, obj) def _parent_fx(obj, parent_id): return self.delete_ext(path % parent_id, obj) fn = _fx if not parent_resource else _parent_fx setattr(self, "delete_%s" % resource_singular, fn) def extend_update(self, resource_singular, path, parent_resource): def _fx(obj, body=None): return self.update_ext(path, obj, body) def _parent_fx(obj, parent_id, body=None): return self.update_ext(path % parent_id, obj, body) fn = _fx if not parent_resource else _parent_fx setattr(self, "update_%s" % resource_singular, fn) def _extend_client_with_module(self, module, version): classes = inspect.getmembers(module, inspect.isclass) for cls_name, cls in classes: if hasattr(cls, 'versions'): if version not in cls.versions: continue parent_resource = getattr(cls, 'parent_resource', None) if issubclass(cls, client_extension.ClientExtensionList): self.extend_list(cls.resource_plural, cls.object_path, parent_resource) elif issubclass(cls, client_extension.ClientExtensionCreate): self.extend_create(cls.resource, cls.object_path, parent_resource) elif issubclass(cls, client_extension.ClientExtensionUpdate): self.extend_update(cls.resource, cls.resource_path, parent_resource) elif issubclass(cls, client_extension.ClientExtensionDelete): self.extend_delete(cls.resource, cls.resource_path, parent_resource) elif issubclass(cls, client_extension.ClientExtensionShow): self.extend_show(cls.resource, cls.resource_path, parent_resource) elif issubclass(cls, client_extension.NeutronClientExtension): setattr(self, "%s_path" % cls.resource_plural, cls.object_path) setattr(self, "%s_path" % cls.resource, cls.resource_path) self.EXTED_PLURALS.update({cls.resource_plural: cls.resource}) def _register_extensions(self, version): for name, module in itertools.chain( client_extension._discover_via_entry_points()): self._extend_client_with_module(module, version)
openstack/python-neutronclient
neutronclient/v2_0/client.py
Python
apache-2.0
115,185
 var currPageIndex = 0; app.initialize(); $(document).ready(function () { //$('.appV').html('v1.17'); //onDocumentReady(); setMenu(); toggleMenu(); }); function onDocumentReady() { SetPagesList(); setBackground(); runPinchzoom(); turnPages(currPageIndex); setPep(); //changeSize(); setZIndex(); setTimeout("setImgList();", 500); } function setImgList() { var imgList = [ 'images/smallTop.png', 'images/middle.png', 'images/smallBottom.png', 'images/largeTop.png', 'images/largeBottom.png', 'images/menu_cats.png', 'images/menu_recipes.png' ]; var imgListLength = imgList.length; for (var i = 0; i < recipesList.length; i++) { imgList[i + 8] = "images/RecipesImages/" + recipesList[i].image; } preload(imgList); } function preload(arrayOfImages) { for (var i = 0; i < arrayOfImages.length; i++) { setTimeout("$('<img />').attr('src', '"+arrayOfImages[i]+"').appendTo('body').css('display', 'none');", 200); } //$(arrayOfImages).each(function () { //}); } function setPep() { $('.ingredientsDiv, .directionsDiv, .text').pep({ useCSSTranslation: false, constrainTo: 'parent', place: false }); } function setBackground() { var picturesArray = new Array(); for (var i = 0; i < categoriesList.length; i++) { picturesArray[i] = categoriesList[i].background; } $('BODY').bgStretcher({ images: picturesArray, imageWidth: 2000, imageHeight: 1200, slideShowSpeed: 1500, anchoring: 'center top', anchoringImg: 'center top', slideShow: false, transitionEffect: 'simpleSlide', slideDirection: 'W', sequenceMode: 'normal', buttonNext: '.next', buttonPrev: '.back', }); } function chkIfIE9() { if (isIE9()) { $('.ingredientsDiv, .directionsDiv, .imgDiv').addClass('hide'); } else { setTimeout(" $('.ingredientsDiv, .directionsDiv, .imgDiv').removeClass('hide');", 1000); } } function isIE9() { var myNav = navigator.userAgent.toLowerCase(); //alert(myNav); return (myNav.indexOf('msie 9') != -1); } function setZIndex() { $('.ingredientsDiv, .directionsDiv, .imgDiv').click(function () { $('.ingredientsDiv, .directionsDiv, .imgDiv').removeClass('zIndex2'); $(this).addClass('zIndex2'); }); } var isChangingSize = false; function changeSize() { $('.ingredientsDiv, .directionsDiv').click(function () { if (!isChangingSize) { if ($(this).hasClass('bigSize')) { $(this).removeClass('bigSize'); isChangingSize = true; } else { $(this).addClass('bigSize'); isChangingSize = true; } setTimeout("isChangingSize = false;", 200); } }); } function runPinchzoom() { if (!Hammer.HAS_TOUCHEVENTS && !Hammer.HAS_POINTEREVENTS) { Hammer.plugins.fakeMultitouch(); } var pinchzoom = $('.pinchzoom').each(function () { var hammertime = Hammer($(this).get(0), { transform_always_block: true, transform_min_scale: 1, drag_block_horizontal: true, drag_block_vertical: true, drag_min_distance: 0 }); var rect = $(this).find('.rect').get(0); var posX = 0, posY = 0, scale = 1, last_scale, rotation = 1, last_rotation; hammertime.on('touch drag transform', function (ev) { switch (ev.type) { case 'touch': last_scale = scale; last_rotation = rotation; break; case 'drag': posX = ev.gesture.deltaX; posY = ev.gesture.deltaY; break; case 'transform': rotation = last_rotation + ev.gesture.rotation; scale = Math.max(1, Math.min(last_scale * ev.gesture.scale, 2)); break; } if (rotation == 1) rotation = 0; // transform! var transform = //"translate3d(" + posX + "px," + posY + "px, 0) " + "scale3d(" + scale + "," + scale + ", 1) " + "rotate(" + rotation + "deg) "; rect.style.transform = transform; rect.style.oTransform = transform; rect.style.msTransform = transform; rect.style.mozTransform = transform; rect.style.webkitTransform = transform; rect.style.msTransform = transform; }); }); } // Category class: function category(id, name, background, header_bg) { this.id = id; this.name = name; this.background = background; this.header_bg = header_bg; this.type = 'category'; } // Recipe class: function recipe(cat_id, name, header_bg, description1, description2, image, pdf) { this.cat_id = cat_id; this.name = name; this.header_bg = header_bg; this.description1 = description1; this.description2 = description2; this.image = image; this.pdf = pdf; this.type = 'recipe'; } var categoriesList = new Array(); categoriesList[0] = new category(0, "Main", 'images/bg_main.jpg', ''); categoriesList[1] = new category(1, "Intro", 'images/bg_intro.jpg', ''); categoriesList[2] = new category(10, "Alex & Cathy's Recipes", 'images/bg_owners.jpg', ''); categoriesList[3] = new category(2, "Appetizers", 'images/bg_appetizers.jpg', 'images/cat_appetizers.png'); categoriesList[4] = new category(3, "Main dishes", 'images/bg_main_dishes.jpg', 'images/cat_mainDishes.png'); categoriesList[5] = new category(4, "Desserts", 'images/bg_desserts.jpg', 'images/cat_desserts.png'); categoriesList[6] = new category(5, "Breakfast", 'images/bg_breakfast.jpg', 'images/cat_breakfast.png'); categoriesList[7] = new category(6, "Drinks", 'images/bg_drinks.jpg', 'images/cat_drinks.png'); categoriesList[8] = new category(7, "Sides", 'images/bg_sides.jpg', 'images/cat_sides.png'); categoriesList[9] = new category(8, "Thank You", 'images/bg_thank_you.jpg', ''); //categoriesList[8] = new category(8, "SoupAndBeans", 'images/bg_soup_and_beans.jpg', 'images/cat_soupsAndBeans.png'); var recipesList = new Array(); var pagesList = new Array(); function SetPagesList() { var catID; var index = 0; for (var i = 0; i < categoriesList.length; i++) { catID = categoriesList[i].id; if (catID != 10) { pagesList[index] = categoriesList[i]; index++; } for (var j = 0; j < recipesList.length; j++) { if (recipesList[j].cat_id == catID) { pagesList[index] = recipesList[j]; index++; } } } } var isPageInMove = false; function turnPages(moveToIndex) { if (!isPageInMove && moveToIndex < pagesList.length) { isPageInMove = true; $('.bigSize').removeClass('bigSize'); $('BODY').bgStretcher.pause(); moveToPage = pagesList[moveToIndex]; //alert(moveToPage.name); if (findCurrBackgroundIndex(pagesList[currPageIndex]) != findCurrBackgroundIndex(pagesList[moveToIndex])) { //if (moveToIndex != 0) { var slideNumber = findCurrBackgroundIndex(pagesList[moveToIndex]); $('BODY').bgStretcher.slideShow(null, slideNumber); //if (currPageIndex < moveToIndex) { // $('.next').click(); //} //else { // $('.back').click(); //} //} } if (moveToPage.type == 'category') { //hide the elements - FOR IE9: chkIfIE9(); //////////////////////////// hideElelnent(); if (pagesList[moveToIndex].header_bg == "") { $('.categoryHeaderDiv').hide(0) } else { //$('.headerDiv').hide(); $('.categoryHeaderDiv').fadeIn() $('.categoryHeaderDiv img').attr({ 'src': pagesList[moveToIndex].header_bg, 'alt': pagesList[moveToIndex].name }); $('.categoryHeaderDiv').removeClass('categoryHeaderDivOut'); } $('#container').show(1000); } else { //show the elements - FOR IE9: setTimeout(" $('.ingredientsDiv, .directionsDiv, .imgDiv').removeClass('hide');", 1000); //////////////////////////// hideElelnent(); $('#container').fadeOut(); setTimeout(function () { setCurrRecipe(pagesList[moveToIndex]); $('.ingredientsDiv, .directionsDiv').each(function () { //alert($(this).css('transition-property')); $(this).removeClass('textOut'); $(this).css('transition-duration', Math.random() / 2 + .5 + 's'); $('.imgDiv').hide(); $('.imgDiv img').load(function () { $('.imgDiv').show(); setTimeout("$('.imgDiv').removeClass('imgOut');", 10); }); $('.imgDiv').css('transition-duration', Math.random() / 2 + .5 + 's'); $('.headerDiv').removeClass('headerOut headerScale'); $('.headerDiv').show(); $('.headerDiv').css('transition-duration', Math.random() / 2 + .5 + 's'); }); }, 1000); } currPageIndex = moveToIndex; setTimeout("isPageInMove = false;", 1000); if (moveToIndex == 0) $('.arrowBack').fadeOut(1000); else if ($('.arrowBack').css('display') == 'none') $('.arrowBack').fadeIn(1000); if (moveToIndex == pagesList.length - 1) $('.arrowNext').fadeOut(1000); else if ($('.arrowNext').css('display') == 'none') $('.arrowNext').fadeIn(1000); } } function findCurrBackgroundIndex(currPage) { var backgroungIndex = 0; if (currPage.type == 'category') { for (var i = 0; i < categoriesList.length; i++) { if (categoriesList[i].id == currPage.id) { backgroungIndex = i; } } } else { for (var i = 0; i < categoriesList.length; i++) { if (categoriesList[i].id == currPage.cat_id) { backgroungIndex = i; } } } return backgroungIndex; } function hideElelnent() { $('.ingredientsDiv, .directionsDiv').each(function () { $(this).addClass('textOut'); $(this).css('transition-duration', Math.random() / 2 + .5 + 's'); }); $('.imgDiv').addClass('imgOut'); $('.imgDiv').css('transition-duration', Math.random() / 2 + .5 + 's'); $('.headerDiv').addClass('headerOut'); $('.categoryHeaderDiv').addClass('categoryHeaderDivOut'); setTimeout(function () { $('.headerDiv').addClass('headerScale'); }, 300); $('.headerDiv').css('transition-duration', Math.random() / 2 + .2 + 's'); } function setCurrRecipe(currRecipe) { $('.ingredientsDiv, .directionsDiv, .imgDiv').css('transition-property', 'none'); $('.headerDiv img').attr({ 'src': currRecipe.header_bg, 'alt': currRecipe.name }); $('.ingredientsDiv_middle p').html(currRecipe.description1); $('.directionsDiv_middle p').html(currRecipe.description2); // $('.printer').attr('href', '/pdf/' + currRecipe.pdf); //$('.printer').attr('href', '#'); $('.printer').unbind('click'); $('.printer').click(function () { //alert('aa'); //window.open(currRecipe.pdf, '_system', 'location=yes'); //window.open('http://docs.google.com/viewer?url=' + currRecipe.pdf, '_blank', 'location=no'); //alert('bb'); //alert(currRecipe.pdf); //window.plugins.childBrowser.showWebPage(currRecipe.pdf, { showLocationBar: false }); window.open(encodeURI(currRecipe.pdf), '_system', 'location=no'); }); if (currRecipe.image == null || currRecipe.image == "") { $('.imgDiv').hide(0); } else { $('.imgDiv img').attr({ 'src': 'images/RecipesImages/' + currRecipe.image, 'alt': currRecipe.name }); $('.imgDiv').show(0); } //$('.ingredientsDiv').css("height", ""); //$('.directionsDiv').css("height", ""); $('.ingredientsDiv, .directionsDiv, .imgDiv').each(function () { $(this).css("width", ""); $(this).css("height", ""); $(this).find('div').each(function () { $(this).css("width", "") $(this).css("height", "") }); //alert(fontSize * currScale); //$('.ingredientsDiv_middle p, .directionsDiv_middle p').css('font-size', fontSize * currScale + 'px'); }); //alert($('.ingredientsDiv').height()); setElementSize(1); $('.ingredientsDiv, .directionsDiv, .imgDiv').css('transition-property', 'all'); } function setElementSize(currScale) { var ingredientsDivTop = 220 * (1 - ((1 - currScale) / 2)); $('.ingredientsDiv').css({ 'top': ingredientsDivTop + 'px', 'left': '80px' }); //$('.ingredientsDiv_middle').height($('.ingredientsDiv_middle p').outerHeight(true)); //$('.directionsDiv_middle').height($('.directionsDiv_middle p').outerHeight(true)); $('.directionsDiv').css({ 'top': ((ingredientsDivTop + $('.ingredientsDiv').height()) + 50) * currScale + 'px', 'left': '80px' }); $('.imgDiv').css({ 'top': (ingredientsDivTop + 50) * currScale + 'px', 'left': '600px' }); //alert($('.ingredientsDiv_middle p').outerHeight(true)); //alert($('.ingredientsDiv_middle').height()); //setTimeout("setElementSizeInner(" + currScale + ");", 1200); setElementSizeInner(currScale); //alert($('directionsDiv').height()); } function setElementSizeInner(currScale) { var ingredientsDivTop = 220 * (1 - ((1 - currScale) / 2)); var fontSize = 15; var directionsDivButtom = ingredientsDivTop + ($('.ingredientsDiv').height() + 50 + $('.directionsDiv').height()) * currScale; //alert($(window).height() + " " + directionsDivButtom + " " + $('.directionsDiv').height()); var callAgain = false; if (($(window).height() * 0.90) < directionsDivButtom) { currScale *= 0.9; callAgain = true; setElementSizeInner(currScale); } //} else { //$('.ingredientsDiv_middle').height($('.ingredientsDiv_middle p').outerHeight(true)); //$('.directionsDiv_middle').height($('.directionsDiv_middle p').outerHeight(true)); //alert(ingredientsDivTop + " " + ($('.ingredientsDiv').height()) * currScale + " " + $('.directionsDiv').css('top')); //$('.ingredientsDiv, .directionsDiv').css('transition-property', 'transform'); $('.imgDiv').width(500 * currScale); $('.imgFrame').css('background-size', $('.imgDiv').width() + 'px ' + $('.imgDiv').height() + 'px'); $('.ingredientsDiv, .directionsDiv').each(function () { var halfTheScale = 1 - ((1 - currScale) / 2); $(this).width($(this).width() * halfTheScale); $(this).height($(this).height() * currScale); $(this).find('div').each(function () { $(this).width($(this).width() * halfTheScale); //$(this).height($(this).height() * currScale); //alert($(this).width() + " " + $(this).height()); $(this).css('background-size', $(this).width() + 'px ' + $(this).height() + 'px'); }); //$('.imgDiv img').width($(this).width()); $('.ingredientsDiv_middle p, .directionsDiv_middle p').css('font-size', fontSize * currScale + 'px'); }); var originalMarginLeft = 80; var totalMarginLeft; if (600 + $('.imgDiv').width() < $(window).width()) { totalMarginLeft = ($(window).width() - (600 + $('.imgDiv').width())) / 2 + 20; } else { totalMarginLeft = 20; } var imgLeftPosition = (-totalMarginLeft * 2 + $(window).width() - $('.imgDiv').width()); $('.ingredientsDiv').css({ 'top': ingredientsDivTop + 'px', 'left': totalMarginLeft + 'px' }); $('.directionsDiv').css({ 'top': ingredientsDivTop + $('.ingredientsDiv').height() + 70 + 'px', 'left': totalMarginLeft + 'px' }); $('.imgDiv').css({ 'left': totalMarginLeft + imgLeftPosition + 'px' }); //if (callAgain) // setElementSizeInner(currScale); } } function setMenu() { for (var i = 0; i < categoriesList.length; i++) { $('<li><a href="#"><span></span></a></li>').appendTo('.menu_cats'); for (var j = 0; j < recipesList.length; j++) { if (recipesList[j].cat_id == categoriesList[i].id) { $('<li><a href="#"><span></span></a></li>').appendTo('.menu_recipe'); } } } $('.menu_cats > li').each(function () { if (categoriesList[$(this).index()].id != 1) { $(this).find('span').text((categoriesList[$(this).index()].name).toUpperCase()); } if ($(this).find('span').html() == "") { $(this).hide(); } }); $('.menu_cats > li > a').click(function () { var catID; $('.menu_recipe li').remove(); for (var i = 0; i < categoriesList.length; i++) { //alert($(this).find('span').html() +' '+ categoriesList[i].name.toUpperCase()); if ($(this).find('span').html().replace("&amp;", "&") == categoriesList[i].name.toUpperCase()) { catID = categoriesList[i].id; if (catID == 0 || catID == 8) { $('.menu_recipe').slideUp(); } else { $('.menu_recipe').slideDown(); } } } if (catID == 0) { turnPages(0); hideMenu(); } else if (catID == 8) { turnPages(51); hideMenu(); } else { var currCatRecipesList = new Array; var index = 0; for (var j = 0; j < pagesList.length; j++) { if (pagesList[j].type == 'recipe' && pagesList[j].cat_id == catID) { $('<li onclick="turnPages(' + j + ');"><span onclick="hideMenu();">' + pagesList[j].name + '</span></li>').appendTo('.menu_recipe'); currCatRecipesList[index] = pagesList[j]; index++; } } } }); } function toggleMenu() { $('.btnMenu').click(function () { $('.menu_cats').slideToggle(); $('.menu_recipe').slideUp(); }); } function hideMenu() { $('.menu_cats, .menu_recipe').slideUp(); }
Webnology-/cookbook2013VeryLast
www/js/javascript.js
JavaScript
apache-2.0
18,944
/* * Copyright (c) 2021 Citrix Systems, 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 vpn /** * Binding class showing the authenticationsamlpolicy that can be bound to vpnglobal. */ type Vpnglobalauthenticationsamlpolicybinding struct { /** * The name of the policy. */ Policyname string `json:"policyname,omitempty"` /** * Integer specifying the policy's priority. The lower the priority number, the higher the policy's priority. Maximum value for default syntax policies is 2147483647 and for classic policies is 64000. */ Priority int `json:"priority,omitempty"` /** * Bind the authentication policy as the secondary policy to use in a two-factor configuration. A user must then authenticate not only to a primary authentication server but also to a secondary authentication server. User groups are aggregated across both authentication servers. The user name must be exactly the same on both authentication servers, but the authentication servers can require different passwords. */ Secondary bool `json:"secondary,omitempty"` /** * Bind the Authentication policy to a tertiary chain which will be used only for group extraction. The user will not authenticate against this server, and this will only be called it primary and/or secondary authentication has succeeded. */ Groupextraction bool `json:"groupextraction,omitempty"` /** * Applicable only to advance vpn session policy. An expression or other value specifying the priority of the next policy which will get evaluated if the current policy rule evaluates to TRUE. */ Gotopriorityexpression string `json:"gotopriorityexpression,omitempty"` }
citrix/terraform-provider-netscaler
vendor/github.com/citrix/adc-nitro-go/resource/config/vpn/vpnglobal_authenticationsamlpolicy_binding.go
GO
apache-2.0
2,162
/* * Copyright (C) 2012 Andrew Neal 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.spollo.player.menu; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.os.Bundle; import android.support.v4.app.DialogFragment; import com.spollo.player.R; import com.spollo.player.Config; import com.spollo.player.cache.ImageFetcher; import com.spollo.player.utils.ApolloUtils; import com.spollo.player.utils.MusicUtils; /** * Alert dialog used to delete tracks. * <p> * TODO: Remove albums from the recents list upon deletion. * * @author Andrew Neal (andrewdneal@gmail.com) */ public class DeleteDialog extends DialogFragment { public interface DeleteDialogCallback { public void onDelete(long[] id); } /** * The item(s) to delete */ private long[] mItemList; /** * The image cache */ private ImageFetcher mFetcher; /** * Empty constructor as per the {@link Fragment} documentation */ public DeleteDialog() { } /** * @param title The title of the artist, album, or song to delete * @param items The item(s) to delete * @param key The key used to remove items from the cache. * @return A new instance of the dialog */ public static DeleteDialog newInstance(final String title, final long[] items, final String key) { final DeleteDialog frag = new DeleteDialog(); final Bundle args = new Bundle(); args.putString(Config.NAME, title); args.putLongArray("items", items); args.putString("cachekey", key); frag.setArguments(args); return frag; } /** * {@inheritDoc} */ @Override public Dialog onCreateDialog(final Bundle savedInstanceState) { final String delete = getString(R.string.context_menu_delete); final Bundle arguments = getArguments(); // Get the image cache key final String key = arguments.getString("cachekey"); // Get the track(s) to delete mItemList = arguments.getLongArray("items"); // Get the dialog title final String title = arguments.getString(Config.NAME); final String dialogTitle = getString(R.string.delete_dialog_title, title); // Initialize the image cache mFetcher = ApolloUtils.getImageFetcher(getActivity()); // Build the dialog return new AlertDialog.Builder(getActivity()).setTitle(dialogTitle) .setMessage(R.string.cannot_be_undone) .setPositiveButton(delete, new OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { // Remove the items from the image cache mFetcher.removeFromCache(key); // Delete the selected item(s) MusicUtils.deleteTracks(getActivity(), mItemList); if (getActivity() instanceof DeleteDialogCallback) { ((DeleteDialogCallback)getActivity()).onDelete(mItemList); } dialog.dismiss(); } }).setNegativeButton(R.string.cancel, new OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { dialog.dismiss(); } }).create(); } }
i25ffz/spollo
src/com/spollo/player/menu/DeleteDialog.java
Java
apache-2.0
4,090
package com.introproventures.graphql.jpa.query.converter.model; import java.util.Date; import java.util.Objects; import javax.persistence.Column; import javax.persistence.Convert; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.MappedSuperclass; import org.springframework.format.annotation.DateTimeFormat; @MappedSuperclass public abstract class AbstractVariableEntity extends ActivitiEntityMetadata { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String type; private String name; @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) private Date createTime; @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) private Date lastUpdatedTime; private String executionId; @Convert(converter = VariableValueJsonConverter.class) @Column(columnDefinition="text") private VariableValue<?> value; private Boolean markedAsDeleted = false; private String processInstanceId; public AbstractVariableEntity() { } public AbstractVariableEntity(Long id, String type, String name, String processInstanceId, String serviceName, String serviceFullName, String serviceVersion, String appName, String appVersion, Date createTime, Date lastUpdatedTime, String executionId) { super(serviceName, serviceFullName, serviceVersion, appName, appVersion); this.id = id; this.type = type; this.name = name; this.processInstanceId = processInstanceId; this.createTime = createTime; this.lastUpdatedTime = lastUpdatedTime; this.executionId = executionId; } public Long getId() { return id; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getLastUpdatedTime() { return lastUpdatedTime; } public void setLastUpdatedTime(Date lastUpdatedTime) { this.lastUpdatedTime = lastUpdatedTime; } public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } public <T> void setValue(T value) { this.value = new VariableValue<>(value); } public <T> T getValue() { return (T) value.getValue(); } public Boolean getMarkedAsDeleted() { return markedAsDeleted; } public void setMarkedAsDeleted(Boolean markedAsDeleted) { this.markedAsDeleted = markedAsDeleted; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + Objects.hash(id); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; AbstractVariableEntity other = (AbstractVariableEntity) obj; return Objects.equals(id, other.id); } }
introproventures/graphql-jpa-query
graphql-jpa-query-schema/src/test/java/com/introproventures/graphql/jpa/query/converter/model/AbstractVariableEntity.java
Java
apache-2.0
4,011
""" Copyright 2017 Deepgram 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. """ def modify_kurfile(data): for k in ('train', 'validate', 'test', 'evaluate'): if k not in data: continue if 'weights' in data[k]: del data[k]['weights'] if 'provider' not in data[k]: data[k]['provider'] = {} data[k]['provider']['num_batches'] = 1 data[k]['provider']['batch_size'] = 2 if 'train' in data: if 'checkpoint' in data['train']: del data['train']['checkpoint'] if 'stop_when' not in data['train']: data['train']['stop_when'] = {} data['train']['stop_when']['epochs'] = 2 if 'epochs' in data['train']: del data['train']['epochs'] if 'log' in data['train']: del data['train']['log'] if 'evaluate' in data: if 'destination' in data['evaluate']: del data['evaluate']['destination'] ### EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF
deepgram/kur
tests/examples/modkurfile.py
Python
apache-2.0
1,380
#region Copyright /*Copyright (C) 2015 Konstantin Udilovich 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. */ #endregion using System; using System.Collections.Generic; using System.Windows.Controls; using Dynamo.Controls; using Dynamo.Models; using Dynamo.Wpf; using ProtoCore.AST.AssociativeAST; using Kodestruct.Common.CalculationLogger; using Kodestruct.Dynamo.Common; using Dynamo.Nodes; using Dynamo.Graph.Nodes; using System.Xml; using Dynamo.Graph; namespace Kodestruct.Loads.ASCE7.Lateral.Wind.PressureCoefficient { /// <summary> ///Selection of the type of face relative to wind direction (windward, leeward or side) /// </summary> [NodeName("Wind face")] [NodeCategory("Kodestruct.Loads.ASCE7.Lateral.Wind.PressureCoefficient")] [NodeDescription("Selection of the type of face relative to wind direction (windward, leeward or side) ")] [IsDesignScriptCompatible] public class WindFaceSelection : UiNodeBase { public WindFaceSelection() { //OutPortData.Add(new PortData("ReportEntry", "Calculation log entries (for reporting)")); OutPortData.Add(new PortData("WindFaceType", "Type of face relative to wind direction (windward, leeward or side) ")); RegisterAllPorts(); SetDefaultParameters(); //PropertyChanged += NodePropertyChanged; } private void SetDefaultParameters() { //ReportEntry=""; WindFaceType = "Windward"; } /// <summary> /// Gets the type of this class, to be used in base class for reflection /// </summary> protected override Type GetModelType() { return GetType(); } #region Properties #region InputProperties #endregion #region OutputProperties #region WindFaceTypeProperty /// <summary> /// WindFaceType property /// </summary> /// <value>Type of face relative to wind direction (windward, leeward or side) </value> public string _WindFaceType; public string WindFaceType { get { return _WindFaceType; } set { _WindFaceType = value; RaisePropertyChanged("WindFaceType"); OnNodeModified(); } } #endregion #region ReportEntryProperty ///// <summary> ///// log property ///// </summary> ///// <value>Calculation entries that can be converted into a report.</value> //public string reportEntry; //public string ReportEntry //{ // get { return reportEntry; } // set // { // reportEntry = value; // RaisePropertyChanged("ReportEntry"); // OnNodeModified(); // } //} #endregion #endregion #endregion #region Serialization /// <summary> ///Saves property values to be retained when opening the node /// </summary> protected override void SerializeCore(XmlElement nodeElement, SaveContext context) { base.SerializeCore(nodeElement, context); nodeElement.SetAttribute("WindFaceType", WindFaceType); } /// <summary> ///Retrieved property values when opening the node /// </summary> protected override void DeserializeCore(XmlElement nodeElement, SaveContext context) { base.DeserializeCore(nodeElement, context); var attrib = nodeElement.Attributes["WindFaceType"]; if (attrib == null) return; WindFaceType = attrib.Value; //SetComponentDescription(); } #endregion /// <summary> ///Customization of WPF view in Dynamo UI /// </summary> public class WindFaceViewCustomization : UiNodeBaseViewCustomization, INodeViewCustomization<WindFaceSelection> { public void CustomizeView(WindFaceSelection model, NodeView nodeView) { base.CustomizeView(model, nodeView); WindFaceView control = new WindFaceView(); control.DataContext = model; nodeView.inputGrid.Children.Add(control); base.CustomizeView(model, nodeView); } } } }
Kodestruct/Kodestruct.Dynamo
Kodestruct.Dynamo.UI/Nodes/Loads/ASCE7/Lateral/Wind/WindFace.cs
C#
apache-2.0
4,968
export { default } from 'ember-table-filterable/components/table-filterable';
clairton/ember-table-filterable
app/components/table-filterable.js
JavaScript
apache-2.0
77
package org.hitzoft.xml; /** * * @author jesus.espinoza */ public enum SignatureMethodAlgorithm { DSA_SHA1("http://www.w3.org/2000/09/xmldsig#dsa-sha1"), DSA_SHA256("http://www.w3.org/2009/xmldsig11#dsa-sha256"), RSA_SHA1("http://www.w3.org/2000/09/xmldsig#rsa-sha1"), RSA_SHA256("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"), RSA_SHA512("http://www.w3.org/2001/04/xmldsig-more#rsa-sha512"); // // ECDSA_SHA1("http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1"), // ECDSA_SHA256("http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256"), // ECDSA_SHA512("http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512"), // // HMAC_SHA1("http://www.w3.org/2000/09/xmldsig#hmac-sha1"); private final String URI; private SignatureMethodAlgorithm(String URI) { this.URI = URI; } @Override public String toString() { return URI; } }
Chuy288/simple-xml-signer
src/main/java/org/hitzoft/xml/SignatureMethodAlgorithm.java
Java
apache-2.0
945
import endsWith from 'lodash/endsWith'; import startsWith from 'lodash/startsWith'; import trim from 'lodash/trim'; const VALID_SLUG_PATTERN = /^([a-z0-9]-?)*[a-z0-9]$/; const VALID_DATED_SLUG_PATTERN = /^([a-z0-9-]|[a-z0-9-][a-z0-9-/]*[a-z0-9-])$/; /** * Returns true if the provided value is a slug. * * @param {string} slug * @param {boolean} [allowSlashes] * * @returns {boolean} */ export default function isValidSlug(slug, allowSlashes = false) { if (!trim(slug)) { return false; } if (startsWith(slug, '-') || startsWith(slug, '/')) { return false; } if (endsWith(slug, '-') || endsWith(slug, '/')) { return false; } const regex = allowSlashes ? VALID_DATED_SLUG_PATTERN : VALID_SLUG_PATTERN; return regex.test(slug); }
gdbots/common-js
src/isValidSlug.js
JavaScript
apache-2.0
767
package main import ( "fmt" "reflect" ) var ( Int reflect.Type = reflect.TypeOf(0) String reflect.Type = reflect.TypeOf("") ) // 可从基本类型获取所对应复合类型。 func main() { var c reflect.Type c = reflect.ChanOf(reflect.SendDir, String) fmt.Println(c) m := reflect.MapOf(String, Int) fmt.Println(m) s := reflect.SliceOf(Int) fmt.Println(s) t := struct{ Name string }{} p := reflect.PtrTo(reflect.TypeOf(t)) fmt.Println(p) //与之对应,⽅法 Elem 可返回复合类型的基类型。 var t1 reflect.Type t1 = reflect.TypeOf(make(chan int)).Elem() fmt.Println(t1) }
Anteoy/gtools
test/base/note/reflect/type/base-recombination/main.go
GO
apache-2.0
611
using System.ComponentModel; #pragma warning disable 0067 namespace OQF.CommonUiElements.Info.Pages.PageViewModels.TournamentInfoPage { internal class TournamentInfoPageViewModelSampleData : ITournamentInfoPageViewModel { public event PropertyChangedEventHandler PropertyChanged; public void Dispose() { } public string DisplayName => "Turnier"; } }
bytePassion/OpenQuoridorFramework
OpenQuoridorFramework/OQF.CommonUiElements/Info/Pages/PageViewModels/TournamentInfoPage/TournamentInfoPageViewModelSampleData.cs
C#
apache-2.0
366
// Copyright Eagle Legacy Modernization, 2010-date // Original author: Steven A. O'Hara, Dec 17, 2010 package com.eagle.programmar.Java.Terminals; import com.eagle.tokens.TerminalPunctuationToken; public class Java_Punctuation extends TerminalPunctuationToken { // Need default constructor for reading from the XML file public Java_Punctuation() { this('\0'); } public Java_Punctuation(char punct) { super(punct); } public Java_Punctuation(String punct) { super(punct); } }
oharasteve/eagle
src/com/eagle/programmar/Java/Terminals/Java_Punctuation.java
Java
apache-2.0
495
package com.example.cmmdyweather.gson; import com.google.gson.annotations.SerializedName; /** * Created by 夏夜晚凤 on 2017/2/14. */ public class Basic { @SerializedName("city") public String cityName; @SerializedName("id") public String weatherId; public Update update; public class Update{ @SerializedName("loc") public String updateTime; } }
cmmdy/cmmdyweather
app/src/main/java/com/example/cmmdyweather/gson/Basic.java
Java
apache-2.0
402
// Copyright © Microsoft Open Technologies, 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 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION // ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A // PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache License, Version 2.0 for the specific language // governing permissions and limitations under the License. package com.microsoft.aad.adal; /** * Cancellation error. */ public class AuthenticationCancelError extends AuthenticationException { static final long serialVersionUID = 1; /** * Constructs a new AuthenticationCancelError. */ public AuthenticationCancelError() { super(); } /** * Constructs a new AuthenticationCancelError with message. * * @param msg Message for cancel request */ public AuthenticationCancelError(String msg) { super(ADALError.AUTH_FAILED_CANCELLED, msg); } }
w9jds/azure-activedirectory-library-for-android
src/src/com/microsoft/aad/adal/AuthenticationCancelError.java
Java
apache-2.0
1,266
/* * Copyright 2017 MovingBlocks * * 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 org.destinationsol.game.input; import com.badlogic.gdx.math.Vector2; import org.destinationsol.Const; import org.destinationsol.common.SolMath; import org.destinationsol.game.SolGame; import org.destinationsol.game.planet.Planet; public class BigObjAvoider { public static final float MAX_DIST_LEN = 2 * (Const.MAX_GROUND_HEIGHT + Const.ATM_HEIGHT); private Vector2 myProj; public BigObjAvoider() { myProj = new Vector2(); } public float avoid(SolGame game, Vector2 from, Vector2 dest, float toDestAngle) { float toDestLen = from.dst(dest); if (toDestLen > MAX_DIST_LEN) { toDestLen = MAX_DIST_LEN; } float res = toDestAngle; Planet p = game.getPlanetMan().getNearestPlanet(from); Vector2 pPos = p.getPos(); float pRad = p.getFullHeight(); if (dest.dst(pPos) < pRad) { pRad = p.getGroundHeight(); } myProj.set(pPos); myProj.sub(from); SolMath.rotate(myProj, -toDestAngle); if (0 < myProj.x && myProj.x < toDestLen) { if (SolMath.abs(myProj.y) < pRad) { toDestLen = myProj.x; res = toDestAngle + 45 * SolMath.toInt(myProj.y < 0); } } Vector2 sunPos = p.getSys().getPos(); float sunRad = Const.SUN_RADIUS; myProj.set(sunPos); myProj.sub(from); SolMath.rotate(myProj, -toDestAngle); if (0 < myProj.x && myProj.x < toDestLen) { if (SolMath.abs(myProj.y) < sunRad) { res = toDestAngle + 45 * SolMath.toInt(myProj.y < 0); } } return res; } }
Sigma-One/DestinationSol
engine/src/main/java/org/destinationsol/game/input/BigObjAvoider.java
Java
apache-2.0
2,268
package com.hsj.egameserver.server; public class Crypt { private static Crypt _instance = null; private synchronized static void createInstance() { if (_instance == null) { _instance = new Crypt(); } } public static Crypt getInstance() { if (_instance == null) { createInstance(); } return _instance; } public Crypt() { } public char[] C2Sdecrypt(byte encdata[]) { char decdata[] = new char[encdata.length]; for (int i = 0; i < encdata.length; i++) { decdata[i] = (char) ((char) (encdata[i] - 15) % 256); } return decdata; } public byte[] S2Cencrypt(char decdata[]) { byte encdata[] = new byte[decdata.length]; for (int i = 0; i < decdata.length; i++) { encdata[i] = (byte) ((decdata[i] ^ 0xc3) + 0x0f); } return encdata; } }
woshihuo12/evilbonefun
egameserver/src/main/java/com/hsj/egameserver/server/Crypt.java
Java
apache-2.0
931
package info.izumin.android.bletia.core.action; import info.izumin.android.bletia.core.BleState; import info.izumin.android.bletia.core.BletiaException; import info.izumin.android.bletia.core.ResolveStrategy; import info.izumin.android.bletia.core.StateContainer; import info.izumin.android.bletia.core.wrapper.BluetoothGattWrapper; /** * Created by izumin on 11/14/15. */ public abstract class AbstractDisconnectAction<R> extends AbstractAction<Void, BletiaException, Void, R> { public static final String TAG = AbstractDisconnectAction.class.getSimpleName(); private final StateContainer mContainer; public AbstractDisconnectAction(ResolveStrategy<Void, BletiaException, R> resolveStrategy, StateContainer container) { super(null, Type.DISCONNECT, resolveStrategy); mContainer = container; } @Override public boolean execute(BluetoothGattWrapper gattWrapper) { mContainer.setState(BleState.DISCONNECTING); gattWrapper.disconnect(); return true; } }
izumin5210/Bletia
bletia-core/src/main/java/info/izumin/android/bletia/core/action/AbstractDisconnectAction.java
Java
apache-2.0
1,026
package com.labo.kaji.relativepopupwindow; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.support.annotation.IntDef; import android.support.annotation.NonNull; import android.support.v4.widget.PopupWindowCompat; import android.util.AttributeSet; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.PopupWindow; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * @author kakajika * @since 2016/07/01 */ public class RelativePopupWindow extends PopupWindow { @IntDef({ VerticalPosition.CENTER, VerticalPosition.ABOVE, VerticalPosition.BELOW, VerticalPosition.ALIGN_TOP, VerticalPosition.ALIGN_BOTTOM, }) @Retention(RetentionPolicy.SOURCE) public @interface VerticalPosition { int CENTER = 0; int ABOVE = 1; int BELOW = 2; int ALIGN_TOP = 3; int ALIGN_BOTTOM = 4; } @IntDef({ HorizontalPosition.CENTER, HorizontalPosition.LEFT, HorizontalPosition.RIGHT, HorizontalPosition.ALIGN_LEFT, HorizontalPosition.ALIGN_RIGHT, }) @Retention(RetentionPolicy.SOURCE) public @interface HorizontalPosition { int CENTER = 0; int LEFT = 1; int RIGHT = 2; int ALIGN_LEFT = 3; int ALIGN_RIGHT = 4; } public RelativePopupWindow(Context context) { super(context); } public RelativePopupWindow(Context context, AttributeSet attrs) { super(context, attrs); } public RelativePopupWindow(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) public RelativePopupWindow(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } public RelativePopupWindow() { super(); } public RelativePopupWindow(View contentView) { super(contentView); } public RelativePopupWindow(int width, int height) { super(width, height); } public RelativePopupWindow(View contentView, int width, int height) { super(contentView, width, height); } public RelativePopupWindow(View contentView, int width, int height, boolean focusable) { super(contentView, width, height, focusable); } /** * Show at relative position to anchor View. * @param anchor Anchor View * @param vertPos Vertical Position Flag * @param horizPos Horizontal Position Flag */ public void showOnAnchor(@NonNull View anchor, @VerticalPosition int vertPos, @HorizontalPosition int horizPos) { showOnAnchor(anchor, vertPos, horizPos, 0, 0); } /** * Show at relative position to anchor View. * @param anchor Anchor View * @param vertPos Vertical Position Flag * @param horizPos Horizontal Position Flag * @param fitInScreen Automatically fit in screen or not */ public void showOnAnchor(@NonNull View anchor, @VerticalPosition int vertPos, @HorizontalPosition int horizPos, boolean fitInScreen) { showOnAnchor(anchor, vertPos, horizPos, 0, 0, fitInScreen); } /** * Show at relative position to anchor View with translation. * @param anchor Anchor View * @param vertPos Vertical Position Flag * @param horizPos Horizontal Position Flag * @param x Translation X * @param y Translation Y */ public void showOnAnchor(@NonNull View anchor, @VerticalPosition int vertPos, @HorizontalPosition int horizPos, int x, int y) { showOnAnchor(anchor, vertPos, horizPos, x, y, true); } /** * Show at relative position to anchor View with translation. * @param anchor Anchor View * @param vertPos Vertical Position Flag * @param horizPos Horizontal Position Flag * @param x Translation X * @param y Translation Y * @param fitInScreen Automatically fit in screen or not */ public void showOnAnchor(@NonNull View anchor, @VerticalPosition int vertPos, @HorizontalPosition int horizPos, int x, int y, boolean fitInScreen) { setClippingEnabled(fitInScreen); View contentView = getContentView(); contentView.measure(makeDropDownMeasureSpec(getWidth()), makeDropDownMeasureSpec(getHeight())); final int measuredW = contentView.getMeasuredWidth(); final int measuredH = contentView.getMeasuredHeight(); if (!fitInScreen) { final int[] anchorLocation = new int[2]; anchor.getLocationInWindow(anchorLocation); x += anchorLocation[0]; y += anchorLocation[1] + anchor.getHeight(); } switch (vertPos) { case VerticalPosition.ABOVE: y -= measuredH + anchor.getHeight(); break; case VerticalPosition.ALIGN_BOTTOM: y -= measuredH; break; case VerticalPosition.CENTER: y -= anchor.getHeight()/2 + measuredH/2; break; case VerticalPosition.ALIGN_TOP: y -= anchor.getHeight(); break; case VerticalPosition.BELOW: // Default position. break; } switch (horizPos) { case HorizontalPosition.LEFT: x -= measuredW; break; case HorizontalPosition.ALIGN_RIGHT: x -= measuredW - anchor.getWidth(); break; case HorizontalPosition.CENTER: x += anchor.getWidth()/2 - measuredW/2; break; case HorizontalPosition.ALIGN_LEFT: // Default position. break; case HorizontalPosition.RIGHT: x += anchor.getWidth(); break; } if (fitInScreen) { PopupWindowCompat.showAsDropDown(this, anchor, x, y, Gravity.NO_GRAVITY); } else { showAtLocation(anchor, Gravity.NO_GRAVITY, x, y); } } @SuppressWarnings("ResourceType") private static int makeDropDownMeasureSpec(int measureSpec) { return View.MeasureSpec.makeMeasureSpec(View.MeasureSpec.getSize(measureSpec), getDropDownMeasureSpecMode(measureSpec)); } private static int getDropDownMeasureSpecMode(int measureSpec) { switch (measureSpec) { case ViewGroup.LayoutParams.WRAP_CONTENT: return View.MeasureSpec.UNSPECIFIED; default: return View.MeasureSpec.EXACTLY; } } }
weiwenqiang/GitHub
Dialog/PopupWindow/RelativePopupWindow-master/relativepopupwindow/src/main/java/com/labo/kaji/relativepopupwindow/RelativePopupWindow.java
Java
apache-2.0
6,819
/* * Copyright 2015 NEC Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.o3project.odenos.core.component.network.topology; import static org.msgpack.template.Templates.tMap; import static org.msgpack.template.Templates.TString; import org.apache.commons.lang.builder.ToStringBuilder; import org.msgpack.packer.Packer; import org.msgpack.type.ValueType; import org.msgpack.unpacker.Unpacker; import org.o3project.odenos.remoteobject.message.BaseObject; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * Switch Port data class. * */ public class Port extends BaseObject implements Cloneable { private static final int MSG_NUM_MIN = 1; private static final int MSG_NUM_MAX = 7; private String type = "Port"; private String portId; private String nodeId; private String outLink; private String inLink; /** * Constructor. */ public Port() { } /** * Constructor. * @param portId port id that is unique in the Node. */ public Port(String portId) { this.portId = portId; } /** * Constructor. * @param portId port id that is unique in the Node. * @param nodeId Port belongs to this node id. */ public Port(String portId, String nodeId) { this(portId); this.nodeId = nodeId; } /** * Constructor. * @param version number of version. * @param portId port id that is unique in the Node. * @param nodeId Port belongs to this node id. */ public Port(String version, String portId, String nodeId) { this(portId, nodeId); this.setVersion(version); } /** * Constructor. * @param version string of version. * @param portId port id that is unique in the Node. * @param nodeId Port belongs to this node id. * @param outLink output link id. * @param inLink input link id. * @param attributes map of attributes. */ public Port(String version, String portId, String nodeId, String outLink, String inLink, Map<String, String> attributes) { this(version, portId, nodeId); this.outLink = outLink; this.inLink = inLink; this.putAttributes(attributes); } /** * Constructor. * @param msg port message. */ public Port(Port msg) { this(msg.getVersion(), msg.getId(), msg.getNode(), msg.getOutLink(), msg.getInLink(), new HashMap<String, String>( msg.getAttributes())); } /** * Confirm the parameter. * @return true if parameter is valid. */ public boolean validate() { if (this.nodeId == null || this.portId == null || this.type == null) { return false; } return true; } /** * Returns a type of port. * @return type of port. */ public String getType() { return type; } /** * Returns a port ID. * @return port ID. */ public String getId() { return portId; } /** * Sets a port ID. * @param portId port ID. */ public void setId(String portId) { this.portId = portId; } /** * Returns a node ID. * @return node ID. */ public String getNode() { return nodeId; } /** * Sets a node ID. * @param nodeId node ID. */ public void setNode(String nodeId) { this.nodeId = nodeId; } /** * Returns a output link ID. * @return output link ID. */ public String getOutLink() { return outLink; } /** * Sets a output link ID. * @param linkId output link ID. */ public void setOutLink(String linkId) { outLink = linkId; } /** * Returns a input link ID. * @return input link ID. */ public String getInLink() { return inLink; } /** * Sets a input link ID. * @param linkId input link ID. */ public void setInLink(String linkId) { inLink = linkId; } @Override public void readFrom(Unpacker upk) throws IOException { int size = upk.readMapBegin(); if (size < MSG_NUM_MIN || MSG_NUM_MAX < size) { throw new IOException(); } while (size-- > 0) { switch (upk.readString()) { case "type": type = upk.readString(); break; case "version": if (upk.getNextType() == ValueType.NIL) { upk.readNil(); setVersion("0"); } else { setVersion(upk.readString()); } break; case "port_id": if (upk.getNextType() == ValueType.NIL) { upk.readNil(); portId = null; } else { portId = upk.readString(); } break; case "node_id": if (upk.getNextType() == ValueType.NIL) { upk.readNil(); nodeId = null; } else { nodeId = upk.readString(); } break; case "out_link": if (upk.getNextType() == ValueType.NIL) { upk.readNil(); outLink = null; } else { outLink = upk.readString(); } break; case "in_link": if (upk.getNextType() == ValueType.NIL) { upk.readNil(); inLink = null; } else { inLink = upk.readString(); } break; case "attributes": putAttributes(upk.read(tMap(TString, TString))); break; default: break; } } upk.readMapEnd(); } @Override public void writeTo(Packer pk) throws IOException { pk.writeMapBegin(MSG_NUM_MAX); pk.write("type"); pk.write(type); pk.write("version"); pk.write(getVersion()); pk.write("port_id"); pk.write(portId); pk.write("node_id"); pk.write(nodeId); pk.write("out_link"); if (outLink != null) { pk.write(outLink); } else { pk.writeNil(); } pk.write("in_link"); if (inLink != null) { pk.write(inLink); } else { pk.writeNil(); } pk.write("attributes"); pk.write(getAttributes()); pk.writeMapEnd(); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (!(obj instanceof Port)) { return false; } Port portMessage = (Port) obj; try { if (portMessage.getType().equals(this.type) && portMessage.getVersion().equals(this.getVersion()) && portMessage.getId().equals(this.portId) && portMessage.getNode().equals(this.nodeId) && String.format("%s", portMessage.getOutLink()).equals( String.format("%s", this.outLink)) && String.format("%s", portMessage.getInLink()).equals( String.format("%s", this.inLink)) && portMessage.getAttributes().equals(this.getAttributes())) { return true; } } catch (NullPointerException e) { //e.printStackTrace(); } return false; } @Override public Port clone() { return new Port(this); } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { ToStringBuilder sb = new ToStringBuilder(this); sb.append("version", getVersion()); sb.append("portId", portId); sb.append("nodeId", nodeId); sb.append("outLink", outLink); sb.append("inLink", inLink); sb.append("attributes", getAttributes()); return sb.toString(); } }
y-higuchi/odenos
src/main/java/org/o3project/odenos/core/component/network/topology/Port.java
Java
apache-2.0
7,900
// Copyright 2019 Google LLC // // 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. using Google.Api.Ads.Common.Util; using Google.Api.Ads.AdManager.Lib; using Google.Api.Ads.AdManager.v202111; using System; namespace Google.Api.Ads.AdManager.Examples.CSharp.v202111 { /// <summary> /// This code example creates a custom creative for a given advertiser. To /// determine which companies are advertisers, run GetCompaniesByStatement.cs. /// To determine which creatives already exist, run GetAllCreatives.cs. /// </summary> public class CreateCustomCreative : SampleBase { /// <summary> /// Returns a description about the code example. /// </summary> public override string Description { get { return "This code example creates a custom creative for a given advertiser. " + "To determine which companies are advertisers, " + "run GetCompaniesByStatement.cs. To determine which creatives already exist, " + "run GetAllCreatives.cs."; } } /// <summary> /// Main method, to run this code example as a standalone application. /// </summary> public static void Main() { CreateCustomCreative codeExample = new CreateCustomCreative(); Console.WriteLine(codeExample.Description); codeExample.Run(new AdManagerUser()); } /// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user) { using (CreativeService creativeService = user.GetService<CreativeService>()) { // Set the ID of the advertiser (company) that all creatives will be // assigned to. long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE")); // Create the local custom creative object. CustomCreative customCreative = new CustomCreative(); customCreative.name = "Custom creative " + GetTimeStamp(); customCreative.advertiserId = advertiserId; customCreative.destinationUrl = "http://google.com"; // Set the custom creative image asset. CustomCreativeAsset customCreativeAsset = new CustomCreativeAsset(); customCreativeAsset.macroName = "IMAGE_ASSET"; CreativeAsset asset = new CreativeAsset(); asset.fileName = string.Format("inline{0}.jpg", GetTimeStamp()); asset.assetByteArray = MediaUtilities.GetAssetDataFromUrl("https://goo.gl/3b9Wfh", user.Config); customCreativeAsset.asset = asset; customCreative.customCreativeAssets = new CustomCreativeAsset[] { customCreativeAsset }; // Set the HTML snippet using the custom creative asset macro. customCreative.htmlSnippet = "<a href='%%CLICK_URL_UNESC%%%%DEST_URL%%'>" + "<img src='%%FILE:" + customCreativeAsset.macroName + "%%'/>" + "</a><br>Click above for great deals!"; // Set the creative size. Size size = new Size(); size.width = 300; size.height = 250; size.isAspectRatio = false; customCreative.size = size; try { // Create the custom creative on the server. Creative[] createdCreatives = creativeService.createCreatives(new Creative[] { customCreative }); foreach (Creative createdCreative in createdCreatives) { Console.WriteLine( "A custom creative with ID \"{0}\", name \"{1}\", and size ({2}, " + "{3}) was created and can be previewed at {4}", createdCreative.id, createdCreative.name, createdCreative.size.width, createdCreative.size.height, createdCreative.previewUrl); } } catch (Exception e) { Console.WriteLine("Failed to create custom creatives. Exception says \"{0}\"", e.Message); } } } } }
googleads/googleads-dotnet-lib
examples/AdManager/CSharp/v202111/CreativeService/CreateCustomCreative.cs
C#
apache-2.0
5,069
<?php namespace Atompulse\Bundle\FusionBundle\Assets\Refiner; /** * Class SimpleRefiner * @package Atompulse\Bundle\FusionBundle\Compiler\Refiner * * @author Petru Cojocar <petru.cojocar@gmail.com> */ class SimpleRefiner implements RefinerInterface { /** * Very basic content optimizer * @param string $content * @return mixed|string */ public static function refine($content) { // remove comments $content = preg_replace('$\/\*[\s\S]*?\*\/$', '', $content); //$content = preg_replace('/[ \t]*(?:\/\*(?:.(?!(?<=\*)\/))*\*\/|\/\/[^\n\r]*\n?\r?)/', '', $content); $content = preg_replace('$(?<=\s|\w)[\/]{2,}.*$', '', $content); // remove tabs, spaces, newlines, etc. $content = str_replace(["\r\n", "\r", "\n", "\t", ' ', ' ', ' '], '', $content); // remove special language constructs $content = str_replace([" : ",": ",', ',' (', ' = ',' || ',' ? ',') {'], [':', ':',',','(','=','||','?','){'], $content); return $content; } }
atompulse/atompulse
src/Atompulse/Bundle/FusionBundle/Assets/Refiner/SimpleRefiner.php
PHP
apache-2.0
1,051
/** * Copyright 2014 Shape Security, 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. */ import { getHexValue, isLineTerminator, isWhiteSpace, isIdentifierStart, isIdentifierPart, isDecimalDigit } from './utils'; import { ErrorMessages } from './errors'; export const TokenClass = { Eof: { name: '<End>' }, Ident: { name: 'Identifier', isIdentifierName: true }, Keyword: { name: 'Keyword', isIdentifierName: true }, NumericLiteral: { name: 'Numeric' }, TemplateElement: { name: 'Template' }, Punctuator: { name: 'Punctuator' }, StringLiteral: { name: 'String' }, RegularExpression: { name: 'RegularExpression' }, Illegal: { name: 'Illegal' }, }; export const TokenType = { EOS: { klass: TokenClass.Eof, name: 'EOS' }, LPAREN: { klass: TokenClass.Punctuator, name: '(' }, RPAREN: { klass: TokenClass.Punctuator, name: ')' }, LBRACK: { klass: TokenClass.Punctuator, name: '[' }, RBRACK: { klass: TokenClass.Punctuator, name: ']' }, LBRACE: { klass: TokenClass.Punctuator, name: '{' }, RBRACE: { klass: TokenClass.Punctuator, name: '}' }, COLON: { klass: TokenClass.Punctuator, name: ':' }, SEMICOLON: { klass: TokenClass.Punctuator, name: ';' }, PERIOD: { klass: TokenClass.Punctuator, name: '.' }, ELLIPSIS: { klass: TokenClass.Punctuator, name: '...' }, ARROW: { klass: TokenClass.Punctuator, name: '=>' }, CONDITIONAL: { klass: TokenClass.Punctuator, name: '?' }, INC: { klass: TokenClass.Punctuator, name: '++' }, DEC: { klass: TokenClass.Punctuator, name: '--' }, ASSIGN: { klass: TokenClass.Punctuator, name: '=' }, ASSIGN_BIT_OR: { klass: TokenClass.Punctuator, name: '|=' }, ASSIGN_BIT_XOR: { klass: TokenClass.Punctuator, name: '^=' }, ASSIGN_BIT_AND: { klass: TokenClass.Punctuator, name: '&=' }, ASSIGN_SHL: { klass: TokenClass.Punctuator, name: '<<=' }, ASSIGN_SHR: { klass: TokenClass.Punctuator, name: '>>=' }, ASSIGN_SHR_UNSIGNED: { klass: TokenClass.Punctuator, name: '>>>=' }, ASSIGN_ADD: { klass: TokenClass.Punctuator, name: '+=' }, ASSIGN_SUB: { klass: TokenClass.Punctuator, name: '-=' }, ASSIGN_MUL: { klass: TokenClass.Punctuator, name: '*=' }, ASSIGN_DIV: { klass: TokenClass.Punctuator, name: '/=' }, ASSIGN_MOD: { klass: TokenClass.Punctuator, name: '%=' }, ASSIGN_EXP: { klass: TokenClass.Punctuator, name: '**=' }, COMMA: { klass: TokenClass.Punctuator, name: ',' }, OR: { klass: TokenClass.Punctuator, name: '||' }, AND: { klass: TokenClass.Punctuator, name: '&&' }, BIT_OR: { klass: TokenClass.Punctuator, name: '|' }, BIT_XOR: { klass: TokenClass.Punctuator, name: '^' }, BIT_AND: { klass: TokenClass.Punctuator, name: '&' }, SHL: { klass: TokenClass.Punctuator, name: '<<' }, SHR: { klass: TokenClass.Punctuator, name: '>>' }, SHR_UNSIGNED: { klass: TokenClass.Punctuator, name: '>>>' }, ADD: { klass: TokenClass.Punctuator, name: '+' }, SUB: { klass: TokenClass.Punctuator, name: '-' }, MUL: { klass: TokenClass.Punctuator, name: '*' }, DIV: { klass: TokenClass.Punctuator, name: '/' }, MOD: { klass: TokenClass.Punctuator, name: '%' }, EXP: { klass: TokenClass.Punctuator, name: '**' }, EQ: { klass: TokenClass.Punctuator, name: '==' }, NE: { klass: TokenClass.Punctuator, name: '!=' }, EQ_STRICT: { klass: TokenClass.Punctuator, name: '===' }, NE_STRICT: { klass: TokenClass.Punctuator, name: '!==' }, LT: { klass: TokenClass.Punctuator, name: '<' }, GT: { klass: TokenClass.Punctuator, name: '>' }, LTE: { klass: TokenClass.Punctuator, name: '<=' }, GTE: { klass: TokenClass.Punctuator, name: '>=' }, INSTANCEOF: { klass: TokenClass.Keyword, name: 'instanceof' }, IN: { klass: TokenClass.Keyword, name: 'in' }, NOT: { klass: TokenClass.Punctuator, name: '!' }, BIT_NOT: { klass: TokenClass.Punctuator, name: '~' }, ASYNC: { klass: TokenClass.Keyword, name: 'async' }, AWAIT: { klass: TokenClass.Keyword, name: 'await' }, ENUM: { klass: TokenClass.Keyword, name: 'enum' }, DELETE: { klass: TokenClass.Keyword, name: 'delete' }, TYPEOF: { klass: TokenClass.Keyword, name: 'typeof' }, VOID: { klass: TokenClass.Keyword, name: 'void' }, BREAK: { klass: TokenClass.Keyword, name: 'break' }, CASE: { klass: TokenClass.Keyword, name: 'case' }, CATCH: { klass: TokenClass.Keyword, name: 'catch' }, CLASS: { klass: TokenClass.Keyword, name: 'class' }, CONTINUE: { klass: TokenClass.Keyword, name: 'continue' }, DEBUGGER: { klass: TokenClass.Keyword, name: 'debugger' }, DEFAULT: { klass: TokenClass.Keyword, name: 'default' }, DO: { klass: TokenClass.Keyword, name: 'do' }, ELSE: { klass: TokenClass.Keyword, name: 'else' }, EXPORT: { klass: TokenClass.Keyword, name: 'export' }, EXTENDS: { klass: TokenClass.Keyword, name: 'extends' }, FINALLY: { klass: TokenClass.Keyword, name: 'finally' }, FOR: { klass: TokenClass.Keyword, name: 'for' }, FUNCTION: { klass: TokenClass.Keyword, name: 'function' }, IF: { klass: TokenClass.Keyword, name: 'if' }, IMPORT: { klass: TokenClass.Keyword, name: 'import' }, LET: { klass: TokenClass.Keyword, name: 'let' }, NEW: { klass: TokenClass.Keyword, name: 'new' }, RETURN: { klass: TokenClass.Keyword, name: 'return' }, SUPER: { klass: TokenClass.Keyword, name: 'super' }, SWITCH: { klass: TokenClass.Keyword, name: 'switch' }, THIS: { klass: TokenClass.Keyword, name: 'this' }, THROW: { klass: TokenClass.Keyword, name: 'throw' }, TRY: { klass: TokenClass.Keyword, name: 'try' }, VAR: { klass: TokenClass.Keyword, name: 'var' }, WHILE: { klass: TokenClass.Keyword, name: 'while' }, WITH: { klass: TokenClass.Keyword, name: 'with' }, NULL: { klass: TokenClass.Keyword, name: 'null' }, TRUE: { klass: TokenClass.Keyword, name: 'true' }, FALSE: { klass: TokenClass.Keyword, name: 'false' }, YIELD: { klass: TokenClass.Keyword, name: 'yield' }, NUMBER: { klass: TokenClass.NumericLiteral, name: '' }, STRING: { klass: TokenClass.StringLiteral, name: '' }, REGEXP: { klass: TokenClass.RegularExpression, name: '' }, IDENTIFIER: { klass: TokenClass.Ident, name: '' }, CONST: { klass: TokenClass.Keyword, name: 'const' }, TEMPLATE: { klass: TokenClass.TemplateElement, name: '' }, ESCAPED_KEYWORD: { klass: TokenClass.Keyword, name: '' }, ILLEGAL: { klass: TokenClass.Illegal, name: '' }, }; const TT = TokenType; const I = TT.ILLEGAL; const F = false; const T = true; const ONE_CHAR_PUNCTUATOR = [ I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, TT.NOT, I, I, I, TT.MOD, TT.BIT_AND, I, TT.LPAREN, TT.RPAREN, TT.MUL, TT.ADD, TT.COMMA, TT.SUB, TT.PERIOD, TT.DIV, I, I, I, I, I, I, I, I, I, I, TT.COLON, TT.SEMICOLON, TT.LT, TT.ASSIGN, TT.GT, TT.CONDITIONAL, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, TT.LBRACK, I, TT.RBRACK, TT.BIT_XOR, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, TT.LBRACE, TT.BIT_OR, TT.RBRACE, TT.BIT_NOT, ]; const PUNCTUATOR_START = [ F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, T, F, F, F, T, T, F, T, T, T, T, T, T, F, T, F, F, F, F, F, F, F, F, F, F, T, T, T, T, T, T, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, T, F, T, T, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, T, T, T, T, F, ]; export class JsError extends Error { constructor(index, line, column, msg) { super(msg); this.index = index; // Safari defines these properties as non-writable and non-configurable on Error objects try { this.line = line; this.column = column; } catch (e) {} // define these as well so Safari still has access to this info this.parseErrorLine = line; this.parseErrorColumn = column; this.description = msg; this.message = `[${line}:${column}]: ${msg}`; } } function fromCodePoint(cp) { if (cp <= 0xFFFF) return String.fromCharCode(cp); let cu1 = String.fromCharCode(Math.floor((cp - 0x10000) / 0x400) + 0xD800); let cu2 = String.fromCharCode((cp - 0x10000) % 0x400 + 0xDC00); return cu1 + cu2; } function decodeUtf16(lead, trail) { return (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; } export default class Tokenizer { constructor(source) { this.source = source; this.index = 0; this.line = 0; this.lineStart = 0; this.startIndex = 0; this.startLine = 0; this.startLineStart = 0; this.lastIndex = 0; this.lastLine = 0; this.lastLineStart = 0; this.hasLineTerminatorBeforeNext = false; this.tokenIndex = 0; } saveLexerState() { return { source: this.source, index: this.index, line: this.line, lineStart: this.lineStart, startIndex: this.startIndex, startLine: this.startLine, startLineStart: this.startLineStart, lastIndex: this.lastIndex, lastLine: this.lastLine, lastLineStart: this.lastLineStart, lookahead: this.lookahead, hasLineTerminatorBeforeNext: this.hasLineTerminatorBeforeNext, tokenIndex: this.tokenIndex, }; } restoreLexerState(state) { this.source = state.source; this.index = state.index; this.line = state.line; this.lineStart = state.lineStart; this.startIndex = state.startIndex; this.startLine = state.startLine; this.startLineStart = state.startLineStart; this.lastIndex = state.lastIndex; this.lastLine = state.lastLine; this.lastLineStart = state.lastLineStart; this.lookahead = state.lookahead; this.hasLineTerminatorBeforeNext = state.hasLineTerminatorBeforeNext; this.tokenIndex = state.tokenIndex; } createILLEGAL() { this.startIndex = this.index; this.startLine = this.line; this.startLineStart = this.lineStart; return this.index < this.source.length ? this.createError(ErrorMessages.UNEXPECTED_ILLEGAL_TOKEN, this.source.charAt(this.index)) : this.createError(ErrorMessages.UNEXPECTED_EOS); } createUnexpected(token) { switch (token.type.klass) { case TokenClass.Eof: return this.createError(ErrorMessages.UNEXPECTED_EOS); case TokenClass.Ident: return this.createError(ErrorMessages.UNEXPECTED_IDENTIFIER); case TokenClass.Keyword: if (token.type === TokenType.ESCAPED_KEYWORD) { return this.createError(ErrorMessages.UNEXPECTED_ESCAPED_KEYWORD); } return this.createError(ErrorMessages.UNEXPECTED_TOKEN, token.slice.text); case TokenClass.NumericLiteral: return this.createError(ErrorMessages.UNEXPECTED_NUMBER); case TokenClass.TemplateElement: return this.createError(ErrorMessages.UNEXPECTED_TEMPLATE); case TokenClass.Punctuator: return this.createError(ErrorMessages.UNEXPECTED_TOKEN, token.type.name); case TokenClass.StringLiteral: return this.createError(ErrorMessages.UNEXPECTED_STRING); // the other token classes are RegularExpression and Illegal, but they cannot reach here } // istanbul ignore next throw new Error('Unreachable: unexpected token of class ' + token.type.klass); } createError(message, ...params) { let msg; if (typeof message === 'function') { msg = message(...params); } else { msg = message; } return new JsError(this.startIndex, this.startLine + 1, this.startIndex - this.startLineStart + 1, msg); } createErrorWithLocation(location, message) { /* istanbul ignore next */ let msg = message.replace(/\{(\d+)\}/g, (_, n) => JSON.stringify(arguments[+n + 2])); if (location.slice && location.slice.startLocation) { location = location.slice.startLocation; } return new JsError(location.offset, location.line, location.column + 1, msg); } static cse2(id, ch1, ch2) { return id.charAt(1) === ch1 && id.charAt(2) === ch2; } static cse3(id, ch1, ch2, ch3) { return id.charAt(1) === ch1 && id.charAt(2) === ch2 && id.charAt(3) === ch3; } static cse4(id, ch1, ch2, ch3, ch4) { return id.charAt(1) === ch1 && id.charAt(2) === ch2 && id.charAt(3) === ch3 && id.charAt(4) === ch4; } static cse5(id, ch1, ch2, ch3, ch4, ch5) { return id.charAt(1) === ch1 && id.charAt(2) === ch2 && id.charAt(3) === ch3 && id.charAt(4) === ch4 && id.charAt(5) === ch5; } static cse6(id, ch1, ch2, ch3, ch4, ch5, ch6) { return id.charAt(1) === ch1 && id.charAt(2) === ch2 && id.charAt(3) === ch3 && id.charAt(4) === ch4 && id.charAt(5) === ch5 && id.charAt(6) === ch6; } static cse7(id, ch1, ch2, ch3, ch4, ch5, ch6, ch7) { return id.charAt(1) === ch1 && id.charAt(2) === ch2 && id.charAt(3) === ch3 && id.charAt(4) === ch4 && id.charAt(5) === ch5 && id.charAt(6) === ch6 && id.charAt(7) === ch7; } getKeyword(id) { if (id.length === 1 || id.length > 10) { return TokenType.IDENTIFIER; } /* istanbul ignore next */ switch (id.length) { case 2: switch (id.charAt(0)) { case 'i': switch (id.charAt(1)) { case 'f': return TokenType.IF; case 'n': return TokenType.IN; default: break; } break; case 'd': if (id.charAt(1) === 'o') { return TokenType.DO; } break; } break; case 3: switch (id.charAt(0)) { case 'v': if (Tokenizer.cse2(id, 'a', 'r')) { return TokenType.VAR; } break; case 'f': if (Tokenizer.cse2(id, 'o', 'r')) { return TokenType.FOR; } break; case 'n': if (Tokenizer.cse2(id, 'e', 'w')) { return TokenType.NEW; } break; case 't': if (Tokenizer.cse2(id, 'r', 'y')) { return TokenType.TRY; } break; case 'l': if (Tokenizer.cse2(id, 'e', 't')) { return TokenType.LET; } break; } break; case 4: switch (id.charAt(0)) { case 't': if (Tokenizer.cse3(id, 'h', 'i', 's')) { return TokenType.THIS; } else if (Tokenizer.cse3(id, 'r', 'u', 'e')) { return TokenType.TRUE; } break; case 'n': if (Tokenizer.cse3(id, 'u', 'l', 'l')) { return TokenType.NULL; } break; case 'e': if (Tokenizer.cse3(id, 'l', 's', 'e')) { return TokenType.ELSE; } else if (Tokenizer.cse3(id, 'n', 'u', 'm')) { return TokenType.ENUM; } break; case 'c': if (Tokenizer.cse3(id, 'a', 's', 'e')) { return TokenType.CASE; } break; case 'v': if (Tokenizer.cse3(id, 'o', 'i', 'd')) { return TokenType.VOID; } break; case 'w': if (Tokenizer.cse3(id, 'i', 't', 'h')) { return TokenType.WITH; } break; } break; case 5: switch (id.charAt(0)) { case 'a': if (Tokenizer.cse4(id, 's', 'y', 'n', 'c')) { return TokenType.ASYNC; } if (Tokenizer.cse4(id, 'w', 'a', 'i', 't')) { return TokenType.AWAIT; } break; case 'w': if (Tokenizer.cse4(id, 'h', 'i', 'l', 'e')) { return TokenType.WHILE; } break; case 'b': if (Tokenizer.cse4(id, 'r', 'e', 'a', 'k')) { return TokenType.BREAK; } break; case 'f': if (Tokenizer.cse4(id, 'a', 'l', 's', 'e')) { return TokenType.FALSE; } break; case 'c': if (Tokenizer.cse4(id, 'a', 't', 'c', 'h')) { return TokenType.CATCH; } else if (Tokenizer.cse4(id, 'o', 'n', 's', 't')) { return TokenType.CONST; } else if (Tokenizer.cse4(id, 'l', 'a', 's', 's')) { return TokenType.CLASS; } break; case 't': if (Tokenizer.cse4(id, 'h', 'r', 'o', 'w')) { return TokenType.THROW; } break; case 'y': if (Tokenizer.cse4(id, 'i', 'e', 'l', 'd')) { return TokenType.YIELD; } break; case 's': if (Tokenizer.cse4(id, 'u', 'p', 'e', 'r')) { return TokenType.SUPER; } break; } break; case 6: switch (id.charAt(0)) { case 'r': if (Tokenizer.cse5(id, 'e', 't', 'u', 'r', 'n')) { return TokenType.RETURN; } break; case 't': if (Tokenizer.cse5(id, 'y', 'p', 'e', 'o', 'f')) { return TokenType.TYPEOF; } break; case 'd': if (Tokenizer.cse5(id, 'e', 'l', 'e', 't', 'e')) { return TokenType.DELETE; } break; case 's': if (Tokenizer.cse5(id, 'w', 'i', 't', 'c', 'h')) { return TokenType.SWITCH; } break; case 'e': if (Tokenizer.cse5(id, 'x', 'p', 'o', 'r', 't')) { return TokenType.EXPORT; } break; case 'i': if (Tokenizer.cse5(id, 'm', 'p', 'o', 'r', 't')) { return TokenType.IMPORT; } break; } break; case 7: switch (id.charAt(0)) { case 'd': if (Tokenizer.cse6(id, 'e', 'f', 'a', 'u', 'l', 't')) { return TokenType.DEFAULT; } break; case 'f': if (Tokenizer.cse6(id, 'i', 'n', 'a', 'l', 'l', 'y')) { return TokenType.FINALLY; } break; case 'e': if (Tokenizer.cse6(id, 'x', 't', 'e', 'n', 'd', 's')) { return TokenType.EXTENDS; } break; } break; case 8: switch (id.charAt(0)) { case 'f': if (Tokenizer.cse7(id, 'u', 'n', 'c', 't', 'i', 'o', 'n')) { return TokenType.FUNCTION; } break; case 'c': if (Tokenizer.cse7(id, 'o', 'n', 't', 'i', 'n', 'u', 'e')) { return TokenType.CONTINUE; } break; case 'd': if (Tokenizer.cse7(id, 'e', 'b', 'u', 'g', 'g', 'e', 'r')) { return TokenType.DEBUGGER; } break; } break; case 10: if (id === 'instanceof') { return TokenType.INSTANCEOF; } break; } return TokenType.IDENTIFIER; } skipSingleLineComment(offset) { this.index += offset; while (this.index < this.source.length) { /** * @type {Number} */ let chCode = this.source.charCodeAt(this.index); this.index++; if (isLineTerminator(chCode)) { this.hasLineTerminatorBeforeNext = true; if (chCode === 0xD /* "\r" */ && this.source.charCodeAt(this.index) === 0xA /* "\n" */) { this.index++; } this.lineStart = this.index; this.line++; return; } } } skipMultiLineComment() { this.index += 2; const length = this.source.length; let isLineStart = false; while (this.index < length) { let chCode = this.source.charCodeAt(this.index); if (chCode < 0x80) { switch (chCode) { case 42: // "*" // Block comment ends with "*/". if (this.source.charAt(this.index + 1) === '/') { this.index = this.index + 2; return isLineStart; } this.index++; break; case 10: // "\n" isLineStart = true; this.hasLineTerminatorBeforeNext = true; this.index++; this.lineStart = this.index; this.line++; break; case 13: // "\r": isLineStart = true; this.hasLineTerminatorBeforeNext = true; if (this.source.charAt(this.index + 1) === '\n') { this.index++; } this.index++; this.lineStart = this.index; this.line++; break; default: this.index++; } } else if (chCode === 0x2028 || chCode === 0x2029) { isLineStart = true; this.hasLineTerminatorBeforeNext = true; this.index++; this.lineStart = this.index; this.line++; } else { this.index++; } } throw this.createILLEGAL(); } skipComment() { this.hasLineTerminatorBeforeNext = false; let isLineStart = this.index === 0; const length = this.source.length; while (this.index < length) { let chCode = this.source.charCodeAt(this.index); if (isWhiteSpace(chCode)) { this.index++; } else if (isLineTerminator(chCode)) { this.hasLineTerminatorBeforeNext = true; this.index++; if (chCode === 13 /* "\r" */ && this.source.charAt(this.index) === '\n') { this.index++; } this.lineStart = this.index; this.line++; isLineStart = true; } else if (chCode === 47 /* "/" */) { if (this.index + 1 >= length) { break; } chCode = this.source.charCodeAt(this.index + 1); if (chCode === 47 /* "/" */) { this.skipSingleLineComment(2); isLineStart = true; } else if (chCode === 42 /* "*" */) { isLineStart = this.skipMultiLineComment() || isLineStart; } else { break; } } else if (!this.moduleIsTheGoalSymbol && isLineStart && chCode === 45 /* "-" */) { if (this.index + 2 >= length) { break; } // U+003E is ">" if (this.source.charAt(this.index + 1) === '-' && this.source.charAt(this.index + 2) === '>') { // "-->" is a single-line comment this.skipSingleLineComment(3); } else { break; } } else if (!this.moduleIsTheGoalSymbol && chCode === 60 /* "<" */) { if (this.source.slice(this.index + 1, this.index + 4) === '!--') { this.skipSingleLineComment(4); isLineStart = true; } else { break; } } else { break; } } } scanHexEscape2() { if (this.index + 2 > this.source.length) { return -1; } let r1 = getHexValue(this.source.charAt(this.index)); if (r1 === -1) { return -1; } let r2 = getHexValue(this.source.charAt(this.index + 1)); if (r2 === -1) { return -1; } this.index += 2; return r1 << 4 | r2; } scanUnicode() { if (this.source.charAt(this.index) === '{') { // \u{HexDigits} let i = this.index + 1; let hexDigits = 0, ch; while (i < this.source.length) { ch = this.source.charAt(i); let hex = getHexValue(ch); if (hex === -1) { break; } hexDigits = hexDigits << 4 | hex; if (hexDigits > 0x10FFFF) { throw this.createILLEGAL(); } i++; } if (ch !== '}') { throw this.createILLEGAL(); } if (i === this.index + 1) { ++this.index; // This is so that the error is 'Unexpected "}"' instead of 'Unexpected "{"'. throw this.createILLEGAL(); } this.index = i + 1; return hexDigits; } // \uHex4Digits if (this.index + 4 > this.source.length) { return -1; } let r1 = getHexValue(this.source.charAt(this.index)); if (r1 === -1) { return -1; } let r2 = getHexValue(this.source.charAt(this.index + 1)); if (r2 === -1) { return -1; } let r3 = getHexValue(this.source.charAt(this.index + 2)); if (r3 === -1) { return -1; } let r4 = getHexValue(this.source.charAt(this.index + 3)); if (r4 === -1) { return -1; } this.index += 4; return r1 << 12 | r2 << 8 | r3 << 4 | r4; } getEscapedIdentifier() { let id = ''; let check = isIdentifierStart; while (this.index < this.source.length) { let ch = this.source.charAt(this.index); let code = ch.charCodeAt(0); let start = this.index; ++this.index; if (ch === '\\') { if (this.index >= this.source.length) { throw this.createILLEGAL(); } if (this.source.charAt(this.index) !== 'u') { throw this.createILLEGAL(); } ++this.index; code = this.scanUnicode(); if (code < 0) { throw this.createILLEGAL(); } ch = fromCodePoint(code); } else if (code >= 0xD800 && code <= 0xDBFF) { if (this.index >= this.source.length) { throw this.createILLEGAL(); } let lowSurrogateCode = this.source.charCodeAt(this.index); ++this.index; if (!(lowSurrogateCode >= 0xDC00 && lowSurrogateCode <= 0xDFFF)) { throw this.createILLEGAL(); } code = decodeUtf16(code, lowSurrogateCode); ch = fromCodePoint(code); } if (!check(code)) { if (id.length < 1) { throw this.createILLEGAL(); } this.index = start; return id; } check = isIdentifierPart; id += ch; } return id; } getIdentifier() { let start = this.index; let l = this.source.length; let i = this.index; let check = isIdentifierStart; while (i < l) { let ch = this.source.charAt(i); let code = ch.charCodeAt(0); if (ch === '\\' || code >= 0xD800 && code <= 0xDBFF) { // Go back and try the hard one. this.index = start; return this.getEscapedIdentifier(); } if (!check(code)) { this.index = i; return this.source.slice(start, i); } ++i; check = isIdentifierPart; } this.index = i; return this.source.slice(start, i); } scanIdentifier() { let startLocation = this.getLocation(); let start = this.index; // Backslash (U+005C) starts an escaped character. let id = this.source.charAt(this.index) === '\\' ? this.getEscapedIdentifier() : this.getIdentifier(); let slice = this.getSlice(start, startLocation); slice.text = id; let hasEscape = this.index - start !== id.length; let type = this.getKeyword(id); if (hasEscape && type !== TokenType.IDENTIFIER) { type = TokenType.ESCAPED_KEYWORD; } return { type, value: id, slice, escaped: hasEscape }; } getLocation() { return { line: this.startLine + 1, column: this.startIndex - this.startLineStart, offset: this.startIndex, }; } getLastTokenEndLocation() { return { line: this.lastLine + 1, column: this.lastIndex - this.lastLineStart, offset: this.lastIndex, }; } getSlice(start, startLocation) { return { text: this.source.slice(start, this.index), start, startLocation, end: this.index }; } scanPunctuatorHelper() { let ch1 = this.source.charAt(this.index); switch (ch1) { // Check for most common single-character punctuators. case '.': { let ch2 = this.source.charAt(this.index + 1); if (ch2 !== '.') return TokenType.PERIOD; let ch3 = this.source.charAt(this.index + 2); if (ch3 !== '.') return TokenType.PERIOD; return TokenType.ELLIPSIS; } case '(': return TokenType.LPAREN; case ')': case ';': case ',': return ONE_CHAR_PUNCTUATOR[ch1.charCodeAt(0)]; case '{': return TokenType.LBRACE; case '}': case '[': case ']': case ':': case '?': case '~': return ONE_CHAR_PUNCTUATOR[ch1.charCodeAt(0)]; default: // "=" (U+003D) marks an assignment or comparison operator. if (this.index + 1 < this.source.length && this.source.charAt(this.index + 1) === '=') { switch (ch1) { case '=': if (this.index + 2 < this.source.length && this.source.charAt(this.index + 2) === '=') { return TokenType.EQ_STRICT; } return TokenType.EQ; case '!': if (this.index + 2 < this.source.length && this.source.charAt(this.index + 2) === '=') { return TokenType.NE_STRICT; } return TokenType.NE; case '|': return TokenType.ASSIGN_BIT_OR; case '+': return TokenType.ASSIGN_ADD; case '-': return TokenType.ASSIGN_SUB; case '*': return TokenType.ASSIGN_MUL; case '<': return TokenType.LTE; case '>': return TokenType.GTE; case '/': return TokenType.ASSIGN_DIV; case '%': return TokenType.ASSIGN_MOD; case '^': return TokenType.ASSIGN_BIT_XOR; case '&': return TokenType.ASSIGN_BIT_AND; // istanbul ignore next default: break; // failed } } } if (this.index + 1 < this.source.length) { let ch2 = this.source.charAt(this.index + 1); if (ch1 === ch2) { if (this.index + 2 < this.source.length) { let ch3 = this.source.charAt(this.index + 2); if (ch1 === '>' && ch3 === '>') { // 4-character punctuator: >>>= if (this.index + 3 < this.source.length && this.source.charAt(this.index + 3) === '=') { return TokenType.ASSIGN_SHR_UNSIGNED; } return TokenType.SHR_UNSIGNED; } if (ch1 === '<' && ch3 === '=') { return TokenType.ASSIGN_SHL; } if (ch1 === '>' && ch3 === '=') { return TokenType.ASSIGN_SHR; } if (ch1 === '*' && ch3 === '=') { return TokenType.ASSIGN_EXP; } } // Other 2-character punctuators: ++ -- << >> && || switch (ch1) { case '*': return TokenType.EXP; case '+': return TokenType.INC; case '-': return TokenType.DEC; case '<': return TokenType.SHL; case '>': return TokenType.SHR; case '&': return TokenType.AND; case '|': return TokenType.OR; // istanbul ignore next default: break; // failed } } else if (ch1 === '=' && ch2 === '>') { return TokenType.ARROW; } } return ONE_CHAR_PUNCTUATOR[ch1.charCodeAt(0)]; } // 7.7 Punctuators scanPunctuator() { let startLocation = this.getLocation(); let start = this.index; let subType = this.scanPunctuatorHelper(); this.index += subType.name.length; return { type: subType, value: subType.name, slice: this.getSlice(start, startLocation) }; } scanHexLiteral(start, startLocation) { let i = this.index; while (i < this.source.length) { let ch = this.source.charAt(i); let hex = getHexValue(ch); if (hex === -1) { break; } i++; } if (this.index === i) { throw this.createILLEGAL(); } if (i < this.source.length && isIdentifierStart(this.source.charCodeAt(i))) { throw this.createILLEGAL(); } this.index = i; let slice = this.getSlice(start, startLocation); return { type: TokenType.NUMBER, value: parseInt(slice.text.substr(2), 16), slice }; } scanBinaryLiteral(start, startLocation) { let offset = this.index - start; while (this.index < this.source.length) { let ch = this.source.charAt(this.index); if (ch !== '0' && ch !== '1') { break; } this.index++; } if (this.index - start <= offset) { throw this.createILLEGAL(); } if (this.index < this.source.length && (isIdentifierStart(this.source.charCodeAt(this.index)) || isDecimalDigit(this.source.charCodeAt(this.index)))) { throw this.createILLEGAL(); } return { type: TokenType.NUMBER, value: parseInt(this.getSlice(start, startLocation).text.substr(offset), 2), slice: this.getSlice(start, startLocation), octal: false, noctal: false, }; } scanOctalLiteral(start, startLocation) { while (this.index < this.source.length) { let ch = this.source.charAt(this.index); if (ch >= '0' && ch <= '7') { this.index++; } else if (isIdentifierPart(ch.charCodeAt(0))) { throw this.createILLEGAL(); } else { break; } } if (this.index - start === 2) { throw this.createILLEGAL(); } return { type: TokenType.NUMBER, value: parseInt(this.getSlice(start, startLocation).text.substr(2), 8), slice: this.getSlice(start, startLocation), octal: false, noctal: false, }; } scanLegacyOctalLiteral(start, startLocation) { let isOctal = true; while (this.index < this.source.length) { let ch = this.source.charAt(this.index); if (ch >= '0' && ch <= '7') { this.index++; } else if (ch === '8' || ch === '9') { isOctal = false; this.index++; } else if (isIdentifierPart(ch.charCodeAt(0))) { throw this.createILLEGAL(); } else { break; } } let slice = this.getSlice(start, startLocation); if (!isOctal) { this.eatDecimalLiteralSuffix(); return { type: TokenType.NUMBER, slice, value: +slice.text, octal: true, noctal: !isOctal, }; } return { type: TokenType.NUMBER, slice, value: parseInt(slice.text.substr(1), 8), octal: true, noctal: !isOctal, }; } scanNumericLiteral() { let ch = this.source.charAt(this.index); // assert(ch === "." || "0" <= ch && ch <= "9") let startLocation = this.getLocation(); let start = this.index; if (ch === '0') { this.index++; if (this.index < this.source.length) { ch = this.source.charAt(this.index); if (ch === 'x' || ch === 'X') { this.index++; return this.scanHexLiteral(start, startLocation); } else if (ch === 'b' || ch === 'B') { this.index++; return this.scanBinaryLiteral(start, startLocation); } else if (ch === 'o' || ch === 'O') { this.index++; return this.scanOctalLiteral(start, startLocation); } else if (ch >= '0' && ch <= '9') { return this.scanLegacyOctalLiteral(start, startLocation); } } else { let slice = this.getSlice(start, startLocation); return { type: TokenType.NUMBER, value: +slice.text, slice, octal: false, noctal: false, }; } } else if (ch !== '.') { // Must be "1".."9" ch = this.source.charAt(this.index); while (ch >= '0' && ch <= '9') { this.index++; if (this.index === this.source.length) { let slice = this.getSlice(start, startLocation); return { type: TokenType.NUMBER, value: +slice.text, slice, octal: false, noctal: false, }; } ch = this.source.charAt(this.index); } } this.eatDecimalLiteralSuffix(); if (this.index !== this.source.length && isIdentifierStart(this.source.charCodeAt(this.index))) { throw this.createILLEGAL(); } let slice = this.getSlice(start, startLocation); return { type: TokenType.NUMBER, value: +slice.text, slice, octal: false, noctal: false, }; } eatDecimalLiteralSuffix() { let ch = this.source.charAt(this.index); if (ch === '.') { this.index++; if (this.index === this.source.length) { return; } ch = this.source.charAt(this.index); while (ch >= '0' && ch <= '9') { this.index++; if (this.index === this.source.length) { return; } ch = this.source.charAt(this.index); } } // EOF not reached here if (ch === 'e' || ch === 'E') { this.index++; if (this.index === this.source.length) { throw this.createILLEGAL(); } ch = this.source.charAt(this.index); if (ch === '+' || ch === '-') { this.index++; if (this.index === this.source.length) { throw this.createILLEGAL(); } ch = this.source.charAt(this.index); } if (ch >= '0' && ch <= '9') { while (ch >= '0' && ch <= '9') { this.index++; if (this.index === this.source.length) { break; } ch = this.source.charAt(this.index); } } else { throw this.createILLEGAL(); } } } scanStringEscape(str, octal) { this.index++; if (this.index === this.source.length) { throw this.createILLEGAL(); } let ch = this.source.charAt(this.index); if (isLineTerminator(ch.charCodeAt(0))) { this.index++; if (ch === '\r' && this.source.charAt(this.index) === '\n') { this.index++; } this.lineStart = this.index; this.line++; } else { switch (ch) { case 'n': str += '\n'; this.index++; break; case 'r': str += '\r'; this.index++; break; case 't': str += '\t'; this.index++; break; case 'u': case 'x': { let unescaped; this.index++; if (this.index >= this.source.length) { throw this.createILLEGAL(); } unescaped = ch === 'u' ? this.scanUnicode() : this.scanHexEscape2(); if (unescaped < 0) { throw this.createILLEGAL(); } str += fromCodePoint(unescaped); break; } case 'b': str += '\b'; this.index++; break; case 'f': str += '\f'; this.index++; break; case 'v': str += '\u000B'; this.index++; break; default: if (ch >= '0' && ch <= '7') { let octalStart = this.index; let octLen = 1; // 3 digits are only allowed when string starts // with 0, 1, 2, 3 if (ch >= '0' && ch <= '3') { octLen = 0; } let code = 0; while (octLen < 3 && ch >= '0' && ch <= '7') { this.index++; if (octLen > 0 || ch !== '0') { octal = this.source.slice(octalStart, this.index); } code *= 8; code += ch - '0'; octLen++; if (this.index === this.source.length) { throw this.createILLEGAL(); } ch = this.source.charAt(this.index); } if (code === 0 && octLen === 1 && (ch === '8' || ch === '9')) { octal = this.source.slice(octalStart, this.index + 1); } str += String.fromCharCode(code); } else if (ch === '8' || ch === '9') { throw this.createILLEGAL(); } else { str += ch; this.index++; } } } return [str, octal]; } // 7.8.4 String Literals scanStringLiteral() { let str = ''; let quote = this.source.charAt(this.index); // assert((quote === "\"" || quote === """), "String literal must starts with a quote") let startLocation = this.getLocation(); let start = this.index; this.index++; let octal = null; while (this.index < this.source.length) { let ch = this.source.charAt(this.index); if (ch === quote) { this.index++; return { type: TokenType.STRING, slice: this.getSlice(start, startLocation), str, octal }; } else if (ch === '\\') { [str, octal] = this.scanStringEscape(str, octal); } else if (isLineTerminator(ch.charCodeAt(0))) { throw this.createILLEGAL(); } else { str += ch; this.index++; } } throw this.createILLEGAL(); } scanTemplateElement() { let startLocation = this.getLocation(); let start = this.index; this.index++; while (this.index < this.source.length) { let ch = this.source.charCodeAt(this.index); switch (ch) { case 0x60: { // ` this.index++; return { type: TokenType.TEMPLATE, tail: true, slice: this.getSlice(start, startLocation) }; } case 0x24: { // $ if (this.source.charCodeAt(this.index + 1) === 0x7B) { // { this.index += 2; return { type: TokenType.TEMPLATE, tail: false, slice: this.getSlice(start, startLocation) }; } this.index++; break; } case 0x5C: { // \\ let octal = this.scanStringEscape('', null)[1]; if (octal != null) { throw this.createError(ErrorMessages.NO_OCTALS_IN_TEMPLATES); } break; } case 0x0D: { // \r this.line++; this.index++; if (this.index < this.source.length && this.source.charAt(this.index) === '\n') { this.index++; } this.lineStart = this.index; break; } case 0x0A: // \r case 0x2028: case 0x2029: { this.line++; this.index++; this.lineStart = this.index; break; } default: this.index++; } } throw this.createILLEGAL(); } scanRegExp(str) { let startLocation = this.getLocation(); let start = this.index; let terminated = false; let classMarker = false; while (this.index < this.source.length) { let ch = this.source.charAt(this.index); if (ch === '\\') { str += ch; this.index++; ch = this.source.charAt(this.index); // ECMA-262 7.8.5 if (isLineTerminator(ch.charCodeAt(0))) { throw this.createError(ErrorMessages.UNTERMINATED_REGEXP); } str += ch; this.index++; } else if (isLineTerminator(ch.charCodeAt(0))) { throw this.createError(ErrorMessages.UNTERMINATED_REGEXP); } else { if (classMarker) { if (ch === ']') { classMarker = false; } } else if (ch === '/') { terminated = true; str += ch; this.index++; break; } else if (ch === '[') { classMarker = true; } str += ch; this.index++; } } if (!terminated) { throw this.createError(ErrorMessages.UNTERMINATED_REGEXP); } while (this.index < this.source.length) { let ch = this.source.charAt(this.index); if (ch === '\\') { throw this.createError(ErrorMessages.INVALID_REGEXP_FLAGS); } if (!isIdentifierPart(ch.charCodeAt(0))) { break; } this.index++; str += ch; } return { type: TokenType.REGEXP, value: str, slice: this.getSlice(start, startLocation) }; } advance() { let startLocation = this.getLocation(); this.lastIndex = this.index; this.lastLine = this.line; this.lastLineStart = this.lineStart; this.skipComment(); this.startIndex = this.index; this.startLine = this.line; this.startLineStart = this.lineStart; if (this.lastIndex === 0) { this.lastIndex = this.index; this.lastLine = this.line; this.lastLineStart = this.lineStart; } if (this.index >= this.source.length) { return { type: TokenType.EOS, slice: this.getSlice(this.index, startLocation) }; } let charCode = this.source.charCodeAt(this.index); if (charCode < 0x80) { if (PUNCTUATOR_START[charCode]) { return this.scanPunctuator(); } if (isIdentifierStart(charCode) || charCode === 0x5C /* backslash (\) */) { return this.scanIdentifier(); } // Dot (.) U+002E can also start a floating-point number, hence the need // to check the next character. if (charCode === 0x2E) { if (this.index + 1 < this.source.length && isDecimalDigit(this.source.charCodeAt(this.index + 1))) { return this.scanNumericLiteral(); } return this.scanPunctuator(); } // String literal starts with single quote (U+0027) or double quote (U+0022). if (charCode === 0x27 || charCode === 0x22) { return this.scanStringLiteral(); } // Template literal starts with back quote (U+0060) if (charCode === 0x60) { return this.scanTemplateElement(); } if (charCode /* "0" */ >= 0x30 && charCode <= 0x39 /* "9" */) { return this.scanNumericLiteral(); } // Slash (/) U+002F can also start a regex. throw this.createILLEGAL(); } else { if (isIdentifierStart(charCode) || charCode >= 0xD800 && charCode <= 0xDBFF) { return this.scanIdentifier(); } throw this.createILLEGAL(); } } eof() { return this.lookahead.type === TokenType.EOS; } lex() { let prevToken = this.lookahead; this.lookahead = this.advance(); this.tokenIndex++; return prevToken; } }
shapesecurity/shift-parser-js
src/tokenizer.js
JavaScript
apache-2.0
46,755
import {Component, Inject, ElementRef} from '@angular/core'; import {SlideCommon} from '../../slideCommon/slideCommon'; import {Editor} from '../../../editor/editor'; import {EditorTab} from '../../../editorTab/editorTab'; import {HOST_SLIDE_CONTAINER_CLASS} from '../../../../services/constants'; @Component({ selector:'fwksCompare2', templateUrl:'src/components/slides/preamble/fwksCompare2/fwksCompare2.html', styleUrls: ['src/components/slides/preamble/fwksCompare2/fwksCompare2.css'], directives: [Editor, EditorTab] }) export class FwksCompare2 extends SlideCommon{ constructor(elt: ElementRef, @Inject(HOST_SLIDE_CONTAINER_CLASS) hostClass: string) { super(elt, hostClass); } }
worldline/TrainingJEEAngular
trainingapp/src/components/slides/preamble/fwksCompare2/fwksCompare2.ts
TypeScript
apache-2.0
696
/* * Copyright 2019 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. */ /** * @hide */ package com.google.firebase.messaging.internal;
firebase/firebase-admin-java
src/main/java/com/google/firebase/messaging/internal/package-info.java
Java
apache-2.0
661
package org.larsworks.bitcoin.app.core.notifications; import org.larsworks.bitcoin.app.core.notifications.conditions.Condition; /** * @author Lars Kleen * @since 0.0.1 * Date: 01.02.14 * Time: 13:32 */ public interface NotificationEngine<T> { void addCondition(Condition<T> condition); void removeCondition(Condition<T> condition); void process(T t); }
lkleen/bitcoin-app
core/src/main/java/org/larsworks/bitcoin/app/core/notifications/NotificationEngine.java
Java
apache-2.0
405
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using SystemEx.Windows.Forms; using WastedgeQuerier.Util; namespace WastedgeQuerier.JavaScript { public partial class NewProjectForm : SystemEx.Windows.Forms.Form { public string ProjectName => _name.Text; public string ProjectLocation => _location.Text; public NewProjectForm() { InitializeComponent(); using (var key = Program.BaseKey) { _location.Text = key.GetValue("Last Project Location") as string ?? Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); } } private void _browse_Click(object sender, EventArgs e) { var form = new FolderBrowser { Title = "Project Location" }; if (form.ShowDialog(this) == DialogResult.OK) _location.Text = form.SelectedPath; } private void _acceptButton_Click(object sender, EventArgs e) { if (_name.Text.Length == 0) { TaskDialogEx.Show(this, "Please enter a name", Text, TaskDialogCommonButtons.OK, TaskDialogIcon.Warning); } else if (!Directory.Exists(_location.Text)) { TaskDialogEx.Show(this, "Please select a valid location", Text, TaskDialogCommonButtons.OK, TaskDialogIcon.Warning); } else { var fullPath = Path.Combine(_location.Text, _name.Text); if (Directory.Exists(fullPath)) { TaskDialogEx.Show(this, $"The directory {fullPath} already exists", Text, TaskDialogCommonButtons.OK, TaskDialogIcon.Warning); } else { using (var key = Program.BaseKey) { key.SetValue("Last Project Location", _location.Text); } DialogResult = DialogResult.OK; } } } } }
wastedge/wastedge-querier
WastedgeQuerier/JavaScript/NewProjectForm.cs
C#
apache-2.0
2,391
Rails.application.routes.draw do devise_for :users, :controllers => { registrations: 'registrations' } get "/profiles/search" => "profiles#search" resources :profiles resources :forums do resources :posts end resources :posts, only: [] do resources :comments end # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". # You can have the root of your site routed with "root" root "welcome#welcome" get "/home", to: "welcome#home" # Example of regular route: # get 'products/:id' => 'catalog#view' # Example of named route that can be invoked with purchase_url(id: product.id) # get 'products/:id/purchase' => 'catalog#purchase', as: :purchase # Example resource route (maps HTTP verbs to controller actions automatically): # resources :products # Example resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Example resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Example resource route with more complex sub-resources: # resources :products do # resources :comments # resources :sales do # get 'recent', on: :collection # end # end # Example resource route with concerns: # concern :toggleable do # post 'toggle' # end # resources :posts, concerns: :toggleable # resources :photos, concerns: :toggleable # Example resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end end
julianche/ixalumninew
config/routes.rb
Ruby
apache-2.0
1,895
// Copyright 2021 Google LLC // // 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.google.api.ads.admanager.jaxws.v202105; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for RequiredCollectionError.Reason. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="RequiredCollectionError.Reason"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="REQUIRED"/> * &lt;enumeration value="TOO_LARGE"/> * &lt;enumeration value="TOO_SMALL"/> * &lt;enumeration value="UNKNOWN"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "RequiredCollectionError.Reason") @XmlEnum public enum RequiredCollectionErrorReason { /** * * A required collection is missing. * * */ REQUIRED, /** * * Collection size is too large. * * */ TOO_LARGE, /** * * Collection size is too small. * * */ TOO_SMALL, /** * * The value returned if the actual value is not exposed by the requested API version. * * */ UNKNOWN; public String value() { return name(); } public static RequiredCollectionErrorReason fromValue(String v) { return valueOf(v); } }
googleads/googleads-java-lib
modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v202105/RequiredCollectionErrorReason.java
Java
apache-2.0
2,070
package publish import ( "bytes" "sync" "github.com/drausin/libri/libri/common/ecid" "github.com/drausin/libri/libri/common/id" "github.com/drausin/libri/libri/common/storage" "github.com/drausin/libri/libri/librarian/api" "github.com/drausin/libri/libri/librarian/client" lclient "github.com/drausin/libri/libri/librarian/client" ) // Acquirer Gets documents from the libri network. type Acquirer interface { // Acquire Gets a document from the libri network using a librarian client. Acquire(docKey id.ID, authorPub []byte, lc api.Getter) (*api.Document, error) } type acquirer struct { clientID ecid.ID orgID ecid.ID clientSigner client.Signer orgSigner client.Signer params *Parameters } // NewAcquirer creates a new Acquirer with the given clientID clientSigner, and params. func NewAcquirer( clientID, orgID ecid.ID, clientSigner, orgSigner client.Signer, params *Parameters, ) Acquirer { return &acquirer{ clientID: clientID, orgID: orgID, clientSigner: clientSigner, orgSigner: orgSigner, params: params, } } func (a *acquirer) Acquire(docKey id.ID, authorPub []byte, lc api.Getter) (*api.Document, error) { rq := client.NewGetRequest(a.clientID, a.orgID, docKey) ctx, cancel, err := client.NewSignedTimeoutContext(a.clientSigner, a.orgSigner, rq, a.params.GetTimeout) if err != nil { return nil, err } rp, err := lc.Get(ctx, rq) cancel() if err != nil { return nil, err } if !bytes.Equal(rq.Metadata.RequestId, rp.Metadata.RequestId) { return nil, client.ErrUnexpectedRequestID } if err := api.ValidateDocument(rp.Value); err != nil { return nil, err } return rp.Value, nil } // SingleStoreAcquirer Gets a document and saves it to internal storage. type SingleStoreAcquirer interface { // Acquire Gets the document with the given key from the libri network and saves it to // internal storage. Acquire(docKey id.ID, authorPub []byte, lc api.Getter) error } type singleStoreAcquirer struct { inner Acquirer docS storage.DocumentStorer } // NewSingleStoreAcquirer creates a new SingleStoreAcquirer from the inner Acquirer and the docS // document storer. func NewSingleStoreAcquirer(inner Acquirer, docS storage.DocumentStorer) SingleStoreAcquirer { return &singleStoreAcquirer{ inner: inner, docS: docS, } } func (a *singleStoreAcquirer) Acquire(docKey id.ID, authorPub []byte, lc api.Getter) error { doc, err := a.inner.Acquire(docKey, authorPub, lc) if err != nil { return err } if err := a.docS.Store(docKey, doc); err != nil { return err } return nil } // MultiStoreAcquirer Gets and stores multiple documents. type MultiStoreAcquirer interface { // Acquire in parallel Gets and stores the documents with the given keys. It balances // between librarian clients for its Put requests. Acquire(docKeys []id.ID, authorPub []byte, cb client.GetterBalancer) error // GetRetryGetter returns a new retrying api.Getter. GetRetryGetter(cb client.GetterBalancer) api.Getter } type multiStoreAcquirer struct { inner SingleStoreAcquirer params *Parameters } // NewMultiStoreAcquirer creates a new MultiStoreAcquirer from the inner SingleStoreAcquirer and // params. func NewMultiStoreAcquirer(inner SingleStoreAcquirer, params *Parameters) MultiStoreAcquirer { return &multiStoreAcquirer{ inner: inner, params: params, } } func (a *multiStoreAcquirer) Acquire( docKeys []id.ID, authorPub []byte, cb client.GetterBalancer, ) error { rlc := a.GetRetryGetter(cb) docKeysChan := make(chan id.ID, a.params.PutParallelism) go loadChan(docKeys, docKeysChan) wg := new(sync.WaitGroup) getErrs := make(chan error, a.params.GetParallelism) for c := uint32(0); c < a.params.GetParallelism; c++ { wg.Add(1) go func() { for docKey := range docKeysChan { if err := a.inner.Acquire(docKey, authorPub, rlc); err != nil { getErrs <- err break } } wg.Done() }() } wg.Wait() close(getErrs) select { case err := <-getErrs: return err default: return nil } } func (a *multiStoreAcquirer) GetRetryGetter(cb client.GetterBalancer) api.Getter { return lclient.NewRetryGetter(cb, true, a.params.GetTimeout) }
drausin/libri
libri/author/io/publish/acquirer.go
GO
apache-2.0
4,183